text
stringlengths 12
1.05M
| repo_name
stringlengths 5
86
| path
stringlengths 4
191
| language
stringclasses 1
value | license
stringclasses 15
values | size
int32 12
1.05M
| keyword
listlengths 1
23
| text_hash
stringlengths 64
64
|
|---|---|---|---|---|---|---|---|
#!/usr/bin/env python
#
# Copyright (C) STMicroelectronics Ltd. 2012
#
# This file is part of ATOS.
#
# ATOS is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License
# as published by the Free Software Foundation; either version 2
# of the License, or (at your option) any later version.
#
# ATOS is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# v2.0 along with ATOS. If not, see <http://www.gnu.org/licenses/>.
#
# Usage: get usage with atos-graph -h
#
import sys
import re, math
import atos_lib
import logger
try:
import pylab as pl
import matplotlib
except:
print "pylab matplotlib module is not installed"
sys.exit(1)
# ####################################################################
def nowarn(func):
def wrapper(*args, **kwargs):
import warnings
with warnings.catch_warnings():
warnings.simplefilter("ignore")
res = func(*args, **kwargs)
return res
return wrapper
# ####################################################################
@nowarn
def draw_graph(getgraph, opts):
# http://matplotlib.sourceforge.net/index.html
fg = pl.figure()
ax = fg.add_subplot(111)
global graph_plots, all_points
graph_plots, all_points = [], []
def draw_tradeoff_plots(ratio, points, attrs):
# select tradeoff given ratio
best = atos_lib.atos_client_results.select_tradeoff(points, ratio)
# graph limits
xmin = min([p.sizered for p in points])
xmax = max([p.sizered for p in points])
ymin = min([p.speedup for p in points])
ymax = max([p.speedup for p in points])
# number of points on ratio line
nbtk = int((ratio >= 1 and 2 or 1 / ratio) * 32)
# ratio line points coordinates
xtk = [xmin + i * ((xmax - xmin) / nbtk) for i in range(nbtk + 1)]
ytk = [best.speedup + (1.0 / ratio) * (best.sizered - x) for x in xtk]
coords = filter(lambda (x, y): y >= ymin and y <= ymax, zip(xtk, ytk))
# first plot: selected tradeoff point
attrs.update({'label': '_nolegend_'})
attrs.update({'markersize': 20, 'linewidth': 0, 'alpha': 0.4})
plots = [(([best.sizered], [best.speedup]), dict(attrs))]
# second plot: ratio line
attrs.update({'marker': '', 'linewidth': 2, 'linestyle': 'solid'})
plots += [((zip(*coords)[0], zip(*coords)[1]), dict(attrs))]
return plots
def draw_all():
global graph_plots, all_points, selected_points, similar_points # :(
# remove old plots
old_points = [(p.sizered, p.speedup, p.variant) for p in all_points]
for x in list(graph_plots):
graph_plots.remove(x)
x.remove()
# get graph values
scatters, frontiers = getgraph()
all_points = sum([x[0] for x in scatters + frontiers], [])
# draw scatters
for (points, attrs) in scatters:
attrsmap = {
's': 20, 'label': '_nolegend_', 'zorder': 2,
'color': 'r', 'edgecolor': 'k'}
attrsmap.update(attrs)
xy = zip(*[(p.sizered, p.speedup) for p in points])
gr = ax.scatter(*xy, **attrsmap)
graph_plots.append(gr)
# draw frontiers (line plots)
for (points, attrs) in frontiers:
attrsmap = {
'color': 'r', 'marker': 'o', 'label': '_nolegend_',
'zorder': 2, 'markersize': 7,
'linestyle': 'dashed', 'linewidth': 2}
attrsmap.update(attrs)
xy = zip(*sorted([(p.sizered, p.speedup) for p in points]))
gr, = ax.plot(xy[0], xy[1], **attrsmap)
graph_plots.append(gr)
# show tradeoffs for each frontier
for ratio in opts.tradeoffs or []:
for ((xcrd, ycrd), attrs) in \
draw_tradeoff_plots(ratio, points, dict(attrsmap)):
graph_plots.append(ax.plot(xcrd, ycrd, **attrs)[0])
# draw selected points (hidden)
if opts.show and all_points:
# workaround pb with pick_event event ind (4000)
attrsmap = {
'color': 'b', 'marker': 'o', 'markersize': 20, 'linewidth': 0,
'alpha': 0.4}
xy = zip(*sorted([(p.sizered, p.speedup) for p in all_points]))
selected_points, = \
ax.plot(xy[0], xy[1], visible=False, picker=4000, **attrsmap)
graph_plots.append(selected_points)
# similar point plot
attrsmap.update({'color': 'g'})
similar_points, = ax.plot(None, None, visible=False, **attrsmap)
graph_plots.append(similar_points)
# highlight new points
if opts.follow and old_points:
new_points = [p for p in all_points if (
(p.sizered, p.speedup, p.variant) not in old_points)]
attrsmap = {
'color': 'r', 'marker': 'o', 'markersize': 20, 'linewidth': 0,
'alpha': 0.4, 'zorder': 1}
if new_points:
xy = zip(*[(p.sizered, p.speedup) for p in new_points])
new_points, = ax.plot(*xy, **attrsmap)
graph_plots.append(new_points)
# redraw legend and figure
if opts.xlim: pl.xlim([float(l) for l in opts.xlim.split(",")])
if opts.ylim: pl.ylim([float(l) for l in opts.ylim.split(",")])
ax.legend(loc='lower left')
fg.canvas.draw()
# dynamic annotations
def on_pick(event):
def closest(x, y):
dp = [(math.hypot(p.sizered - x, p.speedup - y), p)
for p in all_points]
return sorted(dp)[0][1]
def highlight(p):
# print point on console
print '-' * 40 + '\n' + point_str(p)
# highlight point
selected_points.set_visible(True)
selected_points.set_data(p.sizered, p.speedup)
# highlight similar points (same variant)
sim = zip(*([(c.sizered, c.speedup) for c in all_points
if c.variant == p.variant and c != p]))
similar_points.set_visible(True)
similar_points.set_data(sim and sim[0], sim and sim[1])
# selected point legend
main_legend = ax.legend_
lg = point_str(p, short=True, no_id=opts.anonymous)
lp = pl.legend(
[selected_points], [lg], loc='lower right', numpoints=1)
pl.setp(lp.get_texts(), fontsize='medium')
lp.get_frame().set_alpha(0.5)
pl.gca().add_artist(main_legend)
fg.canvas.draw()
ax.legend_ = main_legend
highlight(closest(event.mouseevent.xdata, event.mouseevent.ydata))
# live plotting
def on_timer():
draw_all()
# draw graph for the first time
draw_all()
# graph title
title = 'Optimization Space for %s' % (
opts.id or opts.targets or (
all_points and all_points[0].target))
if opts.refid: title += ' [ref=%s]' % opts.refid
if opts.filter: title += ' [filter=%s]' % opts.filter
# redraw axis, set labels, legend, grid, ...
def labelfmt(x, pos=0): return '%.2f%%' % (100.0 * x)
ax.xaxis.set_major_formatter(pl.FuncFormatter(labelfmt))
ax.yaxis.set_major_formatter(pl.FuncFormatter(labelfmt))
pl.axhspan(0.0, 0.0)
pl.axvspan(0.0, 0.0)
pl.title(title)
pl.xlabel('size reduction (higher is better) -->')
pl.ylabel('speedup (higher is better) -->')
if opts.xlim: pl.xlim([float(l) for l in opts.xlim.split(",")])
if opts.ylim: pl.ylim([float(l) for l in opts.ylim.split(",")])
pl.grid(True)
if opts.outfile:
fg.savefig(opts.outfile)
if opts.show:
fg.canvas.mpl_connect('pick_event', on_pick)
if opts.follow: timer = atos_lib.repeatalarm(on_timer, 5.0).start()
pl.show()
if opts.follow: timer.stop()
@nowarn
def draw_correl_graph(getgraph, opts):
# http://matplotlib.sourceforge.net/index.html
fg = pl.figure()
ax = fg.add_subplot(111)
bars = getgraph()
for (values, attrs) in bars:
indexes, width = pl.arange(len(values)), 1.0 / len(bars)
yvalues = [x.speedup for x in values]
xoffset = width * bars.index((values, attrs))
ax.bar(indexes + xoffset, yvalues, width, picker=4000, **attrs)
ax.legend(loc='lower left')
fg.canvas.draw()
# dynamic annotations
def on_pick(event):
ind = int(event.mouseevent.xdata)
point = bars[0][0][ind]
tooltip.set_position(
(event.mouseevent.xdata, event.mouseevent.ydata))
tooltip.set_text(point_descr(point))
tooltip.set_visible(True)
fg.canvas.draw()
tooltip = ax.text(
0, 0, "undef", bbox=dict(facecolor='white', alpha=0.8),
verticalalignment='bottom', visible=False)
# graph title
try:
title = 'Correlation Graph for %s' % (
opts.id or opts.targets or bars[0][0][0].target)
except: title = 'Correlation Graph'
# redraw axis, set labels, legend, grid, ...
def labelfmt(x, pos=0): return '%.2f%%' % (100.0 * x)
ax.yaxis.set_major_formatter(pl.FuncFormatter(labelfmt))
pl.ylabel('speedup (higher is better) -->')
pl.xlabel('Configurations (ordered by decreasing speedup of '
+ bars[0][1]['label'] + ') -->')
pl.title(title)
pl.axhspan(0.0, 0.0)
pl.axvspan(0.0, 0.0)
pl.grid(True)
if opts.outfile:
fg.savefig(opts.outfile)
if opts.show:
fg.canvas.mpl_connect('pick_event', on_pick)
pl.show()
@nowarn
def draw_heat_graph(getgraph, opts):
# from pyevolve_graph script
stage_points = getgraph()
fg = pl.figure()
ax = fg.add_subplot(111)
pl.imshow(
stage_points, aspect="auto", interpolation="gaussian",
cmap=matplotlib.cm.__dict__["jet"])
pl.title("Population scores along the generations")
def labelfmt(x, pos=0):
# there is surely a better way to do that
return (float(x) == int(x)) and '%d' % (x) or ''
ax.xaxis.set_major_formatter(pl.FuncFormatter(labelfmt))
pl.xlabel('Generations -->')
pl.ylabel('Sorted Population Results')
pl.grid(True)
pl.colorbar()
if opts.outfile:
fg.savefig(opts.outfile)
if opts.show:
pl.show()
# ####################################################################
def point_descr(point):
res = point.target + ' '
res += (len(point.variant) >= 45
and point.variant[:25] + '...' + point.variant[-15:]
or point.variant)
return res
def point_str(point, short=False, no_id=False):
res = ''
if not no_id:
if short and len(point.variant) >= 45:
legend_id = point.variant[:25] + '...' + point.variant[-15:]
else: legend_id = point.variant
res = legend_id + '\n'
res += 'speedup=%.2f%% runtime=%.2f\n' % (
point.speedup * 100, point.time)
res += 'reduction=%.2f%% binsize=%d' % (
point.sizered * 100, point.size)
if not no_id:
res += '\nid=%s' % (atos_lib.hashid(point.variant))
return res
def getoptcases(dbpath, opts):
variant_results = atos_lib.get_results(dbpath, opts)
atos_lib.atos_client_results.set_frontier_field(variant_results)
frontier = filter(lambda x: x.on_frontier, variant_results)
if not opts.follow: print '%d points, %d on frontier' % (
len(variant_results), len(frontier))
return variant_results
def optgraph(opts):
optcases = getoptcases(
opts.dbfile and opts.dbfile[0] or opts.configuration_path, opts)
scatters, frontiers = [], []
# scatters definition
scatters_def = []
if opts.highlight:
scatters_def += [
(opts.highlight, {
's': 40, 'color': 'y', 'label': 'ref cases', 'zorder': 4})
]
if opts.xd == 0:
scatters_def += [
('.*', {'label': 'opt cases', 'color': 'b'})
]
elif opts.xd == 1:
scatters_def += [
('OPT(-fprofile-use)?-Os.*$',
{'label': '[-Os]', 'color': 'green'}),
('OPT(-fprofile-use)?-O1.*$',
{'label': '[-O1]', 'color': 'cyan'}),
('OPT(-fprofile-use)?-O2.*$',
{'label': '[-O2]', 'color': 'blue'}),
('OPT(-fprofile-use)?-O3.*$',
{'label': '[-O3]', 'color': 'red'}),
('.*',
{'label': '_nolegend_', 'color': 'white'})
]
elif opts.xd == 2:
scatters_def += [
('OPT-fprofile-use.*-flto$',
{'label': '[fdo+lto]', 'color': 'red'}),
('OPT-fprofile-use.*$',
{'label': '[fdo]', 'color': 'blue'}),
('.*-flto$',
{'label': '[lto]', 'color': 'green'}),
('.*',
{'label': '_nolegend_', 'color': 'white'})
]
elif opts.xd == 3:
scatters_def += [
('OPT-fprofile-use-O3.*-flto$',
{'label': '[O3 fdo+lto]', 'color': 'red'}),
('OPT-fprofile-use-O2.*-flto$',
{'label': '[O2 fdo+lto]', 'color': 'green'}),
('OPT-fprofile-use-O3.*$',
{'label': '[O3 fdo]', 'color': 'blue'}),
('OPT-fprofile-use-O2.*$',
{'label': '[O2 fdo]', 'color': 'cyan'}),
('.*',
{'label': '_nolegend_', 'color': 'white'})
]
elif opts.xd == 4:
if not (opts.cookies and len(opts.cookies) == 1):
logger.error("xd=4 only works with a given cookie", exit_status=1)
db = atos_lib.atos_cookie_db_json.cookie_db(opts.configuration_path)
root_cookie = db.cookies.get(opts.cookies[0], None)
assert root_cookie, "root cookie not found"
stage_cookies = root_cookie.get('succs', [])
# find generation_number and set corresponding field
for c in optcases:
stage_num = None
for (nstage, stage_cookie) in enumerate(stage_cookies):
if stage_cookie in c.cookies.split(','):
stage_num = 's%d' % nstage
break
if stage_num: c.variant += '-' + stage_num
# create scatters for each stage
for (nstage, stage_cookie) in enumerate(stage_cookies):
cdelta = 0.3 + nstage * (0.7 / (len(stage_cookies) + 1))
scatters_def += [
('.*-s%d$' % nstage, {'label': '[stage-%d]' % nstage,
'color': (0, cdelta, cdelta)})]
scatters_def += [
('.*', {'label': '[stage-?]', 'color': (0.0, 1.0, 1.0)})]
# scatters list
if not opts.frontier_only:
# partionning of points into scatters
partitions, attrs_values = {}, dict(scatters_def)
for c in optcases:
for (opt, val) in scatters_def:
if not re.match(opt, c.variant): continue
partitions.setdefault(opt, []).append(c)
break
partkeys = [x[0] for x in scatters_def if x[0] in partitions.keys()]
for opt in partkeys:
scatters += [(partitions[opt], attrs_values[opt])]
# frontiers list
attrs = {'label': 'frontier'}
if opts.xd != 0:
attrs = {'marker': 'x', 'zorder': 1, 'mew': 2,
'markersize': 9, 'label': '_nolegend_'}
if optcases:
frontiers += [([c for c in optcases if c.on_frontier], attrs)]
return scatters, frontiers
def multgraph(opts):
dbpathes = [opts.configuration_path] + opts.configuration_pathes
nbdb = len(dbpathes)
optcasesl = [getoptcases(f, opts) for f in dbpathes]
scatters, frontiers = [], []
# dbfiles labels and colors
labels = opts.labels and opts.labels.split(',') or []
for i in range(nbdb - len(labels)): labels.append(str(i))
colors = ['red', 'blue', 'green', 'magenta']
# scatters list
if not opts.frontier_only:
for i in range(nbdb):
attrs = {'color': colors[i % len(colors)], 'label': labels[i]}
scatters += [(optcasesl[i], attrs)]
# frontiers
attrs = {'marker': 'x', 'zorder': 1, 'mew': 2}
for i in range(nbdb):
attrs.update({'color': colors[i % len(colors)]})
if opts.frontier_only: attrs.update({'label': 'frontier-' + labels[i]})
frontiers += [
([c for c in optcasesl[i] if c.on_frontier], dict(attrs))]
return scatters, frontiers
def correlgraph(opts):
dbpathes = [opts.configuration_path] + opts.configuration_pathes
# load results from all databases
optcasesl = []
targets = opts.targets and opts.targets.split('+') or None
for dbpath in dbpathes:
client = atos_lib.atos_client_results(
atos_lib.atos_db.db(dbpath, no_cache=True),
targets and targets.split(',') or None,
atos_lib.strtoquery(opts.query), opts.id)
client.compute_speedups(opts.refid)
optcasesl.append({client.values[2]: client.results})
# dbfiles labels and colors
nbdb = len(dbpathes)
labels = opts.labels and opts.labels.split(',') or []
for i in range(nbdb - len(labels)): labels.append(str(i))
colors = ['red', 'blue', 'green', 'magenta']
# targets common to all dbs
common_targets = (
list(reduce(lambda acc, s: acc.intersection(s),
map(lambda d: set(d.keys()), optcasesl))))
# couples of (target, variant) common to all dbs, REF removed
common_target_variant = list(
reduce(lambda acc, s: acc.intersection(s),
map(lambda c: set([(t, v) for t in common_targets
for v in c[t].keys() if v != opts.refid]),
optcasesl)))
# couples of common (target, variant), sorted by speedups
sorted_common_target_variant = list(reversed(
sorted(common_target_variant,
key=lambda (t, v): optcasesl[0][t][v].speedup)))
#
bars = []
for i in range(nbdb):
attrs = {'color': colors[i % len(colors)], 'label': labels[i]}
optcs = map(
lambda (t, v): optcasesl[i][t][v], sorted_common_target_variant)
bars += [(optcs, attrs)]
return bars
def heatgraph(opts):
def gen_number(result, cookie_to_gen):
result_cookies = result.dict().get('cookies', '').split(',')
for cookie in result_cookies:
if cookie in cookie_to_gen:
return cookie_to_gen[cookie]
return None
def cfg_result(res):
if not opts.tradeoffs:
return res.speedup
return (
res.speedup + (res.sizered / opts.tradeoffs[0])) * 100.0
# get exploration results
optcases = getoptcases(
opts.dbfile and opts.dbfile[0] or opts.configuration_path, opts)
# build cookie_to_gen map
cookie_db = atos_lib.atos_cookie_db_json.cookie_db(
opts.configuration_path)
root_cookie = cookie_db.cookies.get(opts.cookies[0], None)
assert root_cookie, "root cookie not found"
stage_cookies = root_cookie.get('succs', [])
cookie_to_gen = dict(map(lambda (n, c): (c, n), enumerate(stage_cookies)))
# build list of generation results
all_points = []
tradeoff = opts.tradeoffs and opts.tradeoffs[0]
gen_values = sorted(cookie_to_gen.values())[1:]
for gen in gen_values:
gen_results = filter(
lambda res: gen_number(res, cookie_to_gen) == gen, optcases)
gen_points = map(cfg_result, gen_results)
all_points.append(gen_points)
print "gensz", map(lambda x: len(x), all_points)
# add missing points and sort each generation results
max_gen_size = max(map(lambda x: len(x), all_points))
for gen_points in all_points:
gen_points.extend([0.0] * (max_gen_size - len(gen_points)))
gen_points.sort()
print "gensz", map(lambda x: len(x), all_points)
all_points = map(list, zip(*all_points))
return all_points
|
knochelh/atos-utils
|
atoslib/atos_graph.py
|
Python
|
gpl-2.0
| 20,364
|
[
"Gaussian"
] |
ef61905776d7e1d3b2527e9c650821c63eef7b13de2f085d5fb73b1bce308282
|
##~#~#~#~#~#~#~#~#~#~#~#~#~#~#~#~#~#~#~#~#~#~#~#~#~#~#~#~#~#~#~#~#~#~#~#~#~#~#~#~#~#~##
## ##
## This file forms part of the Badlands surface processes modelling companion. ##
## ##
## For full license and copyright information, please refer to the LICENSE.md file ##
## located at the project root, or contact the authors. ##
## ##
##~#~#~#~#~#~#~#~#~#~#~#~#~#~#~#~#~#~#~#~#~#~#~#~#~#~#~#~#~#~#~#~#~#~#~#~#~#~#~#~#~#~##
"""
Here we set usefull functions used to build simple cross-section from Badlands outputs.
"""
import os
import math
import h5py
import errno
import numpy as np
from pyevtk.hl import gridToVTK
import warnings
warnings.simplefilter(action = "ignore", category = FutureWarning)
class stratalMesh:
"""
Class for creating stratigraphic mesh from Badlands outputs.
"""
def __init__(self, folder=None):
"""
Initialization function which takes the folder path to Badlands outputs.
Parameters
----------
variable : folder
Folder path to Badlands outputs.
"""
self.folder = folder
if not os.path.isdir(folder):
raise RuntimeError('The given folder cannot be found or the path is incomplete.')
self.x = None
self.y = None
self.xi = None
self.yi = None
self.dx = None
self.dist = None
self.dx = None
self.nx = None
self.ny = None
self.nz = None
self.dep = None
self.th = None
self.elev = None
self.timestep = 0
return
def loadStratigraphy(self, timestep=0):
"""
Read the HDF5 file for a given time step.
Parameters
----------
variable : timestep
Time step to load.
"""
self.timestep = timestep
df = h5py.File('%s/sed.time%s.hdf5'%(self.folder, timestep), 'r')
coords = np.array((df['/coords']))
layDepth = np.array((df['/layDepth']))
layElev = np.array((df['/layElev']))
layThick = np.array((df['/layThick']))
x, y = np.hsplit(coords, 2)
dep = layDepth
elev = layElev
th = layThick
self.dx = x[1]-x[0]
self.x = x
self.y = y
self.nx = int((x.max() - x.min())/self.dx+1)
self.ny = int((y.max() - y.min())/self.dx+1)
self.nz = dep.shape[1]
self.xi = np.linspace(x.min(), x.max(), self.nx)
self.yi = np.linspace(y.min(), y.max(), self.ny)
self.dep = dep.reshape((self.ny,self.nx,self.nz))
self.elev = elev.reshape((self.ny,self.nx,self.nz))
self.th = th.reshape((self.ny,self.nx,self.nz))
return
def buildMesh(self, outfolder='.'):
"""
Create a vtk unstructured grid based on current time step stratal parameters.
Parameters
----------
variable : outfolder
Folder path to store the stratal vtk mesh.
"""
vtkfile = '%s/stratalMesh.time%s'%(outfolder, self.timestep)
x = np.zeros((self.nx, self.ny, self.nz))
y = np.zeros((self.nx, self.ny, self.nz))
z = np.zeros((self.nx, self.ny, self.nz))
e = np.zeros((self.nx, self.ny, self.nz))
h = np.zeros((self.nx, self.ny, self.nz))
t = np.zeros((self.nx, self.ny, self.nz))
for k in range(self.nz):
for j in range(self.ny):
for i in range(self.nx):
x[i,j,k] = self.xi[i]
y[i,j,k] = self.yi[j]
z[i,j,k] = self.dep[j,i,k]
e[i,j,k] = self.elev[j,i,k]
h[i,j,k] = self.th[j,i,k]
t[i,j,k] = k
gridToVTK(vtkfile, x, y, z, pointData = {"relative elevation" : e, "thickness" :h, "layer ID" :t})
return
|
badlands-model/pyBadlands-Companion
|
badlands_companion/stratalMesh.py
|
Python
|
gpl-3.0
| 4,103
|
[
"VTK"
] |
a2f210254c3caa295b2c52f6c1ca93b78a9125790dd356014eba61dc6f07fa9a
|
import json
import os
from io import StringIO
from Bio import Entrez
Entrez.tool = "GalaxyEutils_1_0"
BATCH_SIZE = 200
class Client(object):
def __init__(self, history_file=None, user_email=None, admin_email=None):
self.using_history = False
self.using_parsedids = False
if user_email is not None and admin_email is not None:
Entrez.email = ';'.join((admin_email, user_email))
elif user_email is not None:
Entrez.email = user_email
elif admin_email is not None:
Entrez.email = admin_email
else:
Entrez.email = os.environ.get('NCBI_EUTILS_CONTACT', None)
if Entrez.email is None:
raise Exception("Cannot continue without an email; please set "
"administrator email in NCBI_EUTILS_CONTACT")
if history_file is not None:
with open(history_file, 'r') as handle:
data = json.loads(handle.read())
# esearch
if 'QueryKey' in data:
self.query_key = data['QueryKey']
self.webenv = data['WebEnv']
self.query_keys = []
self.query_keys += [data['QueryKey']]
self.using_history = True
elif 'query_key' in data:
self.query_key = data['query_key']
self.webenv = data['WebEnv']
self.query_keys = []
self.query_keys += [data['query_key']]
self.using_history = True
elif 'esearchresult' in data:
self.query_key = data['esearchresult']['querykey']
self.webenv = data['esearchresult']['webenv']
self.query_keys = []
self.query_keys += [data['esearchresult']['querykey']]
self.using_history = True
# elink
elif 'linksets' in data:
# elink for cmd=neighbor_history
if 'linksetdbhistories' in data['linksets'][0]:
self.webenv = data['linksets'][0]['webenv']
self.query_key = data['linksets'][0]['linksetdbhistories'][0]['querykey']
self.using_history = True
# elink for cmd=neighbor|neighbor_score
elif 'linksetdbs' in data['linksets'][0]:
self.using_parsedids = True
# elink for neighbor
if isinstance(data['linksets'][0]['linksetdbs'][0]['links'][0], str):
self.idstr = ','.join(data['linksets'][0]['linksetdbs'][0]['links'])
# elink for neighbor_score
else:
self.idstr = ','.join(map(lambda x: x['id'], data['linksets'][0]['linksetdbs'][0]['links']))
if 'linksetdbhistories' in data['linksets'][0]:
self.webenv = data['linksets'][0]['webenv']
self.query_keys = []
for query in data['linksets'][0]['linksetdbhistories']:
if 'querykey' in query:
self.query_keys += [query['querykey']]
else:
print("No match")
print(data)
def get_history(self):
if self.using_history:
return {
'query_key': self.query_key,
'WebEnv': self.webenv,
}
elif self.using_parsedids:
return {
'id': self.idstr,
}
else:
return {}
def get_histories(self):
histories = []
for key in self.query_keys:
histories += [{'WebEnv': self.webenv, 'query_key': key}]
return histories
def post(self, database, **payload):
return json.dumps(Entrez.read(Entrez.epost(database, **payload)), indent=4)
def fetch(self, db, ftype=None, **payload):
os.makedirs("downloads")
if 'id' in payload:
summary = self.id_summary(db, payload['id'])
elif 'WebEnv' not in payload or 'query_key' not in payload:
summary = self.history_summary(db)
else:
summary = payload
count = len(summary)
payload['retmax'] = BATCH_SIZE
# This may be bad. I'm not sure yet. I think it will be ... but UGH.
for i in range(0, count, BATCH_SIZE):
payload['retstart'] = i
file_path = os.path.join('downloads', 'EFetch Results Chunk %s.%s' % (i, ftype))
with open(file_path, 'w') as handle:
handle.write(Entrez.efetch(db, **payload).read())
def id_summary(self, db, id_list):
payload = {
'db': db,
'id': id_list,
}
return Entrez.read(Entrez.esummary(**payload))
def history_summary(self, db):
if not self.using_history:
raise Exception("History must be available for this method")
payload = {
'db': db,
'query_key': self.query_key,
'WebEnv': self.webenv,
}
return Entrez.read(Entrez.esummary(**payload))
def summary(self, **payload):
return Entrez.esummary(**payload).read()
def link(self, **payload):
return Entrez.elink(**payload).read()
def extract_history_from_xml_file(self, xml_file):
history = {}
with open(xml_file, 'r') as handle:
xml_str = handle.read()
history = self.extract_history_from_xml(xml_str)
return history
def extract_history_from_xml(self, xml_str):
try:
parsed_data = Entrez.read(StringIO(xml_str))
history = {}
gotit = 0
# New code doesn't work for esearch input to elink - Parsing esearch output (reading an xml history) does not work as an elink input payload, which needs 'QueryKey'. Notably, if parsing elink output as input to elink, conversion of xml 'QueryKey' to 'query_key' is needed for some reason. Also Notably, efetch returned results using the 'QueryKey' key
# For esearch xml history results
if 'QueryKey' in parsed_data:
history['query_key'] = parsed_data['QueryKey']
gotit += 1
if 'WebEnv' in parsed_data:
history['WebEnv'] = parsed_data['WebEnv']
gotit += 1
# For elink xml history results
if gotit < 2:
if 'LinkSetDbHistory' in parsed_data[0]:
if 'QueryKey' in parsed_data[0]['LinkSetDbHistory'][0]:
history['query_key'] = parsed_data[0]['LinkSetDbHistory'][0]['QueryKey']
gotit += 1
if 'WebEnv' in parsed_data[0]:
history['WebEnv'] = parsed_data[0]['WebEnv']
gotit += 1
if gotit < 2:
raise Exception("Could not find WebEnv in xml response")
except Exception as e:
print("Error parsing...")
print(xml_str)
raise(e)
return history
def extract_histories_from_xml_file(self, xml_file):
histories = []
with open(xml_file, 'r') as handle:
xml_str = handle.read()
histories = self.extract_histories_from_xml(xml_str)
return histories
def extract_histories_from_xml(self, xml_str):
try:
parsed_data = Entrez.read(StringIO(xml_str))
histories = []
gotit = 0
# New code doesn't work for esearch input to elink - Parsing esearch output (reading an xml history) does not work as an elink input payload, which needs 'QueryKey'. Notably, if parsing elink output as input to elink, conversion of xml 'QueryKey' to 'query_key' is needed for some reason. Also Notably, efetch returned results using the 'QueryKey' key
# For esearch xml history results
if 'QueryKey' in parsed_data:
tmp_hist = {}
tmp_hist['query_key'] = parsed_data['QueryKey']
gotit += 1
if 'WebEnv' in parsed_data:
tmp_hist['WebEnv'] = parsed_data['WebEnv']
gotit += 1
if gotit == 2:
histories += [tmp_hist]
# For elink xml history results
else:
gotenv = 0
if 'LinkSetDbHistory' in parsed_data[0]:
for query in parsed_data[0]['LinkSetDbHistory']:
tmp_hist = {}
if 'WebEnv' in parsed_data[0]:
tmp_hist['WebEnv'] = parsed_data[0]['WebEnv']
if 'QueryKey' in query:
tmp_hist['query_key'] = query['QueryKey']
histories += [tmp_hist]
gotit += 1
if gotit == 0 and gotenv == 0:
raise Exception("Could not find WebEnv in xml response")
except Exception as e:
print("Error parsing...")
print(xml_str)
raise(e)
return histories
def search(self, **payload):
return Entrez.esearch(**payload).read()
def info(self, **kwargs):
return Entrez.einfo(**kwargs).read()
def gquery(self, **kwargs):
return Entrez.egquery(**kwargs).read()
def citmatch(self, **kwargs):
return Entrez.ecitmatch(**kwargs).read()
@classmethod
def jsonstring2jsondata(cls, json_str):
json_handle = StringIO(json_str)
json_data = json.loads(json_handle.read())
return json_data
@classmethod
def jsonfile2UIlist(cls, json_file):
merged_ids = []
with open(json_file, 'r') as handle:
json_data = json.loads(handle.read())
for id in cls.jsondata2UIlist(json_data):
merged_ids += [id]
return merged_ids
@classmethod
def jsondata2UIlist(cls, json_data):
merged_ids = []
# Always prioritize the result links as opposed to the search links
# elink - retrieves linked IDs for cmd=neighbor|neighbor_score only
if 'linksets' in json_data:
for lnk in json_data['linksets'][0]['linksetdbs']:
if 'links' in lnk:
for id in lnk['links']:
# elink for neighbor
if isinstance(id, str):
merged_ids.append(id)
# elink for neighbor_score
else:
merged_ids.append(id['id'])
# esearch
elif 'esearchresult' in json_data:
for id in json_data['esearchresult']['idlist']:
merged_ids += [id]
return merged_ids
@classmethod
def xmlfile2UIlist(cls, xml_file):
merged_ids = []
with open(xml_file, 'r') as handle:
xml_data = Entrez.read(handle)
for id in cls.xmldata2UIlist(xml_data):
merged_ids += [id]
return merged_ids
@classmethod
def xmlstring2UIlist(cls, xml_str):
merged_ids = []
xml_data = Entrez.read(StringIO(xml_str))
for id in cls.xmldata2UIlist(xml_data):
merged_ids += [id]
return merged_ids
@classmethod
def xmldata2UIlist(cls, xml_data):
merged_ids = []
try:
# Always prioritize the result links as opposed to the search links
# elink - retrieves linked IDs for cmd=neighbor|neighbor_score only
if 'LinkSetDb' in xml_data[0]:
for lnk in xml_data[0]['LinkSetDb'][0]['Link']:
# elink for neighbor
if isinstance(lnk, str):
merged_ids.append(lnk)
# elink for neighbor_score
else:
merged_ids.append(lnk['Id'])
# esearch
elif 'IdList' in xml_data:
for id in xml_data['IdList']:
merged_ids += [id]
# If it was not elink output, we will end up here
except Exception:
# esearch
if 'IdList' in xml_data:
for id in xml_data['IdList']:
merged_ids += [id]
return merged_ids
@classmethod
def parse_ids(cls, id_list, id, history_file, xml_file, json_file):
"""Parse IDs passed on --cli or in a file passed to the cli
"""
merged_ids = []
if id is not None:
for pid in id.replace('__cn__', ',').replace('\n', ',').split(','):
if pid is not None and len(pid) > 0:
merged_ids.append(pid)
if id_list is not None:
with open(id_list, 'r') as handle:
merged_ids += [x.strip() for x in handle.readlines()]
if xml_file is not None:
tmp_ids = cls.xmlfile2UIlist(xml_file)
for id in tmp_ids:
merged_ids += [id]
if json_file is not None:
tmp_ids = cls.jsonfile2UIlist(json_file)
for id in tmp_ids:
merged_ids += [id]
return merged_ids
@classmethod
def getVersion(cls):
"""Return the biopython version
"""
import Bio
return Bio.__version__
|
martenson/tools-iuc
|
tools/ncbi_entrez_eutils/eutils.py
|
Python
|
mit
| 13,566
|
[
"Biopython"
] |
144354a9b2f68ad96d07a1f41735344ad891edd2d2aa4f67d86af24379120226
|
import sys
import numpy as np
import optparse
def mkgaussian(size, center=None,sig=None,theta=None):
x = np.arange(size*1.0)
y = x[:,np.newaxis]
if sig==None:
sig=(size/10,size/10)
elif isinstance( sig, ( int, long ) ) or isinstance( sig, ( float ) ):
sig=(sig,sig)
else:
assert len(sig)==2 ,"sig must be an integer/float, a list/array of 2 (or None)"
if center is None:
x0 = y0 =0.5*size
else :
assert (len(center)==2) ,"center must be a list/array of 2 (or None)"
x0 = center[0]
y0 = center[1]
if not theta:
return np.exp(-0.5*(((x-x0)/sig[0])**2 + ((y-y0)/sig[1])**2)),[x0,y0],sig,theta
else:
assert (isinstance( theta, ( float ) ) or isinstance( theta, ( int, long ) )), "theta must be a float"
thetarad=theta*np.pi/180.
a = 0.5*(np.cos(thetarad)/sig[0])**2 + 0.5*(np.sin(thetarad)/sig[1])**2
b = -0.25*np.sin(2*thetarad)/sig[0]**2 + 0.25*np.sin(2*thetarad)/sig[1]**2
c = 0.5*(np.sin(thetarad)/sig[0])**2 + 0.5*(np.cos(thetarad)/sig[1])**2
return np.exp( - (a*(x-x0)**2 + 2*b*(x-x0)*(y-y0) + c*(y-y0)**2)),[x0,y0],sig,theta
if __name__=='__main__':
parser = optparse.OptionParser(usage="python mkgauss.py ", conflict_handler="resolve")
parser.add_option('--size', default=100, type=int,
help='size of the array (side)')
parser.add_option('--center', default=None, type=str,
help='center of the gaussian: float or comma separated sequence of 2 floats')
parser.add_option('--sigma', default=None, type=str,
help='sigma of the gaussian: float or comma separated sequence of 2 floats')
parser.add_option('--theta', default=None, type=float,
help='angle in degreed')
parser.add_option('--normalization', default=1.0, type=float,
help='normalization factor')
parser.add_option('--save', default=False,action='store_true',
help='save the gaussian as a fits file')
parser.add_option('--show', default=False,action='store_true',
help='show the gaussian surface')
sigma,center,theta=None,None,None
options, args = parser.parse_args()
if options.sigma:
try:
sigma=float(options.sigma)
except:
try:
sigma=[float(s) for s in options.sigma.split(',')]
assert len(sigma)==2 ,'sigma must be float or comma separated sequence of 2 floats'
except:
print 'sigma must be float or comma separated sequence of 2 floats'
sys.exit()
if options.center:
try:
center=float(options.center)
except:
try:
center=[float(s) for s in options.center.split(',')]
assert len(center)==2, 'center must be float or comma separated sequence of 2 floats'
except:
print 'center must be float or comma separated sequence of 2 floats'
sys.exit()
gauss,c,s,t=mkgaussian(options.size,sig=sigma,center=center,theta=options.theta)
gauss = options.normalization*gauss
if options.show:
import pylab as pl
pl.imshow(gauss)
pl.show()
if options.save:
import pyfits
if t == None: t = 0
hdu = pyfits.PrimaryHDU(gauss)
hdulist = pyfits.HDUList([hdu])
hdulist.writeto('gaussian_center%.1fx%.1f_sigma%.1fx%.1f_theta%.1f_size%d.fits'
%(c[0],c[1],s[0],s[1],t,options.size),clobber=True)
|
fedhere/fedsastroutils
|
mkgauss.py
|
Python
|
mit
| 3,666
|
[
"Gaussian"
] |
6ddf43b246e71514fa95af7df9539cf6fd294c21543a6a512e6b041d3dbcf90b
|
#!/usr/bin/env python
import os
from optparse import OptionParser
from ase.io.trajectory import print_trajectory_info
from ase.io.bundletrajectory import print_bundletrajectory_info
description = 'Print summary of information from trajectory files.'
def main():
p = OptionParser(usage='%prog file.traj [file2.traj ...]',
description=description)
opts, args = p.parse_args()
if len(args) == 0:
p.error('Incorrect number of arguments')
for f in args:
if os.path.isfile(f):
print_trajectory_info(f)
elif os.path.isdir(f):
print_bundletrajectory_info(f)
else:
p.error('%s is neither a file nor a directory!' % f)
|
askhl/ase
|
ase/cli/info.py
|
Python
|
gpl-2.0
| 720
|
[
"ASE"
] |
02a2e31bbe32135be090b632c206016ce7a125dc7718885ff1d273957812dd84
|
from __future__ import division, absolute_import, print_function
import collections
import re
import sys
import warnings
import operator
import numpy as np
import numpy.core.numeric as _nx
from numpy.core import linspace, atleast_1d, atleast_2d, transpose
from numpy.core.numeric import (
ones, zeros, arange, concatenate, array, asarray, asanyarray, empty,
empty_like, ndarray, around, floor, ceil, take, dot, where, intp,
integer, isscalar, absolute, AxisError
)
from numpy.core.umath import (
pi, multiply, add, arctan2, frompyfunc, cos, less_equal, sqrt, sin,
mod, exp, log10, not_equal, subtract
)
from numpy.core.fromnumeric import (
ravel, nonzero, sort, partition, mean, any, sum
)
from numpy.core.numerictypes import typecodes, number
from numpy.lib.twodim_base import diag
from .utils import deprecate
from numpy.core.multiarray import (
_insert, add_docstring, digitize, bincount, normalize_axis_index,
interp as compiled_interp, interp_complex as compiled_interp_complex
)
from numpy.core.umath import _add_newdoc_ufunc as add_newdoc_ufunc
from numpy.compat import long
from numpy.compat.py3k import basestring
if sys.version_info[0] < 3:
# Force range to be a generator, for np.delete's usage.
range = xrange
import __builtin__ as builtins
else:
import builtins
__all__ = [
'select', 'piecewise', 'trim_zeros', 'copy', 'iterable', 'percentile',
'diff', 'gradient', 'angle', 'unwrap', 'sort_complex', 'disp', 'flip',
'rot90', 'extract', 'place', 'vectorize', 'asarray_chkfinite', 'average',
'histogram', 'histogramdd', 'bincount', 'digitize', 'cov', 'corrcoef',
'msort', 'median', 'sinc', 'hamming', 'hanning', 'bartlett',
'blackman', 'kaiser', 'trapz', 'i0', 'add_newdoc', 'add_docstring',
'meshgrid', 'delete', 'insert', 'append', 'interp', 'add_newdoc_ufunc'
]
def rot90(m, k=1, axes=(0,1)):
"""
Rotate an array by 90 degrees in the plane specified by axes.
Rotation direction is from the first towards the second axis.
Parameters
----------
m : array_like
Array of two or more dimensions.
k : integer
Number of times the array is rotated by 90 degrees.
axes: (2,) array_like
The array is rotated in the plane defined by the axes.
Axes must be different.
.. versionadded:: 1.12.0
Returns
-------
y : ndarray
A rotated view of `m`.
See Also
--------
flip : Reverse the order of elements in an array along the given axis.
fliplr : Flip an array horizontally.
flipud : Flip an array vertically.
Notes
-----
rot90(m, k=1, axes=(1,0)) is the reverse of rot90(m, k=1, axes=(0,1))
rot90(m, k=1, axes=(1,0)) is equivalent to rot90(m, k=-1, axes=(0,1))
Examples
--------
>>> m = np.array([[1,2],[3,4]], int)
>>> m
array([[1, 2],
[3, 4]])
>>> np.rot90(m)
array([[2, 4],
[1, 3]])
>>> np.rot90(m, 2)
array([[4, 3],
[2, 1]])
>>> m = np.arange(8).reshape((2,2,2))
>>> np.rot90(m, 1, (1,2))
array([[[1, 3],
[0, 2]],
[[5, 7],
[4, 6]]])
"""
axes = tuple(axes)
if len(axes) != 2:
raise ValueError("len(axes) must be 2.")
m = asanyarray(m)
if axes[0] == axes[1] or absolute(axes[0] - axes[1]) == m.ndim:
raise ValueError("Axes must be different.")
if (axes[0] >= m.ndim or axes[0] < -m.ndim
or axes[1] >= m.ndim or axes[1] < -m.ndim):
raise ValueError("Axes={} out of range for array of ndim={}."
.format(axes, m.ndim))
k %= 4
if k == 0:
return m[:]
if k == 2:
return flip(flip(m, axes[0]), axes[1])
axes_list = arange(0, m.ndim)
(axes_list[axes[0]], axes_list[axes[1]]) = (axes_list[axes[1]],
axes_list[axes[0]])
if k == 1:
return transpose(flip(m,axes[1]), axes_list)
else:
# k == 3
return flip(transpose(m, axes_list), axes[1])
def flip(m, axis):
"""
Reverse the order of elements in an array along the given axis.
The shape of the array is preserved, but the elements are reordered.
.. versionadded:: 1.12.0
Parameters
----------
m : array_like
Input array.
axis : integer
Axis in array, which entries are reversed.
Returns
-------
out : array_like
A view of `m` with the entries of axis reversed. Since a view is
returned, this operation is done in constant time.
See Also
--------
flipud : Flip an array vertically (axis=0).
fliplr : Flip an array horizontally (axis=1).
Notes
-----
flip(m, 0) is equivalent to flipud(m).
flip(m, 1) is equivalent to fliplr(m).
flip(m, n) corresponds to ``m[...,::-1,...]`` with ``::-1`` at position n.
Examples
--------
>>> A = np.arange(8).reshape((2,2,2))
>>> A
array([[[0, 1],
[2, 3]],
[[4, 5],
[6, 7]]])
>>> flip(A, 0)
array([[[4, 5],
[6, 7]],
[[0, 1],
[2, 3]]])
>>> flip(A, 1)
array([[[2, 3],
[0, 1]],
[[6, 7],
[4, 5]]])
>>> A = np.random.randn(3,4,5)
>>> np.all(flip(A,2) == A[:,:,::-1,...])
True
"""
if not hasattr(m, 'ndim'):
m = asarray(m)
indexer = [slice(None)] * m.ndim
try:
indexer[axis] = slice(None, None, -1)
except IndexError:
raise ValueError("axis=%i is invalid for the %i-dimensional input array"
% (axis, m.ndim))
return m[tuple(indexer)]
def iterable(y):
"""
Check whether or not an object can be iterated over.
Parameters
----------
y : object
Input object.
Returns
-------
b : bool
Return ``True`` if the object has an iterator method or is a
sequence and ``False`` otherwise.
Examples
--------
>>> np.iterable([1, 2, 3])
True
>>> np.iterable(2)
False
"""
try:
iter(y)
except TypeError:
return False
return True
def _hist_bin_sqrt(x):
"""
Square root histogram bin estimator.
Bin width is inversely proportional to the data size. Used by many
programs for its simplicity.
Parameters
----------
x : array_like
Input data that is to be histogrammed, trimmed to range. May not
be empty.
Returns
-------
h : An estimate of the optimal bin width for the given data.
"""
return x.ptp() / np.sqrt(x.size)
def _hist_bin_sturges(x):
"""
Sturges histogram bin estimator.
A very simplistic estimator based on the assumption of normality of
the data. This estimator has poor performance for non-normal data,
which becomes especially obvious for large data sets. The estimate
depends only on size of the data.
Parameters
----------
x : array_like
Input data that is to be histogrammed, trimmed to range. May not
be empty.
Returns
-------
h : An estimate of the optimal bin width for the given data.
"""
return x.ptp() / (np.log2(x.size) + 1.0)
def _hist_bin_rice(x):
"""
Rice histogram bin estimator.
Another simple estimator with no normality assumption. It has better
performance for large data than Sturges, but tends to overestimate
the number of bins. The number of bins is proportional to the cube
root of data size (asymptotically optimal). The estimate depends
only on size of the data.
Parameters
----------
x : array_like
Input data that is to be histogrammed, trimmed to range. May not
be empty.
Returns
-------
h : An estimate of the optimal bin width for the given data.
"""
return x.ptp() / (2.0 * x.size ** (1.0 / 3))
def _hist_bin_scott(x):
"""
Scott histogram bin estimator.
The binwidth is proportional to the standard deviation of the data
and inversely proportional to the cube root of data size
(asymptotically optimal).
Parameters
----------
x : array_like
Input data that is to be histogrammed, trimmed to range. May not
be empty.
Returns
-------
h : An estimate of the optimal bin width for the given data.
"""
return (24.0 * np.pi**0.5 / x.size)**(1.0 / 3.0) * np.std(x)
def _hist_bin_doane(x):
"""
Doane's histogram bin estimator.
Improved version of Sturges' formula which works better for
non-normal data. See
stats.stackexchange.com/questions/55134/doanes-formula-for-histogram-binning
Parameters
----------
x : array_like
Input data that is to be histogrammed, trimmed to range. May not
be empty.
Returns
-------
h : An estimate of the optimal bin width for the given data.
"""
if x.size > 2:
sg1 = np.sqrt(6.0 * (x.size - 2) / ((x.size + 1.0) * (x.size + 3)))
sigma = np.std(x)
if sigma > 0.0:
# These three operations add up to
# g1 = np.mean(((x - np.mean(x)) / sigma)**3)
# but use only one temp array instead of three
temp = x - np.mean(x)
np.true_divide(temp, sigma, temp)
np.power(temp, 3, temp)
g1 = np.mean(temp)
return x.ptp() / (1.0 + np.log2(x.size) +
np.log2(1.0 + np.absolute(g1) / sg1))
return 0.0
def _hist_bin_fd(x):
"""
The Freedman-Diaconis histogram bin estimator.
The Freedman-Diaconis rule uses interquartile range (IQR) to
estimate binwidth. It is considered a variation of the Scott rule
with more robustness as the IQR is less affected by outliers than
the standard deviation. However, the IQR depends on fewer points
than the standard deviation, so it is less accurate, especially for
long tailed distributions.
If the IQR is 0, this function returns 1 for the number of bins.
Binwidth is inversely proportional to the cube root of data size
(asymptotically optimal).
Parameters
----------
x : array_like
Input data that is to be histogrammed, trimmed to range. May not
be empty.
Returns
-------
h : An estimate of the optimal bin width for the given data.
"""
iqr = np.subtract(*np.percentile(x, [75, 25]))
return 2.0 * iqr * x.size ** (-1.0 / 3.0)
def _hist_bin_auto(x):
"""
Histogram bin estimator that uses the minimum width of the
Freedman-Diaconis and Sturges estimators.
The FD estimator is usually the most robust method, but its width
estimate tends to be too large for small `x`. The Sturges estimator
is quite good for small (<1000) datasets and is the default in the R
language. This method gives good off the shelf behaviour.
Parameters
----------
x : array_like
Input data that is to be histogrammed, trimmed to range. May not
be empty.
Returns
-------
h : An estimate of the optimal bin width for the given data.
See Also
--------
_hist_bin_fd, _hist_bin_sturges
"""
# There is no need to check for zero here. If ptp is, so is IQR and
# vice versa. Either both are zero or neither one is.
return min(_hist_bin_fd(x), _hist_bin_sturges(x))
# Private dict initialized at module load time
_hist_bin_selectors = {'auto': _hist_bin_auto,
'doane': _hist_bin_doane,
'fd': _hist_bin_fd,
'rice': _hist_bin_rice,
'scott': _hist_bin_scott,
'sqrt': _hist_bin_sqrt,
'sturges': _hist_bin_sturges}
def histogram(a, bins=10, range=None, normed=False, weights=None,
density=None):
r"""
Compute the histogram of a set of data.
Parameters
----------
a : array_like
Input data. The histogram is computed over the flattened array.
bins : int or sequence of scalars or str, optional
If `bins` is an int, it defines the number of equal-width
bins in the given range (10, by default). If `bins` is a
sequence, it defines the bin edges, including the rightmost
edge, allowing for non-uniform bin widths.
.. versionadded:: 1.11.0
If `bins` is a string from the list below, `histogram` will use
the method chosen to calculate the optimal bin width and
consequently the number of bins (see `Notes` for more detail on
the estimators) from the data that falls within the requested
range. While the bin width will be optimal for the actual data
in the range, the number of bins will be computed to fill the
entire range, including the empty portions. For visualisation,
using the 'auto' option is suggested. Weighted data is not
supported for automated bin size selection.
'auto'
Maximum of the 'sturges' and 'fd' estimators. Provides good
all around performance.
'fd' (Freedman Diaconis Estimator)
Robust (resilient to outliers) estimator that takes into
account data variability and data size.
'doane'
An improved version of Sturges' estimator that works better
with non-normal datasets.
'scott'
Less robust estimator that that takes into account data
variability and data size.
'rice'
Estimator does not take variability into account, only data
size. Commonly overestimates number of bins required.
'sturges'
R's default method, only accounts for data size. Only
optimal for gaussian data and underestimates number of bins
for large non-gaussian datasets.
'sqrt'
Square root (of data size) estimator, used by Excel and
other programs for its speed and simplicity.
range : (float, float), optional
The lower and upper range of the bins. If not provided, range
is simply ``(a.min(), a.max())``. Values outside the range are
ignored. The first element of the range must be less than or
equal to the second. `range` affects the automatic bin
computation as well. While bin width is computed to be optimal
based on the actual data within `range`, the bin count will fill
the entire range including portions containing no data.
normed : bool, optional
This keyword is deprecated in NumPy 1.6.0 due to confusing/buggy
behavior. It will be removed in NumPy 2.0.0. Use the ``density``
keyword instead. If ``False``, the result will contain the
number of samples in each bin. If ``True``, the result is the
value of the probability *density* function at the bin,
normalized such that the *integral* over the range is 1. Note
that this latter behavior is known to be buggy with unequal bin
widths; use ``density`` instead.
weights : array_like, optional
An array of weights, of the same shape as `a`. Each value in
`a` only contributes its associated weight towards the bin count
(instead of 1). If `density` is True, the weights are
normalized, so that the integral of the density over the range
remains 1.
density : bool, optional
If ``False``, the result will contain the number of samples in
each bin. If ``True``, the result is the value of the
probability *density* function at the bin, normalized such that
the *integral* over the range is 1. Note that the sum of the
histogram values will not be equal to 1 unless bins of unity
width are chosen; it is not a probability *mass* function.
Overrides the ``normed`` keyword if given.
Returns
-------
hist : array
The values of the histogram. See `density` and `weights` for a
description of the possible semantics.
bin_edges : array of dtype float
Return the bin edges ``(length(hist)+1)``.
See Also
--------
histogramdd, bincount, searchsorted, digitize
Notes
-----
All but the last (righthand-most) bin is half-open. In other words,
if `bins` is::
[1, 2, 3, 4]
then the first bin is ``[1, 2)`` (including 1, but excluding 2) and
the second ``[2, 3)``. The last bin, however, is ``[3, 4]``, which
*includes* 4.
.. versionadded:: 1.11.0
The methods to estimate the optimal number of bins are well founded
in literature, and are inspired by the choices R provides for
histogram visualisation. Note that having the number of bins
proportional to :math:`n^{1/3}` is asymptotically optimal, which is
why it appears in most estimators. These are simply plug-in methods
that give good starting points for number of bins. In the equations
below, :math:`h` is the binwidth and :math:`n_h` is the number of
bins. All estimators that compute bin counts are recast to bin width
using the `ptp` of the data. The final bin count is obtained from
``np.round(np.ceil(range / h))`.
'Auto' (maximum of the 'Sturges' and 'FD' estimators)
A compromise to get a good value. For small datasets the Sturges
value will usually be chosen, while larger datasets will usually
default to FD. Avoids the overly conservative behaviour of FD
and Sturges for small and large datasets respectively.
Switchover point is usually :math:`a.size \approx 1000`.
'FD' (Freedman Diaconis Estimator)
.. math:: h = 2 \frac{IQR}{n^{1/3}}
The binwidth is proportional to the interquartile range (IQR)
and inversely proportional to cube root of a.size. Can be too
conservative for small datasets, but is quite good for large
datasets. The IQR is very robust to outliers.
'Scott'
.. math:: h = \sigma \sqrt[3]{\frac{24 * \sqrt{\pi}}{n}}
The binwidth is proportional to the standard deviation of the
data and inversely proportional to cube root of ``x.size``. Can
be too conservative for small datasets, but is quite good for
large datasets. The standard deviation is not very robust to
outliers. Values are very similar to the Freedman-Diaconis
estimator in the absence of outliers.
'Rice'
.. math:: n_h = 2n^{1/3}
The number of bins is only proportional to cube root of
``a.size``. It tends to overestimate the number of bins and it
does not take into account data variability.
'Sturges'
.. math:: n_h = \log _{2}n+1
The number of bins is the base 2 log of ``a.size``. This
estimator assumes normality of data and is too conservative for
larger, non-normal datasets. This is the default method in R's
``hist`` method.
'Doane'
.. math:: n_h = 1 + \log_{2}(n) +
\log_{2}(1 + \frac{|g_1|}{\sigma_{g_1}})
g_1 = mean[(\frac{x - \mu}{\sigma})^3]
\sigma_{g_1} = \sqrt{\frac{6(n - 2)}{(n + 1)(n + 3)}}
An improved version of Sturges' formula that produces better
estimates for non-normal datasets. This estimator attempts to
account for the skew of the data.
'Sqrt'
.. math:: n_h = \sqrt n
The simplest and fastest estimator. Only takes into account the
data size.
Examples
--------
>>> np.histogram([1, 2, 1], bins=[0, 1, 2, 3])
(array([0, 2, 1]), array([0, 1, 2, 3]))
>>> np.histogram(np.arange(4), bins=np.arange(5), density=True)
(array([ 0.25, 0.25, 0.25, 0.25]), array([0, 1, 2, 3, 4]))
>>> np.histogram([[1, 2, 1], [1, 0, 1]], bins=[0,1,2,3])
(array([1, 4, 1]), array([0, 1, 2, 3]))
>>> a = np.arange(5)
>>> hist, bin_edges = np.histogram(a, density=True)
>>> hist
array([ 0.5, 0. , 0.5, 0. , 0. , 0.5, 0. , 0.5, 0. , 0.5])
>>> hist.sum()
2.4999999999999996
>>> np.sum(hist * np.diff(bin_edges))
1.0
.. versionadded:: 1.11.0
Automated Bin Selection Methods example, using 2 peak random data
with 2000 points:
>>> import matplotlib.pyplot as plt
>>> rng = np.random.RandomState(10) # deterministic random data
>>> a = np.hstack((rng.normal(size=1000),
... rng.normal(loc=5, scale=2, size=1000)))
>>> plt.hist(a, bins='auto') # arguments are passed to np.histogram
>>> plt.title("Histogram with 'auto' bins")
>>> plt.show()
"""
a = asarray(a)
if weights is not None:
weights = asarray(weights)
if weights.shape != a.shape:
raise ValueError(
'weights should have the same shape as a.')
weights = weights.ravel()
a = a.ravel()
# Do not modify the original value of range so we can check for `None`
if range is None:
if a.size == 0:
# handle empty arrays. Can't determine range, so use 0-1.
first_edge, last_edge = 0.0, 1.0
else:
first_edge, last_edge = a.min() + 0.0, a.max() + 0.0
else:
first_edge, last_edge = [mi + 0.0 for mi in range]
if first_edge > last_edge:
raise ValueError(
'max must be larger than min in range parameter.')
if not np.all(np.isfinite([first_edge, last_edge])):
raise ValueError(
'range parameter must be finite.')
if first_edge == last_edge:
first_edge -= 0.5
last_edge += 0.5
# density overrides the normed keyword
if density is not None:
normed = False
# parse the overloaded bins argument
n_equal_bins = None
bin_edges = None
if isinstance(bins, basestring):
bin_name = bins
# if `bins` is a string for an automatic method,
# this will replace it with the number of bins calculated
if bin_name not in _hist_bin_selectors:
raise ValueError(
"{!r} is not a valid estimator for `bins`".format(bin_name))
if weights is not None:
raise TypeError("Automated estimation of the number of "
"bins is not supported for weighted data")
# Make a reference to `a`
b = a
# Update the reference if the range needs truncation
if range is not None:
keep = (a >= first_edge)
keep &= (a <= last_edge)
if not np.logical_and.reduce(keep):
b = a[keep]
if b.size == 0:
n_equal_bins = 1
else:
# Do not call selectors on empty arrays
width = _hist_bin_selectors[bin_name](b)
if width:
n_equal_bins = int(np.ceil((last_edge - first_edge) / width))
else:
# Width can be zero for some estimators, e.g. FD when
# the IQR of the data is zero.
n_equal_bins = 1
elif np.ndim(bins) == 0:
try:
n_equal_bins = operator.index(bins)
except TypeError:
raise TypeError(
'`bins` must be an integer, a string, or an array')
if n_equal_bins < 1:
raise ValueError('`bins` must be positive, when an integer')
elif np.ndim(bins) == 1:
bin_edges = np.asarray(bins)
if np.any(bin_edges[:-1] > bin_edges[1:]):
raise ValueError(
'`bins` must increase monotonically, when an array')
else:
raise ValueError('`bins` must be 1d, when an array')
del bins
# compute the bins if only the count was specified
if n_equal_bins is not None:
bin_edges = linspace(
first_edge, last_edge, n_equal_bins + 1, endpoint=True)
# Histogram is an integer or a float array depending on the weights.
if weights is None:
ntype = np.dtype(np.intp)
else:
ntype = weights.dtype
# We set a block size, as this allows us to iterate over chunks when
# computing histograms, to minimize memory usage.
BLOCK = 65536
# The fast path uses bincount, but that only works for certain types
# of weight
simple_weights = (
weights is None or
np.can_cast(weights.dtype, np.double) or
np.can_cast(weights.dtype, complex)
)
if n_equal_bins is not None and simple_weights:
# Fast algorithm for equal bins
# We now convert values of a to bin indices, under the assumption of
# equal bin widths (which is valid here).
# Initialize empty histogram
n = np.zeros(n_equal_bins, ntype)
# Pre-compute histogram scaling factor
norm = n_equal_bins / (last_edge - first_edge)
# We iterate over blocks here for two reasons: the first is that for
# large arrays, it is actually faster (for example for a 10^8 array it
# is 2x as fast) and it results in a memory footprint 3x lower in the
# limit of large arrays.
for i in arange(0, len(a), BLOCK):
tmp_a = a[i:i+BLOCK]
if weights is None:
tmp_w = None
else:
tmp_w = weights[i:i + BLOCK]
# Only include values in the right range
keep = (tmp_a >= first_edge)
keep &= (tmp_a <= last_edge)
if not np.logical_and.reduce(keep):
tmp_a = tmp_a[keep]
if tmp_w is not None:
tmp_w = tmp_w[keep]
tmp_a_data = tmp_a.astype(float)
tmp_a = tmp_a_data - first_edge
tmp_a *= norm
# Compute the bin indices, and for values that lie exactly on
# last_edge we need to subtract one
indices = tmp_a.astype(np.intp)
indices[indices == n_equal_bins] -= 1
# The index computation is not guaranteed to give exactly
# consistent results within ~1 ULP of the bin edges.
decrement = tmp_a_data < bin_edges[indices]
indices[decrement] -= 1
# The last bin includes the right edge. The other bins do not.
increment = ((tmp_a_data >= bin_edges[indices + 1])
& (indices != n_equal_bins - 1))
indices[increment] += 1
# We now compute the histogram using bincount
if ntype.kind == 'c':
n.real += np.bincount(indices, weights=tmp_w.real,
minlength=n_equal_bins)
n.imag += np.bincount(indices, weights=tmp_w.imag,
minlength=n_equal_bins)
else:
n += np.bincount(indices, weights=tmp_w,
minlength=n_equal_bins).astype(ntype)
else:
# Compute via cumulative histogram
cum_n = np.zeros(bin_edges.shape, ntype)
if weights is None:
for i in arange(0, len(a), BLOCK):
sa = sort(a[i:i+BLOCK])
cum_n += np.r_[sa.searchsorted(bin_edges[:-1], 'left'),
sa.searchsorted(bin_edges[-1], 'right')]
else:
zero = array(0, dtype=ntype)
for i in arange(0, len(a), BLOCK):
tmp_a = a[i:i+BLOCK]
tmp_w = weights[i:i+BLOCK]
sorting_index = np.argsort(tmp_a)
sa = tmp_a[sorting_index]
sw = tmp_w[sorting_index]
cw = np.concatenate(([zero], sw.cumsum()))
bin_index = np.r_[sa.searchsorted(bin_edges[:-1], 'left'),
sa.searchsorted(bin_edges[-1], 'right')]
cum_n += cw[bin_index]
n = np.diff(cum_n)
if density:
db = array(np.diff(bin_edges), float)
return n/db/n.sum(), bin_edges
elif normed:
# deprecated, buggy behavior. Remove for NumPy 2.0.0
db = array(np.diff(bin_edges), float)
return n/(n*db).sum(), bin_edges
else:
return n, bin_edges
def histogramdd(sample, bins=10, range=None, normed=False, weights=None):
"""
Compute the multidimensional histogram of some data.
Parameters
----------
sample : array_like
The data to be histogrammed. It must be an (N,D) array or data
that can be converted to such. The rows of the resulting array
are the coordinates of points in a D dimensional polytope.
bins : sequence or int, optional
The bin specification:
* A sequence of arrays describing the bin edges along each dimension.
* The number of bins for each dimension (nx, ny, ... =bins)
* The number of bins for all dimensions (nx=ny=...=bins).
range : sequence, optional
A sequence of lower and upper bin edges to be used if the edges are
not given explicitly in `bins`. Defaults to the minimum and maximum
values along each dimension.
normed : bool, optional
If False, returns the number of samples in each bin. If True,
returns the bin density ``bin_count / sample_count / bin_volume``.
weights : (N,) array_like, optional
An array of values `w_i` weighing each sample `(x_i, y_i, z_i, ...)`.
Weights are normalized to 1 if normed is True. If normed is False,
the values of the returned histogram are equal to the sum of the
weights belonging to the samples falling into each bin.
Returns
-------
H : ndarray
The multidimensional histogram of sample x. See normed and weights
for the different possible semantics.
edges : list
A list of D arrays describing the bin edges for each dimension.
See Also
--------
histogram: 1-D histogram
histogram2d: 2-D histogram
Examples
--------
>>> r = np.random.randn(100,3)
>>> H, edges = np.histogramdd(r, bins = (5, 8, 4))
>>> H.shape, edges[0].size, edges[1].size, edges[2].size
((5, 8, 4), 6, 9, 5)
"""
try:
# Sample is an ND-array.
N, D = sample.shape
except (AttributeError, ValueError):
# Sample is a sequence of 1D arrays.
sample = atleast_2d(sample).T
N, D = sample.shape
nbin = empty(D, int)
edges = D*[None]
dedges = D*[None]
if weights is not None:
weights = asarray(weights)
try:
M = len(bins)
if M != D:
raise ValueError(
'The dimension of bins must be equal to the dimension of the '
' sample x.')
except TypeError:
# bins is an integer
bins = D*[bins]
# Select range for each dimension
# Used only if number of bins is given.
if range is None:
# Handle empty input. Range can't be determined in that case, use 0-1.
if N == 0:
smin = zeros(D)
smax = ones(D)
else:
smin = atleast_1d(array(sample.min(0), float))
smax = atleast_1d(array(sample.max(0), float))
else:
if not np.all(np.isfinite(range)):
raise ValueError(
'range parameter must be finite.')
smin = zeros(D)
smax = zeros(D)
for i in arange(D):
smin[i], smax[i] = range[i]
# Make sure the bins have a finite width.
for i in arange(len(smin)):
if smin[i] == smax[i]:
smin[i] = smin[i] - .5
smax[i] = smax[i] + .5
# avoid rounding issues for comparisons when dealing with inexact types
if np.issubdtype(sample.dtype, np.inexact):
edge_dt = sample.dtype
else:
edge_dt = float
# Create edge arrays
for i in arange(D):
if isscalar(bins[i]):
if bins[i] < 1:
raise ValueError(
"Element at index %s in `bins` should be a positive "
"integer." % i)
nbin[i] = bins[i] + 2 # +2 for outlier bins
edges[i] = linspace(smin[i], smax[i], nbin[i]-1, dtype=edge_dt)
else:
edges[i] = asarray(bins[i], edge_dt)
nbin[i] = len(edges[i]) + 1 # +1 for outlier bins
dedges[i] = diff(edges[i])
if np.any(np.asarray(dedges[i]) <= 0):
raise ValueError(
"Found bin edge of size <= 0. Did you specify `bins` with"
"non-monotonic sequence?")
nbin = asarray(nbin)
# Handle empty input.
if N == 0:
return np.zeros(nbin-2), edges
# Compute the bin number each sample falls into.
Ncount = {}
for i in arange(D):
Ncount[i] = digitize(sample[:, i], edges[i])
# Using digitize, values that fall on an edge are put in the right bin.
# For the rightmost bin, we want values equal to the right edge to be
# counted in the last bin, and not as an outlier.
for i in arange(D):
# Rounding precision
mindiff = dedges[i].min()
if not np.isinf(mindiff):
decimal = int(-log10(mindiff)) + 6
# Find which points are on the rightmost edge.
not_smaller_than_edge = (sample[:, i] >= edges[i][-1])
on_edge = (around(sample[:, i], decimal) ==
around(edges[i][-1], decimal))
# Shift these points one bin to the left.
Ncount[i][nonzero(on_edge & not_smaller_than_edge)[0]] -= 1
# Flattened histogram matrix (1D)
# Reshape is used so that overlarge arrays
# will raise an error.
hist = zeros(nbin, float).reshape(-1)
# Compute the sample indices in the flattened histogram matrix.
ni = nbin.argsort()
xy = zeros(N, int)
for i in arange(0, D-1):
xy += Ncount[ni[i]] * nbin[ni[i+1:]].prod()
xy += Ncount[ni[-1]]
# Compute the number of repetitions in xy and assign it to the
# flattened histmat.
if len(xy) == 0:
return zeros(nbin-2, int), edges
flatcount = bincount(xy, weights)
a = arange(len(flatcount))
hist[a] = flatcount
# Shape into a proper matrix
hist = hist.reshape(sort(nbin))
for i in arange(nbin.size):
j = ni.argsort()[i]
hist = hist.swapaxes(i, j)
ni[i], ni[j] = ni[j], ni[i]
# Remove outliers (indices 0 and -1 for each dimension).
core = D*[slice(1, -1)]
hist = hist[core]
# Normalize if normed is True
if normed:
s = hist.sum()
for i in arange(D):
shape = ones(D, int)
shape[i] = nbin[i] - 2
hist = hist / dedges[i].reshape(shape)
hist /= s
if (hist.shape != nbin - 2).any():
raise RuntimeError(
"Internal Shape Error")
return hist, edges
def average(a, axis=None, weights=None, returned=False):
"""
Compute the weighted average along the specified axis.
Parameters
----------
a : array_like
Array containing data to be averaged. If `a` is not an array, a
conversion is attempted.
axis : None or int or tuple of ints, optional
Axis or axes along which to average `a`. The default,
axis=None, will average over all of the elements of the input array.
If axis is negative it counts from the last to the first axis.
.. versionadded:: 1.7.0
If axis is a tuple of ints, averaging is performed on all of the axes
specified in the tuple instead of a single axis or all the axes as
before.
weights : array_like, optional
An array of weights associated with the values in `a`. Each value in
`a` contributes to the average according to its associated weight.
The weights array can either be 1-D (in which case its length must be
the size of `a` along the given axis) or of the same shape as `a`.
If `weights=None`, then all data in `a` are assumed to have a
weight equal to one.
returned : bool, optional
Default is `False`. If `True`, the tuple (`average`, `sum_of_weights`)
is returned, otherwise only the average is returned.
If `weights=None`, `sum_of_weights` is equivalent to the number of
elements over which the average is taken.
Returns
-------
average, [sum_of_weights] : array_type or double
Return the average along the specified axis. When returned is `True`,
return a tuple with the average as the first element and the sum
of the weights as the second element. The return type is `Float`
if `a` is of integer type, otherwise it is of the same type as `a`.
`sum_of_weights` is of the same type as `average`.
Raises
------
ZeroDivisionError
When all weights along axis are zero. See `numpy.ma.average` for a
version robust to this type of error.
TypeError
When the length of 1D `weights` is not the same as the shape of `a`
along axis.
See Also
--------
mean
ma.average : average for masked arrays -- useful if your data contains
"missing" values
Examples
--------
>>> data = range(1,5)
>>> data
[1, 2, 3, 4]
>>> np.average(data)
2.5
>>> np.average(range(1,11), weights=range(10,0,-1))
4.0
>>> data = np.arange(6).reshape((3,2))
>>> data
array([[0, 1],
[2, 3],
[4, 5]])
>>> np.average(data, axis=1, weights=[1./4, 3./4])
array([ 0.75, 2.75, 4.75])
>>> np.average(data, weights=[1./4, 3./4])
Traceback (most recent call last):
...
TypeError: Axis must be specified when shapes of a and weights differ.
"""
a = np.asanyarray(a)
if weights is None:
avg = a.mean(axis)
scl = avg.dtype.type(a.size/avg.size)
else:
wgt = np.asanyarray(weights)
if issubclass(a.dtype.type, (np.integer, np.bool_)):
result_dtype = np.result_type(a.dtype, wgt.dtype, 'f8')
else:
result_dtype = np.result_type(a.dtype, wgt.dtype)
# Sanity checks
if a.shape != wgt.shape:
if axis is None:
raise TypeError(
"Axis must be specified when shapes of a and weights "
"differ.")
if wgt.ndim != 1:
raise TypeError(
"1D weights expected when shapes of a and weights differ.")
if wgt.shape[0] != a.shape[axis]:
raise ValueError(
"Length of weights not compatible with specified axis.")
# setup wgt to broadcast along axis
wgt = np.broadcast_to(wgt, (a.ndim-1)*(1,) + wgt.shape)
wgt = wgt.swapaxes(-1, axis)
scl = wgt.sum(axis=axis, dtype=result_dtype)
if np.any(scl == 0.0):
raise ZeroDivisionError(
"Weights sum to zero, can't be normalized")
avg = np.multiply(a, wgt, dtype=result_dtype).sum(axis)/scl
if returned:
if scl.shape != avg.shape:
scl = np.broadcast_to(scl, avg.shape).copy()
return avg, scl
else:
return avg
def asarray_chkfinite(a, dtype=None, order=None):
"""Convert the input to an array, checking for NaNs or Infs.
Parameters
----------
a : array_like
Input data, in any form that can be converted to an array. This
includes lists, lists of tuples, tuples, tuples of tuples, tuples
of lists and ndarrays. Success requires no NaNs or Infs.
dtype : data-type, optional
By default, the data-type is inferred from the input data.
order : {'C', 'F'}, optional
Whether to use row-major (C-style) or
column-major (Fortran-style) memory representation.
Defaults to 'C'.
Returns
-------
out : ndarray
Array interpretation of `a`. No copy is performed if the input
is already an ndarray. If `a` is a subclass of ndarray, a base
class ndarray is returned.
Raises
------
ValueError
Raises ValueError if `a` contains NaN (Not a Number) or Inf (Infinity).
See Also
--------
asarray : Create and array.
asanyarray : Similar function which passes through subclasses.
ascontiguousarray : Convert input to a contiguous array.
asfarray : Convert input to a floating point ndarray.
asfortranarray : Convert input to an ndarray with column-major
memory order.
fromiter : Create an array from an iterator.
fromfunction : Construct an array by executing a function on grid
positions.
Examples
--------
Convert a list into an array. If all elements are finite
``asarray_chkfinite`` is identical to ``asarray``.
>>> a = [1, 2]
>>> np.asarray_chkfinite(a, dtype=float)
array([1., 2.])
Raises ValueError if array_like contains Nans or Infs.
>>> a = [1, 2, np.inf]
>>> try:
... np.asarray_chkfinite(a)
... except ValueError:
... print('ValueError')
...
ValueError
"""
a = asarray(a, dtype=dtype, order=order)
if a.dtype.char in typecodes['AllFloat'] and not np.isfinite(a).all():
raise ValueError(
"array must not contain infs or NaNs")
return a
def piecewise(x, condlist, funclist, *args, **kw):
"""
Evaluate a piecewise-defined function.
Given a set of conditions and corresponding functions, evaluate each
function on the input data wherever its condition is true.
Parameters
----------
x : ndarray or scalar
The input domain.
condlist : list of bool arrays or bool scalars
Each boolean array corresponds to a function in `funclist`. Wherever
`condlist[i]` is True, `funclist[i](x)` is used as the output value.
Each boolean array in `condlist` selects a piece of `x`,
and should therefore be of the same shape as `x`.
The length of `condlist` must correspond to that of `funclist`.
If one extra function is given, i.e. if
``len(funclist) == len(condlist) + 1``, then that extra function
is the default value, used wherever all conditions are false.
funclist : list of callables, f(x,*args,**kw), or scalars
Each function is evaluated over `x` wherever its corresponding
condition is True. It should take a 1d array as input and give an 1d
array or a scalar value as output. If, instead of a callable,
a scalar is provided then a constant function (``lambda x: scalar``) is
assumed.
args : tuple, optional
Any further arguments given to `piecewise` are passed to the functions
upon execution, i.e., if called ``piecewise(..., ..., 1, 'a')``, then
each function is called as ``f(x, 1, 'a')``.
kw : dict, optional
Keyword arguments used in calling `piecewise` are passed to the
functions upon execution, i.e., if called
``piecewise(..., ..., alpha=1)``, then each function is called as
``f(x, alpha=1)``.
Returns
-------
out : ndarray
The output is the same shape and type as x and is found by
calling the functions in `funclist` on the appropriate portions of `x`,
as defined by the boolean arrays in `condlist`. Portions not covered
by any condition have a default value of 0.
See Also
--------
choose, select, where
Notes
-----
This is similar to choose or select, except that functions are
evaluated on elements of `x` that satisfy the corresponding condition from
`condlist`.
The result is::
|--
|funclist[0](x[condlist[0]])
out = |funclist[1](x[condlist[1]])
|...
|funclist[n2](x[condlist[n2]])
|--
Examples
--------
Define the sigma function, which is -1 for ``x < 0`` and +1 for ``x >= 0``.
>>> x = np.linspace(-2.5, 2.5, 6)
>>> np.piecewise(x, [x < 0, x >= 0], [-1, 1])
array([-1., -1., -1., 1., 1., 1.])
Define the absolute value, which is ``-x`` for ``x <0`` and ``x`` for
``x >= 0``.
>>> np.piecewise(x, [x < 0, x >= 0], [lambda x: -x, lambda x: x])
array([ 2.5, 1.5, 0.5, 0.5, 1.5, 2.5])
Apply the same function to a scalar value.
>>> y = -2
>>> np.piecewise(y, [y < 0, y >= 0], [lambda x: -x, lambda x: x])
array(2)
"""
x = asanyarray(x)
n2 = len(funclist)
# undocumented: single condition is promoted to a list of one condition
if isscalar(condlist) or (
not isinstance(condlist[0], (list, ndarray)) and x.ndim != 0):
condlist = [condlist]
condlist = array(condlist, dtype=bool)
n = len(condlist)
if n == n2 - 1: # compute the "otherwise" condition.
condelse = ~np.any(condlist, axis=0, keepdims=True)
condlist = np.concatenate([condlist, condelse], axis=0)
n += 1
elif n != n2:
raise ValueError(
"with {} condition(s), either {} or {} functions are expected"
.format(n, n, n+1)
)
y = zeros(x.shape, x.dtype)
for k in range(n):
item = funclist[k]
if not isinstance(item, collections.Callable):
y[condlist[k]] = item
else:
vals = x[condlist[k]]
if vals.size > 0:
y[condlist[k]] = item(vals, *args, **kw)
return y
def select(condlist, choicelist, default=0):
"""
Return an array drawn from elements in choicelist, depending on conditions.
Parameters
----------
condlist : list of bool ndarrays
The list of conditions which determine from which array in `choicelist`
the output elements are taken. When multiple conditions are satisfied,
the first one encountered in `condlist` is used.
choicelist : list of ndarrays
The list of arrays from which the output elements are taken. It has
to be of the same length as `condlist`.
default : scalar, optional
The element inserted in `output` when all conditions evaluate to False.
Returns
-------
output : ndarray
The output at position m is the m-th element of the array in
`choicelist` where the m-th element of the corresponding array in
`condlist` is True.
See Also
--------
where : Return elements from one of two arrays depending on condition.
take, choose, compress, diag, diagonal
Examples
--------
>>> x = np.arange(10)
>>> condlist = [x<3, x>5]
>>> choicelist = [x, x**2]
>>> np.select(condlist, choicelist)
array([ 0, 1, 2, 0, 0, 0, 36, 49, 64, 81])
"""
# Check the size of condlist and choicelist are the same, or abort.
if len(condlist) != len(choicelist):
raise ValueError(
'list of cases must be same length as list of conditions')
# Now that the dtype is known, handle the deprecated select([], []) case
if len(condlist) == 0:
# 2014-02-24, 1.9
warnings.warn("select with an empty condition list is not possible"
"and will be deprecated",
DeprecationWarning, stacklevel=2)
return np.asarray(default)[()]
choicelist = [np.asarray(choice) for choice in choicelist]
choicelist.append(np.asarray(default))
# need to get the result type before broadcasting for correct scalar
# behaviour
dtype = np.result_type(*choicelist)
# Convert conditions to arrays and broadcast conditions and choices
# as the shape is needed for the result. Doing it separately optimizes
# for example when all choices are scalars.
condlist = np.broadcast_arrays(*condlist)
choicelist = np.broadcast_arrays(*choicelist)
# If cond array is not an ndarray in boolean format or scalar bool, abort.
deprecated_ints = False
for i in range(len(condlist)):
cond = condlist[i]
if cond.dtype.type is not np.bool_:
if np.issubdtype(cond.dtype, np.integer):
# A previous implementation accepted int ndarrays accidentally.
# Supported here deliberately, but deprecated.
condlist[i] = condlist[i].astype(bool)
deprecated_ints = True
else:
raise ValueError(
'invalid entry in choicelist: should be boolean ndarray')
if deprecated_ints:
# 2014-02-24, 1.9
msg = "select condlists containing integer ndarrays is deprecated " \
"and will be removed in the future. Use `.astype(bool)` to " \
"convert to bools."
warnings.warn(msg, DeprecationWarning, stacklevel=2)
if choicelist[0].ndim == 0:
# This may be common, so avoid the call.
result_shape = condlist[0].shape
else:
result_shape = np.broadcast_arrays(condlist[0], choicelist[0])[0].shape
result = np.full(result_shape, choicelist[-1], dtype)
# Use np.copyto to burn each choicelist array onto result, using the
# corresponding condlist as a boolean mask. This is done in reverse
# order since the first choice should take precedence.
choicelist = choicelist[-2::-1]
condlist = condlist[::-1]
for choice, cond in zip(choicelist, condlist):
np.copyto(result, choice, where=cond)
return result
def copy(a, order='K'):
"""
Return an array copy of the given object.
Parameters
----------
a : array_like
Input data.
order : {'C', 'F', 'A', 'K'}, optional
Controls the memory layout of the copy. 'C' means C-order,
'F' means F-order, 'A' means 'F' if `a` is Fortran contiguous,
'C' otherwise. 'K' means match the layout of `a` as closely
as possible. (Note that this function and :meth:`ndarray.copy` are very
similar, but have different default values for their order=
arguments.)
Returns
-------
arr : ndarray
Array interpretation of `a`.
Notes
-----
This is equivalent to:
>>> np.array(a, copy=True) #doctest: +SKIP
Examples
--------
Create an array x, with a reference y and a copy z:
>>> x = np.array([1, 2, 3])
>>> y = x
>>> z = np.copy(x)
Note that, when we modify x, y changes, but not z:
>>> x[0] = 10
>>> x[0] == y[0]
True
>>> x[0] == z[0]
False
"""
return array(a, order=order, copy=True)
# Basic operations
def gradient(f, *varargs, **kwargs):
"""
Return the gradient of an N-dimensional array.
The gradient is computed using second order accurate central differences
in the interior points and either first or second order accurate one-sides
(forward or backwards) differences at the boundaries.
The returned gradient hence has the same shape as the input array.
Parameters
----------
f : array_like
An N-dimensional array containing samples of a scalar function.
varargs : list of scalar or array, optional
Spacing between f values. Default unitary spacing for all dimensions.
Spacing can be specified using:
1. single scalar to specify a sample distance for all dimensions.
2. N scalars to specify a constant sample distance for each dimension.
i.e. `dx`, `dy`, `dz`, ...
3. N arrays to specify the coordinates of the values along each
dimension of F. The length of the array must match the size of
the corresponding dimension
4. Any combination of N scalars/arrays with the meaning of 2. and 3.
If `axis` is given, the number of varargs must equal the number of axes.
Default: 1.
edge_order : {1, 2}, optional
Gradient is calculated using N-th order accurate differences
at the boundaries. Default: 1.
.. versionadded:: 1.9.1
axis : None or int or tuple of ints, optional
Gradient is calculated only along the given axis or axes
The default (axis = None) is to calculate the gradient for all the axes
of the input array. axis may be negative, in which case it counts from
the last to the first axis.
.. versionadded:: 1.11.0
Returns
-------
gradient : ndarray or list of ndarray
A set of ndarrays (or a single ndarray if there is only one dimension)
corresponding to the derivatives of f with respect to each dimension.
Each derivative has the same shape as f.
Examples
--------
>>> f = np.array([1, 2, 4, 7, 11, 16], dtype=float)
>>> np.gradient(f)
array([ 1. , 1.5, 2.5, 3.5, 4.5, 5. ])
>>> np.gradient(f, 2)
array([ 0.5 , 0.75, 1.25, 1.75, 2.25, 2.5 ])
Spacing can be also specified with an array that represents the coordinates
of the values F along the dimensions.
For instance a uniform spacing:
>>> x = np.arange(f.size)
>>> np.gradient(f, x)
array([ 1. , 1.5, 2.5, 3.5, 4.5, 5. ])
Or a non uniform one:
>>> x = np.array([0., 1., 1.5, 3.5, 4., 6.], dtype=float)
>>> np.gradient(f, x)
array([ 1. , 3. , 3.5, 6.7, 6.9, 2.5])
For two dimensional arrays, the return will be two arrays ordered by
axis. In this example the first array stands for the gradient in
rows and the second one in columns direction:
>>> np.gradient(np.array([[1, 2, 6], [3, 4, 5]], dtype=float))
[array([[ 2., 2., -1.],
[ 2., 2., -1.]]), array([[ 1. , 2.5, 4. ],
[ 1. , 1. , 1. ]])]
In this example the spacing is also specified:
uniform for axis=0 and non uniform for axis=1
>>> dx = 2.
>>> y = [1., 1.5, 3.5]
>>> np.gradient(np.array([[1, 2, 6], [3, 4, 5]], dtype=float), dx, y)
[array([[ 1. , 1. , -0.5],
[ 1. , 1. , -0.5]]), array([[ 2. , 2. , 2. ],
[ 2. , 1.7, 0.5]])]
It is possible to specify how boundaries are treated using `edge_order`
>>> x = np.array([0, 1, 2, 3, 4])
>>> f = x**2
>>> np.gradient(f, edge_order=1)
array([ 1., 2., 4., 6., 7.])
>>> np.gradient(f, edge_order=2)
array([-0., 2., 4., 6., 8.])
The `axis` keyword can be used to specify a subset of axes of which the
gradient is calculated
>>> np.gradient(np.array([[1, 2, 6], [3, 4, 5]], dtype=float), axis=0)
array([[ 2., 2., -1.],
[ 2., 2., -1.]])
Notes
-----
Assuming that :math:`f\\in C^{3}` (i.e., :math:`f` has at least 3 continuous
derivatives) and let be :math:`h_{*}` a non homogeneous stepsize, the
spacing the finite difference coefficients are computed by minimising
the consistency error :math:`\\eta_{i}`:
.. math::
\\eta_{i} = f_{i}^{\\left(1\\right)} -
\\left[ \\alpha f\\left(x_{i}\\right) +
\\beta f\\left(x_{i} + h_{d}\\right) +
\\gamma f\\left(x_{i}-h_{s}\\right)
\\right]
By substituting :math:`f(x_{i} + h_{d})` and :math:`f(x_{i} - h_{s})`
with their Taylor series expansion, this translates into solving
the following the linear system:
.. math::
\\left\\{
\\begin{array}{r}
\\alpha+\\beta+\\gamma=0 \\\\
-\\beta h_{d}+\\gamma h_{s}=1 \\\\
\\beta h_{d}^{2}+\\gamma h_{s}^{2}=0
\\end{array}
\\right.
The resulting approximation of :math:`f_{i}^{(1)}` is the following:
.. math::
\\hat f_{i}^{(1)} =
\\frac{
h_{s}^{2}f\\left(x_{i} + h_{d}\\right)
+ \\left(h_{d}^{2} - h_{s}^{2}\\right)f\\left(x_{i}\\right)
- h_{d}^{2}f\\left(x_{i}-h_{s}\\right)}
{ h_{s}h_{d}\\left(h_{d} + h_{s}\\right)}
+ \\mathcal{O}\\left(\\frac{h_{d}h_{s}^{2}
+ h_{s}h_{d}^{2}}{h_{d}
+ h_{s}}\\right)
It is worth noting that if :math:`h_{s}=h_{d}`
(i.e., data are evenly spaced)
we find the standard second order approximation:
.. math::
\\hat f_{i}^{(1)}=
\\frac{f\\left(x_{i+1}\\right) - f\\left(x_{i-1}\\right)}{2h}
+ \\mathcal{O}\\left(h^{2}\\right)
With a similar procedure the forward/backward approximations used for
boundaries can be derived.
References
----------
.. [1] Quarteroni A., Sacco R., Saleri F. (2007) Numerical Mathematics
(Texts in Applied Mathematics). New York: Springer.
.. [2] Durran D. R. (1999) Numerical Methods for Wave Equations
in Geophysical Fluid Dynamics. New York: Springer.
.. [3] Fornberg B. (1988) Generation of Finite Difference Formulas on
Arbitrarily Spaced Grids,
Mathematics of Computation 51, no. 184 : 699-706.
`PDF <http://www.ams.org/journals/mcom/1988-51-184/
S0025-5718-1988-0935077-0/S0025-5718-1988-0935077-0.pdf>`_.
"""
f = np.asanyarray(f)
N = f.ndim # number of dimensions
axes = kwargs.pop('axis', None)
if axes is None:
axes = tuple(range(N))
else:
axes = _nx.normalize_axis_tuple(axes, N)
len_axes = len(axes)
n = len(varargs)
if n == 0:
# no spacing argument - use 1 in all axes
dx = [1.0] * len_axes
elif n == 1 and np.ndim(varargs[0]) == 0:
# single scalar for all axes
dx = varargs * len_axes
elif n == len_axes:
# scalar or 1d array for each axis
dx = list(varargs)
for i, distances in enumerate(dx):
if np.ndim(distances) == 0:
continue
elif np.ndim(distances) != 1:
raise ValueError("distances must be either scalars or 1d")
if len(distances) != f.shape[axes[i]]:
raise ValueError("when 1d, distances must match "
"the length of the corresponding dimension")
diffx = np.diff(distances)
# if distances are constant reduce to the scalar case
# since it brings a consistent speedup
if (diffx == diffx[0]).all():
diffx = diffx[0]
dx[i] = diffx
else:
raise TypeError("invalid number of arguments")
edge_order = kwargs.pop('edge_order', 1)
if kwargs:
raise TypeError('"{}" are not valid keyword arguments.'.format(
'", "'.join(kwargs.keys())))
if edge_order > 2:
raise ValueError("'edge_order' greater than 2 not supported")
# use central differences on interior and one-sided differences on the
# endpoints. This preserves second order-accuracy over the full domain.
outvals = []
# create slice objects --- initially all are [:, :, ..., :]
slice1 = [slice(None)]*N
slice2 = [slice(None)]*N
slice3 = [slice(None)]*N
slice4 = [slice(None)]*N
otype = f.dtype
if otype.type is np.datetime64:
# the timedelta dtype with the same unit information
otype = np.dtype(otype.name.replace('datetime', 'timedelta'))
# view as timedelta to allow addition
f = f.view(otype)
elif otype.type is np.timedelta64:
pass
elif np.issubdtype(otype, np.inexact):
pass
else:
# all other types convert to floating point
otype = np.double
for axis, ax_dx in zip(axes, dx):
if f.shape[axis] < edge_order + 1:
raise ValueError(
"Shape of array too small to calculate a numerical gradient, "
"at least (edge_order + 1) elements are required.")
# result allocation
out = np.empty_like(f, dtype=otype)
# spacing for the current axis
uniform_spacing = np.ndim(ax_dx) == 0
# Numerical differentiation: 2nd order interior
slice1[axis] = slice(1, -1)
slice2[axis] = slice(None, -2)
slice3[axis] = slice(1, -1)
slice4[axis] = slice(2, None)
if uniform_spacing:
out[slice1] = (f[slice4] - f[slice2]) / (2. * ax_dx)
else:
dx1 = ax_dx[0:-1]
dx2 = ax_dx[1:]
a = -(dx2)/(dx1 * (dx1 + dx2))
b = (dx2 - dx1) / (dx1 * dx2)
c = dx1 / (dx2 * (dx1 + dx2))
# fix the shape for broadcasting
shape = np.ones(N, dtype=int)
shape[axis] = -1
a.shape = b.shape = c.shape = shape
# 1D equivalent -- out[1:-1] = a * f[:-2] + b * f[1:-1] + c * f[2:]
out[slice1] = a * f[slice2] + b * f[slice3] + c * f[slice4]
# Numerical differentiation: 1st order edges
if edge_order == 1:
slice1[axis] = 0
slice2[axis] = 1
slice3[axis] = 0
dx_0 = ax_dx if uniform_spacing else ax_dx[0]
# 1D equivalent -- out[0] = (f[1] - f[0]) / (x[1] - x[0])
out[slice1] = (f[slice2] - f[slice3]) / dx_0
slice1[axis] = -1
slice2[axis] = -1
slice3[axis] = -2
dx_n = ax_dx if uniform_spacing else ax_dx[-1]
# 1D equivalent -- out[-1] = (f[-1] - f[-2]) / (x[-1] - x[-2])
out[slice1] = (f[slice2] - f[slice3]) / dx_n
# Numerical differentiation: 2nd order edges
else:
slice1[axis] = 0
slice2[axis] = 0
slice3[axis] = 1
slice4[axis] = 2
if uniform_spacing:
a = -1.5 / ax_dx
b = 2. / ax_dx
c = -0.5 / ax_dx
else:
dx1 = ax_dx[0]
dx2 = ax_dx[1]
a = -(2. * dx1 + dx2)/(dx1 * (dx1 + dx2))
b = (dx1 + dx2) / (dx1 * dx2)
c = - dx1 / (dx2 * (dx1 + dx2))
# 1D equivalent -- out[0] = a * f[0] + b * f[1] + c * f[2]
out[slice1] = a * f[slice2] + b * f[slice3] + c * f[slice4]
slice1[axis] = -1
slice2[axis] = -3
slice3[axis] = -2
slice4[axis] = -1
if uniform_spacing:
a = 0.5 / ax_dx
b = -2. / ax_dx
c = 1.5 / ax_dx
else:
dx1 = ax_dx[-2]
dx2 = ax_dx[-1]
a = (dx2) / (dx1 * (dx1 + dx2))
b = - (dx2 + dx1) / (dx1 * dx2)
c = (2. * dx2 + dx1) / (dx2 * (dx1 + dx2))
# 1D equivalent -- out[-1] = a * f[-3] + b * f[-2] + c * f[-1]
out[slice1] = a * f[slice2] + b * f[slice3] + c * f[slice4]
outvals.append(out)
# reset the slice object in this dimension to ":"
slice1[axis] = slice(None)
slice2[axis] = slice(None)
slice3[axis] = slice(None)
slice4[axis] = slice(None)
if len_axes == 1:
return outvals[0]
else:
return outvals
def diff(a, n=1, axis=-1):
"""
Calculate the n-th discrete difference along the given axis.
The first difference is given by ``out[n] = a[n+1] - a[n]`` along
the given axis, higher differences are calculated by using `diff`
recursively.
Parameters
----------
a : array_like
Input array
n : int, optional
The number of times values are differenced. If zero, the input
is returned as-is.
axis : int, optional
The axis along which the difference is taken, default is the
last axis.
Returns
-------
diff : ndarray
The n-th differences. The shape of the output is the same as `a`
except along `axis` where the dimension is smaller by `n`. The
type of the output is the same as the type of the difference
between any two elements of `a`. This is the same as the type of
`a` in most cases. A notable exception is `datetime64`, which
results in a `timedelta64` output array.
See Also
--------
gradient, ediff1d, cumsum
Notes
-----
Type is preserved for boolean arrays, so the result will contain
`False` when consecutive elements are the same and `True` when they
differ.
For unsigned integer arrays, the results will also be unsigned. This
should not be surprising, as the result is consistent with
calculating the difference directly:
>>> u8_arr = np.array([1, 0], dtype=np.uint8)
>>> np.diff(u8_arr)
array([255], dtype=uint8)
>>> u8_arr[1,...] - u8_arr[0,...]
array(255, np.uint8)
If this is not desirable, then the array should be cast to a larger
integer type first:
>>> i16_arr = u8_arr.astype(np.int16)
>>> np.diff(i16_arr)
array([-1], dtype=int16)
Examples
--------
>>> x = np.array([1, 2, 4, 7, 0])
>>> np.diff(x)
array([ 1, 2, 3, -7])
>>> np.diff(x, n=2)
array([ 1, 1, -10])
>>> x = np.array([[1, 3, 6, 10], [0, 5, 6, 8]])
>>> np.diff(x)
array([[2, 3, 4],
[5, 1, 2]])
>>> np.diff(x, axis=0)
array([[-1, 2, 0, -2]])
>>> x = np.arange('1066-10-13', '1066-10-16', dtype=np.datetime64)
>>> np.diff(x)
array([1, 1], dtype='timedelta64[D]')
"""
if n == 0:
return a
if n < 0:
raise ValueError(
"order must be non-negative but got " + repr(n))
a = asanyarray(a)
nd = a.ndim
axis = normalize_axis_index(axis, nd)
slice1 = [slice(None)] * nd
slice2 = [slice(None)] * nd
slice1[axis] = slice(1, None)
slice2[axis] = slice(None, -1)
slice1 = tuple(slice1)
slice2 = tuple(slice2)
op = not_equal if a.dtype == np.bool_ else subtract
for _ in range(n):
a = op(a[slice1], a[slice2])
return a
def interp(x, xp, fp, left=None, right=None, period=None):
"""
One-dimensional linear interpolation.
Returns the one-dimensional piecewise linear interpolant to a function
with given values at discrete data-points.
Parameters
----------
x : array_like
The x-coordinates of the interpolated values.
xp : 1-D sequence of floats
The x-coordinates of the data points, must be increasing if argument
`period` is not specified. Otherwise, `xp` is internally sorted after
normalizing the periodic boundaries with ``xp = xp % period``.
fp : 1-D sequence of float or complex
The y-coordinates of the data points, same length as `xp`.
left : optional float or complex corresponding to fp
Value to return for `x < xp[0]`, default is `fp[0]`.
right : optional float or complex corresponding to fp
Value to return for `x > xp[-1]`, default is `fp[-1]`.
period : None or float, optional
A period for the x-coordinates. This parameter allows the proper
interpolation of angular x-coordinates. Parameters `left` and `right`
are ignored if `period` is specified.
.. versionadded:: 1.10.0
Returns
-------
y : float or complex (corresponding to fp) or ndarray
The interpolated values, same shape as `x`.
Raises
------
ValueError
If `xp` and `fp` have different length
If `xp` or `fp` are not 1-D sequences
If `period == 0`
Notes
-----
Does not check that the x-coordinate sequence `xp` is increasing.
If `xp` is not increasing, the results are nonsense.
A simple check for increasing is::
np.all(np.diff(xp) > 0)
Examples
--------
>>> xp = [1, 2, 3]
>>> fp = [3, 2, 0]
>>> np.interp(2.5, xp, fp)
1.0
>>> np.interp([0, 1, 1.5, 2.72, 3.14], xp, fp)
array([ 3. , 3. , 2.5 , 0.56, 0. ])
>>> UNDEF = -99.0
>>> np.interp(3.14, xp, fp, right=UNDEF)
-99.0
Plot an interpolant to the sine function:
>>> x = np.linspace(0, 2*np.pi, 10)
>>> y = np.sin(x)
>>> xvals = np.linspace(0, 2*np.pi, 50)
>>> yinterp = np.interp(xvals, x, y)
>>> import matplotlib.pyplot as plt
>>> plt.plot(x, y, 'o')
[<matplotlib.lines.Line2D object at 0x...>]
>>> plt.plot(xvals, yinterp, '-x')
[<matplotlib.lines.Line2D object at 0x...>]
>>> plt.show()
Interpolation with periodic x-coordinates:
>>> x = [-180, -170, -185, 185, -10, -5, 0, 365]
>>> xp = [190, -190, 350, -350]
>>> fp = [5, 10, 3, 4]
>>> np.interp(x, xp, fp, period=360)
array([7.5, 5., 8.75, 6.25, 3., 3.25, 3.5, 3.75])
Complex interpolation
>>> x = [1.5, 4.0]
>>> xp = [2,3,5]
>>> fp = [1.0j, 0, 2+3j]
>>> np.interp(x, xp, fp)
array([ 0.+1.j , 1.+1.5j])
"""
fp = np.asarray(fp)
if np.iscomplexobj(fp):
interp_func = compiled_interp_complex
input_dtype = np.complex128
else:
interp_func = compiled_interp
input_dtype = np.float64
if period is None:
if isinstance(x, (float, int, number)):
return interp_func([x], xp, fp, left, right).item()
elif isinstance(x, np.ndarray) and x.ndim == 0:
return interp_func([x], xp, fp, left, right).item()
else:
return interp_func(x, xp, fp, left, right)
else:
if period == 0:
raise ValueError("period must be a non-zero value")
period = abs(period)
left = None
right = None
return_array = True
if isinstance(x, (float, int, number)):
return_array = False
x = [x]
x = np.asarray(x, dtype=np.float64)
xp = np.asarray(xp, dtype=np.float64)
fp = np.asarray(fp, dtype=input_dtype)
if xp.ndim != 1 or fp.ndim != 1:
raise ValueError("Data points must be 1-D sequences")
if xp.shape[0] != fp.shape[0]:
raise ValueError("fp and xp are not of the same length")
# normalizing periodic boundaries
x = x % period
xp = xp % period
asort_xp = np.argsort(xp)
xp = xp[asort_xp]
fp = fp[asort_xp]
xp = np.concatenate((xp[-1:]-period, xp, xp[0:1]+period))
fp = np.concatenate((fp[-1:], fp, fp[0:1]))
if return_array:
return interp_func(x, xp, fp, left, right)
else:
return interp_func(x, xp, fp, left, right).item()
def angle(z, deg=0):
"""
Return the angle of the complex argument.
Parameters
----------
z : array_like
A complex number or sequence of complex numbers.
deg : bool, optional
Return angle in degrees if True, radians if False (default).
Returns
-------
angle : ndarray or scalar
The counterclockwise angle from the positive real axis on
the complex plane, with dtype as numpy.float64.
See Also
--------
arctan2
absolute
Examples
--------
>>> np.angle([1.0, 1.0j, 1+1j]) # in radians
array([ 0. , 1.57079633, 0.78539816])
>>> np.angle(1+1j, deg=True) # in degrees
45.0
"""
if deg:
fact = 180/pi
else:
fact = 1.0
z = asarray(z)
if (issubclass(z.dtype.type, _nx.complexfloating)):
zimag = z.imag
zreal = z.real
else:
zimag = 0
zreal = z
return arctan2(zimag, zreal) * fact
def unwrap(p, discont=pi, axis=-1):
"""
Unwrap by changing deltas between values to 2*pi complement.
Unwrap radian phase `p` by changing absolute jumps greater than
`discont` to their 2*pi complement along the given axis.
Parameters
----------
p : array_like
Input array.
discont : float, optional
Maximum discontinuity between values, default is ``pi``.
axis : int, optional
Axis along which unwrap will operate, default is the last axis.
Returns
-------
out : ndarray
Output array.
See Also
--------
rad2deg, deg2rad
Notes
-----
If the discontinuity in `p` is smaller than ``pi``, but larger than
`discont`, no unwrapping is done because taking the 2*pi complement
would only make the discontinuity larger.
Examples
--------
>>> phase = np.linspace(0, np.pi, num=5)
>>> phase[3:] += np.pi
>>> phase
array([ 0. , 0.78539816, 1.57079633, 5.49778714, 6.28318531])
>>> np.unwrap(phase)
array([ 0. , 0.78539816, 1.57079633, -0.78539816, 0. ])
"""
p = asarray(p)
nd = p.ndim
dd = diff(p, axis=axis)
slice1 = [slice(None, None)]*nd # full slices
slice1[axis] = slice(1, None)
ddmod = mod(dd + pi, 2*pi) - pi
_nx.copyto(ddmod, pi, where=(ddmod == -pi) & (dd > 0))
ph_correct = ddmod - dd
_nx.copyto(ph_correct, 0, where=abs(dd) < discont)
up = array(p, copy=True, dtype='d')
up[slice1] = p[slice1] + ph_correct.cumsum(axis)
return up
def sort_complex(a):
"""
Sort a complex array using the real part first, then the imaginary part.
Parameters
----------
a : array_like
Input array
Returns
-------
out : complex ndarray
Always returns a sorted complex array.
Examples
--------
>>> np.sort_complex([5, 3, 6, 2, 1])
array([ 1.+0.j, 2.+0.j, 3.+0.j, 5.+0.j, 6.+0.j])
>>> np.sort_complex([1 + 2j, 2 - 1j, 3 - 2j, 3 - 3j, 3 + 5j])
array([ 1.+2.j, 2.-1.j, 3.-3.j, 3.-2.j, 3.+5.j])
"""
b = array(a, copy=True)
b.sort()
if not issubclass(b.dtype.type, _nx.complexfloating):
if b.dtype.char in 'bhBH':
return b.astype('F')
elif b.dtype.char == 'g':
return b.astype('G')
else:
return b.astype('D')
else:
return b
def trim_zeros(filt, trim='fb'):
"""
Trim the leading and/or trailing zeros from a 1-D array or sequence.
Parameters
----------
filt : 1-D array or sequence
Input array.
trim : str, optional
A string with 'f' representing trim from front and 'b' to trim from
back. Default is 'fb', trim zeros from both front and back of the
array.
Returns
-------
trimmed : 1-D array or sequence
The result of trimming the input. The input data type is preserved.
Examples
--------
>>> a = np.array((0, 0, 0, 1, 2, 3, 0, 2, 1, 0))
>>> np.trim_zeros(a)
array([1, 2, 3, 0, 2, 1])
>>> np.trim_zeros(a, 'b')
array([0, 0, 0, 1, 2, 3, 0, 2, 1])
The input data type is preserved, list/tuple in means list/tuple out.
>>> np.trim_zeros([0, 1, 2, 0])
[1, 2]
"""
first = 0
trim = trim.upper()
if 'F' in trim:
for i in filt:
if i != 0.:
break
else:
first = first + 1
last = len(filt)
if 'B' in trim:
for i in filt[::-1]:
if i != 0.:
break
else:
last = last - 1
return filt[first:last]
@deprecate
def unique(x):
"""
This function is deprecated. Use numpy.lib.arraysetops.unique()
instead.
"""
try:
tmp = x.flatten()
if tmp.size == 0:
return tmp
tmp.sort()
idx = concatenate(([True], tmp[1:] != tmp[:-1]))
return tmp[idx]
except AttributeError:
items = sorted(set(x))
return asarray(items)
def extract(condition, arr):
"""
Return the elements of an array that satisfy some condition.
This is equivalent to ``np.compress(ravel(condition), ravel(arr))``. If
`condition` is boolean ``np.extract`` is equivalent to ``arr[condition]``.
Note that `place` does the exact opposite of `extract`.
Parameters
----------
condition : array_like
An array whose nonzero or True entries indicate the elements of `arr`
to extract.
arr : array_like
Input array of the same size as `condition`.
Returns
-------
extract : ndarray
Rank 1 array of values from `arr` where `condition` is True.
See Also
--------
take, put, copyto, compress, place
Examples
--------
>>> arr = np.arange(12).reshape((3, 4))
>>> arr
array([[ 0, 1, 2, 3],
[ 4, 5, 6, 7],
[ 8, 9, 10, 11]])
>>> condition = np.mod(arr, 3)==0
>>> condition
array([[ True, False, False, True],
[False, False, True, False],
[False, True, False, False]])
>>> np.extract(condition, arr)
array([0, 3, 6, 9])
If `condition` is boolean:
>>> arr[condition]
array([0, 3, 6, 9])
"""
return _nx.take(ravel(arr), nonzero(ravel(condition))[0])
def place(arr, mask, vals):
"""
Change elements of an array based on conditional and input values.
Similar to ``np.copyto(arr, vals, where=mask)``, the difference is that
`place` uses the first N elements of `vals`, where N is the number of
True values in `mask`, while `copyto` uses the elements where `mask`
is True.
Note that `extract` does the exact opposite of `place`.
Parameters
----------
arr : ndarray
Array to put data into.
mask : array_like
Boolean mask array. Must have the same size as `a`.
vals : 1-D sequence
Values to put into `a`. Only the first N elements are used, where
N is the number of True values in `mask`. If `vals` is smaller
than N, it will be repeated, and if elements of `a` are to be masked,
this sequence must be non-empty.
See Also
--------
copyto, put, take, extract
Examples
--------
>>> arr = np.arange(6).reshape(2, 3)
>>> np.place(arr, arr>2, [44, 55])
>>> arr
array([[ 0, 1, 2],
[44, 55, 44]])
"""
if not isinstance(arr, np.ndarray):
raise TypeError("argument 1 must be numpy.ndarray, "
"not {name}".format(name=type(arr).__name__))
return _insert(arr, mask, vals)
def disp(mesg, device=None, linefeed=True):
"""
Display a message on a device.
Parameters
----------
mesg : str
Message to display.
device : object
Device to write message. If None, defaults to ``sys.stdout`` which is
very similar to ``print``. `device` needs to have ``write()`` and
``flush()`` methods.
linefeed : bool, optional
Option whether to print a line feed or not. Defaults to True.
Raises
------
AttributeError
If `device` does not have a ``write()`` or ``flush()`` method.
Examples
--------
Besides ``sys.stdout``, a file-like object can also be used as it has
both required methods:
>>> from StringIO import StringIO
>>> buf = StringIO()
>>> np.disp('"Display" in a file', device=buf)
>>> buf.getvalue()
'"Display" in a file\\n'
"""
if device is None:
device = sys.stdout
if linefeed:
device.write('%s\n' % mesg)
else:
device.write('%s' % mesg)
device.flush()
return
# See http://docs.scipy.org/doc/numpy/reference/c-api.generalized-ufuncs.html
_DIMENSION_NAME = r'\w+'
_CORE_DIMENSION_LIST = '(?:{0:}(?:,{0:})*)?'.format(_DIMENSION_NAME)
_ARGUMENT = r'\({}\)'.format(_CORE_DIMENSION_LIST)
_ARGUMENT_LIST = '{0:}(?:,{0:})*'.format(_ARGUMENT)
_SIGNATURE = '^{0:}->{0:}$'.format(_ARGUMENT_LIST)
def _parse_gufunc_signature(signature):
"""
Parse string signatures for a generalized universal function.
Arguments
---------
signature : string
Generalized universal function signature, e.g., ``(m,n),(n,p)->(m,p)``
for ``np.matmul``.
Returns
-------
Tuple of input and output core dimensions parsed from the signature, each
of the form List[Tuple[str, ...]].
"""
if not re.match(_SIGNATURE, signature):
raise ValueError(
'not a valid gufunc signature: {}'.format(signature))
return tuple([tuple(re.findall(_DIMENSION_NAME, arg))
for arg in re.findall(_ARGUMENT, arg_list)]
for arg_list in signature.split('->'))
def _update_dim_sizes(dim_sizes, arg, core_dims):
"""
Incrementally check and update core dimension sizes for a single argument.
Arguments
---------
dim_sizes : Dict[str, int]
Sizes of existing core dimensions. Will be updated in-place.
arg : ndarray
Argument to examine.
core_dims : Tuple[str, ...]
Core dimensions for this argument.
"""
if not core_dims:
return
num_core_dims = len(core_dims)
if arg.ndim < num_core_dims:
raise ValueError(
'%d-dimensional argument does not have enough '
'dimensions for all core dimensions %r'
% (arg.ndim, core_dims))
core_shape = arg.shape[-num_core_dims:]
for dim, size in zip(core_dims, core_shape):
if dim in dim_sizes:
if size != dim_sizes[dim]:
raise ValueError(
'inconsistent size for core dimension %r: %r vs %r'
% (dim, size, dim_sizes[dim]))
else:
dim_sizes[dim] = size
def _parse_input_dimensions(args, input_core_dims):
"""
Parse broadcast and core dimensions for vectorize with a signature.
Arguments
---------
args : Tuple[ndarray, ...]
Tuple of input arguments to examine.
input_core_dims : List[Tuple[str, ...]]
List of core dimensions corresponding to each input.
Returns
-------
broadcast_shape : Tuple[int, ...]
Common shape to broadcast all non-core dimensions to.
dim_sizes : Dict[str, int]
Common sizes for named core dimensions.
"""
broadcast_args = []
dim_sizes = {}
for arg, core_dims in zip(args, input_core_dims):
_update_dim_sizes(dim_sizes, arg, core_dims)
ndim = arg.ndim - len(core_dims)
dummy_array = np.lib.stride_tricks.as_strided(0, arg.shape[:ndim])
broadcast_args.append(dummy_array)
broadcast_shape = np.lib.stride_tricks._broadcast_shape(*broadcast_args)
return broadcast_shape, dim_sizes
def _calculate_shapes(broadcast_shape, dim_sizes, list_of_core_dims):
"""Helper for calculating broadcast shapes with core dimensions."""
return [broadcast_shape + tuple(dim_sizes[dim] for dim in core_dims)
for core_dims in list_of_core_dims]
def _create_arrays(broadcast_shape, dim_sizes, list_of_core_dims, dtypes):
"""Helper for creating output arrays in vectorize."""
shapes = _calculate_shapes(broadcast_shape, dim_sizes, list_of_core_dims)
arrays = tuple(np.empty(shape, dtype=dtype)
for shape, dtype in zip(shapes, dtypes))
return arrays
class vectorize(object):
"""
vectorize(pyfunc, otypes=None, doc=None, excluded=None, cache=False,
signature=None)
Generalized function class.
Define a vectorized function which takes a nested sequence of objects or
numpy arrays as inputs and returns an single or tuple of numpy array as
output. The vectorized function evaluates `pyfunc` over successive tuples
of the input arrays like the python map function, except it uses the
broadcasting rules of numpy.
The data type of the output of `vectorized` is determined by calling
the function with the first element of the input. This can be avoided
by specifying the `otypes` argument.
Parameters
----------
pyfunc : callable
A python function or method.
otypes : str or list of dtypes, optional
The output data type. It must be specified as either a string of
typecode characters or a list of data type specifiers. There should
be one data type specifier for each output.
doc : str, optional
The docstring for the function. If `None`, the docstring will be the
``pyfunc.__doc__``.
excluded : set, optional
Set of strings or integers representing the positional or keyword
arguments for which the function will not be vectorized. These will be
passed directly to `pyfunc` unmodified.
.. versionadded:: 1.7.0
cache : bool, optional
If `True`, then cache the first function call that determines the number
of outputs if `otypes` is not provided.
.. versionadded:: 1.7.0
signature : string, optional
Generalized universal function signature, e.g., ``(m,n),(n)->(m)`` for
vectorized matrix-vector multiplication. If provided, ``pyfunc`` will
be called with (and expected to return) arrays with shapes given by the
size of corresponding core dimensions. By default, ``pyfunc`` is
assumed to take scalars as input and output.
.. versionadded:: 1.12.0
Returns
-------
vectorized : callable
Vectorized function.
Examples
--------
>>> def myfunc(a, b):
... "Return a-b if a>b, otherwise return a+b"
... if a > b:
... return a - b
... else:
... return a + b
>>> vfunc = np.vectorize(myfunc)
>>> vfunc([1, 2, 3, 4], 2)
array([3, 4, 1, 2])
The docstring is taken from the input function to `vectorize` unless it
is specified:
>>> vfunc.__doc__
'Return a-b if a>b, otherwise return a+b'
>>> vfunc = np.vectorize(myfunc, doc='Vectorized `myfunc`')
>>> vfunc.__doc__
'Vectorized `myfunc`'
The output type is determined by evaluating the first element of the input,
unless it is specified:
>>> out = vfunc([1, 2, 3, 4], 2)
>>> type(out[0])
<type 'numpy.int32'>
>>> vfunc = np.vectorize(myfunc, otypes=[float])
>>> out = vfunc([1, 2, 3, 4], 2)
>>> type(out[0])
<type 'numpy.float64'>
The `excluded` argument can be used to prevent vectorizing over certain
arguments. This can be useful for array-like arguments of a fixed length
such as the coefficients for a polynomial as in `polyval`:
>>> def mypolyval(p, x):
... _p = list(p)
... res = _p.pop(0)
... while _p:
... res = res*x + _p.pop(0)
... return res
>>> vpolyval = np.vectorize(mypolyval, excluded=['p'])
>>> vpolyval(p=[1, 2, 3], x=[0, 1])
array([3, 6])
Positional arguments may also be excluded by specifying their position:
>>> vpolyval.excluded.add(0)
>>> vpolyval([1, 2, 3], x=[0, 1])
array([3, 6])
The `signature` argument allows for vectorizing functions that act on
non-scalar arrays of fixed length. For example, you can use it for a
vectorized calculation of Pearson correlation coefficient and its p-value:
>>> import scipy.stats
>>> pearsonr = np.vectorize(scipy.stats.pearsonr,
... signature='(n),(n)->(),()')
>>> pearsonr([[0, 1, 2, 3]], [[1, 2, 3, 4], [4, 3, 2, 1]])
(array([ 1., -1.]), array([ 0., 0.]))
Or for a vectorized convolution:
>>> convolve = np.vectorize(np.convolve, signature='(n),(m)->(k)')
>>> convolve(np.eye(4), [1, 2, 1])
array([[ 1., 2., 1., 0., 0., 0.],
[ 0., 1., 2., 1., 0., 0.],
[ 0., 0., 1., 2., 1., 0.],
[ 0., 0., 0., 1., 2., 1.]])
See Also
--------
frompyfunc : Takes an arbitrary Python function and returns a ufunc
Notes
-----
The `vectorize` function is provided primarily for convenience, not for
performance. The implementation is essentially a for loop.
If `otypes` is not specified, then a call to the function with the
first argument will be used to determine the number of outputs. The
results of this call will be cached if `cache` is `True` to prevent
calling the function twice. However, to implement the cache, the
original function must be wrapped which will slow down subsequent
calls, so only do this if your function is expensive.
The new keyword argument interface and `excluded` argument support
further degrades performance.
References
----------
.. [1] NumPy Reference, section `Generalized Universal Function API
<http://docs.scipy.org/doc/numpy/reference/c-api.generalized-ufuncs.html>`_.
"""
def __init__(self, pyfunc, otypes=None, doc=None, excluded=None,
cache=False, signature=None):
self.pyfunc = pyfunc
self.cache = cache
self.signature = signature
self._ufunc = None # Caching to improve default performance
if doc is None:
self.__doc__ = pyfunc.__doc__
else:
self.__doc__ = doc
if isinstance(otypes, str):
for char in otypes:
if char not in typecodes['All']:
raise ValueError("Invalid otype specified: %s" % (char,))
elif iterable(otypes):
otypes = ''.join([_nx.dtype(x).char for x in otypes])
elif otypes is not None:
raise ValueError("Invalid otype specification")
self.otypes = otypes
# Excluded variable support
if excluded is None:
excluded = set()
self.excluded = set(excluded)
if signature is not None:
self._in_and_out_core_dims = _parse_gufunc_signature(signature)
else:
self._in_and_out_core_dims = None
def __call__(self, *args, **kwargs):
"""
Return arrays with the results of `pyfunc` broadcast (vectorized) over
`args` and `kwargs` not in `excluded`.
"""
excluded = self.excluded
if not kwargs and not excluded:
func = self.pyfunc
vargs = args
else:
# The wrapper accepts only positional arguments: we use `names` and
# `inds` to mutate `the_args` and `kwargs` to pass to the original
# function.
nargs = len(args)
names = [_n for _n in kwargs if _n not in excluded]
inds = [_i for _i in range(nargs) if _i not in excluded]
the_args = list(args)
def func(*vargs):
for _n, _i in enumerate(inds):
the_args[_i] = vargs[_n]
kwargs.update(zip(names, vargs[len(inds):]))
return self.pyfunc(*the_args, **kwargs)
vargs = [args[_i] for _i in inds]
vargs.extend([kwargs[_n] for _n in names])
return self._vectorize_call(func=func, args=vargs)
def _get_ufunc_and_otypes(self, func, args):
"""Return (ufunc, otypes)."""
# frompyfunc will fail if args is empty
if not args:
raise ValueError('args can not be empty')
if self.otypes is not None:
otypes = self.otypes
nout = len(otypes)
# Note logic here: We only *use* self._ufunc if func is self.pyfunc
# even though we set self._ufunc regardless.
if func is self.pyfunc and self._ufunc is not None:
ufunc = self._ufunc
else:
ufunc = self._ufunc = frompyfunc(func, len(args), nout)
else:
# Get number of outputs and output types by calling the function on
# the first entries of args. We also cache the result to prevent
# the subsequent call when the ufunc is evaluated.
# Assumes that ufunc first evaluates the 0th elements in the input
# arrays (the input values are not checked to ensure this)
args = [asarray(arg) for arg in args]
if builtins.any(arg.size == 0 for arg in args):
raise ValueError('cannot call `vectorize` on size 0 inputs '
'unless `otypes` is set')
inputs = [arg.flat[0] for arg in args]
outputs = func(*inputs)
# Performance note: profiling indicates that -- for simple
# functions at least -- this wrapping can almost double the
# execution time.
# Hence we make it optional.
if self.cache:
_cache = [outputs]
def _func(*vargs):
if _cache:
return _cache.pop()
else:
return func(*vargs)
else:
_func = func
if isinstance(outputs, tuple):
nout = len(outputs)
else:
nout = 1
outputs = (outputs,)
otypes = ''.join([asarray(outputs[_k]).dtype.char
for _k in range(nout)])
# Performance note: profiling indicates that creating the ufunc is
# not a significant cost compared with wrapping so it seems not
# worth trying to cache this.
ufunc = frompyfunc(_func, len(args), nout)
return ufunc, otypes
def _vectorize_call(self, func, args):
"""Vectorized call to `func` over positional `args`."""
if self.signature is not None:
res = self._vectorize_call_with_signature(func, args)
elif not args:
res = func()
else:
ufunc, otypes = self._get_ufunc_and_otypes(func=func, args=args)
# Convert args to object arrays first
inputs = [array(a, copy=False, subok=True, dtype=object)
for a in args]
outputs = ufunc(*inputs)
if ufunc.nout == 1:
res = array(outputs, copy=False, subok=True, dtype=otypes[0])
else:
res = tuple([array(x, copy=False, subok=True, dtype=t)
for x, t in zip(outputs, otypes)])
return res
def _vectorize_call_with_signature(self, func, args):
"""Vectorized call over positional arguments with a signature."""
input_core_dims, output_core_dims = self._in_and_out_core_dims
if len(args) != len(input_core_dims):
raise TypeError('wrong number of positional arguments: '
'expected %r, got %r'
% (len(input_core_dims), len(args)))
args = tuple(asanyarray(arg) for arg in args)
broadcast_shape, dim_sizes = _parse_input_dimensions(
args, input_core_dims)
input_shapes = _calculate_shapes(broadcast_shape, dim_sizes,
input_core_dims)
args = [np.broadcast_to(arg, shape, subok=True)
for arg, shape in zip(args, input_shapes)]
outputs = None
otypes = self.otypes
nout = len(output_core_dims)
for index in np.ndindex(*broadcast_shape):
results = func(*(arg[index] for arg in args))
n_results = len(results) if isinstance(results, tuple) else 1
if nout != n_results:
raise ValueError(
'wrong number of outputs from pyfunc: expected %r, got %r'
% (nout, n_results))
if nout == 1:
results = (results,)
if outputs is None:
for result, core_dims in zip(results, output_core_dims):
_update_dim_sizes(dim_sizes, result, core_dims)
if otypes is None:
otypes = [asarray(result).dtype for result in results]
outputs = _create_arrays(broadcast_shape, dim_sizes,
output_core_dims, otypes)
for output, result in zip(outputs, results):
output[index] = result
if outputs is None:
# did not call the function even once
if otypes is None:
raise ValueError('cannot call `vectorize` on size 0 inputs '
'unless `otypes` is set')
if builtins.any(dim not in dim_sizes
for dims in output_core_dims
for dim in dims):
raise ValueError('cannot call `vectorize` with a signature '
'including new output dimensions on size 0 '
'inputs')
outputs = _create_arrays(broadcast_shape, dim_sizes,
output_core_dims, otypes)
return outputs[0] if nout == 1 else outputs
def cov(m, y=None, rowvar=True, bias=False, ddof=None, fweights=None,
aweights=None):
"""
Estimate a covariance matrix, given data and weights.
Covariance indicates the level to which two variables vary together.
If we examine N-dimensional samples, :math:`X = [x_1, x_2, ... x_N]^T`,
then the covariance matrix element :math:`C_{ij}` is the covariance of
:math:`x_i` and :math:`x_j`. The element :math:`C_{ii}` is the variance
of :math:`x_i`.
See the notes for an outline of the algorithm.
Parameters
----------
m : array_like
A 1-D or 2-D array containing multiple variables and observations.
Each row of `m` represents a variable, and each column a single
observation of all those variables. Also see `rowvar` below.
y : array_like, optional
An additional set of variables and observations. `y` has the same form
as that of `m`.
rowvar : bool, optional
If `rowvar` is True (default), then each row represents a
variable, with observations in the columns. Otherwise, the relationship
is transposed: each column represents a variable, while the rows
contain observations.
bias : bool, optional
Default normalization (False) is by ``(N - 1)``, where ``N`` is the
number of observations given (unbiased estimate). If `bias` is True,
then normalization is by ``N``. These values can be overridden by using
the keyword ``ddof`` in numpy versions >= 1.5.
ddof : int, optional
If not ``None`` the default value implied by `bias` is overridden.
Note that ``ddof=1`` will return the unbiased estimate, even if both
`fweights` and `aweights` are specified, and ``ddof=0`` will return
the simple average. See the notes for the details. The default value
is ``None``.
.. versionadded:: 1.5
fweights : array_like, int, optional
1-D array of integer freguency weights; the number of times each
observation vector should be repeated.
.. versionadded:: 1.10
aweights : array_like, optional
1-D array of observation vector weights. These relative weights are
typically large for observations considered "important" and smaller for
observations considered less "important". If ``ddof=0`` the array of
weights can be used to assign probabilities to observation vectors.
.. versionadded:: 1.10
Returns
-------
out : ndarray
The covariance matrix of the variables.
See Also
--------
corrcoef : Normalized covariance matrix
Notes
-----
Assume that the observations are in the columns of the observation
array `m` and let ``f = fweights`` and ``a = aweights`` for brevity. The
steps to compute the weighted covariance are as follows::
>>> w = f * a
>>> v1 = np.sum(w)
>>> v2 = np.sum(w * a)
>>> m -= np.sum(m * w, axis=1, keepdims=True) / v1
>>> cov = np.dot(m * w, m.T) * v1 / (v1**2 - ddof * v2)
Note that when ``a == 1``, the normalization factor
``v1 / (v1**2 - ddof * v2)`` goes over to ``1 / (np.sum(f) - ddof)``
as it should.
Examples
--------
Consider two variables, :math:`x_0` and :math:`x_1`, which
correlate perfectly, but in opposite directions:
>>> x = np.array([[0, 2], [1, 1], [2, 0]]).T
>>> x
array([[0, 1, 2],
[2, 1, 0]])
Note how :math:`x_0` increases while :math:`x_1` decreases. The covariance
matrix shows this clearly:
>>> np.cov(x)
array([[ 1., -1.],
[-1., 1.]])
Note that element :math:`C_{0,1}`, which shows the correlation between
:math:`x_0` and :math:`x_1`, is negative.
Further, note how `x` and `y` are combined:
>>> x = [-2.1, -1, 4.3]
>>> y = [3, 1.1, 0.12]
>>> X = np.stack((x, y), axis=0)
>>> print(np.cov(X))
[[ 11.71 -4.286 ]
[ -4.286 2.14413333]]
>>> print(np.cov(x, y))
[[ 11.71 -4.286 ]
[ -4.286 2.14413333]]
>>> print(np.cov(x))
11.71
"""
# Check inputs
if ddof is not None and ddof != int(ddof):
raise ValueError(
"ddof must be integer")
# Handles complex arrays too
m = np.asarray(m)
if m.ndim > 2:
raise ValueError("m has more than 2 dimensions")
if y is None:
dtype = np.result_type(m, np.float64)
else:
y = np.asarray(y)
if y.ndim > 2:
raise ValueError("y has more than 2 dimensions")
dtype = np.result_type(m, y, np.float64)
X = array(m, ndmin=2, dtype=dtype)
if not rowvar and X.shape[0] != 1:
X = X.T
if X.shape[0] == 0:
return np.array([]).reshape(0, 0)
if y is not None:
y = array(y, copy=False, ndmin=2, dtype=dtype)
if not rowvar and y.shape[0] != 1:
y = y.T
X = np.concatenate((X, y), axis=0)
if ddof is None:
if bias == 0:
ddof = 1
else:
ddof = 0
# Get the product of frequencies and weights
w = None
if fweights is not None:
fweights = np.asarray(fweights, dtype=float)
if not np.all(fweights == np.around(fweights)):
raise TypeError(
"fweights must be integer")
if fweights.ndim > 1:
raise RuntimeError(
"cannot handle multidimensional fweights")
if fweights.shape[0] != X.shape[1]:
raise RuntimeError(
"incompatible numbers of samples and fweights")
if any(fweights < 0):
raise ValueError(
"fweights cannot be negative")
w = fweights
if aweights is not None:
aweights = np.asarray(aweights, dtype=float)
if aweights.ndim > 1:
raise RuntimeError(
"cannot handle multidimensional aweights")
if aweights.shape[0] != X.shape[1]:
raise RuntimeError(
"incompatible numbers of samples and aweights")
if any(aweights < 0):
raise ValueError(
"aweights cannot be negative")
if w is None:
w = aweights
else:
w *= aweights
avg, w_sum = average(X, axis=1, weights=w, returned=True)
w_sum = w_sum[0]
# Determine the normalization
if w is None:
fact = X.shape[1] - ddof
elif ddof == 0:
fact = w_sum
elif aweights is None:
fact = w_sum - ddof
else:
fact = w_sum - ddof*sum(w*aweights)/w_sum
if fact <= 0:
warnings.warn("Degrees of freedom <= 0 for slice",
RuntimeWarning, stacklevel=2)
fact = 0.0
X -= avg[:, None]
if w is None:
X_T = X.T
else:
X_T = (X*w).T
c = dot(X, X_T.conj())
c *= 1. / np.float64(fact)
return c.squeeze()
def corrcoef(x, y=None, rowvar=True, bias=np._NoValue, ddof=np._NoValue):
"""
Return Pearson product-moment correlation coefficients.
Please refer to the documentation for `cov` for more detail. The
relationship between the correlation coefficient matrix, `R`, and the
covariance matrix, `C`, is
.. math:: R_{ij} = \\frac{ C_{ij} } { \\sqrt{ C_{ii} * C_{jj} } }
The values of `R` are between -1 and 1, inclusive.
Parameters
----------
x : array_like
A 1-D or 2-D array containing multiple variables and observations.
Each row of `x` represents a variable, and each column a single
observation of all those variables. Also see `rowvar` below.
y : array_like, optional
An additional set of variables and observations. `y` has the same
shape as `x`.
rowvar : bool, optional
If `rowvar` is True (default), then each row represents a
variable, with observations in the columns. Otherwise, the relationship
is transposed: each column represents a variable, while the rows
contain observations.
bias : _NoValue, optional
Has no effect, do not use.
.. deprecated:: 1.10.0
ddof : _NoValue, optional
Has no effect, do not use.
.. deprecated:: 1.10.0
Returns
-------
R : ndarray
The correlation coefficient matrix of the variables.
See Also
--------
cov : Covariance matrix
Notes
-----
Due to floating point rounding the resulting array may not be Hermitian,
the diagonal elements may not be 1, and the elements may not satisfy the
inequality abs(a) <= 1. The real and imaginary parts are clipped to the
interval [-1, 1] in an attempt to improve on that situation but is not
much help in the complex case.
This function accepts but discards arguments `bias` and `ddof`. This is
for backwards compatibility with previous versions of this function. These
arguments had no effect on the return values of the function and can be
safely ignored in this and previous versions of numpy.
"""
if bias is not np._NoValue or ddof is not np._NoValue:
# 2015-03-15, 1.10
warnings.warn('bias and ddof have no effect and are deprecated',
DeprecationWarning, stacklevel=2)
c = cov(x, y, rowvar)
try:
d = diag(c)
except ValueError:
# scalar covariance
# nan if incorrect value (nan, inf, 0), 1 otherwise
return c / c
stddev = sqrt(d.real)
c /= stddev[:, None]
c /= stddev[None, :]
# Clip real and imaginary parts to [-1, 1]. This does not guarantee
# abs(a[i,j]) <= 1 for complex arrays, but is the best we can do without
# excessive work.
np.clip(c.real, -1, 1, out=c.real)
if np.iscomplexobj(c):
np.clip(c.imag, -1, 1, out=c.imag)
return c
def blackman(M):
"""
Return the Blackman window.
The Blackman window is a taper formed by using the first three
terms of a summation of cosines. It was designed to have close to the
minimal leakage possible. It is close to optimal, only slightly worse
than a Kaiser window.
Parameters
----------
M : int
Number of points in the output window. If zero or less, an empty
array is returned.
Returns
-------
out : ndarray
The window, with the maximum value normalized to one (the value one
appears only if the number of samples is odd).
See Also
--------
bartlett, hamming, hanning, kaiser
Notes
-----
The Blackman window is defined as
.. math:: w(n) = 0.42 - 0.5 \\cos(2\\pi n/M) + 0.08 \\cos(4\\pi n/M)
Most references to the Blackman window come from the signal processing
literature, where it is used as one of many windowing functions for
smoothing values. It is also known as an apodization (which means
"removing the foot", i.e. smoothing discontinuities at the beginning
and end of the sampled signal) or tapering function. It is known as a
"near optimal" tapering function, almost as good (by some measures)
as the kaiser window.
References
----------
Blackman, R.B. and Tukey, J.W., (1958) The measurement of power spectra,
Dover Publications, New York.
Oppenheim, A.V., and R.W. Schafer. Discrete-Time Signal Processing.
Upper Saddle River, NJ: Prentice-Hall, 1999, pp. 468-471.
Examples
--------
>>> np.blackman(12)
array([ -1.38777878e-17, 3.26064346e-02, 1.59903635e-01,
4.14397981e-01, 7.36045180e-01, 9.67046769e-01,
9.67046769e-01, 7.36045180e-01, 4.14397981e-01,
1.59903635e-01, 3.26064346e-02, -1.38777878e-17])
Plot the window and the frequency response:
>>> from numpy.fft import fft, fftshift
>>> window = np.blackman(51)
>>> plt.plot(window)
[<matplotlib.lines.Line2D object at 0x...>]
>>> plt.title("Blackman window")
<matplotlib.text.Text object at 0x...>
>>> plt.ylabel("Amplitude")
<matplotlib.text.Text object at 0x...>
>>> plt.xlabel("Sample")
<matplotlib.text.Text object at 0x...>
>>> plt.show()
>>> plt.figure()
<matplotlib.figure.Figure object at 0x...>
>>> A = fft(window, 2048) / 25.5
>>> mag = np.abs(fftshift(A))
>>> freq = np.linspace(-0.5, 0.5, len(A))
>>> response = 20 * np.log10(mag)
>>> response = np.clip(response, -100, 100)
>>> plt.plot(freq, response)
[<matplotlib.lines.Line2D object at 0x...>]
>>> plt.title("Frequency response of Blackman window")
<matplotlib.text.Text object at 0x...>
>>> plt.ylabel("Magnitude [dB]")
<matplotlib.text.Text object at 0x...>
>>> plt.xlabel("Normalized frequency [cycles per sample]")
<matplotlib.text.Text object at 0x...>
>>> plt.axis('tight')
(-0.5, 0.5, -100.0, ...)
>>> plt.show()
"""
if M < 1:
return array([])
if M == 1:
return ones(1, float)
n = arange(0, M)
return 0.42 - 0.5*cos(2.0*pi*n/(M-1)) + 0.08*cos(4.0*pi*n/(M-1))
def bartlett(M):
"""
Return the Bartlett window.
The Bartlett window is very similar to a triangular window, except
that the end points are at zero. It is often used in signal
processing for tapering a signal, without generating too much
ripple in the frequency domain.
Parameters
----------
M : int
Number of points in the output window. If zero or less, an
empty array is returned.
Returns
-------
out : array
The triangular window, with the maximum value normalized to one
(the value one appears only if the number of samples is odd), with
the first and last samples equal to zero.
See Also
--------
blackman, hamming, hanning, kaiser
Notes
-----
The Bartlett window is defined as
.. math:: w(n) = \\frac{2}{M-1} \\left(
\\frac{M-1}{2} - \\left|n - \\frac{M-1}{2}\\right|
\\right)
Most references to the Bartlett window come from the signal
processing literature, where it is used as one of many windowing
functions for smoothing values. Note that convolution with this
window produces linear interpolation. It is also known as an
apodization (which means"removing the foot", i.e. smoothing
discontinuities at the beginning and end of the sampled signal) or
tapering function. The fourier transform of the Bartlett is the product
of two sinc functions.
Note the excellent discussion in Kanasewich.
References
----------
.. [1] M.S. Bartlett, "Periodogram Analysis and Continuous Spectra",
Biometrika 37, 1-16, 1950.
.. [2] E.R. Kanasewich, "Time Sequence Analysis in Geophysics",
The University of Alberta Press, 1975, pp. 109-110.
.. [3] A.V. Oppenheim and R.W. Schafer, "Discrete-Time Signal
Processing", Prentice-Hall, 1999, pp. 468-471.
.. [4] Wikipedia, "Window function",
http://en.wikipedia.org/wiki/Window_function
.. [5] W.H. Press, B.P. Flannery, S.A. Teukolsky, and W.T. Vetterling,
"Numerical Recipes", Cambridge University Press, 1986, page 429.
Examples
--------
>>> np.bartlett(12)
array([ 0. , 0.18181818, 0.36363636, 0.54545455, 0.72727273,
0.90909091, 0.90909091, 0.72727273, 0.54545455, 0.36363636,
0.18181818, 0. ])
Plot the window and its frequency response (requires SciPy and matplotlib):
>>> from numpy.fft import fft, fftshift
>>> window = np.bartlett(51)
>>> plt.plot(window)
[<matplotlib.lines.Line2D object at 0x...>]
>>> plt.title("Bartlett window")
<matplotlib.text.Text object at 0x...>
>>> plt.ylabel("Amplitude")
<matplotlib.text.Text object at 0x...>
>>> plt.xlabel("Sample")
<matplotlib.text.Text object at 0x...>
>>> plt.show()
>>> plt.figure()
<matplotlib.figure.Figure object at 0x...>
>>> A = fft(window, 2048) / 25.5
>>> mag = np.abs(fftshift(A))
>>> freq = np.linspace(-0.5, 0.5, len(A))
>>> response = 20 * np.log10(mag)
>>> response = np.clip(response, -100, 100)
>>> plt.plot(freq, response)
[<matplotlib.lines.Line2D object at 0x...>]
>>> plt.title("Frequency response of Bartlett window")
<matplotlib.text.Text object at 0x...>
>>> plt.ylabel("Magnitude [dB]")
<matplotlib.text.Text object at 0x...>
>>> plt.xlabel("Normalized frequency [cycles per sample]")
<matplotlib.text.Text object at 0x...>
>>> plt.axis('tight')
(-0.5, 0.5, -100.0, ...)
>>> plt.show()
"""
if M < 1:
return array([])
if M == 1:
return ones(1, float)
n = arange(0, M)
return where(less_equal(n, (M-1)/2.0), 2.0*n/(M-1), 2.0 - 2.0*n/(M-1))
def hanning(M):
"""
Return the Hanning window.
The Hanning window is a taper formed by using a weighted cosine.
Parameters
----------
M : int
Number of points in the output window. If zero or less, an
empty array is returned.
Returns
-------
out : ndarray, shape(M,)
The window, with the maximum value normalized to one (the value
one appears only if `M` is odd).
See Also
--------
bartlett, blackman, hamming, kaiser
Notes
-----
The Hanning window is defined as
.. math:: w(n) = 0.5 - 0.5cos\\left(\\frac{2\\pi{n}}{M-1}\\right)
\\qquad 0 \\leq n \\leq M-1
The Hanning was named for Julius von Hann, an Austrian meteorologist.
It is also known as the Cosine Bell. Some authors prefer that it be
called a Hann window, to help avoid confusion with the very similar
Hamming window.
Most references to the Hanning window come from the signal processing
literature, where it is used as one of many windowing functions for
smoothing values. It is also known as an apodization (which means
"removing the foot", i.e. smoothing discontinuities at the beginning
and end of the sampled signal) or tapering function.
References
----------
.. [1] Blackman, R.B. and Tukey, J.W., (1958) The measurement of power
spectra, Dover Publications, New York.
.. [2] E.R. Kanasewich, "Time Sequence Analysis in Geophysics",
The University of Alberta Press, 1975, pp. 106-108.
.. [3] Wikipedia, "Window function",
http://en.wikipedia.org/wiki/Window_function
.. [4] W.H. Press, B.P. Flannery, S.A. Teukolsky, and W.T. Vetterling,
"Numerical Recipes", Cambridge University Press, 1986, page 425.
Examples
--------
>>> np.hanning(12)
array([ 0. , 0.07937323, 0.29229249, 0.57115742, 0.82743037,
0.97974649, 0.97974649, 0.82743037, 0.57115742, 0.29229249,
0.07937323, 0. ])
Plot the window and its frequency response:
>>> from numpy.fft import fft, fftshift
>>> window = np.hanning(51)
>>> plt.plot(window)
[<matplotlib.lines.Line2D object at 0x...>]
>>> plt.title("Hann window")
<matplotlib.text.Text object at 0x...>
>>> plt.ylabel("Amplitude")
<matplotlib.text.Text object at 0x...>
>>> plt.xlabel("Sample")
<matplotlib.text.Text object at 0x...>
>>> plt.show()
>>> plt.figure()
<matplotlib.figure.Figure object at 0x...>
>>> A = fft(window, 2048) / 25.5
>>> mag = np.abs(fftshift(A))
>>> freq = np.linspace(-0.5, 0.5, len(A))
>>> response = 20 * np.log10(mag)
>>> response = np.clip(response, -100, 100)
>>> plt.plot(freq, response)
[<matplotlib.lines.Line2D object at 0x...>]
>>> plt.title("Frequency response of the Hann window")
<matplotlib.text.Text object at 0x...>
>>> plt.ylabel("Magnitude [dB]")
<matplotlib.text.Text object at 0x...>
>>> plt.xlabel("Normalized frequency [cycles per sample]")
<matplotlib.text.Text object at 0x...>
>>> plt.axis('tight')
(-0.5, 0.5, -100.0, ...)
>>> plt.show()
"""
if M < 1:
return array([])
if M == 1:
return ones(1, float)
n = arange(0, M)
return 0.5 - 0.5*cos(2.0*pi*n/(M-1))
def hamming(M):
"""
Return the Hamming window.
The Hamming window is a taper formed by using a weighted cosine.
Parameters
----------
M : int
Number of points in the output window. If zero or less, an
empty array is returned.
Returns
-------
out : ndarray
The window, with the maximum value normalized to one (the value
one appears only if the number of samples is odd).
See Also
--------
bartlett, blackman, hanning, kaiser
Notes
-----
The Hamming window is defined as
.. math:: w(n) = 0.54 - 0.46cos\\left(\\frac{2\\pi{n}}{M-1}\\right)
\\qquad 0 \\leq n \\leq M-1
The Hamming was named for R. W. Hamming, an associate of J. W. Tukey
and is described in Blackman and Tukey. It was recommended for
smoothing the truncated autocovariance function in the time domain.
Most references to the Hamming window come from the signal processing
literature, where it is used as one of many windowing functions for
smoothing values. It is also known as an apodization (which means
"removing the foot", i.e. smoothing discontinuities at the beginning
and end of the sampled signal) or tapering function.
References
----------
.. [1] Blackman, R.B. and Tukey, J.W., (1958) The measurement of power
spectra, Dover Publications, New York.
.. [2] E.R. Kanasewich, "Time Sequence Analysis in Geophysics", The
University of Alberta Press, 1975, pp. 109-110.
.. [3] Wikipedia, "Window function",
http://en.wikipedia.org/wiki/Window_function
.. [4] W.H. Press, B.P. Flannery, S.A. Teukolsky, and W.T. Vetterling,
"Numerical Recipes", Cambridge University Press, 1986, page 425.
Examples
--------
>>> np.hamming(12)
array([ 0.08 , 0.15302337, 0.34890909, 0.60546483, 0.84123594,
0.98136677, 0.98136677, 0.84123594, 0.60546483, 0.34890909,
0.15302337, 0.08 ])
Plot the window and the frequency response:
>>> from numpy.fft import fft, fftshift
>>> window = np.hamming(51)
>>> plt.plot(window)
[<matplotlib.lines.Line2D object at 0x...>]
>>> plt.title("Hamming window")
<matplotlib.text.Text object at 0x...>
>>> plt.ylabel("Amplitude")
<matplotlib.text.Text object at 0x...>
>>> plt.xlabel("Sample")
<matplotlib.text.Text object at 0x...>
>>> plt.show()
>>> plt.figure()
<matplotlib.figure.Figure object at 0x...>
>>> A = fft(window, 2048) / 25.5
>>> mag = np.abs(fftshift(A))
>>> freq = np.linspace(-0.5, 0.5, len(A))
>>> response = 20 * np.log10(mag)
>>> response = np.clip(response, -100, 100)
>>> plt.plot(freq, response)
[<matplotlib.lines.Line2D object at 0x...>]
>>> plt.title("Frequency response of Hamming window")
<matplotlib.text.Text object at 0x...>
>>> plt.ylabel("Magnitude [dB]")
<matplotlib.text.Text object at 0x...>
>>> plt.xlabel("Normalized frequency [cycles per sample]")
<matplotlib.text.Text object at 0x...>
>>> plt.axis('tight')
(-0.5, 0.5, -100.0, ...)
>>> plt.show()
"""
if M < 1:
return array([])
if M == 1:
return ones(1, float)
n = arange(0, M)
return 0.54 - 0.46*cos(2.0*pi*n/(M-1))
## Code from cephes for i0
_i0A = [
-4.41534164647933937950E-18,
3.33079451882223809783E-17,
-2.43127984654795469359E-16,
1.71539128555513303061E-15,
-1.16853328779934516808E-14,
7.67618549860493561688E-14,
-4.85644678311192946090E-13,
2.95505266312963983461E-12,
-1.72682629144155570723E-11,
9.67580903537323691224E-11,
-5.18979560163526290666E-10,
2.65982372468238665035E-9,
-1.30002500998624804212E-8,
6.04699502254191894932E-8,
-2.67079385394061173391E-7,
1.11738753912010371815E-6,
-4.41673835845875056359E-6,
1.64484480707288970893E-5,
-5.75419501008210370398E-5,
1.88502885095841655729E-4,
-5.76375574538582365885E-4,
1.63947561694133579842E-3,
-4.32430999505057594430E-3,
1.05464603945949983183E-2,
-2.37374148058994688156E-2,
4.93052842396707084878E-2,
-9.49010970480476444210E-2,
1.71620901522208775349E-1,
-3.04682672343198398683E-1,
6.76795274409476084995E-1
]
_i0B = [
-7.23318048787475395456E-18,
-4.83050448594418207126E-18,
4.46562142029675999901E-17,
3.46122286769746109310E-17,
-2.82762398051658348494E-16,
-3.42548561967721913462E-16,
1.77256013305652638360E-15,
3.81168066935262242075E-15,
-9.55484669882830764870E-15,
-4.15056934728722208663E-14,
1.54008621752140982691E-14,
3.85277838274214270114E-13,
7.18012445138366623367E-13,
-1.79417853150680611778E-12,
-1.32158118404477131188E-11,
-3.14991652796324136454E-11,
1.18891471078464383424E-11,
4.94060238822496958910E-10,
3.39623202570838634515E-9,
2.26666899049817806459E-8,
2.04891858946906374183E-7,
2.89137052083475648297E-6,
6.88975834691682398426E-5,
3.36911647825569408990E-3,
8.04490411014108831608E-1
]
def _chbevl(x, vals):
b0 = vals[0]
b1 = 0.0
for i in range(1, len(vals)):
b2 = b1
b1 = b0
b0 = x*b1 - b2 + vals[i]
return 0.5*(b0 - b2)
def _i0_1(x):
return exp(x) * _chbevl(x/2.0-2, _i0A)
def _i0_2(x):
return exp(x) * _chbevl(32.0/x - 2.0, _i0B) / sqrt(x)
def i0(x):
"""
Modified Bessel function of the first kind, order 0.
Usually denoted :math:`I_0`. This function does broadcast, but will *not*
"up-cast" int dtype arguments unless accompanied by at least one float or
complex dtype argument (see Raises below).
Parameters
----------
x : array_like, dtype float or complex
Argument of the Bessel function.
Returns
-------
out : ndarray, shape = x.shape, dtype = x.dtype
The modified Bessel function evaluated at each of the elements of `x`.
Raises
------
TypeError: array cannot be safely cast to required type
If argument consists exclusively of int dtypes.
See Also
--------
scipy.special.iv, scipy.special.ive
Notes
-----
We use the algorithm published by Clenshaw [1]_ and referenced by
Abramowitz and Stegun [2]_, for which the function domain is
partitioned into the two intervals [0,8] and (8,inf), and Chebyshev
polynomial expansions are employed in each interval. Relative error on
the domain [0,30] using IEEE arithmetic is documented [3]_ as having a
peak of 5.8e-16 with an rms of 1.4e-16 (n = 30000).
References
----------
.. [1] C. W. Clenshaw, "Chebyshev series for mathematical functions", in
*National Physical Laboratory Mathematical Tables*, vol. 5, London:
Her Majesty's Stationery Office, 1962.
.. [2] M. Abramowitz and I. A. Stegun, *Handbook of Mathematical
Functions*, 10th printing, New York: Dover, 1964, pp. 379.
http://www.math.sfu.ca/~cbm/aands/page_379.htm
.. [3] http://kobesearch.cpan.org/htdocs/Math-Cephes/Math/Cephes.html
Examples
--------
>>> np.i0([0.])
array(1.0)
>>> np.i0([0., 1. + 2j])
array([ 1.00000000+0.j , 0.18785373+0.64616944j])
"""
x = atleast_1d(x).copy()
y = empty_like(x)
ind = (x < 0)
x[ind] = -x[ind]
ind = (x <= 8.0)
y[ind] = _i0_1(x[ind])
ind2 = ~ind
y[ind2] = _i0_2(x[ind2])
return y.squeeze()
## End of cephes code for i0
def kaiser(M, beta):
"""
Return the Kaiser window.
The Kaiser window is a taper formed by using a Bessel function.
Parameters
----------
M : int
Number of points in the output window. If zero or less, an
empty array is returned.
beta : float
Shape parameter for window.
Returns
-------
out : array
The window, with the maximum value normalized to one (the value
one appears only if the number of samples is odd).
See Also
--------
bartlett, blackman, hamming, hanning
Notes
-----
The Kaiser window is defined as
.. math:: w(n) = I_0\\left( \\beta \\sqrt{1-\\frac{4n^2}{(M-1)^2}}
\\right)/I_0(\\beta)
with
.. math:: \\quad -\\frac{M-1}{2} \\leq n \\leq \\frac{M-1}{2},
where :math:`I_0` is the modified zeroth-order Bessel function.
The Kaiser was named for Jim Kaiser, who discovered a simple
approximation to the DPSS window based on Bessel functions. The Kaiser
window is a very good approximation to the Digital Prolate Spheroidal
Sequence, or Slepian window, which is the transform which maximizes the
energy in the main lobe of the window relative to total energy.
The Kaiser can approximate many other windows by varying the beta
parameter.
==== =======================
beta Window shape
==== =======================
0 Rectangular
5 Similar to a Hamming
6 Similar to a Hanning
8.6 Similar to a Blackman
==== =======================
A beta value of 14 is probably a good starting point. Note that as beta
gets large, the window narrows, and so the number of samples needs to be
large enough to sample the increasingly narrow spike, otherwise NaNs will
get returned.
Most references to the Kaiser window come from the signal processing
literature, where it is used as one of many windowing functions for
smoothing values. It is also known as an apodization (which means
"removing the foot", i.e. smoothing discontinuities at the beginning
and end of the sampled signal) or tapering function.
References
----------
.. [1] J. F. Kaiser, "Digital Filters" - Ch 7 in "Systems analysis by
digital computer", Editors: F.F. Kuo and J.F. Kaiser, p 218-285.
John Wiley and Sons, New York, (1966).
.. [2] E.R. Kanasewich, "Time Sequence Analysis in Geophysics", The
University of Alberta Press, 1975, pp. 177-178.
.. [3] Wikipedia, "Window function",
http://en.wikipedia.org/wiki/Window_function
Examples
--------
>>> np.kaiser(12, 14)
array([ 7.72686684e-06, 3.46009194e-03, 4.65200189e-02,
2.29737120e-01, 5.99885316e-01, 9.45674898e-01,
9.45674898e-01, 5.99885316e-01, 2.29737120e-01,
4.65200189e-02, 3.46009194e-03, 7.72686684e-06])
Plot the window and the frequency response:
>>> from numpy.fft import fft, fftshift
>>> window = np.kaiser(51, 14)
>>> plt.plot(window)
[<matplotlib.lines.Line2D object at 0x...>]
>>> plt.title("Kaiser window")
<matplotlib.text.Text object at 0x...>
>>> plt.ylabel("Amplitude")
<matplotlib.text.Text object at 0x...>
>>> plt.xlabel("Sample")
<matplotlib.text.Text object at 0x...>
>>> plt.show()
>>> plt.figure()
<matplotlib.figure.Figure object at 0x...>
>>> A = fft(window, 2048) / 25.5
>>> mag = np.abs(fftshift(A))
>>> freq = np.linspace(-0.5, 0.5, len(A))
>>> response = 20 * np.log10(mag)
>>> response = np.clip(response, -100, 100)
>>> plt.plot(freq, response)
[<matplotlib.lines.Line2D object at 0x...>]
>>> plt.title("Frequency response of Kaiser window")
<matplotlib.text.Text object at 0x...>
>>> plt.ylabel("Magnitude [dB]")
<matplotlib.text.Text object at 0x...>
>>> plt.xlabel("Normalized frequency [cycles per sample]")
<matplotlib.text.Text object at 0x...>
>>> plt.axis('tight')
(-0.5, 0.5, -100.0, ...)
>>> plt.show()
"""
from numpy.dual import i0
if M == 1:
return np.array([1.])
n = arange(0, M)
alpha = (M-1)/2.0
return i0(beta * sqrt(1-((n-alpha)/alpha)**2.0))/i0(float(beta))
def sinc(x):
"""
Return the sinc function.
The sinc function is :math:`\\sin(\\pi x)/(\\pi x)`.
Parameters
----------
x : ndarray
Array (possibly multi-dimensional) of values for which to to
calculate ``sinc(x)``.
Returns
-------
out : ndarray
``sinc(x)``, which has the same shape as the input.
Notes
-----
``sinc(0)`` is the limit value 1.
The name sinc is short for "sine cardinal" or "sinus cardinalis".
The sinc function is used in various signal processing applications,
including in anti-aliasing, in the construction of a Lanczos resampling
filter, and in interpolation.
For bandlimited interpolation of discrete-time signals, the ideal
interpolation kernel is proportional to the sinc function.
References
----------
.. [1] Weisstein, Eric W. "Sinc Function." From MathWorld--A Wolfram Web
Resource. http://mathworld.wolfram.com/SincFunction.html
.. [2] Wikipedia, "Sinc function",
http://en.wikipedia.org/wiki/Sinc_function
Examples
--------
>>> x = np.linspace(-4, 4, 41)
>>> np.sinc(x)
array([ -3.89804309e-17, -4.92362781e-02, -8.40918587e-02,
-8.90384387e-02, -5.84680802e-02, 3.89804309e-17,
6.68206631e-02, 1.16434881e-01, 1.26137788e-01,
8.50444803e-02, -3.89804309e-17, -1.03943254e-01,
-1.89206682e-01, -2.16236208e-01, -1.55914881e-01,
3.89804309e-17, 2.33872321e-01, 5.04551152e-01,
7.56826729e-01, 9.35489284e-01, 1.00000000e+00,
9.35489284e-01, 7.56826729e-01, 5.04551152e-01,
2.33872321e-01, 3.89804309e-17, -1.55914881e-01,
-2.16236208e-01, -1.89206682e-01, -1.03943254e-01,
-3.89804309e-17, 8.50444803e-02, 1.26137788e-01,
1.16434881e-01, 6.68206631e-02, 3.89804309e-17,
-5.84680802e-02, -8.90384387e-02, -8.40918587e-02,
-4.92362781e-02, -3.89804309e-17])
>>> plt.plot(x, np.sinc(x))
[<matplotlib.lines.Line2D object at 0x...>]
>>> plt.title("Sinc Function")
<matplotlib.text.Text object at 0x...>
>>> plt.ylabel("Amplitude")
<matplotlib.text.Text object at 0x...>
>>> plt.xlabel("X")
<matplotlib.text.Text object at 0x...>
>>> plt.show()
It works in 2-D as well:
>>> x = np.linspace(-4, 4, 401)
>>> xx = np.outer(x, x)
>>> plt.imshow(np.sinc(xx))
<matplotlib.image.AxesImage object at 0x...>
"""
x = np.asanyarray(x)
y = pi * where(x == 0, 1.0e-20, x)
return sin(y)/y
def msort(a):
"""
Return a copy of an array sorted along the first axis.
Parameters
----------
a : array_like
Array to be sorted.
Returns
-------
sorted_array : ndarray
Array of the same type and shape as `a`.
See Also
--------
sort
Notes
-----
``np.msort(a)`` is equivalent to ``np.sort(a, axis=0)``.
"""
b = array(a, subok=True, copy=True)
b.sort(0)
return b
def _ureduce(a, func, **kwargs):
"""
Internal Function.
Call `func` with `a` as first argument swapping the axes to use extended
axis on functions that don't support it natively.
Returns result and a.shape with axis dims set to 1.
Parameters
----------
a : array_like
Input array or object that can be converted to an array.
func : callable
Reduction function capable of receiving a single axis argument.
It is is called with `a` as first argument followed by `kwargs`.
kwargs : keyword arguments
additional keyword arguments to pass to `func`.
Returns
-------
result : tuple
Result of func(a, **kwargs) and a.shape with axis dims set to 1
which can be used to reshape the result to the same shape a ufunc with
keepdims=True would produce.
"""
a = np.asanyarray(a)
axis = kwargs.get('axis', None)
if axis is not None:
keepdim = list(a.shape)
nd = a.ndim
axis = _nx.normalize_axis_tuple(axis, nd)
for ax in axis:
keepdim[ax] = 1
if len(axis) == 1:
kwargs['axis'] = axis[0]
else:
keep = set(range(nd)) - set(axis)
nkeep = len(keep)
# swap axis that should not be reduced to front
for i, s in enumerate(sorted(keep)):
a = a.swapaxes(i, s)
# merge reduced axis
a = a.reshape(a.shape[:nkeep] + (-1,))
kwargs['axis'] = -1
keepdim = tuple(keepdim)
else:
keepdim = (1,) * a.ndim
r = func(a, **kwargs)
return r, keepdim
def median(a, axis=None, out=None, overwrite_input=False, keepdims=False):
"""
Compute the median along the specified axis.
Returns the median of the array elements.
Parameters
----------
a : array_like
Input array or object that can be converted to an array.
axis : {int, sequence of int, None}, optional
Axis or axes along which the medians are computed. The default
is to compute the median along a flattened version of the array.
A sequence of axes is supported since version 1.9.0.
out : ndarray, optional
Alternative output array in which to place the result. It must
have the same shape and buffer length as the expected output,
but the type (of the output) will be cast if necessary.
overwrite_input : bool, optional
If True, then allow use of memory of input array `a` for
calculations. The input array will be modified by the call to
`median`. This will save memory when you do not need to preserve
the contents of the input array. Treat the input as undefined,
but it will probably be fully or partially sorted. Default is
False. If `overwrite_input` is ``True`` and `a` is not already an
`ndarray`, an error will be raised.
keepdims : bool, optional
If this is set to True, the axes which are reduced are left
in the result as dimensions with size one. With this option,
the result will broadcast correctly against the original `arr`.
.. versionadded:: 1.9.0
Returns
-------
median : ndarray
A new array holding the result. If the input contains integers
or floats smaller than ``float64``, then the output data-type is
``np.float64``. Otherwise, the data-type of the output is the
same as that of the input. If `out` is specified, that array is
returned instead.
See Also
--------
mean, percentile
Notes
-----
Given a vector ``V`` of length ``N``, the median of ``V`` is the
middle value of a sorted copy of ``V``, ``V_sorted`` - i
e., ``V_sorted[(N-1)/2]``, when ``N`` is odd, and the average of the
two middle values of ``V_sorted`` when ``N`` is even.
Examples
--------
>>> a = np.array([[10, 7, 4], [3, 2, 1]])
>>> a
array([[10, 7, 4],
[ 3, 2, 1]])
>>> np.median(a)
3.5
>>> np.median(a, axis=0)
array([ 6.5, 4.5, 2.5])
>>> np.median(a, axis=1)
array([ 7., 2.])
>>> m = np.median(a, axis=0)
>>> out = np.zeros_like(m)
>>> np.median(a, axis=0, out=m)
array([ 6.5, 4.5, 2.5])
>>> m
array([ 6.5, 4.5, 2.5])
>>> b = a.copy()
>>> np.median(b, axis=1, overwrite_input=True)
array([ 7., 2.])
>>> assert not np.all(a==b)
>>> b = a.copy()
>>> np.median(b, axis=None, overwrite_input=True)
3.5
>>> assert not np.all(a==b)
"""
r, k = _ureduce(a, func=_median, axis=axis, out=out,
overwrite_input=overwrite_input)
if keepdims:
return r.reshape(k)
else:
return r
def _median(a, axis=None, out=None, overwrite_input=False):
# can't be reasonably be implemented in terms of percentile as we have to
# call mean to not break astropy
a = np.asanyarray(a)
# Set the partition indexes
if axis is None:
sz = a.size
else:
sz = a.shape[axis]
if sz % 2 == 0:
szh = sz // 2
kth = [szh - 1, szh]
else:
kth = [(sz - 1) // 2]
# Check if the array contains any nan's
if np.issubdtype(a.dtype, np.inexact):
kth.append(-1)
if overwrite_input:
if axis is None:
part = a.ravel()
part.partition(kth)
else:
a.partition(kth, axis=axis)
part = a
else:
part = partition(a, kth, axis=axis)
if part.shape == ():
# make 0-D arrays work
return part.item()
if axis is None:
axis = 0
indexer = [slice(None)] * part.ndim
index = part.shape[axis] // 2
if part.shape[axis] % 2 == 1:
# index with slice to allow mean (below) to work
indexer[axis] = slice(index, index+1)
else:
indexer[axis] = slice(index-1, index+1)
# Check if the array contains any nan's
if np.issubdtype(a.dtype, np.inexact) and sz > 0:
# warn and return nans like mean would
rout = mean(part[indexer], axis=axis, out=out)
return np.lib.utils._median_nancheck(part, rout, axis, out)
else:
# if there are no nans
# Use mean in odd and even case to coerce data type
# and check, use out array.
return mean(part[indexer], axis=axis, out=out)
def percentile(a, q, axis=None, out=None,
overwrite_input=False, interpolation='linear', keepdims=False):
"""
Compute the qth percentile of the data along the specified axis.
Returns the qth percentile(s) of the array elements.
Parameters
----------
a : array_like
Input array or object that can be converted to an array.
q : float in range of [0,100] (or sequence of floats)
Percentile to compute, which must be between 0 and 100 inclusive.
axis : {int, sequence of int, None}, optional
Axis or axes along which the percentiles are computed. The
default is to compute the percentile(s) along a flattened
version of the array. A sequence of axes is supported since
version 1.9.0.
out : ndarray, optional
Alternative output array in which to place the result. It must
have the same shape and buffer length as the expected output,
but the type (of the output) will be cast if necessary.
overwrite_input : bool, optional
If True, then allow use of memory of input array `a`
calculations. The input array will be modified by the call to
`percentile`. This will save memory when you do not need to
preserve the contents of the input array. In this case you
should not make any assumptions about the contents of the input
`a` after this function completes -- treat it as undefined.
Default is False. If `a` is not already an array, this parameter
will have no effect as `a` will be converted to an array
internally regardless of the value of this parameter.
interpolation : {'linear', 'lower', 'higher', 'midpoint', 'nearest'}
This optional parameter specifies the interpolation method to
use when the desired quantile lies between two data points
``i < j``:
* linear: ``i + (j - i) * fraction``, where ``fraction``
is the fractional part of the index surrounded by ``i``
and ``j``.
* lower: ``i``.
* higher: ``j``.
* nearest: ``i`` or ``j``, whichever is nearest.
* midpoint: ``(i + j) / 2``.
.. versionadded:: 1.9.0
keepdims : bool, optional
If this is set to True, the axes which are reduced are left in
the result as dimensions with size one. With this option, the
result will broadcast correctly against the original array `a`.
.. versionadded:: 1.9.0
Returns
-------
percentile : scalar or ndarray
If `q` is a single percentile and `axis=None`, then the result
is a scalar. If multiple percentiles are given, first axis of
the result corresponds to the percentiles. The other axes are
the axes that remain after the reduction of `a`. If the input
contains integers or floats smaller than ``float64``, the output
data-type is ``float64``. Otherwise, the output data-type is the
same as that of the input. If `out` is specified, that array is
returned instead.
See Also
--------
mean, median, nanpercentile
Notes
-----
Given a vector ``V`` of length ``N``, the ``q``-th percentile of
``V`` is the value ``q/100`` of the way from the minimum to the
maximum in a sorted copy of ``V``. The values and distances of
the two nearest neighbors as well as the `interpolation` parameter
will determine the percentile if the normalized ranking does not
match the location of ``q`` exactly. This function is the same as
the median if ``q=50``, the same as the minimum if ``q=0`` and the
same as the maximum if ``q=100``.
Examples
--------
>>> a = np.array([[10, 7, 4], [3, 2, 1]])
>>> a
array([[10, 7, 4],
[ 3, 2, 1]])
>>> np.percentile(a, 50)
3.5
>>> np.percentile(a, 50, axis=0)
array([[ 6.5, 4.5, 2.5]])
>>> np.percentile(a, 50, axis=1)
array([ 7., 2.])
>>> np.percentile(a, 50, axis=1, keepdims=True)
array([[ 7.],
[ 2.]])
>>> m = np.percentile(a, 50, axis=0)
>>> out = np.zeros_like(m)
>>> np.percentile(a, 50, axis=0, out=out)
array([[ 6.5, 4.5, 2.5]])
>>> m
array([[ 6.5, 4.5, 2.5]])
>>> b = a.copy()
>>> np.percentile(b, 50, axis=1, overwrite_input=True)
array([ 7., 2.])
>>> assert not np.all(a == b)
"""
q = array(q, dtype=np.float64, copy=True)
r, k = _ureduce(a, func=_percentile, q=q, axis=axis, out=out,
overwrite_input=overwrite_input,
interpolation=interpolation)
if keepdims:
return r.reshape(q.shape + k)
else:
return r
def _percentile(a, q, axis=None, out=None,
overwrite_input=False, interpolation='linear', keepdims=False):
a = asarray(a)
if q.ndim == 0:
# Do not allow 0-d arrays because following code fails for scalar
zerod = True
q = q[None]
else:
zerod = False
# avoid expensive reductions, relevant for arrays with < O(1000) elements
if q.size < 10:
for i in range(q.size):
if q[i] < 0. or q[i] > 100.:
raise ValueError("Percentiles must be in the range [0,100]")
q[i] /= 100.
else:
# faster than any()
if np.count_nonzero(q < 0.) or np.count_nonzero(q > 100.):
raise ValueError("Percentiles must be in the range [0,100]")
q /= 100.
# prepare a for partioning
if overwrite_input:
if axis is None:
ap = a.ravel()
else:
ap = a
else:
if axis is None:
ap = a.flatten()
else:
ap = a.copy()
if axis is None:
axis = 0
Nx = ap.shape[axis]
indices = q * (Nx - 1)
# round fractional indices according to interpolation method
if interpolation == 'lower':
indices = floor(indices).astype(intp)
elif interpolation == 'higher':
indices = ceil(indices).astype(intp)
elif interpolation == 'midpoint':
indices = 0.5 * (floor(indices) + ceil(indices))
elif interpolation == 'nearest':
indices = around(indices).astype(intp)
elif interpolation == 'linear':
pass # keep index as fraction and interpolate
else:
raise ValueError(
"interpolation can only be 'linear', 'lower' 'higher', "
"'midpoint', or 'nearest'")
n = np.array(False, dtype=bool) # check for nan's flag
if indices.dtype == intp: # take the points along axis
# Check if the array contains any nan's
if np.issubdtype(a.dtype, np.inexact):
indices = concatenate((indices, [-1]))
ap.partition(indices, axis=axis)
# ensure axis with qth is first
ap = np.moveaxis(ap, axis, 0)
axis = 0
# Check if the array contains any nan's
if np.issubdtype(a.dtype, np.inexact):
indices = indices[:-1]
n = np.isnan(ap[-1:, ...])
if zerod:
indices = indices[0]
r = take(ap, indices, axis=axis, out=out)
else: # weight the points above and below the indices
indices_below = floor(indices).astype(intp)
indices_above = indices_below + 1
indices_above[indices_above > Nx - 1] = Nx - 1
# Check if the array contains any nan's
if np.issubdtype(a.dtype, np.inexact):
indices_above = concatenate((indices_above, [-1]))
weights_above = indices - indices_below
weights_below = 1.0 - weights_above
weights_shape = [1, ] * ap.ndim
weights_shape[axis] = len(indices)
weights_below.shape = weights_shape
weights_above.shape = weights_shape
ap.partition(concatenate((indices_below, indices_above)), axis=axis)
# ensure axis with qth is first
ap = np.moveaxis(ap, axis, 0)
weights_below = np.moveaxis(weights_below, axis, 0)
weights_above = np.moveaxis(weights_above, axis, 0)
axis = 0
# Check if the array contains any nan's
if np.issubdtype(a.dtype, np.inexact):
indices_above = indices_above[:-1]
n = np.isnan(ap[-1:, ...])
x1 = take(ap, indices_below, axis=axis) * weights_below
x2 = take(ap, indices_above, axis=axis) * weights_above
# ensure axis with qth is first
x1 = np.moveaxis(x1, axis, 0)
x2 = np.moveaxis(x2, axis, 0)
if zerod:
x1 = x1.squeeze(0)
x2 = x2.squeeze(0)
if out is not None:
r = add(x1, x2, out=out)
else:
r = add(x1, x2)
if np.any(n):
warnings.warn("Invalid value encountered in percentile",
RuntimeWarning, stacklevel=3)
if zerod:
if ap.ndim == 1:
if out is not None:
out[...] = a.dtype.type(np.nan)
r = out
else:
r = a.dtype.type(np.nan)
else:
r[..., n.squeeze(0)] = a.dtype.type(np.nan)
else:
if r.ndim == 1:
r[:] = a.dtype.type(np.nan)
else:
r[..., n.repeat(q.size, 0)] = a.dtype.type(np.nan)
return r
def trapz(y, x=None, dx=1.0, axis=-1):
"""
Integrate along the given axis using the composite trapezoidal rule.
Integrate `y` (`x`) along given axis.
Parameters
----------
y : array_like
Input array to integrate.
x : array_like, optional
The sample points corresponding to the `y` values. If `x` is None,
the sample points are assumed to be evenly spaced `dx` apart. The
default is None.
dx : scalar, optional
The spacing between sample points when `x` is None. The default is 1.
axis : int, optional
The axis along which to integrate.
Returns
-------
trapz : float
Definite integral as approximated by trapezoidal rule.
See Also
--------
sum, cumsum
Notes
-----
Image [2]_ illustrates trapezoidal rule -- y-axis locations of points
will be taken from `y` array, by default x-axis distances between
points will be 1.0, alternatively they can be provided with `x` array
or with `dx` scalar. Return value will be equal to combined area under
the red lines.
References
----------
.. [1] Wikipedia page: http://en.wikipedia.org/wiki/Trapezoidal_rule
.. [2] Illustration image:
http://en.wikipedia.org/wiki/File:Composite_trapezoidal_rule_illustration.png
Examples
--------
>>> np.trapz([1,2,3])
4.0
>>> np.trapz([1,2,3], x=[4,6,8])
8.0
>>> np.trapz([1,2,3], dx=2)
8.0
>>> a = np.arange(6).reshape(2, 3)
>>> a
array([[0, 1, 2],
[3, 4, 5]])
>>> np.trapz(a, axis=0)
array([ 1.5, 2.5, 3.5])
>>> np.trapz(a, axis=1)
array([ 2., 8.])
"""
y = asanyarray(y)
if x is None:
d = dx
else:
x = asanyarray(x)
if x.ndim == 1:
d = diff(x)
# reshape to correct shape
shape = [1]*y.ndim
shape[axis] = d.shape[0]
d = d.reshape(shape)
else:
d = diff(x, axis=axis)
nd = y.ndim
slice1 = [slice(None)]*nd
slice2 = [slice(None)]*nd
slice1[axis] = slice(1, None)
slice2[axis] = slice(None, -1)
try:
ret = (d * (y[slice1] + y[slice2]) / 2.0).sum(axis)
except ValueError:
# Operations didn't work, cast to ndarray
d = np.asarray(d)
y = np.asarray(y)
ret = add.reduce(d * (y[slice1]+y[slice2])/2.0, axis)
return ret
#always succeed
def add_newdoc(place, obj, doc):
"""
Adds documentation to obj which is in module place.
If doc is a string add it to obj as a docstring
If doc is a tuple, then the first element is interpreted as
an attribute of obj and the second as the docstring
(method, docstring)
If doc is a list, then each element of the list should be a
sequence of length two --> [(method1, docstring1),
(method2, docstring2), ...]
This routine never raises an error.
This routine cannot modify read-only docstrings, as appear
in new-style classes or built-in functions. Because this
routine never raises an error the caller must check manually
that the docstrings were changed.
"""
try:
new = getattr(__import__(place, globals(), {}, [obj]), obj)
if isinstance(doc, str):
add_docstring(new, doc.strip())
elif isinstance(doc, tuple):
add_docstring(getattr(new, doc[0]), doc[1].strip())
elif isinstance(doc, list):
for val in doc:
add_docstring(getattr(new, val[0]), val[1].strip())
except Exception:
pass
# Based on scitools meshgrid
def meshgrid(*xi, **kwargs):
"""
Return coordinate matrices from coordinate vectors.
Make N-D coordinate arrays for vectorized evaluations of
N-D scalar/vector fields over N-D grids, given
one-dimensional coordinate arrays x1, x2,..., xn.
.. versionchanged:: 1.9
1-D and 0-D cases are allowed.
Parameters
----------
x1, x2,..., xn : array_like
1-D arrays representing the coordinates of a grid.
indexing : {'xy', 'ij'}, optional
Cartesian ('xy', default) or matrix ('ij') indexing of output.
See Notes for more details.
.. versionadded:: 1.7.0
sparse : bool, optional
If True a sparse grid is returned in order to conserve memory.
Default is False.
.. versionadded:: 1.7.0
copy : bool, optional
If False, a view into the original arrays are returned in order to
conserve memory. Default is True. Please note that
``sparse=False, copy=False`` will likely return non-contiguous
arrays. Furthermore, more than one element of a broadcast array
may refer to a single memory location. If you need to write to the
arrays, make copies first.
.. versionadded:: 1.7.0
Returns
-------
X1, X2,..., XN : ndarray
For vectors `x1`, `x2`,..., 'xn' with lengths ``Ni=len(xi)`` ,
return ``(N1, N2, N3,...Nn)`` shaped arrays if indexing='ij'
or ``(N2, N1, N3,...Nn)`` shaped arrays if indexing='xy'
with the elements of `xi` repeated to fill the matrix along
the first dimension for `x1`, the second for `x2` and so on.
Notes
-----
This function supports both indexing conventions through the indexing
keyword argument. Giving the string 'ij' returns a meshgrid with
matrix indexing, while 'xy' returns a meshgrid with Cartesian indexing.
In the 2-D case with inputs of length M and N, the outputs are of shape
(N, M) for 'xy' indexing and (M, N) for 'ij' indexing. In the 3-D case
with inputs of length M, N and P, outputs are of shape (N, M, P) for
'xy' indexing and (M, N, P) for 'ij' indexing. The difference is
illustrated by the following code snippet::
xv, yv = np.meshgrid(x, y, sparse=False, indexing='ij')
for i in range(nx):
for j in range(ny):
# treat xv[i,j], yv[i,j]
xv, yv = np.meshgrid(x, y, sparse=False, indexing='xy')
for i in range(nx):
for j in range(ny):
# treat xv[j,i], yv[j,i]
In the 1-D and 0-D case, the indexing and sparse keywords have no effect.
See Also
--------
index_tricks.mgrid : Construct a multi-dimensional "meshgrid"
using indexing notation.
index_tricks.ogrid : Construct an open multi-dimensional "meshgrid"
using indexing notation.
Examples
--------
>>> nx, ny = (3, 2)
>>> x = np.linspace(0, 1, nx)
>>> y = np.linspace(0, 1, ny)
>>> xv, yv = np.meshgrid(x, y)
>>> xv
array([[ 0. , 0.5, 1. ],
[ 0. , 0.5, 1. ]])
>>> yv
array([[ 0., 0., 0.],
[ 1., 1., 1.]])
>>> xv, yv = np.meshgrid(x, y, sparse=True) # make sparse output arrays
>>> xv
array([[ 0. , 0.5, 1. ]])
>>> yv
array([[ 0.],
[ 1.]])
`meshgrid` is very useful to evaluate functions on a grid.
>>> x = np.arange(-5, 5, 0.1)
>>> y = np.arange(-5, 5, 0.1)
>>> xx, yy = np.meshgrid(x, y, sparse=True)
>>> z = np.sin(xx**2 + yy**2) / (xx**2 + yy**2)
>>> h = plt.contourf(x,y,z)
"""
ndim = len(xi)
copy_ = kwargs.pop('copy', True)
sparse = kwargs.pop('sparse', False)
indexing = kwargs.pop('indexing', 'xy')
if kwargs:
raise TypeError("meshgrid() got an unexpected keyword argument '%s'"
% (list(kwargs)[0],))
if indexing not in ['xy', 'ij']:
raise ValueError(
"Valid values for `indexing` are 'xy' and 'ij'.")
s0 = (1,) * ndim
output = [np.asanyarray(x).reshape(s0[:i] + (-1,) + s0[i + 1:])
for i, x in enumerate(xi)]
if indexing == 'xy' and ndim > 1:
# switch first and second axis
output[0].shape = (1, -1) + s0[2:]
output[1].shape = (-1, 1) + s0[2:]
if not sparse:
# Return the full N-D matrix (not only the 1-D vector)
output = np.broadcast_arrays(*output, subok=True)
if copy_:
output = [x.copy() for x in output]
return output
def delete(arr, obj, axis=None):
"""
Return a new array with sub-arrays along an axis deleted. For a one
dimensional array, this returns those entries not returned by
`arr[obj]`.
Parameters
----------
arr : array_like
Input array.
obj : slice, int or array of ints
Indicate which sub-arrays to remove.
axis : int, optional
The axis along which to delete the subarray defined by `obj`.
If `axis` is None, `obj` is applied to the flattened array.
Returns
-------
out : ndarray
A copy of `arr` with the elements specified by `obj` removed. Note
that `delete` does not occur in-place. If `axis` is None, `out` is
a flattened array.
See Also
--------
insert : Insert elements into an array.
append : Append elements at the end of an array.
Notes
-----
Often it is preferable to use a boolean mask. For example:
>>> mask = np.ones(len(arr), dtype=bool)
>>> mask[[0,2,4]] = False
>>> result = arr[mask,...]
Is equivalent to `np.delete(arr, [0,2,4], axis=0)`, but allows further
use of `mask`.
Examples
--------
>>> arr = np.array([[1,2,3,4], [5,6,7,8], [9,10,11,12]])
>>> arr
array([[ 1, 2, 3, 4],
[ 5, 6, 7, 8],
[ 9, 10, 11, 12]])
>>> np.delete(arr, 1, 0)
array([[ 1, 2, 3, 4],
[ 9, 10, 11, 12]])
>>> np.delete(arr, np.s_[::2], 1)
array([[ 2, 4],
[ 6, 8],
[10, 12]])
>>> np.delete(arr, [1,3,5], None)
array([ 1, 3, 5, 7, 8, 9, 10, 11, 12])
"""
wrap = None
if type(arr) is not ndarray:
try:
wrap = arr.__array_wrap__
except AttributeError:
pass
arr = asarray(arr)
ndim = arr.ndim
arrorder = 'F' if arr.flags.fnc else 'C'
if axis is None:
if ndim != 1:
arr = arr.ravel()
ndim = arr.ndim
axis = -1
if ndim == 0:
# 2013-09-24, 1.9
warnings.warn(
"in the future the special handling of scalars will be removed "
"from delete and raise an error", DeprecationWarning, stacklevel=2)
if wrap:
return wrap(arr)
else:
return arr.copy(order=arrorder)
axis = normalize_axis_index(axis, ndim)
slobj = [slice(None)]*ndim
N = arr.shape[axis]
newshape = list(arr.shape)
if isinstance(obj, slice):
start, stop, step = obj.indices(N)
xr = range(start, stop, step)
numtodel = len(xr)
if numtodel <= 0:
if wrap:
return wrap(arr.copy(order=arrorder))
else:
return arr.copy(order=arrorder)
# Invert if step is negative:
if step < 0:
step = -step
start = xr[-1]
stop = xr[0] + 1
newshape[axis] -= numtodel
new = empty(newshape, arr.dtype, arrorder)
# copy initial chunk
if start == 0:
pass
else:
slobj[axis] = slice(None, start)
new[slobj] = arr[slobj]
# copy end chunck
if stop == N:
pass
else:
slobj[axis] = slice(stop-numtodel, None)
slobj2 = [slice(None)]*ndim
slobj2[axis] = slice(stop, None)
new[slobj] = arr[slobj2]
# copy middle pieces
if step == 1:
pass
else: # use array indexing.
keep = ones(stop-start, dtype=bool)
keep[:stop-start:step] = False
slobj[axis] = slice(start, stop-numtodel)
slobj2 = [slice(None)]*ndim
slobj2[axis] = slice(start, stop)
arr = arr[slobj2]
slobj2[axis] = keep
new[slobj] = arr[slobj2]
if wrap:
return wrap(new)
else:
return new
_obj = obj
obj = np.asarray(obj)
# After removing the special handling of booleans and out of
# bounds values, the conversion to the array can be removed.
if obj.dtype == bool:
warnings.warn("in the future insert will treat boolean arrays and "
"array-likes as boolean index instead of casting it "
"to integer", FutureWarning, stacklevel=2)
obj = obj.astype(intp)
if isinstance(_obj, (int, long, integer)):
# optimization for a single value
obj = obj.item()
if (obj < -N or obj >= N):
raise IndexError(
"index %i is out of bounds for axis %i with "
"size %i" % (obj, axis, N))
if (obj < 0):
obj += N
newshape[axis] -= 1
new = empty(newshape, arr.dtype, arrorder)
slobj[axis] = slice(None, obj)
new[slobj] = arr[slobj]
slobj[axis] = slice(obj, None)
slobj2 = [slice(None)]*ndim
slobj2[axis] = slice(obj+1, None)
new[slobj] = arr[slobj2]
else:
if obj.size == 0 and not isinstance(_obj, np.ndarray):
obj = obj.astype(intp)
if not np.can_cast(obj, intp, 'same_kind'):
# obj.size = 1 special case always failed and would just
# give superfluous warnings.
# 2013-09-24, 1.9
warnings.warn(
"using a non-integer array as obj in delete will result in an "
"error in the future", DeprecationWarning, stacklevel=2)
obj = obj.astype(intp)
keep = ones(N, dtype=bool)
# Test if there are out of bound indices, this is deprecated
inside_bounds = (obj < N) & (obj >= -N)
if not inside_bounds.all():
# 2013-09-24, 1.9
warnings.warn(
"in the future out of bounds indices will raise an error "
"instead of being ignored by `numpy.delete`.",
DeprecationWarning, stacklevel=2)
obj = obj[inside_bounds]
positive_indices = obj >= 0
if not positive_indices.all():
warnings.warn(
"in the future negative indices will not be ignored by "
"`numpy.delete`.", FutureWarning, stacklevel=2)
obj = obj[positive_indices]
keep[obj, ] = False
slobj[axis] = keep
new = arr[slobj]
if wrap:
return wrap(new)
else:
return new
def insert(arr, obj, values, axis=None):
"""
Insert values along the given axis before the given indices.
Parameters
----------
arr : array_like
Input array.
obj : int, slice or sequence of ints
Object that defines the index or indices before which `values` is
inserted.
.. versionadded:: 1.8.0
Support for multiple insertions when `obj` is a single scalar or a
sequence with one element (similar to calling insert multiple
times).
values : array_like
Values to insert into `arr`. If the type of `values` is different
from that of `arr`, `values` is converted to the type of `arr`.
`values` should be shaped so that ``arr[...,obj,...] = values``
is legal.
axis : int, optional
Axis along which to insert `values`. If `axis` is None then `arr`
is flattened first.
Returns
-------
out : ndarray
A copy of `arr` with `values` inserted. Note that `insert`
does not occur in-place: a new array is returned. If
`axis` is None, `out` is a flattened array.
See Also
--------
append : Append elements at the end of an array.
concatenate : Join a sequence of arrays along an existing axis.
delete : Delete elements from an array.
Notes
-----
Note that for higher dimensional inserts `obj=0` behaves very different
from `obj=[0]` just like `arr[:,0,:] = values` is different from
`arr[:,[0],:] = values`.
Examples
--------
>>> a = np.array([[1, 1], [2, 2], [3, 3]])
>>> a
array([[1, 1],
[2, 2],
[3, 3]])
>>> np.insert(a, 1, 5)
array([1, 5, 1, 2, 2, 3, 3])
>>> np.insert(a, 1, 5, axis=1)
array([[1, 5, 1],
[2, 5, 2],
[3, 5, 3]])
Difference between sequence and scalars:
>>> np.insert(a, [1], [[1],[2],[3]], axis=1)
array([[1, 1, 1],
[2, 2, 2],
[3, 3, 3]])
>>> np.array_equal(np.insert(a, 1, [1, 2, 3], axis=1),
... np.insert(a, [1], [[1],[2],[3]], axis=1))
True
>>> b = a.flatten()
>>> b
array([1, 1, 2, 2, 3, 3])
>>> np.insert(b, [2, 2], [5, 6])
array([1, 1, 5, 6, 2, 2, 3, 3])
>>> np.insert(b, slice(2, 4), [5, 6])
array([1, 1, 5, 2, 6, 2, 3, 3])
>>> np.insert(b, [2, 2], [7.13, False]) # type casting
array([1, 1, 7, 0, 2, 2, 3, 3])
>>> x = np.arange(8).reshape(2, 4)
>>> idx = (1, 3)
>>> np.insert(x, idx, 999, axis=1)
array([[ 0, 999, 1, 2, 999, 3],
[ 4, 999, 5, 6, 999, 7]])
"""
wrap = None
if type(arr) is not ndarray:
try:
wrap = arr.__array_wrap__
except AttributeError:
pass
arr = asarray(arr)
ndim = arr.ndim
arrorder = 'F' if arr.flags.fnc else 'C'
if axis is None:
if ndim != 1:
arr = arr.ravel()
ndim = arr.ndim
axis = ndim - 1
elif ndim == 0:
# 2013-09-24, 1.9
warnings.warn(
"in the future the special handling of scalars will be removed "
"from insert and raise an error", DeprecationWarning, stacklevel=2)
arr = arr.copy(order=arrorder)
arr[...] = values
if wrap:
return wrap(arr)
else:
return arr
else:
axis = normalize_axis_index(axis, ndim)
slobj = [slice(None)]*ndim
N = arr.shape[axis]
newshape = list(arr.shape)
if isinstance(obj, slice):
# turn it into a range object
indices = arange(*obj.indices(N), **{'dtype': intp})
else:
# need to copy obj, because indices will be changed in-place
indices = np.array(obj)
if indices.dtype == bool:
# See also delete
warnings.warn(
"in the future insert will treat boolean arrays and "
"array-likes as a boolean index instead of casting it to "
"integer", FutureWarning, stacklevel=2)
indices = indices.astype(intp)
# Code after warning period:
#if obj.ndim != 1:
# raise ValueError('boolean array argument obj to insert '
# 'must be one dimensional')
#indices = np.flatnonzero(obj)
elif indices.ndim > 1:
raise ValueError(
"index array argument obj to insert must be one dimensional "
"or scalar")
if indices.size == 1:
index = indices.item()
if index < -N or index > N:
raise IndexError(
"index %i is out of bounds for axis %i with "
"size %i" % (obj, axis, N))
if (index < 0):
index += N
# There are some object array corner cases here, but we cannot avoid
# that:
values = array(values, copy=False, ndmin=arr.ndim, dtype=arr.dtype)
if indices.ndim == 0:
# broadcasting is very different here, since a[:,0,:] = ... behaves
# very different from a[:,[0],:] = ...! This changes values so that
# it works likes the second case. (here a[:,0:1,:])
values = np.moveaxis(values, 0, axis)
numnew = values.shape[axis]
newshape[axis] += numnew
new = empty(newshape, arr.dtype, arrorder)
slobj[axis] = slice(None, index)
new[slobj] = arr[slobj]
slobj[axis] = slice(index, index+numnew)
new[slobj] = values
slobj[axis] = slice(index+numnew, None)
slobj2 = [slice(None)] * ndim
slobj2[axis] = slice(index, None)
new[slobj] = arr[slobj2]
if wrap:
return wrap(new)
return new
elif indices.size == 0 and not isinstance(obj, np.ndarray):
# Can safely cast the empty list to intp
indices = indices.astype(intp)
if not np.can_cast(indices, intp, 'same_kind'):
# 2013-09-24, 1.9
warnings.warn(
"using a non-integer array as obj in insert will result in an "
"error in the future", DeprecationWarning, stacklevel=2)
indices = indices.astype(intp)
indices[indices < 0] += N
numnew = len(indices)
order = indices.argsort(kind='mergesort') # stable sort
indices[order] += np.arange(numnew)
newshape[axis] += numnew
old_mask = ones(newshape[axis], dtype=bool)
old_mask[indices] = False
new = empty(newshape, arr.dtype, arrorder)
slobj2 = [slice(None)]*ndim
slobj[axis] = indices
slobj2[axis] = old_mask
new[slobj] = values
new[slobj2] = arr
if wrap:
return wrap(new)
return new
def append(arr, values, axis=None):
"""
Append values to the end of an array.
Parameters
----------
arr : array_like
Values are appended to a copy of this array.
values : array_like
These values are appended to a copy of `arr`. It must be of the
correct shape (the same shape as `arr`, excluding `axis`). If
`axis` is not specified, `values` can be any shape and will be
flattened before use.
axis : int, optional
The axis along which `values` are appended. If `axis` is not
given, both `arr` and `values` are flattened before use.
Returns
-------
append : ndarray
A copy of `arr` with `values` appended to `axis`. Note that
`append` does not occur in-place: a new array is allocated and
filled. If `axis` is None, `out` is a flattened array.
See Also
--------
insert : Insert elements into an array.
delete : Delete elements from an array.
Examples
--------
>>> np.append([1, 2, 3], [[4, 5, 6], [7, 8, 9]])
array([1, 2, 3, 4, 5, 6, 7, 8, 9])
When `axis` is specified, `values` must have the correct shape.
>>> np.append([[1, 2, 3], [4, 5, 6]], [[7, 8, 9]], axis=0)
array([[1, 2, 3],
[4, 5, 6],
[7, 8, 9]])
>>> np.append([[1, 2, 3], [4, 5, 6]], [7, 8, 9], axis=0)
Traceback (most recent call last):
...
ValueError: arrays must have same number of dimensions
"""
arr = asanyarray(arr)
if axis is None:
if arr.ndim != 1:
arr = arr.ravel()
values = ravel(values)
axis = arr.ndim-1
return concatenate((arr, values), axis=axis)
|
ryfeus/lambda-packs
|
Spacy/source2.7/numpy/lib/function_base.py
|
Python
|
mit
| 170,032
|
[
"Gaussian"
] |
4be3d8477e6b795391f7a52fe57f9e88b598abeb5d5f76f66bc4127b6d2323f0
|
#
# Copyright 2001 - 2016 Ludek Smid [http://www.ospace.net/]
#
# This file is part of Outer Space.
#
# Outer Space is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2 of the License, or
# (at your option) any later version.
#
# Outer Space is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with Outer Space; if not, write to the Free Software
# Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
#
import json
import random, os, time, copy
import ige
from ige import log
from ige.ClientMngr import Session
from ige.GameMngr import GameMngr as IGEGameMngr
from ige.Index import Index
from ige.Transaction import Transaction
from ige.IDataHolder import IDataHolder
from ige import GameException, SecurityException, CreatePlayerException
import Const
import IPlayer, IUniverse, IGalaxy, ISystem, IWormHole, IPlanet, IFleet
import INature, IAIPlayer, IAIRenegadePlayer, IAIMutantPlayer, IAIPiratePlayer
import GalaxyGenerator
import IAIEDENPlayer, IPiratePlayer
import Rules, Utils
from Rules import Tech
class GameMngr(IGEGameMngr):
#
# Required methods
#
def __init__(self, gameID, config, clientMngr, msgMngr, database, configDir, gameName = None):
IGEGameMngr.__init__(self, gameID, config, clientMngr, msgMngr, database, configDir, gameName)
# register command object
self.registerObject(IUniverse.IUniverse)
self.registerObject(IPlayer.IPlayer)
self.registerObject(IGalaxy.IGalaxy)
self.registerObject(ISystem.ISystem)
self.registerObject(IWormHole.IWormHole)
self.registerObject(IPlanet.IPlanet)
self.registerObject(IFleet.IFleet)
self.registerObject(INature.INature)
self.registerObject(IAIPlayer.IAIPlayer)
self.registerObject(IAIRenegadePlayer.IAIRenegadePlayer)
self.registerObject(IAIMutantPlayer.IAIMutantPlayer)
self.registerObject(IAIPiratePlayer.IAIPiratePlayer)
self.registerObject(IAIEDENPlayer.IAIEDENPlayer)
self.registerObject(IPiratePlayer.IPiratePlayer)
def init(self):
IGEGameMngr.init(self)
def start(self):
IGEGameMngr.start(self)
def stop(self, checkpoint = 1):
IGEGameMngr.stop(self, checkpoint)
def shutdown(self):
IGEGameMngr.shutdown(self)
def reset(self):
# remove all AI accounts and their records in AI list
self.clientMngr.resetAIAccounts()
IGEGameMngr.reset(self)
# save informations
self.db.checkpoint()
def upgrade(self):
IGEGameMngr.upgrade(self)
def createAdmin(self):
obj = IPlayer.IPlayer(self).new(Const.T_PLAYER)
obj.name = 'GameMaster'
return obj
def accountGalaxies(self, login):
""" Returns set of galaxies account is already in. Empty set otherwise """
galaxyIDs = set()
try:
for playerID in self.db[Const.OID_I_LOGIN2OID][login]:
galaxyIDs.add(self.db[playerID].galaxy)
except KeyError:
# fresh account
pass
return galaxyIDs
def registerPlayer(self, login, playerObj, oid = None):
log.debug("Registering login {0}".format(login))
# action
if not oid:
log.debug("Creating object")
oid = self.db.create(playerObj)
else:
self.db.create(playerObj, id = oid)
log.debug("Fixing indexes")
try:
self.db[Const.OID_I_LOGIN2OID][login].append(oid)
except KeyError:
self.db[Const.OID_I_LOGIN2OID][login] = [oid]
playerObj.oid = oid
playerObj.owner = oid
return oid
def createUniverse(self):
universe = self.cmdPool[Const.T_UNIVERSE].new(Const.T_UNIVERSE)
self.db.create(universe, Const.OID_UNIVERSE)
tran = Transaction(self, Const.OID_ADMIN)
# create 'NATURE' player
player = self.cmdPool[Const.T_NATURE].new(Const.T_NATURE)
self.registerPlayer(player.login, player, Const.OID_NATURE)
def getTurnData(self, sid):
IGEGameMngr.getTurnData(self, sid)
universe = self.db[Const.OID_UNIVERSE]
universe.turn += 1
return (
self.db[Const.OID_UNIVERSE].turn,
(
((Const.OID_UNIVERSE,), ('INIT',)),
(universe.galaxies, ('INIT', 'PROD', 'ACTION', 'BATTLE', 'SCAN2', 'FINAL')),
((Const.OID_UNIVERSE,), ('FINAL', 'FINAL2')),
),
None
), None
def turnFinished(self, sid):
IGEGameMngr.turnFinished(self, sid)
self.generateStats()
self.generateGameInfo()
return 1, None
def getActivePositions(self, sid):
session = self.clientMngr.getSession(sid)
result = []
for playerID in self.db[Const.OID_I_LOGIN2OID].get(session.login, []):
player = self.db[playerID]
galaxy = self.db[player.galaxy]
result.append((playerID, galaxy.name, player.type))
return result, None
def getStartingPositions(self, sid):
session = self.clientMngr.getSession(sid)
universe = self.db[Const.OID_UNIVERSE]
badGalaxies = self.accountGalaxies(session.login)
result = []
for galaxyID in set(universe.galaxies).difference(badGalaxies):
galaxy = self.db[galaxyID]
if galaxy.scenario == Const.SCENARIO_SINGLE:
# single player scenarios are off limit :)
continue
if galaxy.startingPos:
result.append((galaxyID, galaxy.name, Const.PLAYER_SELECT_NEWPLAYER))
for playerID in universe.players:
player = self.db[playerID]
if player.galaxy in badGalaxies:
continue
try:
system = self.db[self.db[player.planets[0]].compOf]
except IndexError:
# no planets, definitely not a good starting position
continue
galaxy = self.db[system.compOf]
if galaxy.scenario == Const.SCENARIO_SINGLE:
# single player scenarios are off limit :)
continue
if player.type == Const.T_AIPLAYER and player.planets:
# check if home system is under attack
if system.combatCounter > 0:
continue
result.append((playerID, galaxy.name, Const.PLAYER_SELECT_AIPLAYER))
if player.type == Const.T_AIPIRPLAYER:
result.append((playerID, galaxy.name, Const.PLAYER_SELECT_PIRATE))
return result, None
def singleGamesLimit(self, sid):
session = self.clientMngr.getSession(sid)
noOfSingles = 0
for galaxyID in self.accountGalaxies(session.login):
galaxy = self.db[galaxyID]
if galaxy.scenario == Const.SCENARIO_SINGLE:
noOfSingles += 1
if noOfSingles >= Const.ACCOUNT_SCENARIO_LIMITS[Const.SCENARIO_SINGLE]:
# limit of single galaxies allowed to the account reached
return True
return False
def takeOverAIPlayer(self, sid, playerID):
log.debug('Creating new player in session', sid)
session = self.clientMngr.getSession(sid)
log.debug('Creating new player with CID', session.cid)
universe = self.db[Const.OID_UNIVERSE]
log.debug('Creating transaction')
tran = Transaction(self, session.cid, session)
player = self.db[playerID]
if not (player.type == Const.T_AIPLAYER and player.planets):
raise GameException('No such starting position.')
if player.galaxy in self.accountGalaxies(session.login):
raise GameException('Account already owns player in this galaxy.')
galaxy = self.db[player.galaxy]
if galaxy.scenario == Const.SCENARIO_SINGLE:
raise GameException('AI in single scenario cannot be taken over.')
# create player
log.debug("Morphing AI player", playerID)
player.type = Const.T_PLAYER
self.cmdPool[Const.T_PLAYER].upgrade(tran, player)
self.cmdPool[Const.T_PLAYER].update(tran, player)
# reregister player
self.removePlayer(player.oid)
player.name = session.nick
player.login = session.login
self.registerPlayer(player.login, player, player.oid)
# reset relations
player.diplomacyRels.clear()
# add player to the universe
universe.players.append(playerID)
log.debug('Processing scan phase')
galaxy = tran.db[player.galaxy]
self.cmdPool[Const.T_GALAXY].processSCAN2Phase(tran, galaxy, True)
# save game info
self.generateGameInfo()
return player.oid, None
def takeOverPirate(self, sid, playerID, vipPassword):
# limit this now only to the qark
session = self.clientMngr.getSession(sid)
player = self.db[playerID]
if vipPassword != self.config.vip.password:
raise SecurityException('Wrong VIP password.')
if player.galaxy in self.accountGalaxies(session.login):
raise GameException('Account already owns player in this galaxy.')
if player.galaxy:
galaxy = self.db[player.galaxy]
if galaxy.scenario == Const.SCENARIO_SINGLE:
raise GameException('AI in single scenario cannot be taken over.')
log.debug('Creating pirate in session {0} with CID {1}'.format(sid, session.cid))
universe = self.db[Const.OID_UNIVERSE]
log.debug('Creating transaction')
tran = Transaction(self, session.cid, session)
# create player
#log.debug("Morphing Pirate player", playerID)
log.debug("Player type", player.type)
if player.type != Const.T_AIPIRPLAYER:
raise GameException('No such starting position.')
player.type = Const.T_PIRPLAYER
self.cmdPool[Const.T_PIRPLAYER].upgrade(tran, player)
self.cmdPool[Const.T_PIRPLAYER].update(tran, player)
# reregister player
self.removePlayer(player.oid)
player.fullName = "Pirate %s" % session.nick
player.name = session.nick
player.login = session.login
self.registerPlayer(player.login, player, player.oid)
# add player to the universe
universe.players.append(playerID)
# initial scan
scannerPwr = Rules.techs[9002].scannerPwr
for planetID in player.planets:
planet = self.db[planetID]
system = self.db[planet.compOf]
system.scannerPwrs[player.oid] = scannerPwr
log.debug('Processing scan phase')
galaxy = tran.db[player.galaxy]
self.cmdPool[Const.T_GALAXY].processSCAN2Phase(tran, galaxy, True)
# save game info
self.generateGameInfo()
return player.oid, None
def _createNewPlayer(self, session, galaxyID):
universe = self.db[Const.OID_UNIVERSE]
galaxy = self.db[galaxyID]
if not galaxy.startingPos:
raise GameException('No such starting position.')
if galaxyID in self.accountGalaxies(session.login):
raise GameException('Account already owns player in this galaxy.')
log.debug('Creating new player with CID', session.cid)
player = self.cmdPool[Const.T_PLAYER].new(Const.T_PLAYER)
player.name = session.nick
player.login = session.login
player.timeEnabled = galaxy.timeEnabled
player.galaxy = galaxy.oid
log.debug('Selecting starting point')
planetID = IGalaxy.IGalaxy.getFreeStartingPosition(self.db, galaxy)
player.planets.append(planetID)
log.debug('Creating transaction')
tran = Transaction(self, session.cid, session)
IPlayer.IPlayer.setStartingTechnologies(player)
# register player
log.debug('Registering player for login {0}'.format(session.login))
playerID = self.registerPlayer(session.login, player)
log.debug('Player ID =', playerID)
# singleplayer galaxy needs owner recorded so player can log back there
# also provides access rights to control it
if galaxy.scenario == Const.SCENARIO_SINGLE:
galaxy.owner = playerID
planet = self.db[planetID]
planet.owner = playerID
system = tran.db[planet.compOf]
IPlayer.IPlayer.setStartingShipDesigns(player)
IPlayer.IPlayer.setStartingPlanet(tran, playerID, planet)
IPlayer.IPlayer.setStartingFleet(tran, playerID, system)
# add player to universe
log.debug('Adding player to universe')
universe.players.append(playerID)
# initial scan
system = self.db[planet.compOf]
log.debug('Processing scan phase')
self.cmdPool[Const.T_PLANET].processPRODPhase(tran, planet, None)
# this only works for one planet starting scenarios, it might be imprecise, as it's
# calculated here
# TODO: make proper difference between getting stats, and acting on them, and utilize that
player.effSciPoints = planet.prodSci * (1 + ((Rules.baseGovPwr - planet.storPop) / float(Rules.baseGovPwr) ) / 2.0)
system.scannerPwrs[playerID] = planet.scannerPwr = Rules.startingScannerPwr
self.cmdPool[Const.T_GALAXY].processSCAN2Phase(tran, galaxy, True)
# check if galaxy can be "started" (for purpose of single player games)
self.cmdPool[Const.T_GALAXY].enableTime(tran, galaxy)
# save game info
self.generateGameInfo()
return playerID, None
def createNewPlayer(self, sid, galaxyID):
log.debug('Creating new player in session', sid)
session = self.clientMngr.getSession(sid)
return self._createNewPlayer(session, galaxyID)
def createNewSubscribedPlayer(self, login, galaxyID):
log.debug('Creating new subscribed player using fake session')
player = self.clientMngr[login]
session = Session(None)
session.setAttrs(login, player.nick, player.email)
return self._createNewPlayer(session, galaxyID)
def removePlayer(self, playerID):
log.debug('removePlayer', playerID)
player = self.db[playerID]
# unregister player
self.unregisterPlayer(player)
# remove player from universe
universe = self.db[Const.OID_UNIVERSE]
try:
universe.players.remove(playerID)
except ValueError:
log.warning("Cannot remove player", playerID)
def validateClient(self, session):
# TODO better validation
return 1
#
# Game related methods
#
def generateGameInfo(self):
"""Generate game related info."""
# make directory
try:
os.makedirs(os.path.join(self.configDir, 'website/%s' % self.gameID))
except OSError:
pass
# create structure to save
stats = dict()
universe = self.db[Const.OID_UNIVERSE]
stats["players"] = len(universe.players)
stats["turn"] = "%d:%02d" % (universe.turn / Rules.turnsPerDay, universe.turn % Rules.turnsPerDay)
galaxies = list()
stats["galaxies"] = galaxies
for galaxyID in universe.galaxies:
galaxy = self.db[galaxyID]
galaxyStats = dict(
name = galaxy.name,
url = "http://www.ospace.net:9080/%s/galaxy%d.html" % (self.gameID, galaxyID),
freePositions = len(galaxy.startingPos),
players = 0,
rebels = 0,
age = int((galaxy.galaxyTurn - galaxy.creationTurn) / Rules.turnsPerDay ),
running = galaxy.timeEnabled,
)
for playerID in universe.players:
player = self.db[playerID]
if galaxy.oid != player.galaxy:
continue
if player.type == Const.T_PLAYER:
galaxyStats["players"] += 1
elif player.type == Const.T_AIPLAYER:
galaxyStats["rebels"] += 1
galaxies.append(galaxyStats)
json.dump(stats, open(os.path.join(self.configDir, "website/%s/info.json" % self.gameID), "w"))
def generateStats(self):
""" Generate games statistics """
# gather stats
try:
os.makedirs(os.path.join(self.configDir, 'website/%s' % self.gameID))
except OSError:
pass
stats = {}
galaxies = {}
resolutions = {}
universe = self.db[Const.OID_UNIVERSE]
jsonComma = False
fhjson = open(os.path.join(self.configDir, 'website/%s/json.txt' % (self.gameID)), 'w')
print >>fhjson, '{"turn":"%s",' % universe.turn
for playerID in universe.players:
player = self.db[playerID]
stats[playerID] = player.stats
galaxies[playerID] = player.galaxy
resolution = self.cmdPool[player.type].getResolution(player)
if resolutions.has_key(resolution):
resolutions[resolution] += 1
else:
resolutions[resolution] = 1
for galaxyID in universe.galaxies:
gStats = copy.deepcopy(stats)
for playerID in gStats.keys():
# huh, someone should have commented this
if galaxyID != galaxies[playerID]:
del gStats[playerID]
continue
try:
gStats[playerID].storPop
except AttributeError:
# time has not been enabled yet
del gStats[playerID]
if 0:
# average
storPop = 0
planets = 0
structs = 0
prodProd = 0
prodSci = 0
for playerID in gStats:
pStats = gStats[playerID]
storPop += pStats.storPop
planets += pStats.planets
structs += pStats.structs
prodProd += pStats.prodProd
prodSci += pStats.prodSci
if prodProd == 0: prodProd = 1000
if prodSci == 0: prodSci = 1000
for playerID in gStats:
pStats = gStats[playerID]
pStats.storPop = int(pStats.storPop * 1000 / storPop)
pStats.planets = int(pStats.planets * 1000 / planets)
pStats.structs = int(pStats.structs * 1000 / structs)
pStats.prodProd = int(pStats.prodProd * 1000 / prodProd)
pStats.prodSci = int(pStats.prodSci * 1000 / prodSci)
# generate tables
fh = open(os.path.join(self.configDir, 'website/%s/galaxy%d.html' % (self.gameID, galaxyID)), 'w')
galaxy = self.db[galaxyID]
if galaxy.imperator != Const.OID_NONE:
if self.db[galaxy.imperator].imperator > 1:
imperator = " - Imperator %s" % self.db[galaxy.imperator].name
imperatoroid = self.db[galaxy.imperator].oid
leaderoid = 0
else:
imperator = " - Leader %s" % self.db[galaxy.imperator].name
imperatoroid = 0
leaderoid = self.db[galaxy.imperator].oid
else:
imperator = ""
imperatoroid = 0
leaderoid = 0
print >>fh, statsHeader % (self.gameID, galaxy.name, imperator)
order = self.sortStatsBy(gStats, 'storPop')
self.printJSONStatsTable(fhjson, gStats, order, galaxyID, galaxy.name, imperatoroid, leaderoid, jsonComma)
jsonComma = True
self.printStatsEcoTable(fh, 'Sorted by population', gStats, order)
#order = self.sortStatsBy(gStats, 'systems')
#self.printStatsEcoTable(fh, 'Sorted by number of systems', gStats, order)
order = self.sortStatsBy(gStats, 'planets')
self.printStatsEcoTable(fh, 'Sorted by number of planets', gStats, order)
order = self.sortStatsBy(gStats, 'structs')
self.printStatsEcoTable(fh, 'Sorted by number of structures', gStats, order)
order = self.sortStatsBy(gStats, 'prodProd')
self.printStatsEcoTable(fh, 'Sorted by production', gStats, order)
order = self.sortStatsBy(gStats, 'prodSci')
self.printStatsEcoTable(fh, 'Sorted by science', gStats, order)
order = self.sortStatsBy(gStats, 'fleetPwr')
self.printStatsEcoTable(fh, 'Sorted by military power', gStats, order)
print >>fh, statsFooter
fh.close()
print >>fhjson, '}'
fhjson.close()
#write resolutions of clients in use for statistics tracking
fhres = open(os.path.join(self.configDir, 'website/res.txt'), 'w')
print >>fhres, 'Resoltion: Number of users'
reskeys = resolutions.keys();
reskeys.sort();
for resolution in reskeys:
print >>fhres, '%s: %s' % (resolution, resolutions[resolution])
fhres.close()
def sortStatsBy(self, stats, attr):
keyF = lambda a: getattr(stats[a], attr)
order = sorted(stats.keys(), key=keyF, reverse = True)
return order
def printJSONStatsTable(self, fh, stats, order, galaxyID, galaxyName, imperatoroid, leaderoid, jsonComma):
if jsonComma:
print >> fh, ','
print >> fh, '"%s":{"galaxyname":"%s","imperatorid":"%s","leaderid":"%s","players":' % (galaxyID, galaxyName, imperatoroid, leaderoid)
print >> fh, '{'
print >> fh, '"order":["name","pop","planets","structs","prod","sci","mp"]'
for playerID in order:
print >> fh, ','
needComma = True
stat = stats[playerID]
print >> fh, '"%s":["%s","%s","%s","%s","%s","%s","%s"]' % (playerID, self.db[playerID].name, stat.storPop, stat.planets, stat.structs, stat.prodProd, stat.prodSci, stat.fleetPwr)
print >> fh, '}}'
def printStatsEcoTable(self, fh, title, stats, order):
print >> fh, '<table cellspacing="1" border="0" cellpadding="2" width="100%">'
print >> fh, '<tr>'
print >> fh, '<td class="title" align="center" colspan="8">%s</td>' % title
print >> fh, '</tr>'
print >> fh, '<tr>'
print >> fh, '<td class="title" align="right">#</td>'
print >> fh, '<td class="title" align="left">Player</td>'
print >> fh, '<td class="title" align="right">Population</td>'
print >> fh, '<td class="title" align="right">Planets</td>'
print >> fh, '<td class="title" align="right">Structures</td>'
print >> fh, '<td class="title" align="right">Production</td>'
print >> fh, '<td class="title" align="right">Military pwr</td>'
print >> fh, '<td class="title" align="right">Science</td>'
print >> fh, '</tr>'
print >> fh, '<tr>'
# index
index = 1
print >> fh, '<td align="right" nowrap>'
for playerID in order:
stat = stats[playerID]
if index % 2: print >> fh, '%d.<br>' % index
else: print >> fh, '<font color="#c0c0c0">%d</font>.<br>' % index
index += 1
print >> fh, '</td>'
# name
index = 1
print >> fh, '<td align="left" nowrap>'
for playerID in order:
stat = stats[playerID]
if index % 2: print >> fh, '%s<br>' % self.db[playerID].name
else: print >> fh, '<font color="#c0c0c0">%s</font><br>' % self.db[playerID].name
index += 1
print >> fh, '</td>'
# storPop
index = 1
print >> fh, '<td align="right" nowrap>'
for playerID in order:
stat = stats[playerID]
if index % 2: print >> fh, '%d<br>' % stat.storPop
else: print >> fh, '<font color="#c0c0c0">%d</font><br>' % stat.storPop
index += 1
print >> fh, '</td>'
# planets
index = 1
print >> fh, '<td align="right" nowrap>'
for playerID in order:
stat = stats[playerID]
if index % 2: print >> fh, '%d<br>' % stat.planets
else: print >> fh, '<font color="#c0c0c0">%d</font><br>' % stat.planets
index += 1
print >> fh, '</td>'
# structs
index = 1
print >> fh, '<td align="right" nowrap>'
for playerID in order:
stat = stats[playerID]
if index % 2: print >> fh, '%d<br>' % stat.structs
else: print >> fh, '<font color="#c0c0c0">%d</font><br>' % stat.structs
index += 1
print >> fh, '</td>'
# prodProd
index = 1
print >> fh, '<td align="right" nowrap>'
for playerID in order:
stat = stats[playerID]
if index % 2: print >> fh, '%d<br>' % stat.prodProd
else: print >> fh, '<font color="#c0c0c0">%d</font><br>' % stat.prodProd
index += 1
print >> fh, '</td>'
# fleet
index = 1
print >> fh, '<td align="right" nowrap>'
for playerID in order:
stat = stats[playerID]
if index % 2: print >> fh, '%d<br>' % stat.fleetPwr
else: print >> fh, '<font color="#c0c0c0">%d</font><br>' % stat.fleetPwr
index += 1
# prodSci
index = 1
print >> fh, '<td align="right" nowrap>'
for playerID in order:
stat = stats[playerID]
if index % 2: print >> fh, '%d<br>' % stat.prodSci
else: print >> fh, '<font color="#c0c0c0">%d</font><br>' % stat.prodSci
index += 1
print >> fh, '</td>'
print >> fh, '</tr>'
print >> fh, '</table><br>'
statsHeader = '''\
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">
<html>
<head>
<title>Outer Space Statistics for Game %s</title>
<link rel="STYLESHEET" href="../styles.css" type="text/css">
</head>
<body>
<center>
<h1>Statistics for galaxy %s%s</h1>
<table cellspacing=2 border=0 cellpadding=5 width="80%%" class="main">
<tr>
<td valign="top">
<!-- body start -->
'''
statsFooter = '''\
<!-- body end -->
</td>
</tr>
<tr>
<td class="footer" colspan=2 align="center">© 2001 - %s Ludek Smid</td>
</tr>
</table>
</center>
</body>
</html>''' % time.localtime()[0]
|
ospaceteam/outerspace
|
server/lib/ige/ospace/GameMngr.py
|
Python
|
gpl-2.0
| 26,932
|
[
"Galaxy"
] |
4a226376cb1ada5d3eb63f7c74aa2235909b9a616e04b84d1873bf5841a78fda
|
#!/usr/bin/env python -i
# preceding line should have path for Python on your machine
# mc.py
# Purpose: mimic operation of example/MC/in.mc via Python
# Syntax: mc.py in.mc
# in.mc = LAMMPS input script
from __future__ import print_function
import sys,random,math
# set these parameters
# make sure neigh skin (in in.mc) > 2*deltamove
nloop = 3000
deltaperturb = 0.2
deltamove = 0.1
kT = 0.05
random.seed(27848)
# parse command line
argv = sys.argv
if len(argv) != 2:
print("Syntax: mc.py in.mc")
sys.exit()
infile = sys.argv[1]
from lammps import lammps, LAMMPS_INT, LMP_STYLE_GLOBAL, LMP_VAR_EQUAL
lmp = lammps()
# run infile one line at a time
# just sets up MC problem
lines = open(infile,'r').readlines()
for line in lines: lmp.command(line)
lmp.command("variable e equal pe")
# run 0 to get energy of perfect lattice
# emin = minimum energy
lmp.command("run 0")
natoms = lmp.extract_global("natoms")
emin = lmp.extract_compute("thermo_pe",LMP_STYLE_GLOBAL,LAMMPS_INT) / natoms
lmp.command("variable emin equal $e")
# disorder the system
# estart = initial energy
x = lmp.extract_atom("x")
for i in range(natoms):
x[i][0] += deltaperturb * (2*random.random()-1)
x[i][1] += deltaperturb * (2*random.random()-1)
lmp.command("variable elast equal $e")
lmp.command("thermo_style custom step v_emin v_elast pe")
lmp.command("run 0")
x = lmp.extract_atom("x")
lmp.command("variable elast equal $e")
estart = lmp.extract_compute("thermo_pe", LMP_STYLE_GLOBAL, LAMMPS_INT) / natoms
# loop over Monte Carlo moves
# extract x after every run, in case reneighboring changed ptr in LAMMPS
elast = estart
naccept = 0
for i in range(nloop):
iatom = random.randrange(0,natoms)
x0 = x[iatom][0]
y0 = x[iatom][1]
x[iatom][0] += deltamove * (2*random.random()-1)
x[iatom][1] += deltamove * (2*random.random()-1)
lmp.command("run 1 pre no post no")
x = lmp.extract_atom("x")
e = lmp.extract_compute("thermo_pe", LMP_STYLE_GLOBAL, LAMMPS_INT) / natoms
if e <= elast:
elast = e
lmp.command("variable elast equal $e")
naccept += 1
elif random.random() <= math.exp(natoms*(elast-e)/kT):
elast = e
lmp.command("variable elast equal $e")
naccept += 1
else:
x[iatom][0] = x0
x[iatom][1] = y0
# final energy and stats
lmp.command("variable nbuild equal nbuild")
nbuild = lmp.extract_variable("nbuild", None, LMP_VAR_EQUAL)
lmp.command("run 0")
estop = lmp.extract_compute("thermo_pe", LMP_STYLE_GLOBAL, LAMMPS_INT) / natoms
print("MC stats:")
print(" starting energy =",estart)
print(" final energy =",estop)
print(" minimum energy of perfect lattice =",emin)
print(" accepted MC moves =",naccept)
print(" neighbor list rebuilds =",nbuild)
|
akohlmey/lammps
|
python/examples/mc.py
|
Python
|
gpl-2.0
| 2,730
|
[
"LAMMPS"
] |
3610600e62a28fe77b85f2a76ad78100d94c682fdf6f7b0d31bc0511e551ed48
|
#!/usr/bin/python
#
# Copyright (c) 2009-2019 Emanuel Borsboom. See COPYING.txt for license.
#
# Produce formatted HTML for the tables for the year specified on the
# command-line.
#
# Usage example:
#
# ./year_html 2009 >2009.html
#
import sys
import time
import posix
year = int(sys.argv[1])
print '<html><head><title>Current Atlas Lookup Tables: Juan de Fuca Strait to Strait of Georgia — ' + str(year) + '</title>'
print '''
<style type="text/css" media="all">
body { font-family: sans-serif }
.ca_table { empty-cells: show; background-color: white }
.ca_td { white-space: nowrap }
.ca_td_headerdate1 { background-color: white }
.ca_td_headertime1, .ca_td_odddate1 { background-color: #77ddff }
.ca_td_evendate1 { background-color: #66ccee }
.ca_td_evendate1, .ca_td_odddate1 { text-align: right }
.ca_td_headertime1 { font-weight: bold }
.ca_td_headerdate1, .ca_td_headertime1 { border-bottom: 1px solid black }
.ca_tr_even1 { background-color: #eeeeee }
.ca_td_headertime1 { text-align: center }
.ca_td_headerdate1, .ca_td_evendate1, .ca_td_odddate1 { border-right: 1px solid black }
.ca_td_evendate1, .ca_td_odddate1 { padding-right: 2px; font-weight: bold }
.ca_td_evenpage1, .ca_td_oddpage1 { text-align: center; padding-left:2px; padding-right:2px }
.ca_span_deviation { color: #888888; font-size: small }
.ca_span_dayofweek { font-size: small; font-weight: normal }
.ca_td_dst { font-size: small; text-align:right; font-style: italic }
.printonly { display: none }
</style>
<style type="text/css" media="print">
p, li { font-size: 15pt }
a { text-decoration: none; color: black }
.onlineonly { display: none }
.printonly { display:block }
</style>
'''
print '</head><body>'
print '<h1 style="text-align:center">Current Atlas Lookup Tables</h1>'
print '<h2 style="text-align:center">Juan de Fuca Strait to Strait of Georgia</h2>'
print '<h1 style="text-align:center">' + str(year) + '</h1>'
print '<p style="text-align:center" class="onlineonly"><a href="https://borsboom.io/current-atlas-tables/">Other Years and Printable PDFs</a></p>'
print '''
<p style="text-align: center"><em>For use with:</em>
<br /><img src="current_atlas.jpg" width="431" height="591" style="border: 1px solid black"/>
<!--
<br />
<br /><em>Current Atlas / Atlas des Courants</em>
<br /><em><strong>Juan de Fuca Strait to/à Strait of Georgia</strong></em>
<br />(Published by the Canadian Hydrographic Service)
-->
</p>
<p>To find the chart number for a date and time,
first find the table for the required date, then find the row for the required day,
then read across to the
column for required hour, and finally turn to the chart number in the <em>Current Atlas</em>.
The small time below the chart number indicates the actual time
that the chart most closely matches. Times <strong>are</strong> adjusted for daylight savings (PDT, 0200 second Sunday in March through 0200 first Sunday in November).</p>
<p><strong>These tables are for non-commercial use only!</strong></p>
<p>For tables for other years<span class="onlineonly"> and printable PDFs</span>, visit <a href="https://borsboom.io/current-atlas-tables/">borsboom.io/current-atlas-tables</a>.
<div class="onlineonly"><h4>Contents</h4><ul>
'''
for month in range(1,13):
print ('<li><a href="#' + ('%02d' % month) + '">' +
time.strftime('%B, %Y', time.localtime(time.mktime((year,month,1,0,0,0,0,0,0)))) +
'</a></li>')
print '</ul></div>'
print '''
<p style="float:right; text-align:right; font-size: small">
<a rel="license" href="http://creativecommons.org/licenses/by-nc-sa/2.5/ca/"><img alt="Creative Commons License" style="border-width:0" src="http://i.creativecommons.org/l/by-nc-sa/2.5/ca/88x31.png" /></a><br /><span xmlns:dc="http://purl.org/dc/elements/1.1/" href="http://purl.org/dc/dcmitype/Text" property="dc:title" rel="dc:type">Licensed under a <a rel="license" href="http://creativecommons.org/licenses/by-nc-sa/2.5/ca/">Creative Commons<br />Attribution-Noncommercial-Share<br />Alike 2.5 Canada License</a>.
</p>
<p style="page-break-after:always">
<br />
<em>Produced by <strong>Emanuel Borsboom</strong>
<br />Mayne Island, B.C.
<br />web: <a href="https://borsboom.io/">borsboom.io</a></em>
</p>
<p class="printonly" style="page-break-after:always;text-align:center">(this page intentionally left blank)</p>
'''
for month in range(1,13):
print ('<h3 style="margin-bottom:4pt;page-break-before:always"><a name="' + ('%02d' % month) + '" />' +
time.strftime('%B, %Y', time.localtime(time.mktime((year,month,1,0,0,0,0,0,0)))) +
'<span class="printonly" style="float:right;font-size:smaller">Current Atlas Lookup Tables: Juan de Fuca Strait to Strait of Georgia</span>' +
'</h3><center> <br />')
sys.stdout.flush()
posix.system('tide -l "Point Atkinson, British Columbia" -f c -b "' +
time.strftime('%Y-%m-%d %H:%M', time.localtime(time.mktime((year,month,0,12,0,0,0,0,0)))) +
'" -e "' +
time.strftime('%Y-%m-%d %H:%M', time.localtime(time.mktime((year,month+1,1,12,0,0,0,0,0)))) +
'" | ./calculate.py --time-interval 60 | ./format.py --html --header-time-format "%H" --time-format "%H%M" --date-format \'%d<br /><span class="ca_span_dayofweek">%a</span>\' --deviations')
print '</center>'
print '</body></html>'
|
borsboom/current-atlas-tables
|
year_html.py
|
Python
|
mit
| 5,296
|
[
"VisIt"
] |
8e8dc1eada35528b1b845b07bda0adeb7bcf749b00e3f65d41f91323c731e0b9
|
# ----------------------------------------------------------------------------
# Copyright (c) 2013--, scikit-bio development team.
#
# Distributed under the terms of the Modified BSD License.
#
# The full license is in the file COPYING.txt, distributed with this software.
# ----------------------------------------------------------------------------
from .subsample import subsample
__all__ = ['subsample']
from numpy.testing import Tester
test = Tester().test
|
JWDebelius/scikit-bio
|
skbio/stats/_subsample/__init__.py
|
Python
|
bsd-3-clause
| 466
|
[
"scikit-bio"
] |
96e38c56c68d3e7beaa9051b49b122f4a1e5df1673b127d1401cf076576d3715
|
# Copyright (c) 2013-2015 University Corporation for Atmospheric Research/Unidata.
# Distributed under the terms of the MIT License.
# SPDX-License-Identifier: MIT
"""Support making data requests to the NetCDF subset service (NCSS) on a TDS.
This includes forming proper queries as well as parsing the returned data.
"""
import atexit
from io import BytesIO
from os import remove
import platform
import xml.etree.ElementTree as ET
import numpy as np
from .http_util import DataQuery, HTTPEndPoint, parse_iso_date
from .ncss_dataset import NCSSDataset
def default_unit_handler(data, units=None): # pylint:disable=unused-argument
"""Handle units in the default manner.
Ignores units and just returns :func:`numpy.array`.
"""
return np.array(data)
class NCSS(HTTPEndPoint):
"""Wrap access to the NetCDF Subset Service (NCSS) on a THREDDS server.
Simplifies access via HTTP to the NCSS endpoint. Parses the metadata, provides
data download and parsing based on the appropriate query.
Attributes
----------
metadata : NCSSDataset
Contains the result of parsing the NCSS endpoint's dataset.xml. This has
information about the time and space coverage, as well as full information
about all of the variables.
variables : set(str)
Names of all variables available in this dataset
unit_handler : callable
Function to handle units that come with CSV/XML data. Should be a callable that
takes a list of string values and unit str (can be :data:`None`), and returns the
desired representation of values. Defaults to ignoring units and returning
:func:`numpy.array`.
"""
# Need staticmethod to keep this from becoming a bound method, where self
# is passed implicitly
unit_handler = staticmethod(default_unit_handler)
def _get_metadata(self):
# Need to use .content here to avoid decode problems
meta_xml = self.get_path('dataset.xml').content
root = ET.fromstring(meta_xml)
self.metadata = NCSSDataset(root)
self.variables = set(self.metadata.variables.keys())
def query(self):
"""Return a new query for NCSS.
Returns
-------
query : NCSSQuery
The newly created query
"""
return NCSSQuery()
def validate_query(self, query):
"""Validate a query.
Determines whether `query` is well-formed. This includes checking for all
required parameters, as well as checking parameters for valid values.
Parameters
----------
query : NCSSQuery
The query to validate
Returns
-------
valid : bool
Whether `query` is valid.
"""
# Make sure all variables are in the dataset
return bool(query.var) and all(var in self.variables for var in query.var)
def get_data(self, query):
"""Fetch parsed data from a THREDDS server using NCSS.
Requests data from the NCSS endpoint given the parameters in `query` and
handles parsing of the returned content based on the mimetype.
Parameters
----------
query : NCSSQuery
The parameters to send to the NCSS endpoint
Returns
-------
Parsed data response from the server. Exact format depends on the format of the
response.
See Also
--------
get_data_raw
"""
resp = self.get_query(query)
return response_handlers(resp, self.unit_handler)
def get_data_raw(self, query):
"""Fetch raw data from a THREDDS server using NCSS.
Requests data from the NCSS endpoint given the parameters in `query` and
returns the raw bytes of the response.
Parameters
----------
query : NCSSQuery
The parameters to send to the NCSS endpoint
Returns
-------
content : bytes
The raw, un-parsed, data returned by the server
See Also
--------
get_data
"""
return self.get_query(query).content
class NCSSQuery(DataQuery):
"""Represent a query to the NetCDF Subset Service (NCSS).
Expands on the queries supported by :class:`~siphon.http_util.DataQuery` to add queries
specific to NCSS.
"""
def projection_box(self, min_x, min_y, max_x, max_y):
"""Add a bounding box in projected (native) coordinates to the query.
This adds a request for a spatial bounding box, bounded by (`min_x`, `max_x`) for
x direction and (`min_y`, `max_y`) for the y direction. This modifies the query
in-place, but returns ``self`` so that multiple queries can be chained together
on one line.
This replaces any existing spatial queries that have been set.
Parameters
----------
min_x : float
The left edge of the bounding box
min_y : float
The bottom edge of the bounding box
max_x : float
The right edge of the bounding box
max_y: float
The top edge of the bounding box
Returns
-------
self : NCSSQuery
Returns self for chaining calls
"""
self._set_query(self.spatial_query, minx=min_x, miny=min_y,
maxx=max_x, maxy=max_y)
return self
def accept(self, fmt):
"""Set format for data returned from NCSS.
This modifies the query in-place, but returns `self` so that multiple queries
can be chained together on one line.
Parameters
----------
fmt : str
The format to send to the server.
Returns
-------
self : NCSSQuery
Returns self for chaining calls
"""
return self.add_query_parameter(accept=fmt)
def add_lonlat(self, value=True):
"""Set whether NCSS should add latitude/longitude to returned data.
This is only used on grid requests. Used to make returned data CF-compliant.
This modifies the query in-place, but returns `self` so that multiple queries
can be chained together on one line.
Parameters
----------
value : bool, optional
Whether to add latitude/longitude information. Defaults to True.
Returns
-------
self : NCSSQuery
Returns self for chaining calls
"""
return self.add_query_parameter(addLatLon=value)
def strides(self, time=None, spatial=None):
"""Set time and/or spatial (horizontal) strides.
This is only used on grid requests. Used to skip points in the returned data.
This modifies the query in-place, but returns `self` so that multiple queries
can be chained together on one line.
Parameters
----------
time : int, optional
Stride for times returned. Defaults to None, which is equivalent to 1.
spatial : int, optional
Stride for horizontal grid. Defaults to None, which is equivalent to 1.
Returns
-------
self : NCSSQuery
Returns self for chaining calls
"""
if time:
self.add_query_parameter(timeStride=time)
if spatial:
self.add_query_parameter(horizStride=spatial)
return self
def vertical_level(self, level):
"""Set vertical level for which data should be retrieved.
The value depends on the coordinate values for the vertical dimension of the
requested variable.
This modifies the query in-place, but returns `self` so that multiple queries
can be chained together on one line.
Parameters
----------
level : float
The value of the desired level
Returns
-------
self : NCSSQuery
Returns self for chaining calls
"""
return self.add_query_parameter(vertCoord=level)
#
# The remainder of the file is not considered part of the public API.
# Use at your own risk!
#
class ResponseRegistry(object):
"""Register functions to be called based on the mimetype in the response headers."""
def __init__(self):
"""Initialize the registry."""
self._reg = {}
def register(self, mimetype):
"""Register a function to handle a particular mimetype."""
def dec(func):
self._reg[mimetype] = func
return func
return dec
@staticmethod
def default(content, units): # pylint:disable=unused-argument
"""Handle a mimetype when no function is registered."""
return content
def __call__(self, resp, unit_handler):
"""Process the HTTP response using the appropriate handler."""
mimetype = resp.headers['content-type'].split(';')[0]
return self._reg.get(mimetype, self.default)(resp.content, unit_handler)
response_handlers = ResponseRegistry()
def squish(l):
"""If list contains only 1 element, return it instead."""
return l if len(l) > 1 else l[0]
def combine_dicts(l):
"""Combine a list of dictionaries into single one."""
ret = {}
for item in l:
ret.update(item)
return ret
# Parsing of XML returns from NCSS
@response_handlers.register('application/xml')
def parse_xml(data, handle_units):
"""Parse XML data returned by NCSS."""
root = ET.fromstring(data)
return squish(parse_xml_dataset(root, handle_units))
def parse_xml_point(elem):
"""Parse an XML point tag."""
point = {}
units = {}
for data in elem.findall('data'):
name = data.get('name')
unit = data.get('units')
point[name] = float(data.text) if name != 'date' else parse_iso_date(data.text)
if unit:
units[name] = unit
return point, units
def combine_xml_points(l, units, handle_units):
"""Combine multiple Point tags into an array."""
ret = {}
for item in l:
for key, value in item.items():
ret.setdefault(key, []).append(value)
for key, value in ret.items():
if key != 'date':
ret[key] = handle_units(value, units.get(key, None))
return ret
def parse_xml_dataset(elem, handle_units):
"""Create a netCDF-like dataset from XML data."""
points, units = zip(*[parse_xml_point(p) for p in elem.findall('point')])
# Group points by the contents of each point
datasets = {}
for p in points:
datasets.setdefault(tuple(p.keys()), []).append(p)
all_units = combine_dicts(units)
return [combine_xml_points(d, all_units, handle_units) for d in datasets.values()]
# Handling of netCDF 3/4 from NCSS
try:
from netCDF4 import Dataset
from tempfile import NamedTemporaryFile
@response_handlers.register('application/x-netcdf')
@response_handlers.register('application/x-netcdf4')
def read_netcdf(data, handle_units): # pylint:disable=unused-argument
"""Handle HTTP responses in netCDF format."""
ostype = platform.architecture()
if ostype[1].lower() == 'windowspe':
with NamedTemporaryFile(delete=False) as tmp_file:
tmp_file.write(data)
tmp_file.flush()
atexit.register(deletetempfile, tmp_file.name)
return Dataset(tmp_file.name, 'r')
else:
with NamedTemporaryFile() as tmp_file:
tmp_file.write(data)
tmp_file.flush()
return Dataset(tmp_file.name, 'r')
except ImportError:
import warnings
warnings.warn('netCDF4 module not installed. '
'Will be unable to handle NetCDF returns from NCSS.')
def deletetempfile(fname):
"""Delete a temporary file.
Warn on any exceptions.
"""
try:
remove(fname)
except OSError:
import warnings
warnings.warn('temporary netcdf dataset file not deleted. '
'to delete temporary dataset file in the future '
'be sure to use dataset.close() when finished.')
# Parsing of CSV data returned from NCSS
@response_handlers.register('text/plain')
def parse_csv_response(data, unit_handler):
"""Handle CSV-formatted HTTP responses."""
return squish([parse_csv_dataset(d, unit_handler) for d in data.split(b'\n\n')])
def parse_csv_header(line):
"""Parse the CSV header returned by TDS."""
units = {}
names = []
for var in line.split(','):
start = var.find('[')
if start < 0:
names.append(str(var))
continue
else:
names.append(str(var[:start]))
end = var.find(']', start)
unitstr = var[start + 1:end]
eq = unitstr.find('=')
if eq >= 0:
# go past = and ", skip final "
units[names[-1]] = unitstr[eq + 2:-1]
return names, units
def parse_csv_dataset(data, handle_units):
"""Parse CSV data into a netCDF-like dataset."""
fobj = BytesIO(data)
names, units = parse_csv_header(fobj.readline().decode('utf-8'))
arrs = np.genfromtxt(fobj, dtype=None, names=names, delimiter=',', unpack=True,
converters={'date': lambda s: parse_iso_date(s.decode('utf-8'))})
d = {}
for f in arrs.dtype.fields:
dat = arrs[f]
if dat.dtype == np.object:
dat = dat.tolist()
d[f] = handle_units(dat, units.get(f, None))
return d
|
dopplershift/siphon
|
siphon/ncss.py
|
Python
|
mit
| 13,533
|
[
"NetCDF"
] |
8d63f125cccead61896cc01ca8ec8e21144ae31568a60f6442a46756ee30ff59
|
#! /usr/bin/env python3
# -*- coding: utf-8 -*-
# Copyright 2022 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
import argparse
import os
import libcst as cst
import pathlib
import sys
from typing import (Any, Callable, Dict, List, Sequence, Tuple)
def partition(
predicate: Callable[[Any], bool],
iterator: Sequence[Any]
) -> Tuple[List[Any], List[Any]]:
"""A stable, out-of-place partition."""
results = ([], [])
for i in iterator:
results[int(predicate(i))].append(i)
# Returns trueList, falseList
return results[1], results[0]
class securitycenterCallTransformer(cst.CSTTransformer):
CTRL_PARAMS: Tuple[str] = ('retry', 'timeout', 'metadata')
METHOD_TO_PARAMS: Dict[str, Tuple[str]] = {
'create_finding': ('parent', 'finding_id', 'finding', ),
'create_source': ('parent', 'source', ),
'get_iam_policy': ('resource', 'options', ),
'get_organization_settings': ('name', ),
'get_source': ('name', ),
'group_assets': ('parent', 'group_by', 'filter', 'compare_duration', 'read_time', 'page_token', 'page_size', ),
'group_findings': ('parent', 'group_by', 'filter', 'read_time', 'page_token', 'page_size', ),
'list_assets': ('parent', 'filter', 'order_by', 'read_time', 'compare_duration', 'field_mask', 'page_token', 'page_size', ),
'list_findings': ('parent', 'filter', 'order_by', 'read_time', 'field_mask', 'page_token', 'page_size', ),
'list_sources': ('parent', 'page_token', 'page_size', ),
'run_asset_discovery': ('parent', ),
'set_finding_state': ('name', 'state', 'start_time', ),
'set_iam_policy': ('resource', 'policy', ),
'test_iam_permissions': ('resource', 'permissions', ),
'update_finding': ('finding', 'update_mask', ),
'update_organization_settings': ('organization_settings', 'update_mask', ),
'update_security_marks': ('security_marks', 'update_mask', 'start_time', ),
'update_source': ('source', 'update_mask', ),
}
def leave_Call(self, original: cst.Call, updated: cst.Call) -> cst.CSTNode:
try:
key = original.func.attr.value
kword_params = self.METHOD_TO_PARAMS[key]
except (AttributeError, KeyError):
# Either not a method from the API or too convoluted to be sure.
return updated
# If the existing code is valid, keyword args come after positional args.
# Therefore, all positional args must map to the first parameters.
args, kwargs = partition(lambda a: not bool(a.keyword), updated.args)
if any(k.keyword.value == "request" for k in kwargs):
# We've already fixed this file, don't fix it again.
return updated
kwargs, ctrl_kwargs = partition(
lambda a: a.keyword.value not in self.CTRL_PARAMS,
kwargs
)
args, ctrl_args = args[:len(kword_params)], args[len(kword_params):]
ctrl_kwargs.extend(cst.Arg(value=a.value, keyword=cst.Name(value=ctrl))
for a, ctrl in zip(ctrl_args, self.CTRL_PARAMS))
request_arg = cst.Arg(
value=cst.Dict([
cst.DictElement(
cst.SimpleString("'{}'".format(name)),
cst.Element(value=arg.value)
)
# Note: the args + kwargs looks silly, but keep in mind that
# the control parameters had to be stripped out, and that
# those could have been passed positionally or by keyword.
for name, arg in zip(kword_params, args + kwargs)]),
keyword=cst.Name("request")
)
return updated.with_changes(
args=[request_arg] + ctrl_kwargs
)
def fix_files(
in_dir: pathlib.Path,
out_dir: pathlib.Path,
*,
transformer=securitycenterCallTransformer(),
):
"""Duplicate the input dir to the output dir, fixing file method calls.
Preconditions:
* in_dir is a real directory
* out_dir is a real, empty directory
"""
pyfile_gen = (
pathlib.Path(os.path.join(root, f))
for root, _, files in os.walk(in_dir)
for f in files if os.path.splitext(f)[1] == ".py"
)
for fpath in pyfile_gen:
with open(fpath, 'r') as f:
src = f.read()
# Parse the code and insert method call fixes.
tree = cst.parse_module(src)
updated = tree.visit(transformer)
# Create the path and directory structure for the new file.
updated_path = out_dir.joinpath(fpath.relative_to(in_dir))
updated_path.parent.mkdir(parents=True, exist_ok=True)
# Generate the updated source file at the corresponding path.
with open(updated_path, 'w') as f:
f.write(updated.code)
if __name__ == '__main__':
parser = argparse.ArgumentParser(
description="""Fix up source that uses the securitycenter client library.
The existing sources are NOT overwritten but are copied to output_dir with changes made.
Note: This tool operates at a best-effort level at converting positional
parameters in client method calls to keyword based parameters.
Cases where it WILL FAIL include
A) * or ** expansion in a method call.
B) Calls via function or method alias (includes free function calls)
C) Indirect or dispatched calls (e.g. the method is looked up dynamically)
These all constitute false negatives. The tool will also detect false
positives when an API method shares a name with another method.
""")
parser.add_argument(
'-d',
'--input-directory',
required=True,
dest='input_dir',
help='the input directory to walk for python files to fix up',
)
parser.add_argument(
'-o',
'--output-directory',
required=True,
dest='output_dir',
help='the directory to output files fixed via un-flattening',
)
args = parser.parse_args()
input_dir = pathlib.Path(args.input_dir)
output_dir = pathlib.Path(args.output_dir)
if not input_dir.is_dir():
print(
f"input directory '{input_dir}' does not exist or is not a directory",
file=sys.stderr,
)
sys.exit(-1)
if not output_dir.is_dir():
print(
f"output directory '{output_dir}' does not exist or is not a directory",
file=sys.stderr,
)
sys.exit(-1)
if os.listdir(output_dir):
print(
f"output directory '{output_dir}' is not empty",
file=sys.stderr,
)
sys.exit(-1)
fix_files(input_dir, output_dir)
|
googleapis/python-securitycenter
|
scripts/fixup_securitycenter_v1beta1_keywords.py
|
Python
|
apache-2.0
| 7,209
|
[
"VisIt"
] |
4dc7e79d7c3a8f4ac19782d8c658f2c860e3bec9c34682b6fda7bd7556d0bbe7
|
"""Hyperion config flow."""
from __future__ import annotations
import asyncio
from contextlib import suppress
import logging
from typing import Any
from urllib.parse import urlparse
from hyperion import client, const
import voluptuous as vol
from homeassistant.components.ssdp import ATTR_SSDP_LOCATION, ATTR_UPNP_SERIAL
from homeassistant.config_entries import (
SOURCE_REAUTH,
ConfigEntry,
ConfigFlow,
OptionsFlow,
)
from homeassistant.const import (
CONF_BASE,
CONF_HOST,
CONF_ID,
CONF_PORT,
CONF_SOURCE,
CONF_TOKEN,
)
from homeassistant.core import callback
from homeassistant.data_entry_flow import FlowResult
import homeassistant.helpers.config_validation as cv
from . import create_hyperion_client
from .const import (
CONF_AUTH_ID,
CONF_CREATE_TOKEN,
CONF_EFFECT_HIDE_LIST,
CONF_EFFECT_SHOW_LIST,
CONF_PRIORITY,
DEFAULT_ORIGIN,
DEFAULT_PRIORITY,
DOMAIN,
)
_LOGGER = logging.getLogger(__name__)
_LOGGER.setLevel(logging.DEBUG)
# +------------------+ +------------------+ +--------------------+ +--------------------+
# |Step: SSDP | |Step: user | |Step: import | |Step: reauth |
# | | | | | | | |
# |Input: <discovery>| |Input: <host/port>| |Input: <import data>| |Input: <entry_data> |
# +------------------+ +------------------+ +--------------------+ +--------------------+
# v v v v
# +-------------------+-----------------------+--------------------+
# Auth not | Auth |
# required? | required? |
# | v
# | +------------+
# | |Step: auth |
# | | |
# | |Input: token|
# | +------------+
# | Static |
# v token |
# <------------------+
# | |
# | | New token
# | v
# | +------------------+
# | |Step: create_token|
# | +------------------+
# | |
# | v
# | +---------------------------+ +--------------------------------+
# | |Step: create_token_external|-->|Step: create_token_external_fail|
# | +---------------------------+ +--------------------------------+
# | |
# | v
# | +-----------------------------------+
# | |Step: create_token_external_success|
# | +-----------------------------------+
# | |
# v<------------------+
# |
# v
# +-------------+ Confirm not required?
# |Step: Confirm|---------------------->+
# +-------------+ |
# | |
# v SSDP: Explicit confirm |
# +------------------------------>+
# |
# v
# +----------------+
# | Create/Update! |
# +----------------+
# A note on choice of discovery mechanisms: Hyperion supports both Zeroconf and SSDP out
# of the box. This config flow needs two port numbers from the Hyperion instance, the
# JSON port (for the API) and the UI port (for the user to approve dynamically created
# auth tokens). With Zeroconf the port numbers for both are in different Zeroconf
# entries, and as Home Assistant only passes a single entry into the config flow, we can
# only conveniently 'see' one port or the other (which means we need to guess one port
# number). With SSDP, we get the combined block including both port numbers, so SSDP is
# the favored discovery implementation.
class HyperionConfigFlow(ConfigFlow, domain=DOMAIN):
"""Handle a Hyperion config flow."""
VERSION = 1
def __init__(self) -> None:
"""Instantiate config flow."""
self._data: dict[str, Any] = {}
self._request_token_task: asyncio.Task | None = None
self._auth_id: str | None = None
self._require_confirm: bool = False
self._port_ui: int = const.DEFAULT_PORT_UI
def _create_client(self, raw_connection: bool = False) -> client.HyperionClient:
"""Create and connect a client instance."""
return create_hyperion_client(
self._data[CONF_HOST],
self._data[CONF_PORT],
token=self._data.get(CONF_TOKEN),
raw_connection=raw_connection,
)
async def _advance_to_auth_step_if_necessary(
self, hyperion_client: client.HyperionClient
) -> FlowResult:
"""Determine if auth is required."""
auth_resp = await hyperion_client.async_is_auth_required()
# Could not determine if auth is required.
if not auth_resp or not client.ResponseOK(auth_resp):
return self.async_abort(reason="auth_required_error")
auth_required = auth_resp.get(const.KEY_INFO, {}).get(const.KEY_REQUIRED, False)
if auth_required:
return await self.async_step_auth()
return await self.async_step_confirm()
async def async_step_reauth(
self,
config_data: dict[str, Any],
) -> FlowResult:
"""Handle a reauthentication flow."""
self._data = dict(config_data)
async with self._create_client(raw_connection=True) as hyperion_client:
if not hyperion_client:
return self.async_abort(reason="cannot_connect")
return await self._advance_to_auth_step_if_necessary(hyperion_client)
async def async_step_ssdp(self, discovery_info: dict[str, Any]) -> FlowResult:
"""Handle a flow initiated by SSDP."""
# Sample data provided by SSDP: {
# 'ssdp_location': 'http://192.168.0.1:8090/description.xml',
# 'ssdp_st': 'upnp:rootdevice',
# 'deviceType': 'urn:schemas-upnp-org:device:Basic:1',
# 'friendlyName': 'Hyperion (192.168.0.1)',
# 'manufacturer': 'Hyperion Open Source Ambient Lighting',
# 'manufacturerURL': 'https://www.hyperion-project.org',
# 'modelDescription': 'Hyperion Open Source Ambient Light',
# 'modelName': 'Hyperion',
# 'modelNumber': '2.0.0-alpha.8',
# 'modelURL': 'https://www.hyperion-project.org',
# 'serialNumber': 'f9aab089-f85a-55cf-b7c1-222a72faebe9',
# 'UDN': 'uuid:f9aab089-f85a-55cf-b7c1-222a72faebe9',
# 'ports': {
# 'jsonServer': '19444',
# 'sslServer': '8092',
# 'protoBuffer': '19445',
# 'flatBuffer': '19400'
# },
# 'presentationURL': 'index.html',
# 'iconList': {
# 'icon': {
# 'mimetype': 'image/png',
# 'height': '100',
# 'width': '100',
# 'depth': '32',
# 'url': 'img/hyperion/ssdp_icon.png'
# }
# },
# 'ssdp_usn': 'uuid:f9aab089-f85a-55cf-b7c1-222a72faebe9',
# 'ssdp_ext': '',
# 'ssdp_server': 'Raspbian GNU/Linux 10 (buster)/10 UPnP/1.0 Hyperion/2.0.0-alpha.8'}
# SSDP requires user confirmation.
self._require_confirm = True
self._data[CONF_HOST] = urlparse(discovery_info[ATTR_SSDP_LOCATION]).hostname
try:
self._port_ui = urlparse(discovery_info[ATTR_SSDP_LOCATION]).port
except ValueError:
self._port_ui = const.DEFAULT_PORT_UI
try:
self._data[CONF_PORT] = int(
discovery_info.get("ports", {}).get(
"jsonServer", const.DEFAULT_PORT_JSON
)
)
except ValueError:
self._data[CONF_PORT] = const.DEFAULT_PORT_JSON
if not (hyperion_id := discovery_info.get(ATTR_UPNP_SERIAL)):
return self.async_abort(reason="no_id")
# For discovery mechanisms, we set the unique_id as early as possible to
# avoid discovery popping up a duplicate on the screen. The unique_id is set
# authoritatively later in the flow by asking the server to confirm its id
# (which should theoretically be the same as specified here)
await self.async_set_unique_id(hyperion_id)
self._abort_if_unique_id_configured()
async with self._create_client(raw_connection=True) as hyperion_client:
if not hyperion_client:
return self.async_abort(reason="cannot_connect")
return await self._advance_to_auth_step_if_necessary(hyperion_client)
async def async_step_user(
self,
user_input: dict[str, Any] | None = None,
) -> FlowResult:
"""Handle a flow initiated by the user."""
errors = {}
if user_input:
self._data.update(user_input)
async with self._create_client(raw_connection=True) as hyperion_client:
if hyperion_client:
return await self._advance_to_auth_step_if_necessary(
hyperion_client
)
errors[CONF_BASE] = "cannot_connect"
return self.async_show_form(
step_id="user",
data_schema=vol.Schema(
{
vol.Required(CONF_HOST): str,
vol.Optional(CONF_PORT, default=const.DEFAULT_PORT_JSON): int,
}
),
errors=errors,
)
async def _cancel_request_token_task(self) -> None:
"""Cancel the request token task if it exists."""
if self._request_token_task is not None:
if not self._request_token_task.done():
self._request_token_task.cancel()
with suppress(asyncio.CancelledError):
await self._request_token_task
self._request_token_task = None
async def _request_token_task_func(self, auth_id: str) -> None:
"""Send an async_request_token request."""
auth_resp: dict[str, Any] | None = None
async with self._create_client(raw_connection=True) as hyperion_client:
if hyperion_client:
# The Hyperion-py client has a default timeout of 3 minutes on this request.
auth_resp = await hyperion_client.async_request_token(
comment=DEFAULT_ORIGIN, id=auth_id
)
await self.hass.config_entries.flow.async_configure(
flow_id=self.flow_id, user_input=auth_resp
)
def _get_hyperion_url(self) -> str:
"""Return the URL of the Hyperion UI."""
# If this flow was kicked off by SSDP, this will be the correct frontend URL. If
# this is a manual flow instantiation, then it will be a best guess (as this
# flow does not have that information available to it). This is only used for
# approving new dynamically created tokens, so the complexity of asking the user
# manually for this information is likely not worth it (when it would only be
# used to open a URL, that the user already knows the address of).
return f"http://{self._data[CONF_HOST]}:{self._port_ui}"
async def _can_login(self) -> bool | None:
"""Verify login details."""
async with self._create_client(raw_connection=True) as hyperion_client:
if not hyperion_client:
return None
return bool(
client.LoginResponseOK(
await hyperion_client.async_login(token=self._data[CONF_TOKEN])
)
)
async def async_step_auth(
self,
user_input: dict[str, Any] | None = None,
) -> FlowResult:
"""Handle the auth step of a flow."""
errors = {}
if user_input:
if user_input.get(CONF_CREATE_TOKEN):
return await self.async_step_create_token()
# Using a static token.
self._data[CONF_TOKEN] = user_input.get(CONF_TOKEN)
login_ok = await self._can_login()
if login_ok is None:
return self.async_abort(reason="cannot_connect")
if login_ok:
return await self.async_step_confirm()
errors[CONF_BASE] = "invalid_access_token"
return self.async_show_form(
step_id="auth",
data_schema=vol.Schema(
{
vol.Required(CONF_CREATE_TOKEN): bool,
vol.Optional(CONF_TOKEN): str,
}
),
errors=errors,
)
async def async_step_create_token(
self, user_input: dict[str, Any] | None = None
) -> FlowResult:
"""Send a request for a new token."""
if user_input is None:
self._auth_id = client.generate_random_auth_id()
return self.async_show_form(
step_id="create_token",
description_placeholders={
CONF_AUTH_ID: self._auth_id,
},
)
# Cancel the request token task if it's already running, then re-create it.
await self._cancel_request_token_task()
# Start a task in the background requesting a new token. The next step will
# wait on the response (which includes the user needing to visit the Hyperion
# UI to approve the request for a new token).
assert self._auth_id is not None
self._request_token_task = self.hass.async_create_task(
self._request_token_task_func(self._auth_id)
)
return self.async_external_step(
step_id="create_token_external", url=self._get_hyperion_url()
)
async def async_step_create_token_external(
self, auth_resp: dict[str, Any] | None = None
) -> FlowResult:
"""Handle completion of the request for a new token."""
if auth_resp is not None and client.ResponseOK(auth_resp):
token = auth_resp.get(const.KEY_INFO, {}).get(const.KEY_TOKEN)
if token:
self._data[CONF_TOKEN] = token
return self.async_external_step_done(
next_step_id="create_token_success"
)
return self.async_external_step_done(next_step_id="create_token_fail")
async def async_step_create_token_success(
self, _: dict[str, Any] | None = None
) -> FlowResult:
"""Create an entry after successful token creation."""
# Clean-up the request task.
await self._cancel_request_token_task()
# Test the token.
login_ok = await self._can_login()
if login_ok is None:
return self.async_abort(reason="cannot_connect")
if not login_ok:
return self.async_abort(reason="auth_new_token_not_work_error")
return await self.async_step_confirm()
async def async_step_create_token_fail(
self, _: dict[str, Any] | None = None
) -> FlowResult:
"""Show an error on the auth form."""
# Clean-up the request task.
await self._cancel_request_token_task()
return self.async_abort(reason="auth_new_token_not_granted_error")
async def async_step_confirm(
self, user_input: dict[str, Any] | None = None
) -> FlowResult:
"""Get final confirmation before entry creation."""
if user_input is None and self._require_confirm:
return self.async_show_form(
step_id="confirm",
description_placeholders={
CONF_HOST: self._data[CONF_HOST],
CONF_PORT: self._data[CONF_PORT],
CONF_ID: self.unique_id,
},
)
async with self._create_client() as hyperion_client:
if not hyperion_client:
return self.async_abort(reason="cannot_connect")
hyperion_id = await hyperion_client.async_sysinfo_id()
if not hyperion_id:
return self.async_abort(reason="no_id")
entry = await self.async_set_unique_id(hyperion_id, raise_on_progress=False)
if self.context.get(CONF_SOURCE) == SOURCE_REAUTH and entry is not None:
self.hass.config_entries.async_update_entry(entry, data=self._data)
# Need to manually reload, as the listener won't have been installed because
# the initial load did not succeed (the reauth flow will not be initiated if
# the load succeeds)
await self.hass.config_entries.async_reload(entry.entry_id)
return self.async_abort(reason="reauth_successful")
self._abort_if_unique_id_configured()
return self.async_create_entry(
title=f"{self._data[CONF_HOST]}:{self._data[CONF_PORT]}", data=self._data
)
@staticmethod
@callback
def async_get_options_flow(config_entry: ConfigEntry) -> HyperionOptionsFlow:
"""Get the Hyperion Options flow."""
return HyperionOptionsFlow(config_entry)
class HyperionOptionsFlow(OptionsFlow):
"""Hyperion options flow."""
def __init__(self, config_entry: ConfigEntry) -> None:
"""Initialize a Hyperion options flow."""
self._config_entry = config_entry
def _create_client(self) -> client.HyperionClient:
"""Create and connect a client instance."""
return create_hyperion_client(
self._config_entry.data[CONF_HOST],
self._config_entry.data[CONF_PORT],
token=self._config_entry.data.get(CONF_TOKEN),
)
async def async_step_init(
self, user_input: dict[str, Any] | None = None
) -> FlowResult:
"""Manage the options."""
effects = {source: source for source in const.KEY_COMPONENTID_EXTERNAL_SOURCES}
async with self._create_client() as hyperion_client:
if not hyperion_client:
return self.async_abort(reason="cannot_connect")
for effect in hyperion_client.effects or []:
if const.KEY_NAME in effect:
effects[effect[const.KEY_NAME]] = effect[const.KEY_NAME]
# If a new effect is added to Hyperion, we always want it to show by default. So
# rather than store a 'show list' in the config entry, we store a 'hide list'.
# However, it's more intuitive to ask the user to select which effects to show,
# so we inverse the meaning prior to storage.
if user_input is not None:
effect_show_list = user_input.pop(CONF_EFFECT_SHOW_LIST)
user_input[CONF_EFFECT_HIDE_LIST] = sorted(
set(effects) - set(effect_show_list)
)
return self.async_create_entry(title="", data=user_input)
default_effect_show_list = list(
set(effects)
- set(self._config_entry.options.get(CONF_EFFECT_HIDE_LIST, []))
)
return self.async_show_form(
step_id="init",
data_schema=vol.Schema(
{
vol.Optional(
CONF_PRIORITY,
default=self._config_entry.options.get(
CONF_PRIORITY, DEFAULT_PRIORITY
),
): vol.All(vol.Coerce(int), vol.Range(min=0, max=255)),
vol.Optional(
CONF_EFFECT_SHOW_LIST,
default=default_effect_show_list,
): cv.multi_select(effects),
}
),
)
|
aronsky/home-assistant
|
homeassistant/components/hyperion/config_flow.py
|
Python
|
apache-2.0
| 20,049
|
[
"VisIt"
] |
3eb26c3e9ce8971e82020759053e1b8b5729cd2cade87d98548e50f8173e9769
|
"""
Define the resolution functions for the data.
This defines classes for 1D and 2D resolution calculations.
"""
from __future__ import division
import unittest
from scipy.special import erf # type: ignore
from numpy import sqrt, log, log10, exp, pi # type: ignore
import numpy as np # type: ignore
__all__ = ["Resolution", "Perfect1D", "Pinhole1D", "Slit1D",
"apply_resolution_matrix", "pinhole_resolution", "slit_resolution",
"pinhole_extend_q", "slit_extend_q", "bin_edges",
"interpolate", "linear_extrapolation", "geometric_extrapolation",
]
MINIMUM_RESOLUTION = 1e-8
MINIMUM_ABSOLUTE_Q = 0.02 # relative to the minimum q in the data
# According to (Barker & Pedersen 1995 JAC), 2.5 sigma is a good limit.
# According to simulations with github.com:scattering/sansresolution.git
# it is better to use asymmetric bounds (2.5, 3.0)
PINHOLE_N_SIGMA = (2.5, 3.0)
class Resolution(object):
"""
Abstract base class defining a 1D resolution function.
*q* is the set of q values at which the data is measured.
*q_calc* is the set of q values at which the theory needs to be evaluated.
This may extend and interpolate the q values.
*apply* is the method to call with I(q_calc) to compute the resolution
smeared theory I(q).
"""
q = None # type: np.ndarray
q_calc = None # type: np.ndarray
def apply(self, theory):
"""
Smear *theory* by the resolution function, returning *Iq*.
"""
raise NotImplementedError("Subclass does not define the apply function")
class Perfect1D(Resolution):
"""
Resolution function to use when there is no actual resolution smearing
to be applied. It has the same interface as the other resolution
functions, but returns the identity function.
"""
def __init__(self, q):
self.q_calc = self.q = q
def apply(self, theory):
return theory
class Pinhole1D(Resolution):
r"""
Pinhole aperture with q-dependent gaussian resolution.
*q* points at which the data is measured.
*q_width* gaussian 1-sigma resolution at each data point.
*q_calc* is the list of points to calculate, or None if this should
be estimated from the *q* and *q_width*.
*nsigma* is the width of the resolution function. Should be 2.5.
See :func:`pinhole_resolution` for details.
"""
def __init__(self, q, q_width, q_calc=None, nsigma=PINHOLE_N_SIGMA):
#*min_step* is the minimum point spacing to use when computing the
#underlying model. It should be on the order of
#$\tfrac{1}{10}\tfrac{2\pi}{d_\text{max}}$ to make sure that fringes
#are computed with sufficient density to avoid aliasing effects.
# Protect against calls with q_width=0. The extend_q function will
# not extend the q if q_width is 0, but q_width must be non-zero when
# constructing the weight matrix to avoid division by zero errors.
# In practice this should never be needed, since resolution should
# default to Perfect1D if the pinhole geometry is not defined.
self.q, self.q_width = q, q_width
self.q_calc = (pinhole_extend_q(q, q_width, nsigma=nsigma)
if q_calc is None else np.sort(q_calc))
# Protect against models which are not defined for very low q. Limit
# the smallest q value evaluated (in absolute) to 0.02*min
cutoff = MINIMUM_ABSOLUTE_Q*np.min(self.q)
self.q_calc = self.q_calc[abs(self.q_calc) >= cutoff]
# Build weight matrix from calculated q values
self.weight_matrix = pinhole_resolution(
self.q_calc, self.q, np.maximum(q_width, MINIMUM_RESOLUTION),
nsigma=nsigma)
# Force positive q, even for events measured on the opposite side of
# the beam stop.
self.q_calc = abs(self.q_calc)
def apply(self, theory):
return apply_resolution_matrix(self.weight_matrix, theory)
class Slit1D(Resolution):
"""
Slit aperture with resolution function.
*q* points at which the data is measured.
*qx_width* slit width in qx
*qy_width* slit height in qy
*q_calc* is the list of points to calculate, or None if this should
be estimated from the *q* and *q_width*.
The *weight_matrix* is computed by :func:`slit_resolution`
"""
def __init__(self, q, qx_width, qy_width=0., q_calc=None):
# Remember what width/dqy was used even though we won't need them
# after the weight matrix is constructed
self.qx_width, self.qy_width = qx_width, qy_width
# Allow independent resolution on each point even though it is not
# needed in practice.
if np.isscalar(qx_width):
qx_width = np.ones(len(q))*qx_width
else:
qx_width = np.asarray(qx_width)
if np.isscalar(qy_width):
qy_width = np.ones(len(q))*qy_width
else:
qy_width = np.asarray(qy_width)
self.q = q.flatten()
self.q_calc = slit_extend_q(q, qx_width, qy_width) \
if q_calc is None else np.sort(q_calc)
# Protect against models which are not defined for very low q. Limit
# the smallest q value evaluated (in absolute) to 0.02*min
cutoff = MINIMUM_ABSOLUTE_Q*np.min(self.q)
self.q_calc = self.q_calc[abs(self.q_calc) >= cutoff]
# Build weight matrix from calculated q values
self.weight_matrix = \
slit_resolution(self.q_calc, self.q, qx_width, qy_width)
self.q_calc = abs(self.q_calc)
def apply(self, theory):
return apply_resolution_matrix(self.weight_matrix, theory)
def apply_resolution_matrix(weight_matrix, theory):
"""
Apply the resolution weight matrix to the computed theory function.
"""
#print("apply shapes", theory.shape, weight_matrix.shape)
Iq = np.dot(theory[None, :], weight_matrix)
#print("result shape",Iq.shape)
return Iq.flatten()
def pinhole_resolution(q_calc, q, q_width, nsigma=PINHOLE_N_SIGMA):
r"""
Compute the convolution matrix *W* for pinhole resolution 1-D data.
Each row *W[i]* determines the normalized weight that the corresponding
points *q_calc* contribute to the resolution smeared point *q[i]*. Given
*W*, the resolution smearing can be computed using *dot(W,q)*.
Note that resolution is limited to $\pm 2.5 \sigma$.[1] The true resolution
function is a broadened triangle, and does not extend over the entire
range $(-\infty, +\infty)$. It is important to impose this limitation
since some models fall so steeply that the weighted value in gaussian
tails would otherwise dominate the integral.
*q_calc* must be increasing. *q_width* must be greater than zero.
[1] Barker, J. G., and J. S. Pedersen. 1995. Instrumental Smearing Effects
in Radially Symmetric Small-Angle Neutron Scattering by Numerical and
Analytical Methods. Journal of Applied Crystallography 28 (2): 105--14.
https://doi.org/10.1107/S0021889894010095.
"""
# The current algorithm is a midpoint rectangle rule. In the test case,
# neither trapezoid nor Simpson's rule improved the accuracy.
edges = bin_edges(q_calc)
#edges[edges < 0.0] = 0.0 # clip edges below zero
cdf = erf((edges[:, None] - q[None, :]) / (sqrt(2.0)*q_width)[None, :])
weights = cdf[1:] - cdf[:-1]
# Limit q range to (-2.5,+3) sigma
try:
nsigma_low, nsigma_high = nsigma
except TypeError:
nsigma_low = nsigma_high = nsigma
qhigh = q + nsigma_high*q_width
qlow = q - nsigma_low*q_width # linear limits
##qlow = q*q/qhigh # log limits
weights[q_calc[:, None] < qlow[None, :]] = 0.
weights[q_calc[:, None] > qhigh[None, :]] = 0.
weights /= np.sum(weights, axis=0)[None, :]
return weights
def slit_resolution(q_calc, q, width, height, n_height=30):
r"""
Build a weight matrix to compute *I_s(q)* from *I(q_calc)*, given
$q_\perp$ = *width* and $q_\parallel$ = *height*. *n_height* is
is the number of steps to use in the integration over $q_\parallel$
when both $q_\perp$ and $q_\parallel$ are non-zero.
Each $q$ can have an independent width and height value even though
current instruments use the same slit setting for all measured points.
If slit height is large relative to width, use:
.. math::
I_s(q_i) = \frac{1}{\Delta q_\perp}
\int_0^{\Delta q_\perp}
I\left(\sqrt{q_i^2 + q_\perp^2}\right) \,dq_\perp
If slit width is large relative to height, use:
.. math::
I_s(q_i) = \frac{1}{2 \Delta q_\parallel}
\int_{-\Delta q_\parallel}^{\Delta q_\parallel}
I\left(|q_i + q_\parallel|\right) \,dq_\parallel
For a mixture of slit width and height use:
.. math::
I_s(q_i) = \frac{1}{2 \Delta q_\parallel \Delta q_\perp}
\int_{-\Delta q_\parallel}^{\Delta q_\parallel}
\int_0^{\Delta q_\perp}
I\left(\sqrt{(q_i + q_\parallel)^2 + q_\perp^2}\right)
\,dq_\perp dq_\parallel
**Definition**
We are using the mid-point integration rule to assign weights to each
element of a weight matrix $W$ so that
.. math::
I_s(q) = W\,I(q_\text{calc})
If *q_calc* is at the mid-point, we can infer the bin edges from the
pairwise averages of *q_calc*, adding the missing edges before
*q_calc[0]* and after *q_calc[-1]*.
For $q_\parallel = 0$, the smeared value can be computed numerically
using the $u$ substitution
.. math::
u_j = \sqrt{q_j^2 - q^2}
This gives
.. math::
I_s(q) \approx \sum_j I(u_j) \Delta u_j
where $I(u_j)$ is the value at the mid-point, and $\Delta u_j$ is the
difference between consecutive edges which have been first converted
to $u$. Only $u_j \in [0, \Delta q_\perp]$ are used, which corresponds
to $q_j \in \left[q, \sqrt{q^2 + \Delta q_\perp}\right]$, so
.. math::
W_{ij} = \frac{1}{\Delta q_\perp} \Delta u_j
= \frac{1}{\Delta q_\perp} \left(
\sqrt{q_{j+1}^2 - q_i^2} - \sqrt{q_j^2 - q_i^2} \right)
\ \text{if}\ q_j \in \left[q_i, \sqrt{q_i^2 + q_\perp^2}\right]
where $I_s(q_i)$ is the theory function being computed and $q_j$ are the
mid-points between the calculated values in *q_calc*. We tweak the
edges of the initial and final intervals so that they lie on integration
limits.
(To be precise, the transformed midpoint $u(q_j)$ is not necessarily the
midpoint of the edges $u((q_{j-1}+q_j)/2)$ and $u((q_j + q_{j+1})/2)$,
but it is at least in the interval, so the approximation is going to be
a little better than the left or right Riemann sum, and should be
good enough for our purposes.)
For $q_\perp = 0$, the $u$ substitution is simpler:
.. math::
u_j = \left|q_j - q\right|
so
.. math::
W_{ij} = \frac{1}{2 \Delta q_\parallel} \Delta u_j
= \frac{1}{2 \Delta q_\parallel} (q_{j+1} - q_j)
\ \text{if}\ q_j \in
\left[q-\Delta q_\parallel, q+\Delta q_\parallel\right]
However, we need to support cases were $u_j < 0$, which means using
$2 (q_{j+1} - q_j)$ when $q_j \in \left[0, q_\parallel-q_i\right]$.
This is not an issue for $q_i > q_\parallel$.
For both $q_\perp > 0$ and $q_\parallel > 0$ we perform a 2 dimensional
integration with
.. math::
u_{jk} = \sqrt{q_j^2 - (q + (k\Delta q_\parallel/L))^2}
\ \text{for}\ k = -L \ldots L
for $L$ = *n_height*. This gives
.. math::
W_{ij} = \frac{1}{2 \Delta q_\perp q_\parallel}
\sum_{k=-L}^L \Delta u_{jk}
\left(\frac{\Delta q_\parallel}{2 L + 1}\right)
"""
#np.set_printoptions(precision=6, linewidth=10000)
# The current algorithm is a midpoint rectangle rule.
q_edges = bin_edges(q_calc) # Note: requires q > 0
#q_edges[q_edges < 0.0] = 0.0 # clip edges below zero
weights = np.zeros((len(q), len(q_calc)), 'd')
#print(q_calc)
for i, (qi, w, h) in enumerate(zip(q, width, height)):
if w == 0. and h == 0.:
# Perfect resolution, so return the theory value directly.
# Note: assumes that q is a subset of q_calc. If qi need not be
# in q_calc, then we can do a weighted interpolation by looking
# up qi in q_calc, then weighting the result by the relative
# distance to the neighbouring points.
weights[i, :] = (q_calc == qi)
elif h == 0:
weights[i, :] = _q_perp_weights(q_edges, qi, w)
elif w == 0:
in_x = 1.0 * ((q_calc >= qi-h) & (q_calc <= qi+h))
abs_x = 1.0*(q_calc < abs(qi - h)) if qi < h else 0.
#print(qi - h, qi + h)
#print(in_x + abs_x)
weights[i, :] = (in_x + abs_x) * np.diff(q_edges) / (2*h)
else:
for k in range(-n_height, n_height+1):
weights[i, :] += _q_perp_weights(q_edges, qi+k*h/n_height, w)
weights[i, :] /= 2*n_height + 1
return weights.T
def _q_perp_weights(q_edges, qi, w):
# Convert bin edges from q to u
u_limit = np.sqrt(qi**2 + w**2)
u_edges = q_edges**2 - qi**2
u_edges[q_edges < abs(qi)] = 0.
u_edges[q_edges > u_limit] = u_limit**2 - qi**2
weights = np.diff(np.sqrt(u_edges))/w
#print("i, qi",i,qi,qi+width)
#print(q_calc)
#print(weights)
return weights
def pinhole_extend_q(q, q_width, nsigma=PINHOLE_N_SIGMA):
"""
Given *q* and *q_width*, find a set of sampling points *q_calc* so
that each point $I(q)$ has sufficient support from the underlying
function.
"""
try:
nsigma_low, nsigma_high = nsigma
except TypeError:
nsigma_low = nsigma_high = nsigma
q_min, q_max = np.min(q - nsigma_low*q_width), np.max(q + nsigma_high*q_width)
return linear_extrapolation(q, q_min, q_max)
def slit_extend_q(q, width, height):
"""
Given *q*, *width* and *height*, find a set of sampling points *q_calc* so
that each point I(q) has sufficient support from the underlying
function.
"""
q_min, q_max = np.min(q-height), np.max(np.sqrt((q+height)**2 + width**2))
return geometric_extrapolation(q, q_min, q_max)
def bin_edges(x):
"""
Determine bin edges from bin centers, assuming that edges are centered
between the bins.
Note: this uses the arithmetic mean, which may not be appropriate for
log-scaled data.
"""
if len(x) < 2 or (np.diff(x) < 0).any():
raise ValueError("Expected bins to be an increasing set")
edges = np.hstack([
x[0] - 0.5*(x[1] - x[0]), # first point minus half first interval
0.5*(x[1:] + x[:-1]), # mid points of all central intervals
x[-1] + 0.5*(x[-1] - x[-2]), # last point plus half last interval
])
return edges
def interpolate(q, max_step):
"""
Returns *q_calc* with points spaced at most max_step apart.
"""
step = np.diff(q)
index = step > max_step
if np.any(index):
inserts = []
for q_i, step_i in zip(q[:-1][index], step[index]):
n = np.ceil(step_i/max_step)
inserts.extend(q_i + np.arange(1, n)*(step_i/n))
# Extend a couple of fringes beyond the end of the data
inserts.extend(q[-1] + np.arange(1, 8)*max_step)
q_calc = np.sort(np.hstack((q, inserts)))
else:
q_calc = q
return q_calc
def linear_extrapolation(q, q_min, q_max):
"""
Extrapolate *q* out to [*q_min*, *q_max*] using the step size in *q* as
a guide. Extrapolation below uses about the same size as the first
interval. Extrapolation above uses about the same size as the final
interval.
Note that extrapolated values may be negative.
"""
q = np.sort(q)
if q_min + 2*MINIMUM_RESOLUTION < q[0]:
n_low = int(np.ceil((q[0]-q_min) / (q[1]-q[0]))) if q[1] > q[0] else 15
q_low = np.linspace(q_min, q[0], n_low+1)[:-1]
else:
q_low = []
if q_max - 2*MINIMUM_RESOLUTION > q[-1]:
n_high = int(np.ceil((q_max-q[-1]) / (q[-1]-q[-2]))) if q[-1] > q[-2] else 15
q_high = np.linspace(q[-1], q_max, n_high+1)[1:]
else:
q_high = []
return np.concatenate([q_low, q, q_high])
def geometric_extrapolation(q, q_min, q_max, points_per_decade=None):
r"""
Extrapolate *q* to [*q_min*, *q_max*] using geometric steps, with the
average geometric step size in *q* as the step size.
if *q_min* is zero or less then *q[0]/10* is used instead.
*points_per_decade* sets the ratio between consecutive steps such
that there will be $n$ points used for every factor of 10 increase
in *q*.
If *points_per_decade* is not given, it will be estimated as follows.
Starting at $q_1$ and stepping geometrically by $\Delta q$ to $q_n$
in $n$ points gives a geometric average of:
.. math::
\log \Delta q = (\log q_n - \log q_1) / (n - 1)
From this we can compute the number of steps required to extend $q$
from $q_n$ to $q_\text{max}$ by $\Delta q$ as:
.. math::
n_\text{extend} = (\log q_\text{max} - \log q_n) / \log \Delta q
Substituting:
.. math::
n_\text{extend} = (n-1) (\log q_\text{max} - \log q_n)
/ (\log q_n - \log q_1)
"""
q = np.sort(q)
if points_per_decade is None:
log_delta_q = (len(q) - 1) / (log(q[-1]) - log(q[0]))
else:
log_delta_q = log(10.) / points_per_decade
if q_min < q[0]:
if q_min < 0:
q_min = q[0]*MINIMUM_ABSOLUTE_Q
n_low = int(np.ceil(log_delta_q * (log(q[0])-log(q_min))))
q_low = np.logspace(log10(q_min), log10(q[0]), n_low+1)[:-1]
else:
q_low = []
if q_max > q[-1]:
n_high = int(np.ceil(log_delta_q * (log(q_max)-log(q[-1]))))
q_high = np.logspace(log10(q[-1]), log10(q_max), n_high+1)[1:]
else:
q_high = []
return np.concatenate([q_low, q, q_high])
############################################################################
# unit tests
############################################################################
def eval_form(q, form, pars):
"""
Return the SAS model evaluated at *q*.
*form* is the SAS model returned from :fun:`core.load_model`.
*pars* are the parameter values to use when evaluating.
"""
from sasmodels import direct_model
kernel = form.make_kernel([q])
theory = direct_model.call_kernel(kernel, pars)
kernel.release()
return theory
def gaussian(q, q0, dq, nsigma=2.5):
"""
Return the truncated Gaussian resolution function.
*q0* is the center, *dq* is the width and *q* are the points to evaluate.
"""
# Calculate the density of the tails; the resulting gaussian needs to be
# scaled by this amount in ordere to integrate to 1.0
two_tail_density = 2 * (1 + erf(-nsigma/sqrt(2)))/2
return exp(-0.5*((q-q0)/dq)**2)/(sqrt(2*pi)*dq)/(1-two_tail_density)
def romberg_slit_1d(q, width, height, form, pars):
"""
Romberg integration for slit resolution.
This is an adaptive integration technique. It is called with settings
that make it slow to evaluate but give it good accuracy.
"""
from scipy.integrate import romberg # type: ignore
par_set = {p.name for p in form.info.parameters.call_parameters}
if any(k not in par_set for k in pars.keys()):
extra = set(pars.keys()) - par_set
raise ValueError("bad parameters: [%s] not in [%s]"
% (", ".join(sorted(extra)),
", ".join(sorted(pars.keys()))))
if np.isscalar(width):
width = [width]*len(q)
if np.isscalar(height):
height = [height]*len(q)
_int_w = lambda w, qi: eval_form(sqrt(qi**2 + w**2), form, pars)
_int_h = lambda h, qi: eval_form(abs(qi+h), form, pars)
# If both width and height are defined, then it is too slow to use dblquad.
# Instead use trapz on a fixed grid, interpolated into the I(Q) for
# the extended Q range.
#_int_wh = lambda w, h, qi: eval_form(sqrt((qi+h)**2 + w**2), form, pars)
q_calc = slit_extend_q(q, np.asarray(width), np.asarray(height))
Iq = eval_form(q_calc, form, pars)
result = np.empty(len(q))
for i, (qi, w, h) in enumerate(zip(q, width, height)):
if h == 0.:
total = romberg(_int_w, 0, w, args=(qi,),
divmax=100, vec_func=True, tol=0, rtol=1e-8)
result[i] = total/w
elif w == 0.:
total = romberg(_int_h, -h, h, args=(qi,),
divmax=100, vec_func=True, tol=0, rtol=1e-8)
result[i] = total/(2*h)
else:
w_grid = np.linspace(0, w, 21)[None, :]
h_grid = np.linspace(-h, h, 23)[:, None]
u_sub = sqrt((qi+h_grid)**2 + w_grid**2)
f_at_u = np.interp(u_sub, q_calc, Iq)
#print(np.trapz(Iu, w_grid, axis=1))
total = np.trapz(np.trapz(f_at_u, w_grid, axis=1), h_grid[:, 0])
result[i] = total / (2*h*w)
# from scipy.integrate import dblquad
# r, err = dblquad(_int_wh, -h, h, lambda h: 0., lambda h: w,
# args=(qi,))
# result[i] = r/(w*2*h)
# r should be [float, ...], but it is [array([float]), array([float]),...]
return result
def romberg_pinhole_1d(q, q_width, form, pars, nsigma=2.5):
"""
Romberg integration for pinhole resolution.
This is an adaptive integration technique. It is called with settings
that make it slow to evaluate but give it good accuracy.
"""
from scipy.integrate import romberg # type: ignore
par_set = {p.name for p in form.info.parameters.call_parameters}
if any(k not in par_set for k in pars.keys()):
extra = set(pars.keys()) - par_set
raise ValueError("bad parameters: [%s] not in [%s]"
% (", ".join(sorted(extra)),
", ".join(sorted(pars.keys()))))
func = lambda q, q0, dq: eval_form(q, form, pars)*gaussian(q, q0, dq)
total = [romberg(func, max(qi-nsigma*dqi, 1e-10*q[0]), qi+nsigma*dqi,
args=(qi, dqi), divmax=100, vec_func=True,
tol=0, rtol=1e-8)
for qi, dqi in zip(q, q_width)]
return np.asarray(total).flatten()
class ResolutionTest(unittest.TestCase):
"""
Test the resolution calculations.
"""
def setUp(self):
self.x = 0.001*np.arange(1, 11)
self.y = self.Iq(self.x)
def Iq(self, q):
"Linear function for resolution unit test"
return 12.0 - 1000.0*q
def test_perfect(self):
"""
Perfect resolution and no smearing.
"""
resolution = Perfect1D(self.x)
theory = self.Iq(resolution.q_calc)
output = resolution.apply(theory)
np.testing.assert_equal(output, self.y)
def test_slit_zero(self):
"""
Slit smearing with perfect resolution.
"""
resolution = Slit1D(self.x, qx_width=0, qy_width=0, q_calc=self.x)
theory = self.Iq(resolution.q_calc)
output = resolution.apply(theory)
np.testing.assert_equal(output, self.y)
@unittest.skip("not yet supported")
def test_slit_high(self):
"""
Slit smearing with height 0.005
"""
resolution = Slit1D(self.x, qx_width=0, qy_width=0.005, q_calc=self.x)
theory = self.Iq(resolution.q_calc)
output = resolution.apply(theory)
answer = [
9.0618, 8.6402, 8.1187, 7.1392, 6.1528,
5.5555, 4.5584, 3.5606, 2.5623, 2.0000,
]
np.testing.assert_allclose(output, answer, atol=1e-4)
@unittest.skip("not yet supported")
def test_slit_both_high(self):
"""
Slit smearing with width < 100*height.
"""
q = np.logspace(-4, -1, 10)
resolution = Slit1D(q, qx_width=0.2, qy_width=np.inf)
theory = 1000*self.Iq(resolution.q_calc**4)
output = resolution.apply(theory)
answer = [
8.85785, 8.43012, 7.92687, 6.94566, 6.03660,
5.40363, 4.40655, 3.40880, 2.41058, 2.00000,
]
np.testing.assert_allclose(output, answer, atol=1e-4)
@unittest.skip("not yet supported")
def test_slit_wide(self):
"""
Slit smearing with width 0.0002
"""
resolution = Slit1D(self.x, qx_width=0.0002, qy_width=0, q_calc=self.x)
theory = self.Iq(resolution.q_calc)
output = resolution.apply(theory)
answer = [
11.0, 10.0, 9.0, 8.0, 7.0, 6.0, 5.0, 4.0, 3.0, 2.0,
]
np.testing.assert_allclose(output, answer, atol=1e-4)
@unittest.skip("not yet supported")
def test_slit_both_wide(self):
"""
Slit smearing with width > 100*height.
"""
resolution = Slit1D(self.x, qx_width=0.0002, qy_width=0.000001,
q_calc=self.x)
theory = self.Iq(resolution.q_calc)
output = resolution.apply(theory)
answer = [
11.0, 10.0, 9.0, 8.0, 7.0, 6.0, 5.0, 4.0, 3.0, 2.0,
]
np.testing.assert_allclose(output, answer, atol=1e-4)
def test_pinhole_zero(self):
"""
Pinhole smearing with perfect resolution
"""
resolution = Pinhole1D(self.x, 0.0*self.x)
theory = self.Iq(resolution.q_calc)
output = resolution.apply(theory)
np.testing.assert_equal(output, self.y)
# TODO: turn pinhole/slit demos into tests
@unittest.skip("suppress comparison with old version; pinhole calc changed")
def test_pinhole(self):
"""
Pinhole smearing with dQ = 0.001 [Note: not dQ/Q = 0.001]
"""
resolution = Pinhole1D(self.x, 0.001*np.ones_like(self.x),
q_calc=self.x)
theory = 12.0-1000.0*resolution.q_calc
output = resolution.apply(theory)
# Note: answer came from output of previous run. Non-integer
# values at ends come from the fact that q_calc does not
# extend beyond q, and so the weights don't balance.
answer = [
10.47037734, 9.86925860,
9., 8., 7., 6., 5., 4.,
3.13074140, 2.52962266,
]
np.testing.assert_allclose(output, answer, atol=1e-8)
class IgorComparisonTest(unittest.TestCase):
"""
Test resolution calculations against those returned by Igor.
"""
def setUp(self):
self.pars = TEST_PARS_PINHOLE_SPHERE
from sasmodels import core
self.model = core.load_model("sphere", dtype='double')
def _eval_sphere(self, pars, resolution):
from sasmodels import direct_model
kernel = self.model.make_kernel([resolution.q_calc])
theory = direct_model.call_kernel(kernel, pars)
result = resolution.apply(theory)
kernel.release()
return result
def _compare(self, q, output, answer, tolerance):
#err = (output - answer)/answer
#idx = abs(err) >= tolerance
#problem = zip(q[idx], output[idx], answer[idx], err[idx])
#print("\n".join(str(v) for v in problem))
np.testing.assert_allclose(output, answer, rtol=tolerance)
def test_perfect(self):
"""
Compare sphere model with NIST Igor SANS, no resolution smearing.
"""
pars = TEST_PARS_SLIT_SPHERE
data_string = TEST_DATA_SLIT_SPHERE
data = np.loadtxt(data_string.split('\n')).T
q, _, answer, _ = data
resolution = Perfect1D(q)
output = self._eval_sphere(pars, resolution)
self._compare(q, output, answer, 1e-6)
@unittest.skip("suppress comparison with old version; pinhole calc changed")
def test_pinhole(self):
"""
Compare pinhole resolution smearing with NIST Igor SANS
"""
pars = TEST_PARS_PINHOLE_SPHERE
data_string = TEST_DATA_PINHOLE_SPHERE
data = np.loadtxt(data_string.split('\n')).T
q, q_width, answer = data
resolution = Pinhole1D(q, q_width)
output = self._eval_sphere(pars, resolution)
# TODO: relative error should be lower
self._compare(q, output, answer, 3e-4)
@unittest.skip("suppress comparison with old version; pinhole calc changed")
def test_pinhole_romberg(self):
"""
Compare pinhole resolution smearing with romberg integration result.
"""
pars = TEST_PARS_PINHOLE_SPHERE
data_string = TEST_DATA_PINHOLE_SPHERE
pars['radius'] *= 5
data = np.loadtxt(data_string.split('\n')).T
q, q_width, answer = data
answer = romberg_pinhole_1d(q, q_width, self.model, pars)
## Getting 0.1% requires 5 sigma and 200 points per fringe
#q_calc = interpolate(pinhole_extend_q(q, q_width, nsigma=5),
# 2*np.pi/pars['radius']/200)
#tol = 0.001
## The default 2.5 sigma and no extra points gets 1%
q_calc = None # type: np.ndarray
tol = 0.01
resolution = Pinhole1D(q, q_width, q_calc=q_calc)
output = self._eval_sphere(pars, resolution)
if 0: # debug plot
import matplotlib.pyplot as plt # type: ignore
resolution = Perfect1D(q)
source = self._eval_sphere(pars, resolution)
plt.loglog(q, source, '.')
plt.loglog(q, answer, '-', hold=True)
plt.loglog(q, output, '-', hold=True)
plt.show()
self._compare(q, output, answer, tol)
def test_slit(self):
"""
Compare slit resolution smearing with NIST Igor SANS
"""
pars = TEST_PARS_SLIT_SPHERE
data_string = TEST_DATA_SLIT_SPHERE
data = np.loadtxt(data_string.split('\n')).T
q, delta_qv, _, answer = data
resolution = Slit1D(q, qx_width=delta_qv, qy_width=0)
output = self._eval_sphere(pars, resolution)
# TODO: eliminate Igor test since it is too inaccurate to be useful.
# This means we can eliminate the test data as well, and instead
# use a generated q vector.
self._compare(q, output, answer, 0.5)
def test_slit_romberg(self):
"""
Compare slit resolution smearing with romberg integration result.
"""
pars = TEST_PARS_SLIT_SPHERE
data_string = TEST_DATA_SLIT_SPHERE
data = np.loadtxt(data_string.split('\n')).T
q, delta_qv, _, answer = data
answer = romberg_slit_1d(q, delta_qv, 0., self.model, pars)
q_calc = slit_extend_q(interpolate(q, 2*np.pi/pars['radius']/20),
delta_qv[0], 0.)
resolution = Slit1D(q, qx_width=delta_qv, qy_width=0, q_calc=q_calc)
output = self._eval_sphere(pars, resolution)
# TODO: relative error should be lower
self._compare(q, output, answer, 0.025)
def test_ellipsoid(self):
"""
Compare romberg integration for ellipsoid model.
"""
from .core import load_model
pars = {
'scale':0.05,
'radius_polar':500, 'radius_equatorial':15000,
'sld':6, 'sld_solvent': 1,
}
form = load_model('ellipsoid', dtype='double')
q = np.logspace(log10(4e-5), log10(2.5e-2), 68)
width, height = 0.117, 0.
resolution = Slit1D(q, qx_width=width, qy_width=height)
answer = romberg_slit_1d(q, width, height, form, pars)
output = resolution.apply(eval_form(resolution.q_calc, form, pars))
# TODO: 10% is too much error; use better algorithm
#print(np.max(abs(answer-output)/answer))
self._compare(q, output, answer, 0.1)
#TODO: can sas q spacing be too sparse for the resolution calculation?
@unittest.skip("suppress sparse data test; not supported by current code")
def test_pinhole_sparse(self):
"""
Compare pinhole resolution smearing with NIST Igor SANS on sparse data
"""
pars = TEST_PARS_PINHOLE_SPHERE
data_string = TEST_DATA_PINHOLE_SPHERE
data = np.loadtxt(data_string.split('\n')).T
q, q_width, answer = data[:, ::20] # Take every nth point
resolution = Pinhole1D(q, q_width)
output = self._eval_sphere(pars, resolution)
self._compare(q, output, answer, 1e-6)
# pinhole sphere parameters
TEST_PARS_PINHOLE_SPHERE = {
'scale': 1.0, 'background': 0.01,
'radius': 60.0, 'sld': 1, 'sld_solvent': 6.3,
}
# Q, dQ, I(Q) calculated by NIST Igor SANS package
TEST_DATA_PINHOLE_SPHERE = """\
0.001278 0.0002847 2538.41176383
0.001562 0.0002905 2536.91820405
0.001846 0.0002956 2535.13182479
0.002130 0.0003017 2533.06217813
0.002414 0.0003087 2530.70378586
0.002698 0.0003165 2528.05024192
0.002982 0.0003249 2525.10408349
0.003266 0.0003340 2521.86667499
0.003550 0.0003437 2518.33907750
0.003834 0.0003539 2514.52246995
0.004118 0.0003646 2510.41798319
0.004402 0.0003757 2506.02690988
0.004686 0.0003872 2501.35067884
0.004970 0.0003990 2496.38678318
0.005253 0.0004112 2491.16237596
0.005537 0.0004237 2485.63911673
0.005821 0.0004365 2479.83657083
0.006105 0.0004495 2473.75676948
0.006389 0.0004628 2467.40145990
0.006673 0.0004762 2460.77293372
0.006957 0.0004899 2453.86724627
0.007241 0.0005037 2446.69623838
0.007525 0.0005177 2439.25775219
0.007809 0.0005318 2431.55421398
0.008093 0.0005461 2423.58785521
0.008377 0.0005605 2415.36158137
0.008661 0.0005750 2406.87009473
0.008945 0.0005896 2398.12841186
0.009229 0.0006044 2389.13360806
0.009513 0.0006192 2379.88958042
0.009797 0.0006341 2370.39776774
0.010080 0.0006491 2360.69528793
0.010360 0.0006641 2350.85169027
0.010650 0.0006793 2340.42023633
0.010930 0.0006945 2330.11206013
0.011220 0.0007097 2319.20109972
0.011500 0.0007251 2308.43503981
0.011780 0.0007404 2297.44820179
0.012070 0.0007558 2285.83853677
0.012350 0.0007713 2274.41290746
0.012640 0.0007868 2262.36219581
0.012920 0.0008024 2250.51169731
0.013200 0.0008180 2238.45596231
0.013490 0.0008336 2225.76495666
0.013770 0.0008493 2213.29618391
0.014060 0.0008650 2200.19110751
0.014340 0.0008807 2187.34050325
0.014620 0.0008965 2174.30529864
0.014910 0.0009123 2160.61632548
0.015190 0.0009281 2147.21038112
0.015470 0.0009440 2133.62023580
0.015760 0.0009598 2119.37907426
0.016040 0.0009757 2105.45234903
0.016330 0.0009916 2090.86319102
0.016610 0.0010080 2076.60576032
0.016890 0.0010240 2062.19214565
0.017180 0.0010390 2047.10550219
0.017460 0.0010550 2032.38715621
0.017740 0.0010710 2017.52560123
0.018030 0.0010880 2001.99124318
0.018310 0.0011040 1986.84662060
0.018600 0.0011200 1971.03389745
0.018880 0.0011360 1955.61395119
0.019160 0.0011520 1940.08291563
0.019450 0.0011680 1923.87672225
0.019730 0.0011840 1908.10656374
0.020020 0.0012000 1891.66297192
0.020300 0.0012160 1875.66789021
0.020580 0.0012320 1859.56357196
0.020870 0.0012490 1842.79468290
0.021150 0.0012650 1826.50064489
0.021430 0.0012810 1810.11533702
0.021720 0.0012970 1793.06840882
0.022000 0.0013130 1776.51153580
0.022280 0.0013290 1759.87201249
0.022570 0.0013460 1742.57354412
0.022850 0.0013620 1725.79397319
0.023140 0.0013780 1708.35831550
0.023420 0.0013940 1691.45256069
0.023700 0.0014110 1674.48561783
0.023990 0.0014270 1656.86525366
0.024270 0.0014430 1639.79847285
0.024550 0.0014590 1622.68887088
0.024840 0.0014760 1604.96421100
0.025120 0.0014920 1587.85768129
0.025410 0.0015080 1569.99297335
0.025690 0.0015240 1552.84580279
0.025970 0.0015410 1535.54074115
0.026260 0.0015570 1517.75249337
0.026540 0.0015730 1500.40115023
0.026820 0.0015900 1483.03632237
0.027110 0.0016060 1465.05942429
0.027390 0.0016220 1447.67682181
0.027670 0.0016390 1430.46495191
0.027960 0.0016550 1412.49232282
0.028240 0.0016710 1395.13182318
0.028520 0.0016880 1377.93439837
0.028810 0.0017040 1359.99528971
0.029090 0.0017200 1342.67274512
0.029370 0.0017370 1325.55375609
"""
# Slit sphere parameters
TEST_PARS_SLIT_SPHERE = {
'scale': 0.01, 'background': 0.01,
'radius': 60000, 'sld': 1, 'sld_solvent': 4,
}
# Q dQ I(Q) I_smeared(Q)
TEST_DATA_SLIT_SPHERE = """\
2.26097e-05 0.117 5.5781372896e+09 1.4626077708e+06
2.53847e-05 0.117 5.0363141458e+09 1.3117318023e+06
2.81597e-05 0.117 4.4850108103e+09 1.1594863713e+06
3.09347e-05 0.117 3.9364658459e+09 1.0094881630e+06
3.37097e-05 0.117 3.4019975074e+09 8.6518941303e+05
3.92597e-05 0.117 2.4139519814e+09 6.0232158311e+05
4.48097e-05 0.117 1.5816877820e+09 3.8739994090e+05
5.03597e-05 0.117 9.3715407224e+08 2.2745304775e+05
5.59097e-05 0.117 4.8387917428e+08 1.2101295768e+05
6.14597e-05 0.117 2.0193586928e+08 6.0055107771e+04
6.70097e-05 0.117 5.5886110911e+07 3.2749521065e+04
7.25597e-05 0.117 3.7782348010e+06 2.6350963616e+04
7.81097e-05 0.117 5.3407817904e+06 2.9624963314e+04
8.36597e-05 0.117 2.7975485523e+07 3.4403962254e+04
8.92097e-05 0.117 4.9845448282e+07 3.6130017903e+04
9.47597e-05 0.117 6.0092588905e+07 3.3495107849e+04
1.00310e-04 0.117 5.6823430831e+07 2.7475726279e+04
1.05860e-04 0.117 4.3857024036e+07 2.0144282226e+04
1.11410e-04 0.117 2.7277144760e+07 1.3647403260e+04
1.22510e-04 0.117 3.3119334113e+06 6.6519711526e+03
1.33610e-04 0.117 1.4412859402e+06 6.9726212813e+03
1.44710e-04 0.117 8.5620162463e+06 8.1441335775e+03
1.55810e-04 0.117 9.6957429033e+06 6.4559996521e+03
1.66910e-04 0.117 4.3818341914e+06 3.6252154156e+03
1.78010e-04 0.117 2.7448997387e+05 2.4006505342e+03
1.89110e-04 0.117 8.0472009936e+05 2.8187789089e+03
2.00210e-04 0.117 2.8149552834e+06 3.0915662855e+03
2.11310e-04 0.117 2.7510907861e+06 2.3722530293e+03
2.22410e-04 0.117 1.0053133293e+06 1.4473468311e+03
2.33510e-04 0.117 5.8428305052e+03 1.2048540556e+03
2.44610e-04 0.117 5.1699305004e+05 1.4625670042e+03
2.55710e-04 0.117 1.2120227268e+06 1.5010705973e+03
2.66810e-04 0.117 9.7896842846e+05 1.1336343426e+03
2.77910e-04 0.117 2.5507264791e+05 8.1848818080e+02
3.05660e-04 0.117 5.2403101181e+05 7.4913374357e+02
3.33410e-04 0.117 5.8699343809e+04 4.4669964560e+02
3.61160e-04 0.117 3.0844327150e+05 4.6774007542e+02
3.88910e-04 0.117 8.3360142970e+03 2.7169550220e+02
4.16660e-04 0.117 1.8630080583e+05 3.0710983679e+02
4.44410e-04 0.117 3.1616804732e-01 1.7959006831e+02
4.72160e-04 0.117 1.1299016314e+05 2.0763952339e+02
4.99910e-04 0.117 2.9952522747e+03 1.2536542765e+02
5.27660e-04 0.117 6.7625695649e+04 1.4013969777e+02
5.55410e-04 0.117 7.6927460089e+03 8.2145593180e+01
6.10910e-04 0.117 1.1229057779e+04 8.4519745643e+01
6.66410e-04 0.117 1.3035567943e+04 8.1554625609e+01
7.21910e-04 0.117 1.3309931343e+04 7.4437319172e+01
7.77410e-04 0.117 1.2462626212e+04 6.4697088261e+01
8.32910e-04 0.117 1.0912927143e+04 5.3773301044e+01
8.88410e-04 0.117 9.0172597469e+03 4.2843375753e+01
9.43910e-04 0.117 7.0496495917e+03 3.2771032724e+01
9.99410e-04 0.117 5.2030483682e+03 2.4113557144e+01
1.05491e-03 0.117 3.5988976711e+03 1.7160773658e+01
1.11041e-03 0.117 2.2996060652e+03 1.2016626459e+01
1.22141e-03 0.117 6.4766590598e+02 6.0373017740e+00
1.33241e-03 0.117 4.1963483264e+01 4.5215452974e+00
1.44341e-03 0.117 6.3370708246e+01 5.1054681903e+00
1.55441e-03 0.117 3.0736750577e+02 5.9176165298e+00
1.66541e-03 0.117 5.0327682399e+02 5.9815000189e+00
1.77641e-03 0.117 5.4084331454e+02 5.1634639625e+00
1.88741e-03 0.117 4.3488671756e+02 3.8535158148e+00
1.99841e-03 0.117 2.6322287860e+02 2.5824997753e+00
2.10941e-03 0.117 1.0793633150e+02 1.7315517194e+00
2.22041e-03 0.117 1.8474448850e+01 1.4077213604e+00
2.33141e-03 0.117 1.5864062279e+00 1.4771560682e+00
2.44241e-03 0.117 3.2267213848e+01 1.6916253448e+00
2.55341e-03 0.117 7.4289116207e+01 1.8274751193e+00
2.66441e-03 0.117 9.9000521929e+01 1.7706812289e+00
"""
def main():
"""
Run tests given is sys.argv.
Returns 0 if success or 1 if any tests fail.
"""
import sys
import xmlrunner # type: ignore
suite = unittest.TestSuite()
suite.addTest(unittest.defaultTestLoader.loadTestsFromModule(sys.modules[__name__]))
runner = xmlrunner.XMLTestRunner(output='logs')
result = runner.run(suite)
return 1 if result.failures or result.errors else 0
############################################################################
# usage demo
############################################################################
def _eval_demo_1d(resolution, title):
import sys
from sasmodels import core
from sasmodels import direct_model
name = sys.argv[1] if len(sys.argv) > 1 else 'cylinder'
if name == 'cylinder':
pars = {'length':210, 'radius':500, 'background': 0}
elif name == 'teubner_strey':
pars = {'a2':0.003, 'c1':-1e4, 'c2':1e10, 'background':0.312643}
elif name in ('sphere', 'spherepy'):
pars = TEST_PARS_SLIT_SPHERE
elif name == 'ellipsoid':
pars = {
'scale':0.05, 'background': 0,
'r_polar':500, 'r_equatorial':15000,
'sld':6, 'sld_solvent': 1,
}
else:
pars = {}
model_info = core.load_model_info(name)
model = core.build_model(model_info)
kernel = model.make_kernel([resolution.q_calc])
theory = direct_model.call_kernel(kernel, pars)
Iq = resolution.apply(theory)
if isinstance(resolution, Slit1D):
width, height = resolution.qx_width, resolution.qy_width
Iq_romb = romberg_slit_1d(resolution.q, width, height, model, pars)
else:
dq = resolution.q_width
Iq_romb = romberg_pinhole_1d(resolution.q, dq, model, pars)
import matplotlib.pyplot as plt # type: ignore
plt.loglog(resolution.q_calc, theory, label='unsmeared')
plt.loglog(resolution.q, Iq, label='smeared', hold=True)
plt.loglog(resolution.q, Iq_romb, label='romberg smeared', hold=True)
plt.legend()
plt.title(title)
plt.xlabel("Q (1/Ang)")
plt.ylabel("I(Q) (1/cm)")
def demo_pinhole_1d():
"""
Show example of pinhole smearing.
"""
q = np.logspace(-4, np.log10(0.2), 400)
q_width = 0.1*q
resolution = Pinhole1D(q, q_width)
_eval_demo_1d(resolution, title="10% dQ/Q Pinhole Resolution")
def demo_slit_1d():
"""
Show example of slit smearing.
"""
q = np.logspace(-4, np.log10(0.2), 100)
w = h = 0.
#w = 0.000000277790
w = 0.0277790
#h = 0.00277790
#h = 0.0277790
resolution = Slit1D(q, w, h)
_eval_demo_1d(resolution, title="(%g,%g) Slit Resolution"%(w, h))
def demo():
"""
Run the resolution demos.
"""
import matplotlib.pyplot as plt # type: ignore
plt.subplot(121)
demo_pinhole_1d()
#plt.yscale('linear')
plt.subplot(122)
demo_slit_1d()
#plt.yscale('linear')
plt.show()
if __name__ == "__main__":
#demo()
main()
|
SasView/sasmodels
|
sasmodels/resolution.py
|
Python
|
bsd-3-clause
| 42,963
|
[
"Gaussian"
] |
c02890f0ed8c300b6a9b6b73ece407e7ec6e474f2c52a51dd3f72ab6cd0373f0
|
# -*- coding: utf-8 -*-
#
# Gramps - a GTK+/GNOME based genealogy program
#
# Copyright (C) 2003-2006 Donald N. Allingham
# Copyright (C) 2008 Brian G. Matherly
# Copyright (C) 2010 Andrew I Baznikin
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
#
# $Id$
#
# Written by Egyeki Gergely <egeri@elte.hu>, 2004
"""
Specific classes for relationships.
"""
#-------------------------------------------------------------------------
#
# GRAMPS modules
#
#-------------------------------------------------------------------------
from gramps.gen.lib import Person
import gramps.gen.relationship
#-------------------------------------------------------------------------
#
# Shared constants
#
#-------------------------------------------------------------------------
_level = \
["", "", "másod", "harmad", "negyed", "ötöd", "hatod",
"heted", "nyolcad", "kilenced", "tized", "tizenegyed", "tizenketted",
"tizenharmad", "tizennegyed", "tizenötöd", "tizenhatod",
"tizenheted", "tizennyolcad", "tizenkilenced", "huszad","huszonegyed"]
#-------------------------------------------------------------------------
#
# Specific relationship functions
#
#-------------------------------------------------------------------------
class RelationshipCalculator(gramps.gen.relationship.RelationshipCalculator):
"""
RelationshipCalculator Class
"""
def __init__(self):
gramps.gen.relationship.RelationshipCalculator.__init__(self)
def get_parents (self, level):
if level == 0: return ""
elif level == 1: return "szülei"
elif level == 2: return "nagyszülei"
elif level == 3: return "dédszülei"
elif level == 4: return "ükszülei"
else: return "%d. szülei" % level
def get_father (self, level):
if level == 0: return ""
elif level == 1: return "apja"
elif level == 2: return "nagyapja"
elif level == 3: return "dédapja"
elif level == 4: return "ükapja"
else: return "%d. ükapja" % level
def get_mother (self, level):
if level == 0: return ""
elif level == 1: return "anyja"
elif level == 2: return "nagyanyja"
elif level == 3: return "dédanyja"
elif level == 4: return "ükanyja"
else: return "%d. ükanyja" % level
def get_son (self, level):
if level == 0: return ""
elif level == 1: return "fia"
elif level == 2: return "unokája"
elif level == 3: return "dédunokája"
elif level == 4: return "ükunokája"
else: return "%d. unokája" % level
def get_daughter (self, level):
if level == 0: return ""
elif level == 1: return "lánya"
elif level <= len([level]): return self.get_son(level)
def get_uncle (self, level):
if level == 0: return ""
elif level == 1: return "testvére"
elif level == 2: return "nagybátyja"
else: return "%d. nagybátyja" % level
def get_aunt (self, level):
if level == 0: return ""
elif level == 1: return "testvére"
elif level == 2: return "nagynénje"
else: return "%d. nagynénje" % level
def get_nephew (self, level):
if level == 0: return ""
elif level == 1: return "unokája"
else: return "%d. unokája" % level
def get_niece(self, level):
return self.get_nephew(level)
def get_male_cousin (self, level):
if level == 0: return ""
elif level == 1: return "unokatestvére"
else: return "%d. unokatestvére" % level
def get_female_cousin (self, level):
return self.get_male_cousin(level)
#----------------------------------------------
#
# brother and sister age differences
#
#----------------------------------------------
def get_age_comp(self, orig_person, other_person):
# in 3.X api we can't know persons age
return 0
def get_age_brother (self, level):
if level == 0 : return "testvére"
elif level == 1 : return "öccse"
else : return "bátyja"
def get_age_sister (self, level):
if level == 0 : return "testvére"
elif level == 1 : return "húga"
else : return "nővére"
#---------------------------------------------
#
# en: father-in-law, mother-in-law, son-in-law, daughter-in-law
# hu: após, anyós, vő, meny
#
#---------------------------------------------
def is_fathermother_in_law(self, orig, other):
for f in other.get_family_handle_list():
family = self.db.get_family_from_handle(f)
sp_id = None
if family:
if other == family.get_father_handle():
sp_id = family.get_mother_handle()
elif other == family.get_mother_handle():
sp_id = family.get_father_handle()
for g in orig.get_family_handle_list():
family = self.db.get_family_from_handle(g)
if family:
if sp_id in family.get_child_handle_list():
return 1
return 0
#------------------------------------------------------------------------
#
# hu: sógor, sógornő
# en: brother-in-law, sister-in-law
#
#------------------------------------------------------------------------
def is_brothersister_in_law(self, orig, other):
for f in orig.get_family_handle_list():
family = self.db.get_family_from_handle(f)
sp_id = None
if family:
if orig == family.get_father_handle():
sp_id = family.get_mother_handle()
elif other == family.get_mother_handle():
sp_id = family.get_father_handler()
p = other.get_main_parents_family_handle()
family = self.db.get_family_from_handle(p)
if family:
c = family.get_child_handle_list()
if (other.get_handle() in c) and (sp_id in c):
return 1
return 0
#-------------------------------------------------------------------------
#
# get_relationship
#
#-------------------------------------------------------------------------
def get_relationship(self, secondRel, firstRel, orig_person, other_person, in_law_a, in_law_b):
"""
returns a string representing the relationshp between the two people,
along with a list of common ancestors (typically father,mother)
"""
common = ""
if in_law_a or in_law_a:
if firstRel == 0 and secondRel == 0:
if other_person == Person.MALE:
return ("apósa","")
elif other_person == Person.FEMALE:
return ("anyósa","")
else:
return ("apósa vagy anyósa","")
elif secondRel == 0:
if orig_person == Person.MALE:
return ("veje","")
elif orig_person == Person.FEMALE:
return ("menye","")
else:
return ("veje vagy menye","")
elif firstRel == 1:
if other_person == Person.MALE:
return ("sógora","")
elif other_person == Person.FEMALE:
return ("sógornője","")
else:
return ("sógora vagy sógornője","")
if firstRel == 0:
if secondRel == 0:
return ('', common)
elif other_person == Person.MALE:
return (self.get_father(secondRel), common)
else:
return (self.get_mother(secondRel), common)
elif secondRel == 0:
if other_person == Person.MALE:
return (self.get_son(firstRel), common)
else:
return (self.get_daughter(firstRel), common)
elif firstRel == 1:
if other_person == Person.MALE:
if secondRel == 1:
return (self.get_age_brother(self.get_age_comp(orig_person, other_person)), common)
else :return (self.get_uncle(secondRel), common)
else:
if secondRel == 1:
return (self.get_age_sister(self.get_age_comp(orig_person, other_person)), common)
else :return (self.get_aunt(secondRel), common)
elif secondRel == 1:
if other_person == Person.MALE:
return (self.get_nephew(firstRel-1), common)
else:
return (self.get_niece(firstRel-1), common)
else:
if other_person == Person.MALE:
return (self.get_male_cousin(firstRel-1), common)
else:
return (self.get_female_cousin(firstRel-1), common)
def get_single_relationship_string(self, Ga, Gb, gender_a, gender_b,
reltocommon_a, reltocommon_b,
only_birth=True,
in_law_a=False, in_law_b=False):
return self.get_relationship(Ga, Gb, gender_a, gender_b, in_law_a, in_law_b)[0]
def get_sibling_relationship_string(self, sib_type, gender_a, gender_b,
in_law_a=False, in_law_b=False):
return self.get_relationship(1, 1, gender_a, gender_b, in_law_a, in_law_b)[0]
if __name__ == "__main__":
# Test function. Call it as follows from the command line (so as to find
# imported modules):
# export PYTHONPATH=/path/to/gramps/src
# python src/plugins/rel/rel_hu.py
# (Above not needed here)
"""TRANSLATORS, copy this if statement at the bottom of your
rel_xx.py module, and test your work with:
python src/plugins/rel/rel_xx.py
"""
from gramps.gen.relationship import test
RC = RelationshipCalculator()
test(RC, True)
|
arunkgupta/gramps
|
gramps/plugins/rel/rel_hu.py
|
Python
|
gpl-2.0
| 10,835
|
[
"Brian"
] |
3f5912c685d1b6fdcda57e6c8c0ed7ce3304ab2a657ce687c31b276fcd012c2e
|
# This file is part of Merlin.
# Merlin is the Copyright (C)2008,2009,2010 of Robin K. Hansen, Elliot Rosemarine, Andreas Jacobsen.
# Individual portions may be copyright by individual contributors, and
# are included in this collective work with permission of the copyright
# owners.
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2 of the License, or
# (at your option) any later version.
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
import re
from Core.paconf import PA
from Core.db import session
from Core.maps import Updates, Galaxy, Planet, Attack
from Core.loadable import loadable, route
class editattack(loadable):
usage = " [<id> add|remove <coordlist>] | [<id> land <tick|eta>] | [<id> comment <comment>] [<id> waves <waves>]"
access = "half"
@route(r"(\d+)\s+add\s+([. :\-\d,]+)")
def add(self, message, user, params):
id = int(params.group(1))
attack = Attack.load(id)
if attack is None:
message.alert("No attack exists with id %d" %(id))
return
for coord in re.findall(loadable.coord, params.group(2)):
if not coord[4]:
galaxy = Galaxy.load(coord[0],coord[2])
if galaxy:
attack.addGalaxy(galaxy)
else:
planet = Planet.load(coord[0],coord[2],coord[4])
if planet:
attack.addPlanet(planet)
session.commit()
message.reply(str(attack))
@route(r"(\d+)\s+rem(?:ove)?\s+([. :\-\d,]+)")
def remove(self, message, user, params):
id = int(params.group(1))
attack = Attack.load(id)
if attack is None:
message.alert("No attack exists with id %d" %(id))
return
for coord in re.findall(loadable.coord, params.group(2)):
if not coord[4]:
galaxy = Galaxy.load(coord[0],coord[2], active=False)
if galaxy:
attack.removeGalaxy(galaxy)
else:
planet = Planet.load(coord[0],coord[2],coord[4], active=False)
if planet:
attack.removePlanet(planet)
if not len(attack.planets):
session.delete(attack)
session.commit()
if attack in session:
message.reply(str(attack))
else:
message.reply("Deleted Attack %d LT: %d | %s" %(attack.id,attack.landtick,attack.comment,))
@route(r"(\d+)\s+land\s+(\d+)")
def land(self, message, user, params):
id = int(params.group(1))
attack = Attack.load(id)
if attack is None:
message.alert("No attack exists with id %d" %(id))
return
tick = Updates.current_tick()
when = int(params.group(2))
if when == 0:
session.delete(attack)
session.commit()
message.reply("Deleted Attack %d LT: %d | %s" %(attack.id,attack.landtick,attack.comment,))
return
if when < PA.getint("numbers", "protection"):
when += tick
elif when <= tick:
message.alert("Can not create attacks in the past. You wanted tick %s, but current tick is %s." % (when, tick,))
return
if when > 32767:
when = 32767
old = attack.landtick
attack.landtick = when
session.commit()
message.reply("Changed LT for attack %d from %d to %d"%(id,old,when))
@route(r"(\d+)\s+comment\s+(\S.*)")
def comment(self, message, user, params):
id = int(params.group(1))
attack = Attack.load(id)
if attack is None:
message.alert("No attack exists with id %d" %(id))
return
if params.group(2) in self.nulls:
attack.comment = ""
else:
attack.comment = params.group(2)
session.commit()
message.reply("Updated comment for attack %d: %s"%(id,attack.comment,))
@route(r"(\d+)\s+waves\s+(\d+)")
def waves(self, message, user, params):
id = int(params.group(1))
attack = Attack.load(id)
if attack is None:
message.alert("No attack exists with id %d" %(id))
return
attack.waves = params.group(2)
session.commit()
message.reply("Updated waves for attack %d: %d"%(id,attack.waves,))
|
d7415/merlin
|
Hooks/target/editattack.py
|
Python
|
gpl-2.0
| 5,062
|
[
"Galaxy"
] |
d1a9f25ee51f0b87163daa38b4d398e12b1bab32dd8cfebd08b25c63a12a5109
|
"""A setuptools based setup module.
See:
https://packaging.python.org/en/latest/distributing.html
https://github.com/pypa/sampleproject
"""
# Always prefer setuptools over distutils
from setuptools import setup, find_packages
# To use a consistent encoding
from codecs import open
from os import path
here = path.abspath(path.dirname(__file__))
# Get the long description from the README file
with open(path.join(here, 'README.md'), encoding='utf-8') as f:
long_description = f.read()
# Arguments marked as "Required" below must be included for upload to PyPI.
# Fields marked as "Optional" may be commented out.
setup(
# This is the name of your project. The first time you publish this
# package, this name will be registered for you. It will determine how
# users can install this project, e.g.:
#
# $ pip install sampleproject
#
# And where it will live on PyPI: https://pypi.org/project/sampleproject/
#
# There are some restrictions on what makes a valid project name
# specification here:
# https://packaging.python.org/specifications/core-metadata/#name
name='pylivecoding', # Required
# Versions should comply with PEP 440:
# https://www.python.org/dev/peps/pep-0440/
#
# For a discussion on single-sourcing the version across setup.py and the
# project code, see
# https://packaging.python.org/en/latest/single_source_version.html
version='0.0.2', # Required
# This is a one-line description or tagline of what your project does. This
# corresponds to the "Summary" metadata field:
# https://packaging.python.org/specifications/core-metadata/#summary
description='live coding library for Python 3', # Required
# This is an optional longer description of your project that represents
# the body of text which users will see when they visit PyPI.
#
# Often, this is the same as your README, so you can just read it in from
# that file directly (as we have already done above)
#
# This field corresponds to the "Description" metadata field:
# https://packaging.python.org/specifications/core-metadata/#description-optional
long_description='This library has the ability to reload python modules during execution and update existing '
'objects. This way you edit code, reload it and see the results immediately with no need to '
'restart your code. More info and documentation can be found at the home page', # Optional
# Denotes that our long_description is in Markdown; valid values are
# text/plain, text/x-rst, and text/markdown
#
# Optional if long_description is written in reStructuredText (rst) but
# required for plain-text or Markdown; if unspecified, "applications should
# attempt to render [the long_description] as text/x-rst; charset=UTF-8 and
# fall back to text/plain if it is not valid rst" (see link below)
#
# This field corresponds to the "Description-Content-Type" metadata field:
# https://packaging.python.org/specifications/core-metadata/#description-content-type-optional
long_description_content_type='text/markdown', # Optional (see note above)
# This should be a valid link to your project's main homepage.
#
# This field corresponds to the "Home-Page" metadata field:
# https://packaging.python.org/specifications/core-metadata/#home-page-optional
url='https://github.com/kilon/pylivecoding.git', # Optional
# This should be your name or the name of the organization which owns the
# project.
author='kilon', # Optional
# This should be a valid email address corresponding to the author listed
# above.
author_email='kilon.alios@gmail.com', # Optional
# Classifiers help users find your project by categorizing it.
#
# For a list of valid classifiers, see https://pypi.org/classifiers/
classifiers=[ # Optional
# How mature is this project? Common values are
# 3 - Alpha
# 4 - Beta
# 5 - Production/Stable
'Development Status :: 3 - Alpha',
# Indicate who your project is intended for
'Intended Audience :: Developers',
'Topic :: Software Development :: Compilers',
# Pick your license as you wish
'License :: OSI Approved :: MIT License',
# Specify the Python versions you support here. In particular, ensure
# that you indicate whether you support Python 2, Python 3 or both.
'Programming Language :: Python :: 3.5',
'Programming Language :: Python :: 3.6',
],
# This field adds keywords for your project which will appear on the
# project page. What does your project relate to?
#
# Note that this is a string of words separated by whitespace, not a list.
keywords='live code smalltalk python livecoding coding reload', # Optional
# You can just specify package directories manually here if your project is
# simple. Or you can use find_packages().
#
# Alternatively, if you just want to distribute a single Python file, use
# the `py_modules` argument instead as follows, which will expect a file
# called `my_module.py` to exist:
#
# py_modules=["my_module"],
#
packages=find_packages(exclude=['contrib', 'tests']), # Required
# This field lists other packages that your project depends on to run.
# Any package you put here will be installed by pip when your project is
# installed, so they must be valid existing projects.
#
# For an analysis of "install_requires" vs pip's requirements files see:
# https://packaging.python.org/en/latest/requirements.html
install_requires=[], # Optional
# List additional groups of dependencies here (e.g. development
# dependencies). Users will be able to install these using the "extras"
# syntax, for example:
#
# $ pip install sampleproject[dev]
#
# Similar to `install_requires` above, these must be valid existing
# projects.
extras_require={
},
python_requires='>=3',
# If there are data files included in your packages that need to be
# installed, specify them here.
#
# If using Python 2.6 or earlier, then these have to be included in
# MANIFEST.in as well.
package_data={
},
# Although 'package_data' is the preferred approach, in some case you may
# need to place data files outside of your packages. See:
# http://docs.python.org/3.4/distutils/setupscript.html#installing-additional-files
#
# In this case, 'data_file' will be installed into '<sys.prefix>/my_data'
data_files=[], # Optional
# To provide executable scripts, use entry points in preference to the
# "scripts" keyword. Entry points provide cross-platform support and allow
# `pip` to create the appropriate form of executable for the target
# platform.
#
# For example, the following would provide a command called `sample` which
# executes the function `main` from this package when invoked:
entry_points={
},
# List additional URLs that are relevant to your project as a dict.
#
# This field corresponds to the "Project-URL" metadata fields:
# https://packaging.python.org/specifications/core-metadata/#project-url-multiple-use
#
# Examples listed include a pattern for specifying where the package tracks
# issues, where the source is hosted, where to say thanks to the package
# maintainers, and where to support the project financially. The key is
# what's used to render the link text on PyPI.
project_urls={
},
)
|
kilon/pylivecoding
|
setup.py
|
Python
|
mit
| 7,680
|
[
"VisIt"
] |
afac291e323818f6008bbc2cfc315ef03864d9289fbc6bd10d15b6e37d797361
|
#!/usr/bin/env python
# encoding: utf-8
"""
bed_from_genbank.py
grab the gene records from a genbank file (edit for other record types).
- requires: biopython
"""
from __future__ import division
import os
from sys import argv
def parse_fasta(filename):
s = open(filename)
header = ""
record = ""
inrecord = False
for line in s:
if inrecord and not line.startswith(">"):
record +=(line.strip())
elif inrecord and line.startswith(">"):
yield header,record
inrecord = False
header = ""
record = ""
if line.startswith(">"):
header = line.strip()
inrecord = True
yield header,record
def readinput(file1):
s = open(file1)
for line in s:
yield line.strip()
s.close()
def main(infile):
winner = 0
recname = ""
for header,record in parse_fasta(infile):
rec_len = len(record)
cg_cont = (record.count("C")+record.count("G"))/rec_len
print header, rec_len, round(cg_cont,5)
if cg_cont > winner:
winner = round(cg_cont,8)
recname = header
result = recname, winner*100
return result
def writeout(results):
out_file = open("output.txt","w")
print results
for elem in results:
out_file.write(str(elem).lstrip(">"))
out_file.write("\n")
out_file.close()
if __name__ == "__main__":
if len(argv) > 1 :
results = main(argv[1])
else:
results = main('sample.txt')
writeout(results)
|
KoenHoogendoorn1994/rosalind
|
5.py
|
Python
|
gpl-3.0
| 1,593
|
[
"Biopython"
] |
13427c6d9fac503fd61a6be66570470e3cfeecc096b5596f382205b04482c368
|
##########################################################################
# Ganga Project. https://github.com/ganga-devs/ganga
#
##########################################################################
from GangaCore.GPIDev.Schema import Schema, Version, SimpleItem
from GangaCore.GPIDev.Adapters.IVirtualization import IVirtualization
from GangaCore.GPIDev.Adapters.IGangaFile import IGangaFile
class Singularity(IVirtualization):
"""
The Singularity class can be used for either Singularity or Docker images.
It requires that singularity is installed on the worker node.
For Singularity images you provide the image name and tag from Singularity
hub like
j=Job()
j.application=Executable(exe=File('my/full/path/to/executable'))
j.virtualization = Singularity("shub://image:tag")
Notice how the executable is given as a `File` object. This ensures that it
is copied to the working directory and thus will be accessible inside the
container.
The container can also be provided as a Docker image from a repository. The
default repository is Docker hub.
j.virtualization = Singularity("docker://gitlab-registry.cern.ch/lhcb-core/lbdocker/centos7-build:v3")
j.virtualization = Singularity("docker://fedora:latest")
Another option is to provide a `GangaFile` Object which points to a
singularity file. In that case the singularity image file will be copied to
the worker node. The first example is with an image located on some shared
disk. This will be effective for running on a local backend or a batch
system with a shared disk system.
imagefile = SharedFile('myimage.sif', locations=['/my/full/path/myimage.sif'])
j.virtualization = Singularity(image= imagefile)
while a second example is with an image located in the Dirac Storage
Element. This will be effective when using the Dirac backend.
imagefile = DiracFile('myimage.sif', lfn=['/some/lfn/path'])
j.virtualization = Singularity(image= imagefile)
If the image is a private image, the username and password of the deploy
token can be given like the example below. Look inside Gitlab setting for
how to set this up. The token will only need access to the images and
nothing else.
j.virtualization.tokenuser = 'gitlab+deploy-token-123'
j.virtualization.tokenpassword = 'gftrh84dgel-245^ghHH'
Directories can be mounted from the host to the container using key-value
pairs to the mounts option. If the directory is not available on the host, a
warning will be written to stderr of the job and no mount will be attempted.
j.virtualization.mounts = {'/cvmfs':'/cvmfs'}
By default the container is started in singularity with the `--nohome`
option. Extra options can be provided through the `options` attribute. See
the Singularity documentation for what is possible.
If the singularity binary is not available in the PATH on the remote node - or has a different name,
it is possible to give the name of it like
j.virtualization.binary='/cvmfs/oasis.opensciencegrid.org/mis/singularity/current/bin/singularity'
"""
_name = 'Singularity'
_schema = IVirtualization._schema.inherit_copy()
_schema.datadict['image'] = SimpleItem(defvalue="",
typelist=[str,'GangaCore.GPIDev.Adapters.IGangaFile.IGangaFile'],
doc='Link to the container image. This can either be a singularity URL or a GangaFile object')
_schema.datadict['binary'] = SimpleItem(defvalue="singularity",
typelist=[str],
doc='The virtualization binary itself. Can be an absolute path if required.')
def modify_script(self, script, sandbox=False):
"""Overides parent's modify_script function
Arguments other than self:
script - Script that need to be modified
Return value: modified script"""
if isinstance(self.image, IGangaFile):
extra = 'virtualization_image = ' + repr(self.image.namePattern) + '\n'
else:
extra = 'virtualization_image = ' + repr(self.image) + '\n'
extra = extra + 'virtualization_user = ' + repr(self.tokenuser) + '\n'
extra = extra + 'virtualization_password = ' + repr(self.tokenpassword) + '\n'
extra = extra + 'virtualization_mounts = ' + repr(self.mounts) + '\n'
extra = extra + 'virtualization_options = ' + repr(self.options) + '\n'
extra = extra + 'virtualization_binary = ' + repr(self.binary) + '\n'
extra = extra + """
print("Using singularity")
import stat
if not ( ('XDG_RUNTIME_DIR' in runenv) and
os.path.isdir(runenv['XDG_RUNTIME_DIR']) and
(stat.S_IMODE(os.stat(runenv['XDG_RUNTIME_DIR']).st_mode) == 0o700) and
os.access(runenv['XDG_RUNTIME_DIR'], os.W_OK) ):
os.mkdir('.xdg', 0o700)
runenv['XDG_RUNTIME_DIR'] = os.path.join(os.getcwd(), '.xdg')
options = []
if virtualization_user:
runenv["SINGULARITY_DOCKER_USERNAME"] = virtualization_user
runenv["SINGULARITY_DOCKER_PASSWORD"] = virtualization_password
for k,v in virtualization_mounts.items():
if os.path.isdir(k):
options = options + ['--bind' , k + ':' + v]
else:
print('Requested directory %s is not available and no bind will be made to container' % k)
options = options + virtualization_options
if execmd[0].startswith('./'):
execmd[0] = "/work_dir/"+execmd[0]
"""
if sandbox:
extra = extra + """
runenv['SINGULARITY_CACHEDIR']=os.path.join(os.getcwd(),'.singularity','cache')
for i in range(3):
try:
buildcommand = [virtualization_binary, 'build', '--sandbox', 'singularity_sandbox' , virtualization_image]
rc = subprocess.call(buildcommand, env=runenv, shell=False)
if rc==0:
break
except Exception as x:
print('Exception occured in downloading Singularity image: ' + str(buildcommand))
print('Err was: ' + str(x))
execmd = [virtualization_binary, '-q', 'exec', '--bind',
workdir+":"+"/work_dir", "--no-home"] + options + ['singularity_sandbox'] + execmd
"""
else:
extra = extra + """
execmd = [virtualization_binary, '-q', 'exec', '--bind',
workdir+":"+"/work_dir", "--no-home"] + options + [virtualization_image] + execmd
"""
script = script.replace('###VIRTUALIZATION###',extra)
return script
|
ganga-devs/ganga
|
ganga/GangaCore/Lib/Virtualization/Singularity.py
|
Python
|
gpl-3.0
| 6,647
|
[
"DIRAC"
] |
3afe727c1fcaa8834d97c6d17914e94f1a15966ae4160eadc0141cc4fbe1105e
|
# Copyright (c) 2016 Embedit Electronics
# Author: Brian Bradley
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
# copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:
# The above copyright notice and this permission notice shall be included in all
# copies or substantial portions of the Software.
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
# SOFTWARE.
__author__ = 'Brian Bradley'
__version__ = '2.0.1'
from pisoc import *
from math import log
class DigitalPin(object):
"""
:Class:
Provides functionality for use of the GPIO on the PiSoC as a digital input or output, with a number of different drive mode configurations.
:Example:
Define a DigitalPin object in the following way::
>>>My_input = DigitalPin(port,pin,'input')
>>>My_output = DigitalPin(port,pin,'output')
.. note::
Modification of which pins are available should be easy. Just add new pins to you PiSoC schematic, give them an input and an output, and then name them as GPIO_PORT_PIN.
After you do this, confirm that it was done correctly by using the info qualifier when constructing the PiSoC class.
|
"""
def __init__(self, port, pin, configuration = None):
"""
:Method:
__init__
:Description:
Constructs and initializes a DigitalPin object
:param port: Port on the PiSoC
:type port: int
:param pin: Pin relative to chosent port on the PiSoC.
:type pin: int
:param configuration: Drive mode of the pin
:input:
Sets pin as an input (High Impedance)
:output:
Sets pin as an output (Strong Drive)
:pull_up:
Sets pin as an input with a resistive pullup. Pin will be driven high.
:pull_down:
Sets pin as an input with a resistive pulldown. Pin will be driven low.
:open_drain_lo:
Sets pin as open drain (drives low)
:open_drain_hi:
Sets pin as open drain (drives high)
:pull_up_down:
Sets pin as resitive pull up/down
:type configuration: str
:returns:
None
.. note::
GPIO pins unavailable to the firmware will raise a *ValueError*. Verify valid **port** and **pin** assignments using the info qualifier when PiSoC is constructed.
"""
self.address = PiSoC.GPIO_REGISTER
if int(port) not in PiSoC.GPIO.keys():
msg = 'Invalid port: Port numbers found on PiSoC are %s'%", ".join( str(c) for c in PiSoC.GPIO.keys() )
raise ValueError(msg)
else:
self.port = int(port)
if int(pin) not in PiSoC.GPIO[self.port]:
msg = 'Invalid pin: the second argument should be the pin number relative to the desired port. Valid entries on this port are %s'%", ".join(str(c) for c in PiSoC.GPIO[self.port])
raise ValueError(msg)
else:
self.pin = int(pin)
i = 0
for _port in sorted(PiSoC.GPIO):
for _pin in PiSoC.GPIO[_port]:
if _port == self.port and _pin == self.pin:
self.pin_absolute = i
break
else:
i+=1
self.Configure(configuration)
self.Read()
def __repr__(self):
return "DigitalPin(port=%r, pin=%r, configuration=%r)"%(self.port, self.pin, self.config_str)
def Configure(self, config):
"""
:Method:
Configure
:param config: Drive mode of the pin
:input:
Sets pin as an input (High Impedance)
:output:
Sets pin as an output (Strong Drive)
:pull_up:
Sets pin as an input with a resistive pullup. Pin will be driven high.
:pull_down:
Sets pin as an input with a resistive pulldown. Pin will be driven low.
:open_drain_lo:
Sets pin as open drain (drives low)
:open_drain_hi:
Sets pin as open drain (drives high)
:pull_up_down:
Sets pin as resitive pull up/down
:type config: str
:returns:
None
"""
cmd = 0x03
self.config_str = config
if config == 'input':
self.config = 0x02
elif config == 'pull_up':
self.config = 0x03
elif config == 'pull_down':
self.config = 0x04
elif config == 'open_drain_lo':
self.config = 0x05
elif config == 'open_drain_hi':
self.config = 0x06
elif config == 'output':
self.config = 0x07
elif config == 'pull_up_down':
self.config = 0x08
elif config is None:
self.config = None
else:
raise ValueError('Invalid pin configuration')
if not self.config is None:
dat = (self.config<<8)|(self.port<<4) | (self.pin<<1)
PiSoC.commChannel.send_data(self.address,cmd,dat)
self.Read()
def Write(self, val):
"""
:Method:
Write
:Description:
Writes a new value to the DigitalPin
:param val:
Value to be written. *val* should be **1** or **0** for writing the output HIGH or LOW, respectively.
:type val: int
:returns:
None
"""
cmd = 0x01
dat = (self.port<<4) | (self.pin<<1) | (int(val)&0x01)
PiSoC.commChannel.send_data(self.address,cmd,dat)
self.state = val
def Toggle(self):
"""
:Method:
Toggle
:Description:
Toggles the state of the specified output
:returns:
None
"""
#val = int(not (self.state==1))
#self.Write(val)
cmd = 0x02
dat = (self.port<<4) | (self.pin<<1)
PiSoC.commChannel.send_data(self.address,cmd,dat)
def Read(self, bitmap = None, port = False):
"""
:Method:
Read
:Description:
Determines the state of the digital pin on the PiSoC
:param bitmap:
An optional input, which when provided will be used to decide the state of the pin instead of asking the PiSoC.
It is a hexadecimal value which represents either the states of all pins, as returned by :meth:`get_gpio_bitmap`,
or the state of all pins on its port, as returned by :meth:`get_port_state`.
Providing a bitmap to this function simply abstracts the bit manipulation required to decode that result.
:type bitmap: int
:param port: Specifies if the bitmap should represent a map of all gpio, or just a map of this pins port. If no bitmap is provided, this parameter does nothing.
:type port: bool
:returns:
boolean value (True/False) which indicates the state of the DigitalPin as HIGH/LOW, respectively
"""
cmd = 0x00
if bitmap is not None:
if port:
self.state = (bitmap>>self.pin)&0x01
else:
self.state = (bitmap>>self.pin_absolute)&0x01
else:
dat = (self.port<<4) | (self.pin<<1)
self.state = bool(PiSoC.commChannel.receive_data(self.address, cmd, dat))
return self.state
def get_port_state(self):
"""
:Method:
get_port_state
:Description:
Calculates an 8-bit value which represents the state of each pin on this pins associated port. Use this when minimizing data transfers is desired.
:returns:
an integer value between 0 and 255. The binary representation of this number gives information on each pin state.
The nth bit will give the state of the nth pin on this port. Bit 0 is the LSB and Bit 7 is the MSB.
This result can be provided to the instance method :meth:`Read` as a bitmap to abstract the calculation of True/False.
.. note::
Firmware bug in V2.0.0 prevents this from being calculated on the PiSoC directly. It is instead calculated in Python from the result of :meth:`pisoc.digital.DigitalPin.get_gpio_bitmap`
"""
#cmd = 0x05 TODO. Firmware bug appears to make this not work. Workaround is to derive port state from gpio_bitmap
#return PiSoC.commChannel.receive_data(self.address, cmd, self.port<<4)
bitmap = self.get_gpio_bitmap()
i = 0
j = 0
result = 0
for _port in sorted(PiSoC.GPIO):
for _pin in PiSoC.GPIO[_port]:
if _port == self.port:
result |= ((bitmap >> i) << j)
j+=1
i+=1
return result
def get_gpio_bitmap(self):
"""
:Method:
get_gpio_bitmap
:Description:
Calculates an n-bit integer between 0 and :math:`2^n - 1` which represents the state of each available GPIO between 0 and n,
where n is the number of GPIO available. The pins are sorted 0 - n according to their port and pin numbers.
The lowest pin number on the lowest port number is equal to pin 0, and the highest pin number on the highest port number is
equal to pin n. Use this when minimizing data transfers is desired.
:returns:
an integer value between 0 and :math:`2^n - 1` where n is the number of GPIO available.
The binary representation of this number gives information on each pin state.
The kth bit will give the state of the kth available pin. Bit 0 is the LSB and Bit n is the MSB.
This result can be provided to the instance method :meth:`Read` as a bitmap to abstract the calculation of True/False.
"""
cmd = 0x04
return PiSoC.commChannel.receive_data(self.address, cmd)
class PWM(object):
"""
:Class:
This class provides functionality for use of the PWM components available on the PiSoC.
:Example:
Define PWM objects in the following way::
>>> My_PWM = PWM(0)
|
"""
def __init__(self, channel, frequency = None, duty_cycle = None):
"""
:Method:
__init__
:Description:
Constructs and initializes PWM object
:param channel:
Corresponds to one of the physical PWM pins on your PiSoC, valid inputs are *0*-*7*
:type channel: int
:param frequency:
Optional parameter. If specified, the PWM will switch with this frequency in Hertz.
:type frequency: float
:param duty_cycle:
Optional parameter. If specified, the PWM will have this duty cycle. This value should represent the percentage of time during one PWM cycle that the output is HIGH. Valid values are *0*-*100*
:type duty_cycle: float
:returns:
None
"""
if channel not in range(PiSoC.PWM_NUM ):
raise ValueError('Invalid PWM Channel specified, valid entires are 0 through %d' %PiSoC.PWM_NUM)
for key in PiSoC.PWM_clks:
for i in PiSoC.PWM_clks[key][2]:
if int(channel) == i[0]:
addr_str = "PiSoC.PWM_REGISTER"+str(channel)
setattr(self, 'address', eval(addr_str))
self.clk_number = int(key)
self.resolution_in_bits = int(i[1])
self.channel = channel
self.max_num = pow(2,self.resolution_in_bits) - 1
self.max_clk = PiSoC.PWM_clks[self.clk_number][0]
self.min_clk = int(PiSoC.PWM_clks[self.clk_number][0]/65535) + 1
self.Start()
self.period = self.ReadPeriod()
self.cmp = self.ReadCompare()
if frequency is not None:
self.SetFrequency(frequency)
if duty_cycle is not None:
self.SetDutyCycle(duty_cycle)
self.Stop()
self.__running = False
self.__sleeping = True
if self.address in PiSoC.REGISTERS_IN_USE:
logging.warning('Attempting to initialize object at register %d which is already in use.' %self.address)
PiSoC.REGISTERS_IN_USE.append(self.address)
def __repr__(self):
return "PWM(channel=%r, frequency=%r, duty_cycle=%r)"%(self.channel, round(self.GetFrequency(), 2), round(self.GetDutyCycle(), 2))
def Start(self):
"""
:Method:
Start
:Description:
Starts component operation. Sets the initVar variable, calls the PWM_Init function, and then calls the PWM_Enable function
:returns:
None
"""
cmd = 0x00
PiSoC.commChannel.send_data(self.address, cmd)
self.__running = True
def is_running(self):
"""
:Method:
is_running
:Description:
Checks if the PWM component is currently operational
:returns:
boolean result which evaluates to *True* if the PWM component is operational, or *False* if it is not
"""
return self.__running
def Stop(self):
"""
:Method:
Stop
:Description:
Disables component operation
:returns:
None
"""
cmd = 0x01
PiSoC.commChannel.send_data(self.address, cmd)
self.__running = False
def WritePeriod(self, period):
"""
:Method:
WritePeriod
:Description:
Writes the period value used by the PWM hardware
:param period: The length, in *counts*, which defines how long a PWM Cycle will be
* The value must not be greater than *65535* (for 16-bit mode, which is the default)
* for 8-bit mode it must not be greater than *255*
* The period must be greater than the comparison value
:type period: int
:returns:
None
"""
cmd = 0x0C
self.period = int(period)
if self.period<0 or self.period>self.max_num:
if self.period<0:
self.period = 0
else:
self.period = self.max_num
logging.warning('Value outside of bounds. Got %s, adjusted to %s'%(period, self.period))
if self.period<self.cmp:
logging.warning('Attempting to write a PWM period value less than its comparison value. \nDecreasing comparison value to be equal to period before continuing to prevent run time errors.')
self.cmp = int(self.period)
self.WriteCompare(self.cmp)
PiSoC.commChannel.send_data(self.address, cmd, self.period)
def ReadPeriod(self):
"""
:Method:
ReadPeriod
:Description:
Determines the period value, in counts, currently set by the PWM component
:returns:
Integer value representing the PWM period in counts
"""
cmd = 0x0D
self.period = PiSoC.commChannel.receive_data(self.address, cmd)
return self.period
def WriteCompare(self, cmp): #todo change cmp to a different variable name.
"""
:Method:
WriteCompare
:Description:
Writes the comparison value used by the PWM hardware to determine the point in the PWM cycle at which the state will change, relative to the period.
:param cmp: The length, in *counts*, which defines the switching point relative to the PWM period
* The value must not be greater than *65535* (for 16-bit mode, which is the default)
* for 8-bit mode it must not be greater than *255*
* The comparison value must be less than or equal to the period
:type cmp: int
:returns:
None
"""
cmd = 0x0E
self.cmp = int(cmp)
if self.cmp<0 or self.cmp>self.max_num:
if self.cmp<0:
self.cmp = 0
else:
self.cmp = self.max_num
logging.warning('Value outside of bounds. Got %s, adjusted to %s'%(cmp, self.cmp))
if self.period<self.cmp:
logging.warning('Attempting to write comparison value larger than period. \nIncreasing period to be equal to comparison value before continuing to prevent run time errors.')
self.period = self.cmp
self.WritePeriod(self.period)
PiSoC.commChannel.send_data(self.address, cmd, self.cmp)
def ReadCompare(self):
"""
:Method:
ReadCompare
:Description:
Determines the comparison value, in counts, currently set by the PWM component
:returns:
Integer value representing the count value at which the PWM signal will change states during any given cycle, relative to the period.
:Example:
If the period is set to *100*, and the comparison value is set to *20*, the PWM signal will be HIGH for 20% of its period, and then LOW for the remaining 80%
"""
cmd = 0x0F
self.cmp = PiSoC.commChannel.receive_data(self.address, cmd)
return self.cmp
def ClearFIFO(self):
"""
:Method:
ClearFIFO
:Description:
Clears the capture FIFO of any previously captured data. Here PWM_ReadCapture() is called until the FIFO is empty
:returns:
None
.. warning::
This function no longer has an effect since V1.2
"""
cmd = 0x18
PiSoC.commChannel.send_data(self.address, cmd)
def Sleep(self):
"""
:Method:
Sleep
:Description:
Stops the PWM operation, puts the PWM component into it's lowest power state, and saves the current configuration
:returns:
None
"""
cmd = 0x19
PiSoC.commChannel.send_data(self.address, cmd)
self.__sleeping = True
def Wakeup(self):
"""
:Method:
Wakeup
:Description:
Restores and enables the most recently saved configuration
:returns:
None
"""
cmd = 0x1A
PiSoC.commChannel.send_data(self.address, cmd)
self.__sleeping = False
def SetClocks(self, frequency):
"""
:Method:
SetClocks
:Description:
Attempts to set the PWM Clock rate to a desired frequency using an appropriate clock divider.
:param frequency: A frequency in Hz which represents the desired clock rate
* This is NOT the frequency of the PWM, it is the frequency of the clock which drives it
* Changing the clock frequency for any single PWM that shares it's clock source will affect all PWMs that share this clock
* For the suggested clock source of 24 MHz, this value cannot be less than *367* Hz and cannot be more than 24 MHz (*24000000* Hz)
* Generally, the frequency cannot be less than your clock source divided by 65535, and cannot be greater than your clock source itself
:type frequency: float
:returns:
None
.. warning::
Because frequencies are calculated with dividers, high frequencies result in greater potential deviation.
* For a 24 MHz source, frequencies higher than 2.526 MHz accuracy cannot be guaranteed to be within a tolerance of 5%
* For a 24 MHz source, frequencies higher than 5.333 MHz accuracy cannot be guaranteed to be within a tolerance of 10%
* The frequency might still be accurate at high frequencies; tolerances are worst case scenarios
* Use :meth:`~GetClocks` to get the actually achieved frequency
"""
if frequency>self.max_clk or frequency<self.min_clk:
if frequency<0:
frequency = self.min_clk
else:
frequency = self.max_clk
logging.warning('Invalid range specified for PWM clock frequency. Adjusted to %s. Must be less than %dMHz and greater than %dHz'%(frequency, int(float(self.max_clk)/1000000),self.min_clk))
if frequency>5333345: #recalculate this out for arbitrary clock. Only valid for 24MHz Master Clock todo
logging.warning("Attempted to set PWM clock frequency greater than 5.333 MHz; this frequency cannot be gauranteed within a tolerance of 10%. Get the actual frequency with the GetClocks() method")
elif frequency>2526318:
logging.warning("Attempted to set PWM clock frequency greater than 2.526 MHz; this frequency cannot be gauranteed within a tolerance of 5%. Get the actual frequency with the GetClocks() method")
cmd = 0xFF
attempt_divider = int((PiSoC.PWM_clks[self.clk_number][0]/float(frequency)) + 0.5)
PiSoC.PWM_clks[self.clk_number][1] = (PiSoC.commChannel.receive_data(self.address,cmd, attempt_divider)) + 1
def GetClocks(self, precision = 2):
"""
:Method:
GetClocks
:Description:
Calculates the actual clock rate of the PWM's based on the most recently confirmed clock divider value
:param precision:
Optional parameter. Specifies how many decimal places the result should be calculated to.
:type precision: int
:returns:
Floating point value which represents the source clock frequency for this PWM in Hertz.
"""
return round(((PiSoC.PWM_clks[self.clk_number][0])/float((PiSoC.PWM_clks[self.clk_number][1]))), precision)
def GetClockDivider(self):
"""
:Method:
GetClockDivider
:Description:
Gets the most recently confirmed clock divider value, which is used to determine the clocking frequency of the PWM
:returns:
16-bit integer value representing the current clock divider mapped to the source clock for this PWM.
"""
return PiSoC.PWM_clks[self.clk_number][1]
def SetClockDivider(self, divider):
"""
:Method:
SetClockDivider
:Description:
Sets a clock divider to be mapped to the desired PWM's clock source
:param divider:
An integer between *0* and *65535* which the PWM clock will be divided by
:type divider: int
:returns:
None
.. warning::
Changing the clock's divider, and consequently its frequency, will affect any other PWMs which share that clock
"""
cmd = 0xFF
divider = int(divider + .5)
if divider<0 or divider>65535:
raise ValueError('Invalide range for SetClockDivider() method')
PiSoC.PWM_clks[self.clk_number][1] = (PiSoC.commChannel.receive_data(self.address,cmd, divider)) + 1
#eventually move this algorithm to psoc side for greater portability...
def SetFrequency(self,freq, max_error = 5, min_period = 10):
"""
:Method:
SetFrequency
:Description:
Attempts to set the PWM wave frequency to a desired rate by calculating an appropriate period value and/or clock rate.
It will try to maintain the clock rate, unless it is impossible without compromising the duty cycle too severely, in which case a warning will be issued.
:param freq: A frequency in Hz which represents the desired wave rate
* This is NOT the frequency of the clock which drives the PWM, it is the actual output frequency of the PWM signal
* If the frequency cannot be reached without changing the clock rate, any PWM's sharing that clock will be affected
* For the suggested source clock rate of 24MHz, *freq* cannot be less than .006 Hz and cannot be more than 2.4 MHz (*2400000* Hz)
* Generally, freq cannot be less than :math:`\\frac{clock freq}{65535*(2^n - 1)}`, where n is the PWM resolution in bits, and it cannot be more than :math:`\\frac{clock freq}{min\_period}`
:type freq: float
:param max_error: Optional parameter. The largest percentage of error that can be tolerated between the desired frequency and the achieved frequency
* This defaults to 5
* Verify the actual frequency with :meth:`~GetFrequency`
:type max_error: float
:param min_period: Optional parameter. The lowest possible period that can be tolerated when the wave parameters are being calculated
* Valid between 0 and 65535 for a 16-bit PWM
* Valid between 0 and 255 for an 8-bit PWM
* Default behavior is a *min_period* of 10 on 16-bit PWM
* Lower values allow for easier wave parameter calculation, without having to modify the clock source
* Higher values allow finer Duty Cycle maintenence
:type min_period: int
:returns:
None
"""
if freq<=(float(self.min_clk)/65534):
logging.warning('Cannot generate frequencies less than %f Hz. Frequency will be set to %f Hz'%(float(self.min_clk)/65534,float(self.min_clk)/65534))
freq = self.min_clk/65534.0
if freq>(self.max_clk/float(min_period)):
logging.warning('Cannot generate a frequency greater than %dHz without compromosing Duty Cycle beyond specification. Frequency will be set to %dHz to prevent this. '%(self.max_clk/float(min_period),self.max_clk/float(min_period)))
freq = self.max_clk/float(min_period)
DutyCycle_cur = self.GetDutyCycle()/100.0
period_new = int((self.GetClocks()/float(freq)) + 0.5)
if period_new<float(min_period):
period_new = min_period
elif period_new>self.max_num:
period_new = self.max_num
compare_new = int(period_new*DutyCycle_cur + 0.5)
try_freq = self.GetClocks()/float(period_new)
error = abs(((100.0*(try_freq - freq))/freq))
err_chk_strt = True
div_cur = self.GetClockDivider()
while abs(error)>max_error: #this algorithm is terrible and obfuscated. It is bad and I should feel bad. Todo: Make this algorithm not terrible and not obfuscated.
if err_chk_strt:
logging.warning('Could not acheive desired frequency within 5% tolerance without editing the clock rate. This change will affect any PWM channels sharing this clock.')
clock_rate = int(freq*self.max_num + (self.min_clk - freq*self.max_num)*(freq*self.max_num<self.min_clk) - (freq*self.max_num>self.max_clk)*(freq*self.max_num - self.max_clk))
self.SetClocks(clock_rate)
clk_new = self.GetClocks()
div_cur = self.GetClockDivider()
err_chk_strt = False
else:
div_cur = div_cur + shift
clk_new = PiSoC.PWM_clks[self.clk_number][0]/div_cur
if div_cur<1:
div_cur = 1
logging.warning('Could not achieve desired frequency within tolerance')
break
elif div_cur>self.max_num:
div_cur = self.max_num
logging.warning('Could not achieve desired frequency within tolerance')
break
period_new = int((clk_new/float(freq)) + 0.5)
if period_new<float(min_period):
period_new = min_period
elif period_new>self.max_num:
period_new = self.max_num
compare_new = int(period_new*DutyCycle_cur + 0.5)
try_freq = clk_new/float(period_new)
error = ((100.0*(try_freq - freq))/freq)
shift = int(error>0) - 2*(error<0)
else:
if not err_chk_strt:
self.SetClockDivider(div_cur)
if period_new != self.period:
if self.cmp>period_new:
self.WriteCompare(compare_new)
self.WritePeriod(period_new)
else:
self.WritePeriod(period_new)
self.WriteCompare(compare_new)
def SetMIDI(self, midi, max_error = 5, min_period = 10):
"""
:Method:
SetMIDI
:Description:
Generates a PWM wave frequency the corresponds to the specified midi note
:param midi:
A midi note, as defined by the midi standard to correspond with a specific musical note
:type midi: int
:param max_error: Optional parameter. The largest percentage of error that can be tolerated between the desired frequency and the achieved frequency
* This defaults to 5
* This error rate is in reference to the wave frquency, in Hz, not the midi note number which is scaled differently than the frequency
:type max_error: float
:param min_period: Optional parameter. The lowest possible period that can be tolerated when the wave parameters are being calculated
* Valid between 0 and 65535 for a 16-bit PWM
* Valid between 0 and 255 for an 8-bit PWM
* Default behavior is a *min_period* of 10 on 16-bit PWM
* Lower values allow for easier wave parameter calculation, without having to modify the clock source
* Higher values allow finer Duty Cycle maintenence
:type min_period: int
:returns:
None
"""
self.SetFrequency(pow(2, (midi-69)/12.0)*440, max_error, min_period)
def GetMIDI(self):
"""
:Method:
GetMIDI
:Description:
Calculates what MIDI note corresponds to the current PWM frequency
:returns:
The integer MIDI note, as defined by the MIDI standard to correspond with a specific musical note, which most closely resembles the PWM frequency
"""
return int(69.5 + 12.0*(log((self.GetFrequency()/440.0), 2)))
def GetDutyCycle(self, precision = 2):
"""
:Method:
GetDutyCycle
:Description:
Calculates the current duty cycle based on the current period and comparison values
:param precision:
Optional parameter. The number of decimal places which the result should be calculated to. Defaults to 2.
:type precision: int
:returns:
A floating point value which is representative of the percentage of time, between 0 and 100%, that the PWM signal is on, relative to the total length of its period
"""
return round((100.0*(float(self.cmp)/float(self.period))),precision)
def GetFrequency(self, precision = 2):
"""
:Method:
GetFrequency
:Description:
Calculates the current PWM wave frequency based on the current clock rate and period value
:param precision:
Optional parameter. The number of decimal places which the result should be calculated to. Defaults to 2.
:type precision: int
:returns:
A floating point value, which is representative of the current PWM signal frequency in Hz
"""
return round((self.GetClocks()/float(self.period)),precision)
def SetDutyCycle(self,duty_cycle):
"""
:Method:
SetDutyCycle
:Description:
Simplifies the process of setting a meaningful comparison value by calculating it based on a desired duty cycle then setting it to the PWM hardware.
:param duty_cycle: value between 0 and 100 which indicates the percentage of time that the PWM should be HIGH during one period
* A *duty_cycle* of 100 indicates that the PWM is always on
* A *duty_cycle* of 50 indicates that the PWM is on half of the time
* A *duty_cycle* of 0 indicates that the PWM is always off
:type duty_cycle: float
:returns:
None
"""
if duty_cycle<0 or duty_cycle>100:
if duty_cycle<0:
duty_cycle = 0.0
else:
duty_cycle = 100.0
logging.warning('Invalid range for SetDutyCycle: Valid range is 0 to 100. Adjusted to %s'%duty_cycle)
self.cmp = int(self.period * ((duty_cycle)/100.0) + 0.5)
self.WriteCompare(self.cmp)
class Servo(object):
"""
:Class:
This class provides tools for easy manipulation of standard Servo Motors using PWM.
:Example:
Define Servo objects in any the following ways::
>>> My_simple_servo = Servo(0)
>>> My_calibrated_servo = Servo(1, min_pulse = 1.0, max_pulse = 2.0)
>>> My_descriptive_servo = Servo(7, min_pulse = 1.0, max_pulse = 2.0, min_angle = 0, max_angle = 180)
|
"""
def __init__(self, channel, min_pulse = 1.0, max_pulse = 2.0, min_angle = 0, max_angle = 180):
"""
:Method:
:Description:
Creates a servo object with the given parameter set
:param channel: Corresponds to the pin which the signal line of the servo will be connected to. Uses the same numbering convention as :class:`PWM`
:type channel: int
:param min_pulse: Optional parameter. The pulse width (in milliseconds) necessary to obtain angular position *min_angle*.
* Values must be greater than zero
* Normal values are between 0.8 and 1.2
* Find an appropriate value through calibration; it will default to 1.0 if no parameter is given
:type min_pulse: float
:param max_pulse: Optional parameter. The pulse width (in milliseconds) necessary to obtain angular position *max_angle*.
* Values must be greater than zero
* Normal values are between 1.8 and 2.3
* Find an appropriate value through calibration; it will default to 2.0 if no parameter is given
:type max_pulse: float
:param min_angle: Optional parameter. The angle which the servo will return to if applied with a pulse width of *min_pulse*.
* This defaults to 0
* Negative angular positions are valid
* Angles can be any angular unit: degrees, radians, or other arbitrary (linear) scale
:type min_angle: float
:param max_angle: Optional parameter. The angle which the servo will return to if applied with a pulse width of *max_pulse*.
* This defaults to 180
* Negative angular positions are valid
* Angles can be any angular unit: degrees, radians, or other arbitrary (linear) scale
:type max_angle: float
:returns:
None
.. note::
A servo with channel n, will make PWM(n) unnavailable, since the servo controller is implemented using that PWM object.
For fine control over that PWM, you can expose the internal use of the PWM instance using My_servo.servo_PWM, and then you can use any of the PWM methods using My_servo.servo_PWM.method().
This is advised against though, because servos are very particular about the construction of their data signals.
If you change the wrong parameter of the PWM signal, you might damage the motor.
"""
self.min_pulse = float(min_pulse)
self.max_pulse = float(max_pulse)
self.min_angle = float(min_angle)
self.max_angle = float(max_angle)
self.channel = channel
self.pulse_range = float(max_pulse-min_pulse)
self.angle_range = float(max_angle-min_angle)
self.servo_PWM = PWM(self.channel)
if abs(self.servo_PWM.GetFrequency() - 50) > 1:
self.servo_PWM.SetClockDivider(8)
self.servo_PWM.WritePeriod(60000)
self.servo_PWM.WriteCompare(4500)
def __repr__(self):
return "Servo(channel=%s, min_pulse=%s, max_pulse=%s, min_angle=%s, max_angle=%s)"%(self.channel, self.min_pulse, self.max_pulse, self.min_angle, self.max_angle)
def ChangeAngles(self, min_angle, max_angle):
"""
:Method:
ChangeAngles
:Description:
Changes the angle range that defines the minimum and maximum positions of the motor
:param min_angle: Optional parameter. The angle which the servo will return to if applied with a pulse width of *min_pulse*.
* This defaults to 0
* Negative angular positions are valid
* Angles can be any angular unit: degrees, radians, or other arbitrary (linear) scale
:type min_angle: float
:param max_angle: Optional parameter. The angle which the servo will return to if applied with a pulse width of *max_pulse*.
* This defaults to 180
* Negative angular positions are valid
* Angles can be any angular unit: degrees, radians, or other arbitrary (linear) scale
:type max_angle: float
:returns:
None
"""
self.min_angle = float(min_angle)
self.max_angle = float(max_angle)
self.angle_range = float(max_angle-min_angle)
def SetPulse(self, pulse_ms):
"""
:Method:
SetPulse
:Description:
Sets a servo position based on a pulse width in ms
:param pulse_ms:
A pulse width in milliseconds, which will be applied to the signal wire of the Servo at 50 Hz.
Normal values are between 0.8 and 2.3, but they must be between the defined *min_pulse* and *max_pulse* values
:type pulse_ms: float
:returns:
None
"""
if pulse_ms < self.min_pulse:
pulse_ms = self.min_pulse
logging.warning('Tried to set a pulse less than defined range, setting pulse to minimum accepted value (%s)'%self.min_pulse)
elif pulse_ms > self.max_pulse:
pulse_ms = self.max_pulse
logging.warning('Tried to set a pulse greater than defined range, setting pulse to maximum accepted value(%s)'%self.max_pulse)
self.servo_PWM.SetDutyCycle((float(pulse_ms)/(1000.0/(self.servo_PWM.GetFrequency())))*100)
def ReadPulse(self):
"""
:Method:
ReadPulse
:Description:
Calculates the current pulse width of the PWM which is driving the servomotor
:returns:
A pulse duration in milliseconds which characterizes the state of the PWM signal being applied to the servomotor
"""
return float(self.servo_PWM.GetDutyCycle()*(10.0/self.servo_PWM.GetFrequency()))
def ReadAngle(self):
"""
:Method:
ReadAngle
:Description:
Calculates the current angle of the servomotor, linearized relative to the provided maximum and minimum angles
:returns:
A value representative of the angle that the servo motor is held, according to the scale set within the class.
"""
pulse_cur = self.servo_PWM.GetDutyCycle()*(10.0/self.servo_PWM.GetFrequency())
angle_perc = (pulse_cur - self.min_pulse)/float(self.pulse_range)
angle_cur = angle_perc*self.angle_range + self.min_angle
return angle_cur
def SetAngle(self, angle):
"""
:Method:
SetAngle
:Description:
Calculates a pulse width based on the given angular position and the current min/max configuration parameters,
then calls :meth:`~SetPulse` to set the position of the servo
:param angle:
The angle to which the servo should be set, linearized relative to the defined minimum and maximum angles
:type angle: float
:returns:
None
"""
angle_perc = float(angle-self.min_angle)/self.angle_range
pulse = self.min_pulse + angle_perc*self.pulse_range
self.SetPulse(pulse)
def Stop(self):
"""
:Method:
Stop
:Description:
Stops the servo object by terminating the PWM channel that drives it
:returns:
None
.. note::
This may cause the servo to move slightly out of position
"""
self.servo_PWM.Stop()
def is_running(self):
"""
:Method:
is_running
:Description:
Checks to see if the Servo component is currently operational
:returns:
A boolean variable which evaluates to *True* if the PWM component is operational, or *False* if it is not
"""
return self.servo_PWM._PWM__running
def Start(self):
"""
:Method:
Start
:Description:
Starts component operation.
:returns:
None
"""
self.servo_PWM.Start()
class RangeFinder(object):
"""
:Class:
This class provides functionality for use of ultrasonic range finder devices that use standard GPIO pulse width sonic time-of-flight measurement protocols
:Example:
Define a RangeFinder object in the following way::
>>> #set signal pin to 12[0], trigger pin to 12[1], and specify a maximum poll frequency of 50Hz.
>>> my_ranger = RangeFinder([12,0], trigger = [12, 1], poll_frequency = 50)
|
"""
def __init__(self, signal, trigger = None, delay_us = 10, timeout_us = 30000, poll_frequency = None):
"""
:Method:
__init__
:Description:
Initializes an object by describing which pin the echo will be measured on.
Optionally, provide a trigger pin if the ranger is a 4 or 5 pin form factor.
Also optionally provide a trigger pulse width and timeout value in milliseconds, or a maximum frequency in Hz.
:param signal:
A DigitalPin object which defines which exact pin will be used to communicate with the rangers signal/echo pin
:type signal: DigitalPin
:param trigger: A DigitalPin object which defines which exact pin will be used to communicate with the rangers trigger pin
* By default, if no argument is provided, it will assume the trigger pin is the same as the echo pin; this is true for 3-pin devices and so no argument is needed
:type trigger: DigitalPin
:param delay_us:
Optional Parameter. Integer value representing the width of the trigger pulse, in microseconds, that will be sent from the TRIGGER pin
to signal the ranger to send a ping. Defaults to 10.
:type delay_us: int
:param timeout_us: The maximum length of time, in microseconds, that the PiSoC will wait for a confirmed echo
* If this time is exceeded, the ranger will immediately terminate its current process and return the timeout as a response
* This defaults as 30000 microseconds, which is equivalent to 30 ms, and is much longer than generally needed and so won't usually need to be altered
* Refer to your devices documentation for a more specific timeout choice
:type timeout_us: int
:param poll_frequency:
Optional parameter. When set, this API will not make calls to the range finder more frequently than specified.
A call to read from the RangeFinder will block and wait until the specified time has passed so that another call can be made.
Valid entries are in Hertz. Range Finding modules often should not be polled more frequently than 50Hz, and so setting that as a
maximum will prevent invalid responses. If a call is attempted too quickly, note that use of this parameter will cause that call
to block and delay execution of the rest of your program.
:type poll_frequency: float
:returns:
None
"""
self.signal_pin = signal.pin
self.signal_port = signal.port
if trigger == None:
self.trigger_port = signal.port
self.trigger_pin = signal.pin
else:
self.trigger_port = trigger.port
self.trigger_pin = trigger.pin
self.address = PiSoC.RANGE_FINDER
self.delay_us = delay_us
self.timeout = timeout_us
self.packed_dat = (self.trigger_port<<10)|(self.trigger_pin<<7)|(self.signal_port<<3)|(self.signal_pin)
self.raw = 0
self.meters = 0
self.inches = 0
self.centimeters = 0
self.reading = False
self.SetDelay(delay_us)
self.SetTimeout(timeout_us)
self.poll_frequency = poll_frequency
if poll_frequency is not None:
self.poll_period = 1.0/poll_frequency
else:
self.poll_period = 0
self.time_since_last_poll = 0
def __repr__(self):
return "RangeFinder(signal=[%r,%r],trigger=[%r,%r], delay_us=%s, timeout_us=%r, poll_frequency = %r)"%(self.signal_port, self.signal_pin, self.trigger_port, self.trigger_pin, self.delay_us, self.timeout, self.poll_frequency)
def SetTimeout(self, timeout_us):
"""
:Method:
SetTimeout
:Description:
Sets the timeout length in microseconds. If the PiSoC is still waiting for a completed response after this amount of time, it
will terminate its current process immediately return the result
:param timeout_us:
Amount of time, in microseconds, that the PiSoC will wait for a completed response. Valid inputs are between *1* and *65535*.
:type timeout_us: int
:returns:
None
.. note::
This is handled in :meth:`~__init__`, and so this value should be set in the class constructor.
This method should only be called under unique circumstances.
"""
cmd = 0x01
if ((timeout_us>65535) or (timeout_us<=0)):
raise ValueError('Timeout must be between 1 and 65535 microseconds: provided %d' %timeout_us)
PiSoC.commChannel.send_data(self.address, cmd, timeout_us)
self.timeout = timeout_us
def SetDelay(self, delay_us):
"""
:Method:
SetDelay
:Description:
Sets the length of the trigger pulse, in microseconds, which will be used to tell the device to send out a ping
:param delay_us:
Amount of time, in microseconds, that the PiSoC will hold its trigger pulse high. This is a 6 bit value, and so it must be between *0* and *63*
:type delay_us: int
:returns:
None
.. note::
This is handled in :meth:`~__init__`, and so this value should be set in the class constructor.
This method should only be called under unique circumstances.
"""
cmd = 0x02
if (delay_us>63 or delay_us<=0):
raise ValueError('Delay must be between 1 and 63 microseconds: provided %d' %delay_us)
PiSoC.commChannel.send_data(self.address, cmd, delay_us)
def ReadRaw(self):
"""
:Method:
ReadRaw
:Description:
Gets a raw value from the PiSoC, which is representative of how many microseconds the rangers echo pin was held high
:returns:
The length of time, in microseconds, that it took for the ping to echo back to the ultrasonic ranger.
"""
cmd = 0x00
while not self.is_ready():
pass
self.time_since_last_poll = time.time()
reading = PiSoC.commChannel.receive_data(self.address, cmd, self.packed_dat, delay = 0.05)
self.raw = reading
if reading == PiSoC.BAD_PARAM:
logging.error("Timeout occured waiting for signal pin to be asserted; verify connection.")
return reading
def is_ready(self):
return not (time.time() - self.time_since_last_poll)<self.poll_period
def ReadMeters(self, sound = 343.0, precision = 2):
"""
:Method:
ReadMeters
:Description:
Uses :meth:`ReadRaw` to get a raw time value in microseconds, and then calculates the distance between the ranger and the pinged object in meters
:param sound: Optional parameter. The speed of sound which is used to calcuate the distance of the object detected by the ranger
* Defaults to 343 m/s (approximate value based on room temperature of air)
* Must be m/s
* Modify this according to your environmental needs (different temperature/medium)
:type sound: float
:param precision:
Optional parameter. The number of decimal places which the result should be calculated to. Defaults to 2.
:type precision: int
:returns:
The distance, in meters, between the ultrasonic ranger and the pinged object
"""
#time_high = (float(self.readRaw())/period_counts)*period_time
time_high = float(self.ReadRaw())/1000000.0;
# x = vt; speed of sound = 340.29, x is distance from ranger, to object, back to ranger. So twice the desired distance.
self.meters = round((sound*time_high)/2.0, precision)
return self.meters
def ReadCentimeters(self, sound = 343.0, precision = 2):
"""
:Method:
ReadCentimeters
:Description:
Uses :meth:`ReadMeters` and then converts the result to centimeters.
:param sound: Optional parameter. The speed of sound which is used to calcuate the distance of the object detected by the ranger
* Defaults to 343 m/s (approximate value based on room temperature of air)
* Must be m/s
* Modify this according to your environmental needs (different temperature/medium)
:type sound: float
:param precision:
Optional parameter. The number of decimal places which the result should be calculated to. Defaults to 2.
:type precision: int
:returns:
The distance, in centimeters, between the ultrasonic ranger and the pinged object
"""
self.centimeters = round((self.ReadMeters(sound, precision = 9))*100.0, precision)
return self.centimeters
def ReadInches(self, sound = 343.0, precision = 2):
"""
:Method:
ReadInches
:Description:
Uses :meth:`ReadCentimeters` and then converts the result to inches
:param sound: Optional parameter. The speed of sound which is used to calcuate the distance of the object detected by the ranger
* Defaults to 343 m/s (approximate value based on room temperature of air)
* Must be m/s
* Modify this according to your environmental needs (different temperature/medium)
:type sound: float
:param precision:
Optional parameter. The number of decimal places which the result should be calculated to. Defaults to 2.
:type precision: int
:returns:
The distance, in inches, between the ultrasonic ranger and the pinged object
"""
self.inches = round(self.ReadCentimeters(sound, precision = 9)/2.54, precision)
return self.inches
class NeoPixelShield(object):
"""
:Class:
This class provides functionality for use of an Arduino NeoPixels shield on an PiSoC through Python.
:Example:
Create a NeoPixelShield object in the following way::
>>> shield = NeoPixelShield()
"""
def __init__(self):
"""
:Method:
__init__
:Description:
Defines the register address for the striplight controller used by the NeoPixels,
and it defines 140 colors as class attributes, named according to their standardized HTML and CSS names
:returns:
None
"""
self.address = PiSoC.STRIPLIGHT_REGISTER
self.AliceBlue = 0xfff0f8
self.AntiqueWhite = 0xd7faeb
self.Aqua = 0xff00ff
self.Aquamarine = 0xd47fff
self.Azure = 0xfff0ff
self.Beige = 0xdcf5f5
self.Bisque = 0xc4ffe4
self.Black = 0x0
self.BlanchedAlmond = 0xcdffeb
self.Blue = 0xff0000
self.BlueViolet = 0xe28a2b
self.Brown = 0x2aa52a
self.BurlyWood = 0x87deb8
self.CadetBlue = 0xa05f9e
self.Chartreuse = 0x7fff
self.Chocolate = 0x1ed269
self.Coral = 0x50ff7f
self.CornflowerBlue = 0xed6495
self.Cornsilk = 0xdcfff8
self.Crimson = 0x3cdc14
self.Cyan = 0xff00ff
self.DarkBlue = 0x8b0000
self.DarkCyan = 0x8b008b
self.DarkGoldenRod = 0xbb886
self.DarkGray = 0xa9a9a9
self.DarkGreen = 0x64
self.DarkKhaki = 0x6bbdb7
self.DarkMagenta = 0x8b8b00
self.DarkOliveGreen = 0x2f556b
self.DarkOrange = 0xff8c
self.DarkOrchid = 0xcc9932
self.DarkRed = 0x8b00
self.DarkSalmon = 0x7ae996
self.DarkSeaGreen = 0x8f8fbc
self.DarkSlateBlue = 0x8b483d
self.DarkSlateGray = 0x4f2f4f
self.DarkTurquoise = 0xd100ce
self.DarkViolet = 0xd39400
self.DeepPink = 0x93ff14
self.DeepSkyBlue = 0xff00bf
self.DimGray = 0x696969
self.DodgerBlue = 0xff1e90
self.FireBrick = 0x22b222
self.FloralWhite = 0xf0fffa
self.ForestGreen = 0x22228b
self.Fuchsia = 0xffff00
self.Gainsboro = 0xdcdcdc
self.GhostWhite = 0xfff8f8
self.Gold = 0xffd7
self.GoldenRod = 0x20daa5
self.Gray = 0x808080
self.Green = 0x80
self.GreenYellow = 0x2fadff
self.HoneyDew = 0xf0f0ff
self.HotPink = 0xb4ff69
self.IndianRed = 0x5ccd5c
self.Indigo = 0x824b00
self.Ivory = 0xf0ffff
self.Khaki = 0x8cf0e6
self.Lavender = 0xfae6e6
self.LavenderBlush = 0xf5fff0
self.LawnGreen = 0x7cfc
self.LemonChiffon = 0xcdfffa
self.LightBlue = 0xe6add8
self.LightCoral = 0x80f080
self.LightCyan = 0xffe0ff
self.LightGoldenRodYellow = 0xd2fafa
self.LightGray = 0xd3d3d3
self.LightGreen = 0x9090ee
self.LightPink = 0xc1ffb6
self.LightSalmon = 0x7affa0
self.LightSeaGreen = 0xaa20b2
self.LightSkyBlue = 0xfa87ce
self.LightSlateGray = 0x997788
self.LightSteelBlue = 0xdeb0c4
self.LightYellow = 0xe0ffff
self.Lime = 0xff
self.LimeGreen = 0x3232cd
self.Linen = 0xe6faf0
self.Magenta = 0xffff00
self.Maroon = 0x8000
self.MediumAquaMarine = 0xaa66cd
self.MediumBlue = 0xcd0000
self.MediumOrchid = 0xd3ba55
self.MediumPurple = 0xdb9370
self.MediumSeaGreen = 0x713cb3
self.MediumSlateBlue = 0xee7b68
self.MediumSpringGreen = 0x9a00fa
self.MediumTurquoise = 0xcc48d1
self.MediumVioletRed = 0x85c715
self.MidnightBlue = 0x701919
self.MintCream = 0xfaf5ff
self.MistyRose = 0xe1ffe4
self.Moccasin = 0xb5ffe4
self.NavajoWhite = 0xadffde
self.Navy = 0x800000
self.OldLace = 0xe6fdf5
self.Olive = 0x8080
self.OliveDrab = 0x236b8e
self.Orange = 0xffa5
self.OrangeRed = 0xff45
self.Orchid = 0xd6da70
self.PaleGoldenRod = 0xaaeee8
self.PaleGreen = 0x9898fb
self.PaleTurquoise = 0xeeafee
self.PaleVioletRed = 0x93db70
self.PapayaWhip = 0xd5ffef
self.PeachPuff = 0xb9ffda
self.Peru = 0x3fcd85
self.Pink = 0xcbffc0
self.Plum = 0xdddda0
self.PowderBlue = 0xe6b0e0
self.Purple = 0x808000
self.Red = 0xff00
self.RosyBrown = 0x8fbc8f
self.RoyalBlue = 0xe14169
self.SaddleBrown = 0x138b45
self.Salmon = 0x72fa80
self.SandyBrown = 0x60f4a4
self.SeaGreen = 0x572e8b
self.SeaShell = 0xeefff5
self.Sienna = 0x2da052
self.Silver = 0xc0c0c0
self.SkyBlue = 0xeb87ce
self.SlateBlue = 0xcd6a5a
self.SlateGray = 0x907080
self.Snow = 0xfafffa
self.SpringGreen = 0x7f00ff
self.SteelBlue = 0xb44682
self.Tan = 0x8cd2b4
self.Teal = 0x800080
self.Thistle = 0xd8d8bf
self.Tomato = 0x47ff63
self.Turquoise = 0xd040e0
self.Violet = 0xeeee82
self.Wheat = 0xb3f5de
self.White = 0xffffff
self.WhiteSmoke = 0xf5f5f5
self.Yellow = 0xffff
self.YellowGreen = 0x329acd
self.__running = False
def __repr__(self):
return "NeoPixelShield()"
def Start(self):
"""
:Method:
Start
:Description:
Powers up and enables the needed hardware for the NeoPixels component
:returns:
None
"""
cmd = 0x00
PiSoC.commChannel.receive_data(self.address, cmd)
self.__running = True
def is_running(self):
"""
:Method:
is_running
:Description:
Checks to see if the NeoPixels display is currently powered up
:returns:
A boolean variable which evaluates to *True* if the NeoPixels display is running, or *False* if it is not
"""
return self.__running
def Stop(self):
"""
:Method:
Stop
:Description:
Powers down and disables the needed hardware for the NeoPixels component
:returns:
None
"""
cmd = 0x01
PiSoC.commChannel.receive_data(self.address, cmd)
self.__running = False
def RGB_to_hex(self, RGB):
"""
:Method:
RGB_to_hex
:Description:
Converts RGB content to the needed BRG Hex value taken by the NeoPixelShield device
:param RGB: A list or tuple containing three elements, each of which is limited to one byte (0-255)
* The first element is the Red byte
* The second element is the Green byte
* The thirf element is the Blue byte
:type RGB: list
:returns:
A hex value which can be used as a valid color input for :meth:`SetPixel`, :meth:`DrawRow`, :meth:`DrawColumn`, :meth:`Fill`, and :meth:`Stripe`.
Example Usage::
>>> from pisoc import *
>>> shield = NeoPixelShield()
>>> shield.Start()
>>> shield.SetBrightness(3)
>>> purple = shield.RGB_to_hex([255, 0, 255]) #purple = Full Red, No Green, Full Blue
>>> shield.Fill(purple)
"""
RGB = list(RGB)
for i in range(len(RGB)):
if RGB[i] >255:
logging.warning('Each color is limited to one byte only (0-255): provided %d as an element. Setting to 255' %i)
RGB[i] = 255
elif RGB[i] <0:
logging.warning('Each color is limited to one byte only (0-255): provided %d as an element. Setting to 0' %i)
RGB[i] = 0
RED = RGB[0]
GREEN = RGB[1]
BLUE = RGB[2]
return ((BLUE<<16)|(RED<<8)|GREEN)
def SetPixel(self, row, column, color):
"""
:Method:
SetPixel
:Description:
Sets the given pixel at location (x,y) = (row, column), to a color defined by a 24 bit Blue-Red-Green (BRG) value (8-bits each)
:param row:
Row which contains the desired pixel to be set. Valid entries are *0*-*4*.
:type row: int
:param column:
Column which contains the desired pixel to be set. Valid entries are *0*-*7*.
:type column: int
:param color: A 24-bit number representative of a BRG value
* BRG components are given equal weight, so 8-bits each
* There are predefined colors inside of :meth:`~__init__`, which can be called as shield.[*color name*]; example: :code:`shield.Blue`
:type color: int
:returns:
None
"""
cmd = 0x02
if color>0xFFFFFF:
raise ValueError('Color value too large. Color is 24 bit only.')
if row not in range(5):
raise ValueError('NeoPixel shield only has 5 rows available, choose 0-4')
if column not in range(8):
raise ValueError('NeoPixel shield only has 8 rows available, choose 0-7')
PiSoC.commChannel.receive_data(self.address, cmd, color>>16, (color>>8)&0xFF, color&0xFF, row, column, Hformat = [])
def ClearPixel(self, row, column):
"""
:Method:
ClearPixel
:Description:
Clears the given pixel at location (x,y) = (row, column)
:param row:
Row which contains the desired pixel to be set. Valid entries are *0*-*4*.
:type row: int
:param column:
Column which contains the desired pixel to be set. Valid entries are *0*-*7*.
:type column: int
:returns:
None
"""
self.SetPixel(row,column,self.Black)
def Stripe(self, pixelnum, color):
"""
:Method:
Stripe
:Description:
Draws a line of specified length in a desired color, starting from the first pixel,
and extending as far as the 40th (last) pixel. It will wrap around rows if required.
:param pixelnum: Indicates how many pixels, starting with pixel (0,0), will be filled. Valid input between *1* and *40*
:type pixelnum: int
:param color: A 24-bit number representative of a BRG value
* BRG components are given equal weight, so 8-bits each
* There are predefined colors inside of :meth:`~__init__`, which can be called as shield.*color_name*; example: :code:`shield.Blue`
:type color: int
:returns:
None
"""
if pixelnum not in range(1, 41):
try:
pixelnum = int(pixelnum)
except:
logging.warning("pixelnum must be int")
return
if pixelnum>40:
pixelnum = 40
elif pixelnum <1:
pixelnum = 1
logging.warning('Valid stripe length is between 1 and 40, Adusted to %s' %pixelnum)
pixelnum-=1
cmd = 0x03
if color>0xFFFFFF:
logging.warning("Color value is limited to 24 bits. Adjusting input to meet this requirement (0xFFFFFF)")
color = 0xFFFFFF
if color<0:
logging.warning("Color value must be positive. Adjusting input to meet this requirement (0x000000)")
color = 0
PiSoC.commChannel.receive_data(self.address, cmd, color>>16, (color>>8)&0xFF, color&0xFF, pixelnum, Hformat = [])
def DrawRow(self, row, color):
"""
:Method:
DrawRow
:Description:
Sets the pixels in a specified row to a desired color.
:param row:
Row which contains the desired pixel to be set. Valid entries are *0*-*4*.
:type row: int
:param color: A 24-bit number representative of a BRG value
* BRG components are given equal weight, so 8-bits each
* There are predefined colors inside of :meth:`~__init__`, which can be called as shield.[*color name*]; example: :code:`shield.Blue`
:type color: int
:returns:
None
"""
cmd = 0x05
if color>0xFFFFFF:
logging.warning("Color value is limited to 24 bits. Adjusting input to meet this requirement (0xFFFFFF)")
color = 0xFFFFFF
if color<0:
logging.warning("Color value must be positive. Adjusting input to meet this requirement (0x000000)")
color = 0
if row not in range(5):
try:
row = int(row)
except:
logging.warning("row input must be int")
return
if row<0:
row = 0
logging.warning("row must be positive. Setting to 0")
else:
row = 4
logging.warning("row must be less than or equal to 4. Setting to 4.")
PiSoC.commChannel.receive_data(self.address, cmd, color>>16, (color>>8)&0xFF, color&0xFF, row, Hformat = [])
def ClearRow(self, row):
"""
:Method:
ClearRow
:Description:
Clears all pixels within the specified row.
:param row:
Row which contains the desired pixel to be set. Valid entries are *0*-*4*.
:type row: int
:returns:
None
"""
self.DrawRow(row,self.Black)
def DrawColumn(self, column, color):
"""
:Method:
DrawColumn
:Description:
Sets the pixels in a specified column to a desired color.
:param column:
Column which contains the desired pixel to be set. Valid entries are *0*-*7*.
:type column: int
:param color: A 24-bit number representative of a BRG value
* BRG components are given equal weight, so 8-bits each
* There are predefined colors inside of :meth:`~__init__`, which can be called as shield.[*color name*]; example: :code:`shield.Blue`
:type color: int
:returns:
None
"""
cmd = 0x06
if color>0xFFFFFF:
logging.warning("Color value is limited to 24 bits. Adjusting input to meet this requirement (0xFFFFFF)")
color = 0xFFFFFF
if color<0:
logging.warning("Color value must be positive. Adjusting input to meet this requirement (0x000000)")
color = 0
if column not in range(8):
try:
column = int(column)
except:
logging.warning("column input must be int")
return
if column<0:
column = 0
logging.warning("column must be positive. Setting to 0")
else:
column = 7
logging.warning("column must be less than or equal to 7. Setting to 7.")
PiSoC.commChannel.receive_data(self.address, cmd, color>>16, (color>>8)&0xFF, color&0xFF, column, Hformat = [])
def ClearColumn(self, column):
"""
:Method:
ClearColumn
:Description:
Clears all pixels within a specified row
:param column:
Column which contains the desired pixel to be set. Valid entries are *0*-*7*.
:type column: int
:returns:
None
"""
self.DrawColumn(column, self.Black)
def SetBrightness(self, brightness):
"""
:Method:
SetBrightness
:Description:
Preserves the color of each pixel already drawn or to be drawn to the shield, but adjusts the brightness.
:param brightness:
Integer value in the range of *0* - *5*. A value of *0* will clear the display, and a value of 5 indicates maximum brigthness.
:type brightness: int
:returns:
None
"""
cmd = 0x04
if brightness == 0:
self.Clear()
elif brightness in range(1, 6):
dim_level = 5 - brightness
PiSoC.commChannel.receive_data(self.address, cmd, dim_level)
else:
logging.warning('Brightness level must be between 0 and 5.')
def Fill(self, color):
"""
:Method:
Fill
:Description:
Fills the entire display with a specified color.
:param color: A 24-bit number representative of a BRG value
* BRG components are given equal weight, so 8-bits each
* There are predefined colors inside of :meth:`~__init__`, which can be called as shield.[*color name*]; example: :code:`shield.Blue`
:type color: int
:returns:
None
"""
cmd = 0x07
PiSoC.commChannel.receive_data(self.address, cmd, color>>16, (color>>8)&0xFF, color&0xFF, Hformat = [])
def Clear(self):
"""
:Method:
Clear
:Description:
Clears the entire display.
:returns:
None
"""
self.Fill(self.Black)
class Tone(object):
"""
:Class:
The Tone class provides an easy way to integrate musical tones into your programs by setting Notes or frequencies which can be played through a piezo buzzer.
:Example:
Define a Tone object in any the following way::
>>> Note = Tone(0)
"""
def __init__(self, channel):
"""
:Method:
__init__
:Description:
Constructs and initializes the Tone object.
:param channel: Corresponds to the output pin of the Tone signal. Uses the same numbering convention as :class:`PWM`
:type channel: int
:returns:
None
"""
self.tone_PWM = PWM(channel)
self.channel = channel
self.tone_PWM.ReadPeriod()
self.cmp = self.tone_PWM.ReadCompare()
self.unit_vol = 1.0
self.__note_LUT = {'C': 0, 'D': 2, 'E': 4, 'F':5, 'G':7, 'A':9, 'B':11}
def __repr__(self):
return "Tone(channel=%s, volume=%s, note=%s, velocity=%s)"%(self.channel, self.GetVolume(), self.GetMIDI(), self.GetVelocity())
def Sleep(self):
"""
:Method:
Sleep
:Description:
Stops the Tone operation, puts the driving PWM component into it's lowest power state, and saves the current configuration
:returns:
None
"""
self.tone_PWM.Sleep()
def Wakeup(self):
"""
:Method:
Wakeup
:Description:
Restores and enables the most recently saved Tone configuration
:returns:
None
"""
self.tone_PWM.Wakeup()
def SetFrequency(self, freq, max_error = 5):
"""
:Method:
SetFrequency
:Description:
Attempts to set the Tone frequency to a desired rate by calculating an appropriate period value and/or clock rate for it's driving PWM
:param freq: A frequency in Hz which represents the desired wave rate
* If the frequency cannot be reached without changing the clock rate, any Tone objects sharing that clock will be affected
* For the suggested source clock rate of 24MHz, *freq* cannot be less than .006 Hz and cannot be more than 2.4 MHz (*2400000* Hz)
* Generally, *freq* cannot be less than :math:`\\frac{clock freq}{65535*(2^n - 1)}`, where n is the PWM resolution in bits, and it cannot be more than :math:`\\frac{clock freq}{MIN PERIOD}`
:type freq: float
:param max_error: The largest percentage of error that can be tolerated between the desired frequency and the achieved frequency
* This defaults to 5
* Verify the actual frequency with :meth:`~GetFrequency`
:type max_error: float
:returns:
None
"""
self.tone_PWM.SetFrequency(freq, max_error)
def GetFrequency(self, precision = 2):
"""
:Method:
GetFrequency
:Description:
Calculates the current Tone frequency based on known parameters of it's driving PWM
:param precision: Optional parameter. The number of decimal places which the result should be calculated to. Defaults to 2.
:type precision: int
:returns:
None
"""
return self.tone_PWM.GetFrequency(precision)
def SetMIDI(self, note, max_error = 5):
"""
:Method:
SetMIDI
:Description:
Generates a Tone frequency which corresponds to the specified MIDI note
:param note:
An integer Midi note, as defined by the Midi standard to correspond with a specific musical note
:type note: int
:param max_error: Optional parameter. The largest percentage of error that can be tolerated between the desired frequency and the achieved frequency.
* This defaults to 5
* This error rate is in reference to the wave frquency, in Hz, not the MIDI note number which is scaled differently than the frequency
:type max_error: float
:returns:
None
"""
self.tone_PWM.SetMIDI(note, max_error)
def GetMIDI(self):
"""
:Method:
GetMIDI
:Description:
Calculates what MIDI note corresponds to the current Tone frequency
:returns:
The Midi note, as defined by the Midi standard to correspond with a specific musical note
"""
return self.tone_PWM.GetMIDI()
def SetNote(self, note, octave, max_error = 5):
"""
:Method:
SetNote
:Description:
Sets the Tone frequency to that of a desired musical note
:param note: The desired letter note
* Valid parameters are *'A', 'A#', 'B', 'B#', 'C', 'C#', 'D', 'D#', 'E', 'E#', 'F', 'F#', 'G', 'G#'*
:type note: str
:param octave: The desired musical octave in which to play the note. Valid input between 0 and 9.
:type octave: int
:param max_error: Optional parameter. The largest percentage of error that can be tolerated between the desired frequency and the achieved frequency.
* This defaults to 5
* This error rate is in reference to the wave frquency, in Hz, not the MIDI note number which is scaled differently than the frequency
:type max_error: float
:returns:
None
"""
if octave<0:
logging.warning("octave must be greater than or equal to zero. Setting to zero.")
ocate = 0
if octave>9:
logging.warning("octave must be less than or equal to nine. Setting to nine.")
octave = 9
midi = octave*12
try:
if note.find('#') >-1:
midi+=1
note = ''.join([n.capitalize() for n in note if n.capitalize() in self.__note_LUT])
else:
note = note.capitalize()
except:
raise TypeError("%r is an invalid input type (%s) for note."%(n, type(n)))
midi+=self.__note_LUT[note]
self.SetMIDI(midi)
def SetVelocity(self, velocity):
"""
:Method:
SetVelocity
:Description:
Adjusts the volume of the note to correspond with the MIDI velocity standard
:param velocity:
The desired velocity. Valid input is between 0 and 127, as defined by the MIDI standard
:type velocity: int
:returns:
None
"""
if velocity<0:
velocity = 0
logging.warning("velocity must be greater than or equal to zero. Setting to zero.")
if velocity>127:
velocity = 127
logging.warning("velocity must be less than or equal to 127. Setting to 127.")
max_cmp = self.tone_PWM.period/2
self.cmp = int(max_cmp*(velocity/127.0))
self.tone_PWM.WriteCompare(self.cmp)
def GetVelocity(self):
"""
:Method:
GetVelocity
:Description:
Calculates the volume of the Tone and adjusts it to be consistent with the MIDI velocity standard
:returns:
The integer Tone velocity between 0 and 127, as defined by the Midi standard.
"""
velocity = float(self.cmp/(self.tone_PWM.period/2.0))*127.0
return int(velocity)
def SetVolume(self, volume, max_volume = 10, log_base = 2):
"""
:Method:
SetVolume
:Description:
Adjusts the volume of the note logarithmically according to the provided scale.
:param volume:
The desired volume between 0 and *max_volume*
:type volume: float
:param max_volume:
Optional parameter. The maximum volume level which will define the volume scale. Defaults to 10.
:type max_volume: float
:param log_base:
Optional parameter. The base of the logarithmic growth used to fit the volume growth to a logarithmic scale.
A higher base will result in less drastic volume adjustments in the lower range of the scale, and more
drastic ones towards the higher end. This can result in a more linear sounding volume adjustment, due to the
logarithmic nature of human hearing.
:type log_base: int
:returns:
None
"""
if volume<0:
volume = 0
logging.warning("Set volume level less than 0. Adjusting to 0")
if volume>max_volume:
volume = max_volume
logging.warning("Set volume level greater than the maximum. Adjusting volume level to maximum")
#human hearing is logarithmic. Let's try to fit the desired volume to a log scale...
self.unit_vol = float(volume)/float(max_volume)
log_base = int(log_base)
log_scaled = (pow(log_base, self.unit_vol) - 1)/float(log_base - 1)
max_cmp = int(self.tone_PWM.period/2)
self.cmp = int(max_cmp*log_scaled)
self.tone_PWM.WriteCompare(self.cmp)
def GetVolume(self, max_volume = 10):
"""
:Method:
GetVolume
:Description:
Calculates the current volume
:param max_volume:
Optional parameter. Scales the volume result according to a scale of *0* to max_volume. Default is 10.
:type max_volume: int
:returns:
Integer value reprsenting the current volume between 0 and max_volume
"""
volume = self.unit_vol*max_volume
return int(volume)
def Stop(self):
"""
:Method:
Stop
:Description:
Stops the tone by terminating the PWM channel that drives it
:returns:
None
"""
self.tone_PWM.Stop()
def is_running(self):
"""
:Method:
is_running
:Description:
Checks to see if the Tone's PWM component is currently operational
:returns:
None
"""
return self.tone_PWM._PWM__running
def Start(self):
"""
:Method:
Start
:Description:
Starts component operation.
:returns:
None
"""
self.tone_PWM.Start()
class SpeedController(Servo):
"""
:Class:
The SpeedController class is for use with Electronic Speed Controllers, such as those used to drive Quadcopters. This class inherits entirely from Servo.
:Example:
Use a SpeedController object in the following way::
>>> ESC = SpeedController(0)
|
"""
pass
|
EmbeditElectronics/Python_for_PSoC
|
API_Python/pisoc/digital.py
|
Python
|
mit
| 80,987
|
[
"Brian"
] |
0f81358564429fbff7e9f9050b32c2eddc43a2f0e975faecb4c34fa6668908a2
|
# coding: utf-8
# Copyright (c) Pymatgen Development Team.
# Distributed under the terms of the MIT License.
from __future__ import unicode_literals
import unittest
import json
import os
from monty.json import MontyDecoder
from pymatgen.analysis.defects.dilute_solution_model import *
import random
test_dir = os.path.join(os.path.dirname(__file__), "..", "..", "..", "..",
'test_files')
with open(
os.path.join(test_dir, 'mp1048_defect_formation_energies.json')) as fp:
formation_energy_dict = json.load(fp, cls=MontyDecoder)
with open(os.path.join(test_dir, 'mp1048_raw_defect_energies.json')) as fp:
raw_energy_dict = json.load(fp, cls=MontyDecoder)
with open(os.path.join(test_dir, 'mp1487_raw_defect_energies.json')) as fp:
mp1487_raw_energy_dict = json.load(fp, cls=MontyDecoder)
PULL_REQ = os.environ.get("CI_PULL_REQUEST", None) or os.environ.get("TRAVIS", None)
# TODO (from SP): You MUST redo this entire test. The whole test is
# monstrously slow. It takes more than 10 mins to get through this test alone.
@unittest.skipIf(PULL_REQ or random.randint(0, 10) % 10 != 0,
"Pull request or random skip.")
class DiluteSolutionModelTest(unittest.TestCase):
def setUp(self):
"""
Setup mandatory inputs for dilute_solution_model
"""
self.e0 = raw_energy_dict['bulk_energy']
self.asites = raw_energy_dict['antisites']
self.vac = raw_energy_dict['vacancies']
self.struct = raw_energy_dict['structure']
self.T = 600
self.trial_mu = formation_energy_dict[str(self.T)]['chemical_potential']
def test_formation_energies_without_chem_pot(self):
"""
Should generate formation energies without input chempot
"""
energies, chem_pot = dilute_solution_model(
self.struct, self.e0, self.vac, self.asites, self.T,
generate='energy')
self.assertIsNotNone(energies)
self.assertIsNotNone(chem_pot)
def test_formation_energies_with_chem_pot(self):
energies, chem_pot = dilute_solution_model(
self.struct, self.e0, self.vac, self.asites, self.T,
trial_chem_pot=self.trial_mu, generate='energy')
self.assertIsNotNone(energies)
self.assertIsNotNone(chem_pot)
def test_plot_data_without_chem_pot(self):
conc_data, en_data, mu_data = dilute_solution_model(
self.struct, self.e0, self.vac, self.asites, self.T,
generate='plot')
self.assertIsNotNone(conc_data)
self.assertIsNotNone(en_data)
self.assertIsNotNone(mu_data)
for key, value in conc_data.items():
self.assertIsNotNone(value)
for key, value in mu_data.items():
self.assertIsNotNone(value)
for key, value in en_data.items():
self.assertIsNotNone(value)
def test_plot_data_with_chem_pot(self):
conc_data, en_data, mu_data = dilute_solution_model(
self.struct, self.e0, self.vac, self.asites, self.T,
trial_chem_pot=self.trial_mu, generate='plot')
self.assertIsNotNone(conc_data)
self.assertIsNotNone(en_data)
self.assertIsNotNone(mu_data)
for key, value in conc_data.items():
self.assertIsNotNone(value)
for key, value in mu_data.items():
self.assertIsNotNone(value)
for key, value in en_data.items():
self.assertIsNotNone(value)
# print(plot_data['y'])
@unittest.skipIf(PULL_REQ or random.randint(0, 10) % 10 != 0,
"Pull request or random skip.")
class SoluteSiteFinderTest(unittest.TestCase):
def setUp(self):
"""
Setup mandatory inputs for dilute_solution_model
"""
self.e0 = mp1487_raw_energy_dict['bulk_energy']
self.asites = mp1487_raw_energy_dict['antisites']
self.vac = mp1487_raw_energy_dict['vacancies']
self.solutes = mp1487_raw_energy_dict['solutes']
self.struct = mp1487_raw_energy_dict['structure']
self.T = 1000
def test_plot_data_without_chem_pot(self):
plot_data = solute_site_preference_finder(
self.struct, self.e0, self.T, self.vac, self.asites, self.solutes,
solute_concen=0.01)
self.assertIsNotNone(plot_data)
def still_wait_plot_data_with_chem_pot(self):
plot_data = dilute_solution_model(
self.struct, self.e0, self.vac, self.asites, self.T,
trial_chem_pot=self.trial_mu, generate='plot')
self.assertIsNotNone(plot_data)
for key, value in plot_data.items():
self.assertIsNotNone(value)
if __name__ == "__main__":
unittest.main()
|
gpetretto/pymatgen
|
pymatgen/analysis/defects/tests/test_dilute_solution_model.py
|
Python
|
mit
| 4,730
|
[
"pymatgen"
] |
a44125b8646b809ff804824fb07defdc36779e35eec6c7c7e3d30d894c6da722
|
#!/usr/bin/env python
# /*******************************************************************
# * File: test_bulbchan.py
# * Description: Unittest for bulbchan
# * Author: Subhasis Ray
# * E-mail: ray dot subhasis at gmail dot com
# * Created: 2008-10-23 11:01:41
# ********************************************************************/
# /**********************************************************************
# ** This program is part of 'MOOSE', the
# ** Messaging Object Oriented Simulation Environment,
# ** also known as GENESIS 3 base code.
# ** copyright (C) 2008 Upinder S. Bhalla. and NCBS
# ** It is made available under the terms of the
# ** GNU General Public License version 2
# ** See the file COPYING.LIB for the full notice.
# **********************************************************************/
import math
import unittest
import moose
import bulbchan
class TestKMitralUSB(unittest.TestCase):
"""Create a compartment with one KMitralUSB channel and test with a current pulse."""
def __init__(self, *args):
unittest.TestCase.__init__(self, *args)
self.container = moose.Neutral("/TestKMitralUSB")
self.data = moose.Neutral("data", self.container)
self.sim_dt = 50e-6
self.io_dt = 50e-6
self.sim_length = 0.05
self.inject = 5e-10
self.erest_act = -0.065
moose.PyMooseBase.getContext().setClock(0, self.sim_dt, 0)
moose.PyMooseBase.getContext().setClock(1, self.sim_dt, 0)
moose.PyMooseBase.getContext().setClock(2, self.io_dt, 0)
def setUp(self):
pass
def testChannelCurrent(self):
# Set up a compartment for testing
compartment = moose.Compartment("compartment" , self.container)
compartment.length = 28e-6
compartment.diameter = 19e-6
s_area = math.pi * compartment.diameter * compartment.length
compartment.Rm = 2.0 / s_area
compartment.Cm = 0.01 * s_area
x_area = math.pi * compartment.diameter * compartment.diameter / 4.0
compartment.Ra = 0.5 * compartment.length / x_area
compartment.Ek = self.erest_act
compartment.inject = 0.0
print "Ra =", compartment.Ra, "Rm =", compartment.Rm, "Cm =", compartment.Cm
channel = bulbchan.KMitralUSB("K_channel", compartment)
channel.Ik = 0.0
channel.connect("channel", compartment, "channel")
print "Gbar =", channel.Gbar
pulse = moose.PulseGen("inject", self.container)
pulse.firstLevel = self.inject
pulse.firstWidth = 0.01
pulse.firstDelay = 0.01
# pulse.trigMode = 0
pulse.connect("outputSrc", compartment, "injectMsg")
channel_plot = moose.Table("KMitralUSB_Ik", self.data)
channel_plot.connect("inputRequest", channel, "Ik")
channel_plot.stepMode = 3
channel_plot.useClock(2)
inject_plot = moose.Table("KMitralUSB_inject", self.data)
inject_plot.connect("inputRequest", pulse, "output")
inject_plot.stepMode = 3
inject_plot.useClock(2)
vm_plot = moose.Table("KMitralUSB_Vm", self.data)
vm_plot.connect("inputRequest", compartment, "Vm")
vm_plot.stepMode = 3
vm_plot.useClock(2)
moose.PyMooseBase.getContext().reset()
moose.PyMooseBase.getContext().reset()
moose.PyMooseBase.getContext().step(self.sim_length)
channel_plot.dumpFile(channel_plot.name + ".pymoose.plot")
inject_plot.dumpFile(inject_plot.name + ".pymoose.plot")
vm_plot.dumpFile(vm_plot.name + ".pymoose.plot")
# ! testChannelCurrent
# ! TestKMitralUSB
class TestNaMitralUSB(unittest.TestCase):
"""Create a compartment with one KMitralUSB channel and test with a current pulse."""
def __init__(self, *args):
unittest.TestCase.__init__(self, *args)
self.container = moose.Neutral("/TestNaMitralUSB")
self.data = moose.Neutral("data", self.container)
self.sim_dt = 50e-6
self.io_dt = 50e-6
self.sim_length = 0.05
self.inject = 5e-10
self.erest_act = -0.065
moose.PyMooseBase.getContext().setClock(0, self.sim_dt, 0)
moose.PyMooseBase.getContext().setClock(1, self.sim_dt, 0)
moose.PyMooseBase.getContext().setClock(2, self.io_dt, 0)
def setUp(self):
pass
def testChannelCurrent(self):
# Set up a compartment for testing
compartment = moose.Compartment("compartment" , self.container)
compartment.length = 28e-6
compartment.diameter = 19e-6
s_area = math.pi * compartment.diameter * compartment.length
compartment.Rm = 2.0 / s_area
compartment.Cm = 0.01 * s_area
x_area = math.pi * compartment.diameter * compartment.diameter / 4.0
compartment.Ra = 0.5 * compartment.length / x_area
compartment.Ek = self.erest_act
channel = bulbchan.NaMitralUSB("Na_channel", compartment)
channel.connect("channel", compartment, "channel")
pulse = moose.PulseGen("inject", self.container)
pulse.firstLevel = self.inject
pulse.firstWidth = 0.01
pulse.firstDelay = 0.01
pulse.trigMode = 0
pulse.connect("outputSrc", compartment, "injectMsg")
channel_plot = moose.Table("NaMitralUSB_Ik", self.data)
channel_plot.connect("inputRequest", channel, "Ik")
channel_plot.stepMode = 3
channel_plot.useClock(2)
inject_plot = moose.Table("NaMitralUSB_inject", self.data)
inject_plot.connect("inputRequest", pulse, "output")
inject_plot.stepMode = 3
inject_plot.useClock(2)
moose.PyMooseBase.getContext().reset()
moose.PyMooseBase.getContext().step(self.sim_length)
# channel_plot.dumpFile(channel_plot.name + ".pymoose.plot")
# inject_plot.dumpFile(inject_plot.name + ".pymoose.plot")
if __name__ == "__main__":
unittest.main()
|
BhallaLab/moose-thalamocortical
|
DEMOS/pymoose/channels/test_bulbchan.py
|
Python
|
lgpl-2.1
| 6,028
|
[
"MOOSE"
] |
4ae95628aa8d062b5cbfc236c94d5b6c76dd9e2c283e37c7219b63097423c119
|
# Audio Tools, a module and set of tools for manipulating audio data
# Copyright (C) 2007-2016 Brian Langenberger
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2 of the License, or
# (at your option) any later version.
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
RESERVED = {"CATALOG": "CATALOG",
"CDTEXTFILE": "CDTEXTFILE",
"FILE": "FILE",
"BINARY": "BINARY",
"MOTOROLA": "MOTOROLA",
"AIFF": "AIFF",
"WAVE": "WAVE",
"FLAC": "FLAC",
"FLAGS": "FLAGS",
"DCP": "DCP",
"PRE": "PRE",
"SCMS": "SCMS",
"INDEX": "INDEX",
"ISRC": "ISRC_ID",
"PERFORMER": "PERFORMER",
"POSTGAP": "POSTGAP",
"PREGAP": "PREGAP",
"SONGWRITER": "SONGWRITER",
"TITLE": "TITLE",
"TRACK": "TRACK",
"AUDIO": "AUDIO",
"CDG": "CDG"}
tokens = ["REM",
"ISRC",
"TIMESTAMP",
"MP3",
"MODE",
"CDI",
"NUMBER",
"ID",
"STRING"] + list(RESERVED.values())
def t_REM(t):
r"REM .*"
pass
def t_ISRC(t):
r'[A-Z]{2}[A-Za-z0-9]{3}[0-9]{7}'
return t
def t_TIMESTAMP(t):
r'[0-9]{1,3}:[0-9]{1,2}:[0-9]{1,2}'
(m, s, f) = t.value.split(":")
t.value = ((int(m) * 75 * 60) + (int(s) * 75) + (int(f)))
return t
def t_MP3(t):
r'MP3'
return t
def t_MODE(t):
r'MODE1/2048|MODE1/2352|MODE2/2336|MODE2/2352'
return t
def t_CDI(t):
r'CDI/2336|CDI/2352'
return t
def t_NUMBER(t):
r'[0-9]+'
t.value = int(t.value)
return t
def t_ID(t):
r"[A-Z]+"
if t.value in RESERVED.keys():
t.type = RESERVED[t.value]
else:
t.type = "STRING"
return t
def t_STRING(t):
r'\"(\\.|[^"])*\"'
from re import sub
t.value = sub(r'\\.', lambda s: s.group(0)[1:], t.value[1:-1])
return t
t_ignore = " \r\t"
def t_newline(t):
r'\n+'
t.lexer.lineno += t.value.count("\n")
def t_error(t):
raise ValueError("illegal character {!r}".format(t.value[0]))
|
tuffy/python-audio-tools
|
audiotools/cue/tokrules.py
|
Python
|
gpl-2.0
| 2,695
|
[
"Brian"
] |
5b0febb6e0e7a6eaabecd3b05c3ece236ba436f83e50408f141a808bc73947ee
|
#! /usr/bin/env python3
# -*- coding: utf-8 -*-
"""
@name: PyHouse/src/setup.py
@author: D. Brian Kimmel
@contact: D.BrianKimmel@gmail.com
@copyright: (c) 2013-2019 by D. Brian Kimmel
@note: Created on Aug 3, 2013
@license: MIT License
@summary: This module is for Insteon
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
This will take the distribution directory and move the needed files to the
correct place for running.
This may be run at any time to put new versions of the files to be moved.
Runs on:
Linux (OpenSuse 12.3)
Raspberry Pi w/ Wheezy
PyHouse
admin
doc
PcDuino
src
README.rst
TODO.rst
apt install:
python-dev
"""
__updated__ = '2019-07-12'
# Import system type stuff
import sys
from setuptools import setup
import os
sys.path.insert(0, os.path.join(os.path.dirname(os.path.realpath(__file__)), "src"))
# Requirements for the PyHouse application
INSTALL_REQUIRES = [
# sudo apt install libffi-dev libssl-dev libxml2-dev libxslt1-dev libjpeg8-dev
'aniso8601',
'astral >= 1.2',
# 'athena >= 0.8',
'autobahn',
# 'idna >= 2.0',
'jsonpickle >= 0.9.4',
'netaddr',
'netifaces',
# 'nevow >= 0.0.0',
# 'passlib',
# 'pyasn1 >= 0.1.8',
# 'pycrypto',
'pyOpenSSL',
'python-dateutil',
# 'pyserial',
# 'pytz',
'pyudev',
# 'pyusb',
'service-identity',
'twisted >= 16.0.0'
]
EXTRA_REQUIRES = {}
# Dependency links for any of the aforementioned dependencies
DEPENDENCY_LINKS = []
CLASSIFIERS = [
'Development Status :: 5 - Production/Stable',
'Environment :: Web Environment',
'Intended Audience :: End Users/Desktop',
'License :: OSI Approved :: MIT License',
'Natural Language :: English',
'Operating System :: POSIX :: Linux',
'Programming Language :: Python :: 3.5',
'Programming Language :: JavaScript',
'Topic :: Home Automation'
]
setup(
name='PyHouse',
version='17.3.1',
description='Pythone house automation',
author='D. Brian Kimmel',
author_email='D.BrianKimmel@gmail.com',
url='http://www.PyHouse.org',
license='MIT',
classifiers=CLASSIFIERS,
py_modules=[ 'PyHouse' ],
package_dir={'': 'src'},
extras_require=EXTRA_REQUIRES,
dependency_links=DEPENDENCY_LINKS,
include_package_data=True,
zip_safe=False,
install_requires=INSTALL_REQUIRES
)
tests_passed = False
def FindOsRunning():
"""
"""
import platform
l_platform = platform.platform(True, True)
print("Running on platform {}".format(l_platform))
class InitialInstall(object):
"""
Must run as root on fresh install of raspbian jessie!
Add user pyhouse
Create /etc/pyhouse owned by pyhouse user
Create /var/log/pyhouse owned by pyhouse user
Create firewall, network config.
Add .ssh dir and initial credentials.
"""
class SoftwareInstall(object):
"""
Add workspace and populate it with PyHouse git repository
Set up start/stop/update scripts.
"""
class TestInstalledSoftware(object):
"""Test to see if all required software is installed.
"""
def test_python_version(self):
l_version = sys.version_info
if l_version.major != 3:
print("ERROR - Move to Python 3.")
return False
if l_version.minor < 4:
print("ERROR - Python less than version is not tested - Please use 3.x.x")
return False
print(" Python 3 ok...")
return True
def test_twisted(self):
try:
import twisted
except ImportError:
print("ERROR - Twisted not installed. apt-get install python-twisted")
return False
l_version = twisted.version
if l_version.major < 16:
print("ERROR - Twisted must be at least version 16. apt-get install python-twisted")
print(" Twisted >= 16.0 ok...")
return True
def test_zope_interface(self):
try:
import zope.interface
except ImportError:
print("ERROR - Zope.Interface not installed. apt-get install zope-interface")
return False
print(" Zope.interface ok...")
return True
def test_nevow(self):
try:
import nevow
except ImportError:
print("ERROR - Nevow not installed. apt-get install nevow")
return False
print(" Nevow ok...")
return True
class TestAll(object):
"""Test everything.
"""
def __init__(self):
global tests_passed
print("Testing...")
l_inst = TestInstalledSoftware()
l_ok = l_inst.test_python_version()
if l_ok:
l_ok = l_inst.test_twisted()
if l_ok:
l_ok = l_inst.test_zope_interface()
if l_ok:
l_ok = l_inst.test_nevow()
if l_ok:
tests_passed = True
class Install(object):
"""
"""
def __init__(self):
print("Installing...")
if __name__ == "__main__":
print('Main...')
# FindOsRunning()
# TestAll()
# if tests_passed:
# Install()
# pass
# else:
# print("Correct the above faults and rerun.")
# ## END DBK
|
DBrianKimmel/PyHouse
|
Project/setup.py
|
Python
|
mit
| 6,279
|
[
"Brian"
] |
92dd94b917ba731a1fcb5bf3ad2934fe0b867eb3b1561e803686a84824fcf93c
|
import logging
import itertools
from typing import Tuple, List
import numpy as np
import scipy.stats.kde
from PyQt5 import QtWidgets, QtCore
from matplotlib.axes import Axes
from matplotlib.lines import Line2D
import matplotlib.cm
from matplotlib.backends.backend_qt5agg import FigureCanvasQTAgg, NavigationToolbar2QT
from matplotlib.figure import Figure
from matplotlib.backend_bases import PickEvent
from .outliertest_ui import Ui_Form
from .resultviewwindow import ResultViewWindow
from .showimage import ShowImageWindow
from .showcurve import ShowCurveWindow
from ..utils.plotcurve import PlotCurve
from ...core2.dataclasses import Header
from ...core2.processing.calculations.outliertest import OutlierTest
logger = logging.getLogger(__name__)
logger.setLevel(logging.INFO)
class SortFilterModel(QtCore.QSortFilterProxyModel):
samplename: str
distkey: str
def __init__(self, samplename: str, distkey: str):
self.samplename = samplename
self.distkey = distkey
super().__init__()
def filterAcceptsRow(self, source_row: int, source_parent: QtCore.QModelIndex) -> bool:
data = self.sourceModel().index(source_row, 0, source_parent).data(QtCore.Qt.UserRole)
assert isinstance(data, Header)
return (data.title == self.samplename) and (f'{data.distance[0]:.2f}' == self.distkey)
def filterAcceptsColumn(self, source_column: int, source_parent: QtCore.QModelIndex) -> bool:
caption = self.sourceModel().headerData(source_column, QtCore.Qt.Horizontal, QtCore.Qt.DisplayRole)
return caption in ['fsn', 'enddate']
class OutlierTestWindow(ResultViewWindow, Ui_Form):
outliertestresults : OutlierTest
cmatfigure: Figure
cmatcanvas: FigureCanvasQTAgg
cmatfigtoolbar: NavigationToolbar2QT
cmataxes: Axes
otfigure: Figure
otcanvas: FigureCanvasQTAgg
otfigtoolbar: NavigationToolbar2QT
otaxes: Axes
otkdeaxes: Axes
sortfiltermodel: SortFilterModel
plotcurve: PlotCurve
otmarkedline: Line2D
cmatmarkers: List[Line2D]
def setupUi(self, Form):
super().setupUi(Form)
self.project.results.modelReset.connect(self.redraw)
self.cmatfigure = Figure(figsize=(5, 3), constrained_layout=True)
self.cmatcanvas = FigureCanvasQTAgg(self.cmatfigure)
self.cmatcanvas.mpl_connect('pick_event', self.cmatPicked)
self.cmatfigtoolbar = NavigationToolbar2QT(self.cmatcanvas, self.correlMatrixTab)
self.correlMatrixTab.setLayout(QtWidgets.QVBoxLayout())
self.correlMatrixTab.layout().addWidget(self.cmatfigtoolbar)
self.correlMatrixTab.layout().addWidget(self.cmatcanvas, 1)
self.cmataxes = self.cmatfigure.add_subplot(self.cmatfigure.add_gridspec(1, 1)[:, :])
self.otfigure = Figure(figsize=(5, 3), constrained_layout=True)
self.otcanvas = FigureCanvasQTAgg(self.otfigure)
self.otcanvas.mpl_connect('pick_event', self.otPicked)
self.otfigtoolbar = NavigationToolbar2QT(self.otcanvas, self.outlierTestTab)
self.outlierTestTab.setLayout(QtWidgets.QVBoxLayout())
self.outlierTestTab.layout().addWidget(self.otfigtoolbar)
self.outlierTestTab.layout().addWidget(self.otcanvas)
self.plotcurve = PlotCurve(self.curvesTab)
self.curvesTab.setLayout(QtWidgets.QVBoxLayout())
self.curvesTab.layout().addWidget(self.plotcurve)
gs = self.otfigure.add_gridspec(1, 8)
self.otaxes = self.otfigure.add_subplot(gs[:, :-1])
self.otkdeaxes = self.otfigure.add_subplot(gs[:, -1], sharey=self.otaxes)
self.sortfiltermodel = SortFilterModel(self.samplename, self.distancekey)
self.sortfiltermodel.setSourceModel(self.project.headers)
self.treeView.setModel(self.sortfiltermodel)
for col in range(self.sortfiltermodel.columnCount(QtCore.QModelIndex())):
self.treeView.resizeColumnToContents(col)
self.reloadPushButton.clicked.connect(self.project.headers.start)
self.showCurvePushButton.clicked.connect(self.showCurve)
self.showImagePushButton.clicked.connect(self.showImage)
self.treeView.selectionModel().selectionChanged.connect(self.fsnSelectionChanged)
self.onResultItemChanged(self.samplename, self.distancekey)
self.markBadPushButton.clicked.connect(self.markExposures)
self.markGoodPushButton.clicked.connect(self.markExposures)
def markExposures(self):
fsns = [index.data(QtCore.Qt.UserRole).fsn for index in self.treeView.selectionModel().selectedRows(0)]
if self.sender() is self.markBadPushButton:
self.project.settings.markAsBad(fsns)
elif self.sender() is self.markGoodPushButton:
self.project.settings.markAsGood(fsns)
def redraw(self):
self.cmatfigure.clear()
self.cmataxes = self.cmatfigure.add_subplot(self.cmatfigure.add_gridspec(1, 1)[:, :])
im = self.cmataxes.imshow(self.outliertestresults.correlmatrix, cmap='coolwarm', interpolation='nearest', origin='upper', picker=5)
self.cmatfigure.colorbar(im, ax=self.cmataxes)
self.cmataxes.set_xticks(np.arange(len(self.outliertestresults.fsns)))
self.cmataxes.set_xticklabels([str(f) for f in self.outliertestresults.fsns], rotation=90)
self.cmataxes.set_yticks(np.arange(len(self.outliertestresults.fsns)))
self.cmataxes.set_yticklabels([str(f) for f in self.outliertestresults.fsns])
self.cmataxes.set_title(f'{self.samplename} @ {self.distancekey} mm')
self.otaxes.clear()
rmin, rmax = self.outliertestresults.acceptanceInterval()
self.otaxes.axhspan(rmin, rmax, color='lightgreen', alpha=0.5)
self.otaxes.axhline(rmin, color='lightgreen', ls='--')
self.otaxes.axhline(rmax, color='lightgreen', ls='--')
self.otaxes.plot(self.outliertestresults.fsns, self.outliertestresults.score, 'b.', pickradius=5, picker=True)
self.otaxes.set_title(f'{self.samplename} @ {self.distancekey} mm')
self.otmarkedline = self.otaxes.scatter(self.outliertestresults.fsns, self.outliertestresults.score, [0.0]*len(self.outliertestresults.fsns), c='none', edgecolors='red')
self.otkdeaxes.clear()
kde = scipy.stats.kde.gaussian_kde(self.outliertestresults.score)
y = np.linspace(min(np.nanmin(self.outliertestresults.score) - np.ptp(self.outliertestresults.score) * 0.1, rmin),
max(np.nanmax(self.outliertestresults.score) + np.ptp(self.outliertestresults.score), rmax), 300)
self.otkdeaxes.plot(kde(y), y)
self.otkdeaxes.set_xlabel('Gaussian KDE')
self.otkdeaxes.yaxis.set_label_position('right')
self.otkdeaxes.yaxis.set_ticks_position('right')
self.otaxes.set_xlabel('File sequence number')
self.otaxes.set_ylabel('Outlier score')
self.otcanvas.draw()
self.cmatcanvas.draw()
self.setWindowTitle(f'Outlier test results for {self.samplename} @ {self.distancekey} mm')
self.plotcurve.clear()
self.plotcurve.setShowErrorBars(False)
self.plotcurve.setPixelMode(False)
self.cmatmarkers = []
curves = self.project.settings.h5io.readCurves(f'Samples/{self.samplename}/{self.distancekey}')
for i, fsn in enumerate(sorted(curves)):
self.plotcurve.addCurve(curves[fsn], label=f'{fsn}', color=matplotlib.cm.inferno(i/(len(curves)-1)))
self.plotcurve.replot()
def showImage(self):
for index in self.treeView.selectionModel().selectedRows(0):
header = index.data(QtCore.Qt.UserRole)
self.mainwindow.createViewWindow(
ShowImageWindow, items=[('', str(header.fsn))])
def showCurve(self):
fsns = sorted([index.data(QtCore.Qt.UserRole).fsn for index in self.treeView.selectionModel().selectedRows(0)])
if not fsns:
return
self.mainwindow.createViewWindow(ShowCurveWindow, [('', str(fsn)) for fsn in fsns])
def onResultItemChanged(self, samplename: str, distkey: str):
self.outliertestresults = self.project.settings.h5io.readOutlierTest(f'Samples/{self.samplename}/{self.distancekey}')
self.redraw()
@property
def samplename(self) -> str:
return self.resultitems[0][0]
@property
def distancekey(self) -> str:
return self.resultitems[0][1]
def otPicked(self, event: PickEvent):
logger.debug(event.artist)
logger.debug(dir(event))
logger.debug(f'{event.ind=}, {event.guiEvent=}, {event.name=}')
pickedindex = event.ind[0]
fsn = event.artist.get_xdata()[pickedindex]
for row in range(self.treeView.model().rowCount(QtCore.QModelIndex())):
index = self.treeView.model().index(row, 0, QtCore.QModelIndex())
if self.treeView.model().data(index, QtCore.Qt.UserRole).fsn == fsn:
if self.treeView.selectionModel().isRowSelected(row, QtCore.QModelIndex()):
self.treeView.selectionModel().select(index, QtCore.QItemSelectionModel.Rows | QtCore.QItemSelectionModel.Deselect)
else:
self.treeView.selectionModel().select(index, QtCore.QItemSelectionModel.Rows | QtCore.QItemSelectionModel.Select)
def cmatPicked(self, event: PickEvent):
logger.debug([event.mouseevent.xdata, event.mouseevent.ydata])
col = int(round(event.mouseevent.xdata))
row = int(round(event.mouseevent.ydata))
for i in {row, col}:
fsn = self.outliertestresults.fsns[i]
for row in range(self.treeView.model().rowCount(QtCore.QModelIndex())):
index = self.treeView.model().index(row, 0, QtCore.QModelIndex())
if self.treeView.model().data(index, QtCore.Qt.UserRole).fsn == fsn:
if self.treeView.selectionModel().isRowSelected(row, QtCore.QModelIndex()):
self.treeView.selectionModel().select(index, QtCore.QItemSelectionModel.Rows | QtCore.QItemSelectionModel.Deselect)
else:
self.treeView.selectionModel().select(index, QtCore.QItemSelectionModel.Rows | QtCore.QItemSelectionModel.Select)
def fsnSelectionChanged(self, selected, deselected):
selectedfsns = [index.data(QtCore.Qt.UserRole).fsn for index in self.treeView.selectionModel().selectedRows(0)]
sizes = self.otmarkedline.get_sizes()
for i in range(sizes.size):
sizes[i] = 0 if self.outliertestresults.fsns[i] not in selectedfsns else 100
self.otmarkedline.set_sizes(sizes)
self.otcanvas.draw_idle()
for line in self.cmatmarkers:
line.remove()
self.cmatmarkers = []
for fsn in selectedfsns:
try:
index = [i for i in range(self.outliertestresults.fsns.size) if self.outliertestresults.fsns[i] == fsn][0]
except IndexError:
continue
self.cmatmarkers.append(self.cmataxes.axhline(index, color='black', ls='--'))
self.cmatmarkers.append(self.cmataxes.axvline(index, color='black', ls='--'))
self.cmatcanvas.draw_idle()
|
awacha/cct
|
cct/qtgui2/processingmain/outliertest.py
|
Python
|
bsd-3-clause
| 11,189
|
[
"Gaussian"
] |
038bf82509dca3e75303c8f4ed2c3fd247322b5c5546f25cdb621c84745ffe31
|
""" Module contains test fixtures meant to aide in the testing of jobs and
tool evaluation. Such extensive "fixtures" are something of an anti-pattern
so use of this should be limitted to tests of very 'extensive' classes.
"""
from collections import defaultdict
import os.path
import tempfile
import shutil
from galaxy.util.bunch import Bunch
from galaxy.web.security import SecurityHelper
import galaxy.model
from galaxy.model import mapping
from galaxy.tools import Tool
from galaxy.util import parse_xml
from galaxy.util.dbkeys import GenomeBuilds
from galaxy.jobs import NoopQueue
from galaxy.tools.deps.containers import NullContainerFinder
class UsesApp( object ):
def setup_app( self, mock_model=True ):
self.test_directory = tempfile.mkdtemp()
self.app = MockApp( self.test_directory, mock_model=mock_model )
def tear_down_app( self ):
shutil.rmtree( self.test_directory )
# Simple tool with just one text parameter and output.
SIMPLE_TOOL_CONTENTS = '''<tool id="test_tool" name="Test Tool">
<command>echo "$param1" < $out1</command>
<inputs>
<param type="text" name="param1" value="" />
</inputs>
<outputs>
<data name="out1" format="data" label="Output ($param1)" />
</outputs>
</tool>
'''
# A tool with data parameters (kind of like cat1) my favorite test tool :)
SIMPLE_CAT_TOOL_CONTENTS = '''<tool id="test_tool" name="Test Tool">
<command>cat "$param1" #for $r in $repeat# "$r.param2" #end for# < $out1</command>
<inputs>
<param type="data" format="tabular" name="param1" value="" />
<repeat name="repeat1" label="Repeat 1">
<param type="data" format="tabular" name="param2" value="" />
</repeat>
</inputs>
<outputs>
<data name="out1" format="data" />
</outputs>
</tool>
'''
class UsesTools( object ):
def _init_tool( self, tool_contents=SIMPLE_TOOL_CONTENTS ):
self.tool_file = os.path.join( self.test_directory, "tool.xml" )
self.app.config.drmaa_external_runjob_script = ""
self.app.config.tool_secret = "testsecret"
self.app.config.track_jobs_in_database = False
self.app.job_config["get_job_tool_configurations"] = lambda ids: [Bunch(handler=Bunch())]
self.__write_tool( tool_contents )
self.__setup_tool( )
def __setup_tool( self ):
tree = parse_xml( self.tool_file )
self.tool = Tool( self.tool_file, tree.getroot(), self.app )
if getattr( self, "tool_action", None ):
self.tool.tool_action = self.tool_action
def __write_tool( self, contents ):
open( self.tool_file, "w" ).write( contents )
class MockApp( object ):
def __init__( self, test_directory, mock_model=True ):
# The following line is needed in order to create
# HistoryDatasetAssociations - ideally the model classes would be
# usable without the ORM infrastructure in place.
in_memomry_model = mapping.init( "/tmp", "sqlite:///:memory:", create_tables=True )
self.datatypes_registry = Bunch(
integrated_datatypes_configs='/galaxy/integrated_datatypes_configs.xml',
get_datatype_by_extension=lambda ext: Bunch(),
)
self.config = Bunch(
outputs_to_working_directory=False,
new_file_path=os.path.join(test_directory, "new_files"),
tool_data_path=os.path.join(test_directory, "tools"),
root=os.path.join(test_directory, "galaxy"),
admin_users="mary@example.com",
len_file_path=os.path.join( 'tool-data', 'shared', 'ucsc', 'chrom' ),
builds_file_path=os.path.join( 'tool-data', 'shared', 'ucsc', 'builds.txt.sample' ),
)
# Setup some attributes for downstream extension by specific tests.
self.job_config = Bunch(
dynamic_params=None,
)
# Two ways to handle model layer, one is to stub out some objects that
# have an interface similar to real model (mock_model) and can keep
# track of 'persisted' objects in a map. The other is to use a real
# sqlalchemy layer but target an in memory database. Depending on what
# is being tested.
if mock_model:
# Create self.model to mimic app.model.
self.model = Bunch( context=MockContext() )
for module_member_name in dir( galaxy.model ):
module_member = getattr(galaxy.model, module_member_name)
if type( module_member ) == type:
self.model[ module_member_name ] = module_member
else:
self.model = in_memomry_model
self.genome_builds = GenomeBuilds( self )
self.toolbox = None
self.object_store = None
self.security = SecurityHelper(id_secret="testing")
from galaxy.security import GalaxyRBACAgent
self.job_queue = NoopQueue()
self.security_agent = GalaxyRBACAgent( self.model )
self.tool_data_tables = {}
self.dataset_collections_service = None
self.container_finder = NullContainerFinder()
class MockContext(object):
def __init__(self, model_objects=None):
self.expunged_all = False
self.flushed = False
self.model_objects = model_objects or defaultdict( lambda: {} )
self.created_objects = []
def expunge_all(self):
self.expunged_all = True
def query(self, clazz):
return MockQuery(self.model_objects.get(clazz))
def flush(self):
self.flushed = True
def add(self, object):
self.created_objects.append(object)
class MockQuery(object):
def __init__(self, class_objects):
self.class_objects = class_objects
def filter_by(self, **kwds):
return Bunch(first=lambda: None)
def get(self, id):
return self.class_objects.get(id, None)
__all__ = [ UsesApp ]
|
mikel-egana-aranguren/SADI-Galaxy-Docker
|
galaxy-dist/test/unit/tools_support.py
|
Python
|
gpl-3.0
| 5,926
|
[
"Galaxy"
] |
158a13dc0d2fa57ded13498016e4afa6fce9a9aa5a9d1a25244814dfe80655be
|
#!/usr/bin/env python
# coding=utf-8
"""490. Jumping frog
https://projecteuler.net/problem=490
There are n stones in a pond, numbered 1 to n. Consecutive stones are spaced
one unit apart.
A frog sits on stone 1. He wishes to visit each stone exactly once, stopping
on stone n. However, he can only jump from one stone to another if they are at
most 3 units apart. In other words, from stone i, he can reach a stone j if 1
≤ j ≤ n and j is in the set {i-3, i-2, i-1, i+1, i+2, i+3}.
Let f(n) be the number of ways he can do this. For example, f(6) = 14, as
shown below:
1 → 2 → 3 → 4 → 5 → 6
1 → 2 → 3 → 5 → 4 → 6
1 → 2 → 4 → 3 → 5 → 6
1 → 2 → 4 → 5 → 3 → 6
1 → 2 → 5 → 3 → 4 → 6
1 → 2 → 5 → 4 → 3 → 6
1 → 3 → 2 → 4 → 5 → 6
1 → 3 → 2 → 5 → 4 → 6
1 → 3 → 4 → 2 → 5 → 6
1 → 3 → 5 → 2 → 4 → 6
1 → 4 → 2 → 3 → 5 → 6
1 → 4 → 2 → 5 → 3 → 6
1 → 4 → 3 → 2 → 5 → 6
1 → 4 → 5 → 2 → 3 → 6
Other examples are f(10) = 254 and f(40) = 1439682432976.
Let S(L) = ∑ f(n)3 for 1 ≤ n ≤ L.
Examples:
S(10) = 18230635
S(20) = 104207881192114219
S(1 000) mod 109 = 225031475
S(1 000 000) mod 109 = 363486179
Find S(1014) mod 109.
"""
|
openqt/algorithms
|
projecteuler/pe490-jumping-frog.py
|
Python
|
gpl-3.0
| 1,306
|
[
"VisIt"
] |
36d4e846aa24ad6556a1a052c1e4275882a3f26a057683a33bc2921ab6afa764
|
"""
Copyright (C) 2004-2015 Pivotal Software, Inc. All rights reserved.
This program and the accompanying materials are made available under
the terms of the under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
"""
import os
import sys
import shutil
from contextlib import closing
from datetime import datetime
from StringIO import StringIO
import unittest2 as unittest
from unittest2.runner import _WritelnDecorator
from tinctest import TINCTestLoader
from tinctest import TINCTextTestResult
from mpp.models.mpp_tc import _MPPMetaClassType
from mpp.models.mpp_tc import MPPDUT
from mpp.models import SQLTestCase, SQLTestCaseException
# Since we overwrite optimizer_mode depending on product/version, force the internal variables to gpdb/4.3
# This will ensure that optimizer_mode both works as designed, and all the tests written for that works.
# _MPPMetaClassType.DUT = MPPDUT('gpdb', '4.3')
@unittest.skip('mock')
class MockSQLTestCase(SQLTestCase):
"""
@description test case with metadata
@created 2012-07-05 12:00:00
@modified 2012-07-05 12:00:02
@tags orca hashagg
@gucs gp_optimizer=on;gp_log_optimizer=on
@optimizer_mode ON
"""
def setUp(self):
pass
def test_explicit_definition(self):
pass
@unittest.skip('mock')
class MockSQLTemplateTestCase(SQLTestCase):
template_dir = 'template_dir'
template_subs = {'%PERCENTAGE%' : 'my_percent',
'&&' : 'my_amp',
'@AT' : 'my_at'}
@unittest.skip('mock')
class MockSQLTemplateTestCaseExplicit(SQLTestCase):
template_dir = 'template_dir'
template_subs = {'%PERCENTAGE%' : 'my_percent',
'&&' : 'my_amp',
'@AT' : 'my_at'}
@unittest.skip('mock')
class MockSQLTemplateTestCaseRegular(SQLTestCase):
template_dir = 'template_dir'
template_subs = {'%PERCENTAGE%' : 'my_percent',
'&&' : 'my_amp',
'@AT' : 'my_at'}
class MockMPPMetaClassTypeGPDB43(_MPPMetaClassType):
_MPPMetaClassType.DUT = MPPDUT('gpdb', '4.3')
@unittest.skip('mock')
class MockSQLTestCaseForOptimizerMode(SQLTestCase):
"""
@description test case with metadata
@created 2012-07-05 12:00:00
@modified 2012-07-05 12:00:02
@tags orca hashagg
@gucs gp_optimizer=on;gp_log_optimizer=on
@optimizer_mode on
"""
__metaclass__ = MockMPPMetaClassTypeGPDB43
pass
@unittest.skip('mock')
class MockSQLTestCaseForOptimizerModeBoth(SQLTestCase):
"""
@optimizer_mode both
"""
__metaclass__ = MockMPPMetaClassTypeGPDB43
pass
@unittest.skip('mock')
class MockSQLTestCaseInvalidOptimizerMode(SQLTestCase):
"""
@optimizer_mode invalid_value
"""
__metaclass__ = MockMPPMetaClassTypeGPDB43
pass
class MockMPPMetaClassTypeHAWQ(_MPPMetaClassType):
_MPPMetaClassType.DUT = MPPDUT('hawq', '1.1.0.0')
@unittest.skip('mock')
class MockSQLTestCaseOptimizerModeHAWQ(SQLTestCase):
__metaclass__ = MockMPPMetaClassTypeHAWQ
def test_optimizer_mode_both(self):
"""
@optimizer_mode both
"""
pass
def test_optimizer_mode_on(self):
"""
@optimizer_mode on
"""
pass
def test_optimizer_mode_off(self):
"""
@optimizer_mode off
"""
pass
class SQLTestCaseTests(unittest.TestCase):
def test_infer_metadata(self):
test_loader = TINCTestLoader()
test_suite = test_loader.loadTestsFromTestCase(MockSQLTestCase)
test_case = None
for case in test_suite._tests:
if case.name == "MockSQLTestCase.test_query02":
test_case = case
self.assertNotEqual(test_case, None)
self.assertEqual(test_case.name, "MockSQLTestCase.test_query02")
self.assertEqual(test_case.author, 'kumara64')
self.assertEqual(test_case.description, 'test sql test case')
self.assertEqual(test_case.created_datetime, datetime.strptime('2012-07-05 12:00:00', '%Y-%m-%d %H:%M:%S'))
self.assertEqual(test_case.modified_datetime, datetime.strptime('2012-07-08 12:00:02', '%Y-%m-%d %H:%M:%S'))
self.assertEqual(test_case.tags, set(['orca', 'hashagg', 'executor']))
self.assertEqual(test_case.gucs, set(['gp_optimizer=on', 'gp_log_optimizer=on']))
def test_optimizer_mode_from_sql_file(self):
test_case = MockSQLTestCaseForOptimizerMode('test_query02')
# sql file query02.sql has overriden optimizer_mode
self.assertEqual(test_case.optimizer_mode, 'off')
def test_optimizer_mode_from_class(self):
test_case = MockSQLTestCaseForOptimizerMode('test_query03')
self.assertEqual(test_case.optimizer_mode, 'on')
def test_optimizer_mode_invalid_value(self):
with self.assertRaises(SQLTestCaseException) as cm:
test_case = MockSQLTestCaseInvalidOptimizerMode('test_query01')
def test_direct_instantiation(self):
test_case = MockSQLTestCase('test_query02')
self.assertEqual(test_case.name, "MockSQLTestCase.test_query02")
self.assertEqual(test_case.author, 'kumara64')
self.assertEqual(test_case.description, 'test sql test case')
self.assertEqual(test_case.created_datetime, datetime.strptime('2012-07-05 12:00:00', '%Y-%m-%d %H:%M:%S'))
self.assertEqual(test_case.modified_datetime, datetime.strptime('2012-07-08 12:00:02', '%Y-%m-%d %H:%M:%S'))
self.assertEqual(test_case.tags, set(['orca', 'hashagg', 'executor']))
def test_explicit_test_fixtures(self):
test_case = MockSQLTestCase('test_explicit_definition')
self.assertEqual(test_case.name, "MockSQLTestCase.test_explicit_definition")
self.assertEqual(test_case.author, 'balasr3')
self.assertEqual(test_case.description, 'test case with metadata')
self.assertEqual(test_case.created_datetime, datetime.strptime('2012-07-05 12:00:00', '%Y-%m-%d %H:%M:%S'))
self.assertEqual(test_case.modified_datetime, datetime.strptime('2012-07-05 12:00:02', '%Y-%m-%d %H:%M:%S'))
self.assertEqual(test_case.tags, set(['orca', 'hashagg']))
def test_explicit_test_fixtures_through_loading(self):
test_loader = TINCTestLoader()
test_suite = test_loader.loadTestsFromTestCase(MockSQLTestCase)
# 4 tests for 3 sqls in the directory and 1 explicit test method
self.assertEqual(test_suite.countTestCases(), 4)
def test_optimizer_mode_both(self):
test_loader = TINCTestLoader()
test_suite = test_loader.loadTestsFromTestCase(MockSQLTestCaseForOptimizerModeBoth)
for test in test_suite._tests:
# Data provider should exists for query01 and query03.
# query02 shouldn't have it, since its optimizer mode is overwritten with value 'off'
if test.name == "MockSQLTestCaseForOptimizerModeBoth.test_query01" or test.name == "MockSQLTestCaseForOptimizerModeBoth.test_query03":
self.assertEqual(test.optimizer_mode, "both")
self.assertEqual(test.data_provider, "optimizer_handling")
else:
self.assertNotEqual(test.optimizer_mode, "both")
self.assertTrue(test.data_provider is None)
def test_optimizer_mode_hawq(self):
"""
Test whether optimizer_mode both is overriden in hawq to None
"""
test_case = MockSQLTestCaseOptimizerModeHAWQ('test_optimizer_mode_both')
self.assertIsNone(test_case.optimizer_mode)
test_case = MockSQLTestCaseOptimizerModeHAWQ('test_optimizer_mode_on')
self.assertEquals(test_case.optimizer_mode, 'on')
test_case = MockSQLTestCaseOptimizerModeHAWQ('test_optimizer_mode_off')
self.assertEquals(test_case.optimizer_mode, 'off')
class MockSQLTestCaseForSkip(SQLTestCase):
"""
@description test case to test skip tag
@created 2012-08-07 12:00:00
@modified 2012-08-07 12:00:02
"""
class SQLTestCaseSkipTests(unittest.TestCase):
def test_skip_tag_in_sql_file(self):
test_case = MockSQLTestCaseForSkip('test_query01')
self.assertEqual(test_case.name, "MockSQLTestCaseForSkip.test_query01")
self.assertEqual(test_case.skip, 'demonstrating skipping')
def test_skip_when_tag_in_sql_file(self):
test_loader = TINCTestLoader()
test_suite = test_loader.loadTestsFromTestCase(MockSQLTestCaseForSkip)
test_case = None
for case in test_suite._tests:
if case.name == "MockSQLTestCaseForSkip.test_query01":
test_case = case
self.assertNotEqual(test_case, None)
self.assertEqual(test_case.name, "MockSQLTestCaseForSkip.test_query01")
with closing(_WritelnDecorator(StringIO())) as buffer:
test_result = TINCTextTestResult(buffer, True, 1)
test_case.run(test_result)
self.assertEqual(test_result.testsRun, 1)
self.assertEqual(len(test_result.failures), 0)
self.assertEqual(len(test_result.skipped), 1)
self.assertEqual(len(test_result.errors), 0)
@unittest.skip('mock')
class MockSQLTestCaseForLoader(SQLTestCase):
@classmethod
def setUpClass(cls):
pass
class SQLTestLoaderTests(unittest.TestCase):
def test_load_implicit_python_from_name(self):
"""Test loadTestsFromName for a dynamically generated sql test method"""
test_loader = TINCTestLoader()
test_suite = test_loader.loadTestsFromName('mpp.models.test.sql_related.test_sql_test_case.MockSQLTestCaseForLoader.test_query01')
test_case = test_suite._tests[0]
self.assertEqual(test_case.name, "MockSQLTestCaseForLoader.test_query01")
self.assertEqual(test_case.author, 'lammin')
self.assertEqual(test_case.description, 'test sql test case')
self.assertEqual(test_case.created_datetime, datetime.strptime('2012-07-20 12:00:00', '%Y-%m-%d %H:%M:%S'))
self.assertEqual(test_case.modified_datetime, datetime.strptime('2012-07-20 12:00:02', '%Y-%m-%d %H:%M:%S'))
self.assertEqual(test_case.tags, set(['orca', 'hashagg', 'executor']))
def test_load_test_from_class_name(self):
"""Test loadTestsFromName for a class name"""
test_loader = TINCTestLoader()
test_suite = test_loader.loadTestsFromName('mpp.models.test.sql_related.test_sql_test_case.MockSQLTestCaseForLoader')
test_case = None
for my_test_case in test_suite._tests:
if my_test_case.name == 'MockSQLTestCaseForLoader.test_query01':
test_case = my_test_case
break
self.assertTrue(test_case is not None)
self.assertEqual(test_case.name, "MockSQLTestCaseForLoader.test_query01")
self.assertEqual(test_case.author, 'lammin')
self.assertEqual(test_case.description, 'test sql test case')
self.assertEqual(test_case.created_datetime, datetime.strptime('2012-07-20 12:00:00', '%Y-%m-%d %H:%M:%S'))
self.assertEqual(test_case.modified_datetime, datetime.strptime('2012-07-20 12:00:02', '%Y-%m-%d %H:%M:%S'))
self.assertEqual(test_case.tags, set(['orca', 'hashagg', 'executor']))
def test_load_test_from_class_name_with_supplementary_sqls(self):
"""Test loadTestsFromName for a class name"""
test_loader = TINCTestLoader()
test_suite = test_loader.loadTestsFromName('mpp.models.test.sql_related.test_sql_test_case.MockSQLTestCaseForLoader')
# 3 tests for 3 sql tests in the current directory.
self.assertEquals(len(test_suite._tests), 3)
for test_case in test_suite._tests:
if test_case.name == 'MockSQLTestCaseForLoader.test_query03':
break
self.assertEqual(test_case.name, "MockSQLTestCaseForLoader.test_query03")
self.assertEqual(test_case.author, 'balasr3')
self.assertEqual(test_case.description, 'test sql test case sql')
self.assertEqual(test_case.created_datetime, datetime.strptime('2012-07-20 12:00:00', '%Y-%m-%d %H:%M:%S'))
self.assertEqual(test_case.modified_datetime, datetime.strptime('2012-07-20 12:00:02', '%Y-%m-%d %H:%M:%S'))
self.assertEqual(test_case.tags, set(['orca', 'hashagg', 'executor']))
class SQLTemplateTests(unittest.TestCase):
def test_templates_regular_sql(self):
"""Test loadTestsFromName for a dynamically generated sql test method."""
test_loader = TINCTestLoader()
test_suite = test_loader.loadTestsFromName('mpp.models.test.sql_related.test_sql_test_case.MockSQLTemplateTestCaseRegular.test_query01')
test_case = test_suite._tests[0]
# Non-template test case should work as is...
self.assertEqual(test_case.name, "MockSQLTemplateTestCaseRegular.test_query01")
self.assertEqual(test_case.author, 'lammin')
self.assertEqual(test_case.description, 'test sql test case')
self.assertEqual(test_case.created_datetime, datetime.strptime('2012-07-20 12:00:00', '%Y-%m-%d %H:%M:%S'))
self.assertEqual(test_case.modified_datetime, datetime.strptime('2012-07-20 12:00:02', '%Y-%m-%d %H:%M:%S'))
self.assertEqual(test_case.tags, set(['orca', 'hashagg', 'executor']))
def test_templates_template_sql_file(self):
"""Test loadTestsFromName for a dynamically generated sql template test method."""
test_loader = TINCTestLoader()
test_suite = test_loader.loadTestsFromName('mpp.models.test.sql_related.test_sql_test_case.MockSQLTemplateTestCaseExplicit.test_template_query04')
test_case = test_suite._tests[0]
# Template test case should work as if it is non-template test case...
self.assertEqual(test_case.name, "MockSQLTemplateTestCaseExplicit.test_template_query04")
self.assertEqual(test_case.author, 'shahn17')
self.assertEqual(test_case.description, 'template test case')
sql_file_path = os.path.join(test_case.get_out_dir(), "MockSQLTemplateTestCaseExplicit", "template_query04.sql")
ans_file_path = os.path.join(test_case.get_out_dir(), "MockSQLTemplateTestCaseExplicit", "template_query04.ans")
original_sql_file_path = os.path.join(os.path.dirname(sys.modules[test_case.__class__.__module__].__file__), test_case.__class__.sql_dir, test_case.__class__.template_dir, "query04.sql")
original_ans_file_path = os.path.join(os.path.dirname(sys.modules[test_case.__class__.__module__].__file__), test_case.__class__.ans_dir, test_case.__class__.template_dir, "query04.ans")
self.assertEqual(test_case.sql_file, sql_file_path)
self.assertEqual(test_case.ans_file, ans_file_path)
self.assertEqual(test_case._original_sql_file, original_sql_file_path)
self.assertEqual(test_case._original_ans_file, original_ans_file_path)
self.assertTrue(os.path.exists(test_case.sql_file))
self.assertTrue(os.path.exists(test_case.ans_file))
self.assertTrue(os.path.exists(test_case._original_sql_file))
self.assertTrue(os.path.exists(test_case._original_ans_file))
# Cleanup
dir_path = os.path.join(test_case.get_out_dir(), "MockSQLTemplateTestCaseExplicit")
self.assertTrue(os.path.exists(dir_path))
shutil.rmtree(dir_path)
def test_templates_all_files(self):
"""Test loadTestsFromName for a class name"""
test_loader = TINCTestLoader()
test_suite = test_loader.loadTestsFromName('mpp.models.test.sql_related.test_sql_test_case.MockSQLTemplateTestCase')
# 5 tests for 3 sql files in the current directory, and 2 sql files in the template directory
self.assertEquals(len(test_suite._tests), 5)
for test_case in test_suite._tests:
if test_case.name == 'MockSQLTemplateTestCase.test_template_query04':
break
self.assertEqual(test_case.name, "MockSQLTemplateTestCase.test_template_query04")
self.assertEqual(test_case.author, 'shahn17')
self.assertEqual(test_case.description, 'template test case')
sql_file_path = os.path.join(test_case.get_out_dir(), "MockSQLTemplateTestCase", "template_query04.sql")
ans_file_path = os.path.join(test_case.get_out_dir(), "MockSQLTemplateTestCase", "template_query04.ans")
original_sql_file_path = os.path.join(os.path.dirname(sys.modules[test_case.__class__.__module__].__file__), test_case.__class__.sql_dir, test_case.__class__.template_dir, "query04.sql")
original_ans_file_path = os.path.join(os.path.dirname(sys.modules[test_case.__class__.__module__].__file__), test_case.__class__.ans_dir, test_case.__class__.template_dir, "query04.ans")
self.assertEqual(test_case.sql_file, sql_file_path)
self.assertEqual(test_case.ans_file, ans_file_path)
self.assertEqual(test_case._original_sql_file, original_sql_file_path)
self.assertEqual(test_case._original_ans_file, original_ans_file_path)
self.assertTrue(os.path.exists(test_case.sql_file))
self.assertTrue(os.path.exists(test_case.ans_file))
self.assertTrue(os.path.exists(test_case._original_sql_file))
self.assertTrue(os.path.exists(test_case._original_ans_file))
# Template test case sql file should exists
sql_file_path = os.path.join(test_case.get_out_dir(), "MockSQLTemplateTestCase", "template_query04.sql")
self.assertTrue(os.path.exists(sql_file_path))
sql_file_data = None
with open(sql_file_path, 'r') as sql_file_object:
sql_file_data = sql_file_object.read()
self.assertTrue(sql_file_data is not None)
# Correct substitution
self.assertTrue('my_percent' in sql_file_data)
# Error in python code
self.assertTrue('my_at@' in sql_file_data)
# Error in sql template
self.assertTrue('&' in sql_file_data)
# Template test case ans file should exists
ans_file_path = os.path.join(test_case.get_out_dir(), "MockSQLTemplateTestCase", "template_query05.ans")
self.assertTrue(os.path.exists(ans_file_path))
ans_file_data = None
with open(ans_file_path, 'r') as sql_file_object:
ans_file_data = sql_file_object.read()
self.assertTrue(ans_file_data is not None)
# Correct substitution
self.assertTrue('my_percent' in ans_file_data)
# Error in python code
self.assertTrue('my_at@' in ans_file_data)
# Error in ans template
self.assertTrue('&' in ans_file_data)
# Cleanup
dir_path = os.path.join(test_case.get_out_dir(), "MockSQLTemplateTestCase")
self.assertTrue(os.path.exists(dir_path))
shutil.rmtree(dir_path)
@unittest.skip('mock')
class MockTINCTestCaseForLoaderDiscovery(SQLTestCase):
def test_lacking_product_version(self):
"""
@maintainer balasr3
@description test stuff
@created 2012-07-05 12:00:00
@modified 2012-07-05 12:00:02
@tags storage
"""
pass
def test_containing_product_version(self):
"""
@maintainer balasr3
@description test stuff
@created 2012-07-05 12:00:00
@modified 2012-07-05 12:00:02
@tags storage
@product_version gpdb: 4.2
"""
pass
def test_main_product_version(self):
"""
@maintainer balasr3
@description test stuff
@created 2012-07-05 12:00:00
@modified 2012-07-05 12:00:02
@tags storage
@product_version gpdb: main
"""
pass
def test_containing_product_version_exclusive_range(self):
"""
@maintainer balasr3
@description test stuff
@created 2012-07-05 12:00:00
@modified 2012-07-05 12:00:02
@tags storage
@product_version gpdb: (4.1.0.0-main)
"""
pass
def test_containing_product_version_inclusive_range(self):
"""
@maintainer balasr3
@description test stuff
@created 2012-07-05 12:00:00
@modified 2012-07-05 12:00:02
@tags storage
@product_version gpdb: [4.2.0.0-main]
"""
pass
class TINCTestLoaderDiscoveryTests(unittest.TestCase):
def test_matching_author(self):
test_case = MockTINCTestCaseForLoaderDiscovery('test_lacking_product_version')
self.assertTrue(test_case.match_metadata("author", "pedroc"))
self.assertFalse(test_case.match_metadata("author", "kumara64"))
def test_matching_maintainer(self):
test_case = MockTINCTestCaseForLoaderDiscovery('test_lacking_product_version')
self.assertTrue(test_case.match_metadata("maintainer", "balasr3"))
self.assertFalse(test_case.match_metadata("maintainer", "kumara64"))
def test_matching_tags(self):
test_case = MockTINCTestCaseForLoaderDiscovery('test_lacking_product_version')
self.assertTrue(test_case.match_metadata("tags", "storage"))
self.assertFalse(test_case.match_metadata("tags", "text_analytics"))
|
rvs/gpdb
|
src/test/tinc/tincrepo/mpp/models/test/sql_related/test_sql_test_case.py
|
Python
|
apache-2.0
| 21,626
|
[
"ORCA"
] |
283a2dff17fd042cff76c996e7d7bab58761e3113ae494e3a792360c1057ce37
|
import os
import pip
import tempfile
import subprocess
import mdtraj.version
BUCKET_NAME = 'assaytools'
if not mdtraj.version.release:
PREFIX = 'latest'
else:
PREFIX = mdtraj.version.short_version
if not any(d.project_name == 's3cmd' for d in pip.get_installed_distributions()):
raise ImportError('The s3cmd pacakge is required. try $ pip install s3cmd')
# The secret key is available as a secure environment variable
# on travis-ci to push the build documentation to Amazon S3.
with tempfile.NamedTemporaryFile('w') as f:
f.write('''[default]
access_key = {AWS_ACCESS_KEY_ID}
secret_key = {AWS_SECRET_ACCESS_KEY}
'''.format(**os.environ))
f.flush()
template = ('s3cmd --config {config} '
'sync docs/_build/ s3://{bucket}/{prefix}/')
cmd = template.format(
config=f.name,
bucket=BUCKET_NAME,
prefix=PREFIX)
subprocess.call(cmd.split())
|
MehtapIsik/assaytools
|
devtools/travis-ci/push-docs-to-s3.py
|
Python
|
lgpl-2.1
| 925
|
[
"MDTraj"
] |
e0d40d33dceee4943e6bb8a436805727dbd67a0e99c4158aa4478e5ed6d35182
|
#!/usr/bin/env python
# -*- coding: utf8 -*-
# *****************************************************************
# ** PTS -- Python Toolkit for working with SKIRT **
# ** © Astronomical Observatory, Ghent University **
# *****************************************************************
## \package pts.modeling.reporting.component Contains the ReportingComponent class
# -----------------------------------------------------------------
# Ensure Python 3 compatibility
from __future__ import absolute_import, division, print_function
# Import the relevant PTS classes and modules
from ..component.galaxy import GalaxyModelingComponent
from ...core.tools import filesystem as fs
# -----------------------------------------------------------------
class ReportingComponent(GalaxyModelingComponent):
"""
This class...
"""
def __init__(self, *args, **kwargs):
"""
The constructor ...
:param kwargs:
:return:
"""
# Call the constructor of the base class
super(ReportingComponent, self).__init__(*args, **kwargs)
# -- Attributes --
# The path to the data report
self.data_report_path = None
# The path to the preparation initialization report
self.preparation_initialization_report_path = None
# The path to the preparation report
self.preparation_report_path = None
# The path to the decomposition report
self.decomposition_report_path = None
# The path to the photometry report
self.photometry_report_path = None
# The path to the map making report
self.map_making_report_path = None
# The path to the input initialization report
self.input_initialization_report_path = None
# The path to the exploration report
self.exploration_report_path = None
# The path to the fitting report
self.fitting_report_path = None
# The path to the analysis report
self.analysis_report_path = None
# -----------------------------------------------------------------
def setup(self, **kwargs):
"""
This function ...
:param kwargs:
:return:
"""
# Call the setup function of the base class
super(ReportingComponent, self).setup(**kwargs)
# Set the report paths
self.data_report_path = fs.join(self.reports_path, "data.txt")
self.preparation_initialization_report_path = fs.join(self.reports_path, "preparation_initialization.txt")
self.preparation_report_path = fs.join(self.reports_path, "preparation.txt")
self.decomposition_report_path = fs.join(self.reports_path, "decomposition.txt")
self.photometry_report_path = fs.join(self.reports_path, "photometry.txt")
self.map_making_report_path = fs.join(self.reports_path, "map_making.txt")
self.input_initialization_report_path = fs.join(self.reports_path, "input_initialization.txt")
self.exploration_report_path = fs.join(self.reports_path, "exploration.txt")
self.fitting_report_path = fs.join(self.reports_path, "fitting.txt")
self.analysis_report_path = fs.join(self.reports_path, "analysis.txt")
# -----------------------------------------------------------------
|
SKIRT/PTS
|
modeling/reporting/component.py
|
Python
|
agpl-3.0
| 3,349
|
[
"Galaxy"
] |
fe356a3d4524d4342db593a39ab1362be7c197fc889cbb012d9af0e503dcdf8e
|
from __future__ import division
from scipy.constants import *
import ase.units
mole = N_A
def convert(value, quantity, fromUnits, toUnits):
return unitSets[fromUnits][quantity]/unitSets[toUnits][quantity] * value
unitSets = {}
unitSets['ASE'] = dict(
mass = gram/mole,
distance = angstrom,
time = 1/ase.units.second,
energy = eV,
velocity = angstrom/(1/ase.units.second),
force = eV/angstrom,
pressure = 1/ase.units.Pascal,
stress = 1/ase.units.Pascal,
charge = elementary_charge
)
unitSets['metal'] = dict(
mass = gram/mole,
distance = angstrom,
time = pico,
energy = eV,
velocity = angstrom/pico,
force = eV/angstrom,
torque = eV,
temperature = 1,
pressure = bar,
stress = bar,
charge = elementary_charge,
dipole = elementary_charge*angstrom,
electricField = 1/angstrom,
density = gram/centi**3
)
unitSets['real'] = dict(
mass = gram/mole,
distance = angstrom,
time = femto, # femtoseconds
energy = kilo*calorie/mole, # kcal/mole
velocity = angstrom/femto, # Angstroms/femtosecond
force = kilo*calorie/(mole*angstrom),
torque = kilo*calorie/mole,
temperature = 1,
pressure = atmosphere,
stress = atmosphere,
charge = elementary_charge,
electricField = 1/angstrom,
density = gram/centi**3
)
if __name__ == '__main__':
print convert(ase.units.fs, 'time', 'ASE', 'real')
|
csmm/multiase
|
multiasecalc/lammps/unitconversion.py
|
Python
|
gpl-2.0
| 1,495
|
[
"ASE"
] |
03a753edecc4092b47ed9203bcbcfe73d31b87b66accaa99c57a559c7b9e3253
|
# -*- coding: utf-8 -*-
"""
Biological Boolean Networks
=================================
A series of biological Boolean networks that can be directly loaded for experimentation.
"""
# Copyright (C) 2021 by
# Alex Gates <ajgates42@gmail.com>
# Rion Brattig Correia <rionbr@gmail.com>
# Xuan Wang <xw47@indiana.edu>
# Thomas Parmer <tjparmer@indiana.edu>
# All rights reserved.
# MIT license.
import os
from .. boolean_network import BooleanNetwork
_path = os.path.dirname(os.path.realpath(__file__))
""" Make sure we know what the current directory is """
def THALIANA():
"""Boolean network model of the control of flower morphogenesis in Arabidopsis thaliana
The network is defined in :cite:`Chaos:2006`.
Returns:
(BooleanNetwork)
"""
return BooleanNetwork.from_file(_path + '/thaliana.txt', name="Arabidopsis thaliana", keep_constants=True)
def DROSOPHILA(cells=1):
"""Drosophila melanogaster boolean model.
This was firt defined in :cite:`Albert:2008`.
Two models are available in CANA, the original parasegment (4 cells) and a single cell simplification of the model.
In the original parasegment model, some nodes receive inputs from neighboring cells.
In the single cell model, they are condensed (nhhnHH) and treated as constants.
Args:
cells (int) : Which model to return. Accepts either 1 or 4. Default is 1.
Returns:
(BooleanNetwork)
"""
if cells == 1:
return BooleanNetwork.from_file(_path + '/drosophila_single_cell.txt', name="Drosophila melanogaster (single cell)", keep_constants=True)
elif cells == 4:
return BooleanNetwork.from_file(_path + '/drosophila_parasegment.txt', name='Drosophila melanogaster (parasegment)', keep_constants=True)
else:
raise AttributeError('Only drosophila single cell (cells=1) or parasegment (cells=4) models available.')
def BUDDING_YEAST():
"""
The network is defined in :cite:`Fangting:2004`.
Returns:
(BooleanNetwork)
"""
return BooleanNetwork.from_file(_path + '/yeast_cell_cycle.txt', name="Budding Yeast Cell Cycle", keep_constants=True)
def MARQUESPITA():
"""Boolean network used for the Two-Symbol schemata example.
The network is defined in :cite:`Marques-Pita:2013`.
Returns:
(BooleanNetwork)
"""
return BooleanNetwork.from_file(_path + '/marques-pita_rocha.txt', name="Marques-Pita & Rocha", keep_constants=True)
def LEUKEMIA():
"""Boolean network model of survival signaling in T-LGL leukemia
The network is defined in :cite:`Zhang:2008`.
Returns:
(BooleanNetwork)
"""
return BooleanNetwork.from_file(_path + '/leukemia.txt', type='logical', name="T-LGL Leukemia", keep_constants=True)
def BREAST_CANCER():
"""Boolean network model of signal transduction in ER+ breast cancer
The network is defined in :cite:`Zanudo:2017`.
Returns:
(BooleanNetwork)
"""
return BooleanNetwork.from_file(_path + '/breast_cancer.txt', type='logical', name="ER+ Breast Cancer", keep_constants=True)
_cell_collective_models = [
'Apoptosis Network',
'Arabidopsis thaliana Cell Cycle',
'Aurora Kinase A in Neuroblastoma',
'B bronchiseptica and T retortaeformis coinfection',
'B cell differentiation',
'Bordetella bronchiseptica',
'Bortezomib Responses in U266 Human Myeloma Cells',
'BT474 Breast Cell Line Long-term ErbB Network',
'BT474 Breast Cell Line Short-term ErbB Network',
'Budding Yeast Cell Cycle 2009',
'Budding Yeast Cell Cycle',
'Cardiac development',
'CD4 T cell signaling',
'CD4+ T Cell Differentiation and Plasticity',
'CD4+ T cell Differentiation',
'Cell Cycle Transcription by Coupled CDK and Network Oscillators',
'Cholesterol Regulatory Pathway',
'Colitis-associated colon cancer',
'Cortical Area Development',
'Death Receptor Signaling',
'Differentiation of T lymphocytes',
'EGFR & ErbB Signaling',
'FA BRCA pathway',
'Fanconi anemia and checkpoint recovery',
'FGF pathway of Drosophila Signalling Pathways',
'Glucose Repression Signaling 2009',
'Guard Cell Abscisic Acid Signaling',
'HCC1954 Breast Cell Line Long-term ErbB Network',
'HCC1954 Breast Cell Line Short-term ErbB Network',
'HGF Signaling in Keratinocytes',
'HH Pathway of Drosophila Signaling Pathways',
'HIV-1 interactions with T Cell Signalling Pathway',
'Human Gonadal Sex Determination',
'IGVH mutations in chronic lymphocytic leukemia',
'IL-1 Signaling',
'IL-6 Signalling',
'Influenza A Virus Replication Cycle',
'Iron acquisition and oxidative stress response in aspergillus fumigatus',
'Lac Operon',
'Lymphoid and myeloid cell specification and transdifferentiation',
'Lymphopoiesis Regulatory Network',
'Mammalian Cell Cycle 2006',
'Mammalian Cell Cycle',
'MAPK Cancer Cell Fate Network',
'Metabolic Interactions in the Gut Microbiome',
'Neurotransmitter Signaling Pathway',
'Oxidative Stress Pathway',
'PC12 Cell Differentiation',
'Predicting Variabilities in Cardiac Gene',
'Pro-inflammatory Tumor Microenvironment in Acute Lymphoblastic Leukemia',
'Processing of Spz Network from the Drosophila Signaling Pathway',
'Regulation of the L-arabinose operon of Escherichia coli',
'Senescence Associated Secretory Phenotype',
'Septation Initiation Network',
'Signal Transduction in Fibroblasts',
'Signaling in Macrophage Activation',
'Signaling Pathway for Butanol Production in Clostridium beijerinckii NRRL B-598',
'SKBR3 Breast Cell Line Long-term ErbB Network',
'SKBR3 Breast Cell Line Short-term ErbB Network',
'Stomatal Opening Model',
'T cell differentiation',
'T Cell Receptor Signaling',
'T-Cell Signaling 2006',
'T-LGL Survival Network 2008',
'T-LGL Survival Network 2011 Reduced Network',
'T-LGL Survival Network 2011',
'TOL Regulatory Network',
'Toll Pathway of Drosophila Signaling Pathway',
'Treatment of Castration-Resistant Prostate Cancer',
'Trichostrongylus retortaeformis',
'Tumour Cell Invasion and Migration',
'VEGF Pathway of Drosophila Signaling Pathway',
'Wg Pathway of Drosophila Signalling Pathways',
'Yeast Apoptosis']
def load_cell_collective_model(name=None):
"""Loads one of the Cell Collective :cite:`Helikar:2012` models.
Models collected on Aug 2020.
Args:
name (str): the name of the model to be loaded.
Accepts: ["Apoptosis Network", "Arabidopsis thaliana Cell Cycle", "Aurora Kinase A in Neuroblastoma", ...,
"Wg Pathway of Drosophila Signalling Pathways", "Yeast Apoptosis"]
Returns:
(BooleanNetwork)
Note:
See source code for full list of models. Credits to Xuan Wang for compiling these models.
We are working on making a Cell Collective direct loader.
"""
#
if name not in _cell_collective_models:
models_str = "'" + "','".join(_cell_collective_models) + "'"
raise TypeError('Model name could not be found. Please specify one of the following models: {models:s}.'.format(models=models_str))
else:
return BooleanNetwork.from_file(_path + '/cell_collective/' + name + '.txt', name=name, keep_constants=True)
def load_all_cell_collective_models():
"""Load all the Cell Collective models, instanciating +70 models.
Returns:
(list)
Note:
See source code for full list of models.
"""
return [load_cell_collective_model(name=name) for name in _cell_collective_models]
|
rionbr/CANA
|
cana/datasets/bio.py
|
Python
|
mit
| 7,652
|
[
"CDK"
] |
61ee43fbdfa5b0ca1fe327aa1f9a20e8edf423e27a26934a9bd5cd38812d88d8
|
import numpy as np
from geometry.point import Point
class DataGenerator(object):
@staticmethod
def generate_random_set(n=10, d=2, seed_value=431):
np.random.seed(seed_value)
points = np.random.rand(n, d)
return np.array([Point(i[0], i[1]) for i in points])
@staticmethod
def generate_normal_set(n=10, d=2, seed_value=431):
""" Generate random test data with Gaussian distribution."""
np.random.seed(seed_value)
mean = [0,0]
cov = [[1,0],[0,1]]
points = np.random.multivariate_normal(mean, cov, n)
return np.array([Point(i[0], i[1]) for i in points])
|
nhonaitran/aries
|
utils/datagenerator.py
|
Python
|
gpl-2.0
| 596
|
[
"Gaussian"
] |
f67ed4e9eebe2b5b7ef6012a1ce527db420f13032a2a2118d12758a4f68f4bc1
|
"""
Support for the Amazon Polly text to speech service.
For more details about this component, please refer to the documentation at
https://home-assistant.io/components/tts.amazon_polly/
"""
import logging
import voluptuous as vol
from homeassistant.components.tts import Provider, PLATFORM_SCHEMA
import homeassistant.helpers.config_validation as cv
_LOGGER = logging.getLogger(__name__)
REQUIREMENTS = ["boto3==1.4.3"]
CONF_REGION = "region_name"
CONF_ACCESS_KEY_ID = "aws_access_key_id"
CONF_SECRET_ACCESS_KEY = "aws_secret_access_key"
CONF_PROFILE_NAME = "profile_name"
ATTR_CREDENTIALS = "credentials"
DEFAULT_REGION = "us-east-1"
SUPPORTED_REGIONS = ["us-east-1", "us-east-2", "us-west-2", "eu-west-1"]
CONF_VOICE = "voice"
CONF_OUTPUT_FORMAT = "output_format"
CONF_SAMPLE_RATE = "sample_rate"
CONF_TEXT_TYPE = "text_type"
SUPPORTED_VOICES = ["Geraint", "Gwyneth", "Mads", "Naja", "Hans", "Marlene",
"Nicole", "Russell", "Amy", "Brian", "Emma", "Raveena",
"Ivy", "Joanna", "Joey", "Justin", "Kendra", "Kimberly",
"Salli", "Conchita", "Enrique", "Miguel", "Penelope",
"Chantal", "Celine", "Mathieu", "Dora", "Karl", "Carla",
"Giorgio", "Mizuki", "Liv", "Lotte", "Ruben", "Ewa",
"Jacek", "Jan", "Maja", "Ricardo", "Vitoria", "Cristiano",
"Ines", "Carmen", "Maxim", "Tatyana", "Astrid", "Filiz"]
SUPPORTED_OUTPUT_FORMATS = ["mp3", "ogg_vorbis", "pcm"]
SUPPORTED_SAMPLE_RATES = ["8000", "16000", "22050"]
SUPPORTED_SAMPLE_RATES_MAP = {
"mp3": ["8000", "16000", "22050"],
"ogg_vorbis": ["8000", "16000", "22050"],
"pcm": ["8000", "16000"]
}
SUPPORTED_TEXT_TYPES = ["text", "ssml"]
CONTENT_TYPE_EXTENSIONS = {
"audio/mpeg": "mp3",
"audio/ogg": "ogg",
"audio/pcm": "pcm"
}
DEFAULT_VOICE = "Joanna"
DEFAULT_OUTPUT_FORMAT = "mp3"
DEFAULT_TEXT_TYPE = "text"
DEFAULT_SAMPLE_RATES = {
"mp3": "22050",
"ogg_vorbis": "22050",
"pcm": "16000"
}
PLATFORM_SCHEMA = PLATFORM_SCHEMA.extend({
vol.Optional(CONF_REGION, default=DEFAULT_REGION):
vol.In(SUPPORTED_REGIONS),
vol.Inclusive(CONF_ACCESS_KEY_ID, ATTR_CREDENTIALS): cv.string,
vol.Inclusive(CONF_SECRET_ACCESS_KEY, ATTR_CREDENTIALS): cv.string,
vol.Exclusive(CONF_PROFILE_NAME, ATTR_CREDENTIALS): cv.string,
vol.Optional(CONF_VOICE, default=DEFAULT_VOICE): vol.In(SUPPORTED_VOICES),
vol.Optional(CONF_OUTPUT_FORMAT, default=DEFAULT_OUTPUT_FORMAT):
vol.In(SUPPORTED_OUTPUT_FORMATS),
vol.Optional(CONF_SAMPLE_RATE): vol.All(cv.string,
vol.In(SUPPORTED_SAMPLE_RATES)),
vol.Optional(CONF_TEXT_TYPE, default=DEFAULT_TEXT_TYPE):
vol.In(SUPPORTED_TEXT_TYPES),
})
def get_engine(hass, config):
"""Setup Amazon Polly speech component."""
# pylint: disable=import-error
output_format = config.get(CONF_OUTPUT_FORMAT)
sample_rate = config.get(CONF_SAMPLE_RATE,
DEFAULT_SAMPLE_RATES[output_format])
if sample_rate not in SUPPORTED_SAMPLE_RATES_MAP.get(output_format):
_LOGGER.error("%s is not a valid sample rate for %s",
sample_rate, output_format)
return None
config[CONF_SAMPLE_RATE] = sample_rate
import boto3
profile = config.get(CONF_PROFILE_NAME)
if profile is not None:
boto3.setup_default_session(profile_name=profile)
aws_config = {
CONF_REGION: config.get(CONF_REGION),
CONF_ACCESS_KEY_ID: config.get(CONF_ACCESS_KEY_ID),
CONF_SECRET_ACCESS_KEY: config.get(CONF_SECRET_ACCESS_KEY),
}
del config[CONF_REGION]
del config[CONF_ACCESS_KEY_ID]
del config[CONF_SECRET_ACCESS_KEY]
polly_client = boto3.client("polly", **aws_config)
supported_languages = []
all_voices = {}
all_voices_req = polly_client.describe_voices()
for voice in all_voices_req.get("Voices"):
all_voices[voice.get("Id")] = voice
if voice.get("LanguageCode") not in supported_languages:
supported_languages.append(voice.get("LanguageCode"))
return AmazonPollyProvider(polly_client, config, supported_languages,
all_voices)
class AmazonPollyProvider(Provider):
"""Amazon Polly speech api provider."""
def __init__(self, polly_client, config, supported_languages,
all_voices):
"""Initialize Amazon Polly provider for TTS."""
self.client = polly_client
self.config = config
self.supported_langs = supported_languages
self.all_voices = all_voices
self.default_voice = self.config.get(CONF_VOICE)
@property
def supported_languages(self):
"""List of supported languages."""
return self.supported_langs
@property
def default_language(self):
"""Default language."""
return self.all_voices.get(self.default_voice).get("LanguageCode")
@property
def default_options(self):
"""Dict include default options."""
return {CONF_VOICE: self.default_voice}
@property
def supported_options(self):
"""List of supported options."""
return [CONF_VOICE]
def get_tts_audio(self, message, language=None, options=None):
"""Request TTS file from Polly."""
voice_id = options.get(CONF_VOICE, self.default_voice)
voice_in_dict = self.all_voices.get(voice_id)
if language is not voice_in_dict.get("LanguageCode"):
_LOGGER.error("%s does not support the %s language",
voice_id, language)
return (None, None)
resp = self.client.synthesize_speech(
OutputFormat=self.config[CONF_OUTPUT_FORMAT],
SampleRate=self.config[CONF_SAMPLE_RATE],
Text=message,
TextType=self.config[CONF_TEXT_TYPE],
VoiceId=voice_id
)
return (CONTENT_TYPE_EXTENSIONS[resp.get("ContentType")],
resp.get("AudioStream").read())
|
eagleamon/home-assistant
|
homeassistant/components/tts/amazon_polly.py
|
Python
|
apache-2.0
| 6,077
|
[
"Brian"
] |
0d4508dfbc8f5ca64617c6c0ad221d7cacc7cbfc93ae96a6d8d87ac983cb899e
|
"""
Do the initial configuration of a DIRAC component
"""
#
from DIRAC.ConfigurationSystem.Client.Helpers import getCSExtensions
from DIRAC.FrameworkSystem.Client.ComponentInstaller import gComponentInstaller
#
from DIRAC import gConfig
from DIRAC import exit as DIRACexit
__RCSID__ = "$Id$"
gComponentInstaller.exitOnError = True
#
from DIRAC.Core.Base import Script
Script.setUsageMessage( '\n'.join( [ __doc__.split( '\n' )[1],
'Usage:',
' %s [option|cfgfile] ... ComponentType System Component|System/Component' % Script.scriptName,
'Arguments:',
' ComponentType: Name of the ComponentType (ie: agent)',
' System: Name of the DIRAC system (ie: WorkloadManagement)',
' component: Name of the DIRAC component (ie: JobCleaningAgent)'] ) )
Script.parseCommandLine()
args = Script.getPositionalArgs()
componentType = args[0]
if len( args ) == 2:
system, component = args[1].split( '/' )
else:
system = args[1]
component = args[2]
result = gComponentInstaller.addDefaultOptionsToCS( gConfig, componentType, system, component,
getCSExtensions(),
specialOptions = {},
overwrite = False )
if not result['OK']:
print "ERROR:", result['Message']
else:
DIRACexit()
|
Andrew-McNab-UK/DIRAC
|
tests/Jenkins/dirac-cfg-add-option.py
|
Python
|
gpl-3.0
| 1,559
|
[
"DIRAC"
] |
98f959c337f5895feedae1e84a083bd156976b3e69a3461b9e2786641c52ea46
|
from instagram.client import InstagramAPI
import sys
if len(sys.argv) > 1 and sys.argv[1] == 'local':
try:
from test_settings import *
InstagramAPI.host = test_host
InstagramAPI.base_path = test_base_path
InstagramAPI.access_token_field = "access_token"
InstagramAPI.authorize_url = test_authorize_url
InstagramAPI.access_token_url = test_access_token_url
InstagramAPI.protocol = test_protocol
except Exception:
pass
client_id = raw_input("Client ID: ").strip()
client_secret = raw_input("Client Secret: ").strip()
redirect_uri = raw_input("Redirect URI: ").strip()
raw_scope = raw_input("Requested scope (separated by spaces, blank for just basic read): ").strip()
scope = raw_scope.split(' ')
# For basic, API seems to need to be set explicitly
if not scope or scope == [""]:
scope = ["basic"]
api = InstagramAPI(client_id=client_id, client_secret=client_secret, redirect_uri=redirect_uri)
redirect_uri = api.get_authorize_login_url(scope = scope)
print "Visit this page and authorize access in your browser:\n", redirect_uri
code = raw_input("Paste in code in query string after redirect: ").strip()
access_token = api.exchange_code_for_access_token(code)
print "access token:\n", access_token
|
wcyz666/python-instagram
|
get_access_token.py
|
Python
|
bsd-3-clause
| 1,281
|
[
"VisIt"
] |
8a3e02e77c4781fc2382f2b0d97625088fec78ca18a90a564ef0d3def4ba24eb
|
# BDB: A databank of PDB entries with full isotropic B-factors.
# Copyright (C) 2014 Wouter G. Touw (<wouter.touw@radboudumc.nl>)
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License in the
# LICENSE file that should have been included as part of this package.
# If not, see <http://www.gnu.org/licenses/>.
from __future__ import division
import logging
_log = logging.getLogger(__name__)
import itertools
import re
import shutil
import Bio.PDB
import numpy as np
from collections import Counter
from pdbb.pdb.parser import get_pdb_header_and_trailer
def check_beq(structure):
"""Determine if Beq values are the same as the reported B-factors.
The margin is 0.015 Angstrom**2
Return a dictionary with values that are None if ANISOU records are absent.
beq_identical: float that indicates the percentage of B-factors in the
ATOM records that could be reproduced within the margin by
calculating the Beq values from the ANISOU records.
correct_uij : False if a non-standard combination of the Uij values in the
ANISOU records was necessary to reproduce the B-factors.
Raise a ValueError if structure is None.
"""
if not structure:
msg = "Could not check Beq values in ANISOU records. No structure."
_log.error(msg)
raise TypeError(msg)
_log.info("Checking Beq values in ANISOU records...")
margin = 0.015
has_anisou = False
eq = 0
ne = 0
reproduced = 0.0
correct_uij = True
for atom in structure.get_atoms():
anisou = atom.get_anisou()
if anisou is not None:
has_anisou = True
# Beq = 8*pi**2*Ueq
# Ueq = 1/3<u.u> == 1/3<|u|**2> = 1/3(U11+U22+U33)
beq = 8*np.pi**2 * sum(anisou[0:3]) / 3
b = atom.get_bfactor()
if np.isclose(b, beq, atol=margin):
eq = eq + 1
elif check_combinations(anisou, b, margin):
""" e.g. 2a83, 2p6e, 2qik, 3bik, 3d95, 3d96, 3g5t
"""
eq = eq + 1
correct_uij = False
_log.debug("B-factor reproduced by non-standard "
"combination of Uij values in the ANISOU "
"record of ATOM: {}".format(
atom.get_full_id()))
else:
""" e.g 1g8t, 1kr7, 1llr, 1mgr, 1o9g, 1pm1, 1q7l, 1qjp,
1s2p, 1si6, 1sxu, 1sxy, 1sy0, 1sy2, 1ug6, 1x9q, 2a83, 2acp,
2at5, 2bwi, 2ceu, 2fri, 2frj, 2hmn, 2htx, 2j73, 2p6e, 2p6f,
2p6g, 2qfn, 2qik, 2v0a, 2xgb, 2xl6, 2xle, 2xlw, 3bwo, 3dqy,
3fde, 3g5t, 3jql, 3nju, 3nna, 3oxp
"""
ne = ne + 1
_log.debug("Beq not identical to B-factor in ATOM record: {} {} {}".format(atom.get_full_id(), b, beq))
reproduced = eq / (eq + ne) if has_anisou else None
correct_uij = correct_uij if has_anisou else None
return {"beq_identical": reproduced, "correct_uij": correct_uij}
def check_combinations(anisou, b, margin, check_first=False):
"""Check if the B-factor can be reproduced by non-standard U combinations.
Standard: U11, U22, and U33 are the first three values in the ANISOU record
"""
assert(len(anisou) == 6)
reproduced = False
for c in itertools.combinations(list(xrange(0, 6)), 3):
if c == (0, 1, 2) and not check_first: # the standard combination
pass
beq = 8*np.pi**2 * (anisou[c[0]] + anisou[c[1]] + anisou[c[2]])/3
if np.isclose(b, beq, atol=margin):
reproduced = True
_log.debug("B-factor could only be reproduced by combining non-standard Uij values {} {} {}.".format(c[0], c[1], c[2]))
break
return reproduced
def check_tls_range(structure, tls_selections):
"""Check that the residues included in TLS groups are in the structure.
This function currently only checks whether the first and last residues are
in the structure.
Return False if the range is invalid. Return True if the range is valid.
"""
if not structure:
msg = "Could not check TLS group residues. No structure."
_log.error(msg)
raise TypeError(msg)
_log.info("Checking TLS group residues...")
for group in tls_selections:
c1 = group["chain_1"]
c2 = group["chain_2"]
n1 = group["num_1"]
n2 = group["num_2"]
i1 = ' ' if group["ic_1"] is None else group["ic_1"]
i2 = ' ' if group["ic_2"] is None else group["ic_2"]
try:
structure[0][c1][(' ', n1, i1)]
structure[0][c2][(' ', n2, i2)]
except KeyError:
_log.error("TLS group not (entirely) in structure:" +
"{} {}{} --- {} {}{}".format(c1, n1, i1,
c2, n2, i2))
return False
return True
def determine_b_group(structure):
"""Determine the most likely B-factor parameterization.
Return a dictionary with separated output for protein and nucleic acid and
a Boolean that indicates if the structure is a calpha trace.
output can be one of the strings
overall e.g. 1etu
residue_1ADP e.g. the protein in 1hlz
residue_2ADP e.g. the DNA in 1hlz
individual most PDB files
no_b-factors e.g. 1mcb, 3zxa, 2yhx
or None if protein or nucleic acid are not present.
(margin 0.01 Angstrom**2)
Warning: currently only the first protein and/or nucleid acid chains
encountered are taken into account. The same parameterization is assumed
for other chains (if they exist).
"""
group = {
"protein_b": None,
"nucleic_b": None,
"calpha_only": False,
"phos_only": False,
}
_log.info("Determining most likely B-factor group type")
if structure is not None:
chains = structure.get_chains()
for c in chains:
if is_protein_chain(c):
if group["protein_b"] is None:
group["protein_b"] = determine_b_group_chain(c)
elif is_nucleic_chain(c):
if group["nucleic_b"] is None:
group["nucleic_b"] = determine_b_group_chain(c)
elif is_calpha_trace(c):
if group["protein_b"] is None:
group["calpha_only"] = True
_log.info("Calpha-only chain(s) present")
group["protein_b"] = determine_b_group_chain(c)
elif is_phos_trace(c):
if group["nucleic_b"] is None:
group["phos_only"] = True
_log.info("Backbone phosphorus-only chain(s) present")
group["nucleic_b"] = determine_b_group_chain(c)
else:
_log.error("Chain {0:s}: no protein or nucleic acid chain "
"found (of sufficient length).".format(c.get_id()))
_log.info("Most likely B-factor group type protein: {0:s} | nucleic "
"acid: {1:s}.".format(
group["protein_b"] if group["protein_b"] is not None else
"not present",
group["nucleic_b"] if group["nucleic_b"] is not None else
"not present",))
return group
def determine_b_group_chain(chain):
"""Return the most likely B-factor group type for this chain.
Return a string
overall e.g. 1etu
residue_1ADP e.g. the protein in 1hlz
residue_2ADP e.g. the DNA in 1hlz
individual most PDB files
(margin 0.01 Angstrom**2)
Warning: the current approach is rather greedy as only the first ten
residues of the chain are taken into account. A uniform parameterization
accross the chain is assumed. If multiple domains with different overall
B-factors are present in the same chain, the ouput will still be overall.
Note: if only the first three residues would have been considered,
the approach would have been too greedy for 1hlz chain B or 1av1
"""
margin = 0.01
residues = chain.get_residues()
group = "individual"
group_votes = []
b_res = []
i = 0
max_res = 10
# 10 useful residues should be sufficient to make a decision
while (i < max_res):
# Try to check (the first) 10 canonical residues with heavy and
# occupied atoms. Extract (some of) their B-factors and check if the
# most detailed B-factor model holds, otherwise check if a less
# detailed B-factor model is more applicable.
try:
res = next(residues)
except StopIteration:
# e.g. 1c0q
_log.warn("Chain {0:s} has less than {1:d} useful "
"residues composed of ATOMs.".format(
chain.get_id(), max_res))
break
if res.get_id()[0] == " ": # Exclude HETATM and waters
b_atom = []
for atom in res:
# Exclude hydrogens and zero occupancy (many in e.g. 1etu)
if not re.match("H", atom.get_name()) \
and atom.get_occupancy() > 0:
b = atom.get_bfactor()
_log.debug(("{} - B-factor: {}".format(atom.get_full_id(), b)))
b_atom.append(b)
# Any heavy occupied atoms in this canonical residue?
if len(b_atom) > 0:
b_res.append(b_atom)
i = i + 1
# Determine the B-factor type for this residue if it is not CA-only
# and if we already have enough atoms
if len(b_atom) > 1:
b_atom = sorted(b_atom)
if np.isclose(b_atom[-1], b_atom[0], atol=margin):
group_votes.append("residue_1ADP")
elif len(b_atom) > 3 and \
np.allclose(
[b_atom[-1], b_atom[1]],
[b_atom[-2], b_atom[0]],
atol=margin,) and \
not np.isclose(
b_atom[-2],
b_atom[1],
atol=margin,):
group_votes.append("residue_2ADP")
else:
group_votes.append("individual")
counter = Counter(group_votes)
group_counts = counter.most_common()
_log.debug(group_counts)
group = group_counts[0][0] if len(group_counts) > 0 else group
if len(group_counts) > 1:
# If we have ties, assign most complex model
if group_counts[0][1] == group_counts[1][1]:
if "individual" in list(counter.elements()):
group = "individual"
elif "residue_1ADP" in list(counter.elements()):
group = "residue_1ADP"
else:
group = "residue_2ADP"
big_b = [a for r in b_res for a in r]
big_b = sorted(big_b)
if len(b_res) > max_res - 1:
if np.isclose(big_b[0], big_b[-1], atol=margin):
if np.isclose(big_b[0], 0) and np.isclose(big_b[-1], 0):
group = "no_b-factors"
else:
group = "overall"
elif len(set(big_b)) < 4:
# Exception for structures that have two overall B-factors
group = "overall"
return group
def get_structure(pdb_file_path, pdb_id, verbose=False):
"""Return a Bio.PDB.Structure for this PDB file.
Return None if a Structure could not be created.
"""
structure = None
try:
p = Bio.PDB.PDBParser(QUIET=not verbose)
structure = p.get_structure(pdb_id, pdb_file_path)
except (AttributeError, IndexError, ValueError, AssertionError,
Bio.PDB.PDBExceptions.PDBConstructionException) as e:
# (temporary fix until Biopython parser is fixed)
_log.error("Biopython Error. {0:s}".format(e))
return structure
def has_amino_acid_backbone(residue):
"""Return True if the residue's backbone looks like protein."""
for atom in ("N", "CA", "C", "O"):
if atom not in residue.child_dict:
return False
return True
def has_sugar_phosphate_backbone(residue):
"""Return True if the residue's backbone looks like nucleic acid."""
for atom in ("P", "OP1", "OP2", "O5'", "C5'", "C4'",
"O4'", "C3'", "O3'", "C2'", "C1'"):
if atom not in residue.child_dict:
return False
return True
def is_heavy_backbone(atom):
"""Return True if the atom looks like a backbone atom."""
return atom.get_name() in [
"N", "CA", "C", "O", # Protein
"P", "OP1", "OP2", "O5'", "C5'", "C4'",
"O4'", "C3'", "O3'", "C2'", "O2'", "C1'", ] # DNA/RNA
def is_calpha_trace(chain):
"""Return True if more than 75% of the atoms in the chain are CA atoms.
The function accounts for unexpected residues and atoms (such as UNK and
hetatms listed as atms) by calculating the percentage of ca atoms.
Example: 1efg chain A contains 6 protein domains (each with a different
overall B-factor) and GDP, chain B and C are composed of UNK residues.
"""
ca = []
for atom in chain.get_atoms():
if atom.get_name() == "CA":
ca.append(1)
else:
ca.append(0)
ca_ratio = np.count_nonzero(ca) / len(ca)
return ca_ratio >= 0.75
def is_nucleic_chain(chain):
"""Return True if the first 10 residues of the chain look like nucleotides.
It is assumed mixed protein and nucleic acid chains don't exist.
Therefore this approach is rather greedy.
"""
residues = chain.get_residues()
check_max = 10
residues_checked = 0
# The first residue does not contain the phosphate, we rather start
# checking from the second residue
residues.next()
for res in residues:
if residues_checked < check_max \
and res.get_id()[0] == " ": # Exclude HETATM and waters
if not has_sugar_phosphate_backbone(res):
return False
residues_checked = residues_checked + 1
return True
def is_phos_trace(chain):
"""Return True if more than 75% of the atoms in the chain are P atoms.
The function accounts for unexpected residues and atoms (such as UNK and
hetatms listed as atms) by calculating the percentage of P atoms.
Example: 3cw1 chain V.
"""
p = []
for atom in chain.get_atoms():
if atom.get_name() == "P":
p.append(1)
else:
p.append(0)
p_ratio = np.count_nonzero(p) / len(p)
return p_ratio >= 0.75
def is_protein_chain(chain):
"""Return True if the first 10 residues of the chain look like amino acids.
It is assumed mixed protein and nucleic acid chains don't exist.
Therefore this approach is rather greedy.
"""
residues = chain.get_residues()
check_max = 10
residues_checked = 0
for res in residues:
if residues_checked < check_max \
and res.get_id()[0] == " ": # Exclude HETATM and waters
if not has_amino_acid_backbone(res):
return False
residues_checked = residues_checked + 1
return True
def multiply_bfactors_8pipi(structure):
"""Multiply B-factors with 8*pi**2."""
for atom in structure.get_atoms():
atom.set_bfactor(8*np.pi**2 * atom.get_bfactor())
return structure
def report_beq(reproduced):
"""Report if Beqs are identical to B-factors."""
if reproduced["beq_identical"] is None:
_log.debug("No ANISOU records")
return
if not reproduced["correct_uij"]:
_log.warn("One or more B-factors could only be reproduced "
"by a non-standard combination of Uij values in the "
"corresponding ANISOU record.")
if reproduced["beq_identical"] == 1:
_log.info("The B-factors in the ATOM records could all be "
"reproduced within 0.015 A**2 by calculating Beq from "
"the corresponding ANISOU records.".format(
100 * (1 - reproduced["beq_identical"])))
elif reproduced["beq_identical"] < 1:
_log.warn("{0:3.2f}% of the B-factors in the ATOM records "
"could not be reproduced within 0.015 A**2 by calculating "
"Beq from the corresponding ANISOU records.".format(
100 * (1 - reproduced["beq_identical"])))
else:
_log.info("No ANISOU records.")
def transfer_header_and_trailer(pdb_file_path, xyzout):
"""Transfer header and trailer from pdb_file_path to xyzout."""
transferred = False
h, t = get_pdb_header_and_trailer(pdb_file_path)
records = []
# Start with the header...
records.extend(h)
end = "END"
try:
with open(xyzout, "r") as pdb_out:
# ... then copy coordinates
for coord in pdb_out:
# ... remember but skip END now
if re.search(r"^END\s*$", coord):
end = coord.rstrip("\n")
else:
records.append(coord.rstrip("\n"))
# ... then copy the trailer
records.extend(t)
# ... and finally END
records.append(end)
# write a new file
with open(xyzout + "2", "w") as pdb_out:
for record in records:
pdb_out.write("{0:s}\n".format(record))
# replace the old file with the new file
shutil.move(xyzout + "2", xyzout)
transferred = True
except IOError as ex:
_log.error(ex)
return transferred
def write_multiplied_8pipi(pdb_file_path, xyzout, pdb_id, verbose=False):
"""Multiply the B-factors in the input PDB file with 8*pi^2."""
_log.info("Calculating B-factors from Uiso values...")
structure = get_structure(pdb_file_path, pdb_id, verbose)
structure = multiply_bfactors_8pipi(structure)
io = Bio.PDB.PDBIO()
io.set_structure(structure)
# Header and trailer records not present in this output file
io.save(xyzout)
return transfer_header_and_trailer(pdb_file_path, xyzout)
|
cmbi/bdb
|
pdbb/check_beq.py
|
Python
|
gpl-3.0
| 18,848
|
[
"Biopython"
] |
234fc82aa34687815b27449d940c392a320adec2af290c855e485858aadc2afb
|
#
#-*- coding:utf-8 -*-
"""
Gentoo-keys - cli.py
Command line interface module
@copyright: 2012-2015 by Brian Dolbec <dol-sen@gentoo.org>
@license: GNU GPL2, see COPYING for details.
"""
from __future__ import print_function
import os
import sys
from gkeys import __version__
from gkeys.base import CliBase
from gkeys.actions import Actions
from gkeys.action_map import Available_Actions, Action_Map
from gkeys.config import GKeysConfig
class Main(CliBase):
'''Main command line interface class'''
def __init__(self, root=None, config=None, print_results=True):
""" Main class init function.
@param root: string, root path to use
"""
CliBase.__init__(self)
self.root = root or "/"
self.config = config or GKeysConfig(root=root)
self.config.options['print_results'] = print_results
self.cli_config = {
'Actions': Actions,
'Available_Actions': Available_Actions,
'Action_Map': Action_Map,
'Base_Options': [],
'prog': 'gkeys',
'description': 'Gentoo-keys manager program',
'epilog': '''CAUTION: adding UNTRUSTED keys can be HAZARDOUS to your system!'''
}
self.version = __version__
def __call__(self, args=None):
"""Main class call function
@param args: Optional list of argumanets to parse and action to run
Defaults to sys.argv[1:]
"""
if args:
ok = self.setup(args, [])
else:
args = self.parse_args(sys.argv[1:])
ok = self.setup(args, os.path.join(self.config['configdir'],'gkeys.conf'))
if ok:
return self.run(args)
return False
|
gentoo/gentoo-keys
|
gkeys/gkeys/cli.py
|
Python
|
gpl-2.0
| 1,763
|
[
"Brian"
] |
3320a528ecb4fcf32693e1d48a272ec891063c85afb71c90152755286aa5bad3
|
#!/usr/bin/env python
"Update local HMDB database"
import os
import zlib
import sqlite3
import sys
import argparse
import urllib2
import zipfile
import StringIO
import base64
from rdkit import Chem, Geometry
from rdkit.Chem import AllChem, Descriptors
def version():
return '1.0'
def process_hmdb(args):
conn = sqlite3.connect(args.database_dir + '/HMDB_MAGMa.db')
c = conn.cursor()
try:
c.execute("""CREATE TABLE molecules (id TEXT PRIMARY KEY,
mim INTEGER NOT NULL,
charge INTEGER NOT NULL,
natoms INTEGER NOT NULL,
molblock TEXT,
inchikey TEXT,
smiles TEXT,
molform TEXT,
name TEXT,
reference TEXT,
logp INT)""")
conn.commit()
print ("HMDB_MAGMa.db created")
except:
print ("HMDB_MAGMa.db already exists (or error creating it)")
exit()
if args.data_dir == None:
zf = urllib2.urlopen('http://www.hmdb.ca/system/downloads/current/structures.zip')
else:
zf = open(args.data_dir + 'structures.zip')
sdfile = zipfile.ZipFile(StringIO.StringIO(zf.read())).open('structures.sdf')
memstore = {}
line = '$$$$'
while line != "":
record = []
amap = {}
skip = False
ionized = 0
# read heading:
for x in range(4):
line = sdfile.readline()
record.append(line)
if line == "":
continue
natoms = int(record[-1][:3])
nbonds = int(record[-1][3:6])
bonds = 0
y = 0
for x in range(natoms):
line = sdfile.readline()
if line[31:33] == 'H ':
# skip hydrogens
continue
y += 1
amap[x + 1] = y
if line[31:33] not in ['C ', 'N ', 'O ', 'P ', 'S ', 'F ', 'Cl', 'Br', 'I ']:
# filter non-organic compounds
skip = True
elif line[50:51] != '0':
# this flag has something to do with polymeric structures
# and resulted in deviation between calculated and given inchikeys, skip
skip = True
elif line[38:39] == '4':
# radical, resulted in deviation between calculated and given inchikeys
skip = True
record.append(line[:42] + '\n')
for x in range(nbonds):
line = sdfile.readline()
a1 = int(line[:3])
a2 = int(line[3:6])
# skip bonds involving hydrogens
if a1 in amap and a2 in amap:
bonds += 1
# use bonds with stereoflags set to zero
record.append('%3i%3i%s 0\n' %
(amap[a1], amap[a2], line[6:9]))
while line != 'M END\n' and line != '':
line = sdfile.readline()
record.append(line)
if line[:6] == 'M ISO':
skip = True
print 'Skipped isotopically labeled:', record[0][:-1]
while line != "$$$$\n" and line != "":
line = sdfile.readline()
if line == "> <HMDB_ID>\n":
hmdb_id = str(sdfile.readline()[:-1])
elif line == "> <GENERIC_NAME>\n":
molname = str(sdfile.readline()[:-1])
elif line == "> <INCHI_KEY>\n":
inchi_key = sdfile.readline()[:-1]
if line != "" and skip == False:
record[3] = repr(y).rjust(3) + repr(bonds).rjust(3) + record[3][6:]
molblock = ''.join(record)
mol = Chem.MolFromMolBlock(molblock)
if mol == None or mol.GetNumAtoms() == 0:
continue
smiles = Chem.MolToSmiles(mol)
if len(Chem.GetMolFrags(mol)) > 1:
print 'complex:', hmdb_id, smiles
continue
conf = mol.GetConformer(0)
molblock = base64.encodestring(zlib.compress(''.join(record)))
molform = Chem.rdMolDescriptors.CalcMolFormula(mol)
mim = Chem.rdMolDescriptors.CalcExactMolWt(mol)
charge = 0
if '-' in molform:
if molform[-1] == '-':
charge = -1
else:
continue
elif '+' in molform:
if molform[-1] == '+':
charge = 1
else:
continue
if mim > 1200.0:
print 'molecule to heavy:', hmdb_id, smiles
continue
natoms = mol.GetNumHeavyAtoms()
logp = Chem.Crippen.MolLogP(mol)
inchikey = Chem.AllChem.InchiToInchiKey(
AllChem.MolToInchi(mol))[:14]
if inchikey != inchi_key[:14]:
print 'given inchikey does not match calculated inchikey, skipped:', hmdb_id, smiles
continue
ionized = 0
for x in ['C(=O)[O-]', '[NH+]', '[NH2+]', '[NH3+]', '[NH4+]']:
if smiles.find(x) >= 0:
ionized = 1
if inchikey in memstore:
dbid, reference, dbionized = memstore[inchikey]
reference = reference + ',' + hmdb_id
print 'Duplicates:', reference, molname
if dbionized > ionized: # prefer non-ionized CID's
c.execute('''UPDATE molecules SET id=?, mim=?, charge=?, molblock=?, smiles=?,
molform=?, name=?, reference=?, logp=? WHERE id == ?''', (
hmdb_id,
int(mim * 1e6),
charge,
unicode(molblock),
unicode(smiles),
unicode(molform),
unicode(molname, 'utf-8', 'xmlcharrefreplace'),
unicode(reference),
int(logp * 10),
dbid))
memstore[inchikey] = (hmdb_id, reference, ionized)
else:
c.execute('UPDATE molecules SET reference=? WHERE id == ?', (
unicode(reference),dbid))
memstore[inchikey] = (dbid, reference, dbionized)
else:
c.execute('''INSERT INTO molecules (id, mim, charge, natoms, molblock, inchikey,
smiles,molform,name,reference,logp) VALUES (?,?,?,?,?,?,?,?,?,?,?)''', (
hmdb_id,
int(mim * 1e6),
charge,
int(natoms),
unicode(molblock),
unicode(inchikey),
unicode(smiles),
unicode(molform),
unicode(molname, 'utf-8', 'xmlcharrefreplace'),
unicode(hmdb_id),
int(logp * 10)))
memstore[inchikey] = (hmdb_id, hmdb_id, ionized)
conn.commit()
print "Creating index ..."
c.execute('PRAGMA temp_store = 2')
c.execute(
'CREATE INDEX idx_cover ON molecules (charge,mim,natoms,reference,molform,inchikey,smiles,name,molblock,logp)')
conn.commit()
# main
mainparser = argparse.ArgumentParser(description=__doc__)
mainparser.add_argument(
'-v', '--version', action='version', version='%(prog)s ' + version())
mainparser.add_argument(
'-d', '--data_dir', help="""Directory where HMDB structures.zip file is stored
(default: %(default)s, attempt to read directly from HMDB server)""", default=None, type=str)
mainparser.add_argument(
'-b', '--database_dir', help="Directory where HMDB database is stored (default: %(default)s)", default="./", type=str)
mainparser.set_defaults(func=process_hmdb)
args = mainparser.parse_args(sys.argv[1:])
args.func(args)
|
NLeSC/MAGMa
|
pubchem/process_hmdb.py
|
Python
|
apache-2.0
| 8,464
|
[
"RDKit"
] |
268c0f81edc2ebac93acfb376233c73b9d726c147a79a9143e2318cce2eddcc5
|
"""
:copyright: Copyright 2006-2016 by the PyNN team, see AUTHORS.
:license: CeCILL, see LICENSE for details.
"""
import logging
import numpy
import quantities as pq
import brian
from pyNN import recording
from . import simulator
mV = brian.mV
ms = brian.ms
uS = brian.uS
pq.uS = pq.UnitQuantity('microsiemens', 1e-6 * pq.S, 'uS')
pq.nS = pq.UnitQuantity('nanosiemens', 1e-9 * pq.S, 'nS')
logger = logging.getLogger("PyNN")
class Recorder(recording.Recorder):
"""Encapsulates data and functions related to recording model variables."""
_simulator = simulator
def __init__(self, population=None, file=None):
__doc__ = recording.Recorder.__doc__
recording.Recorder.__init__(self, population, file)
self._devices = {} # defer creation until first call of record()
def _create_device(self, group, variable):
"""Create a Brian recording device."""
# By default, StateMonitor has when='end', i.e. the value recorded at
# the end of the timestep is associated with the time at the start of the step,
# This is different to the PyNN semantics (i.e. the value at the end of
# the step is associated with the time at the end of the step.)
clock = simulator.state.network.clock
if variable == 'spikes':
self._devices[variable] = brian.SpikeMonitor(group, record=self.recorded)
else:
varname = self.population.celltype.state_variable_translations[variable]['translated_name']
self._devices[variable] = brian.StateMonitor(group, varname,
record=self.recorded,
clock=clock,
when='start',
timestep=int(round(self.sampling_interval / simulator.state.dt)))
simulator.state.network.add(self._devices[variable])
def _record(self, variable, new_ids, sampling_interval=None):
"""Add the cells in `new_ids` to the set of recorded cells."""
self.sampling_interval = sampling_interval or self._simulator.state.dt
if variable not in self._devices:
self._create_device(self.population.brian_group, variable)
# update StateMonitor.record and StateMonitor.recordindex
if variable is not 'spikes':
device = self._devices[variable]
device.record = numpy.sort(numpy.fromiter(self.recorded[variable], dtype=int)) - self.population.first_id
device.recordindex = dict((i, j) for i, j in zip(device.record,
range(len(device.record))))
logger.debug("recording %s from %s" % (variable, self.recorded[variable]))
def _reset(self):
"""Clear the list of cells to record."""
for device in self._devices.values():
device.reinit()
device.record = False
def _clear_simulator(self):
"""Delete all recorded data, but retain the list of cells to record from."""
for device in self._devices.values():
device.reinit()
def _get_spiketimes(self, id):
i = id - self.population.first_id
return self._devices['spikes'].spiketimes[i] / ms
def _get_all_signals(self, variable, ids, clear=False):
# need to filter according to ids
device = self._devices[variable]
# because we use `when='start'`, need to add the value at the end of the final time step.
values = numpy.array(device._values)
current_values = device.P.state_(device.varname)[device.record]
all_values = numpy.vstack((values, current_values[numpy.newaxis, :]))
logging.debug("@@@@ %s %s %s", id(device), values.shape, all_values.shape)
varname = self.population.celltype.state_variable_translations[variable]['translated_name']
all_values = eval(self.population.celltype.state_variable_translations[variable]['reverse_transform'], {}, {varname: all_values})
if clear:
self._devices[variable].reinit()
return all_values
def _local_count(self, variable, filter_ids=None):
N = {}
filtered_ids = self.filter_recorded(variable, filter_ids)
padding = self.population.first_id
indices = numpy.fromiter(filtered_ids, dtype=int) - padding
for i, id in zip(indices, filtered_ids):
N[id] = len(self._devices['spikes'].spiketimes[i])
return N
|
anupkdas-nus/global_synapses
|
pyNN-dispackgaes/brian/recording.py
|
Python
|
gpl-3.0
| 4,558
|
[
"Brian"
] |
a7cbc10a5f216b4007524473f15e0428e450c7e7bab93ee105b13ec838a782d0
|
import pymc
import TorsionScanSet
from chemistry.topologyobjects import DihedralType
import numpy as np
from simtk.unit import kilojoules_per_mole
class TorsionFitModel(object):
"""pymc model
Attributes:
----------
pymc_parameters: dict() of pymc parameters
parameters_to_optimize: list of tuples (dihedrals to optimize)
fags: list of TorsionScanSet for fragments
platform: OpenMM platform to use for potential energy calculations
"""
def __init__(self, param, stream, frags, platform=None):
"""Create a PyMC model for fitting torsions.
Parameters
---------
param : parmed ParameterSet
Set of parameters that will not be optimized.
stream : parmed ParameterSet
Set of parameters including those that will be optimized.
Existing parameters will be used as initial parameters.
frags : list of fragments
List of small molecule fragments with QM torsion data to fit.
platform : simtk.openmm.Platform
OpenMM Platform to use for computing potential energies.
"""
if type(frags) != list:
frags = [frags]
self.pymc_parameters = dict()
self.frags = frags
self.platform = platform
self.parameters_to_optimize = TorsionScanSet.to_optimize(param, stream)
multiplicities = [1, 2, 3, 4, 6]
multiplicity_bitstrings = dict()
# offset
for frag in self.frags:
name = '%s_offset' % frag.topology._residues[0]
offset = pymc.Uniform(name, lower=-50, upper=50, value=0)
self.pymc_parameters[name] = offset
for p in self.parameters_to_optimize:
torsion_name = p[0] + '_' + p[1] + '_' + p[2] + '_' + p[3]
if torsion_name not in multiplicity_bitstrings.keys():
multiplicity_bitstrings[torsion_name] = 0
for m in multiplicities:
name = p[0] + '_' + p[1] + '_' + p[2] + '_' + p[3] + '_' + str(m) + '_K'
k = pymc.Uniform(name, lower=0, upper=20, value=0)
for i in range(len(param.dihedral_types[p])):
if param.dihedral_types[p][i].per == m:
multiplicity_bitstrings[torsion_name] += 2 ** (m - 1)
k = pymc.Uniform(name, lower=0, upper=20, value=param.dihedral_types[p][i].phi_k)
break
self.pymc_parameters[name] = k
name = p[0] + '_' + p[1] + '_' + p[2] + '_' + p[3] + '_' + str(m) + '_Phase'
phase = pymc.DiscreteUniform(name, lower=0, upper=1, value=0)
for i in range(len(param.dihedral_types[p])):
if param.dihedral_types[p][i].per == m:
if param.dihedral_types[p][i].phase == 0:
phase = pymc.DiscreteUniform(name, lower=0, upper=1, value=0)
break
if param.dihedral_types[p][i].phase == 3.141592653589793:
phase = pymc.DiscreteUniform(name, lower=0, upper=1, value=1)
break
self.pymc_parameters[name] = phase
for torsion_name in multiplicity_bitstrings.keys():
name = torsion_name + '_multiplicity_bitstring'
bitstring = pymc.DiscreteUniform(name, lower=0, upper=63, value=multiplicity_bitstrings[torsion_name])
self.pymc_parameters[name] = bitstring
self.pymc_parameters['log_sigma'] = pymc.Uniform('log_sigma', lower=-10, upper=3, value=np.log(0.01))
self.pymc_parameters['sigma'] = pymc.Lambda('sigma',
lambda log_sigma=self.pymc_parameters['log_sigma']: np.exp(
log_sigma))
self.pymc_parameters['precision'] = pymc.Lambda('precision',
lambda log_sigma=self.pymc_parameters['log_sigma']: np.exp(
-2 * log_sigma))
@pymc.deterministic
def mm_energy(pymc_parameters=self.pymc_parameters, param=param):
self.update_param(param)
mm_energy = np.ndarray(0)
for frag in self.frags:
frag.compute_energy(param, offset=self.pymc_parameters['%s_offset' % frag.topology._residues[0]],
platform=self.platform)
mm_energy = np.append(mm_energy, frag.mm_energy / kilojoules_per_mole)
return mm_energy
size = [len(i.delta_energy) for i in self.frags]
qm_energy = np.ndarray(0)
for i in range(len(frags)):
qm_energy = np.append(qm_energy, frags[i].qm_energy)
self.pymc_parameters['mm_energy'] = mm_energy
self.pymc_parameters['qm_fit'] = pymc.Normal('qm_fit', mu=self.pymc_parameters['mm_energy'],
tau=self.pymc_parameters['precision'], size=size, observed=True,
value=qm_energy)
def add_missing(self, param):
"""
Update param set with missing multiplicities.
:param: chemistry.charmm.CharmmParameterSet
:return: updated CharmmParameterSet with multiplicities 1-6 for parameters to optimize
"""
multiplicities = [1, 2, 3, 4, 6]
for p in self.parameters_to_optimize:
per = []
for i in range(len(param.dihedral_types[p])):
per.append(param.dihedral_types[p][i].per)
for j in multiplicities:
if j not in per:
param.dihedral_types[p].append(DihedralType(0, j, 0))
def update_param(self, param):
"""
Update param set based on current pymc model parameters.
:param: chemistry.charmm.CharmmParameterSet
:return: updated CharmmParmaterSet based on current TorsionFitModel parameters
"""
multiplicities = [1, 2, 3, 4, 6]
for p in self.parameters_to_optimize:
torsion_name = p[0] + '_' + p[1] + '_' + p[2] + '_' + p[3]
multiplicity_bitstring = self.pymc_parameters[torsion_name + '_multiplicity_bitstring'].value
for i in range(len(param.dihedral_types[p])):
m = int(param.dihedral_types[p][i].per)
multiplicity_bitmask = 2 ** (m - 1) # multiplicity bitmask
if multiplicity_bitstring & multiplicity_bitmask:
if m == 5:
continue
k = torsion_name + '_' + str(m) + '_K'
phase = torsion_name + '_' + str(m) + '_Phase'
pymc_variable = self.pymc_parameters[k]
param.dihedral_types[p][i].phi_k = pymc_variable.value
pymc_variable = self.pymc_parameters[phase]
param.dihedral_types[p][i].phase = pymc_variable.value
else:
# This torsion periodicity is disabled.
param.dihedral_types[p][i].phi_k = 0
|
hainm/Torsions
|
torsions/TorsionFitModel.py
|
Python
|
gpl-2.0
| 7,203
|
[
"CHARMM",
"OpenMM"
] |
8824da080f395b193886aecebf305bbf747e0bd550c0c565270b11b9c28705b7
|
"""
.. See the NOTICE file distributed with this work for additional information
regarding copyright ownership.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
"""
from __future__ import print_function
import shlex
import subprocess
import os
import os.path
import shutil
import tarfile
from utils import logger
from tool.common import cd
from tool.bam_utils import bamUtils
class alignerUtils(object): # pylint: disable=invalid-name
"""
Functions for downloading and processing N-seq FastQ files. Functions
provided allow for the downloading and indexing of the genome assemblies.
"""
def __init__(self):
"""
Initialise the module
"""
logger.info("Alignment Utils")
@staticmethod
def replaceENAHeader(file_path, file_out):
"""
The ENA header has pipes in the header as part of the stable_id. This
function removes the ENA stable_id and replaces it with the final
section after splitting the stable ID on the pipe.
"""
with open(file_out, 'w') as new_file:
with open(file_path) as old_file:
for line in old_file:
if line[0] == '>':
space_line = line.split(" ")
new_file.write(">" + space_line[0].split("|")[-1].replace(">", "") + "\n")
else:
new_file.write(line)
return True
@staticmethod
def gem_index_genome(genome_file, index_name=None):
"""
Create an index of the genome FASTA file with GEM. These are saved
alongside the assembly file.
Parameters
----------
genome_file : str
Location of the assembly file in the file system
"""
if not index_name:
index_name = genome_file
command_line = 'gem-indexer -i ' + genome_file + ' -o ' + index_name
args = shlex.split(command_line)
process = subprocess.Popen(args)
process.wait()
return True
@staticmethod
def bowtie_index_genome(genome_file):
"""
Create an index of the genome FASTA file with Bowtie2. These are saved
alongside the assembly file.
Parameters
----------
genome_file : str
Location of the assembly file in the file system
"""
file_name = os.path.split(genome_file)
bt2_1_name = genome_file + ".1.bt2"
bt2_2_name = genome_file + ".2.bt2"
bt2_3_name = genome_file + ".3.bt2"
bt2_4_name = genome_file + ".4.bt2"
rev1_bt2_name = genome_file + ".rev.1.bt2"
rev2_bt2_name = genome_file + ".rev.2.bt2"
with cd(file_name[0]):
command_line = 'bowtie2-build ' + genome_file + ' ' + genome_file
args = shlex.split(command_line)
process = subprocess.Popen(args)
process.wait()
return (bt2_1_name, bt2_2_name, bt2_3_name, bt2_4_name, rev1_bt2_name, rev2_bt2_name)
def bowtie2_untar_index(self, genome_name, tar_file, # pylint: disable=too-many-arguments
bt2_1_file, bt2_2_file, bt2_3_file, bt2_4_file,
bt2_rev1_file, bt2_rev2_file):
"""
Extracts the BWA index files from the genome index tar file.
Parameters
----------
genome_file_name : str
Location string of the genome fasta file
tar_file : str
Location of the Bowtie2 index file
bt2_1_file : str
Location of the amb index file
bt2_2_file : str
Location of the ann index file
bt2_3_file : str
Location of the bwt index file
bt2_4_file : str
Location of the pac index file
bt2_rev1_file : str
Location of the sa index file
bt2_rev2_file : str
Location of the sa index file
Returns
-------
bool
Boolean indicating if the task was successful
"""
index_files = {
"1.bt2": bt2_1_file,
"2.bt2": bt2_2_file,
"3.bt2": bt2_3_file,
"4.bt2": bt2_4_file,
"rev.1.bt2": bt2_rev1_file,
"rev.2.bt2": bt2_rev2_file,
}
return self._untar_index(genome_name, tar_file, index_files)
@staticmethod
def bwa_index_genome(genome_file):
"""
Create an index of the genome FASTA file with BWA. These are saved
alongside the assembly file. If the index has already been generated
then the locations of the files are returned
Parameters
----------
genome_file : str
Location of the assembly file in the file system
Returns
-------
amb_file : str
Location of the amb file
ann_file : str
Location of the ann file
bwt_file : str
Location of the bwt file
pac_file : str
Location of the pac file
sa_file : str
Location of the sa file
Example
-------
.. code-block:: python
:linenos:
from tool.aligner_utils import alignerUtils
au_handle = alignerUtils()
indexes = au_handle.bwa_index_genome('/<data_dir>/human_GRCh38.fa.gz')
print(indexes)
"""
command_line = 'bwa index ' + genome_file
amb_name = genome_file + '.amb'
ann_name = genome_file + '.ann'
bwt_name = genome_file + '.bwt'
pac_name = genome_file + '.pac'
sa_name = genome_file + '.sa'
if os.path.isfile(bwt_name) is False:
args = shlex.split(command_line)
process = subprocess.Popen(args)
process.wait()
return (amb_name, ann_name, bwt_name, pac_name, sa_name)
def bwa_untar_index(self, genome_name, tar_file, # pylint: disable=too-many-arguments
amb_file, ann_file, bwt_file, pac_file, sa_file):
"""
Extracts the BWA index files from the genome index tar file.
Parameters
----------
genome_file_name : str
Location string of the genome fasta file
genome_idx : str
Location of the BWA index file
amb_file : str
Location of the amb index file
ann_file : str
Location of the ann index file
bwt_file : str
Location of the bwt index file
pac_file : str
Location of the pac index file
sa_file : str
Location of the sa index file
Returns
-------
bool
Boolean indicating if the task was successful
"""
index_files = {
"amb": amb_file,
"ann": ann_file,
"bwt": bwt_file,
"pac": pac_file,
"sa": sa_file
}
return self._untar_index(genome_name, tar_file, index_files)
@staticmethod
def _untar_index(genome_name, tar_file, index_files):
"""
Untar the specified files for a genomic index into the specified
location.
Parameters
----------
genome_name : str
Name of the genome for the folder within the tar file
tar_file : str
Location of the tarred index files
index_files : dict
Dictionary object of the suffix and final index file location
"""
try:
g_dir = os.path.split(tar_file)[0]
tar = tarfile.open(tar_file)
tar.extractall(path=g_dir)
tar.close()
gidx_folder = tar_file.replace('.tar.gz', '/') + genome_name
piece_size = 5120000 # 500MB
for suffix in list(index_files.keys()):
with open(index_files[suffix], "wb") as f_out:
with open(gidx_folder + "." + suffix, "rb") as f_in:
while True:
piece = f_in.read(piece_size)
if not piece:
break # end of file
print("PIECE:", piece[0:5])
f_out.write(piece)
shutil.rmtree(tar_file.replace('.tar.gz', ''))
except (OSError, IOError) as error:
logger.fatal("UNTAR: I/O error({0}): {1}".format(error.errno, error.strerror))
return False
return True
@staticmethod
def bowtie2_align_reads(
genome_file, bam_loc, params, reads_file_1, reads_file_2=None):
"""
Map the reads to the genome using BWA.
Parameters
----------
genome_file : str
Location of the assembly file in the file system
reads_file : str
Location of the reads file in the file system
bam_loc : str
Location of the output file
"""
reads = ["-U", reads_file_1]
if reads_file_2 is not None:
reads = [
"-1", reads_file_1,
"-2", reads_file_2
]
logger.info(genome_file)
logger.info(' '.join(params))
cmd_aln = ' '.join([
'bowtie2',
'-p 4',
'-x', genome_file,
'-S', reads_file_1 + '.sam',
' '.join(params),
] + reads)
try:
logger.info("BOWTIE2 COMMAND: " + cmd_aln)
process = subprocess.Popen(cmd_aln, shell=True)
process.wait()
except (OSError, IOError) as msg:
logger.info("I/O error({0}): {1}\n{2}".format(
msg.errno, msg.strerror, cmd_aln))
return False
bu_handle = bamUtils()
return_val = bu_handle.sam_to_bam(reads_file_1 + '.sam', bam_loc)
if return_val:
os.remove(reads_file_1 + '.sam')
else:
logger.warn("IO error with {} to {}".format(reads_file_1 + '.sam', bam_loc))
return return_val
def _bwa_aln_sai(self, genome_file, reads_file, params, single=True): # pylint: disable=no-self-use
"""
Generate the sai files required for creating the sam file.
Parameters
----------
genome_file : str
Location of the assembly file in the file system
reads_file : str
Location of the reads file in the file system
params : dict
Dictionary of the parameters for bwa aln
single : bool
True for single ended, will use 4 threads for processing
False for paired end, will use 2 threads for processing
"""
threads = "2"
if single:
threads = "4"
cmd_aln_sai = ' '.join([
'bwa aln',
'-t', threads,
'-q', '5',
' '.join(params),
'-f', reads_file + '.sai',
genome_file, reads_file
])
try:
logger.info("BWA ALN COMMAND: " + cmd_aln_sai)
process = subprocess.Popen(cmd_aln_sai, shell=True)
process.wait()
except (OSError, IOError) as msg:
logger.info("I/O error({0}): {1}\n{2}".format(
msg.errno, msg.strerror, cmd_aln_sai))
def bwa_aln_align_reads_single(self, genome_file, reads_file, bam_loc, params):
"""
Map the reads to the genome using BWA.
Parameters
----------
genome_file : str
Location of the assembly file in the file system
reads_file : str
Location of the reads file in the file system
bam_loc : str
Location of the output file
"""
cmd_samse = ' '.join([
'bwa samse',
'-f', reads_file + '.sam',
genome_file, reads_file + '.sai', reads_file
])
self._bwa_aln_sai(genome_file, reads_file, params, True)
try:
logger.info("BWA ALN COMMAND: " + cmd_samse)
process = subprocess.Popen(
cmd_samse, shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
process.wait()
proc_out, proc_err = process.communicate() # pylint: disable=unused-variable
except (OSError, IOError) as msg:
logger.info("I/O error({0}): {1}\n{2}".format(
msg.errno, msg.strerror, cmd_samse))
proc_out, proc_err = process.communicate()
logger.fatal("BWA ALN stderr" + proc_err)
return False
bu_handle = bamUtils()
return_val = bu_handle.sam_to_bam(reads_file + '.sam', bam_loc)
if return_val:
os.remove(reads_file + '.sam')
os.remove(reads_file + '.sai')
else:
logger.warn("IO error with {} to {}".format(reads_file + '.sam', bam_loc))
return return_val
def bwa_aln_align_reads_paired(self, genome_file, reads_file_1, reads_file_2, bam_loc, params): # pylint: disable=too-many-arguments
"""
Map the reads to the genome using BWA.
Parameters
----------
genome_file : str
Location of the assembly file in the file system
reads_file : str
Location of the reads file in the file system
bam_loc : str
Location of the output file
"""
cmd_samse = ' '.join([
'bwa sampe',
'-f', reads_file_1 + '.sam',
genome_file,
reads_file_1 + '.sai', reads_file_2 + '.sai',
reads_file_1, reads_file_2
])
try:
import multiprocessing
f1_proc = multiprocessing.Process(
name='fastq_1', target=self._bwa_aln_sai,
args=(genome_file, reads_file_1, params, False)
)
f2_proc = multiprocessing.Process(
name='fastq_2', target=self._bwa_aln_sai,
args=(genome_file, reads_file_2, params, False)
)
f1_proc.start()
f2_proc.start()
f1_proc.join()
f2_proc.join()
except (OSError, IOError) as msg:
logger.info("SAI ERROR: I/O error({0}): {1}".format(
msg.errno, msg.strerror))
return False
try:
logger.info("BWA ALN COMMAND: " + cmd_samse)
process = subprocess.Popen(cmd_samse, shell=True)
process.wait()
except (OSError, IOError) as msg:
logger.info("I/O error({0}): {1}\n{2}".format(
msg.errno, msg.strerror, cmd_samse))
return False
bu_handle = bamUtils()
return_val = bu_handle.sam_to_bam(reads_file_1 + '.sam', bam_loc)
if return_val:
os.remove(reads_file_1 + '.sam')
os.remove(reads_file_1 + '.sai')
os.remove(reads_file_2 + '.sai')
else:
logger.warn("IO error with {} to {}".format(reads_file_1 + '.sam', bam_loc))
return return_val
@staticmethod
def bwa_mem_align_reads(
genome_file, bam_loc, params, reads_file_1, reads_file_2=None):
"""
Map the reads to the genome using BWA.
Parameters
----------
genome_file : str
Location of the assembly file in the file system
reads_file : str
Location of the reads file in the file system
bam_loc : str
Location of the output file
"""
reads = [reads_file_1]
if reads_file_2 is not None:
reads.append(reads_file_2)
cmd_aln = ' '.join([
'bwa mem -t 4',
' '.join(params),
genome_file
] + reads)
try:
with open(reads_file_1 + '.sam', "w") as f_out:
logger.info("BWA MEM COMMAND: " + cmd_aln)
process = subprocess.Popen(cmd_aln, shell=True, stdout=f_out)
process.wait()
except (OSError, IOError) as msg:
logger.info("I/O error({0}): {1}\n{2}".format(
msg.errno, msg.strerror, cmd_aln))
return False
bu_handle = bamUtils()
return_val = bu_handle.sam_to_bam(reads_file_1 + '.sam', bam_loc)
if return_val:
os.remove(reads_file_1 + '.sam')
else:
logger.warn("IO error with {} to {}".format(reads_file_1 + '.sam', bam_loc))
return return_val
|
Multiscale-Genomics/mg-process-fastq
|
tool/aligner_utils.py
|
Python
|
apache-2.0
| 16,998
|
[
"BWA"
] |
69fba9e118a3b4e168beaa9459f1d7ed70ffe1cb6677af7fa6829ef377a67d6f
|
# Copyright 2002 by Jeffrey Chang. All rights reserved.
# This code is part of the Biopython distribution and governed by its
# license. Please see the LICENSE file that should have been included
# as part of this package.
from Bio.config.DBRegistry import CGIDB, DBGroup
from _support import *
prosite_expasy_cgi = CGIDB(
name="prosite-expasy-cgi",
doc="Retrieve a prosite entry by ID",
cgi='http://us.expasy.org/cgi-bin/get-prosite-raw.pl',
delay=5.0,
params=[],
key="",
failure_cases=[(has_str("There is currently no PROSITE entry"),
"No PROSITE entry")],
)
prosite = DBGroup(
name = "prosite",
behavior = "serial"
)
prosite.add(prosite_expasy_cgi)
|
dbmi-pitt/DIKB-Micropublication
|
scripts/mp-scripts/Bio/dbdefs/prosite.py
|
Python
|
apache-2.0
| 723
|
[
"Biopython"
] |
07cde6b8ef599a5884c5d4998d0f89079c882ad85e88f0f0a0c4bb5fc798b6c8
|
# -*- coding: utf-8 -*-
# vi:si:et:sw=4:sts=4:ts=4
##
## Copyright (C) 2013 Async Open Source <http://www.async.com.br>
## All rights reserved
##
## This program is free software; you can redistribute it and/or modify
## it under the terms of the GNU General Public License as published by
## the Free Software Foundation; either version 2 of the License, or
## (at your option) any later version.
##
## This program is distributed in the hope that it will be useful,
## but WITHOUT ANY WARRANTY; without even the implied warranty of
## MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
## GNU General Public License for more details.
##
## You should have received a copy of the GNU General Public License
## along with this program; if not, write to the Free Software
## Foundation, Inc., or visit: http://www.gnu.org/.
##
## Author(s): Stoq Team <stoq-devel@async.com.br>
##
__tests__ = 'stoqlib/gui/widgets/calculator.py'
import contextlib
import gtk
from kiwi.currency import currency
from kiwi.datatypes import ValidationError
from kiwi.ui.widgets.entry import ProxyEntry
from kiwi.ui.widgets.spinbutton import ProxySpinButton
import mock
from stoqlib.gui.stockicons import STOQ_CALC
from stoqlib.gui.test.uitestutils import GUITest
from stoqlib.gui.widgets.calculator import CalculatorPopup
class TestCalculatorPopup(GUITest):
def test_show(self):
spinbutton = ProxySpinButton()
spinbutton.data_type = currency
calc = CalculatorPopup(spinbutton, CalculatorPopup.MODE_SUB)
self.check_widget(calc, 'calculator-popup-show')
def test_attach(self):
entry = ProxyEntry()
entry.data_type = currency
self.assertEqual(entry.get_property('secondary-icon-pixbuf'), None)
calc = CalculatorPopup(entry, CalculatorPopup.MODE_SUB)
pixbuf_pixels = calc.render_icon(STOQ_CALC,
gtk.ICON_SIZE_MENU).get_pixels()
self.assertEqual(
entry.get_property('secondary-icon-pixbuf').get_pixels(), pixbuf_pixels)
entry.set_sensitive(False)
self.assertEqual(entry.get_property('secondary-icon-pixbuf'), None)
entry.set_sensitive(True)
self.assertEqual(
entry.get_property('secondary-icon-pixbuf').get_pixels(), pixbuf_pixels)
spinbutton = ProxySpinButton()
spinbutton.data_type = currency
self.assertEqual(spinbutton.get_property('secondary-icon-pixbuf'), None)
calc = CalculatorPopup(spinbutton, CalculatorPopup.MODE_SUB)
pixbuf_pixels = calc.render_icon(STOQ_CALC,
gtk.ICON_SIZE_MENU).get_pixels()
self.assertEqual(
spinbutton.get_property('secondary-icon-pixbuf').get_pixels(), pixbuf_pixels)
spinbutton.set_sensitive(False)
self.assertEqual(spinbutton.get_property('secondary-icon-pixbuf'), None)
spinbutton.set_sensitive(True)
self.assertEqual(
spinbutton.get_property('secondary-icon-pixbuf').get_pixels(), pixbuf_pixels)
def test_popup(self):
entry = ProxyEntry()
entry.data_type = currency
entry.set_text('150')
calc = CalculatorPopup(entry, CalculatorPopup.MODE_SUB)
event = gtk.gdk.Event(gtk.gdk.BUTTON_PRESS)
event.window = gtk.gdk.get_default_root_window()
with mock.patch.object(calc, 'popup') as popup:
entry.emit('icon-press', gtk.ENTRY_ICON_PRIMARY, event)
self.assertEqual(popup.call_count, 0)
entry.emit('icon-press', gtk.ENTRY_ICON_SECONDARY, event)
self.assertEqual(popup.call_count, 1)
def test_popdown(self):
entry = ProxyEntry()
entry.data_type = currency
entry.set_text('150')
calc = CalculatorPopup(entry, CalculatorPopup.MODE_SUB)
with contextlib.nested(
mock.patch.object(calc, '_maybe_apply_new_value'),
mock.patch.object(calc, 'popdown')) as (manv, popdown):
# Those keys should try to apply the value
for keyval in [gtk.keysyms.Return,
gtk.keysyms.KP_Enter,
gtk.keysyms.Tab]:
event = gtk.gdk.Event(gtk.gdk.KEY_PRESS)
event.keyval = keyval
event.window = gtk.gdk.get_default_root_window()
calc.emit('key-press-event', event)
self.assertEqual(manv.call_count, 1)
self.assertEqual(popdown.call_count, 0)
manv.reset_mock()
popdown.reset_mock()
event = gtk.gdk.Event(gtk.gdk.KEY_PRESS)
# Escape should popdown the popup
event.keyval = gtk.keysyms.Escape
event.window = gtk.gdk.get_default_root_window()
calc.emit('key-press-event', event)
self.assertEqual(popdown.call_count, 1)
self.assertEqual(manv.call_count, 0)
manv.reset_mock()
popdown.reset_mock()
event = gtk.gdk.Event(gtk.gdk.KEY_PRESS)
# Any other should not do anything
event.keyval = gtk.keysyms.A
event.window = gtk.gdk.get_default_root_window()
calc.emit('key-press-event', event)
self.assertEqual(manv.call_count, 0)
self.assertEqual(popdown.call_count, 0)
def test_apply(self):
entry = ProxyEntry()
entry.data_type = currency
entry.set_text('150')
calc = CalculatorPopup(entry, CalculatorPopup.MODE_SUB)
# calc.popup will not work here, so call _update_ui directly
calc._update_ui()
calc._entry.set_text('10%')
event = gtk.gdk.Event(gtk.gdk.KEY_PRESS)
event.keyval = gtk.keysyms.Return
event.window = gtk.gdk.get_default_root_window()
calc.emit('key-press-event', event)
calc.emit('key-press-event', event)
self.assertEqual(entry.read(), 135)
def test_validate(self):
def validate_entry(entry, value):
if value == 100:
return ValidationError()
# FIXME: For some reason, entry is not emitting 'changed' event
# on set_text, not even if we call entry.emit('changed') by hand.
# That only happens here on the test. Figure out why
def update_entry(entry, value):
entry.set_text(value)
entry.validate(force=True)
entry = ProxyEntry()
entry.data_type = currency
entry.connect('validate', validate_entry)
entry.set_text('150')
calc = CalculatorPopup(entry, CalculatorPopup.MODE_SUB)
# calc.popup will not work here, so call _update_ui directly
calc._update_ui()
self.assertValid(calc, ['_entry'])
self.assertNotVisible(calc, ['_warning'])
for value in ['abc', '+10%', '-10%', '+10', '-10']:
update_entry(calc._entry, value)
self.assertInvalid(calc, ['_entry'])
self.assertNotVisible(calc, ['_warning'])
update_entry(calc._entry, '40')
self.assertValid(calc, ['_entry'])
self.assertNotVisible(calc, ['_warning'])
# 50 of discount will make the value invalid on entry
# (see validate_entry above)
update_entry(calc._entry, '50')
self.assertValid(calc, ['_entry'])
self.assertVisible(calc, ['_warning'])
|
andrebellafronte/stoq
|
stoqlib/gui/test/test_calculator.py
|
Python
|
gpl-2.0
| 7,402
|
[
"VisIt"
] |
ace3f2b7bab528f47293d9691b57b0a37dcb3b0efd2532c59afc2108cb8f54c8
|
# Copyright (C) 2013-2014 Fox Wilson, Peter Foley, Srijay Kasturi, Samuel Damashek, James Forcier and Reed Koser
#
# This program is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License
# as published by the Free Software Foundation; either version 2
# of the License, or (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
from random import choice
from helpers.command import Command
@Command('choose')
def cmd(send, msg, args):
"""Chooses between multiple choices.
Syntax: {command} <object> or <object> (or <object>...)
"""
if not msg:
send("Choose what?")
return
choices = msg.split(' or ')
action = ['draws a slip of paper from a hat and gets...', 'says eenie, menie, miney, moe and chooses...',
'picks a random number and gets...', 'rolls dice and gets...', 'asks a random person and gets...',
'plays rock, paper, scissors, lizard, spock and gets...']
send("%s %s" % (choice(action), choice(choices)), 'action')
|
sckasturi/saltlake
|
commands/choose.py
|
Python
|
gpl-2.0
| 1,491
|
[
"MOE"
] |
9db2f2b4c959a5c8f9e97a27ec3567b89bca82ca1751b35f2b96bc3ec9950a4b
|
# Copyright (c) 2014-present PlatformIO <contact@platformio.org>
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
import os
from os.path import dirname, isdir, isfile, join, realpath
from sys import exit as sys_exit
from sys import path
path.append("..")
import click
from platformio import fs, util
from platformio.managers.platform import PlatformFactory, PlatformManager
try:
from urlparse import ParseResult, urlparse, urlunparse
except ImportError:
from urllib.parse import ParseResult, urlparse, urlunparse
RST_COPYRIGHT = """.. Copyright (c) 2014-present PlatformIO <contact@platformio.org>
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
"""
API_PACKAGES = util.get_api_result("/packages")
API_FRAMEWORKS = util.get_api_result("/frameworks")
BOARDS = PlatformManager().get_installed_boards()
PLATFORM_MANIFESTS = PlatformManager().get_installed()
DOCS_ROOT_DIR = realpath(join(dirname(realpath(__file__)), "..", "docs"))
def is_compat_platform_and_framework(platform, framework):
p = PlatformFactory.newPlatform(platform)
return framework in (p.frameworks or {}).keys()
def campaign_url(url, source="platformio.org", medium="docs"):
data = urlparse(url)
query = data.query
if query:
query += "&"
query += "utm_source=%s&utm_medium=%s" % (source, medium)
return urlunparse(
ParseResult(data.scheme, data.netloc, data.path, data.params, query,
data.fragment))
def generate_boards_table(boards, skip_columns=None):
columns = [
("Name", ":ref:`board_{platform}_{id}`"),
("Platform", ":ref:`platform_{platform}`"),
("Debug", "{debug}"),
("MCU", "{mcu}"),
("Frequency", "{f_cpu}MHz"),
("Flash", "{rom}"),
("RAM", "{ram}"),
]
lines = []
lines.append("""
.. list-table::
:header-rows: 1
""")
# add header
for (name, template) in columns:
if skip_columns and name in skip_columns:
continue
prefix = " * - " if name == "Name" else " - "
lines.append(prefix + name)
for data in sorted(boards, key=lambda item: item['name']):
has_onboard_debug = (data['debug'] and any(
t.get("onboard") for (_, t) in data['debug']['tools'].items()))
debug = "No"
if has_onboard_debug:
debug = "On-board"
elif data['debug']:
debug = "External"
variables = dict(id=data['id'],
name=data['name'],
platform=data['platform'],
debug=debug,
mcu=data['mcu'].upper(),
f_cpu=int(data['fcpu'] / 1000000.0),
ram=fs.format_filesize(data['ram']),
rom=fs.format_filesize(data['rom']))
for (name, template) in columns:
if skip_columns and name in skip_columns:
continue
prefix = " * - " if name == "Name" else " - "
lines.append(prefix + template.format(**variables))
if lines:
lines.append("")
return lines
def generate_frameworks_contents(frameworks):
if not frameworks:
return []
lines = []
lines.append("""
Frameworks
----------
.. list-table::
:header-rows: 1
* - Name
- Description""")
known = set()
for framework in API_FRAMEWORKS:
known.add(framework['name'])
if framework['name'] not in frameworks:
continue
lines.append("""
* - :ref:`framework_{name}`
- {description}""".format(**framework))
if set(frameworks) - known:
click.secho("Unknown frameworks %s " % (
set(frameworks) - known), fg="red")
return lines
def generate_platforms_contents(platforms):
if not platforms:
return []
lines = []
lines.append("""
Platforms
---------
.. list-table::
:header-rows: 1
* - Name
- Description""")
for name in sorted(platforms):
p = PlatformFactory.newPlatform(name)
lines.append("""
* - :ref:`platform_{name}`
- {description}""".format(name=p.name, description=p.description))
return lines
def generate_debug_contents(boards, skip_board_columns=None, extra_rst=None):
if not skip_board_columns:
skip_board_columns = []
skip_board_columns.append("Debug")
lines = []
onboard_debug = [
b for b in boards if b['debug'] and any(
t.get("onboard") for (_, t) in b['debug']['tools'].items())
]
external_debug = [
b for b in boards if b['debug'] and b not in onboard_debug
]
if not onboard_debug and not external_debug:
return lines
lines.append("""
Debugging
---------
:ref:`piodebug` - "1-click" solution for debugging with a zero configuration.
.. contents::
:local:
""")
if extra_rst:
lines.append(".. include:: %s" % extra_rst)
lines.append("""
Tools & Debug Probes
~~~~~~~~~~~~~~~~~~~~
Supported debugging tools are listed in "Debug" column. For more detailed
information, please scroll table by horizontal.
You can switch between debugging :ref:`debugging_tools` using
:ref:`projectconf_debug_tool` option in :ref:`projectconf`.
.. warning::
You will need to install debug tool drivers depending on your system.
Please click on compatible debug tool below for the further instructions.
""")
if onboard_debug:
lines.append("""
On-Board Debug Tools
^^^^^^^^^^^^^^^^^^^^
Boards listed below have on-board debug probe and **ARE READY** for debugging!
You do not need to use/buy external debug probe.
""")
lines.extend(
generate_boards_table(onboard_debug,
skip_columns=skip_board_columns))
if external_debug:
lines.append("""
External Debug Tools
^^^^^^^^^^^^^^^^^^^^
Boards listed below are compatible with :ref:`piodebug` but **DEPEND ON**
external debug probe. They **ARE NOT READY** for debugging.
Please click on board name for the further details.
""")
lines.extend(
generate_boards_table(external_debug,
skip_columns=skip_board_columns))
return lines
def generate_packages(platform, packagenames, is_embedded):
if not packagenames:
return
lines = []
lines.append("""
Packages
--------
""")
lines.append(""".. list-table::
:header-rows: 1
* - Name
- Description""")
for name in sorted(packagenames):
if name not in API_PACKAGES:
click.secho("Unknown package `%s`" % name, fg="red")
lines.append("""
* - {name}
-
""".format(name=name))
else:
lines.append("""
* - `{name} <{url}>`__
- {description}""".format(name=name,
url=campaign_url(API_PACKAGES[name]['url']),
description=API_PACKAGES[name]['description']))
if is_embedded:
lines.append("""
.. warning::
**Linux Users**:
* Install "udev" rules :ref:`faq_udev_rules`
* Raspberry Pi users, please read this article
`Enable serial port on Raspberry Pi <https://hallard.me/enable-serial-port-on-raspberry-pi/>`__.
""")
if platform == "teensy":
lines.append("""
**Windows Users:**
Teensy programming uses only Windows built-in HID
drivers. When Teensy is programmed to act as a USB Serial device,
Windows XP, Vista, 7 and 8 require `this serial driver
<http://www.pjrc.com/teensy/serial_install.exe>`_
is needed to access the COM port your program uses. No special driver
installation is necessary on Windows 10.
""")
else:
lines.append("""
**Windows Users:**
Please check that you have a correctly installed USB driver from board
manufacturer
""")
return "\n".join(lines)
def generate_platform(name, rst_dir):
print("Processing platform: %s" % name)
compatible_boards = [
board for board in BOARDS if name == board['platform']
]
lines = []
lines.append(RST_COPYRIGHT)
p = PlatformFactory.newPlatform(name)
assert p.repository_url.endswith(".git")
github_url = p.repository_url[:-4]
lines.append(".. _platform_%s:" % p.name)
lines.append("")
lines.append(p.title)
lines.append("=" * len(p.title))
lines.append("")
lines.append(":Configuration:")
lines.append(" :ref:`projectconf_env_platform` = ``%s``" % p.name)
lines.append("")
lines.append(p.description)
lines.append("""
For more detailed information please visit `vendor site <%s>`_.""" %
campaign_url(p.vendor_url))
lines.append("""
.. contents:: Contents
:local:
:depth: 1
""")
#
# Extra
#
if isfile(join(rst_dir, "%s_extra.rst" % name)):
lines.append(".. include:: %s_extra.rst" % p.name)
#
# Examples
#
lines.append("""
Examples
--------
Examples are listed from `%s development platform repository <%s>`_:
""" % (p.title, campaign_url("%s/tree/master/examples" % github_url)))
examples_dir = join(p.get_dir(), "examples")
if isdir(examples_dir):
for eitem in os.listdir(examples_dir):
example_dir = join(examples_dir, eitem)
if not isdir(example_dir) or not os.listdir(example_dir):
continue
url = "%s/tree/master/examples/%s" % (github_url, eitem)
lines.append("* `%s <%s>`_" % (eitem, campaign_url(url)))
#
# Debugging
#
if compatible_boards:
lines.extend(
generate_debug_contents(
compatible_boards,
skip_board_columns=["Platform"],
extra_rst="%s_debug.rst" %
name if isfile(join(rst_dir, "%s_debug.rst" %
name)) else None))
#
# Development version of dev/platform
#
lines.append("""
Stable and upstream versions
----------------------------
You can switch between `stable releases <{github_url}/releases>`__
of {title} development platform and the latest upstream version using
:ref:`projectconf_env_platform` option in :ref:`projectconf` as described below.
Stable
~~~~~~
.. code-block:: ini
; Latest stable version
[env:latest_stable]
platform = {name}
board = ...
; Custom stable version
[env:custom_stable]
platform = {name}@x.y.z
board = ...
Upstream
~~~~~~~~
.. code-block:: ini
[env:upstream_develop]
platform = {github_url}.git
board = ...
""".format(name=p.name, title=p.title, github_url=github_url))
#
# Packages
#
_packages_content = generate_packages(name, p.packages.keys(),
p.is_embedded())
if _packages_content:
lines.append(_packages_content)
#
# Frameworks
#
compatible_frameworks = []
for framework in API_FRAMEWORKS:
if is_compat_platform_and_framework(name, framework['name']):
compatible_frameworks.append(framework['name'])
lines.extend(generate_frameworks_contents(compatible_frameworks))
#
# Boards
#
if compatible_boards:
vendors = {}
for board in compatible_boards:
if board['vendor'] not in vendors:
vendors[board['vendor']] = []
vendors[board['vendor']].append(board)
lines.append("""
Boards
------
.. note::
* You can list pre-configured boards by :ref:`cmd_boards` command or
`PlatformIO Boards Explorer <https://platformio.org/boards>`_
* For more detailed ``board`` information please scroll the tables below by
horizontally.
""")
for vendor, boards in sorted(vendors.items()):
lines.append(str(vendor))
lines.append("~" * len(vendor))
lines.extend(
generate_boards_table(boards, skip_columns=["Platform"]))
return "\n".join(lines)
def update_platform_docs():
for manifest in PLATFORM_MANIFESTS:
name = manifest['name']
platforms_dir = join(DOCS_ROOT_DIR, "platforms")
rst_path = join(platforms_dir, "%s.rst" % name)
with open(rst_path, "w") as f:
f.write(generate_platform(name, platforms_dir))
def generate_framework(type_, data, rst_dir=None):
print("Processing framework: %s" % type_)
compatible_platforms = [
m for m in PLATFORM_MANIFESTS
if is_compat_platform_and_framework(m['name'], type_)
]
compatible_boards = [
board for board in BOARDS if type_ in board['frameworks']
]
lines = []
lines.append(RST_COPYRIGHT)
lines.append(".. _framework_%s:" % type_)
lines.append("")
lines.append(data['title'])
lines.append("=" * len(data['title']))
lines.append("")
lines.append(":Configuration:")
lines.append(" :ref:`projectconf_env_framework` = ``%s``" % type_)
lines.append("")
lines.append(data['description'])
lines.append("""
For more detailed information please visit `vendor site <%s>`_.
""" % campaign_url(data['url']))
lines.append("""
.. contents:: Contents
:local:
:depth: 1""")
# Extra
if isfile(join(rst_dir, "%s_extra.rst" % type_)):
lines.append(".. include:: %s_extra.rst" % type_)
#
# Debugging
#
if compatible_boards:
lines.extend(
generate_debug_contents(
compatible_boards,
extra_rst="%s_debug.rst" %
type_ if isfile(join(rst_dir, "%s_debug.rst" %
type_)) else None))
if compatible_platforms:
# examples
lines.append("""
Examples
--------
""")
for manifest in compatible_platforms:
p = PlatformFactory.newPlatform(manifest['name'])
lines.append("* `%s for %s <%s>`_" %
(data['title'], manifest['title'],
campaign_url("%s/tree/master/examples" %
p.repository_url[:-4])))
# Platforms
lines.extend(
generate_platforms_contents(
[manifest['name'] for manifest in compatible_platforms]))
#
# Boards
#
if compatible_boards:
vendors = {}
for board in compatible_boards:
if board['vendor'] not in vendors:
vendors[board['vendor']] = []
vendors[board['vendor']].append(board)
lines.append("""
Boards
------
.. note::
* You can list pre-configured boards by :ref:`cmd_boards` command or
`PlatformIO Boards Explorer <https://platformio.org/boards>`_
* For more detailed ``board`` information please scroll the tables below by horizontally.
""")
for vendor, boards in sorted(vendors.items()):
lines.append(str(vendor))
lines.append("~" * len(vendor))
lines.extend(generate_boards_table(boards))
return "\n".join(lines)
def update_framework_docs():
for framework in API_FRAMEWORKS:
name = framework['name']
frameworks_dir = join(DOCS_ROOT_DIR, "frameworks")
rst_path = join(frameworks_dir, "%s.rst" % name)
with open(rst_path, "w") as f:
f.write(generate_framework(name, framework, frameworks_dir))
def update_boards():
lines = []
lines.append(RST_COPYRIGHT)
lines.append(".. _boards:")
lines.append("")
lines.append("Boards")
lines.append("======")
lines.append("""
Rapid Embedded Development, Continuous and IDE integration in a few
steps with PlatformIO thanks to built-in project generator for the most
popular embedded boards and IDE.
.. note::
* You can list pre-configured boards by :ref:`cmd_boards` command or
`PlatformIO Boards Explorer <https://platformio.org/boards>`_
* For more detailed ``board`` information please scroll tables below by horizontal.
""")
platforms = {}
for data in BOARDS:
platform = data['platform']
if platform in platforms:
platforms[platform].append(data)
else:
platforms[platform] = [data]
for platform, boards in sorted(platforms.items()):
p = PlatformFactory.newPlatform(platform)
lines.append(p.title)
lines.append("-" * len(p.title))
lines.append("""
.. toctree::
:maxdepth: 1
""")
for board in sorted(boards, key=lambda item: item['name']):
lines.append(" %s/%s" % (platform, board["id"]))
lines.append("")
emboards_rst = join(DOCS_ROOT_DIR, "boards", "index.rst")
with open(emboards_rst, "w") as f:
f.write("\n".join(lines))
# individual board page
for data in BOARDS:
# if data['id'] != "m5stack-core-esp32":
# continue
rst_path = join(DOCS_ROOT_DIR, "boards", data["platform"],
"%s.rst" % data["id"])
if not isdir(dirname(rst_path)):
os.makedirs(dirname(rst_path))
update_embedded_board(rst_path, data)
def update_embedded_board(rst_path, board):
platform = PlatformFactory.newPlatform(board['platform'])
board_config = platform.board_config(board['id'])
board_manifest_url = platform.repository_url
assert board_manifest_url
if board_manifest_url.endswith(".git"):
board_manifest_url = board_manifest_url[:-4]
board_manifest_url += "/blob/master/boards/%s.json" % board['id']
variables = dict(id=board['id'],
name=board['name'],
platform=board['platform'],
platform_description=platform.description,
url=campaign_url(board['url']),
mcu=board_config.get("build", {}).get("mcu", ""),
mcu_upper=board['mcu'].upper(),
f_cpu=board['fcpu'],
f_cpu_mhz=int(int(board['fcpu']) / 1000000),
ram=fs.format_filesize(board['ram']),
rom=fs.format_filesize(board['rom']),
vendor=board['vendor'],
board_manifest_url=board_manifest_url,
upload_protocol=board_config.get("upload.protocol", ""))
lines = [RST_COPYRIGHT]
lines.append(".. _board_{platform}_{id}:".format(**variables))
lines.append("")
lines.append(board['name'])
lines.append("=" * len(board['name']))
lines.append("""
.. contents::
Hardware
--------
Platform :ref:`platform_{platform}`: {platform_description}
.. list-table::
* - **Microcontroller**
- {mcu_upper}
* - **Frequency**
- {f_cpu_mhz:d}MHz
* - **Flash**
- {rom}
* - **RAM**
- {ram}
* - **Vendor**
- `{vendor} <{url}>`__
""".format(**variables))
#
# Configuration
#
lines.append("""
Configuration
-------------
Please use ``{id}`` ID for :ref:`projectconf_env_board` option in :ref:`projectconf`:
.. code-block:: ini
[env:{id}]
platform = {platform}
board = {id}
You can override default {name} settings per build environment using
``board_***`` option, where ``***`` is a JSON object path from
board manifest `{id}.json <{board_manifest_url}>`_. For example,
``board_build.mcu``, ``board_build.f_cpu``, etc.
.. code-block:: ini
[env:{id}]
platform = {platform}
board = {id}
; change microcontroller
board_build.mcu = {mcu}
; change MCU frequency
board_build.f_cpu = {f_cpu}L
""".format(**variables))
#
# Uploading
#
upload_protocols = board_config.get("upload.protocols", [])
if len(upload_protocols) > 1:
lines.append("""
Uploading
---------
%s supports the next uploading protocols:
""" % board['name'])
for protocol in sorted(upload_protocols):
lines.append("* ``%s``" % protocol)
lines.append("""
Default protocol is ``%s``""" % variables['upload_protocol'])
lines.append("""
You can change upload protocol using :ref:`projectconf_upload_protocol` option:
.. code-block:: ini
[env:{id}]
platform = {platform}
board = {id}
upload_protocol = {upload_protocol}
""".format(**variables))
#
# Debugging
#
lines.append("Debugging")
lines.append("---------")
if not board['debug']:
lines.append(
":ref:`piodebug` currently does not support {name} board.".format(
**variables))
else:
default_debug_tool = board_config.get_debug_tool_name()
has_onboard_debug = any(
t.get("onboard") for (_, t) in board['debug']['tools'].items())
lines.append("""
:ref:`piodebug` - "1-click" solution for debugging with a zero configuration.
.. warning::
You will need to install debug tool drivers depending on your system.
Please click on compatible debug tool below for the further
instructions and configuration information.
You can switch between debugging :ref:`debugging_tools` using
:ref:`projectconf_debug_tool` option in :ref:`projectconf`.
""")
if has_onboard_debug:
lines.append(
"{name} has on-board debug probe and **IS READY** for "
"debugging. You don't need to use/buy external debug probe.".
format(**variables))
else:
lines.append(
"{name} does not have on-board debug probe and **IS NOT "
"READY** for debugging. You will need to use/buy one of "
"external probe listed below.".format(**variables))
lines.append("""
.. list-table::
:header-rows: 1
* - Compatible Tools
- On-board
- Default""")
for (tool_name, tool_data) in sorted(board['debug']['tools'].items()):
lines.append(""" * - :ref:`debugging_tool_{name}`
- {onboard}
- {default}""".format(
name=tool_name,
onboard="Yes" if tool_data.get("onboard") else "",
default="Yes" if tool_name == default_debug_tool else ""))
if board['frameworks']:
lines.extend(generate_frameworks_contents(board['frameworks']))
with open(rst_path, "w") as f:
f.write("\n".join(lines))
def update_debugging():
tool_to_platforms = {}
tool_to_boards = {}
vendors = {}
platforms = []
frameworks = []
for data in BOARDS:
if not data['debug']:
continue
for tool in data['debug']['tools']:
tool = str(tool)
if tool not in tool_to_platforms:
tool_to_platforms[tool] = []
tool_to_platforms[tool].append(data['platform'])
if tool not in tool_to_boards:
tool_to_boards[tool] = []
tool_to_boards[tool].append(data['id'])
platforms.append(data['platform'])
frameworks.extend(data['frameworks'])
vendor = data['vendor']
if vendor in vendors:
vendors[vendor].append(data)
else:
vendors[vendor] = [data]
platforms = sorted(set(platforms))
frameworks = sorted(set(frameworks))
lines = [".. _debugging_platforms:"]
lines.extend(generate_platforms_contents(platforms))
lines.extend(generate_frameworks_contents(frameworks))
# Boards
lines.append("""
Boards
------
.. note::
For more detailed ``board`` information please scroll tables below by horizontal.
""")
for vendor, boards in sorted(vendors.items()):
lines.append(str(vendor))
lines.append("~" * len(vendor))
lines.extend(generate_boards_table(boards))
# save
with open(join(fs.get_source_dir(), "..", "docs", "plus", "debugging.rst"),
"r+") as fp:
content = fp.read()
fp.seek(0)
fp.truncate()
fp.write(content[:content.index(".. _debugging_platforms:")] +
"\n".join(lines))
# Debug tools
for tool, platforms in tool_to_platforms.items():
tool_path = join(DOCS_ROOT_DIR, "plus", "debug-tools", "%s.rst" % tool)
if not isfile(tool_path):
click.secho("Unknown debug tool `%s`" % tool, fg="red")
continue
platforms = sorted(set(platforms))
lines = [".. begin_platforms"]
lines.extend(generate_platforms_contents(platforms))
tool_frameworks = []
for platform in platforms:
for framework in frameworks:
if is_compat_platform_and_framework(platform, framework):
tool_frameworks.append(framework)
lines.extend(generate_frameworks_contents(tool_frameworks))
lines.append("""
Boards
------
.. note::
For more detailed ``board`` information please scroll tables below by horizontal.
""")
lines.extend(
generate_boards_table(
[b for b in BOARDS if b['id'] in tool_to_boards[tool]],
skip_columns=None))
with open(tool_path, "r+") as fp:
content = fp.read()
fp.seek(0)
fp.truncate()
fp.write(content[:content.index(".. begin_platforms")] +
"\n".join(lines))
def update_project_examples():
platform_readme_tpl = """
# {title}: development platform for [PlatformIO](https://platformio.org)
{description}
* [Home](https://platformio.org/platforms/{name}) (home page in PlatformIO Registry)
* [Documentation](https://docs.platformio.org/page/platforms/{name}.html) (advanced usage, packages, boards, frameworks, etc.)
# Examples
{examples}
"""
framework_readme_tpl = """
# {title}: framework for [PlatformIO](https://platformio.org)
{description}
* [Home](https://platformio.org/frameworks/{name}) (home page in PlatformIO Registry)
* [Documentation](https://docs.platformio.org/page/frameworks/{name}.html)
# Examples
{examples}
"""
project_examples_dir = join(fs.get_source_dir(), "..", "examples")
framework_examples_md_lines = {}
embedded = []
desktop = []
for manifest in PLATFORM_MANIFESTS:
p = PlatformFactory.newPlatform(manifest['name'])
github_url = p.repository_url[:-4]
# Platform README
platform_examples_dir = join(p.get_dir(), "examples")
examples_md_lines = []
if isdir(platform_examples_dir):
for item in sorted(os.listdir(platform_examples_dir)):
example_dir = join(platform_examples_dir, item)
if not isdir(example_dir) or not os.listdir(example_dir):
continue
url = "%s/tree/master/examples/%s" % (github_url, item)
examples_md_lines.append("* [%s](%s)" % (item, url))
readme_dir = join(project_examples_dir, "platforms", p.name)
if not isdir(readme_dir):
os.makedirs(readme_dir)
with open(join(readme_dir, "README.md"), "w") as fp:
fp.write(
platform_readme_tpl.format(
name=p.name,
title=p.title,
description=p.description,
examples="\n".join(examples_md_lines)))
# Framework README
for framework in API_FRAMEWORKS:
if not is_compat_platform_and_framework(p.name, framework['name']):
continue
if framework['name'] not in framework_examples_md_lines:
framework_examples_md_lines[framework['name']] = []
lines = []
lines.append("- [%s](%s)" % (p.title, github_url))
lines.extend(" %s" % l for l in examples_md_lines)
lines.append("")
framework_examples_md_lines[framework['name']].extend(lines)
# Root README
line = "* [%s](%s)" % (p.title, "%s/tree/master/examples" % github_url)
if p.is_embedded():
embedded.append(line)
else:
desktop.append(line)
# Frameworks
frameworks = []
for framework in API_FRAMEWORKS:
readme_dir = join(project_examples_dir, "frameworks",
framework['name'])
if not isdir(readme_dir):
os.makedirs(readme_dir)
with open(join(readme_dir, "README.md"), "w") as fp:
fp.write(
framework_readme_tpl.format(
name=framework['name'],
title=framework['title'],
description=framework['description'],
examples="\n".join(
framework_examples_md_lines[framework['name']])))
url = campaign_url(
"https://docs.platformio.org/en/latest/frameworks/%s.html#examples"
% framework['name'],
source="github",
medium="examples")
frameworks.append("* [%s](%s)" % (framework['title'], url))
with open(join(project_examples_dir, "README.md"), "w") as fp:
fp.write("""# PlatformIO Project Examples
- [Development platforms](#development-platforms):
- [Embedded](#embedded)
- [Desktop](#desktop)
- [Frameworks](#frameworks)
## Development platforms
### Embedded
%s
### Desktop
%s
## Frameworks
%s
""" % ("\n".join(embedded), "\n".join(desktop), "\n".join(frameworks)))
def main():
update_platform_docs()
update_framework_docs()
update_boards()
update_debugging()
update_project_examples()
if __name__ == "__main__":
sys_exit(main())
|
platformio/platformio
|
scripts/docspregen.py
|
Python
|
apache-2.0
| 30,402
|
[
"VisIt"
] |
5c6db0aa38a722afddc56faaa970ba354b1849f635b983cc94a16463a674a16d
|
import sys
import DataProvidersAndConsumers
import Utilities
from Quartz import *
import Quartz
from LaunchServices import * # kUTType* constants
def drawJPEGImage(context, url):
# Create a Quartz data provider for the supplied URL.
jpgProvider = CGDataProviderCreateWithURL(url)
if jpgProvider is None:
print >>sys.stderr, "Couldn't create JPEG Data provider!"
return
# Create the CGImageRef for the JPEG image from the data provider.
jpgImage = CGImageCreateWithJPEGDataProvider(jpgProvider, None,
True, kCGRenderingIntentDefault)
# CGImageCreateWithJPEGDataProvider retains the data provider.
# Since this code created the data provider and this code no
# longer needs it, it must release it.
del jpgProvider
if jpgImage is None:
print >>sys.stderr, "Couldn't create CGImageRef for JPEG data!"
return
# Make a rectangle that has its origin at (0,0) and
# has a width and height that is 1/4 the native width
# and height of the image.
jpgRect = CGRectMake(0.0, 0.0,
CGImageGetWidth(jpgImage)/4, CGImageGetHeight(jpgImage)/4)
# Draw the image into the rectangle.
# This is Image 1.
CGContextDrawImage(context, jpgRect, jpgImage)
CGContextSaveGState(context)
# Translate to the top-right corner of the image just drawn.
CGContextTranslateCTM(context, jpgRect.size.width,
jpgRect.size.height)
# Rotate by -90 degrees.
CGContextRotateCTM(context, Utilities.DEGREES_TO_RADIANS(-90))
# Translate in -x by the width of the drawing.
CGContextTranslateCTM(context, -jpgRect.size.width, 0)
# Draw the image into the same rectangle as before.
# This is Image 2.
CGContextDrawImage(context, jpgRect, jpgImage)
CGContextRestoreGState(context)
CGContextSaveGState(context)
# Translate so that the next drawing of the image appears
# below and to the right of the image just drawn.
CGContextTranslateCTM(context,
jpgRect.size.width+jpgRect.size.height, jpgRect.size.height)
# Scale the y axis by a negative value and flip the image.
CGContextScaleCTM(context, 0.75, -1.0)
# This is Image 3.
CGContextDrawImage(context, jpgRect, jpgImage)
CGContextRestoreGState(context)
# Adjust the position of the rectangle so that its origin is
# to the right and above where Image 3 was drawn. Adjust the
# size of the rectangle so that it is 1/4 the image width
# and 1/6 the image height.
jpgRect = CGRectMake( 1.75*jpgRect.size.width + jpgRect.size.height,
jpgRect.size.height,
CGImageGetWidth(jpgImage)/4,
CGImageGetHeight(jpgImage)/6)
# This is Image 4.
CGContextDrawImage(context, jpgRect, jpgImage)
def drawImageFromURL(context, url, width, height, bitsPerComponent, isRGB):
# This routine treats color images as RGB
if isRGB:
bitsPerPixel = bitsPerComponent * 3
else:
bitsPerPixel = bitsPerComponent
bytesPerRow = (width * bitsPerPixel + 7)/8
shouldInterpolate = True
# Create a Quartz data provider from the supplied URL.
dataProvider = CGDataProviderCreateWithURL(url)
if dataProvider is None:
print >>sys.stderr, "Couldn't create Image data provider!"
return
# Get a Quartz color space object appropriate for the image type.
if isRGB:
colorspace = Utilities.getTheCalibratedRGBColorSpace()
else:
colorspace = Utilities.getTheCalibratedGrayColorSpace()
# Create an image of the width, height, and bitsPerComponent with
# no alpha data, the default decode array, with interpolation,
# and the default rendering intent for images. This code is
# intended for Gray images of the format GGGGG... or RGB images
# of the format RGBRGBRGB... .
image = CGImageCreate(width, height, bitsPerComponent,
bitsPerPixel, bytesPerRow, colorspace,
kCGImageAlphaNone, dataProvider, None,
shouldInterpolate, kCGRenderingIntentDefault)
# Quartz retains the data provider with the image and since this
# code does not create any more images with the data provider, it
# can release it.
del dataProvider
if image is None:
print >>sys.stderr, "Couldn't create CGImageRef for this data!"
return
# Create a rectangle into which the code will draw the image.
imageRect = CGRectMake(0.0, 0.0, width, height)
# Draw the image into the rectangle.
CGContextDrawImage(context, imageRect, image)
def doColorRampImage(context):
width = 256
height = 256
bitsPerComponent = 8
bitsPerPixel = 24
bytesPerRow = width * 3
shouldInterpolate = True
imageDataProvider = DataProvidersAndConsumers.createRGBRampDataProvider()
if imageDataProvider is None:
print >>sys.stderr, "Couldn't create Image Data provider!"
return
colorspace = Utilities.getTheCalibratedRGBColorSpace()
image = CGImageCreate(width, height, bitsPerComponent,
bitsPerPixel, bytesPerRow, colorspace, kCGImageAlphaNone,
imageDataProvider, None, shouldInterpolate,
kCGRenderingIntentDefault)
# No longer need the data provider.
del imageDataProvider
if image is None:
print >>sys.stderr, "Couldn't create CGImageRef for this data!"
return
imageRect = CGRectMake(0.0, 0.0, width, height)
# Draw the image.
CGContextDrawImage(context, imageRect, image)
def doImageWithCallbacksCreatedFromURL(context, url, width, height,
bitsPerComponent, isRGB):
if isRGB:
bitsPerPixel = bitsPerComponent * 3
else:
bitsPerPixel = bitsPerComponent
bytesPerRow = ((width * bitsPerPixel) + 7)/8
shouldInterpolate = True
dataProvider = DataProvidersAndConsumers.createSequentialAccessDPForURL(url)
if dataProvider is None:
print >>sys.stderr, "Couldn't create Image Data provider!"
return
# Create a Quartz color space object appropriate for the image type.
# These user written functions create the color space object
# and that reference must be released by this code.
if isRGB:
colorspace = Utilities.getTheCalibratedRGBColorSpace()
else:
colorspace = Utilities.getTheCalibratedGrayColorSpace()
image = CGImageCreate(width, height, bitsPerComponent,
bitsPerPixel, bytesPerRow, colorspace,
kCGImageAlphaNone, dataProvider, None, shouldInterpolate,
kCGRenderingIntentDefault)
del dataProvider
if image is None:
print >>sys.stder, "Couldn't create CGImageRef for this data!"
return
imageRect = CGRectMake(0.0, 0.0, width, height)
# Draw the image into the rectangle.
CGContextDrawImage(context, imageRect, image)
def doGrayRamp(context):
width = 256
height = 1
bitsPerComponent = 8
bitsPerPixel = 8
bytesPerRow = width
shouldInterpolate = True
dataProvider = DataProvidersAndConsumers.createGrayRampDirectAccessDP()
if dataProvider is None:
print >>sys.stderr, "Couldn't create Gray Ramp provider!"
return
colorspace = Utilities.getTheCalibratedGrayColorSpace()
image = CGImageCreate(width, height, bitsPerComponent, bitsPerPixel,
bytesPerRow, colorspace, kCGImageAlphaNone, dataProvider,
None, shouldInterpolate, kCGRenderingIntentDefault)
del dataProvider
if image is None:
print >>sys.stderr, "Couldn't create CGImageRef for image data!"
return
imageRect = CGRectMake(0.0, 0.0, 256, 256)
# Drawing the image that is 256 samples wide and
# 1 scanline high into a rectangle that is 256 x 256 units
# on a side causes Quartz to stretch the image to fill
# the destination rectangle.
CGContextDrawImage(context, imageRect, image)
# This routine examines the CGImageSource at index 0 to
# determine if the first image is a floating point image and
# if it is, it returns an options dictionary suitable for
# passing to CGImageSourceCreateImageAtIndex in order to create
# a CGImageRef that contains full dynamic range floating point data.
def createFloatingPointImageOptions(imageSource):
# Allow the image to be a floating point image.
# Without this, Quartz would return integer pixel data, even for
# floating point images. Typically you don't need floating point data
# but in some special cases you might want it.
options = {
kCGImageSourceShouldAllowFloat: True
}
isFloat = False
# Obtain the properties for the first image
# in the image source. This is a 'Copy' function
# so the code owns a reference to the
# dictionary returned.
properties = CGImageSourceCopyPropertiesAtIndex(imageSource,
0, options)
if properties is not None:
# Get the value for the kCGImagePropertyIsFloat if it exists
# and if the value is a CFBoolean then get the corresponding
# Boolean result.
if kCGImagePropertyIsFloat in properties:
isFloat = bool(properties[kCGImagePropertyIsFloat])
if not isFloat:
return None
return options
def myCreateImageUsingImageSource(url):
# Set to zero, indicating the property was unavailable.
xdpi = ydpi = 0
# Create the image source from the URL.
imageSource = CGImageSourceCreateWithURL(url, None)
if imageSource is None:
print >>sys.stderr, "Couldn't create image source from URL!"
return (None, xdpi, ydpi)
if False:
options = createFloatingPointImageOptions(imageSource)
if options is not None:
print >>sys.stderr, "image IS a floating point image"
else:
print >>sys.stderr, "image IS NOT a floating point image"
else:
options = None
# Obtain the properties dictionary for the first image
# in the image source. This is a copy function so this
# code owns the reference returned and must
# must release it.
properties = CGImageSourceCopyPropertiesAtIndex(
imageSource, 0, options)
if properties is not None:
# Check for the x and y resolution of the image.
xdpi = properties[kCGImagePropertyDPIWidth]
ydpi = properties[kCGImagePropertyDPIHeight]
# Create a CGImageRef from the first image in the CGImageSource.
image = CGImageSourceCreateImageAtIndex(imageSource, 0, options)
# Release the CGImageSource object since it is no longer needed
# and this code created it. This code uses CFRelease since a
# CGImageSource object is a CoreFoundation object.
del imageSource
del options
if image is None:
print >>sys.stderr, "Couldn't create image from image source!"
return None
return (image, xdpi, ydpi)
def myCreateThumbnailFromImageSource(url):
maxThumbSize = 160
# Create the image source from the URL.
imageSource = CGImageSourceCreateWithURL(url, None)
if imageSource is None:
print >>sys.stderr, "Couldn't create image source from URL!"
return None
options = {
# Specify 160 pixels as the maximum width and height of
# the thumbnail for Quartz to create.
kCGImageSourceThumbnailMaxPixelSize: maxThumbSize,
# Request that Quartz create a thumbnail image if
# thumbnail data isn't present in the file.
kCGImageSourceCreateThumbnailFromImageIfAbsent: True,
}
# Create the thumbnail image for the first image in the
# image source, that at index 0, using the options
# dictionary that the code just created.
thumb = CGImageSourceCreateThumbnailAtIndex(imageSource, 0, options)
# Release the options dictionary.
del options
# Release the image source the code created.
del imageSource
if thumb is None:
print >>sys.stderr, "Couldn't create thumbnail from image source!"
return None
return thumb
def imageHasFloatingPointSamples(image):
if hasattr(Quartz, CGImageGetBitmapInfo):
return (kCGBitmapFloatComponents & CGImageGetBitmapInfo(image)) != 0
return False
def drawImageWithCGImageDataSource(context, url):
# This code would be better if it created the image source
# once and used the same image source to create the image and its
# thumbnail, but the point here is to simply test the routines
# myCreateImageUsingImageSource and myCreateThumbnailFromImageSource.
image, xdpi, ydpi = myCreateImageUsingImageSource(url)
if image is None:
print >>sys.stderr, "myCreateImageFromImageSource didn't create a CGImage!"
return
print "xdpi = %2.f, ydpi = %2.f"%(xdpi, ydpi)
imageRect = CGRectMake(0.0, 0.0,
CGImageGetWidth(image)/3, CGImageGetHeight(image)/3)
CGContextDrawImage(context, imageRect, image)
if 0:
isFloatingImage = imageHasFloatingPointSamples(image)
if isFloatingImage:
print "First image IS a floating point image"
else:
print "First image IS NOT a floating point image"
del image
image = myCreateThumbnailFromImageSource(url)
if image is None:
print >>sys.stderr, "myCreateThumbnailFromImageSource didn't create a CGImage!"
return
imageRect = CGRectMake(400.0, 0.0,
CGImageGetWidth(image), CGImageGetHeight(image))
CGContextDrawImage(context, imageRect, image)
del image
class MyIncrementalData (object):
data = None
dataSize = 0
repCount = 0
chunkSize = 0
# This is a dummy data accumulation routine used to demonstrate incremental
# loading of an image.
def myCreateAccumulatedDataSoFar(myDataP):
myDataP.repCount += 1
sizeToReturn = myDataP.chunkSize*myDataP.repCount
if sizeToReturn > myDataP.dataSize:
sizeToReturn = myDataP.dataSize
done = (sizeToReturn == myDataP.dataSize)
data = CFDataCreate(None, myDataP.data, sizeToReturn)
return data, done
def MyDrawIncrementalImage(context, image, fullHeight):
# Obtain the width and height of the image that has been
# accumulated so far.
width = CGImageGetWidth(image)
height = CGImageGetHeight(image)
# Adjust the location of the imageRect so that the origin is
# such that the full image would be located at 0,0 and the partial
# image top-left corner does not move as the image is filled in.
# This is only needed for views where the y axis points up the
# drawing canvas.
imageRect = CGRectMake(0, fullHeight-height, width, height)
CGContextDrawImage(context, imageRect, image)
def myDrawFirstImageIncrementally(context, myDataP):
height = -1
# Create an incremental image source.
imageSource = CGImageSourceCreateIncremental(None)
if imageSource is None:
print >>sys.stderr, "Couldn't create incremental imagesource!"
return
# Loop, gathering the necessary data to find the True
# height of the image.
while 1:
# Fetch the data. The CFData object returned by
# myCreateAccumulatedDataSoFar is used to update the
# image source. When the data is complete, the code
# passes True in the 'done' parameter passed to
# CGImageSourceUpdateData. Once the data is passed
# to CGImageSourceUpdateData, the code can release
# its reference to the data.
# Accumulate the data.
data, done = myCreateAccumulatedDataSoFar(myDataP)
CGImageSourceUpdateData(imageSource, data, done)
# Release the data since Quartz retains it and this code
# no longer needs it.
del data
if height < 0:
# Determine the height of the full image. This is needed in order
# to adjust the location of the drawing of the partial image in
# a context where the y axis has the default Quartz orientation
# pointing up the drawing canvas.
properties = CGImageSourceCopyPropertiesAtIndex(
imageSource, 0, None)
if properties is not None:
if kCGImagePropertyPixelHeight in properties:
height = properties[kCGImagePropertyPixelHeight]
del properties
# Once the height is obtained, go ahead and see if Quartz
# has enough data to create a CGImage object.
if height > 0:
# Now create the CGImageRef from the image source for the
# first image.
image = CGImageSourceCreateImageAtIndex(
imageSource, 0, None)
if image is not None:
# Draw the image using the height of the full image
# to adjust the location where the image is drawn.
MyDrawIncrementalImage(context, image, height)
# Release the partial image once you've drawn it.
del image
# Potentially you would want to flush the context so
# that drawing to a window would appear, even inside
# this loop. Of course this flush should really be
# done on a timer so that the flush only occurs at
# most every 60th of a second. See Chapter 17 regarding
# timing your usage of CGContextFlush.
CGContextFlush(context)
# Obtain the status for the image source for the first image.
status = CGImageSourceGetStatusAtIndex(imageSource, 0)
if done or status == kCGImageStatusComplete:
break
def createMyIncrementalDataFromURL(url, myDataP):
myDataP.data = None
myDataP.dataSize = 0
myDataP.repCount = 0
success, pathString = CFURLGetFileSystemRepresentation(url, True, None, 1024)
pathString = pathString.rstrip('\0')
if success and len(pathString):
fp = open(pathString, 'rb')
myDataP.data = fp.read()
fp.close()
myDataP.dataSize = len(myDataP.data)
if myDataP.dataSize > 0:
myDataP.chunkSize = myDataP.dataSize/10 # 10 chunks
def doIncrementalImageWithURL(context, url):
myData = MyIncrementalData()
createMyIncrementalDataFromURL(url, myData)
if myData.data is None:
print >>sys.stderr, "couldn't read data from URL!"
myDrawFirstImageIncrementally(context, myData)
del myData
# This code requires QuickTime.framework.
# from Carbon import Qt
def createCGImageWithQuickTimeFromURL(url):
"""
Note: this function doesn't actually worked because the APIs used in here
aren't properly wrapped (yet).
"""
return None
imageRef = None
err = noErr
result, dataRef, dataRefType = QTNewDataReferenceFromCFURL(url, 0, None, None)
if dataRef is not None:
err, gi = GetGraphicsImporterForDataRefWithFlags(dataRef,
dataRefType, None, 0)
if not err and gi:
# Tell the graphics importer that it shouldn't perform
# gamma correction and it should create an image in
# the original source color space rather than matching it to
# a generic calibrated color space.
result = GraphicsImportSetFlags(gi,
(kGraphicsImporterDontDoGammaCorrection +
kGraphicsImporterDontUseColorMatching)
)
if result == 0:
result, imageRef = GraphicsImportCreateCGImage(gi,None,0)
if result != 0:
print >>sys.stderr, "got a bad result = %d!"%(result,)
DisposeHandle(dataRef)
CloseComponent(gi)
return imageRef
def drawQTImageWithQuartz(context, url):
image = createCGImageWithQuickTimeFromURL(url)
if image is None:
print >>sys.stderr, "createCGImageWithQuickTimeFromURL didn't create a CGImage!"
return
imageRect = CGRectMake(0.0, 0.0,
CGImageGetWidth(image), CGImageGetHeight(image))
CGContextDrawImage(context, imageRect, image)
def drawJPEGDocumentWithMultipleProfiles(context, url):
isDeviceRGBImage = False
# Create a Quartz data provider for the supplied URL.
jpgProvider = CGDataProviderCreateWithURL(url)
if jpgProvider is None:
print >>sys.stderr, "Couldn't create JPEG Data provider!"
return
# Create the CGImageRef for the JPEG image from the data provider.
jpgImage = CGImageCreateWithJPEGDataProvider(
jpgProvider, None, True, kCGRenderingIntentDefault)
del jpgProvider
if jpgImage is None:
print >>sys.stderr, "Couldn't create CGImageRef for JPEG data!"
return
# Get the color space characterizing the image. This is a
# function with 'Get' semantics so the code doesn't own a reference
# to the color space returned and must not release it.
originalColorSpace = CGImageGetColorSpace(jpgImage)
if originalColorSpace is None:
print >>sys.stderr, "image is a masking image, not an image with color!"
return
if CGColorSpaceGetNumberOfComponents(originalColorSpace) != 3:
print >>sys.stderr, "This example only works with 3 component JPEG images"
return
# Determine if the original color space is DeviceRGB. If that is
# not the case then bail.
comparisonColorSpace = CGColorSpaceCreateDeviceRGB()
# Note that this comparison of color spaces works only on
# Jaguar and later where a CGColorSpaceRef is a
# CoreFoundation object. Otherwise this will crash!
isDeviceRGBImage = (comparisonColorSpace == originalColorSpace)
# This code created 'comparisonColorSpace' so it must release it.
del comparisonColorSpace
if not isDeviceRGBImage:
print >>sys.stderr, "The color space for the JPEG image is not DeviceRGB!"
return
# Might need to adjust this based on the size of the original image.
CGContextScaleCTM(context, 0.5, 0.5)
imageRect = CGRectMake(0.0, CGImageGetHeight(jpgImage)/2,
CGImageGetWidth(jpgImage), CGImageGetHeight(jpgImage))
# Draw the original image to the left of the other two.
CGContextDrawImage(context, imageRect, jpgImage)
# Recharacterize the original image with the generic Calibrated RGB
# color space.
updatedImage1 = CGImageCreateCopyWithColorSpace(jpgImage,
Utilities.getTheCalibratedRGBColorSpace())
# Release the original image since this code is done with it.
del jpgImage
if updatedImage1 is None:
print >>sys.stderr, "There is no updated image to draw!"
return
# Draw the image characterized by the Generic profile
# to the right of the other image.
imageRect = CGRectOffset(imageRect, CGRectGetWidth(imageRect) + 10, 0)
CGContextDrawImage(context, imageRect, updatedImage1)
# Recharacterize the image but now with a color space
# created with the sRGB profile.
updatedImage2 = CGImageCreateCopyWithColorSpace(updatedImage1,
Utilities.getTheSRGBColorSpace())
# Release updatedImage1 since this code is done with it.
del updatedImage1
if updatedImage2 is None:
print >>sys.stderr, "There is no second updated image to draw!"
return
# Draw the image characterized by the sRGB profile to the right of
# the image characterized by the generic RGB profile.
imageRect = CGRectOffset(imageRect, CGRectGetWidth(imageRect) + 10, 0)
CGContextDrawImage(context, imageRect, updatedImage2)
def createRedGreenRampImageData(width, height, size):
try:
dataP = objc.allocateBuffer(size)
except MemoryError:
return None
idx = 0
# Build an image that is RGB 24 bits per sample. This is a ramp
# where the red component value increases in red from left to
# right and the green component increases from top to bottom.
for g in xrange(height):
for r in xrange(width):
dataP[idx+0] = r
dataP[idx+1] = g
dataP[idx+2] = 0
idx+=3
return dataP
def createRGBRampSubDataProvider(subRect):
bytesPerSample = 3
width = 256
height = 256
bytesPerRow = width*bytesPerSample
startOffsetX = subRect.origin.x
startOffsetY = subRect.origin.y
imageDataSize = bytesPerRow*height
# The first image sample is at
# (startOffsetY*bytesPerRow + startOffsetX*bytesPerSample)
# bytes into the RGB ramp data.
firstByteOffset = startOffsetY*bytesPerRow + startOffsetX*bytesPerSample
# The actual size of the image data provided is the full image size
# minus the amount skipped at the beginning. This is more than the
# total amount of data that is needed for the subimage but it is
# valid and easy to calculate.
totalBytesProvided = imageDataSize - firstByteOffset
# Create the full color ramp.
dataP = createRedGreenRampImageData(width, height, imageDataSize)
if dataP is None:
print >>sys.stderr, "Couldn't create image data!"
return None
# Use the pointer to the first byte as the info parameter since
# that is the pointer to the block to free when done.
dataProvider = CGDataProviderCreateWithData(dataP,
buffer(dataP, firstByteOffset),
totalBytesProvided, None)
if dataProvider is None:
return None
return dataProvider
def doColorRampSubImage(context):
# Start 4 scanlines from the top and 16 pixels from the left edge,
# skip the last 40 scanlines of the image and the right
# most 64 pixels.
insetLeft = 16
insetTop = 4
insetRight = 64
insetBottom = 40
fullImageWidth = 256
fullImageHeight = 256
subImageWidth = fullImageWidth-insetLeft-insetRight
subImageHeight = fullImageHeight-insetTop-insetBottom
bitsPerComponent = 8
bitsPerPixel = 24
bytesPerRow = fullImageWidth * 3
shouldInterpolate = True
imageSubRect = CGRectMake(
insetLeft, insetTop, subImageWidth, subImageHeight)
colorspace = Utilities.getTheCalibratedRGBColorSpace()
if hasattr(Quartz, 'CGImageCreateWithImageInRect'):
imageDataProvider = DataProvidersAndConsumers.createRGBRampDataProvider()
if imageDataProvider is None:
print >>sys.stderr, "Couldn't create Image Data provider!"
return
fullImage = CGImageCreate(fullImageWidth, fullImageHeight,
bitsPerComponent, bitsPerPixel,
bytesPerRow, colorspace, kCGImageAlphaNone,
imageDataProvider, None, shouldInterpolate,
kCGRenderingIntentDefault)
if fullImage is not None:
image = CGImageCreateWithImageInRect(fullImage, imageSubRect)
# release the full image since it is no longer required.
del fullImage
# If the image hasn't been created yet, this code uses the
# customized data provider to do so.
if image is None:
imageDataProvider = createRGBRampSubDataProvider(imageSubRect)
if imageDataProvider is None:
print >>sys.stderr, "Couldn't create Image Data provider!"
return
# By supplying bytesPerRow, the extra data at the end of
# each scanline and the beginning of the next is properly skipped.
image = CGImageCreate(subImageWidth, subImageHeight,
bitsPerComponent, bitsPerPixel,
bytesPerRow, colorspace, kCGImageAlphaNone,
imageDataProvider, None, shouldInterpolate,
kCGRenderingIntentDefault)
# This code no longer needs the data provider.
del imageDataProvider
if image is None:
print >>sys.stderr, "Couldn't create CGImageRef for this data!"
return
# Draw the subimage.
rect = CGRectMake(0, 0, subImageWidth, subImageHeight)
CGContextDrawImage(context, rect, image)
def exportCGImageToPNGFileWithDestination(image, url):
resolution = 144.
# Create an image destination at the supplied URL that
# corresponds to the PNG image format.
imageDestination = CGImageDestinationCreateWithURL(url, kUTTypePNG, 1, None)
if imageDestination is None:
print >>sys.stderr, "couldn't create image destination!"
return
# Set the keys to be the x and y resolution of the image.
options = {
kCGImagePropertyDPIWidth: resolution,
kCGImagePropertyDPIHeight: resolution,
}
# Add the image with the options dictionary to the destination.
CGImageDestinationAddImage(imageDestination, image, options)
# Release the options dictionary this code created.
del options
# When all the images are added to the destination, finalize it.
CGImageDestinationFinalize(imageDestination)
# Release the destination when done with it.
del imageDestination
# This code requires QuickTime.framework
# include <QuickTime/QuickTime.h>
def exportCGImageToJPEGFile(imageRef, url):
# This doesn't actually work due to lame Python Quicktime bindings...
return
result, dataRef, dataRefType = QTNewDataReferenceFromCFURL(
url, 0, None, None)
if result == 0:
result, graphicsExporter = OpenADefaultComponent(GraphicsExporterComponentType,
kQTFileTypeJPEG)
if result == 0:
result = GraphicsExportSetInputCGImage(graphicsExporter,
imageRef)
if result == 0:
result = GraphicsExportSetOutputDataReference(
graphicsExporter, dataRef, dataRefType)
if result == 0:
result, sizeWritten = GraphicsExportDoExport(
graphicsExporter, None)
CloseComponent(graphicsExporter)
if dataRef is not None:
DisposeHandle(dataRef)
if result != 0:
print >>sys.stderr, "Exporting QT image got bad result = %d!"%(result,)
def exportColorRampImageWithQT(context):
width = 256
height = 256
bitsPerComponent = 8
bitsPerPixel = 24
bytesPerRow = width * 3
shouldInterpolate = True
imageDataProvider = DataProvidersAndConsumers.createRGBRampDataProvider()
if imageDataProvider is None:
print >>sys.stderr, "Couldn't create Image Data provider!"
return
colorspace = Utilities.getTheCalibratedRGBColorSpace()
image = CGImageCreate(width, height, bitsPerComponent,
bitsPerPixel, bytesPerRow, colorspace,
kCGImageAlphaNone, imageDataProvider,
None, shouldInterpolate, kCGRenderingIntentDefault)
del imageDataProvider
if image is None:
print >>sys.stderr, "Couldn't create CGImageRef for this data!"
return
rect = CGRectMake(0.0, 0.0, width, height)
CGContextDrawImage(context, rect, image)
# Of course this is a total hack.
outPath = "/tmp/imageout.jpg"
exportURL = CFURLCreateFromFileSystemRepresentation(None,
outPath, len(outPath), False)
if exportURL:
exportCGImageToJPEGFile(image, exportURL)
|
albertz/music-player
|
mac/pyobjc-framework-Quartz/Examples/Programming with Quartz/BasicDrawing/Images.py
|
Python
|
bsd-2-clause
| 31,567
|
[
"Jaguar"
] |
dffb195246e5dbc4ca233b44643121f9642d026c05210c421304c9a7b7e3c82a
|
# (C) British Crown Copyright 2010 - 2013, Met Office
#
# This file is part of Iris.
#
# Iris is free software: you can redistribute it and/or modify it under
# the terms of the GNU Lesser General Public License as published by the
# Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# Iris is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU Lesser General Public License for more details.
#
# You should have received a copy of the GNU Lesser General Public License
# along with Iris. If not, see <http://www.gnu.org/licenses/>.
"""
Provides testing capabilities and customisations specific to Iris.
.. note:: This module needs to control the matplotlib backend, so it
**must** be imported before ``matplotlib.pyplot``.
The primary class for this module is :class:`IrisTest`.
By default, this module sets the matplotlib backend to "agg". But when
this module is imported it checks ``sys.argv`` for the flag "-d". If
found, it is removed from ``sys.argv`` and the matplotlib backend is
switched to "tkagg" to allow the interactive visual inspection of
graphical test results.
"""
import collections
import contextlib
import difflib
import filecmp
import gzip
import logging
import os
import os.path
import re
import shutil
import StringIO
import subprocess
import sys
import unittest
import warnings
import xml.dom.minidom
import zlib
import matplotlib
import matplotlib.testing.compare as mcompare
import matplotlib.pyplot as plt
import numpy as np
import numpy.ma as ma
import iris.cube
import iris.config
import iris.util
#: Basepath for test results.
_RESULT_PATH = os.path.join(os.path.dirname(__file__), 'results')
if '--data-files-used' in sys.argv:
sys.argv.remove('--data-files-used')
fname = '/var/tmp/all_iris_test_resource_paths.txt'
print 'saving list of files used by tests to %s' % fname
_EXPORT_DATAPATHS_FILE = open(fname, 'w')
else:
_EXPORT_DATAPATHS_FILE = None
# A shared logger for use by unit tests
logger = logging.getLogger('tests')
# Whether to display matplotlib output to the screen.
_DISPLAY_FIGURES = False
if '-d' in sys.argv:
sys.argv.remove('-d')
plt.switch_backend('tkagg')
_DISPLAY_FIGURES = True
else:
plt.switch_backend('agg')
_DEFAULT_IMAGE_TOLERANCE = 0.001
def main():
"""A wrapper for unittest.main() which adds iris.test specific options to the help (-h) output."""
if '-h' in sys.argv or '--help' in sys.argv:
stdout = sys.stdout
buff = StringIO.StringIO()
# NB. unittest.main() raises an exception after it's shown the help text
try:
sys.stdout = buff
unittest.main()
finally:
sys.stdout = stdout
lines = buff.getvalue().split('\n')
lines.insert(9, 'Iris-specific options:')
lines.insert(10, ' -d Display matplotlib figures (uses tkagg).')
lines.insert(11, ' NOTE: To compare results of failing tests, ')
lines.insert(12, ' use idiff.py instead')
lines.insert(13, ' --data-files-used Save a list of files used to a temporary file')
print '\n'.join(lines)
else:
unittest.main()
def get_data_path(relative_path):
"""
Return the absolute path to a data file when given the relative path
as a string, or sequence of strings.
"""
if not isinstance(relative_path, basestring):
relative_path = os.path.join(*relative_path)
data_path = os.path.join(iris.config.TEST_DATA_DIR, relative_path)
if _EXPORT_DATAPATHS_FILE is not None:
_EXPORT_DATAPATHS_FILE.write(data_path + '\n')
if isinstance(data_path, basestring) and not os.path.exists(data_path):
# if the file is gzipped, ungzip it and return the path of the ungzipped
# file.
gzipped_fname = data_path + '.gz'
if os.path.exists(gzipped_fname):
with gzip.open(gzipped_fname, 'rb') as gz_fh:
with open(data_path, 'wb') as fh:
fh.writelines(gz_fh)
return data_path
def get_result_path(relative_path):
"""Returns the absolute path to a result file when given the relative path
as a string, or sequence of strings."""
if not isinstance(relative_path, basestring):
relative_path = os.path.join(*relative_path)
return os.path.abspath(os.path.join(_RESULT_PATH, relative_path))
class IrisTest(unittest.TestCase):
"""A subclass of unittest.TestCase which provides Iris specific testing functionality."""
_assertion_counts = collections.defaultdict(int)
@classmethod
def setUpClass(cls):
# Ensure that the CF profile if turned-off for testing.
iris.site_configuration['cf_profile'] = None
def _assert_str_same(self, reference_str, test_str, reference_filename, type_comparison_name='Strings'):
if reference_str != test_str:
diff = ''.join(difflib.unified_diff(reference_str.splitlines(1), test_str.splitlines(1),
'Reference', 'Test result', '', '', 0))
self.fail("%s do not match: %s\n%s" % (type_comparison_name, reference_filename, diff))
def _assert_cml(self, cube_xml, reference_xml, reference_filename):
self._assert_str_same(reference_xml, cube_xml, reference_filename, 'CML')
def assertCMLApproxData(self, cubes, reference_filename, *args, **kwargs):
# passes args and kwargs on to approx equal
if isinstance(cubes, iris.cube.Cube):
cubes = [cubes]
for i, cube in enumerate(cubes):
fname = list(reference_filename)
# don't want the ".cml" for the numpy data file
if fname[-1].endswith(".cml"):
fname[-1] = fname[-1][:-4]
fname[-1] += '.data.%d.npy' % i
self.assertCubeDataAlmostEqual(cube, fname, *args, **kwargs)
self.assertCML(cubes, reference_filename, checksum=False)
def assertCDL(self, netcdf_filename, reference_filename, flags='-h'):
"""
Converts the given CF-netCDF file to CDL for comparison with
the reference CDL file, or creates the reference file if it
doesn't exist.
"""
# Convert the netCDF file to CDL file format.
cdl_filename = iris.util.create_temp_filename(suffix='.cdl')
if flags is None:
flags = []
elif isinstance(flags, basestring):
flags = flags.split()
else:
flags = map(str, flags)
with open(cdl_filename, 'w') as cdl_file:
subprocess.check_call(['ncdump'] + flags + [netcdf_filename],
stderr=cdl_file, stdout=cdl_file)
# Ingest the CDL for comparison, excluding first line.
with open(cdl_filename, 'r') as cdl_file:
lines = cdl_file.readlines()[1:]
# Sort the dimensions (except for the first, which can be unlimited).
# This gives consistent CDL across different platforms.
sort_key = lambda line: ('UNLIMITED' not in line, line)
dimension_lines = slice(lines.index('dimensions:\n') + 1,
lines.index('variables:\n'))
lines[dimension_lines] = sorted(lines[dimension_lines], key=sort_key)
cdl = ''.join(lines)
os.remove(cdl_filename)
reference_path = get_result_path(reference_filename)
self._check_same(cdl, reference_path, reference_filename, type_comparison_name='CDL')
def assertCML(self, cubes, reference_filename, checksum=True):
"""
Checks the given cubes match the reference file, or creates the
reference file if it doesn't exist.
"""
if isinstance(cubes, iris.cube.Cube):
cubes = [cubes]
if isinstance(cubes, (list, tuple)):
xml = iris.cube.CubeList(cubes).xml(checksum=checksum)
else:
xml = cubes.xml(checksum=checksum)
reference_path = get_result_path(reference_filename)
self._check_same(xml, reference_path, reference_filename)
def assertTextFile(self, source_filename, reference_filename, desc="text file"):
"""Check if two text files are the same, printing any diffs."""
with open(source_filename) as source_file:
source_text = source_file.readlines()
with open(reference_filename) as reference_file:
reference_text = reference_file.readlines()
if reference_text != source_text:
diff = ''.join(difflib.unified_diff(reference_text, source_text, 'Reference', 'Test result', '', '', 0))
self.fail("%s does not match reference file: %s\n%s" % (desc, reference_filename, diff))
def assertCubeDataAlmostEqual(self, cube, reference_filename, *args, **kwargs):
reference_path = get_result_path(reference_filename)
if os.path.isfile(reference_path):
kwargs.setdefault('err_msg', 'Reference file %s' % reference_path)
result = np.load(reference_path)
if isinstance(result, np.lib.npyio.NpzFile):
self.assertIsInstance(cube.data, ma.MaskedArray, 'Cube data was not a masked array.')
# Avoid comparing any non-initialised array data.
data = cube.data.filled()
np.testing.assert_array_almost_equal(data, result['data'],
*args, **kwargs)
np.testing.assert_array_equal(cube.data.mask, result['mask'])
else:
np.testing.assert_array_almost_equal(cube.data, result, *args, **kwargs)
else:
self._ensure_folder(reference_path)
logger.warning('Creating result file: %s', reference_path)
if isinstance(cube.data, ma.MaskedArray):
# Avoid recording any non-initialised array data.
data = cube.data.filled()
np.savez(file(reference_path, 'wb'), data=data, mask=cube.data.mask)
else:
np.save(file(reference_path, 'wb'), cube.data)
def assertFilesEqual(self, test_filename, reference_filename):
reference_path = get_result_path(reference_filename)
if os.path.isfile(reference_path):
self.assertTrue(filecmp.cmp(test_filename, reference_path))
else:
self._ensure_folder(reference_path)
logger.warning('Creating result file: %s', reference_path)
shutil.copy(test_filename, reference_path)
def assertString(self, string, reference_filename):
reference_path = get_result_path(reference_filename)
# If the test string is a unicode string, encode as
# utf-8 before comparison to the reference string.
if isinstance(string, unicode):
string = string.encode('utf-8')
self._check_same(string, reference_path, reference_filename,
type_comparison_name='Strings')
def assertRepr(self, obj, reference_filename):
self.assertString(repr(obj), reference_filename)
def _check_same(self, item, reference_path, reference_filename, type_comparison_name='CML'):
if os.path.isfile(reference_path):
reference = ''.join(open(reference_path, 'r').readlines())
self._assert_str_same(reference, item, reference_filename, type_comparison_name)
else:
self._ensure_folder(reference_path)
logger.warning('Creating result file: %s', reference_path)
open(reference_path, 'w').writelines(
part.encode('utf-8') if isinstance(part, unicode) else part
for part in item)
def assertXMLElement(self, obj, reference_filename):
"""
Calls the xml_element method given obj and asserts the result is the same as the test file.
"""
doc = xml.dom.minidom.Document()
doc.appendChild(obj.xml_element(doc))
pretty_xml = doc.toprettyxml(indent=" ")
reference_path = get_result_path(reference_filename)
self._check_same(pretty_xml, reference_path, reference_filename, type_comparison_name='XML')
def assertArrayEqual(self, a, b, err_msg=''):
np.testing.assert_array_equal(a, b, err_msg=err_msg)
def assertMaskedArrayEqual(self, a, b):
"""
Check that masked arrays are equal. This requires the
unmasked values and masks to be identical.
"""
np.testing.assert_array_equal(a.mask, b.mask)
np.testing.assert_array_equal(a[~a.mask].data, b[~b.mask].data)
def assertArrayAlmostEqual(self, a, b):
np.testing.assert_array_almost_equal(a, b)
def assertMaskedArrayAlmostEqual(self, a, b):
"""
Check that masked arrays are almost equal. This requires the
masks to be identical, and the unmasked values to be almost
equal.
"""
np.testing.assert_array_equal(a.mask, b.mask)
np.testing.assert_array_almost_equal(a[~a.mask].data, b[~b.mask].data)
def assertArrayAllClose(self, a, b, rtol=1.0e-7, atol=0.0, **kwargs):
"""
Check arrays are equal, within given relative + absolute tolerances.
Args:
* a, b (array-like):
Two arrays to compare.
Kwargs:
* rtol, atol (float):
Relative and absolute tolerances to apply.
Any additional kwargs are passed to numpy.testing.assert_allclose.
Performs pointwise toleranced comparison, and raises an assertion if
the two are not equal 'near enough'.
For full details see underlying routine numpy.testing.assert_allclose.
"""
np.testing.assert_allclose(a, b, rtol=rtol, atol=atol, **kwargs)
@contextlib.contextmanager
def temp_filename(self, suffix=''):
filename = iris.util.create_temp_filename(suffix)
yield filename
os.remove(filename)
def file_checksum(self, file_path):
"""
Generate checksum from file.
"""
in_file = open(file_path, "rb")
return zlib.crc32(in_file.read())
def _unique_id(self):
"""
Returns the unique ID for the current assertion.
The ID is composed of two parts: a unique ID for the current test
(which is itself composed of the module, class, and test names), and
a sequential counter (specific to the current test) that is incremented
on each call.
For example, calls from a "test_tx" routine followed by a "test_ty"
routine might result in::
test_plot.TestContourf.test_tx.0
test_plot.TestContourf.test_tx.1
test_plot.TestContourf.test_tx.2
test_plot.TestContourf.test_ty.0
"""
# Obtain a consistent ID for the current test.
# NB. unittest.TestCase.id() returns different values depending on
# whether the test has been run explicitly, or via test discovery.
# For example:
# python tests/test_plot.py => '__main__.TestContourf.test_tx'
# ird -t => 'iris.tests.test_plot.TestContourf.test_tx'
bits = self.id().split('.')[-3:]
if bits[0] == '__main__':
file_name = os.path.basename(sys.modules['__main__'].__file__)
bits[0] = os.path.splitext(file_name)[0]
test_id = '.'.join(bits)
# Derive the sequential assertion ID within the test
assertion_id = self._assertion_counts[test_id]
self._assertion_counts[test_id] += 1
return test_id + '.' + str(assertion_id)
def _ensure_folder(self, path):
dir_path = os.path.dirname(path)
if not os.path.exists(dir_path):
logger.warning('Creating folder: %s', dir_path)
os.makedirs(dir_path)
def check_graphic(self, tol=_DEFAULT_IMAGE_TOLERANCE):
"""Checks the CRC matches for the current matplotlib.pyplot figure, and closes the figure."""
unique_id = self._unique_id()
figure = plt.gcf()
try:
expected_fname = os.path.join(os.path.dirname(__file__),
'results', 'visual_tests',
unique_id + '.png')
if not os.path.isdir(os.path.dirname(expected_fname)):
os.makedirs(os.path.dirname(expected_fname))
result_fname = os.path.join(os.path.dirname(__file__),
'result_image_comparison',
'result-' + unique_id + '.png')
if not os.path.isdir(os.path.dirname(result_fname)):
# Handle race-condition where the directories are
# created sometime between the check above and the
# creation attempt below.
try:
os.makedirs(os.path.dirname(result_fname))
except OSError as err:
# Don't care about "File exists"
if err.errno != 17:
raise
figure.savefig(result_fname)
if not os.path.exists(expected_fname):
warnings.warn('Created image for test %s' % unique_id)
shutil.copy2(result_fname, expected_fname)
err = mcompare.compare_images(expected_fname, result_fname, tol=tol)
if _DISPLAY_FIGURES:
if err:
print 'Image comparison would have failed. Message: %s' % err
plt.show()
else:
assert not err, 'Image comparison failed. Message: %s' % err
finally:
plt.close()
class GraphicsTest(IrisTest):
def tearDown(self):
# If a plotting test bombs out it can leave the current figure
# in an odd state, so we make sure it's been disposed of.
plt.close()
def skip_data(fn):
"""
Decorator to choose whether to run tests, based on the availability of
external data.
Example usage:
@skip_data
class MyDataTests(tests.IrisTest):
...
"""
no_data = (not iris.config.TEST_DATA_DIR
or not os.path.isdir(iris.config.TEST_DATA_DIR)
or os.environ.get('IRIS_TEST_NO_DATA'))
skip = unittest.skipIf(
condition=no_data,
reason='Test(s) require external data.')
return skip(fn)
|
kwilliams-mo/iris
|
lib/iris/tests/__init__.py
|
Python
|
gpl-3.0
| 18,638
|
[
"NetCDF"
] |
99bdbef8e1616f891debffa083b037c0538a0994f57a68e54e1fd399f524842a
|
from math import *
from numpy import *
from moose import *
from kstest import *
_min = 0.0
_max = 1.0
def uniform_distrfn(x): # we cannot pass min and max as params because the ks test takes a single valued fn.
assert((_min <= x) and (_max > x))
return x/(_max - _min)
# This test does not pass - the KS-test failed 34 times out of 200 runs in sequence
def full_rng_test(testNo=0, tolerance=0.1, maxSamples=1000):
result = True
tests = Neutral("/tests")
tables = Neutral("testResults")
# First test the default setting: min = 0.0, max = 1.0, mean = 0.5
rng = UniformRng("uniformRng" + str(testNo), tests)
data = Table("uniformRng" + str(testNo), tables)
data.stepMode = 3
data.connect("inputRequest", rng, "sample")
rng.useClock(0)
data.useClock(0)
tests.getContext().reset()
tests.getContext().step(maxSamples-1) # step goes 1 step extra
data.dumpFile("uniform_rng.plot")
sample = array(data)
# compare sample mean and variance with theoretical values
sample_mean = sample.mean()
if fabs(sample_mean - rng.mean) > tolerance*fabs(rng.mean):
print "FAILED:", "sample_mean =", sample_mean, ", intended mean =", rng.mean
result = False
sample_var = sum((sample - sample_mean) ** 2 ) / len(data)
if fabs(sample_var - rng.variance) > tolerance*fabs(rng.variance): # note: this fails when mean = 0.0
print "FAILED:", "sample_variance =", sample_var, ", intended variance =", rng.variance
result = False
# do a max of 5 test
if maxSamples % 5 != 0:
maxSamples = 5 * (maxSamples/5)
sample = sample[:maxSamples]
sample.resize(maxSamples/5, 5)
maxes = apply_along_axis(max, 1, sample)
result = ks_test(maxes, lambda x: x**5)
return result
def do_full_rng_test(count=100, tolerance=0.1, maxSample=1000):
"""Run full_rng_test count times with tolerance and maxSample number of samples"""
result = 0
for ii in range(count):
if full_rng_test(ii, tolerance, maxSample):
result += 1
return result
def testUniformRng(testId, min=0.0, max=1.0, tolerance = 0.1, sampleCount=1000):
result = True
tests = Neutral("/tests")
tables = Neutral("/testResults")
# First test the default setting: min = 0.0, max = 1.0, mean = 0.5
rng = UniformRng("uniformRng" + str(testId), tests)
rng.min = min
if fabs(rng.min - min) > finfo(float).eps:
print "FAILED:", testId, ":: actual lower bound =", rng.min, ", intended lower bound =", min
result = False
rng.max = max
if fabs(rng.max - max) > finfo(float).eps:
print "FAILED:", testId, ":: actual upper bound =", rng.max, ", intended upper bound =", max
result = False
data = Table("uniformRng" + str(testId), tables)
data.stepMode = 3
data.connect("inputRequest", rng, "sample")
rng.useClock(0)
data.useClock(0)
tests.getContext().reset()
tests.getContext().step(sampleCount-1) # step goes 1 step extra
sample = array(data)
# compare sample mean and variance with theoretical values
sample_mean = sample.mean()
if fabs(sample_mean - rng.mean) > tolerance*fabs(rng.mean):
print "FAILED:", testId, ":: sample_mean =", sample_mean, ", intended mean =", rng.mean
result = False
sample_var = sum((sample - sample_mean) ** 2 ) / len(data)
if fabs(sample_var - rng.variance) > tolerance*fabs(rng.variance): # note: this fails when mean = 0.0
print "FAILED:", testId, ":: sample_variance =", sample_var, ", intended variance =", rng.variance
result = False
return result
def doTest():
return testUniformRng("urng1") and \
testUniformRng("urng2", 1.0, 10.0) and \
testUniformRng("urng3", 1e5, 1e12) and \
testUniformRng("urng4", -10.0, -1.0) and \
testUniformRng("urng5", -1e12, -1e5) and \
testUniformRng("urng6", -1.0, 1.0) # this test fails, mean close to 0.0 goes off in samples for some reason
if __name__ == "__main__":
print "Testing UnifromRng: passed?", doTest()
|
BhallaLab/moose-thalamocortical
|
pymoose/tests/randnum/uniformrng.py
|
Python
|
lgpl-2.1
| 4,050
|
[
"MOOSE"
] |
f803fa398122103a784c6e712bace0e5f5f79075dd6cd6e49434e2cb8078b0a1
|
#!/usr/bin/env python
"""Unit tests for the skbio.util.trie module"""
from __future__ import division
# ----------------------------------------------------------------------------
# Copyright (c) 2013--, scikit-bio development team.
#
# Distributed under the terms of the Modified BSD License.
#
# The full license is in the file COPYING.txt, distributed with this software.
# ----------------------------------------------------------------------------
from unittest import TestCase, main
from itertools import izip
from skbio.util.trie import CompressedTrie, _CompressedNode, fasta_to_pairlist
class CompressedNodeTests(TestCase):
"""Tests for the _CompressedNode class"""
def setUp(self):
"""Set up test data for use in compresses node unit tests"""
self.key = "aba"
self.values = [1, 2]
self.node = _CompressedNode(self.key, self.values)
def test_init(self):
"""Node init should construct the right structure"""
# With no values should create a node with an empty list for values,
# the provided key as key, and an empty dictionary as children
n = _CompressedNode(self.key)
self.assertEqual(n.values, [])
self.assertEqual(n.key, self.key)
self.assertEqual(n.children, {})
# With values should create a node with the provided values list as
# values, the provided key as key, and an empty dictionary as children
n = _CompressedNode(self.key, self.values)
self.assertEqual(n.values, self.values)
self.assertEqual(n.key, self.key)
self.assertEqual(n.children, {})
def test_truth_value(self):
"""Non zero should check for any data on the node"""
n = _CompressedNode("")
self.assertFalse(bool(n))
self.assertTrue(bool(self.node))
def test_len(self):
"""Should return the number of values attached to the node"""
self.assertEqual(len(self.node), 2)
def test_size(self):
"""Should return the number of nodes attached to the node"""
self.assertEqual(self.node.size, 1)
def test_prefix_map(self):
"""Should return the prefix map of the node"""
exp = {1: [2]}
self.assertEqual(self.node.prefix_map, exp)
def test_insert(self):
"""Correctly inserts a new key in the node"""
n = _CompressedNode(self.key, self.values)
n.insert("abb", [3])
# A new node has been create with the common prefix
self.assertEqual(n.key, "ab")
self.assertEqual(n.values, [])
# Tests the old node and the new one has been correctly added
# as children
exp_keys = set(["b", "a"])
self.assertEqual(set(n.children.keys()), exp_keys)
# Check that the children have the current values
self.assertEqual(n.children["b"].key, "b")
self.assertEqual(n.children["b"].values, [[3]])
self.assertEqual(n.children["b"].children, {})
self.assertEqual(n.children["a"].key, "a")
self.assertEqual(n.children["a"].values, [1, 2])
self.assertEqual(n.children["a"].children, {})
def test_find(self):
"""The key could be found"""
# Correctly retrieves the key stored in the calling node
self.assertEqual(self.node.find("aba"), [1, 2])
# Correctly retrieves the key stored in a node attached to calling one
n = _CompressedNode(self.key, self.values)
n.insert("abb", [3])
self.assertEqual(n.find("aba"), [1, 2])
self.assertEqual(n.find("abb"), [[3]])
self.assertEqual(n.find("ab"), [])
# Correctly retrieves an empty list for a non existent key
self.assertEqual(n.find("cd"), [])
class CompressedTrieTests(TestCase):
"""Tests for the CompressedTrie class"""
def setUp(self):
"""Set up test data for use in compressed trie unit tests"""
self.data = [("ab", "0"),
("abababa", "1"),
("abab", "2"),
("baba", "3"),
("ababaa", "4"),
("a", "5"),
("abababa", "6"),
("bab", "7"),
("babba", "8")]
self.empty_trie = CompressedTrie()
self.trie = CompressedTrie(self.data)
def test_init(self):
"""Trie init should construct the right structure"""
# In no pair_list is provided, it should create an empty Trie
t = CompressedTrie()
self.assertEqual(t._root.key, "")
self.assertEqual(t._root.values, [])
self.assertEqual(t._root.children, {})
# If a pair_list is provided, it should insert all the data
t = CompressedTrie(self.data)
self.assertEqual(t._root.key, "")
self.assertEqual(t._root.values, [])
self.assertEqual(set(t._root.children.keys()), set(["a", "b"]))
def test_non_zero(self):
"""Non zero should check for any data on the trie"""
self.assertFalse(self.empty_trie)
self.assertTrue(self.trie)
def test_len(self):
"""Should return the number of values attached to the trie"""
self.assertEqual(len(self.empty_trie), 0)
self.assertEqual(len(self.trie), 9)
def test_size(self):
"""Should return the number of nodes attached to the trie"""
self.assertEqual(self.empty_trie.size, 1)
self.assertEqual(self.trie.size, 10)
def test_prefix_map(self):
"""Should map prefix to values"""
exp = {"1": ["6", "2", "0", "5"],
"8": ["7"],
"3": [],
"4": []}
self.assertEqual(self.trie.prefix_map, exp)
def test_insert(self):
"""Correctly inserts a new key into the trie"""
t = CompressedTrie(self.data)
t.insert("babc", "9")
self.assertTrue("9" in t.find("babc"))
exp = {"1": ["6", "2", "0", "5"],
"9": ["7"],
"3": [],
"4": [],
"8": []}
self.assertEqual(t.prefix_map, exp)
def test_find(self):
"""Correctly founds the values present on the trie"""
for key, value in self.data:
self.assertTrue(value in self.trie.find(key))
self.assertEqual(self.trie.find("cac"), [])
self.assertEqual(self.trie.find("abababa"), ["1", "6"])
class FastaToPairlistTests(TestCase):
"""Tests for the fasta_to_pairlist function"""
def setUp(self):
self.seqs = [("sid_0", "AC"),
("sid_1", "ACAGTC"),
("sid_2", "ACTA"),
("sid_3", "CAGT"),
("sid_4", "CATGAA"),
("sid_5", "A"),
("sid_6", "CATGTA"),
("sid_7", "CAA"),
("sid_8", "CACCA")]
def test_fasta_to_pairlist(self):
"""Correctly returns a list of (seq, label)"""
exp = [("AC", "sid_0"),
("ACAGTC", "sid_1"),
("ACTA", "sid_2"),
("CAGT", "sid_3"),
("CATGAA", "sid_4"),
("A", "sid_5"),
("CATGTA", "sid_6"),
("CAA", "sid_7"),
("CACCA", "sid_8")]
for obs, exp in izip(fasta_to_pairlist(self.seqs), exp):
self.assertEqual(obs, exp)
if __name__ == '__main__':
main()
|
Jorge-C/bipy
|
skbio/util/tests/test_trie.py
|
Python
|
bsd-3-clause
| 7,395
|
[
"scikit-bio"
] |
aaa0cd88a73a0d18df9a4a25c398f89a86fe7969b0a56b105ed81aec7208b269
|
#!/usr/bin/env python
# coding: utf-8
# # Advanced: Distribution Propagation
#
# **NOTE**: support for distribution propagation was improved in the 2.3.25 release. Please make sure you have at least 2.3.25 installed.
# ## Setup
#
# Let's first make sure we have the latest version of PHOEBE 2.3 installed (uncomment this line if running in an online notebook session such as colab).
# In[1]:
#!pip install -I "phoebe>=2.3,<2.4"
# In[2]:
import phoebe
from phoebe import u # units
import numpy as np
logger = phoebe.logger()
# We'll use a [semi-detached system](./requiv_crit_semidetached.ipynb) so that we can see some interesting cases of distribution propagation from orbital parameters to the equivalent radius of the star filling its roche lobe.
# In[3]:
b = phoebe.default_binary(semidetached='primary')
# Here we'll add some distributions directly to parameters... but the concepts below apply just as well to distributions extracted from posteriors.
# In[5]:
b.add_distribution({'sma@binary': phoebe.gaussian_around(1),
'incl@binary': phoebe.uniform(85, 90),
'q@binary': phoebe.gaussian_around(0.05)},
distribution='mydist')
# ## Plotting Distributions
#
# By calling [plot_distribution_collection](../api/phoebe.frontend.bundle.Bundle.plot_distribution_collection.md), we can see a corner plot of all of these parameters. Since we created these as univariate distributions (see [Advanced: Distribution Types](./distribution_types.ipynb) for multivariate examples), we can see that there are no correlations between the distributions.
#
# By default, this shows a corner plot that samples from all the matching distributions.
# In[6]:
_ = b.plot_distribution_collection(distribution='mydist', show=True)
# We can pass a list of parameters (as twigs) to the `parameters` keyword argument to only plot a subset of the available parameters.
# In[8]:
_ = b.plot_distribution_collection(distribution='mydist',
parameters=['sma@binary', 'q@binary'],
show=True)
# But we can also use `parameters` to propagate the distributions through the constraints linking parameters together. For example, since we have distributions on `sma` and `incl`, including `asini` should combine the two distributions according to the constraint and showing the resulting correlations.
# In[9]:
_ = b.plot_distribution_collection(distribution='mydist',
parameters=['sma@binary', 'q@binary', 'asini@binary'],
show=True)
# ## Accessing Uncertainties from Distributions
#
# Similarly, we can access the resulting uncertainties (taken from the 1-sigma percentiles by default), by calling [uncertainties_from_distribution_collection](../api/phoebe.frontend.bundle.Bundle.uncertainties_from_distribution_collection.md).
#
# Note that the input gaussian distributions are automatically exposed with symmetric uncertainties, whereas the propagated `asini` distribution will rely on asymmetric uncertainties from the sampled values.
# In[10]:
b.uncertainties_from_distribution_collection(distribution='mydist',
parameters=['sma@binary', 'q@binary', 'asini@binary'],
tex=True)
# To expose at a different "sigma-level", we can pass `sigma`.
# In[11]:
b.uncertainties_from_distribution_collection(distribution='mydist',
parameters=['sma@binary', 'q@binary', 'asini@binary'],
sigma=3,
tex=True)
# And to expose a machine-readable list with lower, centeral, and upper bounds represented, we just exclude the `tex=True`.
# In[12]:
b.uncertainties_from_distribution_collection(distribution='mydist',
parameters=['sma@binary', 'q@binary', 'asini@binary'],
sigma=3)
# In[ ]:
|
phoebe-project/phoebe2-docs
|
development/tutorials/distribution_propagation.py
|
Python
|
gpl-3.0
| 4,121
|
[
"Gaussian"
] |
6d3fba341015def949b01bd031394095b0294ae2e4505964f9650983900dda1b
|
import numpy
import scipy.ndimage as ndimage
from skimage import transform
def pyr_down(image, downscale=2, nyquist_attenuation=0.05):
"""Return an image downsampled by the requested factor.
Parameters:
image: numpy array
downscale: factor by which to shrink the image. 2 is customary.
nyquist_attenuation: controls strength of low-pass filtering (see
documentation for downsample_sigma() for detailed description).
Larger values = more image blurring.
Returns: image of type float32
"""
out_shape = numpy.ceil(numpy.array(image.shape) / float(downscale)).astype(int)
sigma = downsample_sigma(downscale, nyquist_attenuation)
smoothed = ndimage.gaussian_filter(image.astype(numpy.float32), sigma, mode='reflect')
return transform.resize(smoothed, out_shape, order=1, mode='reflect', preserve_range=True, anti_aliasing=False)
def pyr_up(image, upscale=2):
"""Return an image upsampled by the requested factor.
Parameters:
image: numpy array
upscale: factor by which to enlarge the image. 2 is customary.
nyquist_attenuation: controls strength of low-pass filtering (see
documentation for downsample_sigma() for detailed description).
Larger values = more image blurring.
Returns: image of type float32
"""
out_shape = numpy.ceil(numpy.array(image.shape) * upscale).astype(int)
return transform.resize(image.astype(numpy.float32), out_shape, order=1, mode='reflect', preserve_range=True, anti_aliasing=False)
def downsample_sigma(scale_factor, nyquist_attenuation=0.05):
"""Calculate sigma for gaussian blur that will attenuate the nyquist frequency
of an image (after down-scaling) by the specified fraction. Surprisingly,
attenuating by only 5-10% is generally sufficient (nyquist_attenuation=0.05
to 0.1).
See http://www.evoid.de/page/the-caveats-of-image-down-sampling/ .
"""
return scale_factor * (-8*numpy.log(1-nyquist_attenuation))**0.5
|
zplab/zplib
|
zplib/image/pyramid.py
|
Python
|
mit
| 2,028
|
[
"Gaussian"
] |
8fa138a26291e58e7a60895eaa5f38bdefe57e4658821ca9da2c5c5911fe8879
|
"""Merge the NARR precip files to netcdf"""
import datetime
import os
import sys
import numpy as np
import pygrib
from pyiem import iemre
from pyiem.util import ncopen
def to_netcdf(valid):
"""Persist this 1 hour precip information to the netcdf storage
Recall that this timestep has data for the previous hour"""
fn = ("/mesonet/ARCHIVE/data/%s/model/NARR/apcp_%s.grib") % (
valid.strftime("%Y/%m/%d"),
valid.strftime("%Y%m%d%H%M"),
)
if not os.path.isfile(fn):
print("merge_narr: missing file %s" % (fn,))
return False
gribs = pygrib.open(fn)
grb = gribs[1]
val = grb.values
nc = ncopen(
"/mesonet/data/iemre/%s_narr.nc" % (valid.year,), "a", timeout=300
)
tidx = int((iemre.hourly_offset(valid) + 1) / 3)
print("%s np.min: %s np.max: %s" % (tidx, np.min(val), np.max(val)))
apcp = nc.variables["apcp"]
apcp[tidx, :, :] = val
nc.close()
return True
def main(argv):
"""Go Main"""
year = int(argv[1])
sts = datetime.datetime(year, 1, 1)
ets = datetime.datetime(year + 1, 1, 1)
interval = datetime.timedelta(hours=3)
now = sts
while now < ets:
to_netcdf(now)
now += interval
if __name__ == "__main__":
main(sys.argv)
|
akrherz/iem
|
scripts/iemre/merge_narr.py
|
Python
|
mit
| 1,278
|
[
"NetCDF"
] |
18b0c5e2830e31689c02002fc50ae5eefaf4c28421b5b65e8acfa2bdaad9f95d
|
# Authors: Jan Cholasta <jcholast@redhat.com>
#
# Copyright (C) 2014 Red Hat
# see file 'COPYING' for use and warranty information
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
#
from __future__ import print_function
import logging
import os
from optparse import OptionGroup # pylint: disable=deprecated-module
import gssapi
from ipalib.constants import RENEWAL_CA_NAME, RENEWAL_REUSE_CA_NAME
from ipalib.install import certmonger, certstore
from ipapython import admintool, ipautil
from ipapython.certdb import (EMPTY_TRUST_FLAGS,
EXTERNAL_CA_TRUST_FLAGS,
TrustFlags,
parse_trust_flags)
from ipapython.dn import DN
from ipaplatform.paths import paths
from ipalib import api, errors, x509
from ipaserver.install import certs, cainstance, installutils
logger = logging.getLogger(__name__)
class CACertManage(admintool.AdminTool):
command_name = 'ipa-cacert-manage'
usage = "%prog renew [options]\n%prog install [options] CERTFILE"
description = "Manage CA certificates."
cert_nickname = 'caSigningCert cert-pki-ca'
@classmethod
def add_options(cls, parser):
super(CACertManage, cls).add_options(parser)
parser.add_option(
"-p", "--password", dest='password',
help="Directory Manager password")
renew_group = OptionGroup(parser, "Renew options")
renew_group.add_option(
"--self-signed", dest='self_signed',
action='store_true',
help="Sign the renewed certificate by itself")
renew_group.add_option(
"--external-ca", dest='self_signed',
action='store_false',
help="Sign the renewed certificate by external CA")
ext_cas = tuple(x.value for x in cainstance.ExternalCAType)
renew_group.add_option(
"--external-ca-type", dest="external_ca_type",
type="choice", choices=ext_cas,
metavar="{{{0}}}".format(",".join(ext_cas)),
help="Type of the external CA. Default: generic")
renew_group.add_option(
"--external-ca-profile", dest="external_ca_profile",
type='constructor', constructor=cainstance.ExternalCAProfile,
default=None, metavar="PROFILE-SPEC",
help="Specify the certificate profile/template to use "
"at the external CA")
renew_group.add_option(
"--external-cert-file", dest="external_cert_files",
action="append", metavar="FILE",
help="File containing the IPA CA certificate and the external CA "
"certificate chain")
parser.add_option_group(renew_group)
install_group = OptionGroup(parser, "Install options")
install_group.add_option(
"-n", "--nickname", dest='nickname',
help="Nickname for the certificate")
install_group.add_option(
"-t", "--trust-flags", dest='trust_flags', default='C,,',
help="Trust flags for the certificate in certutil format")
parser.add_option_group(install_group)
def validate_options(self):
super(CACertManage, self).validate_options(needs_root=True)
installutils.check_server_configuration()
parser = self.option_parser
if not self.args:
parser.error("command not provided")
command = self.command = self.args[0]
if command == 'renew':
pass
elif command == 'install':
if len(self.args) < 2:
parser.error("certificate file name not provided")
else:
parser.error("unknown command \"%s\"" % command)
def run(self):
command = self.command
api.bootstrap(in_server=True, confdir=paths.ETC_IPA)
api.finalize()
self.ldap_connect()
try:
if command == 'renew':
rc = self.renew()
elif command == 'install':
rc = self.install()
finally:
api.Backend.ldap2.disconnect()
return rc
def ldap_connect(self):
password = self.options.password
if not password:
try:
api.Backend.ldap2.connect(ccache=os.environ.get('KRB5CCNAME'))
except (gssapi.exceptions.GSSError, errors.ACIError):
pass
else:
return
password = installutils.read_password(
"Directory Manager", confirm=False, validate=False)
if password is None:
raise admintool.ScriptError(
"Directory Manager password required")
api.Backend.ldap2.connect(bind_pw=password)
def _get_ca_request_id(self, ca_name):
"""Lookup tracking request for IPA CA, using given ca-name."""
criteria = {
'cert-database': paths.PKI_TOMCAT_ALIAS_DIR,
'cert-nickname': self.cert_nickname,
'ca-name': ca_name,
}
return certmonger.get_request_id(criteria)
def renew(self):
ca = cainstance.CAInstance(api.env.realm)
if not ca.is_configured():
raise admintool.ScriptError("CA is not configured on this system")
self.request_id = self._get_ca_request_id(RENEWAL_CA_NAME)
if self.request_id is None:
# if external CA renewal was interrupted, the request may have
# been left with the "dogtag-ipa-ca-renew-agent-reuse" CA;
# look for it too
self.request_id = self._get_ca_request_id(RENEWAL_REUSE_CA_NAME)
if self.request_id is None:
raise admintool.ScriptError(
"CA certificate is not tracked by certmonger")
logger.debug(
"Found certmonger request id %r", self.request_id)
db = certs.CertDB(api.env.realm, nssdir=paths.PKI_TOMCAT_ALIAS_DIR)
cert = db.get_cert_from_db(self.cert_nickname)
options = self.options
if options.external_cert_files:
return self.renew_external_step_2(ca, cert)
if options.self_signed is not None:
self_signed = options.self_signed
else:
self_signed = cert.is_self_signed()
if self_signed:
return self.renew_self_signed(ca)
else:
return self.renew_external_step_1(ca)
def renew_self_signed(self, ca):
print("Renewing CA certificate, please wait")
msg = "You cannot specify {} when renewing a self-signed CA"
if self.options.external_ca_type:
raise admintool.ScriptError(msg.format("--external-ca-type"))
if self.options.external_ca_profile:
raise admintool.ScriptError(msg.format("--external-ca-profile"))
try:
ca.set_renewal_master()
except errors.NotFound:
raise admintool.ScriptError("CA renewal master not found")
self.resubmit_request()
print("CA certificate successfully renewed")
def renew_external_step_1(self, ca):
print("Exporting CA certificate signing request, please wait")
options = self.options
if not options.external_ca_type:
options.external_ca_type = cainstance.ExternalCAType.GENERIC.value
if options.external_ca_type == cainstance.ExternalCAType.MS_CS.value \
and options.external_ca_profile is None:
options.external_ca_profile = cainstance.MSCSTemplateV1(u"SubCA")
if options.external_ca_profile is not None:
# check that profile is valid for the external ca type
if options.external_ca_type \
not in options.external_ca_profile.valid_for:
raise admintool.ScriptError(
"External CA profile specification '{}' "
"cannot be used with external CA type '{}'."
.format(
options.external_ca_profile.unparsed_input,
options.external_ca_type)
)
self.resubmit_request(
RENEWAL_REUSE_CA_NAME,
profile=options.external_ca_profile)
print(("The next step is to get %s signed by your CA and re-run "
"ipa-cacert-manage as:" % paths.IPA_CA_CSR))
print("ipa-cacert-manage renew "
"--external-cert-file=/path/to/signed_certificate "
"--external-cert-file=/path/to/external_ca_certificate")
def renew_external_step_2(self, ca, old_cert):
print("Importing the renewed CA certificate, please wait")
options = self.options
conn = api.Backend.ldap2
old_spki = old_cert.public_key_info_bytes
cert_file, ca_file = installutils.load_external_cert(
options.external_cert_files, DN(old_cert.subject))
with open(cert_file.name, 'rb') as f:
new_cert_data = f.read()
new_cert = x509.load_pem_x509_certificate(new_cert_data)
new_spki = new_cert.public_key_info_bytes
if new_cert.subject != old_cert.subject:
raise admintool.ScriptError(
"Subject name mismatch (visit "
"http://www.freeipa.org/page/Troubleshooting for "
"troubleshooting guide)")
if new_cert.subject_bytes != old_cert.subject_bytes:
raise admintool.ScriptError(
"Subject name encoding mismatch (visit "
"http://www.freeipa.org/page/Troubleshooting for "
"troubleshooting guide)")
if new_spki != old_spki:
raise admintool.ScriptError(
"Subject public key info mismatch (visit "
"http://www.freeipa.org/page/Troubleshooting for "
"troubleshooting guide)")
with certs.NSSDatabase() as tmpdb:
tmpdb.create_db()
tmpdb.add_cert(old_cert, 'IPA CA', EXTERNAL_CA_TRUST_FLAGS)
try:
tmpdb.add_cert(new_cert, 'IPA CA', EXTERNAL_CA_TRUST_FLAGS)
except ipautil.CalledProcessError as e:
raise admintool.ScriptError(
"Not compatible with the current CA certificate: %s" % e)
ca_certs = x509.load_certificate_list_from_file(ca_file.name)
for ca_cert in ca_certs:
tmpdb.add_cert(
ca_cert, str(DN(ca_cert.subject)), EXTERNAL_CA_TRUST_FLAGS)
try:
tmpdb.verify_ca_cert_validity('IPA CA')
except ValueError as e:
raise admintool.ScriptError(
"Not a valid CA certificate: %s (visit "
"http://www.freeipa.org/page/Troubleshooting for "
"troubleshooting guide)" % e)
trust_chain = tmpdb.get_trust_chain('IPA CA')[:-1]
for nickname in trust_chain:
try:
ca_cert = tmpdb.get_cert(nickname)
except RuntimeError:
break
certstore.put_ca_cert_nss(
conn,
api.env.basedn,
ca_cert,
nickname,
EMPTY_TRUST_FLAGS)
dn = DN(('cn', self.cert_nickname), ('cn', 'ca_renewal'),
('cn', 'ipa'), ('cn', 'etc'), api.env.basedn)
try:
entry = conn.get_entry(dn, ['usercertificate'])
entry['usercertificate'] = [new_cert]
conn.update_entry(entry)
except errors.NotFound:
entry = conn.make_entry(
dn,
objectclass=['top', 'pkiuser', 'nscontainer'],
cn=[self.cert_nickname],
usercertificate=[new_cert])
conn.add_entry(entry)
except errors.EmptyModlist:
pass
try:
ca.set_renewal_master()
except errors.NotFound:
raise admintool.ScriptError("CA renewal master not found")
self.resubmit_request(RENEWAL_REUSE_CA_NAME)
print("CA certificate successfully renewed")
def resubmit_request(self, ca=RENEWAL_CA_NAME, profile=None):
timeout = api.env.startup_timeout + 60
cm_profile = None
if isinstance(profile, cainstance.MSCSTemplateV1):
cm_profile = profile.unparsed_input
cm_template = None
if isinstance(profile, cainstance.MSCSTemplateV2):
cm_template = profile.unparsed_input
logger.debug("resubmitting certmonger request '%s'", self.request_id)
certmonger.resubmit_request(self.request_id, ca=ca, profile=cm_profile,
template_v2=cm_template, is_ca=True)
try:
state = certmonger.wait_for_request(self.request_id, timeout)
except RuntimeError:
raise admintool.ScriptError(
"Resubmitting certmonger request '%s' timed out, "
"please check the request manually" % self.request_id)
ca_error = certmonger.get_request_value(self.request_id, 'ca-error')
if state != 'MONITORING' or ca_error:
raise admintool.ScriptError(
"Error resubmitting certmonger request '%s', "
"please check the request manually" % self.request_id)
logger.debug("modifying certmonger request '%s'", self.request_id)
certmonger.modify(self.request_id,
ca=RENEWAL_CA_NAME,
profile='', template_v2='')
def install(self):
print("Installing CA certificate, please wait")
options = self.options
cert_filename = self.args[1]
try:
cert = x509.load_certificate_from_file(cert_filename)
except IOError as e:
raise admintool.ScriptError(
"Can't open \"%s\": %s" % (cert_filename, e))
except (TypeError, ValueError) as e:
raise admintool.ScriptError("Not a valid certificate: %s" % e)
nickname = options.nickname or str(DN(cert.subject))
ca_certs = certstore.get_ca_certs_nss(api.Backend.ldap2,
api.env.basedn,
api.env.realm,
False)
with certs.NSSDatabase() as tmpdb:
tmpdb.create_db()
tmpdb.add_cert(cert, nickname, EXTERNAL_CA_TRUST_FLAGS)
for ca_cert, ca_nickname, ca_trust_flags in ca_certs:
tmpdb.add_cert(ca_cert, ca_nickname, ca_trust_flags)
try:
tmpdb.verify_ca_cert_validity(nickname)
except ValueError as e:
raise admintool.ScriptError(
"Not a valid CA certificate: %s (visit "
"http://www.freeipa.org/page/Troubleshooting for "
"troubleshooting guide)" % e)
trust_flags = options.trust_flags.split(',')
if (set(options.trust_flags) - set(',CPTcgpuw') or
len(trust_flags) not in [3, 4]):
raise admintool.ScriptError("Invalid trust flags")
extra_flags = trust_flags[3:]
extra_usages = set()
if extra_flags:
if 'C' in extra_flags[0]:
extra_usages.add(x509.EKU_PKINIT_KDC)
if 'T' in extra_flags[0]:
extra_usages.add(x509.EKU_PKINIT_CLIENT_AUTH)
trust_flags = parse_trust_flags(','.join(trust_flags[:3]))
trust_flags = TrustFlags(trust_flags.has_key,
trust_flags.trusted,
trust_flags.ca,
trust_flags.usages | extra_usages)
try:
certstore.put_ca_cert_nss(
api.Backend.ldap2, api.env.basedn, cert, nickname, trust_flags)
except ValueError as e:
raise admintool.ScriptError(
"Failed to install the certificate: %s" % e)
print("CA certificate successfully installed")
|
apophys/freeipa
|
ipaserver/install/ipa_cacert_manage.py
|
Python
|
gpl-3.0
| 16,686
|
[
"VisIt"
] |
2428c0e7e479ea356d86e5e2e397e7381b74adcf7c59a7bd554b075c376e20ec
|
# Copyright 2016 Uri Laserson
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
import warnings
from math import isclose
from Bio.Data.CodonTable import standard_dna_table
from pepsyn.codons import (
amber_codon,
ecoli_codon_usage,
ochre_codon,
opal_codon,
zero_low_freq_codons,
zero_non_amber_stops,
)
class TestUsageManipulation(object):
def test_zero_non_amber(self):
with warnings.catch_warnings(): # biopython Seq.__hash__
warnings.simplefilter("ignore")
zeroed_weight = (
ecoli_codon_usage.freq[ochre_codon] + ecoli_codon_usage.freq[opal_codon]
)
new_usage = zero_non_amber_stops(ecoli_codon_usage)
for codon in new_usage.freq:
if codon == ochre_codon or codon == opal_codon:
continue
inflated_freq = ecoli_codon_usage.freq[codon] / (1 - zeroed_weight)
new_freq = new_usage.freq[codon]
assert isclose(new_freq, inflated_freq)
assert new_usage.freq[ochre_codon] == 0
assert new_usage.freq[opal_codon] == 0
|
lasersonlab/pepsyn
|
pepsyn/tests/test_codons.py
|
Python
|
apache-2.0
| 1,634
|
[
"Biopython"
] |
74963138f43d17d4360702913ac44ef003b94bc31d67d0cf2593bb52df38aad7
|
##############################################################################
# Copyright (c) 2013-2018, Lawrence Livermore National Security, LLC.
# Produced at the Lawrence Livermore National Laboratory.
#
# This file is part of Spack.
# Created by Todd Gamblin, tgamblin@llnl.gov, All rights reserved.
# LLNL-CODE-647188
#
# For details, see https://github.com/spack/spack
# Please also see the NOTICE and LICENSE files for our notice and the LGPL.
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU Lesser General Public License (as
# published by the Free Software Foundation) version 2.1, February 1999.
#
# This program is distributed in the hope that it will be useful, but
# WITHOUT ANY WARRANTY; without even the IMPLIED WARRANTY OF
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the terms and
# conditions of the GNU Lesser General Public License for more details.
#
# You should have received a copy of the GNU Lesser General Public
# License along with this program; if not, write to the Free Software
# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
##############################################################################
from spack import *
class Nccmp(Package):
"""Compare NetCDF Files"""
homepage = "http://nccmp.sourceforge.net/"
url = "http://downloads.sourceforge.net/project/nccmp/nccmp-1.8.2.0.tar.gz"
version('1.8.2.0', '81e6286d4413825aec4327e61a28a580')
depends_on('netcdf')
def install(self, spec, prefix):
# Configure says: F90 and F90FLAGS are replaced by FC and
# FCFLAGS respectively in this configure, please unset
# F90/F90FLAGS and set FC/FCFLAGS instead and rerun configure
# again.
env.pop('F90', None)
env.pop('F90FLAGS', None)
configure('--prefix=%s' % prefix)
make()
make("check")
make("install")
|
EmreAtes/spack
|
var/spack/repos/builtin/packages/nccmp/package.py
|
Python
|
lgpl-2.1
| 1,949
|
[
"NetCDF"
] |
9a4e5f93983e790d4b9ea9a6fce9300e434c612fc5cd6b9df13a1864acfc770c
|
#!/usr/bin/env python
"""
fetch all data files for htsint
At least 20GB of free space is recommended
"""
import os,sys,subprocess,re,time,csv
from sys import platform as _platform
from htsint import __basedir__
from htsint import Configure
class DatabaseFetch(object):
"""
Run each time we want files updated for database
"""
def __init__(self,wget=os.path.join("/","usr","bin","wget"),gunzip=os.path.join("/","usr","bin","gunzip")):
"""
Constructor
"""
config = Configure()
## check that we are in linux or osx
if _platform == "linux" or _platform == "linux2":
pass
elif _platform == "darwin":
pass
elif _platform == "win32":
raise Exception("DatabaseFetch currently does not work on windows platforms\n"+\
"you may still download the files one by one and populated the db")
## ensure they have set up config
for key in ['data','dbname']:
if config.log[key] == '':
raise Exception("You must modify the config file before running DatabaseFetch.py")
dataDir = config.log['data']
if not os.path.isdir(dataDir):
raise Exception("Specified htsint data directory does not exist %s"%dataDir)
## move into specified directory
self.cwd = os.getcwd()
os.chdir(dataDir)
## check for the necessary programs
for wgetPath in [wget,os.path.join('/','usr','local','bin','wget')]:
if os.path.exists(wgetPath) == True:
break
wgetPath = None
if wgetPath == None:
raise Exception("ERROR: cannot find wget -- either download the files (see documentation) or specify a path")
self.wgetPath = wgetPath
gunzipPaths = [gunzip,os.path.join("/","bin","gunzip")]
for gunzipPath in gunzipPaths:
if os.path.exists(gunzipPath) == True:
break
gunzipPath = None
if gunzipPath == None:
raise Exception("ERROR: cannot find gunzip -- either download the files (see documentation) or specify a path")
self.gunzipPath = gunzipPath
def _run_subprocess(self,cmd):
proc = subprocess.Popen(cmd,shell=True,stdout=subprocess.PIPE,stdin=subprocess.PIPE)
try:
outs, errs = proc.communicate(timeout=22000)
except TimeoutExpired:
proc.kill()
outs, errs = proc.communicate()
def fetch_file(self,fetchURL):
cmd = "%s -N %s"%(self.wgetPath,fetchURL)
self._run_subprocess(cmd)
def unzip_file(self,fileName):
print('unzipping...%s'%fileName)
cmd = "%s -c %s > %s.db"%(self.gunzipPath,fileName,fileName[:-3])
self._run_subprocess(cmd)
def untar_file(self,fileName):
print('untarring...%s'%fileName)
cmd = "tar xzf %s"%fileName
self._run_subprocess(cmd)
def run(self):
## prepare a log file
fid = open('fetchdb.log','w')
writer = csv.writer(fid)
def push_out(line):
writer.writerow([line])
print(line)
push_out(sys.argv[0])
push_out(time.asctime())
push_out("fetching files...")
## fetch the files required for the database
uniprotUrl = "ftp://ftp.uniprot.org/pub/databases/uniprot/current_release/knowledgebase/"
filesToFetch = ["ftp://ftp.geneontology.org/pub/go/ontology/go.obo",
"ftp://ftp.ncbi.nlm.nih.gov/pub/taxonomy/taxdump.tar.gz",
"ftp://ftp.ncbi.nlm.nih.gov/gene/DATA/gene_info.gz",
"ftp://ftp.ncbi.nlm.nih.gov/gene/DATA/gene2go.gz",
"ftp://ftp.ncbi.nlm.nih.gov/gene/DATA/gene2refseq.gz",
"ftp://ftp.ebi.ac.uk/pub/databases/GO/goa/UNIPROT/gene_association.goa_uniprot.gz",
uniprotUrl + "idmapping/idmapping.dat.gz",
uniprotUrl + "idmapping/LICENSE",
uniprotUrl + "complete/uniprot_sprot.fasta.gz"
]
for fetchURL in filesToFetch:
fileName = os.path.split(fetchURL)[-1]
push_out("fetching %s..."%fileName)
timeStart = time.time()
self.fetch_file(fetchURL)
fetchTime = time.time() - timeStart
push_out("...%s"%fetchTime)
## unzip the gz files
if not re.search("\.gz",fileName):
continue
if not os.path.exists(fileName[:-3]+".db") or fetchTime > 10:
if re.search("\.tar\.gz",fileName):
self.untar_file(fileName)
else:
self.unzip_file(fileName)
## make the uniprot BLAST index
try:
self._run_subprocess("makeblastdb -in uniprot_sprot.fasta.db -dbtype 'prot' -out uniprot_sprot")
except:
print("WARNING: makeblastdb failed")
push_out("complete.")
fid.close()
## move back to original directory
os.chdir(self.cwd)
if __name__ == "__main__":
print("Running...")
dbf = DatabaseFetch()
dbf.run()
|
ajrichards/htsint
|
htsint/database/DatabaseFetch.py
|
Python
|
bsd-3-clause
| 5,365
|
[
"BLAST"
] |
aa3c79af90ed0d74c239553ccb28971b143b3996939872e43ccecd7acfc2a04c
|
"""
Quadratic Discriminant Analysis
"""
# Author: Matthieu Perrot <matthieu.perrot@gmail.com>
#
# License: BSD Style.
import warnings
import numpy as np
import scipy.ndimage as ndimage
from .base import BaseEstimator, ClassifierMixin
# FIXME :
# - in fit(X, y) method, many checks are common with other models
# (in particular LDA model) and should be factorized:
# maybe in BaseEstimator ?
class QDA(BaseEstimator, ClassifierMixin):
"""
Quadratic Discriminant Analysis (QDA)
Parameters
----------
X : array-like, shape = [n_samples, n_features]
Training vector, where n_samples in the number of samples and
n_features is the number of features.
y : array, shape = [n_samples]
Target vector relative to X
priors : array, optional, shape = [n_classes]
Priors on classes
Attributes
----------
`means_` : array-like, shape = [n_classes, n_features]
Class means
`priors_` : array-like, shape = [n_classes]
Class priors (sum to 1)
`covariances_` : list of array-like, shape = [n_features, n_features]
Covariance matrices of each class
Examples
--------
>>> from sklearn.qda import QDA
>>> import numpy as np
>>> X = np.array([[-1, -1], [-2, -1], [-3, -2], [1, 1], [2, 1], [3, 2]])
>>> y = np.array([1, 1, 1, 2, 2, 2])
>>> clf = QDA()
>>> clf.fit(X, y)
QDA(priors=None)
>>> print clf.predict([[-0.8, -1]])
[1]
See also
--------
LDA
"""
def __init__(self, priors=None):
self.priors = np.asarray(priors) if priors is not None else None
def fit(self, X, y, store_covariances=False, tol=1.0e-4):
"""
Fit the QDA model according to the given training data and parameters.
Parameters
----------
X : array-like, shape = [n_samples, n_features]
Training vector, where n_samples in the number of samples and
n_features is the number of features.
y : array, shape = [n_samples]
Target values (integers)
store_covariances : boolean
If True the covariance matrices are computed and stored in the
self.covariances_ attribute.
"""
X = np.asanyarray(X)
y = np.asanyarray(y)
if X.ndim != 2:
raise ValueError('X must be a 2D array')
if X.shape[0] != y.shape[0]:
raise ValueError(
'Incompatible shapes: X has %s samples, while y '
'has %s' % (X.shape[0], y.shape[0]))
if y.dtype.char.lower() not in ('b', 'h', 'i'):
# We need integer values to be able to use
# ndimage.measurements and np.bincount on numpy >= 2.0.
# We currently support (u)int8, (u)int16 and (u)int32.
# Note that versions of scipy >= 0.8 can also accept
# (u)int64. We however don't support it for backwards
# compatibility.
y = y.astype(np.int32)
n_samples, n_features = X.shape
classes = np.unique(y)
n_classes = classes.size
if n_classes < 2:
raise ValueError('y has less than 2 classes')
classes_indices = [(y == c).ravel() for c in classes]
if self.priors is None:
counts = np.array(ndimage.measurements.sum(
np.ones(n_samples, dtype=y.dtype), y, index=classes))
self.priors_ = counts / float(n_samples)
else:
self.priors_ = self.priors
cov = None
if store_covariances:
cov = []
means = []
scalings = []
rotations = []
for group_indices in classes_indices:
Xg = X[group_indices, :]
meang = Xg.mean(0)
means.append(meang)
Xgc = Xg - meang
# Xgc = U * S * V.T
U, S, Vt = np.linalg.svd(Xgc, full_matrices=False)
rank = np.sum(S > tol)
if rank < n_features:
warnings.warn("Variables are collinear")
S2 = (S ** 2) / (len(Xg) - 1)
if store_covariances:
# cov = V * (S^2 / (n-1)) * V.T
cov.append(np.dot(S2 * Vt.T, Vt))
scalings.append(S2)
rotations.append(Vt.T)
if store_covariances:
self.covariances_ = cov
self.means_ = np.asarray(means)
self.scalings = np.asarray(scalings)
self.rotations = rotations
self.classes = classes
return self
def decision_function(self, X):
"""Apply decision function to an array of samples.
Parameters
----------
X : array-like, shape = [n_samples, n_features]
Array of samples (test vectors).
Returns
-------
C : array, shape = [n_samples, n_classes]
Decision function values related to each class, per sample.
"""
X = np.asanyarray(X)
norm2 = []
for i in range(len(self.classes)):
R = self.rotations[i]
S = self.scalings[i]
Xm = X - self.means_[i]
X2 = np.dot(Xm, R * (S ** (-0.5)))
norm2.append(np.sum(X2 ** 2, 1))
norm2 = np.array(norm2).T # shape = [len(X), n_classes]
return (-0.5 * (norm2 + np.sum(np.log(self.scalings), 1))
+ np.log(self.priors_))
def predict(self, X):
"""Perform classification on an array of test vectors X.
The predicted class C for each sample in X is returned.
Parameters
----------
X : array-like, shape = [n_samples, n_features]
Returns
-------
C : array, shape = [n_samples]
"""
d = self.decision_function(X)
y_pred = self.classes[d.argmax(1)]
return y_pred
def predict_proba(self, X):
"""Return posterior probabilities of classification.
Parameters
----------
X : array-like, shape = [n_samples, n_features]
Array of samples/test vectors.
Returns
-------
C : array, shape = [n_samples, n_classes]
Posterior probabilities of classification per class.
"""
values = self.decision_function(X)
# compute the likelihood of the underlying gaussian models
# up to a multiplicative constant.
likelihood = np.exp(values - values.min(axis=1)[:, np.newaxis])
# compute posterior probabilities
return likelihood / likelihood.sum(axis=1)[:, np.newaxis]
def predict_log_proba(self, X):
"""Return posterior probabilities of classification.
Parameters
----------
X : array-like, shape = [n_samples, n_features]
Array of samples/test vectors.
Returns
-------
C : array, shape = [n_samples, n_classes]
Posterior log-probabilities of classification per class.
"""
# XXX : can do better to avoid precision overflows
probas_ = self.predict_proba(X)
return np.log(probas_)
|
joshbohde/scikit-learn
|
sklearn/qda.py
|
Python
|
bsd-3-clause
| 7,074
|
[
"Gaussian"
] |
25a9822b9c7f1d54689ae3e002c89db8f9ec9d945d64ce80dd13e719a4d8b18c
|
"""
Test case for the problem reported, tested and fixed on this post:
http://public.kitware.com/pipermail/vtk-developers/2008-August/005418.html
Without the fix as applied in the patch there, this code should crash on
exit.
"""
import vtk
class TestCase2 :
def __init__(self) :
self.Filter = vtk.vtkProgrammableFilter()
self.Filter.SetExecuteMethod(self.ExecMethod)
def ExecMethod(self) :
print('execute method called')
test2 = TestCase2()
|
HopeFOAM/HopeFOAM
|
ThirdParty-0.1/ParaView-5.0.1/VTK/Common/Core/Testing/Python/TestExecuteMethodFinalizeCrash.py
|
Python
|
gpl-3.0
| 460
|
[
"VTK"
] |
cf30dbdf7e49b0f7eedd4687a41a2a4ecb229404672031d5e3c2f242a0288906
|
#!/usr/bin/env python
"""
This file contains Python code illustrating the creation and manipulation of
vtkTable objects.
"""
from vtk import *
#------------------------------------------------------------------------------
# Script Entry Point (i.e., main() )
#------------------------------------------------------------------------------
if __name__ == "__main__":
""" Main entry point of this python script """
print "vtkTable Example 2: Loading table data from a comma-separated value file."
# Create a Delimited Text Reader object
csv_source = vtkDelimitedTextReader()
# Tell it we want the field-separator to be a comma
csv_source.SetFieldDelimiterCharacters(",")
# Tell the filter that the first row in the data file are headers.
csv_source.SetHaveHeaders(True)
# Provide the filename that we want to load.
csv_source.SetFileName("table_data.csv")
# Update forces the filter to execute and get the data.
csv_source.Update()
# Print out the table data to the screen
csv_source.GetOutput().Dump(6)
# Note: tables loaded from DelimitedTextReader have all
# types defaulted to string data.
print "vtkTable Example 2: Finished."
|
msmolens/VTK
|
Examples/Infovis/Python/tables2.py
|
Python
|
bsd-3-clause
| 1,215
|
[
"VTK"
] |
46e2476d540ac0cbaaefc23a94387498e382af9392b4c6f4108c3dcb2a396698
|
#!/usr/bin/env python
import os
import re
import sys
import glob
import numpy
import pickle
import configparser
from pyproj import Proj
from mayavi import mlab
SCALING = -3.
def plt_catalogue(filename):
"""
:parameter str filename:
"""
# Set projection
p1 = Proj(proj='aeqd')
# Load catalogue
cat = pickle.load(open(filename, 'rb'))
#
x, y = p1(cat.data['longitude'], cat.data['latitude'])
mlab.points3d(x/1e3, y/1e3, SCALING*cat.data['depth'], color=(0, 0, 1),
scale_factor=4.)
def plot_sub_profiles(foldername):
"""
"""
# Projection
p1 = Proj(proj='aeqd')
# Read files
for filename in glob.glob(os.path.join(foldername, 'cs_*.csv')):
dat = numpy.loadtxt(filename)
sid = re.sub('^cs_', '', re.split('\.', os.path.basename(filename))[0])
x, y = p1(dat[:,0], dat[:,1])
mlab.plot3d(x/1e3, y/1e3, SCALING*dat[:,2], tube_radius=2,
color=(1,0,0))
def plot_edges(foldername):
"""
"""
# Projection
p1 = Proj(proj='aeqd')
# Read files
for filename in glob.glob(os.path.join(foldername, 'edge_*.csv')):
dat = numpy.loadtxt(filename)
sid = re.sub('^edge_', '', re.split('\.', os.path.basename(filename))[0])
x, y = p1(dat[:,0], dat[:,1])
mlab.plot3d(x/1e3, y/1e3, SCALING*dat[:,2], tube_radius=2,
color=(1,1,0))
def main(argv):
"""
"""
foldername = argv[0]
config = configparser.ConfigParser()
config.read(argv[1])
fname_eqk_cat = config['data']['catalogue_pickle_filename']
# Create figure
mlab.figure(1, size=(400, 400), bgcolor=(0.75, 0.75, 0.75))
#
plot_sub_profiles(foldername)
plot_edges(foldername)
# Plot catalogue
#plt_catalogue(fname_eqk_cat)
#
mlab.show()
if __name__ == "__main__":
main(sys.argv[1:])
|
GEMScienceTools/oq-subduction
|
openquake/sub/plotting/plot_2pt5_model_mayavi.py
|
Python
|
agpl-3.0
| 1,890
|
[
"Mayavi"
] |
f350bb598e238eaf89932a6940aa11900a41b04d0b47ab3420f0178b6cce4502
|
########################################################################
# Author: Stuart Paterson
# eMail : Stuart.Paterson@cern.ch
########################################################################
""" The Watchdog class is used by the Job Wrapper to resolve and monitor
the system CPU and memory consumed. The Watchdog can determine if
a running job is stalled and indicate this to the Job Wrapper.
This is the Mac compatible Watchdog subclass.
"""
__RCSID__ = "$Id$"
import re
from DIRAC import S_OK, S_ERROR
from DIRAC.WorkloadManagementSystem.JobWrapper.Watchdog import Watchdog
from DIRAC.Core.Utilities.Subprocess import shellCall
class WatchdogMac( Watchdog ):
def __init__( self, pid, thread, spObject, jobCPUtime, memoryLimit = 0, processors = 1, systemFlag = 'mac' ):
""" Constructor, takes system flag as argument.
"""
Watchdog.__init__( self, pid, thread, spObject, jobCPUtime, memoryLimit, processors, systemFlag )
#############################################################################
def getNodeInformation( self ):
"""Try to obtain system HostName, CPU, Model, cache and memory. This information
is not essential to the running of the jobs but will be reported if
available.
"""
result = S_OK()
result['Value']={}
comm = 'sysctl -a'
parameterDict = shellCall(5,comm)
if parameterDict['OK']:
info = parameterDict['Value'][1].split('\n')
for val in info:
if re.search('^kern.hostname',val):
hostname = 'NA'
if re.search('=',val):
hostname = val.split('=')[1].strip()
else:
hostname = val.split(':')[1].strip()
result['Value']['HostName']=hostname
if re.search('^hw.model',val):
model = val.split('=')[1].strip()
result['Value']['Model']=model
if re.search('^hw.machine',val):
cpu = val.split('=')[1].strip()
result['Value']['CPU']=cpu
if re.search('^hw.cachelinesize =',val):
cache = val.split('=')[1].strip()+'KB'
result['Value']['Cache']=cache
if re.search('^hw.memsize =',val):
memory = str(int(val.split('=')[1].strip())/2**20)+'MB'
result['Value']['Memory']=memory
account = 'Unknown'
localID = shellCall(10,'whoami')
if localID['OK']:
account = localID['Value'][1].strip()
result['LocalAccount'] = account
else:
result = S_ERROR( 'Could not obtain system information' )
return result
#############################################################################
def getLoadAverage( self ):
"""Obtains the load average.
"""
comm = 'sysctl vm.loadavg'
loadAvgDict = shellCall( 5, comm )
if loadAvgDict['OK']:
la = float( loadAvgDict['Value'][1].split()[3] )
return S_OK( la )
else:
return S_ERROR( 'Could not obtain load average' )
#############################################################################
def getMemoryUsed(self):
"""Obtains the memory used.
"""
comm = 'sysctl vm.swapusage'
memDict = shellCall( 5, comm )
if memDict['OK']:
mem = memDict['Value'][1].split()[6]
if re.search('M$',mem):
mem = float(mem.replace('M',''))
mem = 2**20*mem
return S_OK( float( mem ) )
else:
return S_ERROR( 'Could not obtain memory used' )
#############################################################################
def getDiskSpace( self ):
"""Obtains the available disk space.
"""
result = S_OK()
comm = 'df -P -m .'
spaceDict = shellCall( 5, comm )
if spaceDict['OK']:
space = spaceDict['Value'][1].split()[10]
result['Value'] = float( space ) # MB
else:
result = S_ERROR( 'Could not obtain disk usage' )
return result
#EOF#EOF#EOF#EOF#EOF#EOF#EOF#EOF#EOF#EOF#EOF#EOF#EOF#EOF#EOF#EOF#EOF#EOF#EOF#
|
Andrew-McNab-UK/DIRAC
|
WorkloadManagementSystem/JobWrapper/WatchdogMac.py
|
Python
|
gpl-3.0
| 4,002
|
[
"DIRAC"
] |
b664799ee7a37f074591745668d900d41dc216a3ffd74e9b1b5aea04b7d0e0ed
|
#!/usr/bin/python
import argparse
""" ChemPyType.py
A python module used to import the numerous and varying molecule file types.
Use within a python script:
import ChemPyType
fileName = "path/to/file.ext"
fileType = "supportedFileType"
molecule = ChemPyType.importMolecule(fileName,fileType)
Use within the command line:
ChemPyType.py -f path/to/file.ext -t supportedFileType
Current supported file types:
Gaussian .com format (GaussianCom)
"""
#File Format Classes
class Molecule():
def __init__(self):
self.nAtoms = 0
self.atomTypes = []
self.x = []
self.y = []
self.z = []
self.connectivity = {}
def readGaussianComFile(fileContents):
molecule = Molecule()
checkCount = False
readLines = False
count = 0
for line in fileContents:
if line.strip():
line = line.split()
if "#" in line[0]:
count = 0
checkCount = True
if checkCount:
if count == 3:
readLines = True
else:
count += 1
if readLines:
if line[0].isalpha():
molecule.nAtoms += 1
molecule.atomTypes.append(line[0])
molecule.x.append(float(line[1]))
molecule.y.append(float(line[2]))
molecule.z.append(float(line[3]))
else:
currentAtom = int(line[0])
if currentAtom not in molecule.connectivity:
molecule.connectivity[currentAtom] = {}
for index,connectedAtom in enumerate(line):
if index % 2 == 1:
connectedAtom = int(connectedAtom)
if connectedAtom not in molecule.connectivity:
molecule.connectivity[connectedAtom] = {}
order = float(line[index+1])
molecule.connectivity[currentAtom]\
[connectedAtom] = order
molecule.connectivity[connectedAtom]\
[currentAtom] = order
return molecule
def getArgs():
parser = argparse.ArgumentParser(description=
"Process file format arguments")
parser.add_argument("--file","-f",nargs=1,dest="fileName",
help="File name of molecule file",required=True)
parser.add_argument("--type","-t",nargs=1,dest="fileType",
help="File type of molecule file",required=True)
return parser.parse_args()
def importMolecule(fileName,fileType):
with open(fileName,"r") as inFile:
if fileType == "GaussianCom":
molecule = readGaussianComFile(inFile)
return molecule
if __name__ == "__main__":
args = getArgs()
importMolecule(args.fileName[0],args.fileType[0])
|
josephtallison/ChemPyType
|
ChemPyType.py
|
Python
|
mit
| 3,004
|
[
"Gaussian"
] |
0af0fd9d989894170f8135c9e876ec0ea2bf58c1e8ae44bf16da6dd2bbca4634
|
# -*- coding: utf-8 -*-
"""
The :mod:`sklearn.naive_bayes` module implements Naive Bayes algorithms. These
are supervised learning methods based on applying Bayes' theorem with strong
(naive) feature independence assumptions.
"""
# Author: Vincent Michel <vincent.michel@inria.fr>
# Minor fixes by Fabian Pedregosa
# Amit Aides <amitibo@tx.technion.ac.il>
# Yehuda Finkelstein <yehudaf@tx.technion.ac.il>
# Lars Buitinck <L.J.Buitinck@uva.nl>
# (parts based on earlier work by Mathieu Blondel)
#
# License: BSD 3 clause
from abc import ABCMeta, abstractmethod
import numpy as np
from scipy.sparse import issparse
from .base import BaseEstimator, ClassifierMixin
from .preprocessing import binarize
from .preprocessing import LabelBinarizer
from .preprocessing import label_binarize
from .utils import array2d, atleast2d_or_csr, column_or_1d, check_arrays
from .utils.extmath import safe_sparse_dot, logsumexp
from .utils.multiclass import _check_partial_fit_first_call
from .externals import six
__all__ = ['BernoulliNB', 'GaussianNB', 'MultinomialNB']
class BaseNB(six.with_metaclass(ABCMeta, BaseEstimator, ClassifierMixin)):
"""Abstract base class for naive Bayes estimators"""
@abstractmethod
def _joint_log_likelihood(self, X):
"""Compute the unnormalized posterior log probability of X
I.e. ``log P(c) + log P(x|c)`` for all rows x of X, as an array-like of
shape [n_classes, n_samples].
Input is passed to _joint_log_likelihood as-is by predict,
predict_proba and predict_log_proba.
"""
def predict(self, X):
"""
Perform classification on an array of test vectors X.
Parameters
----------
X : array-like, shape = [n_samples, n_features]
Returns
-------
C : array, shape = [n_samples]
Predicted target values for X
"""
jll = self._joint_log_likelihood(X)
return self.classes_[np.argmax(jll, axis=1)]
def predict_log_proba(self, X):
"""
Return log-probability estimates for the test vector X.
Parameters
----------
X : array-like, shape = [n_samples, n_features]
Returns
-------
C : array-like, shape = [n_samples, n_classes]
Returns the log-probability of the samples for each class in
the model. The columns correspond to the classes in sorted
order, as they appear in the attribute `classes_`.
"""
jll = self._joint_log_likelihood(X)
# normalize by P(x) = P(f_1, ..., f_n)
log_prob_x = logsumexp(jll, axis=1)
return jll - np.atleast_2d(log_prob_x).T
def predict_proba(self, X):
"""
Return probability estimates for the test vector X.
Parameters
----------
X : array-like, shape = [n_samples, n_features]
Returns
-------
C : array-like, shape = [n_samples, n_classes]
Returns the probability of the samples for each class in
the model. The columns correspond to the classes in sorted
order, as they appear in the attribute `classes_`.
"""
return np.exp(self.predict_log_proba(X))
class GaussianNB(BaseNB):
"""
Gaussian Naive Bayes (GaussianNB)
Attributes
----------
`class_prior_` : array, shape = [n_classes]
probability of each class.
`theta_` : array, shape = [n_classes, n_features]
mean of each feature per class
`sigma_` : array, shape = [n_classes, n_features]
variance of each feature per class
Examples
--------
>>> import numpy as np
>>> X = np.array([[-1, -1], [-2, -1], [-3, -2], [1, 1], [2, 1], [3, 2]])
>>> Y = np.array([1, 1, 1, 2, 2, 2])
>>> from sklearn.naive_bayes import GaussianNB
>>> clf = GaussianNB()
>>> clf.fit(X, Y)
GaussianNB()
>>> print(clf.predict([[-0.8, -1]]))
[1]
"""
def fit(self, X, y):
"""Fit Gaussian Naive Bayes according to X, y
Parameters
----------
X : array-like, shape = [n_samples, n_features]
Training vectors, where n_samples is the number of samples
and n_features is the number of features.
y : array-like, shape = [n_samples]
Target values.
Returns
-------
self : object
Returns self.
"""
X, y = check_arrays(X, y, sparse_format='dense')
y = column_or_1d(y, warn=True)
n_samples, n_features = X.shape
self.classes_ = unique_y = np.unique(y)
n_classes = unique_y.shape[0]
self.theta_ = np.zeros((n_classes, n_features))
self.sigma_ = np.zeros((n_classes, n_features))
self.class_prior_ = np.zeros(n_classes)
epsilon = 1e-9
for i, y_i in enumerate(unique_y):
Xi = X[y == y_i, :]
self.theta_[i, :] = np.mean(Xi, axis=0)
self.sigma_[i, :] = np.var(Xi, axis=0) + epsilon
self.class_prior_[i] = np.float(Xi.shape[0]) / n_samples
return self
def _joint_log_likelihood(self, X):
X = array2d(X)
joint_log_likelihood = []
for i in range(np.size(self.classes_)):
jointi = np.log(self.class_prior_[i])
n_ij = - 0.5 * np.sum(np.log(2. * np.pi * self.sigma_[i, :]))
n_ij -= 0.5 * np.sum(((X - self.theta_[i, :]) ** 2) /
(self.sigma_[i, :]), 1)
joint_log_likelihood.append(jointi + n_ij)
joint_log_likelihood = np.array(joint_log_likelihood).T
return joint_log_likelihood
class BaseDiscreteNB(BaseNB):
"""Abstract base class for naive Bayes on discrete/categorical data
Any estimator based on this class should provide:
__init__
_joint_log_likelihood(X) as per BaseNB
"""
def _update_class_log_prior(self, class_prior=None):
n_classes = len(self.classes_)
if class_prior is not None:
if len(class_prior) != n_classes:
raise ValueError("Number of priors must match number of"
" classes.")
self.class_log_prior_ = np.log(class_prior)
elif self.fit_prior:
# empirical prior, with sample_weight taken into account
self.class_log_prior_ = (np.log(self.class_count_)
- np.log(self.class_count_.sum()))
else:
self.class_log_prior_ = np.zeros(n_classes) - np.log(n_classes)
def partial_fit(self, X, y, classes=None, sample_weight=None):
"""Incremental fit on a batch of samples.
This method is expected to be called several times consecutively
on different chunks of a dataset so as to implement out-of-core
or online learning.
This is especially useful when the whole dataset is too big to fit in
memory at once.
This method has some performance overhead hence it is better to call
partial_fit on chunks of data that are as large as possible
(as long as fitting in the memory budget) to hide the overhead.
Parameters
----------
X : {array-like, sparse matrix}, shape = [n_samples, n_features]
Training vectors, where n_samples is the number of samples and
n_features is the number of features.
y : array-like, shape = [n_samples]
Target values.
classes : array-like, shape = [n_classes]
List of all the classes that can possibly appear in the y vector.
Must be provided at the first call to partial_fit, can be omitted
in subsequent calls.
sample_weight : array-like, shape = [n_samples], optional
Weights applied to individual samples (1. for unweighted).
Returns
-------
self : object
Returns self.
"""
X = atleast2d_or_csr(X, dtype=np.float64)
_, n_features = X.shape
if _check_partial_fit_first_call(self, classes):
# This is the first call to partial_fit:
# initialize various cumulative counters
n_effective_classes = len(classes) if len(classes) > 1 else 2
self.class_count_ = np.zeros(n_effective_classes, dtype=np.float64)
self.feature_count_ = np.zeros((n_effective_classes, n_features),
dtype=np.float64)
Y = label_binarize(y, classes=self.classes_)
if Y.shape[1] == 1:
Y = np.concatenate((1 - Y, Y), axis=1)
n_samples, n_classes = Y.shape
if X.shape[0] != Y.shape[0]:
msg = "X.shape[0]=%d and y.shape[0]=%d are incompatible."
raise ValueError(msg % (X.shape[0], y.shape[0]))
# convert to float to support sample weight consistently
Y = Y.astype(np.float64)
if sample_weight is not None:
Y *= array2d(sample_weight).T
# Count raw events from data before updating the class log prior
# and feature log probas
self._count(X, Y)
# XXX: OPTIM: we could introduce a public finalization method to
# be called by the user explicitly just once after several consecutive
# calls to partial_fit and prior any call to predict[_[log_]proba]
# to avoid computing the smooth log probas at each call to partial fit
self._update_feature_log_prob()
self._update_class_log_prior()
return self
def fit(self, X, y, sample_weight=None):
"""Fit Naive Bayes classifier according to X, y
Parameters
----------
X : {array-like, sparse matrix}, shape = [n_samples, n_features]
Training vectors, where n_samples is the number of samples and
n_features is the number of features.
y : array-like, shape = [n_samples]
Target values.
sample_weight : array-like, shape = [n_samples], optional
Weights applied to individual samples (1. for unweighted).
Returns
-------
self : object
Returns self.
"""
X, y = check_arrays(X, y, sparse_format='csr')
y = column_or_1d(y, warn=True)
_, n_features = X.shape
labelbin = LabelBinarizer()
Y = labelbin.fit_transform(y)
self.classes_ = labelbin.classes_
if Y.shape[1] == 1:
Y = np.concatenate((1 - Y, Y), axis=1)
# convert to float to support sample weight consistently;
# this means we also don't have to cast X to floating point
Y = Y.astype(np.float64)
if sample_weight is not None:
Y *= array2d(sample_weight).T
class_prior = self.class_prior
# Count raw events from data before updating the class log prior
# and feature log probas
n_effective_classes = Y.shape[1]
self.class_count_ = np.zeros(n_effective_classes, dtype=np.float64)
self.feature_count_ = np.zeros((n_effective_classes, n_features),
dtype=np.float64)
self._count(X, Y)
self._update_feature_log_prob()
self._update_class_log_prior(class_prior=class_prior)
return self
# XXX The following is a stopgap measure; we need to set the dimensions
# of class_log_prior_ and feature_log_prob_ correctly.
def _get_coef(self):
return (self.feature_log_prob_[1:]
if len(self.classes_) == 2 else self.feature_log_prob_)
def _get_intercept(self):
return (self.class_log_prior_[1:]
if len(self.classes_) == 2 else self.class_log_prior_)
coef_ = property(_get_coef)
intercept_ = property(_get_intercept)
class MultinomialNB(BaseDiscreteNB):
"""
Naive Bayes classifier for multinomial models
The multinomial Naive Bayes classifier is suitable for classification with
discrete features (e.g., word counts for text classification). The
multinomial distribution normally requires integer feature counts. However,
in practice, fractional counts such as tf-idf may also work.
Parameters
----------
alpha : float, optional (default=1.0)
Additive (Laplace/Lidstone) smoothing parameter
(0 for no smoothing).
fit_prior : boolean
Whether to learn class prior probabilities or not.
If false, a uniform prior will be used.
class_prior : array-like, size (n_classes,)
Prior probabilities of the classes. If specified the priors are not
adjusted according to the data.
Attributes
----------
`class_log_prior_` : array, shape (n_classes, )
Smoothed empirical log probability for each class.
`intercept_` : property
Mirrors ``class_log_prior_`` for interpreting MultinomialNB
as a linear model.
`feature_log_prob_`: array, shape (n_classes, n_features)
Empirical log probability of features
given a class, ``P(x_i|y)``.
`coef_` : property
Mirrors ``feature_log_prob_`` for interpreting MultinomialNB
as a linear model.
`class_count_` : array, shape (n_classes,)
Number of samples encountered for each class during fitting. This
value is weighted by the sample weight when provided.
`feature_count_` : array, shape (n_classes, n_features)
Number of samples encountered for each (class, feature)
during fitting. This value is weighted by the sample weight when
provided.
Examples
--------
>>> import numpy as np
>>> X = np.random.randint(5, size=(6, 100))
>>> y = np.array([1, 2, 3, 4, 5, 6])
>>> from sklearn.naive_bayes import MultinomialNB
>>> clf = MultinomialNB()
>>> clf.fit(X, y)
MultinomialNB(alpha=1.0, class_prior=None, fit_prior=True)
>>> print(clf.predict(X[2]))
[3]
Notes
-----
For the rationale behind the names `coef_` and `intercept_`, i.e.
naive Bayes as a linear classifier, see J. Rennie et al. (2003),
Tackling the poor assumptions of naive Bayes text classifiers, ICML.
References
----------
C.D. Manning, P. Raghavan and H. Schuetze (2008). Introduction to
Information Retrieval. Cambridge University Press, pp. 234-265.
http://nlp.stanford.edu/IR-book/html/htmledition/
naive-bayes-text-classification-1.html
"""
def __init__(self, alpha=1.0, fit_prior=True, class_prior=None):
self.alpha = alpha
self.fit_prior = fit_prior
self.class_prior = class_prior
def _count(self, X, Y):
"""Count and smooth feature occurrences."""
if np.any((X.data if issparse(X) else X) < 0):
raise ValueError("Input X must be non-negative")
self.feature_count_ += safe_sparse_dot(Y.T, X)
self.class_count_ += Y.sum(axis=0)
def _update_feature_log_prob(self):
"""Apply smoothing to raw counts and recompute log probabilities"""
smoothed_fc = self.feature_count_ + self.alpha
smoothed_cc = smoothed_fc.sum(axis=1)
self.feature_log_prob_ = (np.log(smoothed_fc)
- np.log(smoothed_cc.reshape(-1, 1)))
def _joint_log_likelihood(self, X):
"""Calculate the posterior log probability of the samples X"""
X = atleast2d_or_csr(X)
return (safe_sparse_dot(X, self.feature_log_prob_.T)
+ self.class_log_prior_)
class BernoulliNB(BaseDiscreteNB):
"""Naive Bayes classifier for multivariate Bernoulli models.
Like MultinomialNB, this classifier is suitable for discrete data. The
difference is that while MultinomialNB works with occurrence counts,
BernoulliNB is designed for binary/boolean features.
Parameters
----------
alpha : float, optional (default=1.0)
Additive (Laplace/Lidstone) smoothing parameter
(0 for no smoothing).
binarize : float or None, optional
Threshold for binarizing (mapping to booleans) of sample features.
If None, input is presumed to already consist of binary vectors.
fit_prior : boolean
Whether to learn class prior probabilities or not.
If false, a uniform prior will be used.
class_prior : array-like, size=[n_classes,]
Prior probabilities of the classes. If specified the priors are not
adjusted according to the data.
Attributes
----------
`class_log_prior_` : array, shape = [n_classes]
Log probability of each class (smoothed).
`feature_log_prob_` : array, shape = [n_classes, n_features]
Empirical log probability of features given a class, P(x_i|y).
`class_count_` : array, shape = [n_classes]
Number of samples encountered for each class during fitting. This
value is weighted by the sample weight when provided.
`feature_count_` : array, shape = [n_classes, n_features]
Number of samples encountered for each (class, feature)
during fitting. This value is weighted by the sample weight when
provided.
Examples
--------
>>> import numpy as np
>>> X = np.random.randint(2, size=(6, 100))
>>> Y = np.array([1, 2, 3, 4, 4, 5])
>>> from sklearn.naive_bayes import BernoulliNB
>>> clf = BernoulliNB()
>>> clf.fit(X, Y)
BernoulliNB(alpha=1.0, binarize=0.0, class_prior=None, fit_prior=True)
>>> print(clf.predict(X[2]))
[3]
References
----------
C.D. Manning, P. Raghavan and H. Schuetze (2008). Introduction to
Information Retrieval. Cambridge University Press, pp. 234-265.
http://nlp.stanford.edu/IR-book/html/htmledition/the-bernoulli-model-1.html
A. McCallum and K. Nigam (1998). A comparison of event models for naive
Bayes text classification. Proc. AAAI/ICML-98 Workshop on Learning for
Text Categorization, pp. 41-48.
V. Metsis, I. Androutsopoulos and G. Paliouras (2006). Spam filtering with
naive Bayes -- Which naive Bayes? 3rd Conf. on Email and Anti-Spam (CEAS).
"""
def __init__(self, alpha=1.0, binarize=.0, fit_prior=True,
class_prior=None):
self.alpha = alpha
self.binarize = binarize
self.fit_prior = fit_prior
self.class_prior = class_prior
def _count(self, X, Y):
"""Count and smooth feature occurrences."""
if self.binarize is not None:
X = binarize(X, threshold=self.binarize)
self.feature_count_ += safe_sparse_dot(Y.T, X)
self.class_count_ += Y.sum(axis=0)
def _update_feature_log_prob(self):
"""Apply smoothing to raw counts and recompute log probabilities"""
n_classes = len(self.classes_)
smoothed_fc = self.feature_count_ + self.alpha
smoothed_cc = self.class_count_ + self.alpha * n_classes
self.feature_log_prob_ = (np.log(smoothed_fc)
- np.log(smoothed_cc.reshape(-1, 1)))
def _joint_log_likelihood(self, X):
"""Calculate the posterior log probability of the samples X"""
X = atleast2d_or_csr(X)
if self.binarize is not None:
X = binarize(X, threshold=self.binarize)
n_classes, n_features = self.feature_log_prob_.shape
n_samples, n_features_X = X.shape
if n_features_X != n_features:
raise ValueError("Expected input with %d features, got %d instead"
% (n_features, n_features_X))
neg_prob = np.log(1 - np.exp(self.feature_log_prob_))
# Compute neg_prob · (1 - X).T as ∑neg_prob - X · neg_prob
jll = safe_sparse_dot(X, (self.feature_log_prob_ - neg_prob).T)
jll += self.class_log_prior_ + neg_prob.sum(axis=1)
return jll
|
chaluemwut/fbserver
|
venv/lib/python2.7/site-packages/sklearn/naive_bayes.py
|
Python
|
apache-2.0
| 19,853
|
[
"Gaussian"
] |
0d298eee5a70662040947af49287e70140b3cd961ae300c70d9052b10044cb9a
|
#
# Gramps - a GTK+/GNOME based genealogy program
#
# Copyright (C) 2008 Brian G. Matherly
# Copyright (C) 2010 Jakim Friant
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
#
#-------------------------------------------------------------------------
#
# Gramps modules
#
#-------------------------------------------------------------------------
from ._reportdialog import ReportDialog
from gramps.gen.plug.report import CATEGORY_WEB
#-------------------------------------------------------------------------
#
# WebReportDialog class
#
#-------------------------------------------------------------------------
class WebReportDialog(ReportDialog):
"""
The WebReportDialog base class. This is a base class for generating
dialogs for web page reports.
"""
def __init__(self, dbstate, uistate, option_class, name, trans_name):
"""Initialize a dialog"""
self.category = CATEGORY_WEB
ReportDialog.__init__(self, dbstate, uistate, option_class,
name, trans_name)
self.options.handler.set_format_name('html')
def setup_init(self):
pass
def setup_target_frame(self):
"""Target frame is not used."""
pass
def parse_target_frame(self):
"""Target frame is not used."""
return 1
|
SNoiraud/gramps
|
gramps/gui/plug/report/_webreportdialog.py
|
Python
|
gpl-2.0
| 1,978
|
[
"Brian"
] |
354ce99c0e31f13828ffe4d60925dacff399f2d511165d44d3ff7edbb7428e19
|
"""
The header specification for the message protocol
Copyright (c) 2009 John Markus Bjoerndalen <jmb@cs.uit.no>,
Brian Vinter <vinter@nbi.dk>, Rune M. Friborg <rune.m.friborg@gmail.com>.
See LICENSE.txt for licensing details (MIT License).
"""
import ctypes
from pycsp.parallel.const import *
# Bit patters for selecting types
GUARD_CMD = 1<<13
PROCESS_CMD = 1<<12
CHANNEL_CMD = 1<<11
HAS_PAYLOAD = 1<<10
REQ_REPLY = 1<<9
IS_REPLY = 1<<8
NATFIX = 1<<7
IGN_UNKNOWN = 1<<6
ERROR_CMD = 0
"""
GUARD_CMD, PROCESS_CMD and CHANNEL_CMD encodes the destination.
HAS_PAYLOAD tells the receiver, that it must read N bytes containing a payload message
REQ_REPLY informs that if the destination is not available, an error must be returned, such that the sender does not deadlock by waiting eternally for a reply
IS_REPLY informs which queue to post the incoming message to.
NATFIX informs that the receiving socket should also be used as a sending socket
IGN_UNKNOWN informs that it is ok to drop this message, if the destination is not found
"""
# CMDs for processes
LOCKTHREAD_ACQUIRE_LOCK = PROCESS_CMD | 0 | REQ_REPLY
LOCKTHREAD_ACCEPT_LOCK = CHANNEL_CMD | GUARD_CMD | 1 | IS_REPLY
LOCKTHREAD_UNAVAILABLE = CHANNEL_CMD | GUARD_CMD | 2 | IS_REPLY
LOCKTHREAD_NOTIFY_SUCCESS = PROCESS_CMD | 3 | IS_REPLY | HAS_PAYLOAD
LOCKTHREAD_POISON = PROCESS_CMD | 4 | IS_REPLY
LOCKTHREAD_RETIRE = PROCESS_CMD | 5 | IS_REPLY
LOCKTHREAD_RELEASE_LOCK = PROCESS_CMD | 6 | IS_REPLY | IGN_UNKNOWN
LOCKTHREAD_QUIT = PROCESS_CMD | 30
LOCKTHREAD_ACK = PROCESS_CMD | 42
SOCKETTHREAD_SHUTDOWN = PROCESS_CMD | CHANNEL_CMD | 7
SOCKETTHREAD_PING = PROCESS_CMD | CHANNEL_CMD | 20
# CMDs for channels
CHANTHREAD_JOIN_READER = CHANNEL_CMD | 8
CHANTHREAD_JOIN_WRITER = CHANNEL_CMD | 9
CHANTHREAD_RETIRE_READER = CHANNEL_CMD | 12
CHANTHREAD_RETIRE_WRITER = CHANNEL_CMD | 13
CHANTHREAD_POISON_READER = CHANNEL_CMD | 14
CHANTHREAD_POISON_WRITER = CHANNEL_CMD | 15
CHANTHREAD_REGISTER = CHANNEL_CMD | 16
CHANTHREAD_DEREGISTER = CHANNEL_CMD | 17
CHANTHREAD_POST_READ = CHANNEL_CMD | 18
CHANTHREAD_POST_WRITE = CHANNEL_CMD | 19 | HAS_PAYLOAD
CHANTHREAD_POST_ACK_READ = CHANNEL_CMD | 40
CHANTHREAD_POST_ACK_WRITE = CHANNEL_CMD | 41 | HAS_PAYLOAD
CHANTHREAD_ENTER = CHANNEL_CMD | 24 | NATFIX
CHANTHREAD_LEAVE = CHANNEL_CMD | 26
def cmd2str(cmd):
"""
Translate command IDs to their string representation
Use for debugging and error messages
"""
D = {
ERROR_CMD:"ERROR_CMD",
LOCKTHREAD_ACQUIRE_LOCK :"LOCKTHREAD_ACQUIRE_LOCK",
LOCKTHREAD_ACCEPT_LOCK :"LOCKTHREAD_ACCEPT_LOCK",
LOCKTHREAD_UNAVAILABLE :"LOCKTHREAD_UNAVAILABLE",
LOCKTHREAD_NOTIFY_SUCCESS:"LOCKTHREAD_NOTIFY_SUCCESS",
LOCKTHREAD_POISON :"LOCKTHREAD_POISON",
LOCKTHREAD_RETIRE :"LOCKTHREAD_RETIRE",
LOCKTHREAD_RELEASE_LOCK :"LOCKTHREAD_RELEASE_LOCK",
LOCKTHREAD_QUIT :"LOCKTHREAD_QUIT ",
SOCKETTHREAD_SHUTDOWN :"SOCKETTHREAD_SHUTDOWN",
CHANTHREAD_JOIN_READER :"CHANTHREAD_JOIN_READER",
CHANTHREAD_JOIN_WRITER :"CHANTHREAD_JOIN_WRITER",
CHANTHREAD_RETIRE_READER :"CHANTHREAD_RETIRE_READER",
CHANTHREAD_RETIRE_WRITER :"CHANTHREAD_RETIRE_WRITER",
CHANTHREAD_POISON_READER :"CHANTHREAD_POISON_READER",
CHANTHREAD_POISON_WRITER :"CHANTHREAD_POISON_WRITER",
CHANTHREAD_REGISTER :"CHANTHREAD_REGISTER",
CHANTHREAD_DEREGISTER :"CHANTHREAD_DEREGISTER",
CHANTHREAD_POST_READ :"CHANTHREAD_POST_READ",
CHANTHREAD_POST_WRITE :"CHANTHREAD_POST_WRITE",
CHANTHREAD_ENTER :"CHANTHREAD_ENTER",
CHANTHREAD_LEAVE :"CHANTHREAD_LEAVE"
}
return D[cmd]
class Header(ctypes.Structure):
"""
cmd : type of package
id : string, uuid1 in bytes format
seq_number : sequence number used for ignoring channel requests, that was left behind.
arg : contains the payload size following this header
_source_host,_source_port,_source_id enables the receiver to reply to a message
_result_id : updated with the chosen channel in an offer and match
"""
_fields_ = [
("cmd", ctypes.c_short),
("id", ctypes.c_char * 64),
("seq_number", ctypes.c_long),
("arg", ctypes.c_long),
("_source_host", ctypes.c_char * 16),
("_source_port", ctypes.c_int),
("_source_id", ctypes.c_char * 64),
("_result_id", ctypes.c_char * 64)
]
|
runefriborg/pycsp
|
pycsp/parallel/header.py
|
Python
|
mit
| 4,662
|
[
"Brian"
] |
68fafaa687d831173e689018f688828c933ca8865b92cf1905f1c57342d52126
|
import rdflib
from rdflib import URIRef, Literal
from pyontutils import combinators as cmb
from pyontutils.core import OntId, OntTerm, qname
from pyontutils.core import simpleOnt, displayGraph
from pyontutils.namespaces import OntCuries, makeNamespaces
from pyontutils.namespaces import partOf, hasRole, locatedIn
from pyontutils.namespaces import NIFTTL, NIFRID, ilxti, ilxtio, ilxtr, TEMP
from pyontutils.namespaces import owl, rdf, rdfs, oboInOwl, replacedBy, BFO
from pyontutils.namespaces import definition, realizes, hasParticipant, hasPart, hasInput
from pyontutils.combinators import flattenTriples, unionOf, intersectionOf
from pyontutils.combinators import Restriction, EquivalentClass
from pyontutils.combinators import oc, oc_, olit, oec
from pyontutils.combinators import Restriction2, POCombinator
from pyontutils.combinators import annotation, restriction, restrictionN
from nifstd_tools.methods.core import methods_core, asp, proc, tech, prot, _t, restN, oECN, branch
from nifstd_tools.methods.helper import methods_helper, restHasValue
# NOTE if vim is slow it is probably becuase there are
# so many nested parens `:set foldexpr=` fixes the problem
local = rdflib.Namespace(ilxtio[''] + 'methods/')
local_blank = rdflib.Namespace(local[''] + 'blank/')
restSomeHasValue = Restriction2(None, owl.onProperty, owl.someValuesFrom, owl.hasValue)
#restSomeValuesFrom = Restriction(owl.someValuesFrom)
restMinCardValue = Restriction2(rdfs.subClassOf, owl.onProperty, owl.someValuesFrom, owl.minCardinality)
restMaxCardValue = Restriction2(rdfs.subClassOf, owl.onProperty, owl.someValuesFrom, owl.maxCardinality)
restrictionS = Restriction(owl.someValuesFrom)
oECU = EquivalentClass(owl.unionOf)
def t(subject, label, def_, *synonyms):
yield from oc(subject, ilxtr.technique)
yield from olit(subject, rdfs.label, label)
if def_:
yield from olit(subject, definition, def_)
if synonyms:
yield from olit(subject, NIFRID.synonym, *synonyms)
class I:
counter = iter(range(999999))
@property
def d(self):
raise BaseException('do not use')
current = TEMP[str(next(self.counter))]
self.current = current
return current
@property
def b(self):
raise BaseException('do not use')
""" blank node """
current = next(self.counter)
return TEMP[str(current)]
@property
def p(self):
return self.current
i = I()
def DEV(value, current=True):
i.last = value
uri = local[str(value)]
if current:
i.current = uri
return uri
def blank(value):
return local_blank[str(value)]
###
# Methods
###
filename = 'methods'
prefixes = {'local': local,
'blank': local_blank}
imports = (methods_core.iri,
methods_helper.iri,
NIFTTL['bridge/chebi-bridge.ttl'],
NIFTTL['bridge/tax-bridge.ttl'])
#imports = methods_core.iri, methods_helper.iri
comment = 'The ontology of techniques and methods.'
_repo = True
debug = False
triples = (
# biccn
(ilxtr.hasSomething, owl.inverseOf, ilxtr.isSomething),
_t(tech.unfinished, 'Unfinished techniques',
(ilxtr.hasSomething, ilxtr.Something),
synonyms=('incompletely modeled techniques',)
),
_t(DEV(0), 'atlas registration technique',
# ilxtr.hasPrimaryParticipant, restriction(partOf, some animalia)
# TODO this falls into an extrinsic classification technique...
# or a context classification/naming technique...
(ilxtr.isConstrainedBy, ilxtr.parcellationArtifact),
#(ilxtr.assigns, asp.location), # FIXME ilxtr.assigns needs to imply naming...
#(ilxtr.asserts, asp.location), # FIXME ilxtr.asserts needs to imply naming...
(ilxtr.hasPrimaryAspect, asp.locationInAtlas),
# (ilxtr.hasPrimaryAspect, asp.location),
synonyms=('registration technique',
'atlas registration',
'registration')),
# 'spatial transcriptomics'
# 'anatomy registration'
# feducial points
# '3d atlas registration'
# '2d atlas registration'
# 'image registration'
# fresh frozen ventricles are smaller
# 4% pfa non perfused
# 'ROI based atlas registration technique'
# biccn
oc(ilxtr.analysisRole, OntTerm('BFO:0000023', label='role')
),
_t(DEV(1), 'randomization technique', # FIXME this is not defined correctly
(ilxtr.hasPrimaryAspect, asp.informationEntropy),
(ilxtr.hasPrimaryAspect_dAdT, ilxtr.positive),
),
# FIXME see if we really want these?
_t(DEV(2), 'techniques classified by inputs',
(hasInput, ilxtr.materialEntity)),
_t(DEV(3), 'techniques classified by aspects',
(ilxtr.processHasAspect, ilxtr.aspect)),
_t(DEV(4), 'techniques classified by primary aspects',
(ilxtr.hasPrimaryAspect, ilxtr.aspect)),
_t(DEV(5), 'techniques classified by constraining aspects',
(ilxtr.hasConstrainingAspect, ilxtr.aspect),
synonyms=('has constraining aspect',
'technique defined by constraint')),
_t(DEV(6), 'composite techniques',
(hasPart, ilxtr.technique),
comment=('Note that while the notion of atomic techniques is '
'the complement of composite techniques, in an open world '
'it is very hard to show that at technique cannot be broken '
'down any further. Therefore we have to use something other than '
"owl in order to account for techniques that 'at the current time' "
"or 'in the current model' or 'at the current level of abstraction' "
'do not have any explicit parts.')),
_t(DEV(7), 'chemical technique', # FIXME but not molecular? or are molecular subset?
(hasParticipant, # FIXME hasParticipant is incorrect? too broad?
OntTerm('CHEBI:24431', label='chemical entity')
),),
_t(DEV(8), 'molecular technique', # FIXME help I have no idea how to model this same with chemical technique
# TODO FIXME I think it is clear that there are certain techniques which are
# named in a way that is assertional, not definitional
# it seems appropriate for those arbitrarily named techniques to use subClassOf?
(hasInput,
OntTerm('CHEBI:25367', label='molecule')
),),
_t(DEV(9), 'cellular technique',
intersectionOf(ilxtr.technique,
restN(hasInput, OntTerm('SAO:1813327414', label='Cell'))),
intersectionOf(ilxtr.technique,
restN(hasInput,
restN(partOf,
OntTerm('SAO:1813327414', label='Cell')))),
# indeed the equivalence of these two statements is factually correct
# if I have a technique that inputs something, it also inputs all of the parts of it
# including the ones that we have named
equivalentClass=oECN),
_t(DEV(10), 'cell type induction technique',
(ilxtr.hasPrimaryInput, OntTerm('SAO:1813327414', label='Cell')),
(hasInput, ilxtr.inductionFactor),
),
_t(DEV(11), 'molecular cloning technique',
(ilxtr.hasPrimaryInput,
OntTerm('CHEBI:33696', label='nucleic acid')
#OntTerm('CHEBI:16991', label='deoxyribonucleic acid')
# FIXME other options are OntTerm('SAO:454034570') or OntTerm('SO:0000352')
),
# the objective is to isolate a _specific_ sequence of DNA/RNA
# amplification is the next step
(ilxtr.hasPrimaryAspect, asp['count']), # the general objective being to increase the DNA
synonyms=('cloning technique', 'molecular cloning')
),
_t(DEV(12), 'microarray technique',
(hasInput,
# TODO leverage EFO here
# OntTerm(search='microarray', limit=20, prefix='NIFSTD') # nice trick
OntTerm('BIRNLEX:11031', label='Microarray platform')
),
),
# sequencing TODO
_t(tech.sequencing, 'sequencing technique',
intersectionOf(ilxtr.technique,
# FIXME for this to classify property as a molecular technique
# we need a variant of kdp that is an input not just participant...
restrictionN(ilxtr.hasPrimaryInput, ilxtr.thingWithSequence),
restrictionN(ilxtr.hasPrimaryAspect, asp.sequence,),
restrictionN(ilxtr.hasInformationOutput, ilxtr.informationArtifact)),
intersectionOf(ilxtr.technique,
restrictionN(hasPart, tech.sequencing)),
equivalentClass=oECN),
_t(tech._naSeq, 'nucleic acid sequencing technique',
intersectionOf(ilxtr.technique,
restrictionN(ilxtr.hasPrimaryInput,
# hasParticipant molecule or chemical?
#OntTerm(term='nucleic acid')
ilxtr._NApolymer),
restrictionN(ilxtr.hasPrimaryAspect,
#OntTerm(term='sequence')
#OntTerm('SO:0000001', label='region', synonyms=['sequence']) # label='region'
asp.sequence, # pretty sure that SO:0000001 is not really an aspect...
),
restrictionN(ilxtr.hasInformationOutput,
ilxtr.informationArtifact), # note use of artifact
),
intersectionOf(ilxtr.technique,
restrictionN(hasPart, tech._naSeq)),
equivalentClass=oECN),
_t(DEV(13), 'deep sequencing technique',
(hasPart, tech._naSeq),
(ilxtr.isConstrainedBy, prot.deepSequencing), # FIXME circular
synonyms=('deep sequencing',)
),
_t(DEV(14), 'sanger sequencing technique',
(hasPart, tech._naSeq),
(ilxtr.isConstrainedBy, prot.sangerSequencing),
# we want these to differentiate based on the nature of the technqiue
synonyms=('sanger sequencing',)
),
_t(DEV(15), 'shotgun sequencing technique',
(hasPart, tech._naSeq),
(ilxtr.isConstrainedBy, prot.shotgunSequencing),
synonyms=('shotgun sequencing',)
),
_t(tech.scSeq, 'single cell sequencing technique',
# FIXME vs pp -> *NA from a single cell
#ilxtr.technique,
# TODO (hasPart, tech._NALibraryPreparation)
(hasPart, tech.sequencing),
#(hasInput, OntTerm('CHEBI:33696', label='nucleic acid')), # not much protein in a single cell
# hasInput o hasPart some owl:Thing TODO
#(hasInput, OntTerm('SAO:1813327414', label='Cell')), # inputs also need to input all their parts
# this will continue to work if we use hasPart NucleicAcidExtractionIsolationTechnique
# (ilxtr.hasPrimaryParticipantCardinality, 1) # FIXME need this...
#restMaxCardValue(),
restMaxCardValue(ilxtr.hasPrimaryInput, OntTerm('SAO:1813327414', label='Cell'), Literal(1)),
#(ilxtr.hasInformationOutput, ilxtr.informationArtifact), # note use of artifact
synonyms=('single cell sequencing',)
),
_t(tech.snSeq, 'single nucleus sequencing technique',
(hasPart, tech.sequencing),
#(hasInput, OntTerm('CHEBI:33696', label='nucleic acid')), # not much protein in the nucleus...
#(ilxtr.hasPrimaryInput, OntTerm('GO:0005634', label='nucleus')),
restMaxCardValue(ilxtr.hasPrimaryInput, OntTerm('GO:0005634', label='nucleus'), Literal(1)),
# or rather does NOT have input some CytoPlasm
# (ilxtr.hasPrimaryParticipantCardinality, 1) # FIXME need this...
synonyms=('single nucleus sequencing',)
),
(tech.snSeq, owl.disjointWith, tech.scSeq),
_t(tech.libraryPrep, 'nucleic acid library preparation technique',
(ilxtr.hasPrimaryOutput, ilxtr.nucleicAcidLibrary),
synonyms=('library prep', 'library preparation')),
_t(tech.rnaSeq, 'RNA-seq',
intersectionOf(ilxtr.technique,
restN(ilxtr.hasPrimaryInput,
ilxtr.RNApolymer), # RNA but labels are inconsistent
restN(ilxtr.hasPrimaryAspect,
asp.sequence),
restN(hasPart, tech.libraryPrep),
restN(ilxtr.hasInformationOutput,
ilxtr.informationArtifact)),
intersectionOf(ilxtr.technique,
restN(hasPart, tech.rnaSeq)),
synonyms=('RNAseq',),
equivalentClass=oECN),
# Split-seq single cell single nuclei
# SPLiT-seq
_t(DEV(16), 'mRNA-seq',
(hasPart, tech.rnaSeq),
(ilxtr.hasPrimaryInput, OntTerm('SO:0000234')
#(ilxtr.hasPrimaryInput, ilxtr.mRNA
#OntTerm(term='mRNA')
# FIXME wow... needed a rerun on this fellow OntTerm('SAO:116515730', label='MRNA', synonyms=[])
),
#(ilxtr.hasPrimaryAspect, asp.sequence),
#(ilxtr.hasInformationOutput, ilxtr.informationArtifact), # note use of artifact
),
_t(DEV(17), 'snRNA-seq',
#(ilxtr.hasPrimaryParticipant, OntTerm('CHEBI:33697', label='RNA')),
(hasPart, tech.rnaSeq),
#(hasParticipant, OntTerm('GO:0005634', label='nucleus')),
restMaxCardValue(ilxtr.hasPrimaryInput, OntTerm('GO:0005634', label='nucleus'), Literal(1)),
synonyms=('snRNA-Seq',
'snRNAseq',
'sNuc-Seq', # why sequencing community WHY
'single nucleus RNA-seq',)),
_t(DEV(18), 'scRNA-seq',
#(ilxtr.hasPrimaryParticipant, OntTerm('CHEBI:33697', label='RNA')),
(hasPart, tech.rnaSeq),
#(ilxtr.hasPrimaryInput, OntTerm('SAO:1813327414', label='Cell')),
restMaxCardValue(ilxtr.hasPrimaryInput, OntTerm('SAO:1813327414', label='Cell'), Literal(1)),
synonyms=('scRNA-Seq',
'scRNAseq',
'single cell RNAseq',)),
# 'deep-dive scRNA-Seq' # deep-dive vs wide-shallow I think is what this is
_t(DEV(19), 'Patch-seq',
(hasPart, tech.rnaSeq), # FIXME I don't think this modelling is correct/complete
(ilxtr.hasPrimaryInput, ilxtr.RNApolymer),
(hasParticipant, ilxtr.microPipette), # FIXME TODO
synonyms=('Patch-Seq',
'patch seq',)),
_t(tech.mcSeq, 'mC-seq',
#(ilxtr.hasPrimaryInput, ilxtr.openChromatin), # nucleus has part?
#(ilxtr.hasPrimaryInput, ilxtr.methylatedDNA),
(hasPart, tech.libraryPrep),
(ilxtr.hasPrimaryAspect, asp.methylationSequence),
#(ilxtr.hasPrimaryInput, ilxtr.DNA),
(ilxtr.hasPrimaryInput, ilxtr.DNApolymer),
(ilxtr.hasInformationOutput, ilxtr.informationArtifact), # note use of artifact
def_='non CG methylation',
),
_t(DEV(20), 'snmC-seq',
(hasPart, tech.mcSeq),
#(ilxtr.hasPrimaryInput, OntTerm('GO:0005634', label='nucleus')),
restMaxCardValue(ilxtr.hasPrimaryInput, OntTerm('GO:0005634', label='nucleus'), Literal(1)),
synonyms=('snmC-Seq',)),
# mCH
_t(tech.ATACseq, 'ATAC-seq',
(ilxtr.hasSomething, blank(1)),
(hasPart, tech.libraryPrep),
(hasPart, tech.sequencing), # TODO
#(ilxtr.hasInformationOutput, ilxtr.informationArtifact), # note use of artifact
),
_t(DEV(21), 'snATAC-seq',
(hasPart, tech.ATACseq),
#(ilxtr.hasPrimaryInput, OntTerm('GO:0005634', label='nucleus')),
restMaxCardValue(ilxtr.hasPrimaryInput, OntTerm('GO:0005634', label='nucleus'), Literal(1)),
synonyms=('single-nucleus ATAC-seq',
'single nucleus ATAC-seq',)),
_t(DEV(22), 'scATAC-seq',
(hasPart, tech.ATACseq),
#(ilxtr.hasPrimaryInput, OntTerm('SAO:1813327414', label='Cell')),
restMaxCardValue(ilxtr.hasPrimaryInput, OntTerm('SAO:1813327414', label='Cell'), Literal(1)),
def_='enriched for open chromatin',
synonyms=('single-cell ATAC-seq',
'single cell ATAC-seq',)),
_t(DEV(23), 'bulk ATAC-seq',
(hasPart, tech.ATACseq),
(ilxtr.hasSomething, blank(2)),
synonyms=('Bulk-ATAC-seq',)),
#'scranseq' # IS THIS FOR REAL!?
#'ssranseq' # oh boy, this is just me being bad at spelling scrnaseq?
_t(tech.dropSep, 'droplet based separation technique',
(ilxtr.hasSomething, blank(3)),
synonyms=('droplet sequencing', 'Droplet-Sequencing',
'droplet based sequencing technique')
),
# FIXME I think we want to do this this way so that the sequencing techniques
# aren't also classified as separation techniques
cmb.Class(tech.dropSep, restriction(hasParticipant, ilxtr.dropletFormingMicrofluidicsDevice)),
_t(DEV(24), 'Drop-seq',
(hasPart, tech.dropSep), # TODO
(hasPart, tech.rnaSeq), # TODO
(ilxtr.isConstrainedBy, prot.dropSeq), # TODO
# TODO has a specific barcoding technique associated with it
# TODO hasParticipant some droplet formming microfulidics device
#(ilxtr.hasInformationOutput, ilxtr.informationArtifact), # note use of artifact
),
_t(DEV(25), 'DroNc-seq',
(ilxtr.hasSomething, blank(4)),
(hasPart, tech.dropSep), # TODO
(hasPart, tech.rnaSeq), # TODO
# https://www.ncbi.nlm.nih.gov/pubmed/28846088
),
_t(tech.chromium3p, "chromium 3' sequencing",
(ilxtr.hasSomething, blank(5)),
(hasParticipant, ilxtr.chromium3pkit),
(hasPart, tech.dropSep), # TODO
(hasPart, tech.rnaSeq), # TODO
#(ilxtr.hasInformationOutput, ilxtr.informationArtifact), # note use of artifact
def_='a droplet based sequencing library preparation technique',
# snRNA-seq 10x Genomics Chromium v2
# 10x Genomics Chromium V2 scRNA-seq
# 10X (sigh)
synonyms=('10x Genomics sequencing', '10x sequencing', '10x', 'Chromium sequencing'
"10x 3' chemistry", "chromium 3' assay",
"10x Chromium 3' chemsitry",
"10x chromium 3' sequencing",
"Chromium Single Cell 3' Library",
)),
_t(tech.chromium3pv1, "chromium 3' sequencing v1",
tech.chromium3p,
(hasParticipant, ilxtr.chromium3pv1kit),
(hasPart, tech.rnaSeq), # TODO
synonyms=("10x Chromium Single Cell 3' Solution v1",
"10x chromium 3' v1 sequencing",
), # FIXME
comment=("different versions of the chromium 3' chemistry use different barcoding "
'strategies and require different processing pipelines.')),
_t(tech.chromium3pv2, "chromium 3' sequencing v2",
tech.chromium3p,
(hasParticipant, ilxtr.chromium3pv2kit),
(hasPart, tech.rnaSeq), # TODO
synonyms=("10x Chromium Single Cell 3' Solution v2",
"10x chromium 3' v2 sequencing",
), # FIXME
comment=("different versions of the chromium 3' chemistry use different barcoding "
'strategies and require different processing pipelines.')),
(tech.chromium3pv1, owl.disjointWith, tech.chromium3pv2),
_t(DEV(26), 'MAP-seq',
(ilxtr.hasSomething, blank(6)),
(hasPart, tech.sequencing),
(hasPart, tech.libraryPrep),
#(ilxtr.hasInformationOutput, ilxtr.informationArtifact), # note use of artifact
synonyms=('MAPseq',
'MAP seq',
'Multiplexed Analysis of Projections by Sequencing',)),
_t(tech.smartSeq, 'SMART-seq',
(hasPart, tech.rnaSeq),
(hasInput, ilxtr.SMARTSeqKit),
(ilxtr.isConstrainedBy, prot.SMARTSeq),
# Clontech / Takara prep kits feeding Illumina?
comment=('This space is completely loony. '
'See https://www.ncbi.nlm.nih.gov/pmc/articles/PMC5449089/ for a review. '
'This is also a great example of the conflation of protocol with technique.'),
synonyms=('Switching Mechanism at 5\' End of RNA Template sequencing',
'Smart-seq',
'SMART-Seq®',
)),
_t(DEV(27), 'SMART-seq2',
# but illumina also has a page on it ...
# what is going on
(hasPart, tech.rnaSeq),
(ilxtr.isImplementationOf, tech.smartSeq),
(ilxtr.hasSomething, blank(7)),
def_='Improved version of the Smart-seq technique',
synonyms=('Smart-Seq2',
'SMART-seq2')),
_t(DEV(28), 'SMART-seq v4',
(hasPart, tech.rnaSeq),
(ilxtr.isImplementationOf, tech.smartSeq),
def_='Commercial compeitor for Smart-seq2 developed later in time',
synonyms=('SMART-Seq v4',
'SMARTer v4')),
# 'deep smart seq',
_t(tech.anestheticAdministration, 'anesthetic adminstration technique',
# TODO delivered to partOf primaryparticipant
# parent partof primary participant deliver or something
(ilxtr.hasPrimaryParticipant, OntTerm('CHEBI:38867', label='anaesthetic')),),
_t(tech.sedation, 'sedation technique',
# FIXME sedative administration? reading a boring book? physical cooling? bonking on the head?
(ilxtr.hasPrimaryAspect, asp.behavioralActivity), # FIXME asp.activeMovement? doesn't block pain?
(ilxtr.hasPrimaryAspect_dAdT, ilxtr.negative),
(hasParticipant, OntTerm('NCBITaxon:33208', label='Metazoa')),
comment='QUESTION: what is the difference between sedation and anaesthesia?',
synonyms=('sedation',)),
_t(tech.anaesthesia, 'anaesthesia technique',
# anaesthesia is an excellent example of a case where
# just the use of an anaesthetic is not sufficient
# and should not be part of the definition
#(ilxtr.hasPrimaryParticipant,
#cmb.Class(restriction(partOf, OntTerm('UBERON:0001016', label='nervous system')))),
#(hasParticipant, ilxtr.anesthetic), # FIXME has role?
(ilxtr.hasPrimaryAspect, asp.nervousResponsiveness),
(ilxtr.hasPrimaryAspect_dAdT, ilxtr.negative),
(hasPart, tech.anestheticAdministration),
(hasParticipant, OntTerm('NCBITaxon:33208', label='Metazoa')),
synonyms=('anaesthesia',),
),
# local anaesthesia technique
# global anaesthesia technique
_t(DEV(29), 'survival anaesthesia technique',
(ilxtr.hasPrimaryAspect, asp.nervousResponsiveness),
(ilxtr.hasPrimaryAspect_dAdT, ilxtr.negative),
(hasPart, tech.anestheticAdministration),
(hasParticipant, OntTerm('NCBITaxon:33208', label='Metazoa')),
(ilxtr.hasSomething, blank(8)),
synonyms=('anaesthesia with recovery',),
),
_t(DEV(30), 'terminal anaesthesia technique',
(ilxtr.hasPrimaryAspect, asp.nervousResponsiveness),
(ilxtr.hasPrimaryAspect_dAdT, ilxtr.negative),
(hasPart, tech.anestheticAdministration),
(hasParticipant, OntTerm('NCBITaxon:33208', label='Metazoa')),
(ilxtr.hasSomething, blank(9)),
synonyms=('anaesthesia without recovery',
'anaesthesia with no recovery',),
),
_t(tech.ISH, 'in situ hybridization technique', # TODO
intersectionOf(ilxtr.technique, # FIXME
restN(ilxtr.hasPartPriParticipant, ilxtr.RNApolymer), # FIXME non-specic open DNA binding?
# or is it hasPrimaryAspect_dAdS?
restN(ilxtr.hasPrimaryAspect, asp.complementSequencePresent),
restN(hasInput, ilxtr.hybridizationProbe)),
restN(hasPart, tech.ISH),
synonyms=('in situ hybridization', 'ISH'),
equivalentClass=oECN),
#(tech.ISH, owl.equivalentClass, OntTerm('NLXINV:20090610')), # TODO
_t(tech.FISH, 'fluorescence in situ hybridization technique',
(hasPart, tech.ISH),
(hasInput, ilxtr.fluorescentMolecule),
synonyms=('fluorescence in situ hybridization', 'FISH'),
),
_t(tech.smFISH, 'single-molecule fluorescence in situ hybridization technique',
(hasPart, tech.ISH),
(hasInput, ilxtr.fluorescentMolecule),
(ilxtr.hasSomething, blank(10)),
synonyms=('single-molecule fluorescence in situ hybridization',
'single molecule fluorescence in situ hybridization',
'single-molecule FISH',
'single molecule FISH',
'smFISH'),
),
_t(tech.MERFISH, 'multiplexed error-robust fluorescence in situ hybridization technique',
(hasPart, tech.ISH),
(hasInput, ilxtr.fluorescentMolecule),
(ilxtr.hasSomething, blank(11)),
synonyms=('multiplexed error-robust fluorescence in situ hybridization',
'multiplexed error robust fluorescence in situ hybridization',
'multiplexed error-robust FISH',
'multiplexed error robust FISH',
'MERFISH'),
),
_t(DEV(31), 'genetic technique',
(hasParticipant,
# the participant is really some DNA that corresponds to a gene
OntTerm('SO:0000704', label='gene') # prefer SO for this case?
#OntTerm(term='gene', prefix='obo') # representing a gene
),
# FIXME OR has participant some nucleic acid...
),
_t(tech.enrichment, 'enrichment technique',
#(ilxtr.hasSomething, TEMP(42.5)),
(ilxtr.hasPrimaryAspect, asp.proportion),
(ilxtr.hasPrimaryAspect_dAdT, ilxtr.positive),
def_='increase proporation', # the count stays the same
# this is a purification technique
# amplification is a creating technique
),
_t(tech.amplification, 'amplification technique',
(ilxtr.hasPrimaryAspect, asp['count']),
(ilxtr.hasPrimaryAspect_dAdT, ilxtr.positive),
def_='increase number',
),
_t(DEV(32), 'nucleic acid amplification technique',
(ilxtr.hasPrimaryParticipant, OntTerm('CHEBI:33696', label='nucleic acid')),
(ilxtr.hasPrimaryAspect, asp['count']),
(ilxtr.hasPrimaryAspect_dAdT, ilxtr.positive),
),
_t(DEV(33), 'expression manipulation technique',
(ilxtr.hasSomething, blank(12))),
_t(DEV(34), 'conditional expression manipulation technique',
(ilxtr.hasSomething, blank(13))),
_t(DEV(35), 'knock in technique',
(ilxtr.hasSomething, blank(14)),
),
(i.p, ilxtr.hasTempId, OntTerm('HBP_MEM:0000121')),
_t(DEV(36), 'knock down technique',
(ilxtr.hasSomething, blank(15)),
synonyms=('underexpression technique',),
),
# endogenous genetic manipulation HRM 'HBP_MEM:0000119'
# conditional knockout 'HBP_MEM:0000122'
# morpholino 'HBP_MEM:0000124'
# RNA interference 'HBP_MEM:0000123'
# dominant-negative inhibition sigh 'HBP_MEM:0000125'
_t(DEV(37), 'knock out technique',
(ilxtr.hasSomething, blank(16)),
),
(i.p, ilxtr.hasTempId, OntTerm('HBP_MEM:0000120')),
_t(DEV(38), 'mutagenesis technique',
(ilxtr.hasSomething, blank(17))
),
_t(DEV(39), 'overexpression technique',
(ilxtr.hasSomething, blank(18))
),
_t(tech.delivery, 'delivery technique',
intersectionOf(ilxtr.technique,
restN(ilxtr.hasPrimaryParticipant,
ilxtr.materialEntity), # email delivery? fun... not really delivery...
restN(ilxtr.hasPrimaryAspectActualized,
asp.location),
#restN(ilxtr.hasPrimaryAspect_dAdT,
#ilxtr.nonZero)
#),
#intersectionOf(ilxtr.technique,
# FIXME how to use this to start in syringe end in brain?
# maybe using hasTechniqueContext instead?
restN(ilxtr.hasConstrainingAspect, asp.startLocation),
restN(ilxtr.hasConstrainingAspect, asp.endLocation)),
# alternate looking only at different times doesn not work because
# the location at both those times could stay the same :/
# have to also include the value
#intersectionOf(
#restN(ilxtr.hasConstrainingAspect,
#intersectionOf(asp.location, # can't use hasActualizedValue because can't tell times apart?
#restN(ilxtr.hasAspectContext,
#asp.startTime))),
#restN(ilxtr.hasConstrainingAspect,
#intersectionOf(asp.location,
#restN(ilxtr.hasAspectContext,
#asp.endTime)))),
#(ilxtr.hasSomething, TEMP(57.5)),
def_='A technique for moving something from point a to point b.',
equivalentClass=oECN),
_t(DEV(40), 'package delivery technique',
(ilxtr.hasPrimaryAspectActualized, asp.location),
(ilxtr.hasPrimaryParticipant, ilxtr.package),
# the DHL guy case
synonyms=('parcel delivery technique',)
),
_t(DEV(41), 'physical delivery technique',
# i.e. distinct from energy released by chemical means?
# gravity not ATP hydrolysis?
(ilxtr.hasPrimaryAspectActualized, asp.location),
# FIXME
(ilxtr.hasMotiveForce, ilxtr.physicalForce)),
_t(DEV(42), 'diffusion based delivery technique',
(ilxtr.hasPrimaryAspectActualized, asp.location),
# FIXME
(ilxtr.hasMotiveForce, ilxtr.brownianMotion)),
_t(DEV(43), 'bath application technique',
(ilxtr.hasPrimaryAspectActualized, asp.location),
# FIXME
(hasParticipant, ilxtr.bathSolution)),
_t(DEV(44), 'topical application technique',
(ilxtr.hasPrimaryAspectActualized, asp.location),
#(ilxtr.hasTarget, ilxtr.externalSurfaceOfOrganism)
(ilxtr.hasTarget, ilxtr.surface), # TODO surface as a 'generic' black box component
comment='topical application of peanutbutter to bread is allowed',
# potential subclasses, spread, smear, wipe, daub, dust
),
_t(DEV(45), 'mechanical delivery technique',
(ilxtr.hasPrimaryAspectActualized, asp.location),
# FIXME
(ilxtr.hasMotiveForce, ilxtr.mechanicalForce)),
_t(DEV(46), 'rocket delivery technique',
(ilxtr.hasPrimaryAspectActualized, asp.location),
(hasInput, ilxtr.rocket),
comment=('This is here for (among other things) the morbid clinical scenario '
'where someone might need to know that a nerve agent was delivered by '
'rocket and not just released to drift on the wind, because it means '
'that there might be additional complications.')),
_t(OntTerm('BIRNLEX:2135'), 'injection technique',
intersectionOf(ilxtr.technique,
restN(ilxtr.hasSomething, ilxtr.intoSomething), # FIXME
restN(ilxtr.hasPrimaryAspectActualized, asp.location)),
intersectionOf(ilxtr.technique,
restN(ilxtr.hasPrimaryParticipant, ilxtr.somethingThatCanBeInjected)), # FIXME
synonyms=('injection',),
# TODO def_=('must cross some barries or overcome some opposing force or obstacle')
equivalentClass=oECN),
_t(DEV(47), 'ballistic injection technique',
# makes use of phenomena?
(ilxtr.hasSomething, ilxtr.intoSomething), # FIXME
(ilxtr.hasPrimaryAspectActualized, asp.location),
(ilxtr.hasSomething, blank(19))),
_t(DEV(48), 'biolistic injection technique',
# makes use of phenomena?
(ilxtr.hasSomething, ilxtr.intoSomething), # FIXME
(ilxtr.hasPrimaryAspectActualized, asp.location),
(ilxtr.hasSomething, blank(20))),
_t(DEV(49), 'pressure injection technique',
# makes use of phenomena?
(ilxtr.hasSomething, ilxtr.intoSomething), # FIXME
(ilxtr.hasPrimaryAspectActualized, asp.location),
(ilxtr.hasSomething, blank(21))),
_t(DEV(50), 'brain injection technique',
(hasPart, tech.injection), # FIXME we need a way to have primary aspect + target? what is a target?
# in other similar cases we have used hasPart, but then we have to have the
# non-transitive hasPart because
(ilxtr.hasPrimaryParticipant, OntTerm('UBERON:0000955')),
synonyms=('brain injection', 'injection into the brain')),
_t(OntTerm('BIRNLEX:2136'), 'intracellular injection technique',
ilxtr.technique,
(hasPart, tech.injection),
unionOf(restN(hasPart, tech.cellPatching), # vs oneOf? which fails to load?
restN(hasPart, tech.sharpElectrodeTechnique)),
(ilxtr.hasPrimaryParticipant, OntTerm('GO:0005622', label='intracellular')),
#(ilxtr.hasPrimaryParticipant, OntTerm()),
#(ilxtr.hasPrimaryParticipant, OntTerm('SAO:1289190043', label='Cellular Space')), # TODO add intracellular as synonym
synonyms=('intracellular injection',)),
_t(DEV(51), 'viral injection technique',
(hasPart, tech.injection),
(hasParticipant, ilxtr.viralParticle),
def_='a technique for injecting viral particles',
),
_t(DEV(52), 'AAVretro injection technique',
(hasPart, tech.injection),
(hasParticipant, ilxtr.AAVretro),
synonyms=('AAVretro injection',)
),
_t(DEV(53), 'electrical delivery technique',
# FIXME electroporation doesn't actually work this way
(ilxtr.hasPrimaryAspectActualized, asp.location),
(ilxtr.hasConstrainingAspect, asp.electrical),
(ilxtr.hasSomething, blank(22)),
comment='rail gun seems about as close was we can get'
),
_t(tech.poration, 'poration technique',
restN(ilxtr.hasPrimaryParticipant, ilxtr.cellMembrane),
restN(ilxtr.hasPrimaryAspectActualized, asp.permeability),
def_='a technique for making holes in things',
synonyms=('membrane poration technique', 'permeabilization technique')
# FIXME vs general poration?
),
_t(tech.thermalporation, 'thermalporation technique',
intersectionOf(ilxtr.technique,
restN(ilxtr.hasPrimaryParticipant, ilxtr.cellMembrane),
restN(ilxtr.hasPrimaryAspectActualized, asp.permeability),
restN(hasPart, restN(ilxtr.hasPrimaryAspectActualized, asp.temperature))),
synonyms=('heatshock', 'heatshock poration technique'),
),
_t(tech.electroporation, 'electroporation technique',
intersectionOf(ilxtr.technique,
restN(ilxtr.hasPrimaryParticipant, ilxtr.cellMembrane),
restN(ilxtr.hasPrimaryAspectActualized, asp.permeability),
restN(hasParticipant, ilxtr.electricalField)), # FIXME ?
intersectionOf(ilxtr.technique,
restN(hasPart, tech.electroporation)),
# TODO can we add a check that the partOf hasParticipant cell?
synonyms=('electropermeabilization technique',), # FIXME sp?
equivalentClass=oECN),
_t(DEV(54), 'in utero electroporation technique',
(hasPart, tech.electroporation),
(ilxtr.hasPrimaryParticipant, restN(locatedIn, ilxtr.uterus))),
_t(DEV(55), 'single cell electroporation technique',
(hasPart, tech.electroporation),
(hasPart, tech.cellPatching),
# FIXME the target of permeability is not the cell but rather the cell membrane :/
restMaxCardValue(ilxtr.hasPrimaryInput, OntTerm('SAO:1813327414', label='Cell'), Literal(1))),
#_t(TEMP(77.5), 'chemical delivery technique', # not obvious how to define this or if it is used
#(ilxtr.hasSomething, TEMP(77.6))),
_t(DEV(56), 'single neuron electroporation technique',
(hasPart, tech.electroporation),
(hasPart, tech.cellPatching),
# FIXME the target of permeability is not the cell but rather the cell membrane :/
restMaxCardValue(ilxtr.hasPrimaryInput,
OntTerm('SAO:1417703748', label='Neuron'), Literal(1))),
#_t(TEMP(78.5), 'chemical delivery technique', # not obvious how to define this or if it is used
#(ilxtr.hasSomething, TEMP(78.6))),
_t(DEV(57), 'DNA delivery technique',
(ilxtr.hasPrimaryInput, OntTerm('SO:0001235', term='replicon')),
# isConstrainedBy information content of the dna?
(ilxtr.hasPrimaryAspectActualized, asp.location),
),
_t(DEV(58), 'transfection technique',
(ilxtr.hasPrimaryInput, OntTerm('SO:0001235', term='replicon')),
(ilxtr.hasPrimaryAspectActualized, asp.location),
(ilxtr.hasSomething, blank(23)), # TODO hasIntention -> GO gene expression of _that_ gene?
#(ilxtr.hasIntention, 'GO:0010467') # FIXME or DNA amplification
# incorporation into the hosts cellular biology?
# into a cell?
),
_t(DEV(59), 'DNA delivery technique exploiting some active biological process',
(ilxtr.hasPrimaryInput, OntTerm('SO:0001235', term='replicon')),
(ilxtr.hasPrimaryAspectActualized, asp.location),
(ilxtr.hasSomething, blank(24)),
synonyms=('DNA delivery exploiting some pre-existing mechanism technique',),
),
_t(DEV(60), 'DNA delivery via primary genetic code technique',
(ilxtr.hasPrimaryInput, OntTerm('SO:0001235', term='replicon')),
(ilxtr.hasPrimaryAspectActualized, asp.location),
(hasParticipant, ilxtr.primaryHeritableGeneticMaterial)),
#_t(TEMP(84.5), 'DNA delivery via germ line technique', # too cryptic, and is probably actually a process
#(ilxtr.hasPrimaryInput, OntTerm('SO:0001235', term='replicon')),
#(ilxtr.hasPrimaryAspectActualized, asp.location),
#(ilxtr.hasSomething, TEMP(84.6))),
_t(DEV(61), 'DNA delivery via plasmid technique',
(ilxtr.hasPrimaryInput, OntTerm('SO:0001235', term='replicon')),
(ilxtr.hasPrimaryAspectActualized, asp.location),
(hasParticipant, ilxtr.plasmidDNA)),
_t(DEV(62), 'DNA delivery via viral particle technique',
(ilxtr.hasPrimaryInput, OntTerm('SO:0001235', term='replicon')),
(ilxtr.hasPrimaryAspectActualized, asp.location),
# notion of failure due to inadequate titer...
(hasParticipant, ilxtr.viralParticle)),
_t(DEV(63), 'tracing technique',
(hasParticipant, ilxtr.axon),
(ilxtr.hasPrimaryAspect, asp.connectivity),
synonyms=('axon tracing technique',
'axonal tracing technique',
'axon tracing',
'axonal tracing',)),
_t(proc.anterogradeMovement, 'anterograde movement',
BFO['0000015'],
(hasParticipant, ilxtr.materialEntity),
#(ilxtr.processActualizesAspect, asp.distanceFromSoma), # asp and has hasContext
# FIXME aspects for processes
(ilxtr.hasActualPrimaryAspect, asp.distanceFromSoma), # asp and has hasContext
(ilxtr.hasActualPrimaryAspect_dAdT, ilxtr.positive), # TODO not intended ... actual
def_='movement via active or passive means away from the soma of a cell'
),
_t(proc.retrogradeMovement, 'retrograde movement',
BFO['0000015'],
(hasParticipant, ilxtr.materialEntity),
#(ilxtr.processActualizesAspect, asp.distanceFromSoma), # asp and has hasContext
# FIXME aspects for processes
(ilxtr.hasActualPrimaryAspect, asp.distanceFromSoma), # asp and has hasContext
(ilxtr.hasActualPrimaryAspect_dAdT, ilxtr.negative),
def_='movement via active or passive means toward the soma of a cell'
),
_t(DEV(64), 'anterograde tracing technique',
(hasPart, tech.delivery),
(hasParticipant, ilxtr.axon),
(hasPart, proc.anterogradeMovement),
(ilxtr.hasPrimaryAspect, asp.connectivity),
#(ilxtr.hasConstrainingAspect, asp.direction), # need a value... also hasParticipantPartConstrainingAspect?
#(ilxtr.hasConstrainingAspect_value, ilxtr.awayFromSoma), # FIXME actual binding requiress subprocess
# has subprocess (anterograte transport/movement)
# hasPrimaryParticipant ilxtr.materialEntity
# hasPrimaryAspect distanceFromSoma
# hasPrimaryAspect_dAdT ilxtr.negative
synonyms=( 'anterograde tracing',)
),
_t(DEV(65), 'retrograde tracing technique',
(hasPart, tech.delivery),
(hasParticipant, ilxtr.axon),
(hasPart, proc.retrogradeMovement),
(ilxtr.hasPrimaryAspect, asp.connectivity),
#(ilxtr.hasConstrainingAspect, asp.direction), # need a value... also hasParticipantPartConstrainingAspect?
#(ilxtr.hasConstrainingAspect_value, ilxtr.towardSoma), # FIXME actual binding requiress subprocess
# has subprocess
# hasPrimaryParticipant ilxtr.materialEntity
# hasPrimaryAspect distanceFromSoma
# hasPrimaryAspect_dAdT ilxtr.positive
synonyms=('retrograde tracing',)
),
_t(DEV(66), 'bidirectional tracing technique',
(hasPart, tech.delivery),
(hasParticipant, ilxtr.axon),
(hasPart, proc.anterogradeMovement),
(hasPart, proc.retrogradeMovement),
(ilxtr.hasPrimaryAspect, asp.connectivity),
synonyms=('bidirectional tracing',)
),
_t(DEV(67), 'diffusion tracing technique',
(hasParticipant, ilxtr.axon),
(hasPart, tech.delivery),
(ilxtr.hasPrimaryAspect, asp.connectivity),
(ilxtr.hasSomething, blank(25)),
synonyms=('diffusion tracing',)
),
_t(DEV(68), 'transsynaptic tracing technique',
(hasPart, tech.delivery), # agentous delivery mechanism...
(hasParticipant, ilxtr.axon),
(ilxtr.hasPrimaryAspect, asp.connectivity),
(ilxtr.hasParticipant, ilxtr.synapse),
# more than one cell body
synonyms=( 'transsynaptic tracing',)
),
_t(DEV(69), 'monosynapse transsynaptic tracing technique',
(hasParticipant, ilxtr.axon),
(hasPart, tech.delivery),
(ilxtr.hasPrimaryAspect, asp.connectivity),
# more than cell body and more than one nerve
(ilxtr.hasParticipant, ilxtr.synapse), # synapses between at least 2 pairs of cells
(ilxtr.hasSomething, blank(26)),
synonyms=('monosynaptic transsynaptic tracing technique',
'monosynaptic transsynaptic tracing')),
_t(DEV(70), 'multisynapse transsynaptic tracing technique',
(hasParticipant, ilxtr.axon),
(hasPart, tech.delivery),
(ilxtr.hasPrimaryAspect, asp.connectivity),
# more than cell body and more than one nerve
(ilxtr.hasParticipant, ilxtr.synapse), # synapses between at least 2 pairs of cells
(ilxtr.hasSomething, blank(27)),
synonyms=('multisynaptic transsynaptic tracing technique',
'multisynaptic transsynaptic tracing')),
# 'TRIO'
# 'tracing the relationship between input and output'
_t(DEV(71), 'computational technique', # these seem inherantly circulat... they use computation...
ilxtr.technique,
restMinCardValue(ilxtr.isConstrainedBy, ilxtr.algorithm, Literal(1)), # axioms??
(ilxtr.hasDirectInformationInput, ilxtr.informationEntity),
(ilxtr.hasInformationOutput, ilxtr.informationEntity),
# different from?
),
#_t(TEMP(98.5), 'mathematical technique',
#(ilxtr.hasSomething, TEMP(98.6)),
#(ilxtr.isConstrainedBy, ilxtr.algorithm),
#),
_t(tech.statistics, 'statistical technique',
(ilxtr.hasDirectInformationInput, ilxtr.informationEntity),
(ilxtr.hasInformationOutput, ilxtr.informationEntity),
(ilxtr.isConstrainedBy, ilxtr.statisticalAlgorithm),
),
_t(DEV(72), 'simulation technique',
(ilxtr.isConstrainedBy, ilxtr.algorithm),
(ilxtr.hasDirectInformationInput, ilxtr.informationEntity),
(ilxtr.hasInformationOutput, ilxtr.informationEntity),
(ilxtr.hasSomething, blank(28))),
_t(DEV(73), 'storage technique',
(ilxtr.hasPrimaryAspectActualized, asp.location),
# to put away for future use?
# not for immediate use
# sir no longer appearing in this protocol
# leaves the scope of the technique's black box
# put something in a consistent and known location
# so that it can be retrieved again later when needed
#(ilxtr.hasFutureTechique, tech.unstorage)
# changing the primary aspect to a _known_ location
#ilxtr.hasPrimaryAspect_dAdT
(ilxtr.hasIntention, ilxtr.saveForTheFuture),
),
_t(DEV(74), 'preservation technique',
(ilxtr.hasPrimaryAspect, asp.spontaneousChangeInStructure),
# FIXME change in change in some aspect
# expected change in black box if this is not done?
# asp.unbecoming
# FIXME InContents? in anything inside the black box?
(ilxtr.hasPrimaryAspect_dAdT, ilxtr.negative),
),
_t(DEV(75), 'tissue preservation technique',
(ilxtr.hasPrimaryParticipant, ilxtr.tissue),
(ilxtr.hasPrimaryAspect, asp.spontaneousChangeInStructure),
),
_t(tech.localization, 'localization technique',
(ilxtr.hasSomething, blank(29))),
_t(DEV(76), 'colocalization technique',
# FIXME measurement vs putting them together?
ilxtr.technique,
(ilxtr.hasPrimaryParticipant, ilxtr.materialEntity),
restMinCardValue(hasPart, tech.localization, Literal(2)),
(ilxtr.hasPrimaryAspect, asp.location),
(ilxtr.hasInformationOutput, ilxtr.informationEntity),
# the localtion of the primary participants of eac
),
_t(DEV(77), 'image reconstruction technique',
(ilxtr.hasDirectInformationInput, ilxtr.image),
(ilxtr.hasInformationOutput, ilxtr.image),
(ilxtr.isConstrainedBy, ilxtr.inverseProblemAlgorithm)),
_t(tech.tomography, 'tomographic technique',
(ilxtr.hasDirectInformationInput, ilxtr.image), # more than one...
(ilxtr.hasInformationOutput, ilxtr.image),
(ilxtr.isConstrainedBy, ilxtr.radonTransform),
synonyms=('tomography',)),
_t(DEV(78), 'positron emission tomography',
(hasPart, tech.positronEmissionImaging),
(hasPart, tech.tomography),
synonyms=('PET', 'PET scan')),
(i.p, ilxtr.hasTempId, OntTerm('HBP_MEM:0000009')),
# "Single-Proton emission computerized tomography"
# "HBP_MEM:0000010" # TODO
_t(DEV(79), 'stereology technique',
(hasPart, tech.statistics),
(ilxtr.hasSomething, blank(30)),
synonyms=('stereology',)),
_t(DEV(80), 'design based stereology technique',
(ilxtr.hasSomething, blank(31)),
synonyms=('design based stereology',)),
_t(DEV(81), 'spike sorting technique',
(ilxtr.hasDirectInformationInput, ilxtr.timeSeries), # TODO more specific
(ilxtr.hasInformationOutput, ilxtr.timeSeries), # TODO MUCH more specific
#(ilxtr.detects, ilxtr['informationPattern/spikes']) # TODO?
#(ilxtr.hasSomething, TEMP(112.5)),
(ilxtr.isConstrainedBy, ilxtr.spikeSortingAlgorithm),
synonyms=('spike sorting',)),
_t(DEV(82), 'detection technique',
(ilxtr.hasPrimaryParticipant, ilxtr.materialEntity),
(ilxtr.hasInformationOutput, ilxtr.informationEntity),
(ilxtr.detects, ilxtr.materialEntity)),
# detecting something means you are measuring some aspect
# even if it is as simple as the presence or absense of the
# detected phenomena
cmb.Class(i.p, restriction(ilxtr.hasPrimaryAspect, ilxtr.aspect)),
_t(DEV(83), 'identification technique',
(ilxtr.isConstrainedBy, ilxtr.identificationCriteria), # FIXME circular and not what actually differentiates
),
_t(DEV(84), 'characterization technique',
(ilxtr.hasSomething, blank(32))),
_t(DEV(85), 'classification technique',
(ilxtr.isConstrainedBy, ilxtr.classificationCriteria), # FIXME circular and not what actually differentiates
),
_t(DEV(86), 'curation technique',
# ilxtr.isConstrainedBy, curation workflow specification... not helful and not correct
(hasParticipant, OntTerm('NCBITaxon:9606')),
(ilxtr.hasDirectInformationInput, ilxtr.informationArtifact),
(ilxtr.hasInformationOutput, ilxtr.informationArtifact),
(ilxtr.hasSomething, blank(33))),
_t(DEV(87), 'angiographic technique',
(hasPart, ilxtr.xrayImaging),
(ilxtr.knownDetectedPhenomena, restN(partOf, OntTerm('UBERON:0007798'))),
synonyms=('angiography',)),
_t(DEV(88), 'ex vivo technique',
# (hasParticipant, ilxtr.somethingThatUsedToBeAlive),
# more like 'was' a cellular organism
# ah time...
ilxtr.technique,
(ilxtr.hasPrimaryParticipant, OntTerm('NCBITaxon:131567', label='cellular organisms')),
# has part some technique destroying primary participant
# we really really need dead organisms to still have that type
# which restricts our operational definitions a bit, but that is probably a good thing
# 'dead but can still sequence its dna to confirm that -presently- its dna is that of a mouse'
# the technique needs to have killed the exact member otherwise you can kill one mouse and study
# a living one
# (ilxtr.hasPriorTechnique, tech.killing), # FIXME HRMMMMMM with same primary participant...
(ilxtr.hasConstrainingAspect, asp.livingness), # FIXME aliveness?
restHasValue(ilxtr.hasConstrainingAspect_value, Literal(False)), # Literal(False)), # FIXME dataProperty???
#(ilxtr.hasConstrainingAspect, asp.livingness), # FIXME aliveness?
# (ilxtr.hasConstrainingAspect, ilxtr['is']),
synonyms=('ex vivo',),),
_t(tech.inSitu, 'in situ technique', # TODO FIXME
# detecting something in the location that it was originally in
# not in the dissociated remains thereof...
# hasPrimaryParticipantLocatedIn
# and the primary participant is located in / still part of its original part of
# part of the thing that it was part of before the start of _any_ technique
#(ilxtr.hasConstrainingAspect, asp.location),
# the pimary participant is still part of the part of the primary participant of the
# preceeding technique where the input was living
#(ilxtr.hasConstrainingAspect, asp.location),
#(ilxtr.hasConstrainingAspect_value, ilxtr.unchanged), # FIXME
(ilxtr.hasPartPriParticipant, ilxtr.materialEntity),
(ilxtr.hasSomething, blank(34)),
# process has part that has primary aspect actualized location
# process has part that has constraining aspect some aspect matches
# primary participant has part that has aspect matches # TODO not quite
# intersectionOf(
#ilxtr.technique,
#restN(ilxtr.hasPrimaryParticipant,
#restN(hasPart, restN(ilxtr.primaryParticipantIn,
#ilxtr.separationProcessPart)))),
#(ilxtr.hasSomething, TEMP(122.5)),
# primary participant partOf theSameContainingEntity
synonyms=('in situ',),),
(tech.inSitu, owl.disjointWith, tech.inVitro),
_t(DEV(89), 'in vivo technique',
# (hasParticipant, ilxtr.somethingThatIsAlive),
ilxtr.technique,
(ilxtr.hasPrimaryParticipant, OntTerm('NCBITaxon:131567', label='cellular organisms')),
(ilxtr.hasConstrainingAspect, asp.livingness), # FIXME rocks can have aspect aliveness,
# aspects don't tell you about the universality of a result in the way that a quality might
# because right now we only care about the details of the process and what we are measuring
# that is what the value is included explicitly, because some day we might find out that our
# supposedly universal axiom is not, and then we are cooked
restHasValue(ilxtr.hasConstrainingAspect_value, Literal(True)), # FIXME data property Literal(True)),
synonyms=('in vivo',),),
_t(tech.animal, 'in vivo animal technique',
# FIXME vs animal experiment ...
# TODO we probably need a compose operator in addition to hasPart:
# which is to say that this technique is the union of these other techniques ...
(ilxtr.hasPrimaryParticipant, OntTerm('NCBITaxon:33208', label='Metazoa')),
(ilxtr.hasConstrainingAspect, asp.livingness),
restHasValue(ilxtr.hasConstrainingAspect_value, Literal(True)),
),
_t(DEV(90), 'in utero technique',
# has something in
#(hasParticipant, ilxtr.somethingThatIsAliveAndIsInAUterus),
intersectionOf(ilxtr.technique,
restN(ilxtr.hasConstrainingAspect, asp.location),
restN(ilxtr.hasConstrainingAspect_value, ilxtr.uterus)),
intersectionOf(ilxtr.technique,
restN(ilxtr.hasPrimaryParticipant, restN(locatedIn, ilxtr.uterus))),
synonyms=('in utero',),
equivalentClass=oECN),
_t(tech.inVitro, 'in vitro technique',
(ilxtr.hasSomething, blank(35)),
(ilxtr.hasPrimaryParticipant, ilxtr.physiologicalSystemDisjointWithLivingOrganism),
#(ilxtr.hasPrimaryParticipant, thing that was derived from living organsim? no? pure synthesis...),
(hasParticipant, ilxtr.somethingThatIsAliveAndIsInAGlassContainer),
# this is more complicated than it seems,
# the idea that you can have a physiological system
# that is not either derived from some organism ...
synonyms=('in vitro',),),
_t(DEV(91), 'high throughput technique',
(ilxtr.hasSomething, blank(36)),
# TODO has minimum cardinality 'large' on the primary participant
synonyms=('high throughput',),),
_t(DEV(92), 'fourier analysis technique',
(realizes, ilxtr.analysisRole), # FIXME needs to be subClassOf role...
(ilxtr.isConstrainedBy, ilxtr.fourierTransform),
synonyms=('fourier analysis',),),
_t(DEV(93), 'sample preparation technique',
(ilxtr.hasSomething, blank(37)),
# TODO
# (ilxtr.hasIntention, ???)
# to get the thing in the right state so that it can be measured
(ilxtr.hasPrimaryAspect, intersectionOf(asp.nonLocal,
restN(ilxtr.hasContext,
# FIXME again we see that hasContext
# is much broader
ilxtr.constraintImposedByNextStep))),
synonyms=('preparation technique',
'specimine preparation technique',
'sample preparation',
'specimine preparation',),),
_t(tech.dissection, 'dissection technique',
(ilxtr.hasPrimaryOutput, ilxtr.partOfSomePrimaryInput), #FIXME
comment='''
# FIXME need to implement the dual for this
# hasDualTechnique -> hasPrimaryInput -> hasPart <-> removal invariant aka wasPartOf
# vs extraction technique ...
# note that dissection may not actually be a destroying technique in all cases
# for example microdissection or biopsy techniques
''',
synonyms=('dissection',),),
_t(DEV(94), 'atlas guided microdissection technique',
(ilxtr.isConstrainedBy, ilxtr.parcellationAtlas),
(ilxtr.hasPrimaryOutput, ilxtr.partOfSomePrimaryInput), #FIXME
synonyms=('atlas guided microdissection',),),
_t(DEV(95), 'crystallization technique',
(ilxtr.hasPrimaryAspect, asp.latticePeriodicity), # physical order
(ilxtr.hasPrimaryAspect_dAdT, ilxtr.positive),
# cyrstallized vs amorphous
# xray diffraction can tell you what proportion of the whole samle is crystallized (S. Manna)
def_=('A technique for enducing a regular crystal patterning '
'on a set of non-patterend components'),
synonyms=('crystallization',)),
_t(DEV(96), 'crystal quality evalulation technique',
(ilxtr.hasPrimaryInput, ilxtr.materialEntity),
(ilxtr.hasPrimaryAspect, asp.physicalOrderedness),
(ilxtr.hasInformationOutput, ilxtr.informationEntity),
# (ilxtr.hasPrimaryAspect, asp.percentCrystallinity),
# there are many other metrics that can be used that are subclasses
),
_t(DEV(97), 'tissue clearing technique',
(ilxtr.hasPrimaryParticipant, ilxtr.tissue),
(ilxtr.hasPrimaryAspect, asp.transparency), # FIXME
),
_t(DEV(98), 'CLARITY technique',
(ilxtr.hasPrimaryParticipant, ilxtr.tissue),
(ilxtr.isConstrainedBy, prot.CLARITY),
(ilxtr.hasPrimaryAspect, asp.transparency), # FIXME
def_='A tissue clearing technique',
synonyms=('CLARITY',)),
_t(tech.fixation, 'fixation technique',
# prevent decay, decomposition
# modify the mechanical properties to prevent disintegration
# usually crosslinks proteins?
# cyrofixation also for improving the mechanical properties
# literally "fix" something so that it doesn't move or changed, it is "fixed" in time
#(ilxtr.hasSomething, TEMP(135.5)),
#(ilxtr.hasPrimaryAspect, asp.spontaneousChangeInStructure),
#(ilxtr.hasPrimaryAspect_dAdT, ilxtr.negative),
#(ilxtr.hasPrimaryAspect, asp.likelinessToDecompose),
#(ilxtr.hasPrimaryAspect, asp.mechanicalRigidity),
#(ilxtr.hasPrimaryAspect_dAdT, ilxtr.positive),
# TODO I think spontaneous change in structure has to be a requirement
intersectionOf(ilxtr.technique,
restN(ilxtr.hasPrimaryAspectActualized,
asp.spontaneousChangeInStructure),
restN(ilxtr.hasPrimaryAspect_dAdT,
ilxtr.negativeNonZero),
unionOf(restN(ilxtr.hasPrimaryAspectActualized,
asp.stiffness), # mechanical rigidity
restN(ilxtr.hasPrimaryAspectActualized,
asp.elasticity),
restN(ilxtr.hasPrimaryAspectActualized,
asp.spontaneousChangeInStructure))),
intersectionOf(ilxtr.technique,
restN(ilxtr.hasConstrainingAspect, asp.fixedness),
restN(ilxtr.hasConstrainingAspect_dAdT, ilxtr.positiveNonZero),
),
#unionOf(hasAspectChangeCombinator(asp.mechanicalRigidity, ilxtr.positive),
# this approach was simply too verbose and didn't help with classification at all
#hasAspectChangeCombinator(asp.spontaneousChangeInStructure, ilxtr.negative)),
synonyms=('fixation',),
equivalentClass=oECN),
#cmb.Class(tech.fixation,
#),
_t(DEV(99), 'tissue fixation technique',
(ilxtr.hasPrimaryParticipant, ilxtr.tissue),
(ilxtr.hasConstrainingAspect, asp.fixedness),
(ilxtr.hasConstrainingAspect_dAdT, ilxtr.positiveNonZero),
synonyms=('tissue fixation',)),
_t(DEV(100), 'sensitization technique',
# If we were to try to model this fully in the ontology
# then we would have a giant hiearchy of sensitivities to X
# when in fact sensitivity is a defined measure/aspect not
# a fundamental aspect. It is fair to say that there could be
# an aspect for every different way there is to measure sensitivity
# to sunlight since the term is so broad
(ilxtr.hasPrimaryAspectActualized, asp.sensitivity),
),
_t(DEV(101), 'permeabilization technique',
# TODO how to model 'the permeability of a membrane to X'
# check go
(ilxtr.hasPrimaryAspectActualized, asp.permeability),
),
_t(DEV(102), 'chemical synthesis technique',
# involves some chemical reaction ...
# is ioniziation a chemical reaction? e.g. NaCl -> Na+ Cl-??
(ilxtr.hasPrimaryOutput, OntTerm('CHEBI:24431', label='chemical entity')),
),
#_t(TEMP(139.5), 'physical synthesis technique', # this term isn't used very widely
# e.g. making a microchip, doesn't just use chemistry, though it uses some chemistry
# the output is not chemical...
#(ilxtr.hasPrimaryOutput, ilxtr.materialEntity),
#),
_t(DEV(103), 'construction technique',
# build something, or assemble something that cannot be removed
# deconstruction vs destruction, deconstruction usually suggests
# can't be reconstructed? but then we reconstructive surgery
(ilxtr.hasPrimaryOutput, ilxtr.building), # TODO
(ilxtr.hasSomething, blank(38)),
),
_t(DEV(104), 'assembly technique',
# put something together
# suggests that disassembly is possible
(ilxtr.hasPrimaryOutput, ilxtr.materialEntity), # TODO
(ilxtr.hasSomething, blank(39)),
),
_t(DEV(105), 'mixing technique',
#tech.creating, # not entirely clear that this is the case...
#ilxtr.mixedness is circular
(ilxtr.hasSomething, blank(40)),
synonyms=('mixing',),),
_t(DEV(106), 'agitating technique',
#tech.mixing,
# allocation on failure?
# classification depends exactly on the goal
(ilxtr.hasSomething, blank(41)),
synonyms=('agitating',),),
_t(DEV(107), 'stirring technique',
#tech.mixing, # not clear, the intended outcome may be that the thing is 'mixed'...
(ilxtr.hasSomething, blank(42)),
synonyms=('stirring',),),
_t(DEV(108), 'dissolving technique',
(ilxtr.hasSomething, blank(43)),
synonyms=('dissolve',),),
_t(DEV(109), 'husbandry technique',
# FIXME maintenance vs growth
# also how about associated techniques?? like feeding
# include in the oec or 'part of some husbandry technique'??
# alternately we can change it to hasParticipant ilxtr.livingOrganism
# to allow them to include techniques where locally the
# primary participant is something like food, instead of the organism HRM
(ilxtr.hasPrimaryInputOutput, # vs primary participant
OntTerm('NCBITaxon:1', label='root')
),
synonyms=('culture technique', 'husbandry', 'culture'),
),
_t(DEV(110), 'feeding technique',
# metabolism required so no viruses
# TODO how to get this to classify as a maintenance technique
# without having to include the entailment explicitly
# i.e. how do we deal side effects of processes
(ilxtr.hasPrimaryInputOutput, OntTerm('NCBITaxon:131567', label='cellular organisms')),
(hasInput, ilxtr.food), # this works because hasPart food allocation technique will lift to this
synonyms=('feeding',)),
# this is a legitimate case where there is no easy
# way to communicate a side effect of feeding
# I will thing a bit more on this but I think it is the easiest way
# maybe a general class axiom or something like that could do it
# FIXME the issue is that the primary aspects will then start to fight...
# there might be a way to create a class that will work using
# ilxtr.hasSideEffectTechnique or ilxtr.hasSideEffect?
_t(DEV(111), 'high-fat diet feeding technique',
(ilxtr.hasPrimaryInputOutput, OntTerm('NCBITaxon:131567', label='cellular organisms')),
(ilxtr.hasPrimaryAspectActualized, asp.weight),
(hasInput, ilxtr.highFatDiet),
),
_t(DEV(112), 'mouse circadian based high-fat diet feeding technique',
(ilxtr.hasPrimaryInputOutput, OntTerm('NCBITaxon:10090', label='Mus musculus')),
# ie that if one were to measure rather than specify
# the mouse should be in in the same phase during the activity
(ilxtr.hasConstrainingAspect, asp.circadianPhase), # TODO? 'NBO:0000169'
(ilxtr.hasPrimaryAspectActualized, asp.weight),
(hasInput, ilxtr.highFatDiet),
),
_t(DEV(113), 'mouse age based high-fat diet feeding technique',
# TODO there are a whole bunch of other high fat diet feeding techniques
# 'MmusDv:0000050'
# as opposed to the primary aspect being the current point in the cyrcadian cycle
(ilxtr.hasPrimaryInputOutput, OntTerm('NCBITaxon:10090', label='Mus musculus')),
(ilxtr.hasConstrainingAspect, OntTerm('PATO:0000011', label='age')), # FIXME not quite right
(ilxtr.hasPrimaryAspectActualized, asp.weight), # FIXME not quite right
(hasInput, ilxtr.highFatDiet),
# (hasInput, ilx['researchdiets/uris/productnumber/D12492']), # too specific
),
_t(DEV(114), 'bacterial culture technique',
#(hasParticipant, OntTerm('NCBITaxon:2', label='Bacteria <prokaryote>')),
(ilxtr.hasPrimaryInputOutput, OntTerm('NCBITaxon:2')), # FIXME > 1 label
synonyms=('bacterial culture',),),
_t(tech.cellCulture, 'cell culture technique',
(ilxtr.hasPrimaryInputOutput, OntTerm('SAO:1813327414', label='Cell')),
# maybe useing subClassOf instead of equivalentClass?
synonyms=('cell culture',),),
# I think this is the right way to add 'non-definitional' restrictions to a technique
cmb.Class(tech.cellCulture,
restriction(ilxtr.hasConstrainingAspect, asp.temperature),
restriction(hasInput, ilxtr.cultureMedia)),
_t(DEV(115), 'yeast culture technique',
(ilxtr.hasPrimaryInputOutput, OntTerm('NCBITaxon:4932', label='Saccharomyces cerevisiae')),
synonyms=('yeast culture',),),
_t(DEV(116), 'tissue culture technique',
(ilxtr.hasPrimaryInputOutput, ilxtr.tissue),
synonyms=('tissue culture',),),
_t(DEV(117), 'slice culture technique',
(ilxtr.hasPrimaryInputOutput, intersectionOf(ilxtr.brainSlice,
ilxtr.physiologicalSystem)),
synonyms=('slice culture',),),
_t(DEV(118), 'open book preparation technique',
tech.maintaining,
(hasInput,
OntTerm('UBERON:0001049', label='neural tube')
#OntTerm(term='neural tube', prefix='UBERON') # FIXME dissected out neural tube...
),
(ilxtr.hasSomething, blank(44)),
synonyms=('open book culture', 'open book preparation'),),
_t(DEV(119), 'fly culture technique',
(ilxtr.hasPrimaryInputOutput,
OntTerm('NCBITaxon:7215', label='Drosophila <flies,genus>')
#OntTerm(term='drosophila')
),
synonyms=('fly culture',),),
_t(DEV(120), 'rodent husbandry technique',
(ilxtr.hasPrimaryInputOutput,
OntTerm('NCBITaxon:9989', label='Rodentia') # FIXME population vs individual?
),
synonyms=('rodent husbandry', 'rodent culture technique'),),
_t(DEV(121), 'enclosure design technique', # FIXME design technique? produces some information artifact?
(ilxtr.hasSomething, blank(45))),
_t(DEV(122), 'housing technique',
(ilxtr.hasSomething, blank(46)),
synonyms=('housing',),
),
_t(DEV(123), 'mating technique',
ilxtr.technique,
restMinCardValue(hasParticipant, ilxtr.sexuallyReproducingOrgansim, Literal(2)),
synonyms=('mating',),
),
_t(DEV(124), 'watering technique',
(ilxtr.hasPrimaryInputOutput, OntTerm('NCBITaxon:131567', label='cellular organisms')),
(hasInput, ilxtr.water), # no output
synonyms=('watering',),
),
_t(tech.contrastEnhancement, 'contrast enhancement technique',
#restMinCardValue(ilxtr.hasParticipantPartConstrainingAspect, ilxtr.aspect, Literal(1)),
#restMinCardValue(ilxtr.hasConstrainingAspect, ilxtr.aspect, Literal(1)),
intersectionOf(ilxtr.technique,
restN(ilxtr.hasParticipantPartPrimaryAspect, ilxtr.aspect),
restN(ilxtr.hasPartNotPart,
intersectionOf(restN(ilxtr.hasPrimaryAspectActualized, asp.location),
# FIXME need to be able to say that pp part primary aspect and
# part pp constraining aspect are the same
restMinCardValue(ilxtr.hasConstrainingAspect,
ilxtr.aspect,
Literal(1))))),
#intersectionOf(ilxtr.technique,
#restN(ilxtr.hasPrimaryAspect, asp.contrast),
#restN(ilxtr.hasPrimaryAspect_dAdT, ilxtr.positive)),
#intersectionOf(ilxtr.technique,
# FIXME vs contrast detection
#restN(ilxtr.hasProbe, ilxtr.materialEntity)),
synonyms=('contrast enhancement',
'material contrast enhancement technique',),
equivalentClass=oECN),
_t(DEV(125), 'tagging technique',
(ilxtr.hasSomething, blank(47))),
_t(tech.histology, 'histological technique',
# is this the assertional/definitional part where we include everything?
(ilxtr.hasPrimaryParticipant, ilxtr.tissue),
#(ilxtr.hasSomething, TEMP(172.5)),
synonyms=('histology',)),
_t(OntTerm('BIRNLEX:2107'), 'staining technique', # TODO integration
(ilxtr.hasSomething, blank(48))),
_t(DEV(126), 'immunochemical technique',
(ilxtr.hasSomething, blank(49))),
_t(DEV(127),'immunocytochemical technique',
(ilxtr.hasSomething, blank(50)),
(hasInput, ilxtr.cell),
synonyms=('immunocytochemistry technique',
'immunocytochemistry')),
_t(OntTerm('NLXINV:20090609'), 'immunohistochemical technique', # TODO
(ilxtr.hasSomething, blank(51)),
(hasInput, ilxtr.tissue),
synonyms=('immunohistochemistry technique',
'immunohistochemistry')),
(OntTerm('NLXINV:20090609'), ilxtr.hasTempId, OntTerm("HBP_MEM:0000115")),
# TODO "HBP_MEM:0000116"
# "Immunoelectron microscopy"
_t(DEV(128), 'direct immunohistochemical technique',
(ilxtr.hasSomething, blank(52)),
synonyms=('direct immunohistochemistry technique',
'direct immunohistochemistry')),
_t(DEV(129), 'indirect immunohistochemical technique',
(ilxtr.hasSomething, blank(53)),
synonyms=('indirect immunohistochemistry technique',
'indirect immunohistochemistry')),
_t(tech.stateBasedContrastEnhancement, 'state based contrast enhancement technique',
#tech.contrastEnhancement, # FIXME compare this to how we modelled fMRI below? is BOLD and _enhancement_?
(ilxtr.hasSomething, blank(54)),
),
_t(ilxtr.separationProcessPart, 'separation process',
# FIXME this definition would also work for homogenization/mixing
# each part has a different location based on the aspect vs
# each part has the 'same' location based on the aspect (e.g. density of fat vs protein in milk)
intersectionOf(BFO['0000015'], # infers correctly but include for clarity
restN(partOf, tech.separation),
restN(ilxtr.hasPrimaryAspectActualized, asp.location),
#restN(ilxtr.hasPrimaryAspect_dAdT, ilxtr.nonZero), # TODO
restN(ilxtr.hasConstrainingAspect, ilxtr.aspect),
),
def_='this is probably too detailed a model, better to have a measure of separateness',
equivalentClass=oECN),
_t(tech.separating, 'separating technique',
intersectionOf(
ilxtr.technique,
restN(ilxtr.hasPrimaryAspectActualized, asp.homogenaity), # TODO vs Constraining
restN(ilxtr.hasPrimaryAspect_dAdT, ilxtr.negativeNonZero)),
intersectionOf(
ilxtr.technique,
restN(ilxtr.hasPrimaryParticipant,
restN(hasPart, restN(ilxtr.primaryParticipantIn,
ilxtr.separationProcessPart)))),
equivalentClass=oECN),
_t(tech.separation, 'separation technique (old)',
# TODO owl.inverseOf homogenization
# the aspect of each part is to separate it by class
# the location of each of its parts
# the rule for transforming an aspect of the _parts_ into
# the location aspect is the key differentiator
#(ilxtr.knownDifferentiatingPhenomena, ),
#restN(hasPart, )
#(ilxtr.hasPrimaryAspectActualized, asp.location), # TODO we need a clearer subclass for this
intersectionOf(
ilxtr.technique,
restN(ilxtr.hasPrimaryParticipant,
restN(hasPart, restN(ilxtr.primaryParticipantIn,
ilxtr.separationProcessPart)))),
#intersectionOf(
#restN(partOf, i.p),
#restN(ilxtr.hasPrimaryAspectActualized, asp.location),
#restN(ilxtr.hasConstrainingAspect, ilxtr.aspect))))))),
#intersectionOf(ilxtr.tchnique,
#restN(ilxtr.hasPartPriAspect, restN(hasPart, ()))
#),
#intersectionOf(ilxtr.technique,
#restN(ilxtr.hasPartPart,
#intersectionOf(restN(ilxtr.hasPrimaryAspectActualized, asp.location),
#ilxtr.primaryParticipantPartOfPrimaryParticipantOfParent,
# intentionally not requiring this to be a technique
#restMinCardValue(ilxtr.hasConstrainingAspect,
#ilxtr.aspect,
#Literal(1))))),
#intersectionOf(ilxtr.technique,
#restN(ilxtr.hasParticipantPartPrimaryAspectActualized, asp.location),
#restMinCardValue(ilxtr.hasParticipantPartConstrainingAspect,
#ilxtr.aspect,
#Literal(1))),
#restMinCardValue(ilxtr.hasParentPrimaryAspect, ilxtr.aspect, Literal(1)),
# primary input has parts that can all actualize on the same set of aspects
# hasConstrainingAspect maybe??
#(ilxtr.hasConstrainingAspect, ilxtr.aspect),
# VS FIXME TODO does the cardinality restriction work for auto subclassing?
# FIXME hasConstrainingAspect is implicitly on the primary participant, these are on its parts...
#restMinCardValue(ilxtr.hasConstrainingAspect, ilxtr.aspect, Literal(1)),
#(ilxtr.hasSomething, TEMP(183.5)),
equivalentClass=oECN),
_t(DEV(130), 'filtering technique',
(hasPart, intersectionOf(
ilxtr.allocatingProcessPart,
restN(ilxtr.hasConstrainingAspect, asp.size)))),
_t(DEV(131), 'sorting technique',
ilxtr.technique,
# FIXME has part vs has member?
(ilxtr.hasPrimaryParticipant,
restN(hasPart,
restN(ilxtr.primaryParticipantIn,
intersectionOf(ilxtr.separationProcessPart,
restN(ilxtr.hasPrimaryAspect,
asp.categoryAssigned), # FIXME nonLocal
restN(ilxtr.hasConstrainingAspect,
# another true predicate
asp.isCategoryMember))))),
# FIXME named => there is a larger black box where the name _can_ be measured
# hasPrimaryParticipant partOf (hasAspect ilxtr.aspect)
# or is it partOf (hasPrimaryAspect ilxtr.aspect)?
# note that for this approach axioms appear automatically as
# the unresolved names
#(ilxtr.hasParticipantPartPrimaryAspectActualized, asp.category),
#(ilxtr.hasParticipantPartConstrainingAspect, ilxtr.aspect)
),
_t(DEV(132), 'extraction technique',
(hasParticipant, ilxtr.extract), # FIXME circular
),
_t(tech.precipitation, 'precipitation technique',
(hasParticipant, ilxtr.precipitate), # FIXME circular
),
_t(DEV(133), 'pull-down technique',
(hasPart, tech.precipitation),
# allocation enrichement
(ilxtr.hasSomething, blank(55)),),
_t(DEV(134), 'isolation technique',
# enrichment
(ilxtr.hasSomething, blank(56)),),
_t(DEV(135), 'purification technique',
# enrichment
(ilxtr.hasSomething, blank(57)),),
_t(DEV(136), 'fractionation technique',
(ilxtr.hasSomething, blank(58)),),
_t(DEV(137), 'chromatography technique',
(ilxtr.hasParticipantPartPrimaryAspectActualized, asp.location),
(ilxtr.hasParticipantPartConstrainingAspect, asp.partitionCoefficient),
synonyms=('chromatography',),),
_t(DEV(138), 'distillation technique',
(ilxtr.hasParticipantPartConstrainingAspect, asp.boilingPoint),
(ilxtr.hasParticipantPartConstrainingAspect, asp.condensationPoint),
#(ilxtr.knownDifferentiatingPhenomena, asp.boilingPoint),
#(ilxtr.knownDifferentiatingPhenomena, asp.condensationPoint),
synonyms=('distillation',),),
_t(tech.electrophoresis, 'electrophoresis technique',
#(ilxtr.hasSomething, TEMP(196.5)),
(ilxtr.hasParticipantPartPrimaryAspectActualized, asp.location),
(ilxtr.hasParticipantPartConstrainingAspect, asp.size),
(ilxtr.hasParticipantPartConstrainingAspect, asp.charge),
(ilxtr.hasParticipantPartConstrainingAspect, asp.bindingAffinity), # FIXME ... this is qualified...
synonyms=('electrophoresis',),),
_t(DEV(139), 'centrifugation technique',
intersectionOf(ilxtr.technique,
restN(hasInput, ilxtr.centrifuge)),
intersectionOf(ilxtr.technique,
restN(ilxtr.hasParticipantPartPrimaryAspectActualized, asp.location),
restN(ilxtr.hasParticipantPartConstrainingAspect, asp.size), # TODO hasImplicitMeasurement
restN(ilxtr.hasParticipantPartConstrainingAspect, asp.shape),
restN(ilxtr.hasParticipantPartConstrainingAspect, asp.density)),
#(ilxtr.knownDifferentiatingPhenomena, asp.size), # TODO hasImplicitMeasurement
#(ilxtr.knownDifferentiatingPhenomena, asp.shape),
#(ilxtr.knownDifferentiatingPhenomena, asp.density),
synonyms=('centrifugation',),
equivalentClass=oECN),
_t(DEV(140), 'ultracentrifugation technique',
(hasInput, ilxtr.ultracentrifuge),
synonyms=('ultracentrifugation',),),
_t(DEV(141), 'sampling technique',
# selection technqiue, not a separation technique
# it has to do with picking
(ilxtr.hasSomething, blank(59)),),
_t(DEV(142), 'selection technique',
(ilxtr.hasSomething, blank(60)),),
_t(DEV(143), 'blind selection technique',
(ilxtr.hasSomething, blank(61)),),
_t(DEV(144), 'random selection technique',
(ilxtr.hasSomething, blank(62)),),
_t(DEV(145), 'targeted selection technique',
(ilxtr.hasSomething, blank(63)),),
_t(DEV(146), 'biological activity measurement technique',
(ilxtr.hasPrimaryParticipant, ilxtr.physiologicalSystem),
(ilxtr.hasPrimaryAspect, asp.biologicalActivity), # TODO
(ilxtr.hasInformationOutput, ilxtr.informationEntity),
synonyms=('activity measurement technique', 'bioassay')),
_t(DEV(147), 'observational technique',
(ilxtr.hasPrimaryParticipant, ilxtr.materialEntity),
(ilxtr.hasInformationOutput, ilxtr.informationEntity),
# non numerical? interpretational?
(ilxtr.hasSomething, blank(64)),
synonyms=('observation', 'observation technique'),),
_t(DEV(148), 'procurement technique',
intersectionOf(ilxtr.technique,
restN(ilxtr.hasPrimaryAspectActualized, asp.location),
restN(ilxtr.hasConstrainingAspect, asp.endLocation),
restN(ilxtr.hasPrimaryParticipant, # FIXME vs hasPrimaryOutput...
# could have part some delivery technique
# distingushed from delivery technique in that it only
# cares about the _endpoint_ not start and end
OntTerm('BFO:0000040', label='material entity')
#OntTerm(term='material entity', prefix='BFO')
)),
#(ilxtr.hasPrimaryOutput, # primary outputs imply creation
#OntTerm('BFO:0000040', label='material entity')
#OntTerm(term='material entity', prefix='BFO')
#),
def_='A technique for getting or retrieving something.',
synonyms=('acquisition technique', 'procurement', 'acquistion', 'get'),
equivalentClass=oECN),
# naming
oc(tech.naming, ilxtr.technique),
olit(tech.naming, rdfs.label, 'naming'),
olit(tech.naming, definition ,
('Naming is an assertional process that is orthogonal to measuring.'
'Names may be assigned as a product of measurements, but the assignment '
'of a name can only be based on aspects of the thing, the name can never be '
'an aspect of the thing. Names may also be assigned based on aspects of the '
'process that produced the thing, or the prvious state of the thing. '
'For example a protein dissociated from its original cell/tissue no longer '
'contains sufficient information to reconsturct where it came from based on '
'any measurements that can be made on it beyond the species that it came from '
'and maybe where the individual lived if there are enough atoms to do an isotope test.'
'A cell on the other hand may very well have enough information in its RNA and DNA to '
'allow for a bottom up assignment of a name based on its gene expression pattern.')),
_t(tech.ising, 'ising technique',
(ilxtr.hasPrimaryAspect, asp['is']),
def_=('Ising techniques are techniques that affect whether a thing \'is\' or not. '
'Whether they primary participant \'is\' in this context must shall be determined '
'by whether measurements made on the putative primary particiant '
'provide data that meet the necessary and sufficient criteria for the putative primary '
'participant to be assigned the categorical name as defined by the '
'primary particiant\'s owl:Class. For example if the primary particiant of a technique '
'is 100ml of liquid water, then a boiling technique which produces gaseous water from '
'liquid water negatively affects the isness of the 100ml of liquid water because we can '
'no longer assign the name liquid water to the steam that is produced by boiling.')),
olit(tech.ising, rdfs.comment,
('Because \'isness\' or \'being\' is modelled as an aspect it is implied that '
'\'being\' in this context depends entirely on some measurement process and some '
'additional process for classifying or categorizing the object based on that measurement, '
'so that it can be assigned a name. The objective here is to demistify the process of '
'assigning a name to a thing so that it will be possible to provide exact provenance '
'for how the assignment of the name was determined.')),
# allocating
_t(ilxtr.allocatingProcessPart, 'allocating process',
intersectionOf(BFO['0000015'], # infers correctly but include for clarity
restN(partOf, tech.allocating), # FIXME would be nice to have a generator on this...
restN(ilxtr.hasPrimaryAspectActualized, asp.location)),
equivalentClass=oECN),
_t(tech.allocating, 'allocating technique',
intersectionOf(ilxtr.technique,
restN(ilxtr.hasPrimaryAspectActualized,
# FIXME intrinsic extrinsic issue :/
asp.location)),
# FIXME allocation of a part of the primary participant
intersectionOf(
restN(ilxtr.hasPrimaryParticipant,
restN(hasPart, restN(ilxtr.primaryParticipantIn,
ilxtr.allocatingProcessPart)))),
# FIXME no information output
def_=('Allocating techniques move things around without changing how their participants '
'are named. More accurately they move them around without changing any part of their '
'functional defintions which are invariant as a function of their location.'),
equivalentClass=oECN),
_t(tech.aliquoting, 'aliquoting technique',
# TODO should be subClassOf allocating
(ilxtr.hasSomething, blank(65)),
),
# disjointness
(tech.allocating, owl.disjointWith, tech.measuring), # i am an idiot
(tech.allocating, owl.disjointWith, tech.probing),
(tech.allocating, owl.disjointWith, tech.ising),
(tech.measuring, owl.disjointWith, tech.probing),
(tech.measuring, owl.disjointWith, tech.ising),
(tech.probing, owl.disjointWith, tech.ising),
#cmb.Class(None, disjointUnionOf(tech.allocating, tech.measuring, tech.ising, tech.probing)),
# why doesn't this work?
# measured does not imply actualized
# FIXME what about tech.actualizing? i think it is ising or allocating
# FIXME this causes issues
# we may need to split hasPrimaryAspect into hasPrimaryAspectMeasure hasPrimaryAspectActualized
# better to just add hasPrimaryAspectActualized for allocation and friends since pretty much all
# aspects end up being measured one way or another, they have to be
#cmb.Class(tech.allocating,
#cmb.Pair(owl.disjointWith, # overkill using oec but it works
#oc_.full_combinator(oec(
#ilxtr.technique,
#restrictionN(ilxtr.hasInformationOutput,
#ilxtr.informationEntity))))),
# measuring
_t(tech.measuring, 'measuring technique',
# TODO is detection distinct from measurement if there is no explicit symbolization?
(ilxtr.hasPrimaryAspect, ilxtr.aspect), # if you are measuring something you had bettered know what you are measuring
#(ilxtr.detects, ilxtr.materialEntity), # FIXME
(ilxtr.hasInformationOutput, ilxtr.informationEntity), # observe that this not information artifact
# FIXME has primary input?
(ilxtr.hasPrimaryParticipant, ilxtr.materialEntity #OntTerm('BFO:0000001', label='entity')
# FIXME vs hasPrimaryParticipant
# go with material entity since seeing data processing under measurement seems off
),
synonyms=('measure', 'measurment technique'),
),
# actualizing
_t(tech.actualizing, 'actualizing technique',
intersectionOf(ilxtr.technique,
restN(ilxtr.hasPrimaryAspectActualized, ilxtr.aspect)),
intersectionOf(ilxtr.technique,
restN(ilxtr.hasParticipantPartPrimaryAspectActualized, ilxtr.aspect)),
# taking action to make the value
#unionOf(tech.ising, tech.allocating),
def_='a technique that realizes a value of some aspect',
synonyms=('actualize',),
equivalentClass=oECN),
# probing
_t(tech.probing, 'probing technique', # manipulating, poking, purturbing, changing state
(ilxtr.hasProbe, owl.Thing),
#(ilxtr.hasProbe, OntTerm('BFO:0000040', label='material entity')),
# FIXME technically could be an informational entity?
# if I probe someone by speaking latin but they do not respond
# vs if they do it is not the physical content of the sounds
# it is how they interact with the state of the other person's brain
def_=('Probing techniques attempt (intende) to change the state of a thing without changing '
'how it is named. Hitting something with just enough light to excite but not to '
'bleach would be one example, as would poking something with a non-pointy stick.'
),
),
_t(tech.creating, 'creating technique', # FIXME mightent we want to subclass off of these directly?
intersectionOf(ilxtr.technique,
restN(ilxtr.hasPrimaryOutput, ilxtr.materialEntity)),
intersectionOf(ilxtr.technique,
restN(ilxtr.hasPrimaryAspect, asp['is']),
restN(ilxtr.hasPrimaryAspect_dAdT, ilxtr.positiveNonZero)),
synonyms=('synthesis technique',),
equivalentClass=oECN),
(tech.creating, owl.disjointWith, tech.destroying),
# NOTE ! creating and destroying are only with respect to the primary participant
# it is entirely possible to have a composite technique that has two parts
# one of which is destroying and the other of which is creating
# and to link those two parts in such as way as to assert the symmetry
# attempt to create a class that explicitly does not have relationships to the same other class
#oc(ilxtr._helper0),
#olit(ilxtr._helper0, 'that have classes that are primary participants and outputs of the same technique'),
#disjointwith(oec(None, ilxtr.technique,
#*restrictions((ilxtr.hasPrimaryParticipant,
#OntTerm('continuant', prefix='BFO'))))),
#obnode(object_predicate_combinator(rdf.type, owl.Class),
#oec_combinator(ilxtr.technique,
#(ilxtr.hasPrimaryParticipant,)
#(hasOutput,))),
_t(tech.destroying, 'destroying technique',
# owl.unionOf with not ilxtr.disjointWithOutput of? not this will not work
(ilxtr.hasPrimaryAspect, asp['is']),
(ilxtr.hasPrimaryAspect_dAdT, ilxtr.negativeNonZero),),
_t(tech.maintaining, 'maintaining technique',
# if these were not qualified by the primary participant
# then this would be both a creating and a destroying technique
intersectionOf(ilxtr.technique,
restN(ilxtr.hasPrimaryAspect, asp['is']),
restN(ilxtr.hasPrimaryAspect_dAdT, ilxtr.zero)), # FIXME value?
intersectionOf(ilxtr.technique,
restN(ilxtr.hasPrimaryInputOutput, ilxtr.materialEntity)),
synonyms=('maintenance technique',),
equivalentClass=oECN),
_t(tech.analysis, 'analysis technique',
(realizes, ilxtr.analysisRole),
synonyms=('analysis',),),
_t(DEV(149), 'data processing technique',
(ilxtr.hasDirectInformationInput, ilxtr.informationEntity),
(ilxtr.hasInformationOutput, ilxtr.informationEntity),
synonyms=('data processing', 'data transformation technique'),),
_t(DEV(150), 'image processing technique',
(ilxtr.hasDirectInformationInput, ilxtr.image),
(ilxtr.hasInformationOutput, ilxtr.image),
# some subpart may have the explicit output it just requires the direct input
synonyms=('image processing',),),
_t(tech.sigproc, 'signal processing technique',
(ilxtr.hasDirectInformationInput, ilxtr.timeSeries),
(ilxtr.hasInformationOutput, ilxtr.timeSeries),
synonyms=('signal processing',),),
_t(DEV(151), 'signal filtering technique',
# FIXME aspects of information entities...
# lots of stuff going on here...
tech.sigproc,
(ilxtr.hasInformationPrimaryAspect, asp.spectrum),
(ilxtr.hasInformationPrimaryAspect_dAdT, ilxtr.negativeNonZero),
(ilxtr.hasInformationPrimaryParticipant, ilxtr.timeSeries), # FIXME
synonyms=('signal filtering',),
),
_t(tech.ephys, 'electrophysiology technique',
# TODO is this one of the cases where partonomy implies techniqueness?
# note ephys is not itself a measurement technique? stimulation can occur without measurement
# technique and (hasPart some i.p)
intersectionOf(ilxtr.technique,
restN(hasInput, ilxtr.ephysRig)),
intersectionOf(ilxtr.technique,
restN(ilxtr.hasPrimaryAspect, asp.electromagnetic), # FIXME...
restN(ilxtr.hasPrimaryParticipant, ilxtr.physiologicalSystem)),
synonyms=('electrophysiology', 'electrophysiological technique'),
equivalentClass=oECN),
(tech.ephys, ilxtr.hasTempId, OntTerm('HBP_MEM:0000014')),
_t(tech.IRDIC, 'IR DIC video microscopy',
(hasInput, ilxtr.IRCamera),
(ilxtr.detects, ilxtr.infaredLight), # FIXME should be bound to the camera and propagate
(hasInput, ilxtr.DICmicroscope),
(ilxtr.hasInformationOutput, ilxtr.image),
(ilxtr.hasPrimaryParticipant, ilxtr.materialEntity), # how to deal with the parts of a primary input?
# TODO
),
_t(DEV(152), 'in vitro IR DIC slice electrophysiology',
#(hasPart, tech.IRDIC),
(hasInput, ilxtr.IRCamera),
(hasInput, ilxtr.DICmicroscope),
(ilxtr.hasPrimaryInput, ilxtr.acuteBrainSlice), # how to deal with the parts of a primary input?
(ilxtr.hasPrimaryAspect, asp.electrical),
(hasPart, ilxtr.cellPatching),
(hasPart, ilxtr.eClamp),
(ilxtr.hasInformationOutput, ilxtr.timeSeries),
),
_t(tech.ephysRecording, 'electrophysiology recording technique',
ilxtr.technique,
(ilxtr.hasPrimaryParticipant, ilxtr.physiologicalSystem),
#oneOf((hasInput, ilxtr.physiologicalSystem),
#(hasInput, OntTerm('NCBITaxon:1'))),
(ilxtr.hasPrimaryAspect, asp.electrical), # FIXME...
#(ilxtr.hasPrimaryParticipant, ilxtr.physiologicalSystem),
#(hasPart, tech.ephys),
(ilxtr.hasInformationOutput, ilxtr.timeSeries),
synonyms=('electrophysiology recording',),
),
_t(tech.contrastDetection, 'contrast detection technique',
# a subclass could be differential contrast to electron scattering or something...
#(ilxtr.hasPrimaryAspect_dAdPartOfPrimaryParticipant, ilxtr.nonZero), # TODO FIXME this is MUCH better
(ilxtr.hasPrimaryAspect, asp.contrast), # contrast to something? FIXME this seems a bit off...
(ilxtr.hasPrimaryAspect_dAdS, ilxtr.nonZero),
synonyms=('contrast detection',),
),
_t(tech.microscopy, 'microscopy technique',
(hasInput, ilxtr.microscope), # electrophysiology microscopy techinque?
# can't use hasParticipant because we need it to be distinct from 'microscope production technique'
(ilxtr.hasInformationOutput, ilxtr.image),
(ilxtr.hasPrimaryParticipant, ilxtr.materialEntity),
synonyms=('microscopy',),
),
_t(DEV(153), 'microscope production technique',
(ilxtr.hasPrimaryOutput, ilxtr.microscope),
),
_t(DEV(154), 'recording electrode production technique',
(ilxtr.hasPrimaryOutput, ilxtr.recordingElectrode),
),
_t(DEV(155), 'micropipette production technique',
(ilxtr.hasPrimaryOutput, ilxtr.microPipette)),
_t(DEV(156), 'microscope repair technique',
(ilxtr.hasPrimaryInputOutput, ilxtr.microscope)),
_t(tech.lightMicroscopy, 'light microscopy technique',
(hasInput, OntTerm('BIRNLEX:2112', label='Optical microscope')), # FIXME light microscope !
(ilxtr.detects, ilxtr.visibleLight), # TODO photos?
(ilxtr.hasInformationOutput, ilxtr.image),
(ilxtr.hasPrimaryParticipant, ilxtr.materialEntity),
#(ilxtr.detects, OntTerm(search='visible light', prefix='obo')),
#(ilxtr.detects, OntTerm(search='photon', prefix='NIFSTD')),
#(hasParticipant, OntTerm(term='visible light')), # FIXME !!! detects vs participant ???
synonyms=('light microscopy',)),
_t(DEV(157), 'confocal microscopy technique',
(hasInput, OntTerm('BIRNLEX:2029', label='Confocal microscope')),
(ilxtr.detects, ilxtr.visibleLight),
(ilxtr.isConstrainedBy, OntTerm('BIRNLEX:2258', label='Confocal imaging protocol')),
(ilxtr.hasInformationOutput, ilxtr.image),
(ilxtr.hasPrimaryParticipant, ilxtr.materialEntity),
synonyms=('confocal microscopy',)),
_t(DEV(158), 'phase contrast microscopy technique', # TODO
(hasInput, ilxtr.phaseContrastMicroscope), # FIXME circular
(ilxtr.detects, ilxtr.visibleLight), # FIXME true??
(ilxtr.hasInformationOutput, ilxtr.image),
(ilxtr.hasPrimaryParticipant, ilxtr.materialEntity),
synonyms=('phase contrast microscopy',)),
_t(tech.imaging, 'imaging technique',
(ilxtr.hasPrimaryAspect, ilxtr.aspect),
# FIXME... contrast isnt quite right
# it is more total energy flux in a spectrum to which the detection medium is opaque
# over some area with some resolution, though the difference is that imaging is
# spatial in nature where as pure particle detection is less spatial and more event based
#(ilxtr.hasPrimaryAspect, asp.contrast),
#(ilxtr.hasPrimaryAspect, asp.detectedThingPresent),
(ilxtr.hasPrimaryParticipant, ilxtr.materialEntity), # the thing to be imaged
(ilxtr.hasInformationOutput, ilxtr.image),
def_='Imaging is the process of forming an image.',
synonyms=('imaging',),
#equivalentClass=oECN
),
_t(DEV(159), 'functional brain imaging',
intersectionOf(ilxtr.technique,
# TODO figure out how to tie in the bFA, maybe make it 'functional' contrast
# suitably nebulous to allow for many operational definitions
#restN(ilxtr.hasPrimaryAspect, asp.boundFunctionalAspect), # this is interpretational
restN(ilxtr.hasPrimaryAspect, asp.contrast), # this is what is actually measured
restN(ilxtr.hasInformationOutput, ilxtr.image),
restN(ilxtr.hasPrimaryParticipant,
OntTerm('UBERON:0000955', label='brain'))),
# FIXME this is very verbose...
intersectionOf(ilxtr.technique,
#restN(ilxtr.hasPrimaryAspect, asp.boundFunctionalAspect),
restN(ilxtr.hasPrimaryAspect, asp.contrast), # this is what is actually measured
restN(ilxtr.hasInformationOutput, ilxtr.image),
restN(ilxtr.hasPrimaryParticipant,
restN(partOf,
OntTerm('UBERON:0000955', label='brain')))),
#restN(ilxtr.hasPrimaryParticipant,
#unionOf(OntTerm('UBERON:0000955', label='brain'),
#restN(partOf,
#OntTerm('UBERON:0000955', label='brain')))),
#(ilxtr.hasPrimaryAspect, asp.anySpatioTemporalMeasure), # FIXME and thus we see that 'functional' is a buzzword!
#(ilxtr.hasPrimaryAspect_dAdS, ilxtr.nonZero),
synonyms=('imaging that relies on contrast provided by differential aspects of some biological process',),
equivalentClass=oECN),
(i.p, ilxtr.hasTempId, OntTerm('HBP_MEM:0000007')),
_t(DEV(160), 'photographic technique',
(ilxtr.detects, ilxtr.photons), # FIXME acctually it detects energy in _any_ form including electrons
#(ilxtr.hasPrimaryAspect, asp.contrast),
(ilxtr.hasPrimaryParticipant, ilxtr.materialEntity), # the scene
(ilxtr.hasInformationOutput, ilxtr.photograph),
synonyms=('photography',),
),
_t(tech.positronEmissionImaging, 'positron emission imaging',
(ilxtr.hasPrimaryParticipant, ilxtr.materialEntity),
(ilxtr.detects, ilxtr.positron),
#(ilxtr.hasPrimaryAspect, asp.contrast), # contrast to positrons... TODO model as gca?
(ilxtr.hasInformationOutput, ilxtr.image),
(ilxtr.detects, ilxtr.positron)),
cmb.Class(None, # FIXME this doesn't work because it can't fill in the specifics...
intersectionOf(restN(ilxtr.detects, ilxtr.materialEntity),
restN(ilxtr.hasPrimaryAspect, asp.contrast)),
oECN(restN(ilxtr.hasPrimaryAspect,
intersectionOf(asp.contrast,
restN(ilxtr.hasMaterialContext, ilxtr.interactingPhenomena),
restN(ilxtr.hasAspectContext, asp.dynamicRange))))),
_t(tech.opticalImaging, 'optical imaging',
# FIXME TODO what is the difference between optical imaging and light microscopy?
(ilxtr.hasPrimaryParticipant, ilxtr.materialEntity),
(ilxtr.detects, ilxtr.visibleLight), # owl:Class photon and hasWavelenght range ...
#(ilxtr.hasPrimaryAspect, ilxtr.contrast),
(ilxtr.hasInformationOutput, ilxtr.image),
synonyms=('light imaging', 'visible light imaging'),
),
(tech.opticalImaging, ilxtr.hasTempId, OntTerm("HBP_MEM:0000013")),
_t(DEV(161), 'intrinsic optical imaging',
#tech.opticalImaging,
#tech.contrastDetection,
# this is a good counter example to x-ray imaging concernts
# because it shows clearly how
# "the reflectance to infared light by the brain"
# that is not a thing that is a derived thing I think...
# it is an aspect of the black box, it is not a _part_ of the back box
(ilxtr.hasPrimaryParticipant, ilxtr.materialEntity),
#(ilxtr.hasProbe, ilxtr.visibleLight), # FIXME
(ilxtr.detects, ilxtr.visibleLight), # FIXME
#(ilxtr.hasPrimaryAspect, asp.contrast),
#(ilxtr.hasPrimaryAspect, ilxtr.intrinsicSignal), # this is a 'known phenomena'
#(ilxtr.knownProbedPhenomena, ilxtr.intrinsicSignal),
(ilxtr.hasSomething, ilxtr.intrinsicSignal),
(ilxtr.hasInformationOutput, ilxtr.image),
synonyms=('intrinsic signal optical imaging',),
),
_t(ilxtr.xrayImaging, 'x-ray imaging',
#tech.imaging,
(ilxtr.hasPrimaryParticipant, ilxtr.materialEntity),
(ilxtr.hasInformationOutput, ilxtr.image),
#(ilxtr.hasPrimaryAspect, asp.contrast),
(ilxtr.detects, ilxtr.xrays),
# VS contrast in the primary aspect being the signal created by the xrays...
# can probably expand detects in cases where there are non-aspects...
# still not entirely sure these shouldn't all be aspects too...
# TODO need a way to deal with the fact that what we really care about here
# is the connection to the fact that there is some pheonmena that has
# differential contrast to the pheonmena
), # owl:Class photon and hasWavelenght range ...
_t(tech.MRI_ImageProcessing, 'magnetic resonance image processing',
# the stuff that goes on inside the scanner
# or afterward to produce the 'classic' output data
# this way we can create as many subclasses of contrast as we need
(ilxtr.hasDirectInformationInput, ilxtr.image), # TODO raw mri image
(ilxtr.hasPrimaryAspect, asp.contrast), # contrast to something? FIXME this seems a bit off...
(ilxtr.hasPrimaryAspect_dAdS, ilxtr.nonZero),
(ilxtr.hasInformationOutput, ilxtr.spatialFrequencyImageStack), # TODO FIXME
(ilxtr.hasSomething, blank(66)),
),
_t(tech.MRI, 'magnetic resonance imaging',
#tech.imaging,
intersectionOf(ilxtr.technique,
restN(ilxtr.hasPrimaryParticipant, ilxtr.materialEntity),
restN(hasInput, ilxtr.MRIScanner),
# NRM is an aspect not one of the mediators FIXME
restN(ilxtr.hasPrimaryAspect, asp.nuclearMagneticResonance),
# FIXME nmr vs nrm contrast... detection vs measurement
#restN(ilxtr.hasPrimaryAspect, asp.NMRcontrast),
restN(hasPart, tech.MRI_ImageProcessing)),
intersectionOf(ilxtr.technique,
restN(hasPart, tech.MRI)),
# as long as the primaryAspect is subClassOf asp.nuclearMagneticResonance then we are ok
# and we won't get duplication of primary aspects
synonyms=('MRI', 'nuclear magnetic resonance imaging'),
equivalentClass=oECN),
_t(tech.fMRI, 'functional magnetic resonance imaging',
(ilxtr.isConstrainedBy, prot.fMRI),
(hasPart, tech.MRI),
(hasPart, tech.fMRI_ImageProcessing),
),
_t(tech.fMRI_ImageProcessing, 'fMRI image processing',
# FIXME hasPart MRI image processing?
(ilxtr.hasDirectInformationInput, ilxtr.image),
(ilxtr.hasInformationOutput, ilxtr.image),
(ilxtr.hasSomething, blank(67)),
),
olit(tech.fMRI, rdfs.comment,
('In contrast to previous definitions of fMRI technqiues, here we try to '
'remain agnostic as possible about the actual phenomena that is being detected '
'since it is still a matter of scientific exploration. The key is that the process '
'follows a protocol that sets the proper parameters on the scanner (and uses the '
'proper scanner).')),
_t(tech.dwMRI, 'diffusion weighted magnetic resonance imaging',
# FIXME the primary participant isn't really water so much as it is
# the water that is part of the primary participant...
intersectionOf(ilxtr.technique,
restrictionN(hasPart, tech.MRI),
# TODO 'knownProbedPhenomena' or something similar
# TODO
#restrictionN(ilxtr.hasPrimaryParticipant, OntTerm('CHEBI:15377', label='water')),
restrictionN(hasPart, tech.dwMRI_ImageProcessing)),
intersectionOf(ilxtr.technique,
restrictionN(ilxtr.isConstrainedBy, prot.dwMRI)),
synonyms=('dwMRI', 'diffusion weighted nuclear magnetic resonance imaging'),
equivalentClass=oECN),
_t(tech.dwMRI_ImageProcessing, 'diffusion weighted MRI image processing',
(ilxtr.hasDirectInformationInput, ilxtr.image),
(ilxtr.hasInformationOutput, ilxtr.image),
(ilxtr.hasSomething, blank(68)),
),
_t(proc.diffusion, 'diffusion process',
BFO['0000015'],
(hasParticipant, ilxtr.materialEntity), # collective material entity?
(ilxtr.hasActualPrimaryAspect, asp.allocation), # dispersion dispersal
def_=('a process where particles spread out due to random motion')),
_t(tech.DTI, 'diffusion tensor imaging', # FIXME very much
intersectionOf(ilxtr.technique,
restrictionN(hasPart, tech.dwMRI),
restrictionN(hasPart, tech.DTI_ImageProcessing)),
intersectionOf(ilxtr.technique,
restrictionN(ilxtr.isConstrainedBy, prot.DTI)),
# FIXME not clear that this should be in the intersection...
# it seems like it may make more sense to do these as unions?
# TODO kpp kdp
intersectionOf(ilxtr.technique,
restrictionN(hasInput, ilxtr.MRIScanner),
# NOTE using processes is prior knowledge
restrictionN(hasPart, proc.diffusion)),
synonyms=('DTI',),
equivalentClass=oECN),
_t(tech.DTI_ImageProcessing, 'diffusion tensor image processing',
(ilxtr.hasDirectInformationInput, ilxtr.image),
(ilxtr.hasInformationOutput, ilxtr.image),
(ilxtr.hasSomething, blank(69)),
),
_t(DEV(162), 'electroencephalography',
(ilxtr.hasSomething, blank(70)),
(ilxtr.hasPrimaryAspect, asp.electrical),
(ilxtr.hasPrimaryParticipant, ilxtr.physiologicalSystem), # FIXME uberon part of should work for this?
(ilxtr.hasInformationOutput, ilxtr.timeSeries),
synonyms=('EEG',)),
(i.p, ilxtr.hasTempId, OntTerm("HBP_MEM:0000011")),
_t(DEV(163), 'magnetoencephalography',
(ilxtr.hasSomething, blank(71)),
(ilxtr.hasPrimaryParticipant, OntTerm('NCBITaxon:40674', 'Mammalia')),
(ilxtr.hasPrimaryAspect, asp.magnetic),
(ilxtr.hasInformationOutput, ilxtr.timeSeries),
synonyms=('MEG',)),
(i.p, ilxtr.hasTempId, OntTerm("HBP_MEM:0000012")),
# modification techniques
_t(DEV(164), 'modification technique',
# FIXME TODO
(ilxtr.hasPrimaryAspect, asp.isClassifiedAs),
# is classified as
synonyms=('state creation technique', 'state induction technique')
),
_t(tech.activityModulation, 'activity modulation technique',
(ilxtr.hasProbe, ilxtr.materialEntity), # FIXME some pheonmena... very often light...
(ilxtr.hasPrimaryAspect, asp.boundFunctionalAspect),
synonyms=('modulation technique', 'modulation', 'activity modulation')),
_t(DEV(165), 'activation technique',
(ilxtr.hasProbe, ilxtr.materialEntity), # FIXME some pheonmena... very often light...
(ilxtr.hasPrimaryAspect, asp.boundFunctionalAspect),
# hasPrimaryAspect some aspect of the primary participant which FOR THAT PARTICIPANT
# has been defined as functional owl.hasSelf?
# hasSelf asp.functional !??! no, not really what we want
#(hasPart, ilxtr.),
(ilxtr.hasPrimaryAspect_dAdT, ilxtr.positiveNonZero),
),
_t(DEV(166), 'deactivation technique',
(ilxtr.hasProbe, ilxtr.materialEntity), # FIXME some pheonmena... very often light...
(ilxtr.hasPrimaryAspect, asp.boundFunctionalAspect), # FIXME this is more state?
(ilxtr.hasPrimaryAspect_dAdT, ilxtr.negativeNonZero),
),
_t(tech.killing, 'killing technique',
(ilxtr.hasPrimaryAspect, asp.aliveness),
(ilxtr.hasPrimaryAspect_dAdT, ilxtr.negativeNonZero),
),
_t(tech.euthanasia, 'euthanasia technique',
(ilxtr.hasPrimaryAspect, asp.aliveness),
(ilxtr.hasPrimaryAspect_dAdT, ilxtr.negativeNonZero),
synonyms=('euthanasia',),
),
_t(tech.perfusion, 'perfusion technique',
(ilxtr.hasSomething, blank(72)),
),
_t(DEV(167), 'intracardial perfusion technique',
(ilxtr.hasSomething, blank(73)),
synonyms=('intracardial perfusion',),
),
_t(DEV(168), 'pharmacological technique',
intersectionOf(ilxtr.technique,
#restN(ilxtr.hasProbe, ilxtr.molecule), # FIXME on a living system?
restN(hasInput, restN(hasRole, OntTerm('CHEBI:23888')))),
intersectionOf(ilxtr.technique,
#restN(ilxtr.hasProbe, ilxtr.molecule), # FIXME on a living system?
restN(hasInput, restN(hasRole, OntTerm('CHEBI:38632')))),
synonyms=('pharmacology',),
equivalentClass=oECN),
_t(DEV(169), 'ttx bath application technique',
(hasParticipant, ilxtr.bathSolution),
(ilxtr.hasPrimaryAspectActualized, asp.location), # in bath?
(ilxtr.hasPrimaryInput, OntTerm('CHEBI:9506')),
),
_t(DEV(170), 'photoactivation technique',
(ilxtr.hasProbe, ilxtr.photons),
(ilxtr.hasPrimaryAspect, asp.boundFunctionalAspect),
(ilxtr.hasPrimaryAspect_dAdT, ilxtr.positiveNonZero),
),
_t(DEV(171), 'photoinactivation technique',
(ilxtr.hasProbe, ilxtr.photons),
(ilxtr.hasPrimaryAspect, asp.boundFunctionalAspect),
(ilxtr.hasPrimaryAspect_dAdT, ilxtr.negativeNonZero),
),
_t(DEV(172), 'photobleaching technique',
(ilxtr.hasProbe, ilxtr.photons),
(ilxtr.hasSomething, blank(74)),
),
_t(DEV(173), 'photoconversion technique',
(ilxtr.hasProbe, ilxtr.photons),
(ilxtr.hasSomething, blank(75)),
),
_t(DEV(174), 'molecular uncaging technique',
# FIXME caged molecule?
(ilxtr.hasPrimaryParticipant, OntTerm('CHEBI:25367', label='molecule')),
(ilxtr.hasPrimaryAspect, asp.boundFunctionalAspect),
(ilxtr.hasPrimaryAspect_dAdT, ilxtr.positiveNonZero),
synonyms=('uncaging', 'uncaging technique')
),
_t(DEV(175), 'physical modification technique',
# FIXME for all physical things is it that the aspect is physical?
# or that there is actually a physical change induced?
(ilxtr.hasSomething, blank(76)),
),
_t(DEV(176), 'ablation technique',
(ilxtr.hasSomething, blank(77)),
),
_t(DEV(177), 'blinding technique',
(ilxtr.hasPrimaryAspect, asp.vision),
(ilxtr.hasPrimaryAspect_dAdT, ilxtr.negativeNonZero),
),
_t(DEV(178), 'crushing technique',
# tissue destruction technique
(ilxtr.hasSomething, blank(78)),
),
_t(DEV(179), 'deafferenting technique',
# tissue destruction technique
(ilxtr.hasSomething, blank(79)),
),
_t(DEV(180), 'depolarization technique',
(ilxtr.hasPrimaryAspect, asp.voltage),
(ilxtr.hasPrimaryAspect_dAdT, ilxtr.positiveNonZero), # or is it neative (heh)
# yes this is confusing, but cells have negative membrane potentials
),
_t(DEV(181), 'hyperpolarization technique',
(ilxtr.hasPrimaryAspect, asp.voltage),
(ilxtr.hasPrimaryAspect_dAdT, ilxtr.negativeNonZero),
),
_t(DEV(182), 'illumination technique',
# as distinct from a technique for illuminating a page in a medieval text
#tech.agnostic, # TODO agnostic techniques try to do nothing scientific usually
# they are purely goal driven
#(ilxtr.phenomena, ilxtr.photons),
(ilxtr.hasPrimaryAspectActualized, asp.lumenance),
(ilxtr.hasPrimaryAspect_dAdT, ilxtr.positiveNonZero),
),
_t(DEV(183), 'lesioning technique',
(hasPart, tech.surgical), # is this true
# has intention to destory some subset of the nervous system
(ilxtr.hasSomething, blank(80)),
),
_t(DEV(184), 'sensory deprivation technique',
(ilxtr.hasPrimaryAspect, asp.sensory),
(ilxtr.hasPrimaryAspect_dAdT, ilxtr.negativeNonZero),
(ilxtr.hasSomething, blank(81)),
),
_t(DEV(185), 'transection technique',
(hasPart, tech.surgical),
(ilxtr.hasSomething, blank(82)),
),
_t(DEV(186), 'stimulation technique',
#(ilxtr.hasPrimaryAspect, ilxtr.physiologicalActivity), # TODO
(ilxtr.hasProbe, ilxtr.materialEntity),
(ilxtr.hasPrimaryAspect, asp.biologicalActivity),
(ilxtr.hasPrimaryAspect_dAdT, ilxtr.positiveNonZero),
),
#cmb.Class(None, # FIXME this is incorrect the equivalence is asymmetric
# and the way we are using biological activity does not imply phsyiology
#intersectionOf(ilxtr.technique,
#restN(ilxtr.techniqueHasAspect, asp.biologicalActivity)),
#oECN(intersectionOf(ilxtr.technique,
#restN(ilxtr.hasPrimaryParticipant, ilxtr.physiologicalSystem)))),
_t(DEV(187), 'physical stimulation technique', # FIXME another use of physical
(ilxtr.hasSomething, blank(83)),
(ilxtr.hasProbe, ilxtr.mechanicalForce), # but is this physical?
def_='A technique using mechanical force to enduce a state change on a system.',
synonyms=('mechanical stimulation technique',)
),
_t(DEV(188), 'electrical stimulation technique',
#(ilxtr.hasProbe, asp.electrical), # FIXME the probe should be the physical mediator
#(ilxtr.hasProbe, ilxtr.electricalPhenomena), # electircal field?
(ilxtr.hasProbe, ilxtr.electricalField), # electircal field?
(ilxtr.hasPrimaryAspect, asp.electrical),
(ilxtr.hasSomething, blank(84)),
),
_t(tech.stim_Magnetic, 'magnetic stimulation technique',
# TODO need a way to accomodate the stimulation of biological activity
# with the stimulating phenomena
# has intention to stimulate???
(ilxtr.hasProbe, ilxtr.magneticField), # FIXME TODO duality between stimulus and response...
(ilxtr.hasPrimaryAspect, asp.magnetic),
),
_t(DEV(189), 'transcranial magnetic stimulation technique',
(ilxtr.hasProbe, ilxtr.magneticField),
(ilxtr.hasPrimaryAspect, asp.magnetic),
(ilxtr.hasSomething, blank(85)),
),
_t(DEV(190), 'cortico-cortical evoked potential technique',
(ilxtr.hasSomething, blank(86)),
),
_t(DEV(191), 'microstimulation technique',
(ilxtr.hasSomething, blank(87)),
),
_t(tech.cutting, 'cutting technique',
(ilxtr.hasPrimaryInput, ilxtr.cuttingTool), # FIXME tool use...
# TODO
),
_t(tech.surgical, 'surgical technique',
(ilxtr.hasSomething, blank(88)),
# any technique that involves the destruction of some anatomical structure
# which requires healing (if possible)
(hasPart, tech.cutting), # FIXME obviously too broad
synonyms=('surgery',),),
cmb.Class(DEV(192), cmb.Pair(rdfs.label, Literal('reconstructive surgery')), # FIXME TODO
oec(restN(hasPart, tech.surgical),
restN(ilxtr.hasIntention, ilxtr.toReconstruct))),
_t(DEV(193), 'biopsy technique',
(hasPart, tech.surgical), # FIXME
#tech.maintaining, # things that have output tissue that don't unis something
# this is not creating so it is not a primary output
# if maintaining and creating are disjoin on primary inputs then have to be careful
# about usage of hasOutput vs hasPrimaryOutput
(ilxtr.hasPrimaryOutput, ilxtr.tissue), # TODO
),
_t(DEV(194), 'craniotomy technique',
(hasPart, tech.surgical), # FIXME
(ilxtr.hasSomething, blank(89)),
def_='Makes a hold in the cranium (head).',
),
_t(DEV(195), 'durotomy technique',
(hasPart, tech.surgical), # FIXME
(ilxtr.hasSomething, blank(90)),
def_='Makes a hold in the dura.',
),
_t(DEV(196), 'transplantation technique',
(hasPart, tech.surgical), # FIXME
(ilxtr.hasSomething, blank(91)),
synonyms=('transplant',)
),
_t(DEV(197), 'implantation technique',
(hasPart, tech.surgical), # FIXME
(ilxtr.hasSomething, blank(92)),
),
_t(DEV(198), 'stereotaxic technique',
(hasPart, tech.surgical), # FIXME
(hasInput, ilxtr.stereotax),
(ilxtr.isConstrainedBy, ilxtr.stereotaxiCoordinateSystem),
),
_t(DEV(199), 'behavioral technique', # FIXME this is almost always actually some environmental manipulation
# asp.behavioral -> 'Something measurable aspect of an organisms behavior. i.e. the things that it does.'
(ilxtr.hasPrimaryAspect, asp.behavioral),
),
_t(DEV(200), 'behavioral conditioning technique',
(ilxtr.hasSomething, blank(93)),
def_='A technique for producing a specific behavioral response to a set of stimuli.', # FIXME
synonyms=('behavioral conditioning', 'conditioning', 'conditioning technique')
),
_t(DEV(201), 'environmental manipulation technique',
# FIXME extremely broad, includes basically everything we do in science that is not
# done directly to the primary subject
(ilxtr.hasPrimaryParticipant, ilxtr.notTheSubject),
),
_t(DEV(202), 'environmental enrichment technique',
(ilxtr.hasSomething, blank(94)),
synonyms=('behavioral enrichment technique',)
# and here we see the duality between environment and behavior
),
_t(DEV(203), 'dietary technique',
# FIXME this doesn't capture feeding and watering as we might expect
#ilxtr.technique,
# unionOf hasPart dietary technique OR hasPrimaryParticipant food
intersectionOf(ilxtr.technique,
restN(ilxtr.hasPrimaryInput, ilxtr.food_and_water),
restN(ilxtr.hasPrimaryAspectActualized, asp.allocation)),
intersectionOf(ilxtr.technique,
restN(hasPart, i.p)),
#unionOf(intersectionOf(
#restrictionN(ilxtr.hasPrimaryParticipant, ilxtr.food_and_water), # metabolic input
#restrictionN(ilxtr.hasPrimaryAspect, asp.allocation)),
#restrictionN(hasPart, i.p))
equivalentClass=oECN),
_t(DEV(204), 'dietary enrichment technique',
(hasInput, ilxtr.food_and_water),
# NOTE the aspect could be amount or diversity
(ilxtr.hasPrimaryAspect_dAdT, ilxtr.positiveNonZero),
),
_t(DEV(205), 'dietary restriction technique',
#(ilxtr.hasSomething, TEMP(299.5)),
(hasInput, ilxtr.food_and_water), # metabolic input
(ilxtr.hasPrimaryAspect_dAdT, ilxtr.negativeNonZero), # FIXME may need to use has part?
# reduction in some metabolic input
),
_t(DEV(206), 'food deprivation technique',
(ilxtr.hasPrimaryInput, ilxtr.food),
(ilxtr.hasPrimaryAspectActualized, asp.allocation),
(ilxtr.hasPrimaryAspect_dAdT, ilxtr.negativeNonZero),
# the above is correct, use hasPart
# where the food amount is decresed, how to bind food to negative
# do we have to use has part?!
#hasPart, food
#(hasParticipant, ilxtr.food),
#(ilxtr.hasConstrainingAspect, asp.amount),
#cmb.Class(ilxtr.food,
#asp.amount, ilxtr.negative),
#hasAspectChangeCombinator(asp.amount, ilxtr.negative),
synonyms=('starvation technique',
'food restriction technique',
)
),
_t(DEV(207, current=False), 'technique that makes use of food deprivation',
(hasPart, i.p),),
_t(DEV(208), 'water deprivation technique',
(ilxtr.hasPrimaryInput, ilxtr.water),
(ilxtr.hasPrimaryAspectActualized, asp.allocation),
(ilxtr.hasPrimaryAspect_dAdT, ilxtr.negativeNonZero),
synonyms=('water restriction technique',
'water restriction',
)
),
_t(tech.sectioning, 'sectioning technique',
#tech.destroying, # ok to assert here
# easier than having say inputs are not outputs every time
# NOTE: the thing to be sectioned is thus the primary participant
# conservation of mass/energy implies that it is also a creating technique
# if viewed from the persective of the sections
# we should be able to infer that the outputs
# from a sectioning technique were 'created'
(ilxtr.hasPrimaryOutput, ilxtr.section),
#(hasOutput, ilxtr.sectionsOfPrimaryInput), # FIXME circular
#(hasOutput,
#oc_.full_combinator(intersectionOf(
#ilxtr.partOfSomePrimaryInput,
#restN(partOf,
#restrictionN(ilxtr.primaryParticipantIn,
#tech.sectioning)),
#restrictionN(ilxtr.hasAssessedAspect,
#restN(ilxtr.hasConstrainingAspect, asp.flatness)))),
#intersectionOf(
# hasAssessedAspect better than hasAspect?
# implies there is another technique...
# you can measure the flatness of the himallayals
# or of an electron if you wanted
# so hasAspect is maybe not the best?
synonyms=('sectioning',)), # FIXME
cmb.Class(tech.sectioning, restriction(ilxtr.hasDualInputTechnique, tech.destroying)),
_t(DEV(209), 'tissue sectioning technique',
(ilxtr.hasPrimaryOutput, ilxtr.section),
# FIXME primary participant to be destroyed? seems like there is a comflict here...
# the cardinality rules are not catching it?
# FIXME conflict between primary participant and output?
#(ilxtr.hasDualInputTechnique, tech.destroying), # tech.brainInputTechnique?
(ilxtr.hasPrimaryParticipant, OntTerm('UBERON:0000479', label='tissue')),
synonyms=('tissue sectioning',)),
_t(DEV(210), 'brain sectioning technique',
(ilxtr.hasPrimaryOutput, ilxtr.section),
(ilxtr.hasDualTechnique,
restN(ilxtr.hasPrimaryInput,
OntTerm('UBERON:0000955', label='brain'))),
#(ilxtr.hasDualInputTechnique, tech.destroying), # TODO
#(ilxtr.hasPrimaryParticipant, OntTerm('UBERON:0000955', label='brain')),
synonyms=('brain sectioning',)),
#cmb.Class(i.p,),
_t(DEV(211), 'block face sectioning technique',
# SBEM vs block face for gross anatomical registration
tech.sectioning,
(ilxtr.hasSomething, blank(95)),
),
_t(DEV(212), 'microtomy technique',
(hasInput, ilxtr.microtome),
#(ilxtr.hasDualInputTechnique, tech.destroying), # TODO
(ilxtr.hasPrimaryOutput, ilxtr.thinSection), # this prevents issues with microtome based warfare techniques
synonyms=('microtomy',)
),
_t(DEV(213), 'ultramicrotomy technique',
(hasInput, ilxtr.ultramicrotome),
(ilxtr.hasPrimaryOutput, ilxtr.veryThinSection), # FIXME > 1?
synonyms=('ultramicrotomy',)
),
_t(DEV(214), 'array tomographic technique',
(hasPart, tech.lightMicroscopy),
#(hasParticipant, ilxtr.microscope), # FIXME more precisely?
(hasPart, tech.tomography),
#(ilxtr.hasInformationInput, ilxtr.image),
#(ilxtr.hasInformationOutput, ilxtr.image),
#(ilxtr.isConstrainedBy, ilxtr.radonTransform),
synonyms=('array tomography', 'array tomography technique')
),
_t(tech.electronMicroscopy, 'electron microscopy technique',
(hasInput, OntTerm('BIRNLEX:2041', label='Electron microscope', synonyms=[])),
(ilxtr.detects, OntTerm('CHEBI:10545', label='electron')), # FIXME chebi ok in this context?
(ilxtr.hasInformationOutput, ilxtr.image),
(ilxtr.hasPrimaryParticipant, ilxtr.materialEntity),
# hasProbe ilxtr.electron and some focusing elements and detects ilxtr.electron
synonyms=('electron microscopy',)),
(tech.electronMicroscopy, oboInOwl.hasDbXref, OntTerm('NLX:82779')), # ICK from assay branch which conflates measurement :/
_t(tech.scanningElectronMicroscopy, 'scanning electron microscopy technique',
(hasInput, OntTerm('BIRNLEX:2044', label='Scanning electron microscope', synonyms=[])),
(ilxtr.detects, OntTerm('CHEBI:10545', label='electron')), # FIXME chebi ok in this context?
(ilxtr.hasInformationOutput, ilxtr.image),
(ilxtr.hasPrimaryParticipant, ilxtr.materialEntity),
# hasProbe ilxtr.electron and some focusing elements and detects ilxtr.electron
synonyms=('scanning electron microscopy', 'SEM')),
_t(DEV(215), 'electron tomography technique',
(hasPart, tech.electronMicroscopy),
(hasPart, tech.tomography),
synonyms=('electron tomography',),
),
_t(DEV(216), 'correlative light-electron microscopy technique',
#(hasInput, OntTerm('BIRNLEX:2041', label='Electron microscope')),
# this works extremely well because the information outputs propagate nicely
(hasPart, tech.lightMicroscopy),
(hasPart, tech.electronMicroscopy),
(ilxtr.hasPrimaryParticipant, ilxtr.materialEntity),
(ilxtr.hasInformationOutput, ilxtr.image),
synonyms=('correlative light-electron microscopy',)
),
_t(DEV(217), 'serial blockface electron microscopy technique',
(hasPart, tech.electronMicroscopy),
(hasPart, tech.ultramicrotomy),
(hasInput, ilxtr.serialBlockfaceUltraMicrotome),
(ilxtr.hasPrimaryParticipant, ilxtr.materialEntity),
#(hasParticipant, OntTerm('BIRNLEX:2041', label='Electron microscope')),
#(hasParticipant, ilxtr.ultramicrotome),
synonyms=('serial blockface electron microscopy',)
),
_t(DEV(218), 'super resolution microscopy technique',
#(hasParticipant, OntTerm('BIRNLEX:2106', label='Microscope', synonyms=[])), # TODO more
(hasPart, tech.lightMicroscopy), # FIXME special restriction on the properties of the scope?
(ilxtr.isConstrainedBy, ilxtr.superResolutionAlgorithm),
(ilxtr.hasPrimaryParticipant, ilxtr.materialEntity),
synonyms=('super resolution microscopy',)
),
_t(DEV(219), 'northern blotting technique',
(hasPart, tech.electrophoresis),
# fixme knownDetectedPhenomena?
(ilxtr.hasPrimaryParticipant, OntId('CHEBI:33697')),
(ilxtr.hasProbe, ilxtr.hybridizationProbe), # has part some probe addition?
(ilxtr.hasPrimaryAspect, asp.sequence),
synonyms=('northern blot',)
),
_t(DEV(220), 'Southern blotting technique',
(hasPart, tech.electrophoresis),
#(ilxtr.hasPrimaryParticipant, OntTerm('CHEBI:16991', term='DNA')),
(ilxtr.hasPrimaryParticipant, ilxtr.DNApolymer),
(ilxtr.hasProbe, ilxtr.hybridizationProbe),
(ilxtr.hasPrimaryAspect, asp.sequence),
synonyms=('Southern blot',)
),
_t(DEV(221), 'western blotting technique',
# FIXME dissociated
(hasPart, tech.electrophoresis),
(ilxtr.hasPrimaryParticipant, OntTerm('PR:000000001', label='protein')), # at least one
(ilxtr.hasProbe, OntTerm('BIRNLEX:2110', label='Antibody')),
# FIXME is this really a probes in the way that say, an xray is a probe? I think yes
# they create the contrast that will later be detected
(ilxtr.hasPrimaryAspect, asp.epitopePresent), # in sufficient quantity?
# epitope is in theory more physical, but since we don't understand the mechanism
# we don't really know what the antibody is 'measuring' about the epitope
# to deal with this we make it a binary aspect and use the intentional nature of
# has primary aspect to deal with false negatives
# false negative is a failure with respect to a binary aspect intention caused by
# a report of false when the omega measure implementation of the aspect on the
# black box evaluates to true
synonyms=('wester blot',
'protein immunoblot',)),
(i.p, ilxtr.hasTempId, OntTerm("HBP_MEM:0000112")),
_t(DEV(222), 'intracellular electrophysiology technique',
(ilxtr.hasPrimaryParticipant, OntTerm('GO:0005622', label='intracellular')),
# FIXME in a physiological (not dead) system
(ilxtr.hasPrimaryAspect, asp.electrical),
#(ilxtr.hasPrimaryParticipant, OntTerm('SAO:1289190043', label='Cellular Space')), # TODO add intracellular as synonym
),
_t(tech.extracellularEphys, 'extracellular electrophysiology technique',
# or is it hasPrimaryParticipant hasPart some extracellularSpace? (no)
(ilxtr.hasPrimaryParticipant, OntTerm('GO:0005615', label='extracellular space')),
(ilxtr.hasPrimaryAspect, asp.electrical),
),
(tech.extracellularEphys, ilxtr.hasTempId, OntTerm('HBP_MEM:0000015')),
_t(tech.singleElectrodeEphys, 'single electrode extracellular electrophysiology technique',
# FIXME extracellular space that is part of some other participant... how to convey this...
(ilxtr.hasPrimaryAspect, asp.electrical),
(ilxtr.hasPrimaryParticipant, OntTerm('GO:0005615', label='extracellular space')),
(hasInput, ilxtr.singleElectrode), # cardinality 1?
synonyms=('extracellular single electrode technique',)),
(tech.singleElectrodeEphys, ilxtr.hasTempId, OntTerm('HBP_MEM:0000019')),
_t(tech.multiElectrodeEphys, 'multi electrode extracellular electrophysiology technique',
# FIXME extracellular space that is part of some other participant... how to convey this...
(ilxtr.hasPrimaryAspect, asp.electrical),
(ilxtr.hasPrimaryParticipant, OntTerm('GO:0005615', label='extracellular space')),
(hasInput, ilxtr.multiElectrode), # cardinality n?
synonyms=('extracellular multi electrode technique',)),
(tech.singleElectrodeEphys, ilxtr.hasTempId, OntTerm('HBP_MEM:0000019')),
_t(DEV(223), 'multi electrode extracellular electrophysiology recording technique',
(hasPart, tech.multiElectrodeEphys),
(hasPart, tech.ephysRecording),
synonyms=('multi unit recording',
'multi unit recording technique',
'multi-unit recording',),
),
_t(DEV(224), 'single electrode extracellular electrophysiology recording technique',
(hasPart, tech.singleElectrodeEphys),
(hasPart, tech.ephysRecording),
synonyms=('single unit recording',
'single unit recording technique',
'single-unit recording',),
),
_t(DEV(225), 'extracellular electrophysiology recording technique',
(hasPart, tech.extracellularEphys),
(hasPart, tech.ephysRecording),
synonyms=('extracellular recording',),
),
_t(tech.sharpElectrodeEphys, 'sharp intracellular electrode technique',
(ilxtr.hasPrimaryAspect, asp.electrical),
(ilxtr.hasPrimaryParticipant, OntTerm('GO:0005622', label='intracellular')),
(hasInput, ilxtr.sharpElectrode),
synonyms=('sharp electrode technique',)),
(tech.sharpElectrodeEphys, ilxtr.hasTempId, OntTerm('HBP_MEM:0000023')),
_t(tech.sharpElectrodeTechnique, 'sharp electrode technique',
intersectionOf(ilxtr.technique,
restN(ilxtr.hasPrimaryParticipant, ilxtr.cell),
restN(hasInput, ilxtr.sharpMicroPipette)),
equivalentClass=oECN),
_t(tech.cellPatching, 'cell patching technique',
intersectionOf(ilxtr.technique,
restN(ilxtr.hasPrimaryParticipant,
unionOf(ilxtr.cellMembrane,
restN(partOf, ilxtr.cellMembrane))),
restN(hasInput, ilxtr.patchPipette)),
equivalentClass=oECN),
cmb.Class(tech.cellPatching, restriction(hasInput, ilxtr.inVitroEphysRig)),
_t(tech.patchClamp, 'patch clamp technique',
intersectionOf(ilxtr.technique,
restN(hasPart, tech.cellPatching),
restN(ilxtr.hasPrimaryAspect, asp.electrical),
restN(hasInput, ilxtr.patchElectrode)),
intersectionOf(ilxtr.technique,
restN(hasPart, tech.patchClamp)),
equivalentClass=oECN),
(tech.patchClamp, ilxtr.hasTempId, OntTerm('HBP_MEM:0000017')),
_t(DEV(226), 'cell attached patch technique',
(ilxtr.hasPrimaryParticipant, ilxtr.cellMembrane),
(hasInput, ilxtr.patchPipette),
(hasParticipant, OntTerm('GO:0005622', label='intracellular')),
# cell attached configuration?
(ilxtr.hasSomething, blank(96)),
),
(i.p, ilxtr.hasTempId, OntTerm('HBP_MEM:0000029')),
_t(DEV(227), 'inside out patch technique',
(ilxtr.hasPrimaryParticipant, ilxtr.cellMembrane),
(hasInput, ilxtr.patchPipette),
(ilxtr.hasSomething, blank(97)),
),
(i.p, ilxtr.hasTempId, OntTerm('HBP_MEM:0000028')),
_t(DEV(228), 'loose patch technique',
(ilxtr.hasPrimaryParticipant, ilxtr.cellMembrane),
(hasInput, ilxtr.patchPipette),
(ilxtr.hasSomething, blank(98)),
),
(i.p, ilxtr.hasTempId, OntTerm('HBP_MEM:0000024')),
_t(DEV(229), 'outside out patch technique',
(ilxtr.hasPrimaryParticipant, ilxtr.cellMembrane),
(hasInput, ilxtr.patchPipette),
(ilxtr.hasSomething, blank(99)),
),
(i.p, ilxtr.hasTempId, OntTerm('HBP_MEM:0000026')),
_t(DEV(230), 'perforated patch technique',
(ilxtr.hasPrimaryParticipant, ilxtr.cellMembrane),
(hasInput, ilxtr.patchPipette),
(ilxtr.hasSomething, blank(100)),
),
(i.p, ilxtr.hasTempId, OntTerm('HBP_MEM:0000025')),
_t(tech.wholeCellPatch, 'whole cell patch technique',
(ilxtr.hasPrimaryParticipant, ilxtr.cellMembrane),
(hasParticipant, OntTerm('GO:0005622', label='intracellular')),
(hasInput, ilxtr.patchPipette),
(ilxtr.hasSomething, blank(101)),
),
(i.p, ilxtr.hasTempId, OntTerm('HBP_MEM:0000027')),
_t(tech.eClamp, 'electrical clamping technique',
(hasInput, ilxtr.recordingElectrode),
(ilxtr.hasPrimaryAspect, asp.electrical),
(ilxtr.hasConstrainingAspect, asp.electrical),
# FIXME should be different aspects??
),
_t(DEV(231), 'current clamp technique',
(hasInput, ilxtr.recordingElectrode),
(ilxtr.hasPrimaryAspect, asp.voltage),
(ilxtr.hasConstrainingAspect, asp.current),
# TODO hasPrimaryAspectActualized, asp.current
# TODO isConstrainedBy V=IR
),
(i.p, ilxtr.hasTempId, OntTerm('HBP_MEM:0000204')),
_t(tech.vClamp, 'voltage clamp technique',
# voltage really only works in patch configuration
# need to be able to inject enough current
(hasInput, ilxtr.recordingElectrode),
(ilxtr.hasPrimaryAspect, asp.current),
(ilxtr.hasConstrainingAspect, asp.voltage),
# TODO hasPrimaryAspectActualized, asp.current
),
(i.p, ilxtr.hasTempId, OntTerm('HBP_MEM:0000203')),
_t(DEV(232), 'dynamic clamp technique',
(hasPart, tech.vClamp),
(hasInput, ilxtr.dynamicClampAmplifier),
),
_t(DEV(233), 'whole cell patch clamp technique',
(hasPart, tech.eClamp),
(hasPart, tech.wholeCellPatch),
synonyms=('whole cell patch clamp',),
),
_t(DEV(234), 'cell filling technique',
(hasPart, tech.cellPatching),
#(hasPart, tech.contrastEnhancement), #not the right way to do this?
#(hasParticipant, OntTerm('GO:0005622', label='intracellular')),
(hasInput, ilxtr.contrastAgent), # FIXME ...
),
_t(DEV(235), 'neuron morphology reconstruction technique',
(ilxtr.hasSomething, blank(102))),
_t(DEV(236), 'autoradiographic technique',
(ilxtr.hasSomething, blank(103))),
_t(DEV(237), 'intravascaular filling technique',
(ilxtr.hasSomething, blank(104))),
_t(DEV(238), 'brightfield microscopy technique',
(ilxtr.hasSomething, blank(105))),
_t(DEV(239), 'machine learning technique',
(ilxtr.hasSomething, blank(106))),
_t(DEV(240), 'deep learning technique',
(ilxtr.hasSomething, blank(107))),
_t(DEV(241), 'delineation technique',
(ilxtr.hasSomething, blank(108))),
_t(DEV(242), 'epifluorescent microscopy technique',
(ilxtr.hasSomething, blank(109))),
_t(DEV(243), 'epifluorescent microscopy',
(ilxtr.hasSomething, blank(110))),
_t(DEV(244), 'fiber photometry technique',
(ilxtr.hasSomething, blank(111))),
_t(DEV(245), 'focused ion beam scanning electron microscoscopy technique',
(ilxtr.hasSomething, blank(112))),
_t(DEV(246), 'microendoscopic technique',
(ilxtr.hasSomething, blank(113))),
_t(tech.twoPhoton, 'two-photon microscopy technique',
(hasInput, ilxtr.twoPhotonMicroscope), # TODO
(ilxtr.hasSomething, blank(114)), # TODO visible light vs microscopy
synonyms=('two-photon microscopy',)),
_t(tech.lightsheetMicroscopy, 'light sheet microscopy technique',
(hasInput, ilxtr.lightSheetMicroscope), # TODO
(ilxtr.detects, ilxtr.visibleLight),
(ilxtr.hasInformationOutput, ilxtr.image),
(ilxtr.hasPrimaryParticipant, ilxtr.materialEntity),
synonyms=('light sheet microscopy',)),
_t(tech.lightSheetMicroscopyFluorescent, 'light sheet fluorescence microscopy technique',
(hasInput, ilxtr.lightSheetMicroscope), # TODO
(ilxtr.detects, ilxtr.visibleLight),
(hasInput, ilxtr.fluorescentMolecule), # hasParticipant hasPart FIXME
(ilxtr.hasInformationOutput, ilxtr.image),
(ilxtr.hasPrimaryParticipant, ilxtr.materialEntity),
synonyms=('light sheet fluorescence microscopy', 'LSFM')),
oc(DEV(247)),
(DEV(248), owl.deprecated, Literal(True)),
(DEV(249), replacedBy, DEV(250)), # STPT and TPT used to be 361 and 362, now merged
_t(DEV(251), 'two-photon tomographic technique',
(hasPart, tech.twoPhoton),
(hasPart, tech.tomography),
(ilxtr.hasSomething, blank(115)), # TODO serial?? this model conflates with 2p tomography ...
synonyms=('serial two-photon tomography', 'STPT',)
# FIXME acronym
),
_t(tech.lightSheetTomographyOblique, 'oblique light sheet tomographic technique',
(hasPart, tech.lightsheetMicroscopy),
(hasPart, tech.tomography),
(ilxtr.hasSomething, blank(116)), # TODO oblique?
synonyms=('oblique light sheet tomography', 'OLST',)
# FIXME acronym
),
_t(DEV(252), 'wide-field microscopy technique',
(ilxtr.hasSomething, blank(117))),
_t(DEV(253), 'brain-wide technique',
(ilxtr.hasSomething, blank(118))),
_t(DEV(254), 'gene characterization technique',
(ilxtr.hasSomething, blank(119))),
)
def ect(): # FIXME not used supposed to make dAdT zero equi to value hasValue 0
b = rdflib.BNode()
r = tuple(restG(None, POC(owl.onProperty, ilxtr.hasPrimaryAspect_dAdT),
POC(owl.someValuesFrom,
rdflib.Literal(1, datatype=rdflib.XSD.nonNegativeInteger)),
POC(owl.onClass, ilxtr.changeType)),
restG(None, POC(owl.onProperty, ilxtr.hasPrimaryAspect_dAdT),
POC(owl.maxQualifiedCardinality,
rdflib.Literal(1, datatype=rdflib.XSD.nonNegativeInteger)),
POC(owl.onClass, ilxtr.changeType)))
ax = (b, rdf.type, owl.Axiom)
ecr = (b, owl.equivalentClass, r[0][0])
return r1 + r2 + ax + ecr
#triples += ect()
"""
_t(tech.fMRI, 'functional magnetic resonance imaging',
# AAAAAAA how to deal with
# "change in nuclear magnetic resonance of iron molecules as a function of time and their bound oxygen"
# "BOLD" blood oxygenation level dependent contrast is something different...
#ilxtr.NMR_of_iron_in_the_blood # ICK
#(hasPrimaryParticipant, ilxtr.???)
#(hasPart, tech.MRI), # FIXME how to deal with this...
#(hasPart, tech.bloodOxygenLevel),
#(ilxtr.hasPrimaryAspect, ilxtr.nuclearMagneticResonance),
tech.MRI, # FIXME vs respeccing everything?
#(ilxtr.hasPrimaryParticipantSubeset, ilxtr.haemoglobin)
#(ilxtr.hasPrimaryParticipantPart, ilxtr.haemoglobin)
(ilxtr.hasPrimaryParticipant, ilxtr.haemoglobin),
(ilxtr.hasPrimaryParticipantSubsetRule, ilxtr.hasBoundOxygen), # FIXME not quite right still?
synonyms=('fMRI', 'functional nuclear magnetic resonance imaging'),),
olit(tech.fMRI, rdfs.comment,
('Note that this deals explicitly only with the image acquistion portion of fMRI. '
'Other parts of the full process and techniques in an fMRI study should be modelled separately. '
'They can be tied to fMRI using hasPart: or hasPriorTechnique something similar.')), # TODO
(tech.fMRI, ilxtr.hasTempId, OntTerm("HBP_MEM:0000008")),
"""
"""
_t(tech.sequencing, 'sequencing technique',
# hasParticipant molecule or chemical?
(ilxtr.hasPrimaryParticipant, ilxtr.thingWithSequence), # peptide nucleotie sacharide
# can't use hasParticipant because then it would caputre peptide synthesis or oligo synthesis
(ilxtr.hasPrimaryAspect, asp.sequence), # nucleic and peptidergic, and chemical etc.
(ilxtr.hasInformationOutput, ilxtr.informationArtifact), # note use of artifact
),
"""
"""
_t(tech.rnaSeq, 'RNAseq',
(ilxtr.knownDetectedPhenomena, OntTerm('CHEBI:33697', label='RNA')),
(ilxtr.hasPrimaryAspect, asp.sequence),
(ilxtr.hasInformationOutput, ilxtr.informationArtifact), # note use of artifact
synonyms=('RNA-seq',)
),
"""
methods = simpleOnt(filename=filename,
prefixes=prefixes,
imports=imports,
triples=triples,
comment=comment,
branch=branch,
_repo=_repo,
calling__file__=__file__,)
[methods.graph.add((o2, rdfs.subClassOf, ilxtr.Something))
for s1, p1, o1 in methods.graph if
p1 == owl.onProperty and
o1 == ilxtr.hasSomething
for p2, o2 in methods.graph[s1:] if
p2 == owl.someValuesFrom]
methods.graph.add((methods.graph.boundIdentifier,
ilxtr.indexNamespace,
rdflib.URIRef(str(local))))
def methods_main():
methods._graph.add_namespace('asp', str(asp))
methods._graph.add_namespace('ilxtr', str(ilxtr)) # FIXME why is this now showing up...
methods._graph.add_namespace('prot', str(prot))
methods._graph.add_namespace('tech', str(tech))
methods._graph.add_namespace('HBP_MEM', OntCuries['HBP_MEM'])
methods._graph.write()
from collections import defaultdict
data = defaultdict(set)
for t in methods.graph:
for e in t:
if isinstance(e, URIRef) and 'tgbugs' in e:
prefix, suffix = methods._graph.qname(e).split(':')
data[prefix].add(suffix)
intersection = defaultdict(set)
for ki, vi in data.items():
for kj, vj in data.items():
if ki == kj:
continue
intersection[ki,kj].update(vi & vj)
def testbt(simpleont):
bad_types = set((s, bo) for s in simpleont.graph[:rdf.type:owl.Class]
for bo in simpleont.graph[s:rdf.type] if
bo != owl.Class)
[print(t) for t in bad_types]
if bad_types:
raise TypeError()
testbt(methods_helper)
testbt(methods_core)
testbt(methods)
#assert not any(intersection.values()), f'duplicate namespace issue {intersection!r}'
def halp():
import rdflib
trips = sorted(flattenTriples(triples))
graph = rdflib.Graph()
*(graph.add(t) for t in trips),
*(print(tuple(qname(e) if not isinstance(e, rdflib.BNode) else e[:5] for e in t)) for t in trips),
breakpoint()
return trips
#trips = halp()
def expand(_makeGraph, *graphs, debug=False):
import rdflib
import RDFClosure as rdfc
graph = rdflib.Graph()
for graph_ in graphs:
[graph.bind(k, v) for k, v in graph_.namespaces()]
[graph.add(t) for t in graph_]
g = _makeGraph.__class__('', graph=graph)
g.filename = _makeGraph.filename
# other options are
# OWLRL_Semantis RDFS_OWLRL_Semantics but both cuase trouble
# all of these are SUPER slow to run on cpython, very much suggest pypy3
#rdfc.DeductiveClosure(rdfc.OWLRL_Extension_Trimming).expand(graph) # monumentally slow even on pypy3
#rdfc.DeductiveClosure(rdfc.OWLRL_Extension).expand(graph)
eg = rdflib.Graph()
[eg.add(t) for t in graph_]
closure = rdfc.OWLRL_Semantics
rdfc.DeductiveClosure(closure).expand(eg)
[not graph.add((s, rdfs.subClassOf, o))
and [graph.add(t) for t in annotation.serialize((s, rdfs.subClassOf, o),
ilxtr.isDefinedBy, closure.__name__)]
for s, o in eg.subject_objects(rdfs.subClassOf)
if s != o and # prevent cluttering the graph
#o not in [to for o_ in eg.objects(s, rdfs.subClassOf) # not working correctly
#for to in eg.objects(o_) if o_ != o] and
not isinstance(s, rdflib.BNode) and
not isinstance(o, rdflib.BNode) and
'interlex' in s and 'interlex' in o]
#g.write()
displayGraph(graph, debug=debug)
def forComparison():
obo, *_ = makeNamespaces('obo')
filename = 'methods-external-test-bridge'
imports = (obo['ero.owl'],
#URIRef('https://www.eagle-i.net/ero/latest/ero.owl'),
obo['obi.owl'],
obo['ro.owl'],
URIRef('http://www.ebi.ac.uk/efo/efo.owl'),
URIRef('http://purl.org/incf/ontology/ExperimentalNeurophysiology/oen_term.owl'),
) # CNO still uses bfo1.1
comment = 'Bridge for querying against established methods related ontologies.'
_repo = True
debug = False
triples = tuple()
methods_helper = simpleOnt(filename=filename,
#prefixes=prefixes,
imports=imports,
triples=triples,
comment=comment,
branch=branch,
_repo=_repo,
calling__file__=__file__)
def extra():
forComparison()
displayGraph(methods.graph, debug=debug)
mc = methods.graph.__class__()
#mc.add(t) for t in methods_core.graph if t[0] not in
expand(methods_core._graph, methods_core.graph)#, methods_core.graph) # FIXME including core breaks everying?
expand(methods._graph, methods.graph)#, methods_core.graph) # FIXME including core breaks everying?
def main():
from nifstd_tools.methods import core
from nifstd_tools.methods import helper
core.main()
helper.main()
methods_main()
if __name__ == '__main__':
main()
|
tgbugs/pyontutils
|
nifstd/nifstd_tools/methods/__init__.py
|
Python
|
mit
| 148,084
|
[
"CRYSTAL",
"NEURON"
] |
3f6674e6d93d8fa586a592a3db54307b8a58331253b41366c3fd57bbba57a23f
|
"""
Gaussian Smoothing
~~~~~~~~~~~~~~~~~~
Perform a Gaussian convolution on a uniformly gridded data set.
:class:`pyvista.UniformGrid` data sets (a.k.a. images) a can be smoothed by
convolving the image data set with a Gaussian for one- to three-dimensional
inputs. This is commonly referred to as Gaussian blurring and typically used
to reduce noise or decrease the detail of an image dataset
"""
# sphinx_gallery_thumbnail_number = 2
import pyvista as pv
from pyvista import examples
# Load dataset
data = examples.download_gourds()
# Define a good point of view
cp = [
(319.5, 239.5, 1053.7372980874645),
(319.5, 239.5, 0.0),
(0.0, 1.0, 0.0)
]
###############################################################################
# Let's apply the gaussian smoothing with different values of standard
# deviation.
p = pv.Plotter(shape=(2, 2))
p.subplot(0, 0)
p.add_text("Original Image", font_size=24)
p.add_mesh(data, rgb=True)
p.camera_position = cp
p.subplot(0, 1)
p.add_text("Gaussian smoothing, std=2", font_size=24)
p.add_mesh(data.gaussian_smooth(std_dev=2.), rgb=True)
p.camera_position = cp
p.subplot(1, 0)
p.add_text("Gaussian smoothing, std=4", font_size=24)
p.add_mesh(data.gaussian_smooth(std_dev=4.), rgb=True)
p.camera_position = cp
p.subplot(1, 1)
p.add_text("Gaussian smoothing, std=8", font_size=24)
p.add_mesh(data.gaussian_smooth(std_dev=8.), rgb=True)
p.camera_position = cp
p.show()
###############################################################################
# Now let's see an example on a 3D dataset with volume rendering:
data = examples.download_brain()
smoothed_data = data.gaussian_smooth(std_dev=3.)
dargs = dict(clim=smoothed_data.get_data_range(),
opacity=[0, 0, 0, 0.1, 0.3, 0.6, 1])
n = [100, 150, 200, 245, 255]
p = pv.Plotter(shape=(1, 2), notebook=0)
p.subplot(0, 0)
p.add_text("Original Image", font_size=24)
# p.add_mesh(data.contour(n), **dargs)
p.add_volume(data, **dargs)
p.subplot(0, 1)
p.add_text("Gaussian smoothing", font_size=24)
# p.add_mesh(smoothed_data.contour(n), **dargs)
p.add_volume(smoothed_data, **dargs)
p.link_views()
p.camera_position = [(-162.0, 704.8, 65.02),
(90.0, 108.0, 90.0),
(0.0068, 0.0447, 0.999)]
p.show()
|
akaszynski/vtkInterface
|
examples/01-filter/gaussian-smoothing.py
|
Python
|
mit
| 2,262
|
[
"Gaussian"
] |
d746205488cee39937d97aa1e04466a1acda2aeb6603965c952e6f7edfa49ce0
|
# -*- coding: utf-8 -*-
#
# test_inflow.py
# RAPIDpy
#
# Created by Alan D. Snow.
# Copyright © 2016 Alan D Snow. All rights reserved.
#
from datetime import datetime
from glob import glob
import multiprocessing
from netCDF4 import Dataset
from numpy.testing import assert_almost_equal
import numpy as np
import os
from past.builtins import xrange
import pytest
from shutil import copy, copytree, rmtree
import unittest
# local import
from RAPIDpy.inflow import run_lsm_rapid_process
from RAPIDpy.inflow.CreateInflowFileFromERAInterimRunoff import CreateInflowFileFromERAInterimRunoff
from RAPIDpy.inflow.CreateInflowFileFromLDASRunoff import CreateInflowFileFromLDASRunoff
from RAPIDpy.inflow.CreateInflowFileFromWRFHydroRunoff import CreateInflowFileFromWRFHydroRunoff
from RAPIDpy.helper_functions import (compare_csv_decimal_files,
remove_files)
MAIN_TESTS_FOLDER = os.path.dirname(os.path.abspath(__file__))
RAPID_EXE_PATH = os.path.join(MAIN_TESTS_FOLDER,
"..", "..",
"rapid", "src", "rapid")
def compare_array_nan(a, b):
# based on https://stackoverflow.com/questions/23810370/python-numpy-comparing-arrays-with-nan
return ((a == b) | (np.isnan(a) & np.isnan(b))).all()
class TestRAPIDInflow(unittest.TestCase):
def setUp(self):
# define global variables
self.COMPARE_DATA_PATH = os.path.join(MAIN_TESTS_FOLDER, 'compare')
self.INFLOW_COMPARE_DATA_PATH = os.path.join(self.COMPARE_DATA_PATH, 'inflow')
self.LSM_INPUT_DATA_PATH = os.path.join(MAIN_TESTS_FOLDER, 'data','lsm_grids')
self.OUTPUT_DATA_PATH = os.path.join(MAIN_TESTS_FOLDER, 'output')
self.RAPID_DATA_PATH = os.path.join(self.OUTPUT_DATA_PATH, 'input')
self.CYGWIN_BIN_PATH = 'C:\\cygwin64\\bin'
try:
self.tearDown()
except OSError:
pass
def tearDown(self):
rmtree(os.path.join(self.OUTPUT_DATA_PATH, "input"))
rmtree(os.path.join(self.OUTPUT_DATA_PATH, "output"))
@staticmethod
def _compare_m3(generated_m3_file, generated_m3_file_solution):
# check other info in netcdf file
d1 = Dataset(generated_m3_file)
d2 = Dataset(generated_m3_file_solution)
try:
assert_almost_equal(d1.variables['m3_riv'][:], d2.variables['m3_riv'][:], decimal=4)
if 'rivid' in d2.variables.keys():
compare_array_nan(d1.variables['rivid'][:], d2.variables['rivid'][:])
if 'lat' in d2.variables.keys():
compare_array_nan(d1.variables['lat'][:], d2.variables['lat'][:])
if 'lon' in d2.variables.keys():
compare_array_nan(d1.variables['lon'][:], d2.variables['lon'][:])
except AssertionError:
d1.close()
d2.close()
raise
d1.close()
d2.close()
def _setup_automated(self, directory_name):
"""
setup for automated method
"""
rapid_input_path = os.path.join(self.RAPID_DATA_PATH, directory_name)
rapid_output_path = os.path.join(self.OUTPUT_DATA_PATH, "output", directory_name)
try:
os.mkdir(self.RAPID_DATA_PATH)
except OSError:
pass
try:
os.mkdir(os.path.join(self.OUTPUT_DATA_PATH, "output"))
except OSError:
pass
try:
copytree(os.path.join(self.COMPARE_DATA_PATH, "gis", directory_name),
rapid_input_path)
except OSError:
pass
return rapid_input_path, rapid_output_path
def _setup_manual(self, directory_name):
"""
setup for manual method
"""
rapid_input_path, rapid_output_path = self._setup_automated(directory_name)
try:
os.mkdir(rapid_output_path)
except OSError:
pass
return rapid_input_path, rapid_output_path
def _run_automatic(self, lsm_folder_name,
watershed_folder,
file_datetime_pattern=None,
file_datetime_re_pattern=None,
convert_one_hour_to_three=False,
expected_time_step=None,
single_run=False,
filter_dates=True):
"""
run for automatic method
"""
rapid_input_path, rapid_output_path = self._setup_automated(watershed_folder)
run_input_folder = None
run_output_folder = None
rapid_io_folder = self.OUTPUT_DATA_PATH
if single_run:
run_input_folder = rapid_input_path
run_output_folder = rapid_output_path
rapid_io_folder = None
start_datetime = None
end_datetime = None
if filter_dates:
start_datetime = datetime(1980, 1, 1)
end_datetime = datetime(2014, 12, 31)
# run main process
output_file_info = run_lsm_rapid_process(
rapid_executable_location=RAPID_EXE_PATH,
cygwin_bin_location=self.CYGWIN_BIN_PATH,
rapid_io_files_location=rapid_io_folder,
rapid_input_location=run_input_folder,
rapid_output_location=run_output_folder,
lsm_data_location=os.path.join(self.LSM_INPUT_DATA_PATH, lsm_folder_name),
simulation_start_datetime=start_datetime,
simulation_end_datetime=end_datetime,
generate_rapid_namelist_file=False,
run_rapid_simulation=False,
use_all_processors=True,
file_datetime_pattern=file_datetime_pattern,
file_datetime_re_pattern=file_datetime_re_pattern,
convert_one_hour_to_three=convert_one_hour_to_three,
expected_time_step=expected_time_step,
)
return rapid_input_path, rapid_output_path, output_file_info
@pytest.mark.skipif(not os.path.exists(RAPID_EXE_PATH), reason='Only run if RAPID installed')
def test_run_era_interim_inflow(self):
"""
Checks generating inflow file from ERA Interim LSM
"""
rapid_input_path, rapid_output_path = self._setup_automated("x-x")
# run main process
output_file_info = run_lsm_rapid_process(
rapid_executable_location=RAPID_EXE_PATH,
cygwin_bin_location=self.CYGWIN_BIN_PATH,
rapid_io_files_location=self.OUTPUT_DATA_PATH,
lsm_data_location=os.path.join(self.LSM_INPUT_DATA_PATH, 'erai3'),
simulation_start_datetime=datetime(1980, 1, 1),
simulation_end_datetime=datetime(2014, 1, 31),
generate_rapid_namelist_file=False,
run_rapid_simulation=True,
generate_return_periods_file=False,
generate_seasonal_initialization_file=False,
generate_initialization_file=True,
use_all_processors=True,
)
# CHECK OUTPUT
# m3_riv
m3_file_name = "m3_riv_bas_erai_t511_3hr_20030121to20030122.nc"
generated_m3_file = os.path.join(rapid_output_path, m3_file_name)
generated_m3_file_solution = os.path.join(self.INFLOW_COMPARE_DATA_PATH, m3_file_name)
self._compare_m3(generated_m3_file,generated_m3_file_solution)
# qout file
qout_file_name = "Qout_erai_t511_3hr_20030121to20030122.nc"
generated_qout_file = os.path.join(rapid_output_path, qout_file_name)
generated_qout_file_solution = os.path.join(self.INFLOW_COMPARE_DATA_PATH, qout_file_name)
d1 = Dataset(generated_qout_file)
d2 = Dataset(generated_qout_file_solution)
assert_almost_equal(d1.variables['Qout'][:], d2.variables['Qout'][:], decimal=5)
assert (d1.variables['rivid'][:] == d2.variables['rivid'][:]).all()
assert (d1.variables['time'][:] == d2.variables['time'][:]).all()
if 'lat' in d2.variables.keys():
assert (d1.variables['lat'][:] == d2.variables['lat'][:]).all()
if 'lon' in d2.variables.keys():
assert (d1.variables['lon'][:] == d2.variables['lon'][:]).all()
d1.close()
d2.close()
# check output file info
assert output_file_info[0]['x-x']['m3_riv'] == generated_m3_file
assert output_file_info[0]['x-x']['qout'] == generated_qout_file
# initialization file
qinit_file_name = "qinit_erai_t511_3hr_20030121to20030122.csv"
generated_qinit_file = os.path.join(rapid_input_path, qinit_file_name)
generated_qinit_file_solution = os.path.join(self.INFLOW_COMPARE_DATA_PATH, qinit_file_name)
assert compare_csv_decimal_files(generated_qinit_file, generated_qinit_file_solution)
# additional cleanup
remove_files(generated_qinit_file)
@pytest.mark.skipif(not os.path.exists(RAPID_EXE_PATH), reason='Only run if RAPID installed')
def test_run_era_interim_inflow_init(self):
"""
Checks generating inflow file from ERA Interim LSM
"""
rapid_input_path, rapid_output_path = self._setup_automated("x-x")
# initialization file
qinit_file_name = "qinit_erai_t511_3hr_20030121to20030122.csv"
qinit_file = os.path.join(rapid_input_path, qinit_file_name)
copy(os.path.join(self.INFLOW_COMPARE_DATA_PATH, qinit_file_name),
qinit_file)
# run main process
output_file_info = run_lsm_rapid_process(
rapid_executable_location=RAPID_EXE_PATH,
cygwin_bin_location=self.CYGWIN_BIN_PATH,
rapid_io_files_location=self.OUTPUT_DATA_PATH,
lsm_data_location=os.path.join(self.LSM_INPUT_DATA_PATH, 'erai3'),
generate_rapid_namelist_file=False,
run_rapid_simulation=True,
generate_initialization_file=True,
initial_flows_file=qinit_file,
use_all_processors=True,
)
# qout file
generated_qout_file = os.path.join(rapid_output_path, "Qout_erai_t511_3hr_20030121to20030122.nc")
generated_qout_file_solution = os.path.join(self.INFLOW_COMPARE_DATA_PATH,
"Qout_erai_t511_3hr_20030121to20030122_init.nc")
# check output file info
assert output_file_info[0]['x-x']['m3_riv'] == os.path.join(rapid_output_path, "m3_riv_bas_erai_t511_3hr_20030121to20030122.nc")
assert output_file_info[0]['x-x']['qout'] == generated_qout_file
d1 = Dataset(generated_qout_file)
d2 = Dataset(generated_qout_file_solution)
assert_almost_equal(d1.variables['Qout'][:], d2.variables['Qout'][:], decimal=0)
assert (d1.variables['rivid'][:] == d2.variables['rivid'][:]).all()
assert (d1.variables['time'][:] == d2.variables['time'][:]).all()
if 'lat' in d2.variables.keys():
assert (d1.variables['lat'][:] == d2.variables['lat'][:]).all()
if 'lon' in d2.variables.keys():
assert (d1.variables['lon'][:] == d2.variables['lon'][:]).all()
d1.close()
d2.close()
def test_generate_erai_t511_inflow_manual(self):
"""
Checks generating inflow file from ERA Interim t511 LSM manually
"""
rapid_input_path, rapid_output_path = self._setup_manual("x-x")
lsm_file_list = sorted(glob(os.path.join(self.LSM_INPUT_DATA_PATH, 'erai3', '*.nc')))
mp_lock = multiprocessing.Manager().Lock()
inf_tool = CreateInflowFileFromERAInterimRunoff()
m3_file_name = "m3_riv_bas_erai_t511_3hr_20030121to20030122.nc"
generated_m3_file = os.path.join(rapid_output_path, m3_file_name)
inf_tool.generateOutputInflowFile(out_nc=generated_m3_file,
start_datetime_utc=datetime(2003,1,21),
number_of_timesteps=len(lsm_file_list)*8,
simulation_time_step_seconds=3*3600,
in_rapid_connect_file=os.path.join(rapid_input_path, 'rapid_connect.csv'),
in_rivid_lat_lon_z_file=os.path.join(rapid_input_path, 'comid_lat_lon_z.csv'),
land_surface_model_description="RAPID Inflow from ERA Interim (T511 Grid) 3 Hourly Runoff",
modeling_institution="US Army Engineer Research and Development Center"
)
inf_tool.execute(nc_file_list=lsm_file_list,
index_list=list(xrange(len(lsm_file_list))),
in_weight_table=os.path.join(rapid_input_path, 'weight_era_t511.csv'),
out_nc=generated_m3_file,
grid_type='t511',
mp_lock=mp_lock)
# CHECK OUTPUT
generated_m3_file_solution = os.path.join(self.INFLOW_COMPARE_DATA_PATH, m3_file_name)
self._compare_m3(generated_m3_file,generated_m3_file_solution)
def test_generate_nldas2_inflow(self):
"""
Checks generating inflow file from NLDAS V2 LSM
"""
rapid_input_path, rapid_output_path, output_file_info = \
self._run_automatic('nldas2', "x-x", convert_one_hour_to_three=True)
# CHECK OUTPUT
# m3_riv
m3_file_name = "m3_riv_bas_nasa_nldas_3hr_20030121to20030121.nc"
generated_m3_file = os.path.join(rapid_output_path, m3_file_name)
generated_m3_file_solution = os.path.join(self.INFLOW_COMPARE_DATA_PATH, m3_file_name)
self._compare_m3(generated_m3_file,generated_m3_file_solution)
# check output file info
assert output_file_info[0]['x-x']['m3_riv'] == generated_m3_file
def test_generate_nldas2_inflow_single(self):
"""
Checks generating inflow file from NLDAS V2 LSM
"""
rapid_input_path, rapid_output_path, output_file_info = \
self._run_automatic('nldas2', "x-x", convert_one_hour_to_three=True,
single_run=True, filter_dates=False)
# CHECK OUTPUT
# m3_riv
m3_file_name = "m3_riv_bas_nasa_nldas_3hr_20030121to20030121.nc"
generated_m3_file = os.path.join(rapid_output_path, m3_file_name)
generated_m3_file_solution = os.path.join(self.INFLOW_COMPARE_DATA_PATH, m3_file_name)
self._compare_m3(generated_m3_file,generated_m3_file_solution)
# check output file info
assert output_file_info[0]['x-x']['m3_riv'] == generated_m3_file
def test_generate_nldas2_inflow2(self):
"""
Checks generating inflow file from NLDAS V2 LSM manually
"""
rapid_input_path, rapid_output_path = self._setup_manual("x-x")
lsm_file_list = sorted(glob(os.path.join(self.LSM_INPUT_DATA_PATH, 'nldas2', '*.nc')))
lsm_file_list = [lsm_file_list[nldas_index:nldas_index+3] for nldas_index in range(0, len(lsm_file_list), 3)\
if len(lsm_file_list[nldas_index:nldas_index+3])==3]
mp_lock = multiprocessing.Manager().Lock()
inf_tool = CreateInflowFileFromLDASRunoff(lat_dim="lat_110",
lon_dim="lon_110",
lat_var="lat_110",
lon_var="lon_110",
runoff_vars=["SSRUNsfc_110_SFC_ave2h",
"BGRUNsfc_110_SFC_ave2h"],
)
m3_file_name = "m3_riv_bas_nasa_nldas_3hr_20030121to20030121.nc"
generated_m3_file = os.path.join(rapid_output_path, m3_file_name)
inf_tool.generateOutputInflowFile(out_nc=generated_m3_file,
start_datetime_utc=datetime(2003,1,21),
number_of_timesteps=len(lsm_file_list),
simulation_time_step_seconds=3*3600,
in_rapid_connect_file=os.path.join(rapid_input_path, 'rapid_connect.csv'),
in_rivid_lat_lon_z_file=os.path.join(rapid_input_path, 'comid_lat_lon_z.csv'),
land_surface_model_description="RAPID Inflow from NLDAS Hourly Runoff",
modeling_institution="US Army Engineer Research and Development Center"
)
inf_tool.execute(nc_file_list=lsm_file_list,
index_list=list(xrange(len(lsm_file_list))),
in_weight_table=os.path.join(rapid_input_path, 'weight_nldas.csv'),
out_nc=generated_m3_file,
grid_type='nldas',
mp_lock=mp_lock)
# CHECK OUTPUT
generated_m3_file_solution = os.path.join(self.INFLOW_COMPARE_DATA_PATH, m3_file_name)
self._compare_m3(generated_m3_file,generated_m3_file_solution)
def test_generate_era20cm_inflow(self):
"""
Checks generating inflow file from ERA 20CM LSM
"""
rapid_input_path, rapid_output_path = self._setup_automated("x-x")
output_file_info = run_lsm_rapid_process(
rapid_executable_location=RAPID_EXE_PATH,
cygwin_bin_location=self.CYGWIN_BIN_PATH,
rapid_io_files_location=self.OUTPUT_DATA_PATH,
lsm_data_location=os.path.join(self.LSM_INPUT_DATA_PATH, 'era20cm'),
simulation_start_datetime=datetime(1980, 1, 1),
simulation_end_datetime=datetime(2014, 1, 31),
ensemble_list=range(10),
generate_rapid_namelist_file=False,
run_rapid_simulation=False,
use_all_processors=True,
)
for i in range(10):
# CHECK OUTPUT
# m3_riv
m3_file_name = "m3_riv_bas_era_20cm_t159_3hr_20000129to20000130_{0}.nc".format(i)
generated_m3_file = os.path.join(rapid_output_path, m3_file_name)
generated_m3_file_solution = os.path.join(self.INFLOW_COMPARE_DATA_PATH, m3_file_name)
self._compare_m3(generated_m3_file,generated_m3_file_solution)
# check output file info
assert output_file_info[i]['x-x']['m3_riv'] == generated_m3_file
def test_generate_era20cm_inflow2(self):
"""
Checks generating inflow file from ERA 20CM LSM manually
"""
rapid_input_path, rapid_output_path = self._setup_manual("x-x")
lsm_file_list = sorted(glob(os.path.join(self.LSM_INPUT_DATA_PATH, 'era20cm', '*_0.nc')))
mp_lock = multiprocessing.Manager().Lock()
inf_tool = CreateInflowFileFromERAInterimRunoff()
m3_file_name = "m3_riv_bas_era_20cm_t159_3hr_20000129to20000130_0.nc"
generated_m3_file = os.path.join(rapid_output_path, m3_file_name)
inf_tool.generateOutputInflowFile(out_nc=generated_m3_file,
start_datetime_utc=datetime(2014,8,20),
number_of_timesteps=len(lsm_file_list)*8,
simulation_time_step_seconds=3*3600,
in_rapid_connect_file=os.path.join(rapid_input_path, 'rapid_connect.csv'),
in_rivid_lat_lon_z_file=os.path.join(rapid_input_path, 'comid_lat_lon_z.csv'),
land_surface_model_description="RAPID Inflow from ERA 20CM (T159 Grid) 3 Hourly Runoff",
modeling_institution="US Army Engineer Research and Development Center"
)
inf_tool.execute(nc_file_list=lsm_file_list,
index_list=list(xrange(len(lsm_file_list))),
in_weight_table=os.path.join(rapid_input_path, 'weight_era_t159.csv'),
out_nc=generated_m3_file,
grid_type='t159',
mp_lock=mp_lock)
# CHECK OUTPUT
generated_m3_file_solution = os.path.join(self.INFLOW_COMPARE_DATA_PATH, m3_file_name)
self._compare_m3(generated_m3_file,generated_m3_file_solution)
def test_generate_erai_t255_inflow(self):
"""
Checks generating inflow file from ERA Interim t255 LSM
"""
# run main process
rapid_input_path, rapid_output_path, output_file_info = \
self._run_automatic('erai3t255', "x-x")
# CHECK OUTPUT
# m3_riv
m3_file_name = "m3_riv_bas_erai_t255_3hr_20140820to20140821.nc"
generated_m3_file = os.path.join(rapid_output_path, m3_file_name)
generated_m3_file_solution = os.path.join(self.INFLOW_COMPARE_DATA_PATH, m3_file_name)
self._compare_m3(generated_m3_file, generated_m3_file_solution)
def test_generate_erai_t255_inflow2(self):
"""
Checks generating inflow file from ERA Interim t255 LSM manually
"""
rapid_input_path, rapid_output_path = self._setup_manual("x-x")
lsm_file_list = sorted(glob(os.path.join(self.LSM_INPUT_DATA_PATH, 'erai3t255', '*.nc')))
mp_lock = multiprocessing.Manager().Lock()
inf_tool = CreateInflowFileFromERAInterimRunoff()
m3_file_name = "m3_riv_bas_erai_t255_3hr_20140820to20140821.nc"
generated_m3_file = os.path.join(rapid_output_path, m3_file_name)
inf_tool.generateOutputInflowFile(out_nc=generated_m3_file,
start_datetime_utc=datetime(2014,8,20),
number_of_timesteps=len(lsm_file_list)*8,
simulation_time_step_seconds=3*3600,
in_rapid_connect_file=os.path.join(rapid_input_path, 'rapid_connect.csv'),
in_rivid_lat_lon_z_file=os.path.join(rapid_input_path, 'comid_lat_lon_z.csv'),
land_surface_model_description="RAPID Inflow from ERA Interim (T255 Grid) 3 Hourly Runoff",
modeling_institution="US Army Engineer Research and Development Center"
)
inf_tool.execute(nc_file_list=lsm_file_list,
index_list=list(xrange(len(lsm_file_list))),
in_weight_table=os.path.join(rapid_input_path, 'weight_era_t255.csv'),
out_nc=generated_m3_file,
grid_type='t255',
mp_lock=mp_lock)
# CHECK OUTPUT
generated_m3_file_solution = os.path.join(self.INFLOW_COMPARE_DATA_PATH, m3_file_name)
self._compare_m3(generated_m3_file,generated_m3_file_solution)
def test_generate_gldas2_inflow(self):
"""
Checks generating inflow file from GLDAS V2 LSM
"""
rapid_input_path, rapid_output_path, output_file_info = \
self._run_automatic('gldas2', "x-x", filter_dates=False)
# CHECK OUTPUT
# m3_riv
m3_file_name = "m3_riv_bas_nasa_gldas2_3hr_20101231to20101231.nc"
generated_m3_file = os.path.join(rapid_output_path, m3_file_name)
generated_m3_file_solution = os.path.join(self.INFLOW_COMPARE_DATA_PATH, m3_file_name)
self._compare_m3(generated_m3_file,generated_m3_file_solution)
# check output file info
assert output_file_info[0]['x-x']['m3_riv'] == generated_m3_file
def test_generate_gldas2_inflow2(self):
"""
Checks generating inflow file from GLDAS V2 LSM manually
"""
rapid_input_path, rapid_output_path = self._setup_manual("x-x")
lsm_file_list = sorted(glob(os.path.join(self.LSM_INPUT_DATA_PATH, 'gldas2', '*.nc4')))
mp_lock = multiprocessing.Manager().Lock()
inf_tool = CreateInflowFileFromLDASRunoff(lat_dim="lat",
lon_dim="lon",
lat_var="lat",
lon_var="lon",
runoff_vars=["Qs_acc",
"Qsb_acc"])
m3_file_name = "m3_riv_bas_nasa_gldas2_3hr_20101231to20101231.nc"
generated_m3_file = os.path.join(rapid_output_path, m3_file_name)
inf_tool.generateOutputInflowFile(out_nc=generated_m3_file,
start_datetime_utc=datetime(2010,12,31),
number_of_timesteps=len(lsm_file_list),
simulation_time_step_seconds=3*3600,
in_rapid_connect_file=os.path.join(rapid_input_path, 'rapid_connect.csv'),
in_rivid_lat_lon_z_file=os.path.join(rapid_input_path, 'comid_lat_lon_z.csv'),
land_surface_model_description="RAPID Inflow from GLDAS2.0 LIS land surface model 3 hourly runoff",
modeling_institution="US Army Engineer Research and Development Center"
)
inf_tool.execute(nc_file_list=lsm_file_list,
index_list=list(xrange(len(lsm_file_list))),
in_weight_table=os.path.join(rapid_input_path, 'weight_gldas2.csv'),
out_nc=generated_m3_file,
grid_type='gldas2',
mp_lock=mp_lock)
# CHECK OUTPUT
generated_m3_file_solution = os.path.join(self.INFLOW_COMPARE_DATA_PATH, m3_file_name)
self._compare_m3(generated_m3_file,generated_m3_file_solution)
def test_generate_lis_inflow(self):
"""
Checks generating inflow file from LIS LSM
"""
# run main process
rapid_input_path, rapid_output_path, output_file_info = \
self._run_automatic('lis', "u-k", convert_one_hour_to_three=True)
# CHECK OUTPUT
# m3_riv
m3_file_name = "m3_riv_bas_nasa_lis_3hr_20110121to20110121.nc"
generated_m3_file = os.path.join(rapid_output_path, m3_file_name)
generated_m3_file_solution = os.path.join(self.INFLOW_COMPARE_DATA_PATH, m3_file_name)
self._compare_m3(generated_m3_file,generated_m3_file_solution)
# check output file info
assert output_file_info[0]['u-k']['m3_riv'] == generated_m3_file
def test_generate_lis_inflow2(self):
"""
Checks generating inflow file from LIS LSM manually
"""
rapid_input_path, rapid_output_path = self._setup_manual("u-k")
lsm_file_list = sorted(glob(os.path.join(self.LSM_INPUT_DATA_PATH, 'lis', '*.nc')))
lsm_file_list = [lsm_file_list[nldas_index:nldas_index+3] for nldas_index in range(0, len(lsm_file_list), 3)\
if len(lsm_file_list[nldas_index:nldas_index+3])==3]
mp_lock = multiprocessing.Manager().Lock()
inf_tool = CreateInflowFileFromLDASRunoff(lat_dim="north_south",
lon_dim="east_west",
lat_var="lat",
lon_var="lon",
runoff_vars=["Qs_inst",
"Qsb_inst"])
m3_file_name = "m3_riv_bas_nasa_lis_3hr_20110121to20110121.nc"
generated_m3_file = os.path.join(rapid_output_path, m3_file_name)
inf_tool.generateOutputInflowFile(out_nc=generated_m3_file,
start_datetime_utc=datetime(2008,3,3),
number_of_timesteps=len(lsm_file_list),
simulation_time_step_seconds=3*3600,
in_rapid_connect_file=os.path.join(rapid_input_path, 'rapid_connect.csv'),
in_rivid_lat_lon_z_file=os.path.join(rapid_input_path, 'comid_lat_lon_z.csv'),
land_surface_model_description="RAPID Inflow from NASA GSFC LIS hourly runoff",
modeling_institution="US Army Engineer Research and Development Center"
)
inf_tool.execute(nc_file_list=lsm_file_list,
index_list=list(xrange(len(lsm_file_list))),
in_weight_table=os.path.join(rapid_input_path, 'weight_lis.csv'),
out_nc=generated_m3_file,
grid_type='lis',
mp_lock=mp_lock)
# CHECK OUTPUT
generated_m3_file_solution = os.path.join(self.INFLOW_COMPARE_DATA_PATH, m3_file_name)
self._compare_m3(generated_m3_file,generated_m3_file_solution)
def test_generate_joules_inflow(self):
"""
Checks generating inflow file from Joules LSM
"""
rapid_input_path, rapid_output_path, output_file_info = \
self._run_automatic('joules',
"u-k",
file_datetime_pattern="%Y%m%d_%H",
file_datetime_re_pattern=r'\d{8}_\d{2}',
convert_one_hour_to_three=True)
# CHECK OUTPUT
m3_file_name = "m3_riv_bas_met_office_joules_3hr_20080803to20080803.nc"
generated_m3_file = os.path.join(rapid_output_path, m3_file_name)
generated_m3_file_solution = os.path.join(self.INFLOW_COMPARE_DATA_PATH, m3_file_name)
# check other info in netcdf file
self._compare_m3(generated_m3_file, generated_m3_file_solution)
# check output file info
assert output_file_info[0]['u-k']['m3_riv'] == generated_m3_file
def test_generate_joules_inflow2(self):
"""
Checks generating inflow file from Joules LSM manually
"""
rapid_input_path, rapid_output_path = self._setup_manual("u-k")
lsm_file_list = sorted(glob(os.path.join(self.LSM_INPUT_DATA_PATH, 'joules', '*.nc')))
lsm_file_list = [lsm_file_list[nldas_index:nldas_index+3] for nldas_index in range(0, len(lsm_file_list), 3)\
if len(lsm_file_list[nldas_index:nldas_index+3])==3]
mp_lock = multiprocessing.Manager().Lock()
inf_tool = CreateInflowFileFromLDASRunoff(lat_dim="north_south",
lon_dim="east_west",
lat_var="north_south",
lon_var="east_west",
runoff_vars=["Qs_inst",
"Qsb_inst"])
m3_file_name = "m3_riv_bas_met_office_joules_3hr_20080803to20080803.nc"
generated_m3_file = os.path.join(rapid_output_path, m3_file_name)
inf_tool.generateOutputInflowFile(out_nc=generated_m3_file,
start_datetime_utc=datetime(2008,3,3),
number_of_timesteps=len(lsm_file_list),
simulation_time_step_seconds=3*3600,
in_rapid_connect_file=os.path.join(rapid_input_path, 'rapid_connect.csv'),
in_rivid_lat_lon_z_file=os.path.join(rapid_input_path, 'comid_lat_lon_z.csv'),
land_surface_model_description="RAPID Inflow from Met Office Joules Hourly Runoff",
modeling_institution="US Army Engineer Research and Development Center"
)
inf_tool.execute(nc_file_list=lsm_file_list,
index_list=list(xrange(len(lsm_file_list))),
in_weight_table=os.path.join(rapid_input_path, 'weight_joules.csv'),
out_nc=generated_m3_file,
grid_type='joules',
mp_lock=mp_lock)
# CHECK OUTPUT
generated_m3_file_solution = os.path.join(self.INFLOW_COMPARE_DATA_PATH, m3_file_name)
self._compare_m3(generated_m3_file, generated_m3_file_solution)
def test_generate_erai_t511_24_inflow(self):
"""
Checks generating inflow file from ERA Interim t511 24hr LSM
"""
# run main process
rapid_input_path, rapid_output_path, output_file_info = self._run_automatic('erai24', "x-x")
# CHECK OUTPUT
# m3_riv
m3_file_name = "m3_riv_bas_erai_t511_24hr_19990109to19990110.nc"
generated_m3_file = os.path.join(rapid_output_path, m3_file_name)
generated_m3_file_solution = os.path.join(self.INFLOW_COMPARE_DATA_PATH, m3_file_name)
self._compare_m3(generated_m3_file,generated_m3_file_solution)
# check output file info
assert output_file_info[0]['x-x']['m3_riv'] == generated_m3_file
def test_generate_erai_t511_24_inflow2(self):
"""
Checks generating inflow file from ERA Interim t511 24hr LSM manually
"""
rapid_input_path, rapid_output_path = self._setup_manual("x-x")
lsm_file_list = sorted(glob(os.path.join(self.LSM_INPUT_DATA_PATH, 'erai24', '*.nc')))
mp_lock = multiprocessing.Manager().Lock()
inf_tool = CreateInflowFileFromERAInterimRunoff()
m3_file_name = "m3_riv_bas_erai_t511_24hr_19990109to19990110.nc"
generated_m3_file = os.path.join(rapid_output_path, m3_file_name)
inf_tool.generateOutputInflowFile(out_nc=generated_m3_file,
start_datetime_utc=datetime(1999,1,9),
number_of_timesteps=len(lsm_file_list),
simulation_time_step_seconds=24*3600,
in_rapid_connect_file=os.path.join(rapid_input_path, 'rapid_connect.csv'),
in_rivid_lat_lon_z_file=os.path.join(rapid_input_path, 'comid_lat_lon_z.csv'),
land_surface_model_description="RAPID Inflow from ERA Interim (T511 Grid) 24 Hourly Runoff",
modeling_institution="US Army Engineer Research and Development Center"
)
inf_tool.execute(nc_file_list=lsm_file_list,
index_list=list(xrange(len(lsm_file_list))),
in_weight_table=os.path.join(rapid_input_path, 'weight_era_t511.csv'),
out_nc=generated_m3_file,
grid_type='t511',
mp_lock=mp_lock)
# CHECK OUTPUT
generated_m3_file_solution = os.path.join(self.INFLOW_COMPARE_DATA_PATH, m3_file_name)
self._compare_m3(generated_m3_file,generated_m3_file_solution)
def test_generate_wrf_inflow(self):
"""
Checks generating inflow file from WRF LSM
"""
# run main process
rapid_input_path, rapid_output_path, output_file_info = self._run_automatic('wrf', "m-s")
# CHECK OUTPUT
# m3_riv
m3_file_name = "m3_riv_bas_wrf_wrf_1hr_20080601to20080601.nc"
generated_m3_file = os.path.join(rapid_output_path, m3_file_name)
generated_m3_file_solution = os.path.join(self.INFLOW_COMPARE_DATA_PATH, m3_file_name)
self._compare_m3(generated_m3_file, generated_m3_file_solution)
# check output file info
assert output_file_info[0]['m-s']['m3_riv'] == generated_m3_file
def test_generate_wrf_inflow2(self):
"""
Checks generating inflow file from WRF LSM manually
"""
rapid_input_path, rapid_output_path = self._setup_manual("m-s")
lsm_file_list = sorted(glob(os.path.join(self.LSM_INPUT_DATA_PATH, 'wrf', '*.nc')))
mp_lock = multiprocessing.Manager().Lock()
inf_tool = CreateInflowFileFromWRFHydroRunoff(lat_dim="south_north",
lon_dim="west_east",
lat_var="XLAT",
lon_var="XLONG",
surface_runoff_var="SFROFF",
subsurface_runoff_var="UDROFF",
)
m3_file_name = "m3_riv_bas_wrf_wrf_1hr_20080601to20080601.nc"
generated_m3_file = os.path.join(rapid_output_path, m3_file_name)
inf_tool.generateOutputInflowFile(out_nc=generated_m3_file,
start_datetime_utc=datetime(2008,6,1),
number_of_timesteps=len(lsm_file_list),
simulation_time_step_seconds=3*3600,
in_rapid_connect_file=os.path.join(rapid_input_path, 'rapid_connect.csv'),
in_rivid_lat_lon_z_file=os.path.join(rapid_input_path, 'comid_lat_lon_z.csv'),
land_surface_model_description="RAPID Inflow from WRF Hourly Runoff",
modeling_institution="US Army Engineer Research and Development Center"
)
inf_tool.execute(nc_file_list=lsm_file_list,
index_list=list(xrange(len(lsm_file_list))),
in_weight_table=os.path.join(rapid_input_path, 'weight_wrf.csv'),
out_nc=generated_m3_file,
grid_type='wrf',
mp_lock=mp_lock)
# CHECK OUTPUT
generated_m3_file_solution = os.path.join(self.INFLOW_COMPARE_DATA_PATH, m3_file_name)
self._compare_m3(generated_m3_file,generated_m3_file_solution)
def test_generate_cmip5_inflow(self):
"""
Checks generating inflow file from CMIP5 LSM
"""
rapid_input_path, rapid_output_path, output_file_info = \
self._run_automatic('cmip5',
"ark-ms",
file_datetime_pattern="%Y",
file_datetime_re_pattern=r'\d{4}',
expected_time_step=24*3600)
# CHECK OUTPUT
# m3_riv
m3_file_name = "m3_riv_bas_cmip5_cmip5_24hr_20010101to20010103.nc"
generated_m3_file = os.path.join(rapid_output_path, m3_file_name)
generated_m3_file_solution = os.path.join(self.INFLOW_COMPARE_DATA_PATH, m3_file_name)
self._compare_m3(generated_m3_file,generated_m3_file_solution)
# check output file info
assert output_file_info[0]['ark-ms']['m3_riv'] == generated_m3_file
|
erdc-cm/RAPIDpy
|
tests/test_inflow.py
|
Python
|
bsd-3-clause
| 39,496
|
[
"NetCDF"
] |
806f07e2d74149c320a3c71f006665d8cc832571b2d129de654ec13713940ef7
|
""" NormalizeReturn adds return statement where relevant. """
from pythran.analyses import CFG, YieldPoints
from pythran.passmanager import Transformation
import gast as ast
class NormalizeReturn(Transformation):
'''
Adds Return statement when they are implicit,
and adds the None return value when not set
>>> import gast as ast
>>> from pythran import passmanager, backend
>>> node = ast.parse("def foo(y): print(y)")
>>> pm = passmanager.PassManager("test")
>>> _, node = pm.apply(NormalizeReturn, node)
>>> print(pm.dump(backend.Python, node))
def foo(y):
print(y)
return builtins.None
'''
def __init__(self):
super(NormalizeReturn, self).__init__(CFG)
def visit_FunctionDef(self, node):
self.yield_points = self.gather(YieldPoints, node)
for stmt in node.body:
self.visit(stmt)
# Look for nodes that have no successors; the predecessors of
# the special NIL node are those AST nodes that end control flow
# without a return statement.
for n in self.cfg.predecessors(CFG.NIL):
if not isinstance(n, (ast.Return, ast.Raise)):
self.update = True
if self.yield_points:
node.body.append(ast.Return(None))
else:
none = ast.Attribute(
ast.Name("builtins", ast.Load(), None, None),
'None',
ast.Load())
node.body.append(ast.Return(none))
break
return node
def visit_Return(self, node):
if not node.value and not self.yield_points:
none = ast.Attribute(ast.Name("builtins", ast.Load(), None, None),
'None', ast.Load())
node.value = none
self.update = True
return node
|
pombredanne/pythran
|
pythran/transformations/normalize_return.py
|
Python
|
bsd-3-clause
| 1,912
|
[
"VisIt"
] |
f7fed92cc7835e316aa6a8b9bde4752b188b084eaa0f1b301b33ffb31cea7f2e
|
from collections import defaultdict
import os
import mod_utils
import gzip
import numpy as np
import math
from statsmodels.nonparametric.smoothers_lowess import lowess
import scipy.stats.mstats as mstats
class ModLib:
def __init__(self, experiment, experiment_settings, lib_settings):
"""
Constructor for Library class
"""
self.experiment = experiment
self.experiment_settings = experiment_settings
self.lib_settings = lib_settings
self.get_property = self.experiment_settings.get_property
self.get_rdir = experiment_settings.get_rdir
self.get_wdir = experiment_settings.get_wdir
self.rRNA_mutation_data = {} #maps rRNA names to rRNA_mutations objects, which are containers for nucleotide
# objects for that rRNA
self.parse_shapemapper_output_files()
self.assign_rt_stops()
self.winsorize_rt_stops()
def parse_shapemapper_output_files(self):
for rRNA_name in self.experiment_settings.rRNA_seqs:
shapemapper_output_file = os.path.join(self.lib_settings.get_shapemapper_out_dir(),
'Pipeline_Modified_'+rRNA_name+'_mutation_counts.txt')
assert mod_utils.file_exists(shapemapper_output_file)
self.rRNA_mutation_data[rRNA_name] = rRNA_mutations(self, self.lib_settings, self.experiment_settings, shapemapper_output_file, rRNA_name)
def assign_rt_stops(self):
read_counts = mod_utils.parse_wig(self.lib_settings.get_5p_count_wig())
for rRNA_name in self.rRNA_mutation_data:
for position in read_counts[rRNA_name]:
#the rt stop is BEFORE it adds the nucleotide across from the modified one
#so the signal in read_counts[rRNA_name][position] is caused by the mod at self.nucleotides[position-1]
if position-1 in self.rRNA_mutation_data[rRNA_name].nucleotides:
nuc = self.rRNA_mutation_data[rRNA_name].nucleotides[position-1]
nuc.rt_stops = read_counts[rRNA_name][position]
self.rRNA_mutation_data[rRNA_name].total_rt_stops += nuc.rt_stops
def winsorize_rt_stops(self):
#winsorize the data by setting all RT stop counts above "winsorization_upper_percentile" to the value of the RT stops at that percentile
#collect list of all values, winsorize these to get max value, then use the max to filter RT stop counts and save new value
#then divide all by the max to get an RT stop or reactivity score.
all_rt_stop_counts = self.list_rt_stop_counts()
winsorized_counts = mstats.winsorize(all_rt_stop_counts, limits=(0, 1.-self.get_property('winsorization_upper_limit')), inplace=False)
winsorized_max = max(winsorized_counts)
for rRNA in self.rRNA_mutation_data.values():
for nucleotide in rRNA.nucleotides.values():
if nucleotide.rt_stops > winsorized_max:
nucleotide.winsorized_rt_stops = winsorized_max
else:
nucleotide.winsorized_rt_stops = nucleotide.rt_stops
nucleotide.rt_stop_score = float(nucleotide.winsorized_rt_stops)/float(winsorized_max)
def count_mutation_rates_by_nucleotide(self, subtract_background = False, subtract_control = False, exclude_constitutive=False):
"""
counts, over all RNAs, the total number of mutation rates at each of A, T, C, G
This is to get an idea of which nucleotides are being affected by a modification.
:return: a dict like {A: 1054, T:32, C: 604, G:99}
"""
total_counts = defaultdict(int)
for rRNA_name in self.rRNA_mutation_data:
rRNA_counts = self.rRNA_mutation_data[rRNA_name].count_mutation_rates_by_nucleotide(subtract_background=subtract_background,
subtract_control=subtract_control, exclude_constitutive=exclude_constitutive)
for nucleotide_type in rRNA_counts:
total_counts[nucleotide_type] += rRNA_counts[nucleotide_type]
return total_counts
def count_rt_stop_rpm_by_nucleotide(self, subtract_background = False, subtract_control = False, exclude_constitutive=False):
"""
counts, over all RNAs, the total number of RT stops at each of A, T, C, G
This is to get an idea of which nucleotides are being affected by a modification.
:return: a dict like {A: 1054, T:32, C: 604, G:99}
"""
total_counts = defaultdict(int)
for rRNA_name in self.rRNA_mutation_data:
rRNA_counts = self.rRNA_mutation_data[rRNA_name].count_rt_stop_rpm_by_nucleotide(subtract_background=subtract_background, exclude_constitutive=exclude_constitutive)
for nucleotide_type in rRNA_counts:
total_counts[nucleotide_type] += rRNA_counts[nucleotide_type]
return total_counts
def count_mutation_types_by_nucleotide(self, subtract_background = False, subtract_control = False, exclude_constitutive=False):
"""
counts, over all RNAs, the total number of each type ofmutation rates at each of A, T, C, G
This is to get an idea of which nucleotides are being affected by a modification.
:return: a dict like {A: {A->G:1054}, T:{T->G:1054}, C: {C->G:1054}, G:{G->C:1054}}
"""
total_counts = defaultdict((lambda : defaultdict(int)))
for rRNA_name in self.rRNA_mutation_data:
rRNA_counts = self.rRNA_mutation_data[rRNA_name].count_mutation_types_by_nucleotide(subtract_background=subtract_background,
subtract_control=subtract_control, exclude_constitutive=exclude_constitutive)
for nucleotide_type in rRNA_counts:
for mutation_type in rRNA_counts[nucleotide_type]:
total_counts[nucleotide_type][mutation_type] += rRNA_counts[nucleotide_type][mutation_type]
return total_counts
def count_mutation_rates_by_type(self, subtract_background = False, subtract_control = False, exclude_constitutive=False):
"""
counts, over all RNAs, the total number of mutation rates at each of A, T, C, G
This is to get an idea of which nucleotides are being affected by a modification.
:return: a dict like {A: 1054, T:32, C: 604, G:99}
"""
total_counts = defaultdict(int)
for rRNA_name in self.rRNA_mutation_data:
rRNA_counts = self.rRNA_mutation_data[rRNA_name].count_mutation_rates_by_nucleotide(subtract_background=subtract_background,
subtract_control=subtract_control, exclude_constitutive=exclude_constitutive)
for nucleotide_type in rRNA_counts:
total_counts[nucleotide_type] += rRNA_counts[nucleotide_type]
return total_counts
def list_mutation_rates(self, subtract_background = False, subtract_control = False, nucleotides_to_count = 'ATCG', exclude_constitutive=False):
all_mutation_rates = []
for rRNA_name in self.rRNA_mutation_data:
all_mutation_rates.extend(self.rRNA_mutation_data[rRNA_name].
list_mutation_rates(subtract_background = subtract_background, subtract_control = subtract_control,
nucleotides_to_count = nucleotides_to_count, exclude_constitutive=exclude_constitutive))
return all_mutation_rates
def list_rt_stop_rpms(self, subtract_background = False, subtract_control = False, nucleotides_to_count = 'ATCG', exclude_constitutive=False):
all_rt_stop_rpms = []
for rRNA_name in self.rRNA_mutation_data:
all_rt_stop_rpms.extend(self.rRNA_mutation_data[rRNA_name].
list_rt_stop_rpms(subtract_background = subtract_background, subtract_control = subtract_control,
nucleotides_to_count = nucleotides_to_count, exclude_constitutive=exclude_constitutive))
return all_rt_stop_rpms
def list_rt_stop_counts(self, nucleotides_to_count = 'ATCG'):
all_rt_stop_counts = []
for rRNA_name in self.rRNA_mutation_data:
all_rt_stop_counts.extend(self.rRNA_mutation_data[rRNA_name].list_rt_stop_counts(nucleotides_to_count=nucleotides_to_count))
return all_rt_stop_counts
def list_fold_changes(self, nucleotides_to_count = 'ATCG', exclude_constitutive=False):
all_mutation_rates = []
for rRNA_name in self.rRNA_mutation_data:
all_mutation_rates.extend(self.rRNA_mutation_data[rRNA_name].
list_mutation_fold_changes(nucleotides_to_count = nucleotides_to_count, exclude_constitutive=exclude_constitutive))
return all_mutation_rates
def get_normalizing_lib(self):
"""
#returns the library that is the normalization for this one (no-modification control)
"""
if self.lib_settings.sample_name in self.experiment_settings.get_property('experimentals'):
lib_index = self.experiment_settings.get_property('experimentals').index(self.lib_settings.sample_name)
normalizing_lib_name = self.experiment_settings.get_property('no_mod_controls')[lib_index]
return self.experiment.get_lib_from_name(normalizing_lib_name)
elif self.lib_settings.sample_name in self.experiment_settings.get_property('with_mod_controls'):
lib_index = self.experiment_settings.get_property('with_mod_controls').index(self.lib_settings.sample_name)
normalizing_lib_name = self.experiment_settings.get_property('no_mod_controls')[lib_index]
return self.experiment.get_lib_from_name(normalizing_lib_name)
else:
return None
def get_normalizing_lib_with_mod(self):
"""
#returns the library that is the normalization for this one (with-modification control)
"""
if self.lib_settings.sample_name in self.experiment_settings.get_property('experimentals'):
lib_index = self.experiment_settings.get_property('experimentals').index(self.lib_settings.sample_name)
normalizing_lib_name = self.experiment_settings.get_property('with_mod_controls')[lib_index]
return self.experiment.get_lib_from_name(normalizing_lib_name)
else:
return None
def get_nucleotide(self, rRNA_name, position):
return self.rRNA_mutation_data[rRNA_name].nucleotides[position]
def get_mutation_count_at_position(self, rRNA_name, position):
return self.rRNA_mutation_data[rRNA_name].nucleotides[position].total_mutation_counts
def get_coverage_at_position(self, rRNA_name, position):
return self.rRNA_mutation_data[rRNA_name].nucleotides[position].sequencing_depth
def get_mutation_rate_at_position(self, rRNA_name, position):
return self.rRNA_mutation_data[rRNA_name].nucleotides[position].mutation_rate
def get_rt_stop_rpm_at_position(self, rRNA_name, position):
return self.rRNA_mutation_data[rRNA_name].nucleotides[position].get_rt_stop_rpm()
def get_rt_stop_score_at_position(self, rRNA_name, position):
return self.rRNA_mutation_data[rRNA_name].nucleotides[position].rt_stop_score
def write_tsv_tables(self, tsv_filename, subtract_background=False, subtract_control=False, exclude_constitutive=False,
lowess_correct = False):
if subtract_background and subtract_control:
raise SyntaxError('Cannot subtract background and control simultaneously')
f = open(tsv_filename, 'w')
if subtract_background:
f.write('CHROMOSOME\tPOSITION\tMUTATION_RATE\tBKGD_SUB_MUT_RATE\tBKGD_SUB_ERROR\n')
elif subtract_control:
if lowess_correct:
nucleotides_to_count = self.experiment_settings.get_property('affected_nucleotides')
self.lowess_correct_mutation_fold_changes(nucleotides_to_count=nucleotides_to_count,
exclude_constitutive=exclude_constitutive)
f.write('CHROMOSOME\tPOSITION\tNUC\tEXP_MUTATION_RATE\tEXP_MUTATION_COUNTS\tEXP_99%_min\tEXP_99%_max\tCTRL_MUT_RATE\tCTRL_MUT_counts'
'\tCTRL_99%_min\tCTRL_99%_max\tEXP-CTRL\tCTRL_POISSON_SUB_ERROR\tFOLD_CHANGE\tPROTECTION_CALL\n')
elif not subtract_background and not subtract_control:
f.write('CHROMOSOME\tPOSITION\tMUTATION_RATE\tERROR\n')
for rRNA_name in self.rRNA_mutation_data:
for position in self.rRNA_mutation_data[rRNA_name].nucleotides:
nucleotide = self.rRNA_mutation_data[rRNA_name].nucleotides[position]
if lowess_correct and nucleotide.identity not in nucleotides_to_count:
continue
if exclude_constitutive and nucleotide.exclude_constitutive:
if subtract_background:
f.write(self.rRNA_mutation_data[rRNA_name].rRNA_name+'\t'+str(nucleotide.position)+'\t'
+'0'+'\t'+'0'+'\t'
+'0'+'\n')
elif subtract_control:
f.write(self.rRNA_mutation_data[rRNA_name].rRNA_name+'\t'+str(nucleotide.position)+'\t'+
str(nucleotide.identity)+'\t\t\t\t\t\t\t\t\t\t\t\t\n')
elif not subtract_background and not subtract_control:
f.write(self.rRNA_mutation_data[rRNA_name].rRNA_name+'\t'+str(nucleotide.position)+'\t'
+'0'+'\t'+'0'+'\n')
else:
if subtract_background:
f.write(self.rRNA_mutation_data[rRNA_name].rRNA_name+'\t'+str(nucleotide.position)+'\t'
+str(nucleotide.mutation_rate)+'\t'+str(nucleotide.get_back_sub_mutation_rate())+'\t'
+str(nucleotide.get_back_sub_error())+'\n')
elif subtract_control:
ctrl_nuc = nucleotide.get_control_nucleotide()
if lowess_correct:
fold_change = nucleotide.lowess_fc
else:
fold_change = nucleotide.get_control_fold_change_in_mutation_rate()
exp_wil_bottom, exp_wil_top = nucleotide.get_wilson_approximate_score_interval()
ctrl_wil_bottom, ctrl_wil_top = ctrl_nuc.get_wilson_approximate_score_interval()
f.write('%s\t%d\t%s\t%f\t%f\t%f\t%f\t%f\t%f\t%f\t%f\t%f\t%f\t%f\t%s\n' %
(rRNA_name, nucleotide.position, nucleotide.identity, nucleotide.mutation_rate, nucleotide.total_mutation_counts,
exp_wil_bottom, exp_wil_top, ctrl_nuc.mutation_rate, ctrl_nuc.total_mutation_counts,
ctrl_wil_bottom, ctrl_wil_top, nucleotide.get_control_sub_mutation_rate(),
nucleotide.get_control_sub_error(), fold_change,
nucleotide.determine_protection_status(confidence_interval=self.experiment_settings.get_property('confidence_interval_cutoff'),
fold_change_cutoff=self.experiment_settings.get_property('fold_change_cutoff'), lowess_correct = lowess_correct)))
elif not subtract_background and not subtract_control:
f.write(self.rRNA_mutation_data[rRNA_name].rRNA_name+'\t'+str(nucleotide.position)+'\t'
+str(nucleotide.mutation_rate)+'\t'+str(nucleotide.get_error())+'\n')
f.close()
def pickle_mutation_rates(self, output_name, subtract_background=False, subtract_control=False, exclude_constitutive=False):
"""
stores mutation rates as a simple pickle, of {rRNA_name:{position:mutation rate}}
:param subtract_background:
:return:
"""
output_dict = {}
for rRNA in self.rRNA_mutation_data:
output_dict[rRNA] = {}
for position in self.rRNA_mutation_data[rRNA].nucleotides:
nucleotide = self.rRNA_mutation_data[rRNA].nucleotides[position]
if exclude_constitutive and nucleotide.exclude_constitutive:
output_dict[rRNA][position] = 0
else:
if subtract_background and subtract_control:
raise SyntaxError('Cannot subtract background and control simultaneously')
if subtract_background:
output_dict[rRNA][position] = max((nucleotide.mutation_rate - self.get_normalizing_lib().
get_mutation_rate_at_position(rRNA, nucleotide.position)), 0.)
elif subtract_control:
output_dict[rRNA][position] = nucleotide.mutation_rate - self.get_normalizing_lib_with_mod().get_mutation_rate_at_position(rRNA, nucleotide.position)
else:
output_dict[rRNA][position] = nucleotide.mutation_rate
mod_utils.makePickle(output_dict, output_name)
def pickle_mutation_fold_change(self, output_name, exclude_constitutive=False):
"""
stores mutation rates as a simple pickle, of {rRNA_name:{position:mutation rate}}
:param subtract_background:
:return:
"""
output_dict = {}
for rRNA in self.rRNA_mutation_data:
output_dict[rRNA] = {}
for position in self.rRNA_mutation_data[rRNA].nucleotides:
nucleotide = self.rRNA_mutation_data[rRNA].nucleotides[position]
if exclude_constitutive and nucleotide.exclude_constitutive:
output_dict[rRNA][position] = 1.0
else:
try:
output_dict[rRNA][position] = nucleotide.mutation_rate/self.get_normalizing_lib_with_mod().get_mutation_rate_at_position(rRNA, nucleotide.position)
except:
output_dict[rRNA][position] = float('inf')*nucleotide.mutation_rate
mod_utils.makePickle(output_dict, output_name)
def write_mutation_rates_to_wig(self, output_prefix, subtract_background = False, subtract_control = False):
"""
write out mutation rates to a wig file that can be opened with a program like IGV or mochiview,
given the corresponding rRNA fasta as a genome, of course
:param output_prefix:
:param subtract_background:
:param subtract_control
:return:
"""
wig = gzip.open(output_prefix+'.wig.gz', 'w')
if subtract_background:
wig.write('track type=wiggle_0 name=%s\n' % (self.lib_settings.sample_name+'_back_sub'))
elif subtract_control:
wig.write('track type=wiggle_0 name=%s\n' % (self.lib_settings.sample_name+'_control_sub'))
elif not subtract_background and not subtract_control:
wig.write('track type=wiggle_0 name=%s\n' % (self.lib_settings.sample_name))
for rRNA_name in self.rRNA_mutation_data:
if subtract_background and subtract_control:
raise SyntaxError('Cannot subtract background and control simultaneously')
if subtract_background:
wig.write('variableStep chrom=%s\n' % (rRNA_name))
for position in sorted(self.rRNA_mutation_data[rRNA_name].nucleotides.keys()):
if subtract_background:
wig.write('%d\t%f\n' % (position, self.rRNA_mutation_data[rRNA_name].
nucleotides[position].get_back_sub_mutation_rate()))
else:
wig.write('%d\t%f\n' % (position, self.rRNA_mutation_data[rRNA_name].
nucleotides[position].get_back_sub_mutation_rate()))
elif subtract_control:
wig.write('variableStep chrom=%s\n' % (rRNA_name))
for position in sorted(self.rRNA_mutation_data[rRNA_name].nucleotides.keys()):
if subtract_control:
wig.write('%d\t%f\n' % (position, self.rRNA_mutation_data[rRNA_name].
nucleotides[position].get_control_sub_mutation_rate()))
else:
wig.write('%d\t%f\n' % (position, self.rRNA_mutation_data[rRNA_name].
nucleotides[position].get_control_sub_mutation_rate()))
else:
wig.write('variableStep chrom=%s\n' % (rRNA_name))
for position in sorted(self.rRNA_mutation_data[rRNA_name].nucleotides.keys()):
if subtract_background:
wig.write('%d\t%f\n' % (position, self.rRNA_mutation_data[rRNA_name].
nucleotides[position].mutation_rate))
else:
wig.write('%d\t%f\n' % (position, self.rRNA_mutation_data[rRNA_name].
nucleotides[position].mutation_rate))
wig.close()
def write_rt_stops_to_wig(self, output_prefix):
"""
write out mutation rates to a wig file that can be opened with a program like IGV or mochiview,
given the corresponding rRNA fasta as a genome, of course
:param output_prefix:
:param subtract_background:
:param subtract_control
:return:
"""
wig = gzip.open(output_prefix+'.wig.gz', 'w')
wig.write('track type=wiggle_0 name=%s\n' % (self.lib_settings.sample_name))
for rRNA_name in self.rRNA_mutation_data:
wig.write('variableStep chrom=%s\n' % (rRNA_name))
for position in sorted(self.rRNA_mutation_data[rRNA_name].nucleotides.keys()):
wig.write('%d\t%f\n' % (position+1, self.get_rt_stop_rpm_at_position(rRNA_name, position)))
wig.close()
def write_rt_stop_scores_to_wig(self, output_prefix):
"""
write out mutation rates to a wig file that can be opened with a program like IGV or mochiview,
given the corresponding rRNA fasta as a genome, of course
:param output_prefix:
:param subtract_background:
:param subtract_control
:return:
"""
wig = gzip.open(output_prefix+'.wig.gz', 'w')
wig.write('track type=wiggle_0 name=%s\n' % (self.lib_settings.sample_name))
for rRNA_name in self.rRNA_mutation_data:
wig.write('variableStep chrom=%s\n' % (rRNA_name))
for position in sorted(self.rRNA_mutation_data[rRNA_name].nucleotides.keys()):
wig.write('%d\t%f\n' % (position+1, self.get_rt_stop_score_at_position(rRNA_name, position)))
wig.close()
def get_changed_nucleotides(self, change_type, nucleotides_to_count='ATCG', exclude_constitutive=False,
confidence_interval = 0.99, fold_change_cutoff = 3, subtract_background=False):
changed_nucleotides = {}
for rRNA_name in self.rRNA_mutation_data:
changed_nucleotides[rRNA_name] = self.rRNA_mutation_data[rRNA_name].\
get_changed_nucleotides(change_type, nucleotides_to_count=nucleotides_to_count,
exclude_constitutive=exclude_constitutive,
confidence_interval = confidence_interval,
fold_change_cutoff = fold_change_cutoff,
subtract_background=subtract_background)
return changed_nucleotides
def get_nucleotides_from_list(self, nucleotide_list, nucleotides_to_count = 'ATCG', exclude_constitutive=False):
"""
:param nucleotide_list: a list of nucleotide-identifying strings like: 'S.c.18S_rRNA 2125 A'
:return: a list of the nucleotide objects matching those strings
"""
nucleotides = []
for nucleotide_string in nucleotide_list:
rRNA_name, position, identity = nucleotide_string.strip().split(' ')
position = int(position)
identity = identity.upper().replace('U', 'T')
#print nucleotide_string, identity
assert identity in 'ATCGU'
if identity in nucleotides_to_count:
nucleotide_match = self.get_nucleotide(rRNA_name, position)
assert nucleotide_match.identity == identity
if not (exclude_constitutive and nucleotide_match.exclude_constitutive):
nucleotides.append(nucleotide_match)
return nucleotides
def get_all_nucleotides(self, nucleotides_to_count = 'ATCG', exclude_constitutive=False):
"""
return a list of all nucleotides subject to the optional parameters
:param nucleotides_to_count:
:param exclude_constitutive:
:return:
"""
nucleotides = []
for rRNA in self.rRNA_mutation_data.values():
nucleotides += rRNA.get_all_nucleotides(nucleotides_to_count = nucleotides_to_count,
exclude_constitutive=exclude_constitutive)
return nucleotides
def lowess_correct_mutation_fold_changes(self, nucleotides_to_count ='ATCG', exclude_constitutive=False, max_fold_reduction=0.001, max_fold_increase=100):
"""
Add a lowess regression corrected fold change, by regressing on the
:param nucleotides_to_count:
:param exclude_constitutive:
:return:
"""
nucs = self.get_all_nucleotides(nucleotides_to_count = nucleotides_to_count,
exclude_constitutive=exclude_constitutive)
nuc_fold_changes = [nuc.get_control_fold_change_in_mutation_rate() for nuc in nucs]
for i in range(len(nuc_fold_changes)):
if nuc_fold_changes[i] == 0:
nuc_fold_changes[i] = max_fold_reduction
elif nuc_fold_changes[i] == float('inf'):
nuc_fold_changes[i] = max_fold_increase
nuc_avg_counts = [(nuc.total_mutation_counts+nuc.get_control_nucleotide().total_mutation_counts)/2.0
for nuc in nucs]
fc_log = [math.log(fc, 10) for fc in nuc_fold_changes]
mag_log = [math.log(m, 10) if m > 0 else -1. for m in nuc_avg_counts]
lowess_fc_log = lowess(fc_log, mag_log, return_sorted=False)
lowess_fc = 10 ** lowess_fc_log
for i in range(len(nucs)):
nucs[i].lowess_fc = nucs[i].get_control_fold_change_in_mutation_rate()/lowess_fc[i]
class rRNA_mutations:
def __init__(self, lib, lib_settings, experiment_settings, mutation_filename, rRNA_name):
self.lib = lib
self.lib_settings = lib_settings
self.experiment_settings = experiment_settings
self.nucleotides = {}
self.rRNA_name = rRNA_name
self.parse_mutations_columns(mutation_filename)
self.total_rt_stops = 0.0
def parse_mutations_columns(self, filename):
f= open(filename, 'rU')
lines = f.readlines()
self.sequence = self.experiment_settings.rRNA_seqs[self.rRNA_name]
headers = lines[0].strip().split('\t')
position = 1
for line in lines[1:]:
if line.strip().strip('\t') != '':
nucleotide_data = Nucleotide(self, position, headers, line, self.lib_settings)
self.nucleotides[nucleotide_data.position] = nucleotide_data
position += 1
f.close()
def count_mutation_rates_by_nucleotide(self, subtract_background=False, subtract_control=False, exclude_constitutive=False):
"""
counts, over this RNA, the total number of mutations at each of A, T, C, G
This is to get an idea of which nucleotides are being affected by a modification.
NOTE that this will set any background-subtracted rate of less than zero to zero
:return: a dict like {A: 1054, T:32, C: 604, G:99}
"""
counts = defaultdict(int)
for nucleotide in self.nucleotides.values():
if exclude_constitutive and nucleotide.exclude_constitutive:
continue
else:
if subtract_background and subtract_control:
raise SyntaxError('Cannot subtract background and control simultaneously')
if subtract_background:
counts[nucleotide.identity] += max((nucleotide.mutation_rate - self.lib.get_normalizing_lib().
get_mutation_rate_at_position(self.rRNA_name, nucleotide.position)), 0.)
elif subtract_control:
counts[nucleotide.identity] += nucleotide.mutation_rate - self.lib.get_normalizing_lib_with_mod().get_mutation_rate_at_position(self.rRNA_name, nucleotide.position)
else:
counts[nucleotide.identity] += nucleotide.mutation_rate
return counts
def count_rt_stop_rpm_by_nucleotide(self, subtract_background=False, subtract_control=False, exclude_constitutive=False):
"""
counts, over this RNA, the total number of mutations at each of A, T, C, G
This is to get an idea of which nucleotides are being affected by a modification.
NOTE that this will set any background-subtracted rate of less than zero to zero
:return: a dict like {A: 1054, T:32, C: 604, G:99}
"""
counts = defaultdict(int)
for nucleotide in self.nucleotides.values():
if exclude_constitutive and nucleotide.exclude_constitutive:
continue
else:
if subtract_background and subtract_control:
raise SyntaxError('Cannot subtract background and control simultaneously')
if subtract_background:
counts[nucleotide.identity] += max((nucleotide.get_rt_stop_rpm() - self.lib.get_normalizing_lib().
get_rt_stop_rpm_at_position(self.rRNA_name, nucleotide.position)), 0.)
elif subtract_control:
counts[nucleotide.identity] += nucleotide.get_rt_stop_rpm() - self.lib.get_normalizing_lib_with_mod().get_rt_stop_rpm_at_position(self.rRNA_name, nucleotide.position)
else:
counts[nucleotide.identity] += nucleotide.get_rt_stop_rpm()
return counts
def count_mutation_types_by_nucleotide(self, subtract_background=False, subtract_control=False, exclude_constitutive=False):
"""
counts, over this RNA, the total number of mutation of each type at each of A, T, C, G
This is to get an idea of which nucleotides are being affected by a particular mutation
NOTE that this will set any background-subtracted rate of less than zero to zero
"""
counts = defaultdict((lambda : defaultdict(int)))
for nucleotide in self.nucleotides.values():
if exclude_constitutive and nucleotide.exclude_constitutive:
continue
else:
for mutation_type in nucleotide.mutations_by_type:
counts[nucleotide.identity][mutation_type] += nucleotide.mutations_by_type[mutation_type]
return counts
def list_mutation_rates(self, subtract_background=False, subtract_control = False, nucleotides_to_count='ATCG', exclude_constitutive=False):
"""
#note that these values may be less than zero when background is subtracted
:param subtract_background:
:return:
"""
rates = []
for nucleotide in self.nucleotides.values():
if nucleotide.identity in nucleotides_to_count:
if exclude_constitutive and nucleotide.exclude_constitutive:
continue
else:
if subtract_background and subtract_control:
raise SyntaxError('Cannot subtract background and control simultaneously')
if subtract_background:
rates.append((nucleotide.mutation_rate - self.lib.get_normalizing_lib().
get_mutation_rate_at_position(self.rRNA_name, nucleotide.position)))
elif subtract_control:
rates.append((nucleotide.mutation_rate - self.lib.get_normalizing_lib_with_mod().
get_mutation_rate_at_position(self.rRNA_name, nucleotide.position)))
else:
rates.append(nucleotide.mutation_rate)
return rates
def list_rt_stop_rpms(self, subtract_background=False, subtract_control = False, nucleotides_to_count='ATCG', exclude_constitutive=False):
"""
#note that these values may be less than zero when background is subtracted
:param subtract_background:
:return:
"""
rates = []
for nucleotide in self.nucleotides.values():
if nucleotide.identity in nucleotides_to_count:
if exclude_constitutive and nucleotide.exclude_constitutive:
continue
else:
if subtract_background and subtract_control:
raise SyntaxError('Cannot subtract background and control simultaneously')
if subtract_background:
rates.append((nucleotide.get_rt_stop_rpm() - self.lib.get_normalizing_lib().
get_rt_stop_rpm_at_position(self.rRNA_name, nucleotide.position)))
elif subtract_control:
rates.append((nucleotide.get_rt_stop_rpm() - self.lib.get_normalizing_lib_with_mod().
get_rt_stop_rpm_at_position(self.rRNA_name, nucleotide.position)))
else:
rates.append(nucleotide.get_rt_stop_rpm())
return rates
def list_rt_stop_counts(self, nucleotides_to_count='ATCG'):
"""
#note that these values may be less than zero when background is subtracted
:param subtract_background:
:return:
"""
rates = []
for nucleotide in self.nucleotides.values():
if nucleotide.identity in nucleotides_to_count:
rates.append(nucleotide.rt_stops)
return rates
def list_mutation_fold_changes(self, nucleotides_to_count='ATCG', exclude_constitutive=False):
"""
#note that these values may be less than zero when background is subtracted
:param subtract_background:
:return:
"""
rates = []
for nucleotide in self.nucleotides.values():
if nucleotide.identity in nucleotides_to_count:
if exclude_constitutive and nucleotide.exclude_constitutive:
continue
elif nucleotide.get_control_fold_change_in_mutation_rate() == 0.0 or \
nucleotide.get_control_fold_change_in_mutation_rate() == float('inf'):
continue
else:
rates.append(nucleotide.get_control_fold_change_in_mutation_rate())
return rates
def get_changed_nucleotides(self, change_type, nucleotides_to_count='ATCG', exclude_constitutive=False,
confidence_interval = 0.99, fold_change_cutoff = 3, subtract_background=False):
nucleotides = []
for nucleotide in self.nucleotides.values():
if nucleotide.identity in nucleotides_to_count:
if exclude_constitutive and nucleotide.exclude_constitutive:
continue
else:
prot_call = nucleotide.determine_protection_status(confidence_interval=confidence_interval,
fold_change_cutoff=fold_change_cutoff,
subtract_background=subtract_background)
if prot_call == change_type:
nucleotides.append(nucleotide)
return nucleotides
def get_all_nucleotides(self, nucleotides_to_count='ATCG', exclude_constitutive=False):
"""
return a list of all nucleotides subject to the optional parameters
:param nucleotides_to_count:
:param exclude_constitutive:
:return:
"""
nucleotides = []
for nucleotide in self.nucleotides.values():
if nucleotide.identity in nucleotides_to_count:
if exclude_constitutive and nucleotide.exclude_constitutive:
continue
else:
nucleotides.append(nucleotide)
return nucleotides
class Nucleotide:
def __init__(self, rRNA, position, headers, mutation_data_line, lib_settings):
self.rRNA = rRNA
self.position = position
self.identity = rRNA.sequence[self.position-1]
self.mutations_by_type = {} #will map each type of mutation to the number of such mutations detected
self.rt_stops = 0
self.lib_settings = lib_settings
self.parse_mutation_data_line(headers, mutation_data_line)
self.set_exclusion_flag()
def __str__(self):
return "%s%d in %s of %s" % (self.identity, self.position, self.rRNA.rRNA_name, self.lib_settings.sample_name)
def parse_mutation_data_line(self, headers, mutation_data_line):
ll = mutation_data_line.strip().split('\t')
self.total_mutation_counts = sum([float(ll[i]) for i in range(0, 26)])
self.sequencing_depth = float(ll[26])
self.effective_sequencing_depth = float(ll[27])
try:
self.mutation_rate = self.total_mutation_counts/self.sequencing_depth
except:
self.mutation_rate = 0
for i in range(0, 26):
self.mutations_by_type[headers[i]] = float(ll[i])
def set_exclusion_flag(self):
try:
exclusions = self.lib_settings.experiment_settings.exclude_constitutive[self.rRNA.rRNA_name]
if self.position in exclusions:
self.exclude_constitutive = True
else:
self.exclude_constitutive = False
except KeyError:
self.exclude_constitutive = False
def get_back_sub_mutation_rate(self):
return (self.mutation_rate - self.get_background_nucleotide().mutation_rate)
def get_control_sub_mutation_rate(self, subtract_background=False):
if subtract_background:
return (self.get_back_sub_mutation_rate() - self.get_control_nucleotide().get_back_sub_mutation_rate())
else:
return (self.mutation_rate - self.get_control_nucleotide().mutation_rate)
def get_control_fold_change_in_mutation_rate(self, subtract_background = False):
try:
if subtract_background:
return self.get_back_sub_mutation_rate()/self.get_control_nucleotide().get_back_sub_mutation_rate()
else:
return self.mutation_rate/self.get_control_nucleotide().mutation_rate
except ZeroDivisionError:
return float('inf')
def get_fold_signal_over_background(self, background_nuc):
try:
return (self.mutation_rate/background_nuc.mutation_rate)
except ZeroDivisionError:
return float('inf')
def get_control_fold_change_error(self, subtract_background=False, max_fold_reduction=0.001, max_fold_increase=100,
lowess_correct=False):
try:
if lowess_correct:
ratio = self.lowess_fc
else:
ratio = self.get_control_fold_change_in_mutation_rate(subtract_background=subtract_background)
if ratio == float('inf') or ratio == -1*float('inf'):
ratio = max_fold_increase
elif ratio<=0:
ratio = max_fold_reduction
if subtract_background:
num = self.get_back_sub_mutation_rate()
num_error = self.get_back_sub_error()
denom = self.get_control_nucleotide().get_back_sub_mutation_rate()
denom_error = self.get_control_nucleotide().get_back_sub_error()
else:
num = self.mutation_rate
num_error = self.get_error()
denom = self.get_control_nucleotide().mutation_rate
denom_error = self.get_control_nucleotide().get_error()
return ratio*math.sqrt((num_error/num)**2+(denom_error/denom)**2)
except ZeroDivisionError:
return float('inf')
def get_signal_error(self, background_nuc, max_fold_reduction=0.0001, max_fold_increase=10000):
'''
return the counting error for the signal of test_nuc over background_nuc
'''
try:
ratio = self.get_fold_signal_over_background(background_nuc)
if ratio == float('inf') or ratio == -1*float('inf'):
ratio = max_fold_increase
elif ratio<=0:
ratio = max_fold_reduction
num = self.mutation_rate
num_error = self.get_error()
denom = background_nuc.mutation_rate
denom_error = background_nuc.get_error()
return ratio*math.sqrt((num_error/num)**2+(denom_error/denom)**2)
except ZeroDivisionError:
return float('inf')
def get_control_mutation_rate(self):
return self.rRNA.lib.get_normalizing_lib_with_mod().\
get_mutation_rate_at_position(self.rRNA.rRNA_name, self.position)
def get_control_nucleotide(self):
return self.rRNA.lib.get_normalizing_lib_with_mod().rRNA_mutation_data[self.rRNA.rRNA_name].nucleotides[self.position]
def get_background_nucleotide(self):
return self.rRNA.lib.get_normalizing_lib().rRNA_mutation_data[self.rRNA.rRNA_name].nucleotides[self.position]
def get_wilson_approximate_score_interval(self, confidence_interval = 0.99):
"""
Computes the wilson score interval, which APPROXIMATES the confidence interval for the mean of the binomial
distribution, given a sampling of the distribution.
:return:
"""
alpha = (1.0-confidence_interval)
z = 1.0-(alpha/2.0)
n = self.sequencing_depth
p = self.mutation_rate
#breaking up equation
a = 1.0/(1.0+(z**2)/n)
b = p+((z**2)/(2.0*n))
c = z*math.sqrt((p*(1.0-p))/n + (z**2)/(4*(n**2)))
interval_bottom = a*(b-c)
interval_top = a*(b+c)
return interval_bottom, interval_top
def determine_protection_status(self, confidence_interval = 0.99, fold_change_cutoff = 5, subtract_background=False,
max_fold_reduction=0.001, max_fold_increase=100, lowess_correct=False):
#self_min, self_max = self.get_wilson_approximate_score_interval(confidence_interval=confidence_interval)
#control_min, control_max = self.get_control_nucleotide().\
# get_wilson_approximate_score_interval(confidence_interval=confidence_interval)
#if mod_utils.ranges_overlap(self_min, self_max, control_min, control_max) \
# or (self.get_control_fold_change_in_mutation_rate()<fold_change_cutoff
# and self.get_control_fold_change_in_mutation_rate()>1.0/fold_change_cutoff) or self.identity not in \
# self.lib_settings.experiment_settings.get_property('affected_nucleotides'):
# return "no_change"
if lowess_correct:
fold_change = self.lowess_fc
if subtract_background:
print "WARNING: lowess correction overrides background subtraction"
else:
fold_change = self.get_control_fold_change_in_mutation_rate(subtract_background=subtract_background)
#these outliers are always on the edge of the rRNA, so they're probably spurious low-coverage events
if not (self.signal_above_background(self.get_control_nucleotide(), self.get_background_nucleotide(), confidence_interval=0.9) or
self.signal_above_background(self, self.get_background_nucleotide(), confidence_interval=0.9)):
return "no_change"
elif fold_change == float('inf') or fold_change == -1*float('inf'):
#fold_change = max_fold_increase
return "no_change"
elif fold_change<=0:
#fold_change = max_fold_reduction
return "no_change"
mean = math.log(fold_change) #natural log to make dist more gaussian
standard_deviation = self.get_control_fold_change_error(subtract_background=subtract_background,
lowess_correct=lowess_correct)/fold_change #error propogation for natural log
p, z = mod_utils.computePfromMeanAndStDevZscore(mean, standard_deviation, 0) #what is the chance that no change could come from this dist?
if (p > 1.0-confidence_interval and p<confidence_interval)or (self.get_control_fold_change_in_mutation_rate(subtract_background=subtract_background)<fold_change_cutoff
and self.get_control_fold_change_in_mutation_rate(subtract_background=subtract_background)>1.0/fold_change_cutoff)\
or self.identity not in self.lib_settings.experiment_settings.get_property('affected_nucleotides'):
return "no_change"
elif self.get_control_sub_mutation_rate(subtract_background=subtract_background)<0:
return "protected"
elif self.get_control_sub_mutation_rate(subtract_background=subtract_background)>0:
return "deprotected"
else:
return "something_is_wrong_change_zero"
def signal_above_background(self, test_nuc, background_nuc, confidence_interval = 0.9, max_fold_reduction=0.0001, max_fold_increase=10000):
'''
return True if signal in test dataset is statistically significantly above the background dataset
Must provide a nucleotide object for test_lib and background_lib
'''
fold_change = test_nuc.get_fold_signal_over_background(background_nuc)
if fold_change == float('inf') or fold_change == -1 * float('inf'):
fold_change = max_fold_increase
elif fold_change <= 0:
fold_change = max_fold_reduction
mean = math.log(fold_change) #natural log to make dist more gaussian
standard_deviation = test_nuc.get_signal_error(background_nuc)/fold_change #error propogation for natural log
p, z = mod_utils.computePfromMeanAndStDevZscore(mean, standard_deviation, 0) #what is the chance that no change could come from this dist?
if (p<confidence_interval):
return False
elif test_nuc.mutation_rate-background_nuc.mutation_rate<0:
return False
elif test_nuc.mutation_rate-background_nuc.mutation_rate>0:
return True
else:
return False
def get_error(self):
try:
return(np.sqrt(self.mutation_rate/self.sequencing_depth))
except ZeroDivisionError:
return float('inf')
def get_back_sub_error(self):
mutation_rate = self.get_back_sub_mutation_rate()
if mutation_rate < 0:
mutation_rate = 0
try:
return(np.sqrt(mutation_rate/self.sequencing_depth))
except ZeroDivisionError:
return float('inf')
def get_control_sub_error(self):
mutation_rate = self.get_back_sub_mutation_rate()
if mutation_rate < 0:
mutation_rate = 0
try:
return(np.sqrt(mutation_rate/self.sequencing_depth))
except ZeroDivisionError:
return float('inf')
def get_rt_stop_rpm(self):
return self.rt_stops/(self.rRNA.total_rt_stops/1000000.0)
|
borisz264/mod_seq
|
mod_lib.py
|
Python
|
mit
| 48,864
|
[
"Gaussian"
] |
3230e85979d3b3736e434b769c2b4dd323bcd80904316ac83d4e738f341efc70
|
import numpy as np
import random as rand
import sys, os
import copy
import pickle
from mpi4py import MPI
from pymatgen import Lattice, Structure, Element
from pymatgen.io.vasp import Poscar, VaspInput
from pymatgen.analysis.structure_matcher import StructureMatcher, FrameworkComparator
from pymatgen.apps.borg.hive import SimpleVaspToComputedEntryDrone
from pymatgen.apps.borg.queen import BorgQueen
#from mc.applications.dft_spinel_mix.dft_spinel_mix import dft_spinel_mix, spinel_config
from applications.dft_spinel_mix.run_vasp_mpi import vasp_run_mpispawn
from mc import model, CanonicalMonteCarlo, MultiProcessReplicaRun, TemperatureReplicaExchange
from mc_mpi import TemperatureRX_MPI
from model_setup import *
if __name__ == "__main__":
args = sys.argv
kB = 8.6173e-5
nreplicas = int(args[1] )
nprocs_per_vasp = int(args[2])
commworld = MPI.COMM_WORLD
worldrank = commworld.Get_rank()
worldprocs = commworld.Get_size()
if worldprocs > nreplicas:
if worldrank == 0:
print("Setting number of replicas smaller than MPI processes; I hope you"
+" know what you're doing..."
)
sys.stdout.flush()
if worldrank >= nreplicas:
# belong to comm that does nothing
comm = commworld.Split(color=1, key=worldrank)
comm.Free()
sys.exit() # Wait for MPI_finalize
else:
comm = commworld.Split(color=0, key=worldrank)
else:
comm = commworld
# prepare spinel_config
cellsize = 1
base_structure = Structure.from_file(os.path.join(os.path.dirname(__file__), "POSCAR"))#.get_primitive_structure(tolerance=0.001)
config = spch_config(base_structure=base_structure,N_Ovac=0.1)
#config.prepare_Ovac(0.1)
#config.prepare_ordered()
configs = []
for i in range(nreplicas):
config.prepare_Ovac()
configs.append(copy.deepcopy(config))
# prepare vasp spinel model
vasprun = vasp_run_mpispawn("/home/i0009/i000900/src/vasp.5.3/vasp.spawnready.gamma", nprocs=nprocs_per_vasp, comm=comm)
baseinput = VaspInput.from_directory("baseinput") #(os.path.join(os.path.dirname(__file__), "baseinput"))
ltol=0.1
matcher = StructureMatcher(ltol=ltol, primitive_cell=False, ignored_species=["Pt"])
matcher_site = StructureMatcher(ltol=ltol, primitive_cell=False,stol=0.5,
allow_subset=True)#,
#comparator=FrameworkComparator(), ignored_species=["Pt","Zr"])
drone = SimpleVaspToComputedEntryDrone(inc_structure=True)
queen = BorgQueen(drone)
model = dft_zro2_spch(calcode="VASP", vasp_run=vasprun, base_vaspinput=baseinput,
matcher=matcher, matcher_site=matcher_site, queen=queen, selective_dynamics=["Pt"])
if worldrank == 0:
print(config.structure)
#print(model.xparam(config))
kTs = kB*np.array([500.0*1.1**i for i in range(nreplicas)])
#configs = pickle.load(open("config.pickle","rb"))
#configs = [copy.deepcopy(config) for i in range(nreplicas)]
RXcalc = TemperatureRX_MPI(comm, CanonicalMonteCarlo, model, configs, kTs)
RXcalc.reload()
obs = RXcalc.run(nsteps=10, RXtrial_frequency=2, sample_frequency=1, observfunc=observables, subdirs=True)
if worldrank == 0:
for i in range(len(kTs)):
with open("T"+str(i)+".dat", "w") as f:
f.write("\n".join([str(obs[i,j]) for j in range(len(obs[i,:]))]))
for i in range(9):
RXcalc.reload()
obs += RXcalc.run(nsteps=10, RXtrial_frequency=2, sample_frequency=1, observfunc=observables, subdirs=True)
obs_write = obs/float(i+2)
if worldrank == 0:
for i in range(len(kTs)):
with open("T"+str(i)+".dat", "w") as f:
f.write("\n".join([str(obs_write[i,j]) for j in range(len(obs_write[i,:]))]))
|
skasamatsu/py_mc
|
examples/zro2_spch/zro2_spch.py
|
Python
|
gpl-3.0
| 3,992
|
[
"VASP",
"pymatgen"
] |
5c0f06233de47aaaeffe39f9957c58c5ccc68234510c7fee6bf978dded8594bb
|
#
# Copyright (C) 2013 UNIVERSIDAD DE CHILE.
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
#
# Authors: Karel Mundnich <kmundnic@ing.uchile.cl>
from scipy.io import netcdf
import numpy as np
def load_data_from_file(file_path):
""" Loads data from and NetCDF file and returns a numpy.ndarray with the full
data frame.
"""
# Open data
f = netcdf.netcdf_file(file_path, 'r')
# Load data into a variable
aux = f.variables['frame']
# Copy data into a new numpy array for security
measurement = np.array(aux.data)
f.close()
return measurement
|
chunicaa/uch-ultrasonic-anemometer
|
software/utilities.py
|
Python
|
gpl-3.0
| 1,157
|
[
"NetCDF"
] |
4c02c21614679e33223fc5e3b097fa348142e37e9b901c614ff8f70868d011bc
|
'''
Created on Aug 17, 2010
@author: Peter Harrington
peter.b.harrington@gmail.com
'''
from numpy import *
def cadf(inMatX, inMatY, p, nlags):
if (p < -1):
print "Error: p cannot be less than -1"
numObs = inMatX.shape[0]
if ((numObs - 2*nlags + 1) < 1):
print "Error nlags is too large in cadf, negative degrees of freedom"
inMatX = detrend(inMatX,p)
inMatY = detrend(inMatY,p)
b = ((inMatX.transpose()*inMatX).I)*(inMatX.transpose()*inMatY)
r = inMatY - inMatX*b
dep = tdiff(r,1)
dep = trimr(dep,1,0)
z = trimr(lag(r,1),1,0)
k = 1
while (k <= nlags):
z = concatenate((z,lag(dep,k)),1)
k += 1
z = trimr(z,nlags,0)
dep = trimr(dep,nlags,0)
dtemp = detrend(z,0)
beta = linalg.solve(dtemp.transpose()*dtemp, dtemp.transpose()*detrend(dep,0)) #beta = a\b
res = detrend(dep,0) - detrend(z,0)*beta
so = (res.transpose()*res)/(dep.shape[0]-z.shape[1])
var_cov = so[0,0] * ((z.transpose()*z).I)
results={} #use dictonary to return bundled results
results['alpha'] = beta[0,0]
results['adf'] = beta[0,0]/sqrt(var_cov[0,0])
results['crit'] = rztcrit(numObs,inMatX.shape[1],p)
results['nlag'] = nlags
results['nvar'] = inMatX.shape[1] #number of columns in inMatX
return results
def detrend(inputMatrix, p):
if p == -1:
return inputMatrix
numObs = inputMatrix.shape[0]
u = matrix(ones((numObs,1))) #create 0th order term
if (p > 0): #create a time matrix
timep = matrix(zeros((numObs,p)))
t = matrix(range(numObs))
tp = t.transpose()/float(numObs)
m = 1
while (m <= p):
timep[:,m-1] = multiply(tp,m)
m += 1
xmat = concatenate((u,timep),1)
else:
xmat = u
xpxi = (xmat.transpose()*xmat).I #denom for ols
beta = xpxi*(xmat.transpose()*inputMatrix) #calc ols
residuals = inputMatrix - xmat*beta #subtract residuals
return residuals
def lag(inMatX, n = 1, v = 0):
zt = multiply(matrix(ones((n,inMatX.shape[1]))),v) #zero term
z = concatenate((zt,trimr(inMatX,0,n)))
return z
def tdiff(inputMatrix, k):
numObs,numVar = inputMatrix.shape
if k==0:
dmat = inputMatrix
elif k == 1:
dmat = matrix(zeros((numObs,numVar)))
dmat[1:numObs,:] = inputMatrix[1:numObs,:]-inputMatrix[0:numObs-1,:]
else:
dmat = matrix(zeros((numObs,numVar)))
dmat[k:numObs,:] = inputMatrix[k:numObs,:]-inputMatrix[0:numObs-k,:]
return dmat
def trimr(inputMatrix, bottom, top):
n = inputMatrix.shape[0]
return inputMatrix[bottom:n-top,:]
def rztcrit(numObs,k,p):
if (numObs >= 500):
zt = matrix('\
-3.28608,-2.71123,-2.44427,-0.22827,0.19684,1.07845;\
-3.88031,-3.35851,-3.03798,-1.01144,-0.65334,0.15312;\
-4.36339,-3.84931,-3.52926,-1.59069,-1.27691,-0.68855;\
-4.69226,-4.16473,-3.91069,-2.03499,-1.75167,-1.16909;\
-5.12583,-4.55603,-4.24350,-2.43062,-2.15918,-1.63241;\
-5.45902,-4.85433,-4.54552,-2.68999,-2.45059,-1.96213;\
-5.68874,-5.13084,-4.85451,-3.01287,-2.77470,-2.34774;\
-3.95399,-3.33181,-3.01057,-0.96426,-0.63214,0.14815;\
-4.29147,-3.77581,-3.47606,-1.47435,-1.15649,-0.38209;\
-4.80216,-4.16163,-3.87422,-1.95661,-1.68975,-1.17624;\
-5.08973,-4.49148,-4.22534,-2.34763,-2.09506,-1.52368;\
-5.28946,-4.77944,-4.49057,-2.63483,-2.39227,-1.88262;\
-5.64107,-5.10086,-4.81771,-2.95313,-2.74233,-2.30293;\
-5.84555,-5.26853,-5.01340,-3.21419,-2.95790,-2.50159;\
-4.25439,-3.69759,-3.42840,-1.49852,-1.22694,-0.59376;\
-4.62332,-4.12603,-3.83833,-1.91632,-1.65271,-0.93775;\
-5.09990,-4.50073,-4.18896,-2.26553,-1.97459,-1.41616;\
-5.23982,-4.74879,-4.50065,-2.59004,-2.30601,-1.76624;\
-5.63745,-5.07700,-4.77794,-2.88029,-2.66305,-2.25529;\
-5.87733,-5.31763,-5.03729,-3.17526,-2.94043,-2.54329;\
-6.08463,-5.57014,-5.29279,-3.45890,-3.21035,-2.68331;\
-4.68825,-4.14264,-3.83668,-1.89022,-1.62543,-1.02171;\
-5.00664,-4.43544,-4.14709,-2.24334,-1.94304,-1.29258;\
-5.42102,-4.77343,-4.48998,-2.57209,-2.30366,-1.79885;\
-5.60249,-5.02686,-4.77574,-2.89195,-2.61726,-2.09253;\
-5.90744,-5.31272,-5.04121,-3.16076,-2.89667,-2.44274;\
-6.16639,-5.58218,-5.28049,-3.40263,-3.15765,-2.70251;\
-6.29638,-5.79252,-5.52324,-3.65372,-3.40115,-2.94514;\
-4.99327,-4.43088,-4.13314,-2.19577,-1.94806,-1.33955;\
-5.28724,-4.72773,-4.46224,-2.52556,-2.25121,-1.75592;\
-5.53603,-5.03231,-4.74442,-2.81101,-2.53978,-2.01464;\
-5.85790,-5.28516,-4.99765,-3.11650,-2.85684,-2.38643;\
-6.03218,-5.50167,-5.24244,-3.37898,-3.13182,-2.57977;\
-6.38137,-5.80056,-5.52693,-3.62856,-3.37482,-2.85511;\
-6.60394,-6.03056,-5.73651,-3.83174,-3.56048,-3.09560')
elif ((numObs >= 400) and (numObs <= 499)):
zt = matrix('\
-3.39320,-2.78062,-2.47410,-0.27917,0.17257,1.01757;\
-3.81898,-3.34274,-3.04197,-0.98464,-0.63219,0.07862;\
-4.43824,-3.83476,-3.53856,-1.59769,-1.32538,-0.68273;\
-4.78731,-4.19879,-3.90468,-2.03620,-1.78519,-1.25540;\
-5.15859,-4.55815,-4.27559,-2.40402,-2.15148,-1.64991;\
-5.36666,-4.82211,-4.55480,-2.73039,-2.47586,-1.96342;\
-5.70533,-5.14149,-4.83768,-2.98968,-2.75467,-2.33244;\
-3.88099,-3.31554,-3.00918,-1.01400,-0.66651,0.11221;\
-4.35920,-3.76677,-3.47891,-1.47887,-1.17461,-0.45761;\
-4.73655,-4.17175,-3.87843,-1.95622,-1.67273,-1.05752;\
-5.03407,-4.48465,-4.18736,-2.32047,-2.06844,-1.54620;\
-5.37301,-4.80609,-4.50790,-2.65816,-2.39100,-1.90516;\
-5.63842,-5.08273,-4.79419,-2.95211,-2.72047,-2.26114;\
-5.95823,-5.38482,-5.08735,-3.23862,-2.98661,-2.58060;\
-4.29209,-3.74752,-3.44785,-1.49664,-1.19363,-0.54054;\
-4.73620,-4.16373,-3.83159,-1.87826,-1.56786,-0.90630;\
-4.98331,-4.47817,-4.18238,-2.27544,-1.99733,-1.45956;\
-5.34322,-4.77455,-4.47877,-2.60581,-2.34669,-1.82075;\
-5.61331,-5.05800,-4.77543,-2.91228,-2.64829,-2.13015;\
-5.94606,-5.34094,-5.05669,-3.17314,-2.92833,-2.50131;\
-6.17994,-5.62560,-5.32022,-3.45919,-3.21928,-2.73838;\
-4.68326,-4.13893,-3.83504,-1.88594,-1.59783,-1.02900;\
-5.01959,-4.44111,-4.16075,-2.24225,-1.96550,-1.36753;\
-5.35312,-4.76318,-4.48253,-2.53350,-2.26862,-1.74966;\
-5.65846,-5.05443,-4.74318,-2.86021,-2.61633,-2.15096;\
-5.89297,-5.33097,-5.03686,-3.13780,-2.88399,-2.36895;\
-6.11791,-5.59035,-5.29834,-3.39283,-3.13194,-2.64558;\
-6.43463,-5.83831,-5.54375,-3.63526,-3.40822,-2.97731;\
-4.99049,-4.45174,-4.15603,-2.22388,-1.94107,-1.40933;\
-5.37057,-4.77929,-4.48921,-2.54431,-2.27297,-1.72675;\
-5.61805,-5.06136,-4.76461,-2.81651,-2.54785,-2.04956;\
-5.88425,-5.29788,-5.01558,-3.10698,-2.83781,-2.33035;\
-6.15156,-5.57259,-5.28198,-3.36062,-3.10140,-2.61065;\
-6.37314,-5.80031,-5.51577,-3.63686,-3.38505,-2.87176;\
-6.58251,-6.03057,-5.74573,-3.85037,-3.60485,-3.11932')
elif ((numObs >= 300) and (numObs <= 399)):
zt = matrix('\
-3.36203,-2.77548,-2.46139,-0.28681,0.13287,1.03471;\
-3.90239,-3.32711,-3.03723,-0.99653,-0.60551,0.11851;\
-4.32982,-3.81156,-3.51879,-1.59453,-1.29025,-0.57675;\
-4.81264,-4.24058,-3.93314,-2.05226,-1.79734,-1.23867;\
-5.09929,-4.53317,-4.26022,-2.39047,-2.15062,-1.66121;\
-5.40020,-4.84728,-4.56541,-2.72073,-2.48276,-2.01238;\
-5.72554,-5.14543,-4.85290,-3.03642,-2.79747,-2.38877;\
-3.93064,-3.31039,-3.00695,-1.02551,-0.69206,0.10488;\
-4.30844,-3.76971,-3.48291,-1.49867,-1.18293,-0.44930;\
-4.69802,-4.16002,-3.85937,-1.95172,-1.66941,-1.07873;\
-5.09621,-4.51913,-4.22178,-2.32005,-2.06940,-1.52440;\
-5.39988,-4.84499,-4.54918,-2.66241,-2.40886,-1.94518;\
-5.67194,-5.12143,-4.83266,-2.95787,-2.71575,-2.26783;\
-5.90971,-5.38093,-5.10006,-3.24590,-3.00999,-2.55590;\
-4.32518,-3.77645,-3.46220,-1.48724,-1.19931,-0.53182;\
-4.66166,-4.12423,-3.82665,-1.85992,-1.56770,-0.95256;\
-5.06263,-4.47715,-4.19478,-2.27228,-1.98935,-1.40857;\
-5.39577,-4.79037,-4.51644,-2.60186,-2.32067,-1.82448;\
-5.62591,-5.09997,-4.78451,-2.89543,-2.66108,-2.16281;\
-5.96117,-5.38487,-5.08529,-3.19176,-2.95677,-2.45750;\
-6.18044,-5.61962,-5.32402,-3.44453,-3.18600,-2.75024;\
-4.69949,-4.11581,-3.84809,-1.91652,-1.63097,-1.06354;\
-5.02878,-4.48050,-4.18169,-2.20023,-1.92196,-1.37122;\
-5.37891,-4.82102,-4.49501,-2.55100,-2.29407,-1.76313;\
-5.59926,-5.07560,-4.78056,-2.89047,-2.61834,-2.11372;\
-5.97404,-5.35040,-5.03148,-3.15838,-2.91666,-2.44570;\
-6.20250,-5.64756,-5.33112,-3.40255,-3.16800,-2.73795;\
-6.40258,-5.84695,-5.58164,-3.67811,-3.42766,-2.97315;\
-5.02873,-4.44103,-4.15164,-2.19792,-1.94100,-1.39467;\
-5.36834,-4.76996,-4.46992,-2.53666,-2.27257,-1.73355;\
-5.59537,-5.05016,-4.78520,-2.83093,-2.57279,-2.07503;\
-5.85590,-5.33224,-5.03207,-3.11489,-2.86007,-2.36551;\
-6.20771,-5.62475,-5.32273,-3.36439,-3.10806,-2.63899;\
-6.38397,-5.87287,-5.56819,-3.63376,-3.37917,-2.87215;\
-6.69353,-6.08474,-5.78590,-3.87231,-3.61022,-3.14908')
elif ((numObs >= 200) and (numObs <= 299)):
zt = matrix('\
-3.35671,-2.77519,-2.46594,-0.25410,0.19613,1.07222;\
-3.92428,-3.38037,-3.08215,-1.00759,-0.63422,0.09456;\
-4.48168,-3.83395,-3.54540,-1.60205,-1.31840,-0.73432;\
-4.82954,-4.23468,-3.94803,-2.05472,-1.80434,-1.27245;\
-5.19748,-4.57984,-4.28594,-2.42219,-2.18483,-1.73071;\
-5.48348,-4.89872,-4.60436,-2.75423,-2.51959,-2.06231;\
-5.82241,-5.21284,-4.90675,-3.03145,-2.79112,-2.38818;\
-3.88242,-3.33232,-3.01999,-0.98826,-0.63342,0.12132;\
-4.36630,-3.76414,-3.46091,-1.48625,-1.15077,-0.49842;\
-4.76842,-4.20038,-3.89975,-1.93433,-1.63407,-1.04290;\
-5.05007,-4.54203,-4.23534,-2.35721,-2.10330,-1.57965;\
-5.46384,-4.89647,-4.60567,-2.66674,-2.41227,-1.92884;\
-5.80068,-5.17731,-4.86360,-2.97354,-2.71548,-2.25152;\
-6.01552,-5.48792,-5.18651,-3.27732,-3.05193,-2.62313;\
-4.37038,-3.77348,-3.48123,-1.46468,-1.19712,-0.52291;\
-4.71164,-4.17296,-3.87214,-1.88824,-1.61792,-0.99897;\
-5.07287,-4.49791,-4.19539,-2.25537,-1.97775,-1.42073;\
-5.43158,-4.85660,-4.55542,-2.59513,-2.34448,-1.88253;\
-5.71928,-5.15509,-4.85008,-2.91869,-2.67892,-2.16537;\
-5.95901,-5.38920,-5.10190,-3.21921,-2.97088,-2.49105;\
-6.24842,-5.69150,-5.39236,-3.47876,-3.22814,-2.81954;\
-4.76132,-4.12120,-3.81887,-1.87640,-1.57988,-0.95925;\
-5.07595,-4.49599,-4.18062,-2.22181,-1.95429,-1.32816;\
-5.41865,-4.82420,-4.51442,-2.54584,-2.28898,-1.71129;\
-5.69988,-5.10837,-4.81872,-2.87861,-2.62537,-2.10745;\
-6.03815,-5.41121,-5.11067,-3.15726,-2.89572,-2.39236;\
-6.31746,-5.67322,-5.35729,-3.42445,-3.18255,-2.72287;\
-6.54722,-5.92036,-5.63475,-3.68619,-3.44087,-2.99590;\
-5.06954,-4.48980,-4.16461,-2.22770,-1.95682,-1.39685;\
-5.35737,-4.81634,-4.52940,-2.54416,-2.26355,-1.73669;\
-5.65024,-5.06222,-4.78444,-2.84019,-2.55801,-2.03438;\
-6.01717,-5.38593,-5.07183,-3.10854,-2.83015,-2.38316;\
-6.22810,-5.62644,-5.32983,-3.37920,-3.11022,-2.58412;\
-6.51923,-5.91250,-5.61917,-3.64604,-3.37807,-2.91979;\
-6.74433,-6.15641,-5.85483,-3.88559,-3.62884,-3.22791')
elif ((numObs >= 1) and (numObs <= 199)):
zt = matrix('\
-3.40026,-2.81980,-2.49012,-0.28406,0.16278,0.99118;\
-4.02456,-3.40397,-3.08903,-0.99877,-0.63826,0.09294;\
-4.50406,-3.91574,-3.60618,-1.64640,-1.34126,-0.67499;\
-4.97750,-4.31424,-4.00116,-2.07039,-1.80758,-1.24622;\
-5.29795,-4.65255,-4.36236,-2.43756,-2.20744,-1.74384;\
-5.69006,-5.02821,-4.70153,-2.78533,-2.55054,-2.12221;\
-6.01114,-5.32900,-5.01614,-3.10458,-2.87108,-2.45944;\
-4.03875,-3.38465,-3.06445,-1.01452,-0.67017,0.08305;\
-4.49697,-3.83781,-3.52924,-1.50657,-1.18131,-0.49457;\
-4.85358,-4.24290,-3.92668,-1.93268,-1.67668,-1.11969;\
-5.23415,-4.63779,-4.32076,-2.35203,-2.10299,-1.58236;\
-5.60428,-4.99996,-4.67591,-2.71512,-2.45663,-1.97999;\
-5.89816,-5.30839,-4.98307,-3.01998,-2.78403,-2.33971;\
-6.24667,-5.61312,-5.28841,-3.32373,-3.07681,-2.65243;\
-4.50725,-3.84730,-3.53859,-1.50198,-1.21063,-0.49494;\
-4.87844,-4.22489,-3.92431,-1.88702,-1.59187,-0.97217;\
-5.20113,-4.56724,-4.27167,-2.29534,-2.03226,-1.43479;\
-5.61984,-4.95138,-4.63381,-2.62062,-2.34903,-1.81713;\
-5.93516,-5.26326,-4.95702,-2.97158,-2.70668,-2.22094;\
-6.20848,-5.57967,-5.28403,-3.27115,-3.01521,-2.58367;\
-6.52806,-5.84919,-5.55596,-3.54144,-3.30790,-2.88872;\
-4.84291,-4.21809,-3.89360,-1.88296,-1.62337,-0.99875;\
-5.18976,-4.56495,-4.23781,-2.23973,-1.95745,-1.36282;\
-5.49570,-4.91049,-4.57949,-2.54844,-2.30040,-1.81108;\
-5.85200,-5.24753,-4.90738,-2.89515,-2.62635,-2.11513;\
-6.25788,-5.59734,-5.23154,-3.20543,-2.95304,-2.49876;\
-6.42744,-5.80415,-5.49459,-3.46836,-3.20457,-2.78454;\
-6.79276,-6.11558,-5.77461,-3.74987,-3.49703,-3.07378;\
-5.25985,-4.56675,-4.25742,-2.24159,-1.93760,-1.40055;\
-5.53963,-4.88523,-4.55008,-2.53159,-2.26558,-1.74469;\
-5.86277,-5.23537,-4.92559,-2.84160,-2.58154,-2.08171;\
-6.16676,-5.52360,-5.22425,-3.12455,-2.84785,-2.41246;\
-6.43205,-5.80308,-5.46594,-3.42417,-3.19918,-2.69791;\
-6.81177,-6.11377,-5.74083,-3.67826,-3.41996,-2.95145;\
-6.98960,-6.36882,-6.03754,-3.95573,-3.71192,-3.30766')
if ((k < 1) or (k > 5) or (p > 5)):
crit = matrix(zeros((6,1)))
n = (k - 1) * 7 + p + 2
crit = zt[n-1,:]
return crit
|
burakbayramli/dersblog
|
tser/tser_030_coint/pyconometrics.py
|
Python
|
gpl-3.0
| 12,994
|
[
"ADF"
] |
447f9f64efe6b37a8b33c562c05a3c19a68aab89c14b36f0e904bfef0245ef99
|
import linear_env
import sim_env
from actor import Actor
from critic import Critic
from replay_buffer import ReplayBuffer
import numpy as np
import tensorflow as tf
import keras.backend as kbck
import json
import time
import argparse
import matplotlib.pylab as plt
import os.path
def ou(x, mu, theta, sigma):
return theta * (mu - x) + sigma * np.random.randn(np.shape(x)[0])
def simulate(control, swmm ,flows):
best_reward = -1*np.inf
BUFFER_SIZE = 100000
BATCH_SIZE = 120
GAMMA = 0.99
TAU = 0.01 #Target Network HyperParameters
LRA = 0.0001 #Learning rate for Actor
LRC = 0.001 #Lerning rate for Critic
action_dim = 8
state_dim = 10
max_steps = 6000
np.random.seed(100)
EXPLORE = 100000.
episode_count = 1000
done = False
step = 0
epsilon = 1
if swmm:
if control:
#Tensorflow GPU optimization
config = tf.ConfigProto()
config.gpu_options.allow_growth = True
sess = tf.Session(config=config)
kbck.set_session(sess)
# Actor, critic and replay buffer creation
actor = Actor(sess, state_dim, action_dim, BATCH_SIZE, TAU, LRA,flows)
critic = Critic(sess, state_dim, action_dim, BATCH_SIZE, TAU, LRC)
buff = ReplayBuffer(BUFFER_SIZE)
# Get the linear environment
reward_hist = []
for i in range(episode_count):
print("Episode : " + str(i) + " Replay Buffer " + str(buff.count()))
inp_name = "swmm/modelo2.inp"
inp = os.path.dirname(os.path.abspath(__file__)) + os.path.sep + inp_name
vref = np.zeros((state_dim,))
env = sim_env.sim_env(inp,vref)
rainfile()
s_t = np.divide(env.reset(),env.vmax)
total_reward = 0.
for j in range(max_steps):
## Noise addition for exploration
## Ornstein-Uhlenbeck process
loss = 0
epsilon -= 1.0 / EXPLORE
a_t = np.zeros([1,action_dim])
noise_t = np.zeros([1,action_dim])
a_t_original = actor.munet.predict(s_t.reshape(1, s_t.shape[0]))
noise_t[0,:] = max(epsilon, 0) * ou(a_t_original[0,:], 0.5 , 1 , 1.5)
#noise_t[0,4:] = max(epsilon, 0) * ou(a_t_original[0,4:], 0.5 , 1 , 1.5)
a_t[0] = np.minimum(np.maximum(a_t_original[0] + noise_t[0],np.zeros(np.shape(a_t_original))),np.ones(np.shape(a_t_original)))
#Act over the system and get info of the next states
s_t1 , r_t, done = env.step(list(a_t[0]))
s_t1 = np.divide(s_t1,env.vmax)
#Add replay buffer
buff.add(s_t, a_t[0], r_t, s_t1, done)
#Do the batch update
batch = buff.getBatch(BATCH_SIZE)
states = np.asarray([e[0] for e in batch])
actions = np.asarray([e[1] for e in batch])
rewards = np.asarray([e[2] for e in batch])
next_states = np.asarray([e[3] for e in batch])
dones = np.asarray([e[4] for e in batch])
# Get estimated q-values of the pair (next_state,mu(next_state))
actions_next = actor.target_munet.predict(next_states)
target_q_values = critic.target_qnet.predict([next_states, actions_next])
y_t = np.zeros(np.shape(actions))
for k in range(len(batch)):
if dones[k]:
y_t[k] = rewards[k]
else:
y_t[k] = rewards[k] + GAMMA*target_q_values[k]
loss += critic.qnet.train_on_batch([states,actions], y_t)
a_for_grad = actor.munet.predict(states)
grads = critic.gradients(states, a_for_grad)
actor.train(states, grads)
actor.target_train()
critic.target_train()
total_reward = total_reward + GAMMA*r_t
s_t = s_t1
if j%100==0:
print("Episode", i, "Step", j, "Reward", r_t, "Loss", loss)
if done:
break
reward_hist.append(total_reward)
np.save("reward_history_flows_"+str(flows).lower()+".npy",np.array(reward_hist))
if i%20 == 0:
print("Saving the networks...")
actor.munet.save_weights("./actors/anetwork_flows_"+str(flows).lower()+"_it_"+str(i)+".h5", overwrite=True)
critic.qnet.save_weights("./critics/cnetwork_flows_"+str(flows).lower()+"_it_"+str(i)+".h5", overwrite=True)
if total_reward > best_reward:
print("Saving Best Actor...")
np.save("best_reward"+"_flows_"+str(flows)+".npy",np.array(total_reward))
actor.munet.save_weights("./actors/best_anetwork_flows_"+str(flows).lower()+".h5", overwrite=True)
critic.qnet.save_weights("./critics/best_cnetwork_flows_"+str(flows).lower()+".h5", overwrite=True)
best_reward = total_reward
print("TOTAL REWARD @ " + str(i) +"-th Episode : Reward " + str(total_reward))
print("Total Step: " + str(step))
print("")
print("Finish.")
else:
inp_name = "swmm/modelo2.inp"
inp = os.path.dirname(os.path.abspath(__file__)) + os.path.sep + inp_name
vref = np.zeros((state_dim,))
env = sim_env.sim_env(inp,vref)
resv = env.free_sim()
f , axarr = plt.subplots(nrows=2, ncols=1 )
print(np.shape(resv))
resv_norm = np.divide(resv,np.matlib.repmat(env.vmax,np.shape(resv)[0],1))
x = np.linspace(0,1800,np.shape(resv)[0])
## Plot Volume Results
lines = axarr[0].plot(x,resv_norm[:,:5])
axarr[0].legend(lines , list(map(lambda x: "v"+str(x+1),range(5))))
axarr[0].set_title("Volumes - Tanks 1 to 5")
axarr[0].set_xlabel("Times(s)")
axarr[0].set_ylabel("Volume(%vmax)")
lines = axarr[1].plot(x,resv_norm[:,5:10])
axarr[1].legend(lines , list(map(lambda x: "v"+str(x+1) if x+1!=10 else "vS",range(5,10))))
axarr[1].set_title("Volumes - Tanks 6 to 9 and Storm Tank")
axarr[1].set_xlabel("Times(s)")
axarr[1].set_ylabel("Volume(%vmax)")
#sns.despine()
plt.tight_layout()
plt.show()
else:
# Constants for the linear environment
Hs = 2400
A1 = 0.0020
mu1 = 250
sigma1 = 70
A2 = 0.0048
mu2 = 250
sigma2 = 70
dt = 1
x = np.arange(Hs)
d = np.zeros((2,Hs))
if control:
#Tensorflow GPU optimization
config = tf.ConfigProto()
config.gpu_options.allow_growth = True
sess = tf.Session(config=config)
kbck.set_session(sess)
# Actor, critic and replay buffer creation
actor = Actor(sess, state_dim, action_dim, BATCH_SIZE, TAU, LRA,flows)
critic = Critic(sess, state_dim, action_dim, BATCH_SIZE, TAU, LRC)
buff = ReplayBuffer(BUFFER_SIZE)
# Get the linear environment
reward_hist = []
for i in range(episode_count):
print("Episode : " + str(i) + " Replay Buffer " + str(buff.count()))
A1 += 0.0004*np.random.rand()
mu1 += 50*np.random.rand()
sigma1 += 14*np.random.rand()
A2 += 0.00096*np.random.rand()
mu2 += 50*np.random.rand()
sigma2 += 14*np.random.rand()
d[0,:] = A1*np.exp((-1*(x-mu1)**2)/(2*sigma1**2))
d[1,:] = A2*np.exp((-1*(x-mu2)**2)/(2*sigma2**2))
vref = np.zeros((state_dim,))
env = linear_env.env(dt,d,vref)
s_t = np.divide(env.reset(),env.vmax)
total_reward = 0.
for j in range(max_steps):
## Noise addition for exploration
## Ornstein-Uhlenbeck process
loss = 0
epsilon -= 1.0 / EXPLORE
a_t = np.zeros([1,action_dim])
noise_t = np.zeros([1,action_dim])
a_t_original = actor.munet.predict(s_t.reshape(1, s_t.shape[0]))
noise_t[0,:] = max(epsilon, 0) * ou(a_t_original[0,:], 0.5 , 1 , 1.5)
#noise_t[0,4:] = max(epsilon, 0) * ou(a_t_original[0,4:], 0.5 , 1 , 1.5)
a_t[0] = a_t_original[0] + noise_t[0]
#Act over the system and get info of the next states
s_t1 , r_t, done, _ = env.step(a_t[0],flows=flows)
s_t1 = np.divide(s_t1,env.vmax)
#Add replay buffer
buff.add(s_t, a_t[0], r_t, s_t1, done)
#Do the batch update
batch = buff.getBatch(BATCH_SIZE)
states = np.asarray([e[0] for e in batch])
actions = np.asarray([e[1] for e in batch])
rewards = np.asarray([e[2] for e in batch])
next_states = np.asarray([e[3] for e in batch])
dones = np.asarray([e[4] for e in batch])
# Get estimated q-values of the pair (next_state,mu(next_state))
actions_next = actor.target_munet.predict(next_states)
target_q_values = critic.target_qnet.predict([next_states, actions_next])
y_t = np.zeros(np.shape(actions))
for k in range(len(batch)):
if dones[k]:
y_t[k] = rewards[k]
else:
y_t[k] = rewards[k] + GAMMA*target_q_values[k]
loss += critic.qnet.train_on_batch([states,actions], y_t)
a_for_grad = actor.munet.predict(states)
grads = critic.gradients(states, a_for_grad)
actor.train(states, grads)
actor.target_train()
critic.target_train()
total_reward = total_reward + GAMMA*r_t
s_t = s_t1
if j%100==0:
print("Episode", i, "Step", j, "Reward", r_t, "Loss", loss)
if done:
break
reward_hist.append(total_reward)
np.save("reward_history_flows_"+str(flows).lower()+".npy",np.array(reward_hist))
if i%20 == 0:
print("Saving the networks...")
actor.munet.save_weights("./actors/anetwork_flows_"+str(flows).lower()+"_it_"+str(i)+".h5", overwrite=True)
critic.qnet.save_weights("./critics/cnetwork_flows_"+str(flows).lower()+"_it_"+str(i)+".h5", overwrite=True)
if total_reward > best_reward:
print("Saving Best Actor...")
np.save("best_reward"+"_flows_"+str(flows)+".npy",np.array(total_reward))
actor.munet.save_weights("./actors/best_anetwork_flows_"+str(flows).lower()+".h5", overwrite=True)
critic.qnet.save_weights("./critics/best_cnetwork_flows_"+str(flows).lower()+".h5", overwrite=True)
best_reward = total_reward
print("TOTAL REWARD @ " + str(i) +"-th Episode : Reward " + str(total_reward))
print("Total Step: " + str(step))
print("")
print("Finish.")
else:
d[0,:] = A1*np.exp((-1*(x-mu1)**2)/(2*sigma1**2))
d[1,:] = A2*np.exp((-1*(x-mu2)**2)/(2*sigma2**2))
vref = np.zeros((state_dim,))
env = linear_env.env(dt,d,vref)
resv, resf, resu = env.free_sim()
f , axarr = plt.subplots(nrows=2, ncols=2 )
resv_norm = np.divide(np.transpose(resv),np.matlib.repmat(env.vmax,Hs,1))
resu = np.transpose(np.asarray(resu))
## Plot Volume Results
lines = axarr[0,0].plot(x,resv_norm[:,:5])
axarr[0,0].legend(lines , list(map(lambda x: "v"+str(x+1),range(5))))
axarr[0,0].set_title("Volumes - Tanks 1 to 5")
axarr[0,0].set_xlabel("Times(s)")
axarr[0,0].set_ylabel("Volume(%vmax)")
lines = axarr[0,1].plot(x,resv_norm[:,5:10])
axarr[0,1].legend(lines , list(map(lambda x: "v"+str(x+1) if x+1!=10 else "vS",range(5,10))))
axarr[0,1].set_title("Volumes - Tanks 6 to 9 and Storm Tank")
axarr[0,1].set_xlabel("Times(s)")
axarr[0,1].set_ylabel("Volume(%vmax)")
lines = axarr[1,0].plot(x,resu[:,:4])
axarr[1,0].legend(lines , list(map(lambda x: "u"+str(x+1),range(4))))
axarr[1,0].set_title("Actions - Apertures")
axarr[1,0].set_xlabel("Times(s)")
axarr[1,0].set_ylabel("% Aperture")
lines = axarr[1,1].plot(x,resu[:,4:8])
axarr[1,1].legend(lines , list(map(lambda x: "u"+str(x+1),range(4,8))))
axarr[1,1].set_title("Actions - Apertures")
axarr[1,1].set_xlabel("Times(s)")
axarr[1,1].set_ylabel("% Aperture")
plt.suptitle("DDPG performance",y=1.05)
#sns.despine()
plt.tight_layout()
plt.show()
def rainfile():
from math import exp
import numpy as np
from matplotlib import pylab as plt
#Gaussian Extension
A1 = 0.008 + 0.0008*np.random.rand(); mu1 = 500+50*np.random.rand(); sigma1 = 250+25*np.random.rand()
A2 = 0.0063 + 0.00063*np.random.rand() ; mu2 = 500+50*np.random.rand(); sigma2 = 250+25*np.random.rand()
dt = 1
Hs = 1800
x = np.arange(0,Hs,dt)
d = [[],[]]
# dconst = 0.5*mpc_obj.k1*mpc_obj.vmax(1);
d[0] = A1*np.exp((-(x-mu1)**2)/(2*sigma1**2)) # Node 1 - left
d[1] = A2*np.exp((-(x-mu2)**2)/(2*sigma2**2)) # Node 2 - right
def secs_to_hour(secs_convert):
hour = secs_convert//3600
mins = (secs_convert%3600)//60
secs = secs_convert%60
return '{h:02d}:{m:02d}'.format(h=hour,m=mins)
secs_hour_vec = np.vectorize(secs_to_hour)
for k in (1,2):
with open('swmm/runoff%d.dat' % k, 'w') as f:
i = 0
for (t,val) in zip(secs_hour_vec(x), d[k-1]):
if i%60 == 0:
f.write(t+" "+str(val)+"\n")
i += 1
if __name__ == "__main__":
parser = argparse.ArgumentParser()
parser.add_argument("-c","--control", type=int, choices = [0,1], help = "Choose between control(1) or free dynamics(0)")
parser.add_argument("-s","--swmm", type=int, choices = [0,1], help = "Choose between a simulation with swmm(1) or not(0)")
parser.add_argument("-f","--flow", type=int, choices = [0,1], help = "Choose between a simulation with flows(1) or not(0)")
args = parser.parse_args()
if args.flow == 1 and args.swmm == 1:
print("Conflicting option flow 1 and swmm 1")
else:
t0 = time.process_time()
simulate(control=args.control, swmm=args.swmm, flows = args.flow)
tf = time.process_time()
print("Elapsed time: ",tf-t0)
|
deot95/Tesis
|
Proyecto de Grado Ingeniería Electrónica/Workspace/RL/DDPG/ddpg.py
|
Python
|
mit
| 16,268
|
[
"Gaussian"
] |
d6c22d1c80ee2367a1e3a9bf6bc7c8da9a525f69a3ff6de935c273b4339b7b75
|
# -*- coding: utf-8 -*-
"""
Unit tests for instructor.api methods.
"""
import datetime
import ddt
import random
import pytz
import io
import json
import os
import random
import requests
import shutil
import tempfile
from urllib import quote
from django.conf import settings
from django.contrib.auth.models import User
from django.core import mail
from django.core.files.uploadedfile import SimpleUploadedFile
from django.core.urlresolvers import reverse
from django.http import HttpRequest, HttpResponse
from django.test import RequestFactory, TestCase
from django.test.utils import override_settings
from django.utils.timezone import utc
from mock import Mock, patch
from nose.tools import raises
from opaque_keys.edx.locations import SlashSeparatedCourseKey
from course_modes.models import CourseMode
from courseware.models import StudentModule
from courseware.tests.factories import StaffFactory, InstructorFactory, BetaTesterFactory
from xmodule.modulestore.tests.django_utils import TEST_DATA_MOCK_MODULESTORE
from courseware.tests.helpers import LoginEnrollmentTestCase
from django_comment_common.models import FORUM_ROLE_COMMUNITY_TA
from django_comment_common.utils import seed_permissions_roles
from microsite_configuration import microsite
from shoppingcart.models import (
RegistrationCodeRedemption, Order, CouponRedemption,
PaidCourseRegistration, Coupon, Invoice, CourseRegistrationCode
)
from shoppingcart.pdf import PDFInvoice
from student.models import (
CourseEnrollment, CourseEnrollmentAllowed, NonExistentCourseError
)
from student.tests.factories import UserFactory, CourseModeFactory
from student.roles import CourseBetaTesterRole, CourseSalesAdminRole, CourseFinanceAdminRole
from xmodule.modulestore import ModuleStoreEnum
from xmodule.modulestore.django import modulestore
from xmodule.modulestore.tests.django_utils import ModuleStoreTestCase
from xmodule.modulestore.tests.factories import CourseFactory, ItemFactory
import instructor_task.api
import instructor.views.api
from instructor.tests.utils import FakeContentTask, FakeEmail, FakeEmailInfo
from instructor.views.api import generate_unique_password
from instructor.views.api import _split_input_list, common_exceptions_400
from instructor_task.api_helper import AlreadyRunningError
from .test_tools import msk_from_problem_urlname
from ..views.tools import get_extended_due
EXPECTED_CSV_HEADER = '"code","course_id","company_name","created_by","redeemed_by","invoice_id","purchaser","customer_reference_number","internal_reference"'
EXPECTED_COUPON_CSV_HEADER = '"code","course_id","percentage_discount","code_redeemed_count","description"'
# ddt data for test cases involving reports
REPORTS_DATA = (
{
'report_type': 'grade',
'instructor_api_endpoint': 'calculate_grades_csv',
'task_api_endpoint': 'instructor_task.api.submit_calculate_grades_csv',
'extra_instructor_api_kwargs': {}
},
{
'report_type': 'enrolled student profile',
'instructor_api_endpoint': 'get_students_features',
'task_api_endpoint': 'instructor_task.api.submit_calculate_students_features_csv',
'extra_instructor_api_kwargs': {'csv': '/csv'}
}
)
@common_exceptions_400
def view_success(request): # pylint: disable=unused-argument
"A dummy view for testing that returns a simple HTTP response"
return HttpResponse('success')
@common_exceptions_400
def view_user_doesnotexist(request): # pylint: disable=unused-argument
"A dummy view that raises a User.DoesNotExist exception"
raise User.DoesNotExist()
@common_exceptions_400
def view_alreadyrunningerror(request): # pylint: disable=unused-argument
"A dummy view that raises an AlreadyRunningError exception"
raise AlreadyRunningError()
class TestCommonExceptions400(TestCase):
"""
Testing the common_exceptions_400 decorator.
"""
def setUp(self):
self.request = Mock(spec=HttpRequest)
self.request.META = {}
def test_happy_path(self):
resp = view_success(self.request)
self.assertEqual(resp.status_code, 200)
def test_user_doesnotexist(self):
self.request.is_ajax.return_value = False
resp = view_user_doesnotexist(self.request) # pylint: disable=assignment-from-no-return
self.assertEqual(resp.status_code, 400)
self.assertIn("User does not exist", resp.content)
def test_user_doesnotexist_ajax(self):
self.request.is_ajax.return_value = True
resp = view_user_doesnotexist(self.request) # pylint: disable=assignment-from-no-return
self.assertEqual(resp.status_code, 400)
result = json.loads(resp.content)
self.assertIn("User does not exist", result["error"])
def test_alreadyrunningerror(self):
self.request.is_ajax.return_value = False
resp = view_alreadyrunningerror(self.request) # pylint: disable=assignment-from-no-return
self.assertEqual(resp.status_code, 400)
self.assertIn("Task is already running", resp.content)
def test_alreadyrunningerror_ajax(self):
self.request.is_ajax.return_value = True
resp = view_alreadyrunningerror(self.request) # pylint: disable=assignment-from-no-return
self.assertEqual(resp.status_code, 400)
result = json.loads(resp.content)
self.assertIn("Task is already running", result["error"])
@override_settings(MODULESTORE=TEST_DATA_MOCK_MODULESTORE)
@patch('bulk_email.models.html_to_text', Mock(return_value='Mocking CourseEmail.text_message'))
@patch.dict(settings.FEATURES, {'ENABLE_INSTRUCTOR_EMAIL': True, 'REQUIRE_COURSE_EMAIL_AUTH': False})
class TestInstructorAPIDenyLevels(ModuleStoreTestCase, LoginEnrollmentTestCase):
"""
Ensure that users cannot access endpoints they shouldn't be able to.
"""
def setUp(self):
self.course = CourseFactory.create()
self.user = UserFactory.create()
CourseEnrollment.enroll(self.user, self.course.id)
self.problem_location = msk_from_problem_urlname(
self.course.id,
'robot-some-problem-urlname'
)
self.problem_urlname = self.problem_location.to_deprecated_string()
_module = StudentModule.objects.create(
student=self.user,
course_id=self.course.id,
module_state_key=self.problem_location,
state=json.dumps({'attempts': 10}),
)
# Endpoints that only Staff or Instructors can access
self.staff_level_endpoints = [
('students_update_enrollment', {'identifiers': 'foo@example.org', 'action': 'enroll'}),
('get_grading_config', {}),
('get_students_features', {}),
('get_distribution', {}),
('get_student_progress_url', {'unique_student_identifier': self.user.username}),
('reset_student_attempts',
{'problem_to_reset': self.problem_urlname, 'unique_student_identifier': self.user.email}),
('update_forum_role_membership',
{'unique_student_identifier': self.user.email, 'rolename': 'Moderator', 'action': 'allow'}),
('list_forum_members', {'rolename': FORUM_ROLE_COMMUNITY_TA}),
('proxy_legacy_analytics', {'aname': 'ProblemGradeDistribution'}),
('send_email', {'send_to': 'staff', 'subject': 'test', 'message': 'asdf'}),
('list_instructor_tasks', {}),
('list_background_email_tasks', {}),
('list_report_downloads', {}),
('calculate_grades_csv', {}),
('get_students_features', {}),
]
# Endpoints that only Instructors can access
self.instructor_level_endpoints = [
('bulk_beta_modify_access', {'identifiers': 'foo@example.org', 'action': 'add'}),
('modify_access', {'unique_student_identifier': self.user.email, 'rolename': 'beta', 'action': 'allow'}),
('list_course_role_members', {'rolename': 'beta'}),
('rescore_problem',
{'problem_to_reset': self.problem_urlname, 'unique_student_identifier': self.user.email}),
]
def _access_endpoint(self, endpoint, args, status_code, msg):
"""
Asserts that accessing the given `endpoint` gets a response of `status_code`.
endpoint: string, endpoint for instructor dash API
args: dict, kwargs for `reverse` call
status_code: expected HTTP status code response
msg: message to display if assertion fails.
"""
url = reverse(endpoint, kwargs={'course_id': self.course.id.to_deprecated_string()})
if endpoint in ['send_email', 'students_update_enrollment', 'bulk_beta_modify_access']:
response = self.client.post(url, args)
else:
response = self.client.get(url, args)
self.assertEqual(
response.status_code,
status_code,
msg=msg
)
def test_student_level(self):
"""
Ensure that an enrolled student can't access staff or instructor endpoints.
"""
self.client.login(username=self.user.username, password='test')
for endpoint, args in self.staff_level_endpoints:
self._access_endpoint(
endpoint,
args,
403,
"Student should not be allowed to access endpoint " + endpoint
)
for endpoint, args in self.instructor_level_endpoints:
self._access_endpoint(
endpoint,
args,
403,
"Student should not be allowed to access endpoint " + endpoint
)
def test_staff_level(self):
"""
Ensure that a staff member can't access instructor endpoints.
"""
staff_member = StaffFactory(course_key=self.course.id)
CourseEnrollment.enroll(staff_member, self.course.id)
self.client.login(username=staff_member.username, password='test')
# Try to promote to forums admin - not working
# update_forum_role(self.course.id, staff_member, FORUM_ROLE_ADMINISTRATOR, 'allow')
for endpoint, args in self.staff_level_endpoints:
# TODO: make these work
if endpoint in ['update_forum_role_membership', 'proxy_legacy_analytics', 'list_forum_members']:
continue
self._access_endpoint(
endpoint,
args,
200,
"Staff member should be allowed to access endpoint " + endpoint
)
for endpoint, args in self.instructor_level_endpoints:
self._access_endpoint(
endpoint,
args,
403,
"Staff member should not be allowed to access endpoint " + endpoint
)
def test_instructor_level(self):
"""
Ensure that an instructor member can access all endpoints.
"""
inst = InstructorFactory(course_key=self.course.id)
CourseEnrollment.enroll(inst, self.course.id)
self.client.login(username=inst.username, password='test')
for endpoint, args in self.staff_level_endpoints:
# TODO: make these work
if endpoint in ['update_forum_role_membership', 'proxy_legacy_analytics']:
continue
self._access_endpoint(
endpoint,
args,
200,
"Instructor should be allowed to access endpoint " + endpoint
)
for endpoint, args in self.instructor_level_endpoints:
# TODO: make this work
if endpoint in ['rescore_problem']:
continue
self._access_endpoint(
endpoint,
args,
200,
"Instructor should be allowed to access endpoint " + endpoint
)
@override_settings(MODULESTORE=TEST_DATA_MOCK_MODULESTORE)
@patch.dict(settings.FEATURES, {'ALLOW_AUTOMATED_SIGNUPS': True})
class TestInstructorAPIBulkAccountCreationAndEnrollment(ModuleStoreTestCase, LoginEnrollmentTestCase):
"""
Test Bulk account creation and enrollment from csv file
"""
def setUp(self):
self.request = RequestFactory().request()
self.course = CourseFactory.create()
self.instructor = InstructorFactory(course_key=self.course.id)
self.client.login(username=self.instructor.username, password='test')
self.url = reverse('register_and_enroll_students', kwargs={'course_id': self.course.id.to_deprecated_string()})
self.not_enrolled_student = UserFactory(
username='NotEnrolledStudent',
email='nonenrolled@test.com',
first_name='NotEnrolled',
last_name='Student'
)
@patch('instructor.views.api.log.info')
def test_account_creation_and_enrollment_with_csv(self, info_log):
"""
Happy path test to create a single new user
"""
csv_content = "test_student@example.com,test_student_1,tester1,USA"
uploaded_file = SimpleUploadedFile("temp.csv", csv_content)
response = self.client.post(self.url, {'students_list': uploaded_file})
self.assertEqual(response.status_code, 200)
data = json.loads(response.content)
self.assertEquals(len(data['row_errors']), 0)
self.assertEquals(len(data['warnings']), 0)
self.assertEquals(len(data['general_errors']), 0)
# test the log for email that's send to new created user.
info_log.assert_called_with('email sent to new created user at test_student@example.com')
@patch('instructor.views.api.log.info')
def test_account_creation_and_enrollment_with_csv_with_blank_lines(self, info_log):
"""
Happy path test to create a single new user
"""
csv_content = "\ntest_student@example.com,test_student_1,tester1,USA\n\n"
uploaded_file = SimpleUploadedFile("temp.csv", csv_content)
response = self.client.post(self.url, {'students_list': uploaded_file})
self.assertEqual(response.status_code, 200)
data = json.loads(response.content)
self.assertEquals(len(data['row_errors']), 0)
self.assertEquals(len(data['warnings']), 0)
self.assertEquals(len(data['general_errors']), 0)
# test the log for email that's send to new created user.
info_log.assert_called_with('email sent to new created user at test_student@example.com')
@patch('instructor.views.api.log.info')
def test_email_and_username_already_exist(self, info_log):
"""
If the email address and username already exists
and the user is enrolled in the course, do nothing (including no email gets sent out)
"""
csv_content = "test_student@example.com,test_student_1,tester1,USA\n" \
"test_student@example.com,test_student_1,tester2,US"
uploaded_file = SimpleUploadedFile("temp.csv", csv_content)
response = self.client.post(self.url, {'students_list': uploaded_file})
self.assertEqual(response.status_code, 200)
data = json.loads(response.content)
self.assertEquals(len(data['row_errors']), 0)
self.assertEquals(len(data['warnings']), 0)
self.assertEquals(len(data['general_errors']), 0)
# test the log for email that's send to new created user.
info_log.assert_called_with("user already exists with username '{username}' and email '{email}'".format(username='test_student_1', email='test_student@example.com'))
def test_file_upload_type_not_csv(self):
"""
Try uploading some non-CSV file and verify that it is rejected
"""
uploaded_file = SimpleUploadedFile("temp.jpg", io.BytesIO(b"some initial binary data: \x00\x01").read())
response = self.client.post(self.url, {'students_list': uploaded_file})
self.assertEqual(response.status_code, 200)
data = json.loads(response.content)
self.assertNotEquals(len(data['general_errors']), 0)
self.assertEquals(data['general_errors'][0]['response'], 'Make sure that the file you upload is in CSV format with no extraneous characters or rows.')
def test_bad_file_upload_type(self):
"""
Try uploading some non-CSV file and verify that it is rejected
"""
uploaded_file = SimpleUploadedFile("temp.csv", io.BytesIO(b"some initial binary data: \x00\x01").read())
response = self.client.post(self.url, {'students_list': uploaded_file})
self.assertEqual(response.status_code, 200)
data = json.loads(response.content)
self.assertNotEquals(len(data['general_errors']), 0)
self.assertEquals(data['general_errors'][0]['response'], 'Could not read uploaded file.')
def test_insufficient_data(self):
"""
Try uploading a CSV file which does not have the exact four columns of data
"""
csv_content = "test_student@example.com,test_student_1\n"
uploaded_file = SimpleUploadedFile("temp.csv", csv_content)
response = self.client.post(self.url, {'students_list': uploaded_file})
self.assertEqual(response.status_code, 200)
data = json.loads(response.content)
self.assertEquals(len(data['row_errors']), 0)
self.assertEquals(len(data['warnings']), 0)
self.assertEquals(len(data['general_errors']), 1)
self.assertEquals(data['general_errors'][0]['response'], 'Data in row #1 must have exactly four columns: email, username, full name, and country')
def test_invalid_email_in_csv(self):
"""
Test failure case of a poorly formatted email field
"""
csv_content = "test_student.example.com,test_student_1,tester1,USA"
uploaded_file = SimpleUploadedFile("temp.csv", csv_content)
response = self.client.post(self.url, {'students_list': uploaded_file})
data = json.loads(response.content)
self.assertEqual(response.status_code, 200)
self.assertNotEquals(len(data['row_errors']), 0)
self.assertEquals(len(data['warnings']), 0)
self.assertEquals(len(data['general_errors']), 0)
self.assertEquals(data['row_errors'][0]['response'], 'Invalid email {0}.'.format('test_student.example.com'))
@patch('instructor.views.api.log.info')
def test_csv_user_exist_and_not_enrolled(self, info_log):
"""
If the email address and username already exists
and the user is not enrolled in the course, enrolled him/her and iterate to next one.
"""
csv_content = "nonenrolled@test.com,NotEnrolledStudent,tester1,USA"
uploaded_file = SimpleUploadedFile("temp.csv", csv_content)
response = self.client.post(self.url, {'students_list': uploaded_file})
self.assertEqual(response.status_code, 200)
info_log.assert_called_with('user {username} enrolled in the course {course}'.format(username='NotEnrolledStudent', course=self.course.id))
def test_user_with_already_existing_email_in_csv(self):
"""
If the email address already exists, but the username is different,
assume it is the correct user and just register the user in the course.
"""
csv_content = "test_student@example.com,test_student_1,tester1,USA\n" \
"test_student@example.com,test_student_2,tester2,US"
uploaded_file = SimpleUploadedFile("temp.csv", csv_content)
response = self.client.post(self.url, {'students_list': uploaded_file})
self.assertEqual(response.status_code, 200)
data = json.loads(response.content)
warning_message = 'An account with email {email} exists but the provided username {username} ' \
'is different. Enrolling anyway with {email}.'.format(email='test_student@example.com', username='test_student_2')
self.assertNotEquals(len(data['warnings']), 0)
self.assertEquals(data['warnings'][0]['response'], warning_message)
user = User.objects.get(email='test_student@example.com')
self.assertTrue(CourseEnrollment.is_enrolled(user, self.course.id))
def test_user_with_already_existing_username_in_csv(self):
"""
If the username already exists (but not the email),
assume it is a different user and fail to create the new account.
"""
csv_content = "test_student1@example.com,test_student_1,tester1,USA\n" \
"test_student2@example.com,test_student_1,tester2,US"
uploaded_file = SimpleUploadedFile("temp.csv", csv_content)
response = self.client.post(self.url, {'students_list': uploaded_file})
self.assertEqual(response.status_code, 200)
data = json.loads(response.content)
self.assertNotEquals(len(data['row_errors']), 0)
self.assertEquals(data['row_errors'][0]['response'], 'Username {user} already exists.'.format(user='test_student_1'))
def test_csv_file_not_attached(self):
"""
Test when the user does not attach a file
"""
csv_content = "test_student1@example.com,test_student_1,tester1,USA\n" \
"test_student2@example.com,test_student_1,tester2,US"
uploaded_file = SimpleUploadedFile("temp.csv", csv_content)
response = self.client.post(self.url, {'file_not_found': uploaded_file})
self.assertEqual(response.status_code, 200)
data = json.loads(response.content)
self.assertNotEquals(len(data['general_errors']), 0)
self.assertEquals(data['general_errors'][0]['response'], 'File is not attached.')
def test_raising_exception_in_auto_registration_and_enrollment_case(self):
"""
Test that exceptions are handled well
"""
csv_content = "test_student1@example.com,test_student_1,tester1,USA\n" \
"test_student2@example.com,test_student_1,tester2,US"
uploaded_file = SimpleUploadedFile("temp.csv", csv_content)
with patch('instructor.views.api.create_and_enroll_user') as mock:
mock.side_effect = NonExistentCourseError()
response = self.client.post(self.url, {'students_list': uploaded_file})
self.assertEqual(response.status_code, 200)
data = json.loads(response.content)
self.assertNotEquals(len(data['row_errors']), 0)
self.assertEquals(data['row_errors'][0]['response'], 'NonExistentCourseError')
def test_generate_unique_password(self):
"""
generate_unique_password should generate a unique password string that excludes certain characters.
"""
password = generate_unique_password([], 12)
self.assertEquals(len(password), 12)
for letter in password:
self.assertNotIn(letter, 'aAeEiIoOuU1l')
def test_users_created_and_enrolled_successfully_if_others_fail(self):
csv_content = "test_student1@example.com,test_student_1,tester1,USA\n" \
"test_student3@example.com,test_student_1,tester3,CA\n" \
"test_student2@example.com,test_student_2,tester2,USA"
uploaded_file = SimpleUploadedFile("temp.csv", csv_content)
response = self.client.post(self.url, {'students_list': uploaded_file})
self.assertEqual(response.status_code, 200)
data = json.loads(response.content)
self.assertNotEquals(len(data['row_errors']), 0)
self.assertEquals(data['row_errors'][0]['response'], 'Username {user} already exists.'.format(user='test_student_1'))
self.assertTrue(User.objects.filter(username='test_student_1', email='test_student1@example.com').exists())
self.assertTrue(User.objects.filter(username='test_student_2', email='test_student2@example.com').exists())
self.assertFalse(User.objects.filter(email='test_student3@example.com').exists())
@patch.object(instructor.views.api, 'generate_random_string',
Mock(side_effect=['first', 'first', 'second']))
def test_generate_unique_password_no_reuse(self):
"""
generate_unique_password should generate a unique password string that hasn't been generated before.
"""
generated_password = ['first']
password = generate_unique_password(generated_password, 12)
self.assertNotEquals(password, 'first')
@patch.dict(settings.FEATURES, {'ALLOW_AUTOMATED_SIGNUPS': False})
def test_allow_automated_signups_flag_not_set(self):
csv_content = "test_student1@example.com,test_student_1,tester1,USA"
uploaded_file = SimpleUploadedFile("temp.csv", csv_content)
response = self.client.post(self.url, {'students_list': uploaded_file})
self.assertEquals(response.status_code, 403)
@ddt.ddt
@override_settings(MODULESTORE=TEST_DATA_MOCK_MODULESTORE)
class TestInstructorAPIEnrollment(ModuleStoreTestCase, LoginEnrollmentTestCase):
"""
Test enrollment modification endpoint.
This test does NOT exhaustively test state changes, that is the
job of test_enrollment. This tests the response and action switch.
"""
def setUp(self):
self.request = RequestFactory().request()
self.course = CourseFactory.create()
self.instructor = InstructorFactory(course_key=self.course.id)
self.client.login(username=self.instructor.username, password='test')
self.enrolled_student = UserFactory(username='EnrolledStudent', first_name='Enrolled', last_name='Student')
CourseEnrollment.enroll(
self.enrolled_student,
self.course.id
)
self.notenrolled_student = UserFactory(username='NotEnrolledStudent', first_name='NotEnrolled',
last_name='Student')
# Create invited, but not registered, user
cea = CourseEnrollmentAllowed(email='robot-allowed@robot.org', course_id=self.course.id)
cea.save()
self.allowed_email = 'robot-allowed@robot.org'
self.notregistered_email = 'robot-not-an-email-yet@robot.org'
self.assertEqual(User.objects.filter(email=self.notregistered_email).count(), 0)
# Email URL values
self.site_name = microsite.get_value(
'SITE_NAME',
settings.SITE_NAME
)
self.about_path = '/courses/{}/about'.format(self.course.id)
self.course_path = '/courses/{}/'.format(self.course.id)
# uncomment to enable enable printing of large diffs
# from failed assertions in the event of a test failure.
# (comment because pylint C0103(invalid-name))
# self.maxDiff = None
def tearDown(self):
"""
Undo all patches.
"""
patch.stopall()
def test_missing_params(self):
""" Test missing all query parameters. """
url = reverse('students_update_enrollment', kwargs={'course_id': self.course.id.to_deprecated_string()})
response = self.client.post(url)
self.assertEqual(response.status_code, 400)
def test_bad_action(self):
""" Test with an invalid action. """
action = 'robot-not-an-action'
url = reverse('students_update_enrollment', kwargs={'course_id': self.course.id.to_deprecated_string()})
response = self.client.post(url, {'identifiers': self.enrolled_student.email, 'action': action})
self.assertEqual(response.status_code, 400)
def test_invalid_email(self):
url = reverse('students_update_enrollment', kwargs={'course_id': self.course.id.to_deprecated_string()})
response = self.client.post(url, {'identifiers': 'percivaloctavius@', 'action': 'enroll', 'email_students': False})
self.assertEqual(response.status_code, 200)
# test the response data
expected = {
"action": "enroll",
'auto_enroll': False,
"results": [
{
"identifier": 'percivaloctavius@',
"invalidIdentifier": True,
}
]
}
res_json = json.loads(response.content)
self.assertEqual(res_json, expected)
def test_invalid_username(self):
url = reverse('students_update_enrollment', kwargs={'course_id': self.course.id.to_deprecated_string()})
response = self.client.post(url, {'identifiers': 'percivaloctavius', 'action': 'enroll', 'email_students': False})
self.assertEqual(response.status_code, 200)
# test the response data
expected = {
"action": "enroll",
'auto_enroll': False,
"results": [
{
"identifier": 'percivaloctavius',
"invalidIdentifier": True,
}
]
}
res_json = json.loads(response.content)
self.assertEqual(res_json, expected)
def test_enroll_with_username(self):
url = reverse('students_update_enrollment', kwargs={'course_id': self.course.id.to_deprecated_string()})
response = self.client.post(url, {'identifiers': self.notenrolled_student.username, 'action': 'enroll', 'email_students': False})
self.assertEqual(response.status_code, 200)
# test the response data
expected = {
"action": "enroll",
'auto_enroll': False,
"results": [
{
"identifier": self.notenrolled_student.username,
"before": {
"enrollment": False,
"auto_enroll": False,
"user": True,
"allowed": False,
},
"after": {
"enrollment": True,
"auto_enroll": False,
"user": True,
"allowed": False,
}
}
]
}
res_json = json.loads(response.content)
self.assertEqual(res_json, expected)
def test_enroll_without_email(self):
url = reverse('students_update_enrollment', kwargs={'course_id': self.course.id.to_deprecated_string()})
response = self.client.post(url, {'identifiers': self.notenrolled_student.email, 'action': 'enroll', 'email_students': False})
print "type(self.notenrolled_student.email): {}".format(type(self.notenrolled_student.email))
self.assertEqual(response.status_code, 200)
# test that the user is now enrolled
user = User.objects.get(email=self.notenrolled_student.email)
self.assertTrue(CourseEnrollment.is_enrolled(user, self.course.id))
# test the response data
expected = {
"action": "enroll",
"auto_enroll": False,
"results": [
{
"identifier": self.notenrolled_student.email,
"before": {
"enrollment": False,
"auto_enroll": False,
"user": True,
"allowed": False,
},
"after": {
"enrollment": True,
"auto_enroll": False,
"user": True,
"allowed": False,
}
}
]
}
res_json = json.loads(response.content)
self.assertEqual(res_json, expected)
# Check the outbox
self.assertEqual(len(mail.outbox), 0)
@ddt.data('http', 'https')
def test_enroll_with_email(self, protocol):
url = reverse('students_update_enrollment', kwargs={'course_id': self.course.id.to_deprecated_string()})
params = {'identifiers': self.notenrolled_student.email, 'action': 'enroll', 'email_students': True}
environ = {'wsgi.url_scheme': protocol}
response = self.client.post(url, params, **environ)
print "type(self.notenrolled_student.email): {}".format(type(self.notenrolled_student.email))
self.assertEqual(response.status_code, 200)
# test that the user is now enrolled
user = User.objects.get(email=self.notenrolled_student.email)
self.assertTrue(CourseEnrollment.is_enrolled(user, self.course.id))
# test the response data
expected = {
"action": "enroll",
"auto_enroll": False,
"results": [
{
"identifier": self.notenrolled_student.email,
"before": {
"enrollment": False,
"auto_enroll": False,
"user": True,
"allowed": False,
},
"after": {
"enrollment": True,
"auto_enroll": False,
"user": True,
"allowed": False,
}
}
]
}
res_json = json.loads(response.content)
self.assertEqual(res_json, expected)
# Check the outbox
self.assertEqual(len(mail.outbox), 1)
self.assertEqual(
mail.outbox[0].subject,
u'You have been enrolled in {}'.format(self.course.display_name)
)
self.assertEqual(
mail.outbox[0].body,
"Dear NotEnrolled Student\n\nYou have been enrolled in {} "
"at edx.org by a member of the course staff. "
"The course should now appear on your edx.org dashboard.\n\n"
"To start accessing course materials, please visit "
"{proto}://{site}{course_path}\n\n----\n"
"This email was automatically sent from edx.org to NotEnrolled Student".format(
self.course.display_name,
proto=protocol, site=self.site_name, course_path=self.course_path
)
)
@ddt.data('http', 'https')
def test_enroll_with_email_not_registered(self, protocol):
url = reverse('students_update_enrollment', kwargs={'course_id': self.course.id.to_deprecated_string()})
params = {'identifiers': self.notregistered_email, 'action': 'enroll', 'email_students': True}
environ = {'wsgi.url_scheme': protocol}
response = self.client.post(url, params, **environ)
self.assertEqual(response.status_code, 200)
# Check the outbox
self.assertEqual(len(mail.outbox), 1)
self.assertEqual(
mail.outbox[0].subject,
u'You have been invited to register for {}'.format(self.course.display_name)
)
self.assertEqual(
mail.outbox[0].body,
"Dear student,\n\nYou have been invited to join {} at edx.org by a member of the course staff.\n\n"
"To finish your registration, please visit {proto}://{site}/register and fill out the "
"registration form making sure to use robot-not-an-email-yet@robot.org in the E-mail field.\n"
"Once you have registered and activated your account, "
"visit {proto}://{site}{about_path} to join the course.\n\n----\n"
"This email was automatically sent from edx.org to robot-not-an-email-yet@robot.org".format(
self.course.display_name, proto=protocol, site=self.site_name, about_path=self.about_path
)
)
@ddt.data('http', 'https')
@patch.dict(settings.FEATURES, {'ENABLE_MKTG_SITE': True})
def test_enroll_email_not_registered_mktgsite(self, protocol):
url = reverse('students_update_enrollment', kwargs={'course_id': self.course.id.to_deprecated_string()})
params = {'identifiers': self.notregistered_email, 'action': 'enroll', 'email_students': True}
environ = {'wsgi.url_scheme': protocol}
response = self.client.post(url, params, **environ)
self.assertEqual(response.status_code, 200)
self.assertEqual(
mail.outbox[0].body,
"Dear student,\n\nYou have been invited to join {display_name} at edx.org by a member of the course staff.\n\n"
"To finish your registration, please visit {proto}://{site}/register and fill out the registration form "
"making sure to use robot-not-an-email-yet@robot.org in the E-mail field.\n"
"You can then enroll in {display_name}.\n\n----\n"
"This email was automatically sent from edx.org to robot-not-an-email-yet@robot.org".format(
display_name=self.course.display_name, proto=protocol, site=self.site_name
)
)
@ddt.data('http', 'https')
def test_enroll_with_email_not_registered_autoenroll(self, protocol):
url = reverse('students_update_enrollment', kwargs={'course_id': self.course.id.to_deprecated_string()})
params = {'identifiers': self.notregistered_email, 'action': 'enroll', 'email_students': True,
'auto_enroll': True}
environ = {'wsgi.url_scheme': protocol}
response = self.client.post(url, params, **environ)
print "type(self.notregistered_email): {}".format(type(self.notregistered_email))
self.assertEqual(response.status_code, 200)
# Check the outbox
self.assertEqual(len(mail.outbox), 1)
self.assertEqual(
mail.outbox[0].subject,
u'You have been invited to register for {}'.format(self.course.display_name)
)
self.assertEqual(
mail.outbox[0].body,
"Dear student,\n\nYou have been invited to join {display_name} at edx.org by a member of the course staff.\n\n"
"To finish your registration, please visit {proto}://{site}/register and fill out the registration form "
"making sure to use robot-not-an-email-yet@robot.org in the E-mail field.\n"
"Once you have registered and activated your account, you will see {display_name} listed on your dashboard.\n\n----\n"
"This email was automatically sent from edx.org to robot-not-an-email-yet@robot.org".format(
proto=protocol, site=self.site_name, display_name=self.course.display_name
)
)
def test_unenroll_without_email(self):
url = reverse('students_update_enrollment', kwargs={'course_id': self.course.id.to_deprecated_string()})
response = self.client.post(url, {'identifiers': self.enrolled_student.email, 'action': 'unenroll', 'email_students': False})
print "type(self.enrolled_student.email): {}".format(type(self.enrolled_student.email))
self.assertEqual(response.status_code, 200)
# test that the user is now unenrolled
user = User.objects.get(email=self.enrolled_student.email)
self.assertFalse(CourseEnrollment.is_enrolled(user, self.course.id))
# test the response data
expected = {
"action": "unenroll",
"auto_enroll": False,
"results": [
{
"identifier": self.enrolled_student.email,
"before": {
"enrollment": True,
"auto_enroll": False,
"user": True,
"allowed": False,
},
"after": {
"enrollment": False,
"auto_enroll": False,
"user": True,
"allowed": False,
}
}
]
}
res_json = json.loads(response.content)
self.assertEqual(res_json, expected)
# Check the outbox
self.assertEqual(len(mail.outbox), 0)
def test_unenroll_with_email(self):
url = reverse('students_update_enrollment', kwargs={'course_id': self.course.id.to_deprecated_string()})
response = self.client.post(url, {'identifiers': self.enrolled_student.email, 'action': 'unenroll', 'email_students': True})
print "type(self.enrolled_student.email): {}".format(type(self.enrolled_student.email))
self.assertEqual(response.status_code, 200)
# test that the user is now unenrolled
user = User.objects.get(email=self.enrolled_student.email)
self.assertFalse(CourseEnrollment.is_enrolled(user, self.course.id))
# test the response data
expected = {
"action": "unenroll",
"auto_enroll": False,
"results": [
{
"identifier": self.enrolled_student.email,
"before": {
"enrollment": True,
"auto_enroll": False,
"user": True,
"allowed": False,
},
"after": {
"enrollment": False,
"auto_enroll": False,
"user": True,
"allowed": False,
}
}
]
}
res_json = json.loads(response.content)
self.assertEqual(res_json, expected)
# Check the outbox
self.assertEqual(len(mail.outbox), 1)
self.assertEqual(
mail.outbox[0].subject,
'You have been un-enrolled from {display_name}'.format(display_name=self.course.display_name,)
)
self.assertEqual(
mail.outbox[0].body,
"Dear Enrolled Student\n\nYou have been un-enrolled in {display_name} "
"at edx.org by a member of the course staff. "
"The course will no longer appear on your edx.org dashboard.\n\n"
"Your other courses have not been affected.\n\n----\n"
"This email was automatically sent from edx.org to Enrolled Student".format(
display_name=self.course.display_name,
)
)
def test_unenroll_with_email_allowed_student(self):
url = reverse('students_update_enrollment', kwargs={'course_id': self.course.id.to_deprecated_string()})
response = self.client.post(url, {'identifiers': self.allowed_email, 'action': 'unenroll', 'email_students': True})
print "type(self.allowed_email): {}".format(type(self.allowed_email))
self.assertEqual(response.status_code, 200)
# test the response data
expected = {
"action": "unenroll",
"auto_enroll": False,
"results": [
{
"identifier": self.allowed_email,
"before": {
"enrollment": False,
"auto_enroll": False,
"user": False,
"allowed": True,
},
"after": {
"enrollment": False,
"auto_enroll": False,
"user": False,
"allowed": False,
}
}
]
}
res_json = json.loads(response.content)
self.assertEqual(res_json, expected)
# Check the outbox
self.assertEqual(len(mail.outbox), 1)
self.assertEqual(
mail.outbox[0].subject,
'You have been un-enrolled from {display_name}'.format(display_name=self.course.display_name,)
)
self.assertEqual(
mail.outbox[0].body,
"Dear Student,\n\nYou have been un-enrolled from course {display_name} by a member of the course staff. "
"Please disregard the invitation previously sent.\n\n----\n"
"This email was automatically sent from edx.org to robot-allowed@robot.org".format(
display_name=self.course.display_name,
)
)
@ddt.data('http', 'https')
@patch('instructor.enrollment.uses_shib')
def test_enroll_with_email_not_registered_with_shib(self, protocol, mock_uses_shib):
mock_uses_shib.return_value = True
url = reverse('students_update_enrollment', kwargs={'course_id': self.course.id.to_deprecated_string()})
params = {'identifiers': self.notregistered_email, 'action': 'enroll', 'email_students': True}
environ = {'wsgi.url_scheme': protocol}
response = self.client.post(url, params, **environ)
self.assertEqual(response.status_code, 200)
# Check the outbox
self.assertEqual(len(mail.outbox), 1)
self.assertEqual(
mail.outbox[0].subject,
'You have been invited to register for {display_name}'.format(display_name=self.course.display_name,)
)
self.assertEqual(
mail.outbox[0].body,
"Dear student,\n\nYou have been invited to join {display_name} at edx.org by a member of the course staff.\n\n"
"To access the course visit {proto}://{site}{about_path} and register for the course.\n\n----\n"
"This email was automatically sent from edx.org to robot-not-an-email-yet@robot.org".format(
proto=protocol, site=self.site_name, about_path=self.about_path,
display_name=self.course.display_name,
)
)
@patch('instructor.enrollment.uses_shib')
@patch.dict(settings.FEATURES, {'ENABLE_MKTG_SITE': True})
def test_enroll_email_not_registered_shib_mktgsite(self, mock_uses_shib):
# Try with marketing site enabled and shib on
mock_uses_shib.return_value = True
url = reverse('students_update_enrollment', kwargs={'course_id': self.course.id.to_deprecated_string()})
# Try with marketing site enabled
with patch.dict('django.conf.settings.FEATURES', {'ENABLE_MKTG_SITE': True}):
response = self.client.post(url, {'identifiers': self.notregistered_email, 'action': 'enroll', 'email_students': True})
self.assertEqual(response.status_code, 200)
self.assertEqual(
mail.outbox[0].body,
"Dear student,\n\nYou have been invited to join {} at edx.org by a member of the course staff.\n\n----\n"
"This email was automatically sent from edx.org to robot-not-an-email-yet@robot.org".format(
self.course.display_name,
)
)
@ddt.data('http', 'https')
@patch('instructor.enrollment.uses_shib')
def test_enroll_with_email_not_registered_with_shib_autoenroll(self, protocol, mock_uses_shib):
mock_uses_shib.return_value = True
url = reverse('students_update_enrollment', kwargs={'course_id': self.course.id.to_deprecated_string()})
params = {'identifiers': self.notregistered_email, 'action': 'enroll', 'email_students': True,
'auto_enroll': True}
environ = {'wsgi.url_scheme': protocol}
response = self.client.post(url, params, **environ)
print "type(self.notregistered_email): {}".format(type(self.notregistered_email))
self.assertEqual(response.status_code, 200)
# Check the outbox
self.assertEqual(len(mail.outbox), 1)
self.assertEqual(
mail.outbox[0].subject,
'You have been invited to register for {display_name}'.format(display_name=self.course.display_name,)
)
self.assertEqual(
mail.outbox[0].body,
"Dear student,\n\nYou have been invited to join {display_name} at edx.org by a member of the course staff.\n\n"
"To access the course visit {proto}://{site}{course_path} and login.\n\n----\n"
"This email was automatically sent from edx.org to robot-not-an-email-yet@robot.org".format(
display_name=self.course.display_name,
proto=protocol, site=self.site_name, course_path=self.course_path
)
)
def test_enroll_already_enrolled_student(self):
"""
Ensure that already enrolled "verified" students cannot be downgraded
to "honor"
"""
course_enrollment = CourseEnrollment.objects.get(
user=self.enrolled_student, course_id=self.course.id
)
# make this enrollment "verified"
course_enrollment.mode = u'verified'
course_enrollment.save()
self.assertEqual(course_enrollment.mode, u'verified')
# now re-enroll the student through the instructor dash
self._change_student_enrollment(self.enrolled_student, self.course, 'enroll')
# affirm that the student is still in "verified" mode
course_enrollment = CourseEnrollment.objects.get(
user=self.enrolled_student, course_id=self.course.id
)
self.assertEqual(course_enrollment.mode, u"verified")
def test_unenroll_and_enroll_verified(self):
"""
Test that unenrolling and enrolling a student from a verified track
results in that student being in an honor track
"""
course_enrollment = CourseEnrollment.objects.get(
user=self.enrolled_student, course_id=self.course.id
)
# upgrade enrollment
course_enrollment.mode = u'verified'
course_enrollment.save()
self.assertEqual(course_enrollment.mode, u'verified')
self._change_student_enrollment(self.enrolled_student, self.course, 'unenroll')
self._change_student_enrollment(self.enrolled_student, self.course, 'enroll')
course_enrollment = CourseEnrollment.objects.get(
user=self.enrolled_student, course_id=self.course.id
)
self.assertEqual(course_enrollment.mode, u'honor')
def _change_student_enrollment(self, user, course, action):
"""
Helper function that posts to 'students_update_enrollment' to change
a student's enrollment
"""
url = reverse(
'students_update_enrollment',
kwargs={'course_id': course.id.to_deprecated_string()},
)
params = {
'identifiers': user.email,
'action': action,
'email_students': True,
}
response = self.client.post(url, params)
self.assertEqual(response.status_code, 200)
return response
@ddt.ddt
@override_settings(MODULESTORE=TEST_DATA_MOCK_MODULESTORE)
class TestInstructorAPIBulkBetaEnrollment(ModuleStoreTestCase, LoginEnrollmentTestCase):
"""
Test bulk beta modify access endpoint.
"""
def setUp(self):
self.course = CourseFactory.create()
self.instructor = InstructorFactory(course_key=self.course.id)
self.client.login(username=self.instructor.username, password='test')
self.beta_tester = BetaTesterFactory(course_key=self.course.id)
CourseEnrollment.enroll(
self.beta_tester,
self.course.id
)
self.assertTrue(CourseBetaTesterRole(self.course.id).has_user(self.beta_tester))
self.notenrolled_student = UserFactory(username='NotEnrolledStudent')
self.notregistered_email = 'robot-not-an-email-yet@robot.org'
self.assertEqual(User.objects.filter(email=self.notregistered_email).count(), 0)
self.request = RequestFactory().request()
# Email URL values
self.site_name = microsite.get_value(
'SITE_NAME',
settings.SITE_NAME
)
self.about_path = '/courses/{}/about'.format(self.course.id)
self.course_path = '/courses/{}/'.format(self.course.id)
# uncomment to enable enable printing of large diffs
# from failed assertions in the event of a test failure.
# (comment because pylint C0103(invalid-name))
# self.maxDiff = None
def test_missing_params(self):
""" Test missing all query parameters. """
url = reverse('bulk_beta_modify_access', kwargs={'course_id': self.course.id.to_deprecated_string()})
response = self.client.post(url)
self.assertEqual(response.status_code, 400)
def test_bad_action(self):
""" Test with an invalid action. """
action = 'robot-not-an-action'
url = reverse('bulk_beta_modify_access', kwargs={'course_id': self.course.id.to_deprecated_string()})
response = self.client.post(url, {'identifiers': self.beta_tester.email, 'action': action})
self.assertEqual(response.status_code, 400)
def add_notenrolled(self, response, identifier):
"""
Test Helper Method (not a test, called by other tests)
Takes a client response from a call to bulk_beta_modify_access with 'email_students': False,
and the student identifier (email or username) given as 'identifiers' in the request.
Asserts the reponse returns cleanly, that the student was added as a beta tester, and the
response properly contains their identifier, 'error': False, and 'userDoesNotExist': False.
Additionally asserts no email was sent.
"""
self.assertEqual(response.status_code, 200)
self.assertTrue(CourseBetaTesterRole(self.course.id).has_user(self.notenrolled_student))
# test the response data
expected = {
"action": "add",
"results": [
{
"identifier": identifier,
"error": False,
"userDoesNotExist": False
}
]
}
res_json = json.loads(response.content)
self.assertEqual(res_json, expected)
# Check the outbox
self.assertEqual(len(mail.outbox), 0)
def test_add_notenrolled_email(self):
url = reverse('bulk_beta_modify_access', kwargs={'course_id': self.course.id.to_deprecated_string()})
response = self.client.post(url, {'identifiers': self.notenrolled_student.email, 'action': 'add', 'email_students': False})
self.add_notenrolled(response, self.notenrolled_student.email)
self.assertFalse(CourseEnrollment.is_enrolled(self.notenrolled_student, self.course.id))
def test_add_notenrolled_email_autoenroll(self):
url = reverse('bulk_beta_modify_access', kwargs={'course_id': self.course.id.to_deprecated_string()})
response = self.client.post(url, {'identifiers': self.notenrolled_student.email, 'action': 'add', 'email_students': False, 'auto_enroll': True})
self.add_notenrolled(response, self.notenrolled_student.email)
self.assertTrue(CourseEnrollment.is_enrolled(self.notenrolled_student, self.course.id))
def test_add_notenrolled_username(self):
url = reverse('bulk_beta_modify_access', kwargs={'course_id': self.course.id.to_deprecated_string()})
response = self.client.post(url, {'identifiers': self.notenrolled_student.username, 'action': 'add', 'email_students': False})
self.add_notenrolled(response, self.notenrolled_student.username)
self.assertFalse(CourseEnrollment.is_enrolled(self.notenrolled_student, self.course.id))
def test_add_notenrolled_username_autoenroll(self):
url = reverse('bulk_beta_modify_access', kwargs={'course_id': self.course.id.to_deprecated_string()})
response = self.client.post(url, {'identifiers': self.notenrolled_student.username, 'action': 'add', 'email_students': False, 'auto_enroll': True})
self.add_notenrolled(response, self.notenrolled_student.username)
self.assertTrue(CourseEnrollment.is_enrolled(self.notenrolled_student, self.course.id))
@ddt.data('http', 'https')
def test_add_notenrolled_with_email(self, protocol):
url = reverse('bulk_beta_modify_access', kwargs={'course_id': self.course.id.to_deprecated_string()})
params = {'identifiers': self.notenrolled_student.email, 'action': 'add', 'email_students': True}
environ = {'wsgi.url_scheme': protocol}
response = self.client.post(url, params, **environ)
self.assertEqual(response.status_code, 200)
self.assertTrue(CourseBetaTesterRole(self.course.id).has_user(self.notenrolled_student))
# test the response data
expected = {
"action": "add",
"results": [
{
"identifier": self.notenrolled_student.email,
"error": False,
"userDoesNotExist": False
}
]
}
res_json = json.loads(response.content)
self.assertEqual(res_json, expected)
# Check the outbox
self.assertEqual(len(mail.outbox), 1)
self.assertEqual(
mail.outbox[0].subject,
'You have been invited to a beta test for {display_name}'.format(display_name=self.course.display_name,)
)
self.assertEqual(
mail.outbox[0].body,
u"Dear {student_name}\n\nYou have been invited to be a beta tester "
"for {display_name} at edx.org by a member of the course staff.\n\n"
"Visit {proto}://{site}{about_path} to join "
"the course and begin the beta test.\n\n----\n"
"This email was automatically sent from edx.org to {student_email}".format(
display_name=self.course.display_name,
student_name=self.notenrolled_student.profile.name,
student_email=self.notenrolled_student.email,
proto=protocol,
site=self.site_name,
about_path=self.about_path
)
)
@ddt.data('http', 'https')
def test_add_notenrolled_with_email_autoenroll(self, protocol):
url = reverse('bulk_beta_modify_access', kwargs={'course_id': self.course.id.to_deprecated_string()})
params = {'identifiers': self.notenrolled_student.email, 'action': 'add', 'email_students': True,
'auto_enroll': True}
environ = {'wsgi.url_scheme': protocol}
response = self.client.post(url, params, **environ)
self.assertEqual(response.status_code, 200)
self.assertTrue(CourseBetaTesterRole(self.course.id).has_user(self.notenrolled_student))
# test the response data
expected = {
"action": "add",
"results": [
{
"identifier": self.notenrolled_student.email,
"error": False,
"userDoesNotExist": False
}
]
}
res_json = json.loads(response.content)
self.assertEqual(res_json, expected)
# Check the outbox
self.assertEqual(len(mail.outbox), 1)
self.assertEqual(
mail.outbox[0].subject,
'You have been invited to a beta test for {display_name}'.format(display_name=self.course.display_name)
)
self.assertEqual(
mail.outbox[0].body,
u"Dear {student_name}\n\nYou have been invited to be a beta tester "
"for {display_name} at edx.org by a member of the course staff.\n\n"
"To start accessing course materials, please visit "
"{proto}://{site}{course_path}\n\n----\n"
"This email was automatically sent from edx.org to {student_email}".format(
display_name=self.course.display_name,
student_name=self.notenrolled_student.profile.name,
student_email=self.notenrolled_student.email,
proto=protocol,
site=self.site_name,
course_path=self.course_path
)
)
@patch.dict(settings.FEATURES, {'ENABLE_MKTG_SITE': True})
def test_add_notenrolled_email_mktgsite(self):
# Try with marketing site enabled
url = reverse('bulk_beta_modify_access', kwargs={'course_id': self.course.id.to_deprecated_string()})
response = self.client.post(url, {'identifiers': self.notenrolled_student.email, 'action': 'add', 'email_students': True})
self.assertEqual(response.status_code, 200)
self.assertEqual(
mail.outbox[0].body,
u"Dear {}\n\nYou have been invited to be a beta tester "
"for {} at edx.org by a member of the course staff.\n\n"
"Visit edx.org to enroll in the course and begin the beta test.\n\n----\n"
"This email was automatically sent from edx.org to {}".format(
self.notenrolled_student.profile.name,
self.course.display_name,
self.notenrolled_student.email,
)
)
def test_enroll_with_email_not_registered(self):
# User doesn't exist
url = reverse('bulk_beta_modify_access', kwargs={'course_id': self.course.id.to_deprecated_string()})
response = self.client.post(url, {'identifiers': self.notregistered_email, 'action': 'add', 'email_students': True})
self.assertEqual(response.status_code, 200)
# test the response data
expected = {
"action": "add",
"results": [
{
"identifier": self.notregistered_email,
"error": True,
"userDoesNotExist": True
}
]
}
res_json = json.loads(response.content)
self.assertEqual(res_json, expected)
# Check the outbox
self.assertEqual(len(mail.outbox), 0)
def test_remove_without_email(self):
url = reverse('bulk_beta_modify_access', kwargs={'course_id': self.course.id.to_deprecated_string()})
response = self.client.post(url, {'identifiers': self.beta_tester.email, 'action': 'remove', 'email_students': False})
self.assertEqual(response.status_code, 200)
# Works around a caching bug which supposedly can't happen in prod. The instance here is not ==
# the instance fetched from the email above which had its cache cleared
if hasattr(self.beta_tester, '_roles'):
del self.beta_tester._roles
self.assertFalse(CourseBetaTesterRole(self.course.id).has_user(self.beta_tester))
# test the response data
expected = {
"action": "remove",
"results": [
{
"identifier": self.beta_tester.email,
"error": False,
"userDoesNotExist": False
}
]
}
res_json = json.loads(response.content)
self.assertEqual(res_json, expected)
# Check the outbox
self.assertEqual(len(mail.outbox), 0)
def test_remove_with_email(self):
url = reverse('bulk_beta_modify_access', kwargs={'course_id': self.course.id.to_deprecated_string()})
response = self.client.post(url, {'identifiers': self.beta_tester.email, 'action': 'remove', 'email_students': True})
self.assertEqual(response.status_code, 200)
# Works around a caching bug which supposedly can't happen in prod. The instance here is not ==
# the instance fetched from the email above which had its cache cleared
if hasattr(self.beta_tester, '_roles'):
del self.beta_tester._roles
self.assertFalse(CourseBetaTesterRole(self.course.id).has_user(self.beta_tester))
# test the response data
expected = {
"action": "remove",
"results": [
{
"identifier": self.beta_tester.email,
"error": False,
"userDoesNotExist": False
}
]
}
res_json = json.loads(response.content)
self.assertEqual(res_json, expected)
# Check the outbox
self.assertEqual(len(mail.outbox), 1)
self.assertEqual(
mail.outbox[0].subject,
u'You have been removed from a beta test for {display_name}'.format(display_name=self.course.display_name,)
)
self.assertEqual(
mail.outbox[0].body,
"Dear {full_name}\n\nYou have been removed as a beta tester for "
"{display_name} at edx.org by a member of the course staff. "
"The course will remain on your dashboard, but you will no longer "
"be part of the beta testing group.\n\n"
"Your other courses have not been affected.\n\n----\n"
"This email was automatically sent from edx.org to {email_address}".format(
display_name=self.course.display_name,
full_name=self.beta_tester.profile.name,
email_address=self.beta_tester.email
)
)
@override_settings(MODULESTORE=TEST_DATA_MOCK_MODULESTORE)
class TestInstructorAPILevelsAccess(ModuleStoreTestCase, LoginEnrollmentTestCase):
"""
Test endpoints whereby instructors can change permissions
of other users.
This test does NOT test whether the actions had an effect on the
database, that is the job of test_access.
This tests the response and action switch.
Actually, modify_access does not have a very meaningful
response yet, so only the status code is tested.
"""
def setUp(self):
self.course = CourseFactory.create()
self.instructor = InstructorFactory(course_key=self.course.id)
self.client.login(username=self.instructor.username, password='test')
self.other_instructor = InstructorFactory(course_key=self.course.id)
self.other_staff = StaffFactory(course_key=self.course.id)
self.other_user = UserFactory()
def test_modify_access_noparams(self):
""" Test missing all query parameters. """
url = reverse('modify_access', kwargs={'course_id': self.course.id.to_deprecated_string()})
response = self.client.get(url)
self.assertEqual(response.status_code, 400)
def test_modify_access_bad_action(self):
""" Test with an invalid action parameter. """
url = reverse('modify_access', kwargs={'course_id': self.course.id.to_deprecated_string()})
response = self.client.get(url, {
'unique_student_identifier': self.other_staff.email,
'rolename': 'staff',
'action': 'robot-not-an-action',
})
self.assertEqual(response.status_code, 400)
def test_modify_access_bad_role(self):
""" Test with an invalid action parameter. """
url = reverse('modify_access', kwargs={'course_id': self.course.id.to_deprecated_string()})
response = self.client.get(url, {
'unique_student_identifier': self.other_staff.email,
'rolename': 'robot-not-a-roll',
'action': 'revoke',
})
self.assertEqual(response.status_code, 400)
def test_modify_access_allow(self):
url = reverse('modify_access', kwargs={'course_id': self.course.id.to_deprecated_string()})
response = self.client.get(url, {
'unique_student_identifier': self.other_user.email,
'rolename': 'staff',
'action': 'allow',
})
self.assertEqual(response.status_code, 200)
def test_modify_access_allow_with_uname(self):
url = reverse('modify_access', kwargs={'course_id': self.course.id.to_deprecated_string()})
response = self.client.get(url, {
'unique_student_identifier': self.other_instructor.username,
'rolename': 'staff',
'action': 'allow',
})
self.assertEqual(response.status_code, 200)
def test_modify_access_revoke(self):
url = reverse('modify_access', kwargs={'course_id': self.course.id.to_deprecated_string()})
response = self.client.get(url, {
'unique_student_identifier': self.other_staff.email,
'rolename': 'staff',
'action': 'revoke',
})
self.assertEqual(response.status_code, 200)
def test_modify_access_revoke_with_username(self):
url = reverse('modify_access', kwargs={'course_id': self.course.id.to_deprecated_string()})
response = self.client.get(url, {
'unique_student_identifier': self.other_staff.username,
'rolename': 'staff',
'action': 'revoke',
})
self.assertEqual(response.status_code, 200)
def test_modify_access_with_fake_user(self):
url = reverse('modify_access', kwargs={'course_id': self.course.id.to_deprecated_string()})
response = self.client.get(url, {
'unique_student_identifier': 'GandalfTheGrey',
'rolename': 'staff',
'action': 'revoke',
})
self.assertEqual(response.status_code, 200)
expected = {
'unique_student_identifier': 'GandalfTheGrey',
'userDoesNotExist': True,
}
res_json = json.loads(response.content)
self.assertEqual(res_json, expected)
def test_modify_access_with_inactive_user(self):
self.other_user.is_active = False
self.other_user.save() # pylint: disable=no-member
url = reverse('modify_access', kwargs={'course_id': self.course.id.to_deprecated_string()})
response = self.client.get(url, {
'unique_student_identifier': self.other_user.username,
'rolename': 'beta',
'action': 'allow',
})
self.assertEqual(response.status_code, 200)
expected = {
'unique_student_identifier': self.other_user.username,
'inactiveUser': True,
}
res_json = json.loads(response.content)
self.assertEqual(res_json, expected)
def test_modify_access_revoke_not_allowed(self):
""" Test revoking access that a user does not have. """
url = reverse('modify_access', kwargs={'course_id': self.course.id.to_deprecated_string()})
response = self.client.get(url, {
'unique_student_identifier': self.other_staff.email,
'rolename': 'instructor',
'action': 'revoke',
})
self.assertEqual(response.status_code, 200)
def test_modify_access_revoke_self(self):
"""
Test that an instructor cannot remove instructor privelages from themself.
"""
url = reverse('modify_access', kwargs={'course_id': self.course.id.to_deprecated_string()})
response = self.client.get(url, {
'unique_student_identifier': self.instructor.email,
'rolename': 'instructor',
'action': 'revoke',
})
self.assertEqual(response.status_code, 200)
# check response content
expected = {
'unique_student_identifier': self.instructor.username,
'rolename': 'instructor',
'action': 'revoke',
'removingSelfAsInstructor': True,
}
res_json = json.loads(response.content)
self.assertEqual(res_json, expected)
def test_list_course_role_members_noparams(self):
""" Test missing all query parameters. """
url = reverse('list_course_role_members', kwargs={'course_id': self.course.id.to_deprecated_string()})
response = self.client.get(url)
self.assertEqual(response.status_code, 400)
def test_list_course_role_members_bad_rolename(self):
""" Test with an invalid rolename parameter. """
url = reverse('list_course_role_members', kwargs={'course_id': self.course.id.to_deprecated_string()})
response = self.client.get(url, {
'rolename': 'robot-not-a-rolename',
})
self.assertEqual(response.status_code, 400)
def test_list_course_role_members_staff(self):
url = reverse('list_course_role_members', kwargs={'course_id': self.course.id.to_deprecated_string()})
response = self.client.get(url, {
'rolename': 'staff',
})
self.assertEqual(response.status_code, 200)
# check response content
expected = {
'course_id': self.course.id.to_deprecated_string(),
'staff': [
{
'username': self.other_staff.username,
'email': self.other_staff.email,
'first_name': self.other_staff.first_name,
'last_name': self.other_staff.last_name,
}
]
}
res_json = json.loads(response.content)
self.assertEqual(res_json, expected)
def test_list_course_role_members_beta(self):
url = reverse('list_course_role_members', kwargs={'course_id': self.course.id.to_deprecated_string()})
response = self.client.get(url, {
'rolename': 'beta',
})
self.assertEqual(response.status_code, 200)
# check response content
expected = {
'course_id': self.course.id.to_deprecated_string(),
'beta': []
}
res_json = json.loads(response.content)
self.assertEqual(res_json, expected)
def test_update_forum_role_membership(self):
"""
Test update forum role membership with user's email and username.
"""
# Seed forum roles for course.
seed_permissions_roles(self.course.id)
for user in [self.instructor, self.other_user]:
for identifier_attr in [user.email, user.username]:
for rolename in ["Administrator", "Moderator", "Community TA"]:
for action in ["allow", "revoke"]:
self.assert_update_forum_role_membership(user, identifier_attr, rolename, action)
def assert_update_forum_role_membership(self, current_user, identifier, rolename, action):
"""
Test update forum role membership.
Get unique_student_identifier, rolename and action and update forum role.
"""
url = reverse('update_forum_role_membership', kwargs={'course_id': self.course.id.to_deprecated_string()})
response = self.client.get(
url,
{
'unique_student_identifier': identifier,
'rolename': rolename,
'action': action,
}
)
# Status code should be 200.
self.assertEqual(response.status_code, 200)
user_roles = current_user.roles.filter(course_id=self.course.id).values_list("name", flat=True)
if action == 'allow':
self.assertIn(rolename, user_roles)
elif action == 'revoke':
self.assertNotIn(rolename, user_roles)
@ddt.ddt
@override_settings(MODULESTORE=TEST_DATA_MOCK_MODULESTORE)
@patch.dict('django.conf.settings.FEATURES', {'ENABLE_PAID_COURSE_REGISTRATION': True})
class TestInstructorAPILevelsDataDump(ModuleStoreTestCase, LoginEnrollmentTestCase):
"""
Test endpoints that show data without side effects.
"""
def setUp(self):
super(TestInstructorAPILevelsDataDump, self).setUp()
self.course = CourseFactory.create()
self.course_mode = CourseMode(course_id=self.course.id,
mode_slug="honor",
mode_display_name="honor cert",
min_price=40)
self.course_mode.save()
self.instructor = InstructorFactory(course_key=self.course.id)
self.client.login(username=self.instructor.username, password='test')
self.cart = Order.get_cart_for_user(self.instructor)
self.coupon_code = 'abcde'
self.coupon = Coupon(code=self.coupon_code, description='testing code', course_id=self.course.id,
percentage_discount=10, created_by=self.instructor, is_active=True)
self.coupon.save()
#create testing invoice 1
self.sale_invoice_1 = Invoice.objects.create(
total_amount=1234.32, company_name='Test1', company_contact_name='TestName', company_contact_email='Test@company.com',
recipient_name='Testw', recipient_email='test1@test.com', customer_reference_number='2Fwe23S',
internal_reference="A", course_id=self.course.id, is_valid=True
)
self.students = [UserFactory() for _ in xrange(6)]
for student in self.students:
CourseEnrollment.enroll(student, self.course.id)
def test_invalidate_sale_record(self):
"""
Testing the sale invalidating scenario.
"""
for i in range(2):
course_registration_code = CourseRegistrationCode(
code='sale_invoice{}'.format(i), course_id=self.course.id.to_deprecated_string(),
created_by=self.instructor, invoice=self.sale_invoice_1, mode_slug='honor'
)
course_registration_code.save()
data = {'invoice_number': self.sale_invoice_1.id, 'event_type': "invalidate"}
url = reverse('sale_validation', kwargs={'course_id': self.course.id.to_deprecated_string()})
self.assert_request_status_code(200, url, method="POST", data=data)
#Now try to fetch data against not existing invoice number
test_data_1 = {'invoice_number': 100, 'event_type': "invalidate"}
self.assert_request_status_code(404, url, method="POST", data=test_data_1)
# Now invalidate the same invoice number and expect an Bad request
response = self.assert_request_status_code(400, url, method="POST", data=data)
self.assertIn("The sale associated with this invoice has already been invalidated.", response.content)
# now re_validate the invoice number
data['event_type'] = "re_validate"
self.assert_request_status_code(200, url, method="POST", data=data)
# Now re_validate the same actove invoice number and expect an Bad request
response = self.assert_request_status_code(400, url, method="POST", data=data)
self.assertIn("This invoice is already active.", response.content)
test_data_2 = {'invoice_number': self.sale_invoice_1.id}
response = self.assert_request_status_code(400, url, method="POST", data=test_data_2)
self.assertIn("Missing required event_type parameter", response.content)
test_data_3 = {'event_type': "re_validate"}
response = self.assert_request_status_code(400, url, method="POST", data=test_data_3)
self.assertIn("Missing required invoice_number parameter", response.content)
# submitting invalid invoice number
data['invoice_number'] = 'testing'
response = self.assert_request_status_code(400, url, method="POST", data=data)
self.assertIn("invoice_number must be an integer, {value} provided".format(value=data['invoice_number']), response.content)
def test_get_sale_order_records_features_csv(self):
"""
Test that the response from get_sale_order_records is in csv format.
"""
# add the coupon code for the course
coupon = Coupon(
code='test_code', description='test_description', course_id=self.course.id,
percentage_discount='10', created_by=self.instructor, is_active=True
)
coupon.save()
self.cart.order_type = 'business'
self.cart.save()
self.cart.add_billing_details(company_name='Test Company', company_contact_name='Test',
company_contact_email='test@123', recipient_name='R1',
recipient_email='', customer_reference_number='PO#23')
paid_course_reg_item = PaidCourseRegistration.add_to_order(self.cart, self.course.id)
# update the quantity of the cart item paid_course_reg_item
resp = self.client.post(reverse('shoppingcart.views.update_user_cart'), {'ItemId': paid_course_reg_item.id, 'qty': '4'})
self.assertEqual(resp.status_code, 200)
# apply the coupon code to the item in the cart
resp = self.client.post(reverse('shoppingcart.views.use_code'), {'code': coupon.code})
self.assertEqual(resp.status_code, 200)
self.cart.purchase()
# get the updated item
item = self.cart.orderitem_set.all().select_subclasses()[0]
# get the redeemed coupon information
coupon_redemption = CouponRedemption.objects.select_related('coupon').filter(order=self.cart)
sale_order_url = reverse('get_sale_order_records', kwargs={'course_id': self.course.id.to_deprecated_string()})
response = self.client.get(sale_order_url)
self.assertEqual(response['Content-Type'], 'text/csv')
self.assertIn('36', response.content.split('\r\n')[1])
self.assertIn(str(item.unit_cost), response.content.split('\r\n')[1],)
self.assertIn(str(item.list_price), response.content.split('\r\n')[1],)
self.assertIn(item.status, response.content.split('\r\n')[1],)
self.assertIn(coupon_redemption[0].coupon.code, response.content.split('\r\n')[1],)
def test_coupon_redeem_count_in_ecommerce_section(self):
"""
Test that checks the redeem count in the instructor_dashboard coupon section
"""
# add the coupon code for the course
coupon = Coupon(
code='test_code', description='test_description', course_id=self.course.id,
percentage_discount='10', created_by=self.instructor, is_active=True
)
coupon.save()
# Coupon Redeem Count only visible for Financial Admins.
CourseFinanceAdminRole(self.course.id).add_users(self.instructor)
PaidCourseRegistration.add_to_order(self.cart, self.course.id)
# apply the coupon code to the item in the cart
resp = self.client.post(reverse('shoppingcart.views.use_code'), {'code': coupon.code})
self.assertEqual(resp.status_code, 200)
# URL for instructor dashboard
instructor_dashboard = reverse('instructor_dashboard', kwargs={'course_id': self.course.id.to_deprecated_string()})
# visit the instructor dashboard page and
# check that the coupon redeem count should be 0
resp = self.client.get(instructor_dashboard)
self.assertEqual(resp.status_code, 200)
self.assertIn('Redeem Count', resp.content)
self.assertIn('<td>0</td>', resp.content)
# now make the payment of your cart items
self.cart.purchase()
# visit the instructor dashboard page and
# check that the coupon redeem count should be 1
resp = self.client.get(instructor_dashboard)
self.assertEqual(resp.status_code, 200)
self.assertIn('Redeem Count', resp.content)
self.assertIn('<td>1</td>', resp.content)
def test_get_sale_records_features_csv(self):
"""
Test that the response from get_sale_records is in csv format.
"""
for i in range(2):
course_registration_code = CourseRegistrationCode(
code='sale_invoice{}'.format(i), course_id=self.course.id.to_deprecated_string(),
created_by=self.instructor, invoice=self.sale_invoice_1, mode_slug='honor'
)
course_registration_code.save()
url = reverse('get_sale_records', kwargs={'course_id': self.course.id.to_deprecated_string()})
response = self.client.get(url + '/csv', {})
self.assertEqual(response['Content-Type'], 'text/csv')
def test_get_sale_records_features_json(self):
"""
Test that the response from get_sale_records is in json format.
"""
for i in range(5):
course_registration_code = CourseRegistrationCode(
code='sale_invoice{}'.format(i), course_id=self.course.id.to_deprecated_string(),
created_by=self.instructor, invoice=self.sale_invoice_1, mode_slug='honor'
)
course_registration_code.save()
url = reverse('get_sale_records', kwargs={'course_id': self.course.id.to_deprecated_string()})
response = self.client.get(url, {})
res_json = json.loads(response.content)
self.assertIn('sale', res_json)
for res in res_json['sale']:
self.validate_sale_records_response(res, course_registration_code, self.sale_invoice_1, 0)
def test_get_sale_records_features_with_multiple_invoices(self):
"""
Test that the response from get_sale_records is in json format for multiple invoices
"""
for i in range(5):
course_registration_code = CourseRegistrationCode(
code='qwerty{}'.format(i), course_id=self.course.id.to_deprecated_string(),
created_by=self.instructor, invoice=self.sale_invoice_1, mode_slug='honor'
)
course_registration_code.save()
#create test invoice 2
sale_invoice_2 = Invoice.objects.create(
total_amount=1234.32, company_name='Test1', company_contact_name='TestName', company_contact_email='Test@company.com',
recipient_name='Testw_2', recipient_email='test2@test.com', customer_reference_number='2Fwe23S',
internal_reference="B", course_id=self.course.id
)
for i in range(5):
course_registration_code = CourseRegistrationCode(
code='xyzmn{}'.format(i), course_id=self.course.id.to_deprecated_string(),
created_by=self.instructor, invoice=sale_invoice_2, mode_slug='honor'
)
course_registration_code.save()
url = reverse('get_sale_records', kwargs={'course_id': self.course.id.to_deprecated_string()})
response = self.client.get(url, {})
res_json = json.loads(response.content)
self.assertIn('sale', res_json)
self.validate_sale_records_response(res_json['sale'][0], course_registration_code, self.sale_invoice_1, 0)
self.validate_sale_records_response(res_json['sale'][1], course_registration_code, sale_invoice_2, 0)
def validate_sale_records_response(self, res, course_registration_code, invoice, used_codes):
"""
validate sale records attribute values with the response object
"""
self.assertEqual(res['total_amount'], invoice.total_amount)
self.assertEqual(res['recipient_email'], invoice.recipient_email)
self.assertEqual(res['recipient_name'], invoice.recipient_name)
self.assertEqual(res['company_name'], invoice.company_name)
self.assertEqual(res['company_contact_name'], invoice.company_contact_name)
self.assertEqual(res['company_contact_email'], invoice.company_contact_email)
self.assertEqual(res['internal_reference'], invoice.internal_reference)
self.assertEqual(res['customer_reference_number'], invoice.customer_reference_number)
self.assertEqual(res['invoice_number'], invoice.id)
self.assertEqual(res['created_by'], course_registration_code.created_by.username)
self.assertEqual(res['course_id'], invoice.course_id.to_deprecated_string())
self.assertEqual(res['total_used_codes'], used_codes)
self.assertEqual(res['total_codes'], 5)
def test_get_students_features(self):
"""
Test that some minimum of information is formatted
correctly in the response to get_students_features.
"""
url = reverse('get_students_features', kwargs={'course_id': self.course.id.to_deprecated_string()})
response = self.client.get(url, {})
res_json = json.loads(response.content)
self.assertIn('students', res_json)
for student in self.students:
student_json = [
x for x in res_json['students']
if x['username'] == student.username
][0]
self.assertEqual(student_json['username'], student.username)
self.assertEqual(student_json['email'], student.email)
@ddt.data(True, False)
def test_get_students_features_cohorted(self, is_cohorted):
"""
Test that get_students_features includes cohort info when the course is
cohorted, and does not when the course is not cohorted.
"""
url = reverse('get_students_features', kwargs={'course_id': unicode(self.course.id)})
self.course.cohort_config = {'cohorted': is_cohorted}
self.store.update_item(self.course, self.instructor.id)
response = self.client.get(url, {})
res_json = json.loads(response.content)
self.assertEqual('cohort' in res_json['feature_names'], is_cohorted)
@patch.object(instructor.views.api, 'anonymous_id_for_user', Mock(return_value='42'))
@patch.object(instructor.views.api, 'unique_id_for_user', Mock(return_value='41'))
def test_get_anon_ids(self):
"""
Test the CSV output for the anonymized user ids.
"""
url = reverse('get_anon_ids', kwargs={'course_id': self.course.id.to_deprecated_string()})
response = self.client.get(url, {})
self.assertEqual(response['Content-Type'], 'text/csv')
body = response.content.replace('\r', '')
self.assertTrue(body.startswith(
'"User ID","Anonymized User ID","Course Specific Anonymized User ID"'
'\n"3","41","42"\n'
))
self.assertTrue(body.endswith('"8","41","42"\n'))
def test_list_report_downloads(self):
url = reverse('list_report_downloads', kwargs={'course_id': self.course.id.to_deprecated_string()})
with patch('instructor_task.models.LocalFSReportStore.links_for') as mock_links_for:
mock_links_for.return_value = [
('mock_file_name_1', 'https://1.mock.url'),
('mock_file_name_2', 'https://2.mock.url'),
]
response = self.client.get(url, {})
expected_response = {
"downloads": [
{
"url": "https://1.mock.url",
"link": "<a href=\"https://1.mock.url\">mock_file_name_1</a>",
"name": "mock_file_name_1"
},
{
"url": "https://2.mock.url",
"link": "<a href=\"https://2.mock.url\">mock_file_name_2</a>",
"name": "mock_file_name_2"
}
]
}
res_json = json.loads(response.content)
self.assertEqual(res_json, expected_response)
@ddt.data(*REPORTS_DATA)
@ddt.unpack
def test_calculate_report_csv_success(self, report_type, instructor_api_endpoint, task_api_endpoint, extra_instructor_api_kwargs):
kwargs = {'course_id': unicode(self.course.id)}
kwargs.update(extra_instructor_api_kwargs)
url = reverse(instructor_api_endpoint, kwargs=kwargs)
with patch(task_api_endpoint):
response = self.client.get(url, {})
success_status = "Your {report_type} report is being generated! You can view the status of the generation task in the 'Pending Instructor Tasks' section.".format(report_type=report_type)
self.assertIn(success_status, response.content)
@ddt.data(*REPORTS_DATA)
@ddt.unpack
def test_calculate_report_csv_already_running(self, report_type, instructor_api_endpoint, task_api_endpoint, extra_instructor_api_kwargs):
kwargs = {'course_id': unicode(self.course.id)}
kwargs.update(extra_instructor_api_kwargs)
url = reverse(instructor_api_endpoint, kwargs=kwargs)
with patch(task_api_endpoint) as mock:
mock.side_effect = AlreadyRunningError()
response = self.client.get(url, {})
already_running_status = "{report_type} report generation task is already in progress. Check the 'Pending Instructor Tasks' table for the status of the task. When completed, the report will be available for download in the table below.".format(report_type=report_type)
self.assertIn(already_running_status, response.content)
def test_get_distribution_no_feature(self):
"""
Test that get_distribution lists available features
when supplied no feature parameter.
"""
url = reverse('get_distribution', kwargs={'course_id': self.course.id.to_deprecated_string()})
response = self.client.get(url)
self.assertEqual(response.status_code, 200)
res_json = json.loads(response.content)
self.assertEqual(type(res_json['available_features']), list)
url = reverse('get_distribution', kwargs={'course_id': self.course.id.to_deprecated_string()})
response = self.client.get(url + u'?feature=')
self.assertEqual(response.status_code, 200)
res_json = json.loads(response.content)
self.assertEqual(type(res_json['available_features']), list)
def test_get_distribution_unavailable_feature(self):
"""
Test that get_distribution fails gracefully with
an unavailable feature.
"""
url = reverse('get_distribution', kwargs={'course_id': self.course.id.to_deprecated_string()})
response = self.client.get(url, {'feature': 'robot-not-a-real-feature'})
self.assertEqual(response.status_code, 400)
def test_get_distribution_gender(self):
"""
Test that get_distribution fails gracefully with
an unavailable feature.
"""
url = reverse('get_distribution', kwargs={'course_id': self.course.id.to_deprecated_string()})
response = self.client.get(url, {'feature': 'gender'})
self.assertEqual(response.status_code, 200)
res_json = json.loads(response.content)
self.assertEqual(res_json['feature_results']['data']['m'], 6)
self.assertEqual(res_json['feature_results']['choices_display_names']['m'], 'Male')
self.assertEqual(res_json['feature_results']['data']['no_data'], 0)
self.assertEqual(res_json['feature_results']['choices_display_names']['no_data'], 'No Data')
def test_get_student_progress_url(self):
""" Test that progress_url is in the successful response. """
url = reverse('get_student_progress_url', kwargs={'course_id': self.course.id.to_deprecated_string()})
url += "?unique_student_identifier={}".format(
quote(self.students[0].email.encode("utf-8"))
)
response = self.client.get(url)
self.assertEqual(response.status_code, 200)
res_json = json.loads(response.content)
self.assertIn('progress_url', res_json)
def test_get_student_progress_url_from_uname(self):
""" Test that progress_url is in the successful response. """
url = reverse('get_student_progress_url', kwargs={'course_id': self.course.id.to_deprecated_string()})
url += "?unique_student_identifier={}".format(
quote(self.students[0].username.encode("utf-8"))
)
response = self.client.get(url)
self.assertEqual(response.status_code, 200)
res_json = json.loads(response.content)
self.assertIn('progress_url', res_json)
def test_get_student_progress_url_noparams(self):
""" Test that the endpoint 404's without the required query params. """
url = reverse('get_student_progress_url', kwargs={'course_id': self.course.id.to_deprecated_string()})
response = self.client.get(url)
self.assertEqual(response.status_code, 400)
def test_get_student_progress_url_nostudent(self):
""" Test that the endpoint 400's when requesting an unknown email. """
url = reverse('get_student_progress_url', kwargs={'course_id': self.course.id.to_deprecated_string()})
response = self.client.get(url)
self.assertEqual(response.status_code, 400)
@override_settings(MODULESTORE=TEST_DATA_MOCK_MODULESTORE)
class TestInstructorAPIRegradeTask(ModuleStoreTestCase, LoginEnrollmentTestCase):
"""
Test endpoints whereby instructors can change student grades.
This includes resetting attempts and starting rescore tasks.
This test does NOT test whether the actions had an effect on the
database, that is the job of task tests and test_enrollment.
"""
def setUp(self):
self.course = CourseFactory.create()
self.instructor = InstructorFactory(course_key=self.course.id)
self.client.login(username=self.instructor.username, password='test')
self.student = UserFactory()
CourseEnrollment.enroll(self.student, self.course.id)
self.problem_location = msk_from_problem_urlname(
self.course.id,
'robot-some-problem-urlname'
)
self.problem_urlname = self.problem_location.to_deprecated_string()
self.module_to_reset = StudentModule.objects.create(
student=self.student,
course_id=self.course.id,
module_state_key=self.problem_location,
state=json.dumps({'attempts': 10}),
)
def test_reset_student_attempts_deletall(self):
""" Make sure no one can delete all students state on a problem. """
url = reverse('reset_student_attempts', kwargs={'course_id': self.course.id.to_deprecated_string()})
response = self.client.get(url, {
'problem_to_reset': self.problem_urlname,
'all_students': True,
'delete_module': True,
})
self.assertEqual(response.status_code, 400)
def test_reset_student_attempts_single(self):
""" Test reset single student attempts. """
url = reverse('reset_student_attempts', kwargs={'course_id': self.course.id.to_deprecated_string()})
response = self.client.get(url, {
'problem_to_reset': self.problem_urlname,
'unique_student_identifier': self.student.email,
})
self.assertEqual(response.status_code, 200)
# make sure problem attempts have been reset.
changed_module = StudentModule.objects.get(pk=self.module_to_reset.pk)
self.assertEqual(
json.loads(changed_module.state)['attempts'],
0
)
# mock out the function which should be called to execute the action.
@patch.object(instructor_task.api, 'submit_reset_problem_attempts_for_all_students')
def test_reset_student_attempts_all(self, act):
""" Test reset all student attempts. """
url = reverse('reset_student_attempts', kwargs={'course_id': self.course.id.to_deprecated_string()})
response = self.client.get(url, {
'problem_to_reset': self.problem_urlname,
'all_students': True,
})
self.assertEqual(response.status_code, 200)
self.assertTrue(act.called)
def test_reset_student_attempts_missingmodule(self):
""" Test reset for non-existant problem. """
url = reverse('reset_student_attempts', kwargs={'course_id': self.course.id.to_deprecated_string()})
response = self.client.get(url, {
'problem_to_reset': 'robot-not-a-real-module',
'unique_student_identifier': self.student.email,
})
self.assertEqual(response.status_code, 400)
def test_reset_student_attempts_delete(self):
""" Test delete single student state. """
url = reverse('reset_student_attempts', kwargs={'course_id': self.course.id.to_deprecated_string()})
response = self.client.get(url, {
'problem_to_reset': self.problem_urlname,
'unique_student_identifier': self.student.email,
'delete_module': True,
})
self.assertEqual(response.status_code, 200)
# make sure the module has been deleted
self.assertEqual(
StudentModule.objects.filter(
student=self.module_to_reset.student,
course_id=self.module_to_reset.course_id,
# module_id=self.module_to_reset.module_id,
).count(),
0
)
def test_reset_student_attempts_nonsense(self):
""" Test failure with both unique_student_identifier and all_students. """
url = reverse('reset_student_attempts', kwargs={'course_id': self.course.id.to_deprecated_string()})
response = self.client.get(url, {
'problem_to_reset': self.problem_urlname,
'unique_student_identifier': self.student.email,
'all_students': True,
})
self.assertEqual(response.status_code, 400)
@patch.object(instructor_task.api, 'submit_rescore_problem_for_student')
def test_rescore_problem_single(self, act):
""" Test rescoring of a single student. """
url = reverse('rescore_problem', kwargs={'course_id': self.course.id.to_deprecated_string()})
response = self.client.get(url, {
'problem_to_reset': self.problem_urlname,
'unique_student_identifier': self.student.email,
})
self.assertEqual(response.status_code, 200)
self.assertTrue(act.called)
@patch.object(instructor_task.api, 'submit_rescore_problem_for_student')
def test_rescore_problem_single_from_uname(self, act):
""" Test rescoring of a single student. """
url = reverse('rescore_problem', kwargs={'course_id': self.course.id.to_deprecated_string()})
response = self.client.get(url, {
'problem_to_reset': self.problem_urlname,
'unique_student_identifier': self.student.username,
})
self.assertEqual(response.status_code, 200)
self.assertTrue(act.called)
@patch.object(instructor_task.api, 'submit_rescore_problem_for_all_students')
def test_rescore_problem_all(self, act):
""" Test rescoring for all students. """
url = reverse('rescore_problem', kwargs={'course_id': self.course.id.to_deprecated_string()})
response = self.client.get(url, {
'problem_to_reset': self.problem_urlname,
'all_students': True,
})
self.assertEqual(response.status_code, 200)
self.assertTrue(act.called)
@override_settings(MODULESTORE=TEST_DATA_MOCK_MODULESTORE)
@patch('bulk_email.models.html_to_text', Mock(return_value='Mocking CourseEmail.text_message'))
@patch.dict(settings.FEATURES, {'ENABLE_INSTRUCTOR_EMAIL': True, 'REQUIRE_COURSE_EMAIL_AUTH': False})
class TestInstructorSendEmail(ModuleStoreTestCase, LoginEnrollmentTestCase):
"""
Checks that only instructors have access to email endpoints, and that
these endpoints are only accessible with courses that actually exist,
only with valid email messages.
"""
def setUp(self):
self.course = CourseFactory.create()
self.instructor = InstructorFactory(course_key=self.course.id)
self.client.login(username=self.instructor.username, password='test')
test_subject = u'\u1234 test subject'
test_message = u'\u6824 test message'
self.full_test_message = {
'send_to': 'staff',
'subject': test_subject,
'message': test_message,
}
def test_send_email_as_logged_in_instructor(self):
url = reverse('send_email', kwargs={'course_id': self.course.id.to_deprecated_string()})
response = self.client.post(url, self.full_test_message)
self.assertEqual(response.status_code, 200)
def test_send_email_but_not_logged_in(self):
self.client.logout()
url = reverse('send_email', kwargs={'course_id': self.course.id.to_deprecated_string()})
response = self.client.post(url, self.full_test_message)
self.assertEqual(response.status_code, 403)
def test_send_email_but_not_staff(self):
self.client.logout()
student = UserFactory()
self.client.login(username=student.username, password='test')
url = reverse('send_email', kwargs={'course_id': self.course.id.to_deprecated_string()})
response = self.client.post(url, self.full_test_message)
self.assertEqual(response.status_code, 403)
def test_send_email_but_course_not_exist(self):
url = reverse('send_email', kwargs={'course_id': 'GarbageCourse/DNE/NoTerm'})
response = self.client.post(url, self.full_test_message)
self.assertNotEqual(response.status_code, 200)
def test_send_email_no_sendto(self):
url = reverse('send_email', kwargs={'course_id': self.course.id.to_deprecated_string()})
response = self.client.post(url, {
'subject': 'test subject',
'message': 'test message',
})
self.assertEqual(response.status_code, 400)
def test_send_email_no_subject(self):
url = reverse('send_email', kwargs={'course_id': self.course.id.to_deprecated_string()})
response = self.client.post(url, {
'send_to': 'staff',
'message': 'test message',
})
self.assertEqual(response.status_code, 400)
def test_send_email_no_message(self):
url = reverse('send_email', kwargs={'course_id': self.course.id.to_deprecated_string()})
response = self.client.post(url, {
'send_to': 'staff',
'subject': 'test subject',
})
self.assertEqual(response.status_code, 400)
class MockCompletionInfo(object):
"""Mock for get_task_completion_info"""
times_called = 0
def mock_get_task_completion_info(self, *args): # pylint: disable=unused-argument
"""Mock for get_task_completion_info"""
self.times_called += 1
if self.times_called % 2 == 0:
return True, 'Task Completed'
return False, 'Task Errored In Some Way'
@override_settings(MODULESTORE=TEST_DATA_MOCK_MODULESTORE)
class TestInstructorAPITaskLists(ModuleStoreTestCase, LoginEnrollmentTestCase):
"""
Test instructor task list endpoint.
"""
class FakeTask(object):
""" Fake task object """
FEATURES = [
'task_type',
'task_input',
'task_id',
'requester',
'task_state',
'created',
'status',
'task_message',
'duration_sec'
]
def __init__(self, completion):
for feature in self.FEATURES:
setattr(self, feature, 'expected')
# created needs to be a datetime
self.created = datetime.datetime(2013, 10, 25, 11, 42, 35)
# set 'status' and 'task_message' attrs
success, task_message = completion()
if success:
self.status = "Complete"
else:
self.status = "Incomplete"
self.task_message = task_message
# Set 'task_output' attr, which will be parsed to the 'duration_sec' attr.
self.task_output = '{"duration_ms": 1035000}'
self.duration_sec = 1035000 / 1000.0
def make_invalid_output(self):
"""Munge task_output to be invalid json"""
self.task_output = 'HI MY NAME IS INVALID JSON'
# This should be given the value of 'unknown' if the task output
# can't be properly parsed
self.duration_sec = 'unknown'
def to_dict(self):
""" Convert fake task to dictionary representation. """
attr_dict = {key: getattr(self, key) for key in self.FEATURES}
attr_dict['created'] = attr_dict['created'].isoformat()
return attr_dict
def setUp(self):
self.course = CourseFactory.create()
self.instructor = InstructorFactory(course_key=self.course.id)
self.client.login(username=self.instructor.username, password='test')
self.student = UserFactory()
CourseEnrollment.enroll(self.student, self.course.id)
self.problem_location = msk_from_problem_urlname(
self.course.id,
'robot-some-problem-urlname'
)
self.problem_urlname = self.problem_location.to_deprecated_string()
self.module = StudentModule.objects.create(
student=self.student,
course_id=self.course.id,
module_state_key=self.problem_location,
state=json.dumps({'attempts': 10}),
)
mock_factory = MockCompletionInfo()
self.tasks = [self.FakeTask(mock_factory.mock_get_task_completion_info) for _ in xrange(7)]
self.tasks[-1].make_invalid_output()
def tearDown(self):
"""
Undo all patches.
"""
patch.stopall()
@patch.object(instructor_task.api, 'get_running_instructor_tasks')
def test_list_instructor_tasks_running(self, act):
""" Test list of all running tasks. """
act.return_value = self.tasks
url = reverse('list_instructor_tasks', kwargs={'course_id': self.course.id.to_deprecated_string()})
mock_factory = MockCompletionInfo()
with patch('instructor.views.instructor_task_helpers.get_task_completion_info') as mock_completion_info:
mock_completion_info.side_effect = mock_factory.mock_get_task_completion_info
response = self.client.get(url, {})
self.assertEqual(response.status_code, 200)
# check response
self.assertTrue(act.called)
expected_tasks = [ftask.to_dict() for ftask in self.tasks]
actual_tasks = json.loads(response.content)['tasks']
for exp_task, act_task in zip(expected_tasks, actual_tasks):
self.assertDictEqual(exp_task, act_task)
self.assertEqual(actual_tasks, expected_tasks)
@patch.object(instructor_task.api, 'get_instructor_task_history')
def test_list_background_email_tasks(self, act):
"""Test list of background email tasks."""
act.return_value = self.tasks
url = reverse('list_background_email_tasks', kwargs={'course_id': self.course.id.to_deprecated_string()})
mock_factory = MockCompletionInfo()
with patch('instructor.views.instructor_task_helpers.get_task_completion_info') as mock_completion_info:
mock_completion_info.side_effect = mock_factory.mock_get_task_completion_info
response = self.client.get(url, {})
self.assertEqual(response.status_code, 200)
# check response
self.assertTrue(act.called)
expected_tasks = [ftask.to_dict() for ftask in self.tasks]
actual_tasks = json.loads(response.content)['tasks']
for exp_task, act_task in zip(expected_tasks, actual_tasks):
self.assertDictEqual(exp_task, act_task)
self.assertEqual(actual_tasks, expected_tasks)
@patch.object(instructor_task.api, 'get_instructor_task_history')
def test_list_instructor_tasks_problem(self, act):
""" Test list task history for problem. """
act.return_value = self.tasks
url = reverse('list_instructor_tasks', kwargs={'course_id': self.course.id.to_deprecated_string()})
mock_factory = MockCompletionInfo()
with patch('instructor.views.instructor_task_helpers.get_task_completion_info') as mock_completion_info:
mock_completion_info.side_effect = mock_factory.mock_get_task_completion_info
response = self.client.get(url, {
'problem_location_str': self.problem_urlname,
})
self.assertEqual(response.status_code, 200)
# check response
self.assertTrue(act.called)
expected_tasks = [ftask.to_dict() for ftask in self.tasks]
actual_tasks = json.loads(response.content)['tasks']
for exp_task, act_task in zip(expected_tasks, actual_tasks):
self.assertDictEqual(exp_task, act_task)
self.assertEqual(actual_tasks, expected_tasks)
@patch.object(instructor_task.api, 'get_instructor_task_history')
def test_list_instructor_tasks_problem_student(self, act):
""" Test list task history for problem AND student. """
act.return_value = self.tasks
url = reverse('list_instructor_tasks', kwargs={'course_id': self.course.id.to_deprecated_string()})
mock_factory = MockCompletionInfo()
with patch('instructor.views.instructor_task_helpers.get_task_completion_info') as mock_completion_info:
mock_completion_info.side_effect = mock_factory.mock_get_task_completion_info
response = self.client.get(url, {
'problem_location_str': self.problem_urlname,
'unique_student_identifier': self.student.email,
})
self.assertEqual(response.status_code, 200)
# check response
self.assertTrue(act.called)
expected_tasks = [ftask.to_dict() for ftask in self.tasks]
actual_tasks = json.loads(response.content)['tasks']
for exp_task, act_task in zip(expected_tasks, actual_tasks):
self.assertDictEqual(exp_task, act_task)
self.assertEqual(actual_tasks, expected_tasks)
@override_settings(MODULESTORE=TEST_DATA_MOCK_MODULESTORE)
@patch.object(instructor_task.api, 'get_instructor_task_history')
class TestInstructorEmailContentList(ModuleStoreTestCase, LoginEnrollmentTestCase):
"""
Test the instructor email content history endpoint.
"""
def setUp(self):
self.course = CourseFactory.create()
self.instructor = InstructorFactory(course_key=self.course.id)
self.client.login(username=self.instructor.username, password='test')
self.tasks = {}
self.emails = {}
self.emails_info = {}
def tearDown(self):
"""
Undo all patches.
"""
patch.stopall()
def setup_fake_email_info(self, num_emails, with_failures=False):
""" Initialize the specified number of fake emails """
for email_id in range(num_emails):
num_sent = random.randint(1, 15401)
if with_failures:
failed = random.randint(1, 15401)
else:
failed = 0
self.tasks[email_id] = FakeContentTask(email_id, num_sent, failed, 'expected')
self.emails[email_id] = FakeEmail(email_id)
self.emails_info[email_id] = FakeEmailInfo(self.emails[email_id], num_sent, failed)
def get_matching_mock_email(self, **kwargs):
""" Returns the matching mock emails for the given id """
email_id = kwargs.get('id', 0)
return self.emails[email_id]
def get_email_content_response(self, num_emails, task_history_request, with_failures=False):
""" Calls the list_email_content endpoint and returns the repsonse """
self.setup_fake_email_info(num_emails, with_failures)
task_history_request.return_value = self.tasks.values()
url = reverse('list_email_content', kwargs={'course_id': self.course.id.to_deprecated_string()})
with patch('instructor.views.api.CourseEmail.objects.get') as mock_email_info:
mock_email_info.side_effect = self.get_matching_mock_email
response = self.client.get(url, {})
self.assertEqual(response.status_code, 200)
return response
def check_emails_sent(self, num_emails, task_history_request, with_failures=False):
""" Tests sending emails with or without failures """
response = self.get_email_content_response(num_emails, task_history_request, with_failures)
self.assertTrue(task_history_request.called)
expected_email_info = [email_info.to_dict() for email_info in self.emails_info.values()]
actual_email_info = json.loads(response.content)['emails']
self.assertEqual(len(actual_email_info), num_emails)
for exp_email, act_email in zip(expected_email_info, actual_email_info):
self.assertDictEqual(exp_email, act_email)
self.assertEqual(expected_email_info, actual_email_info)
def test_content_list_one_email(self, task_history_request):
""" Test listing of bulk emails when email list has one email """
response = self.get_email_content_response(1, task_history_request)
self.assertTrue(task_history_request.called)
email_info = json.loads(response.content)['emails']
# Emails list should have one email
self.assertEqual(len(email_info), 1)
# Email content should be what's expected
expected_message = self.emails[0].html_message
returned_email_info = email_info[0]
received_message = returned_email_info[u'email'][u'html_message']
self.assertEqual(expected_message, received_message)
def test_content_list_no_emails(self, task_history_request):
""" Test listing of bulk emails when email list empty """
response = self.get_email_content_response(0, task_history_request)
self.assertTrue(task_history_request.called)
email_info = json.loads(response.content)['emails']
# Emails list should be empty
self.assertEqual(len(email_info), 0)
def test_content_list_email_content_many(self, task_history_request):
""" Test listing of bulk emails sent large amount of emails """
self.check_emails_sent(50, task_history_request)
def test_list_email_content_error(self, task_history_request):
""" Test handling of error retrieving email """
invalid_task = FakeContentTask(0, 0, 0, 'test')
invalid_task.make_invalid_input()
task_history_request.return_value = [invalid_task]
url = reverse('list_email_content', kwargs={'course_id': self.course.id.to_deprecated_string()})
response = self.client.get(url, {})
self.assertEqual(response.status_code, 200)
self.assertTrue(task_history_request.called)
returned_email_info = json.loads(response.content)['emails']
self.assertEqual(len(returned_email_info), 1)
returned_info = returned_email_info[0]
for info in ['created', 'sent_to', 'email', 'number_sent', 'requester']:
self.assertEqual(returned_info[info], None)
def test_list_email_with_failure(self, task_history_request):
""" Test the handling of email task that had failures """
self.check_emails_sent(1, task_history_request, True)
def test_list_many_emails_with_failures(self, task_history_request):
""" Test the handling of many emails with failures """
self.check_emails_sent(50, task_history_request, True)
def test_list_email_with_no_successes(self, task_history_request):
task_info = FakeContentTask(0, 0, 10, 'expected')
email = FakeEmail(0)
email_info = FakeEmailInfo(email, 0, 10)
task_history_request.return_value = [task_info]
url = reverse('list_email_content', kwargs={'course_id': self.course.id.to_deprecated_string()})
with patch('instructor.views.api.CourseEmail.objects.get') as mock_email_info:
mock_email_info.return_value = email
response = self.client.get(url, {})
self.assertEqual(response.status_code, 200)
self.assertTrue(task_history_request.called)
returned_info_list = json.loads(response.content)['emails']
self.assertEqual(len(returned_info_list), 1)
returned_info = returned_info_list[0]
expected_info = email_info.to_dict()
self.assertDictEqual(expected_info, returned_info)
@ddt.ddt
@override_settings(MODULESTORE=TEST_DATA_MOCK_MODULESTORE)
@override_settings(ANALYTICS_SERVER_URL="http://robotanalyticsserver.netbot:900/")
@override_settings(ANALYTICS_API_KEY="robot_api_key")
class TestInstructorAPIAnalyticsProxy(ModuleStoreTestCase, LoginEnrollmentTestCase):
"""
Test instructor analytics proxy endpoint.
"""
class FakeProxyResponse(object):
""" Fake successful requests response object. """
def __init__(self):
self.status_code = requests.status_codes.codes.OK
self.content = '{"test_content": "robot test content"}'
class FakeBadProxyResponse(object):
""" Fake strange-failed requests response object. """
def __init__(self):
self.status_code = 'notok.'
self.content = '{"test_content": "robot test content"}'
def setUp(self):
self.course = CourseFactory.create()
self.instructor = InstructorFactory(course_key=self.course.id)
self.client.login(username=self.instructor.username, password='test')
@ddt.data((ModuleStoreEnum.Type.mongo, False), (ModuleStoreEnum.Type.split, True))
@ddt.unpack
@patch.object(instructor.views.api.requests, 'get')
def test_analytics_proxy_url(self, store_type, assert_wo_encoding, act):
""" Test legacy analytics proxy url generation. """
with modulestore().default_store(store_type):
course = CourseFactory.create()
instructor_local = InstructorFactory(course_key=course.id)
self.client.login(username=instructor_local.username, password='test')
act.return_value = self.FakeProxyResponse()
url = reverse('proxy_legacy_analytics', kwargs={'course_id': course.id.to_deprecated_string()})
response = self.client.get(url, {
'aname': 'ProblemGradeDistribution'
})
self.assertEqual(response.status_code, 200)
# Make request URL pattern - everything but course id.
url_pattern = "{url}get?aname={aname}&course_id={course_id}&apikey={api_key}".format(
url="http://robotanalyticsserver.netbot:900/",
aname="ProblemGradeDistribution",
course_id="{course_id!s}",
api_key="robot_api_key",
)
if assert_wo_encoding:
# Format url with no URL-encoding of parameters.
assert_url = url_pattern.format(course_id=course.id.to_deprecated_string())
with self.assertRaises(AssertionError):
act.assert_called_once_with(assert_url)
# Format url *with* URL-encoding of parameters.
expected_url = url_pattern.format(course_id=quote(course.id.to_deprecated_string()))
act.assert_called_once_with(expected_url)
@override_settings(ANALYTICS_SERVER_URL="")
@patch.object(instructor.views.api.requests, 'get')
def test_analytics_proxy_server_url(self, act):
"""
Test legacy analytics when empty server url.
"""
act.return_value = self.FakeProxyResponse()
url = reverse('proxy_legacy_analytics', kwargs={'course_id': self.course.id.to_deprecated_string()})
response = self.client.get(url, {
'aname': 'ProblemGradeDistribution'
})
self.assertEqual(response.status_code, 501)
@override_settings(ANALYTICS_API_KEY="")
@patch.object(instructor.views.api.requests, 'get')
def test_analytics_proxy_api_key(self, act):
"""
Test legacy analytics when empty server API key.
"""
act.return_value = self.FakeProxyResponse()
url = reverse('proxy_legacy_analytics', kwargs={'course_id': self.course.id.to_deprecated_string()})
response = self.client.get(url, {
'aname': 'ProblemGradeDistribution'
})
self.assertEqual(response.status_code, 501)
@override_settings(ANALYTICS_SERVER_URL="")
@override_settings(ANALYTICS_API_KEY="")
@patch.object(instructor.views.api.requests, 'get')
def test_analytics_proxy_empty_url_and_api_key(self, act):
"""
Test legacy analytics when empty server url & API key.
"""
act.return_value = self.FakeProxyResponse()
url = reverse('proxy_legacy_analytics', kwargs={'course_id': self.course.id.to_deprecated_string()})
response = self.client.get(url, {
'aname': 'ProblemGradeDistribution'
})
self.assertEqual(response.status_code, 501)
@patch.object(instructor.views.api.requests, 'get')
def test_analytics_proxy(self, act):
"""
Test legacy analytics content proxyin, actg.
"""
act.return_value = self.FakeProxyResponse()
url = reverse('proxy_legacy_analytics', kwargs={'course_id': self.course.id.to_deprecated_string()})
response = self.client.get(url, {
'aname': 'ProblemGradeDistribution'
})
self.assertEqual(response.status_code, 200)
# check response
self.assertTrue(act.called)
expected_res = {'test_content': "robot test content"}
self.assertEqual(json.loads(response.content), expected_res)
@patch.object(instructor.views.api.requests, 'get')
def test_analytics_proxy_reqfailed(self, act):
""" Test proxy when server reponds with failure. """
act.return_value = self.FakeBadProxyResponse()
url = reverse('proxy_legacy_analytics', kwargs={'course_id': self.course.id.to_deprecated_string()})
response = self.client.get(url, {
'aname': 'ProblemGradeDistribution'
})
self.assertEqual(response.status_code, 500)
@patch.object(instructor.views.api.requests, 'get')
def test_analytics_proxy_missing_param(self, act):
""" Test proxy when missing the aname query parameter. """
act.return_value = self.FakeProxyResponse()
url = reverse('proxy_legacy_analytics', kwargs={'course_id': self.course.id.to_deprecated_string()})
response = self.client.get(url, {})
self.assertEqual(response.status_code, 400)
self.assertFalse(act.called)
class TestInstructorAPIHelpers(TestCase):
""" Test helpers for instructor.api """
def test_split_input_list(self):
strings = []
lists = []
strings.append(
"Lorem@ipsum.dolor, sit@amet.consectetur\nadipiscing@elit.Aenean\r convallis@at.lacus\r, ut@lacinia.Sed")
lists.append(['Lorem@ipsum.dolor', 'sit@amet.consectetur', 'adipiscing@elit.Aenean', 'convallis@at.lacus',
'ut@lacinia.Sed'])
for (stng, lst) in zip(strings, lists):
self.assertEqual(_split_input_list(stng), lst)
def test_split_input_list_unicode(self):
self.assertEqual(_split_input_list('robot@robot.edu, robot2@robot.edu'),
['robot@robot.edu', 'robot2@robot.edu'])
self.assertEqual(_split_input_list(u'robot@robot.edu, robot2@robot.edu'),
['robot@robot.edu', 'robot2@robot.edu'])
self.assertEqual(_split_input_list(u'robot@robot.edu, robot2@robot.edu'),
[u'robot@robot.edu', 'robot2@robot.edu'])
scary_unistuff = unichr(40960) + u'abcd' + unichr(1972)
self.assertEqual(_split_input_list(scary_unistuff), [scary_unistuff])
def test_msk_from_problem_urlname(self):
course_id = SlashSeparatedCourseKey('MITx', '6.002x', '2013_Spring')
name = 'L2Node1'
output = 'i4x://MITx/6.002x/problem/L2Node1'
self.assertEqual(msk_from_problem_urlname(course_id, name).to_deprecated_string(), output)
@raises(ValueError)
def test_msk_from_problem_urlname_error(self):
args = ('notagoodcourse', 'L2Node1')
msk_from_problem_urlname(*args)
@override_settings(MODULESTORE=TEST_DATA_MOCK_MODULESTORE)
class TestDueDateExtensions(ModuleStoreTestCase, LoginEnrollmentTestCase):
"""
Test data dumps for reporting.
"""
def setUp(self):
"""
Fixtures.
"""
super(TestDueDateExtensions, self).setUp()
due = datetime.datetime(2010, 5, 12, 2, 42, tzinfo=utc)
course = CourseFactory.create()
week1 = ItemFactory.create(due=due)
week2 = ItemFactory.create(due=due)
week3 = ItemFactory.create() # No due date
course.children = [week1.location.to_deprecated_string(), week2.location.to_deprecated_string(),
week3.location.to_deprecated_string()]
homework = ItemFactory.create(
parent_location=week1.location,
due=due
)
week1.children = [homework.location.to_deprecated_string()]
user1 = UserFactory.create()
StudentModule(
state='{}',
student_id=user1.id,
course_id=course.id,
module_state_key=week1.location).save()
StudentModule(
state='{}',
student_id=user1.id,
course_id=course.id,
module_state_key=week2.location).save()
StudentModule(
state='{}',
student_id=user1.id,
course_id=course.id,
module_state_key=week3.location).save()
StudentModule(
state='{}',
student_id=user1.id,
course_id=course.id,
module_state_key=homework.location).save()
user2 = UserFactory.create()
StudentModule(
state='{}',
student_id=user2.id,
course_id=course.id,
module_state_key=week1.location).save()
StudentModule(
state='{}',
student_id=user2.id,
course_id=course.id,
module_state_key=homework.location).save()
user3 = UserFactory.create()
StudentModule(
state='{}',
student_id=user3.id,
course_id=course.id,
module_state_key=week1.location).save()
StudentModule(
state='{}',
student_id=user3.id,
course_id=course.id,
module_state_key=homework.location).save()
self.course = course
self.week1 = week1
self.homework = homework
self.week2 = week2
self.week3 = week3
self.user1 = user1
self.user2 = user2
self.instructor = InstructorFactory(course_key=course.id)
self.client.login(username=self.instructor.username, password='test')
def test_change_due_date(self):
url = reverse('change_due_date', kwargs={'course_id': self.course.id.to_deprecated_string()})
response = self.client.get(url, {
'student': self.user1.username,
'url': self.week1.location.to_deprecated_string(),
'due_datetime': '12/30/2013 00:00'
})
self.assertEqual(response.status_code, 200, response.content)
self.assertEqual(datetime.datetime(2013, 12, 30, 0, 0, tzinfo=utc),
get_extended_due(self.course, self.week1, self.user1))
def test_change_to_invalid_due_date(self):
url = reverse('change_due_date', kwargs={'course_id': self.course.id.to_deprecated_string()})
response = self.client.get(url, {
'student': self.user1.username,
'url': self.week1.location.to_deprecated_string(),
'due_datetime': '01/01/2009 00:00'
})
self.assertEqual(response.status_code, 400, response.content)
self.assertEqual(
None,
get_extended_due(self.course, self.week1, self.user1)
)
def test_change_nonexistent_due_date(self):
url = reverse('change_due_date', kwargs={'course_id': self.course.id.to_deprecated_string()})
response = self.client.get(url, {
'student': self.user1.username,
'url': self.week3.location.to_deprecated_string(),
'due_datetime': '12/30/2013 00:00'
})
self.assertEqual(response.status_code, 400, response.content)
self.assertEqual(
None,
get_extended_due(self.course, self.week3, self.user1)
)
def test_reset_date(self):
self.test_change_due_date()
url = reverse('reset_due_date', kwargs={'course_id': self.course.id.to_deprecated_string()})
response = self.client.get(url, {
'student': self.user1.username,
'url': self.week1.location.to_deprecated_string(),
})
self.assertEqual(response.status_code, 200, response.content)
self.assertEqual(
None,
get_extended_due(self.course, self.week1, self.user1)
)
def test_reset_nonexistent_extension(self):
url = reverse('reset_due_date', kwargs={'course_id': self.course.id.to_deprecated_string()})
response = self.client.get(url, {
'student': self.user1.username,
'url': self.week1.location.to_deprecated_string(),
})
self.assertEqual(response.status_code, 400, response.content)
def test_reset_extension_to_deleted_date(self):
"""
Test that we can delete a due date extension after deleting the normal
due date, without causing an error.
"""
self.test_change_due_date()
self.week1.due = None
self.week1 = self.store.update_item(self.week1, self.user1.id)
# Now, week1's normal due date is deleted but the extension still exists.
url = reverse('reset_due_date', kwargs={'course_id': self.course.id.to_deprecated_string()})
response = self.client.get(url, {
'student': self.user1.username,
'url': self.week1.location.to_deprecated_string(),
})
self.assertEqual(response.status_code, 200, response.content)
self.assertEqual(
None,
get_extended_due(self.course, self.week1, self.user1)
)
def test_show_unit_extensions(self):
self.test_change_due_date()
url = reverse('show_unit_extensions',
kwargs={'course_id': self.course.id.to_deprecated_string()})
response = self.client.get(url, {'url': self.week1.location.to_deprecated_string()})
self.assertEqual(response.status_code, 200, response.content)
self.assertEqual(json.loads(response.content), {
u'data': [{u'Extended Due Date': u'2013-12-30 00:00',
u'Full Name': self.user1.profile.name,
u'Username': self.user1.username}],
u'header': [u'Username', u'Full Name', u'Extended Due Date'],
u'title': u'Users with due date extensions for %s' %
self.week1.display_name})
def test_show_student_extensions(self):
self.test_change_due_date()
url = reverse('show_student_extensions',
kwargs={'course_id': self.course.id.to_deprecated_string()})
response = self.client.get(url, {'student': self.user1.username})
self.assertEqual(response.status_code, 200, response.content)
self.assertEqual(json.loads(response.content), {
u'data': [{u'Extended Due Date': u'2013-12-30 00:00',
u'Unit': self.week1.display_name}],
u'header': [u'Unit', u'Extended Due Date'],
u'title': u'Due date extensions for %s (%s)' % (
self.user1.profile.name, self.user1.username)})
@override_settings(MODULESTORE=TEST_DATA_MOCK_MODULESTORE)
@override_settings(REGISTRATION_CODE_LENGTH=8)
class TestCourseRegistrationCodes(ModuleStoreTestCase):
"""
Test data dumps for E-commerce Course Registration Codes.
"""
def setUp(self):
"""
Fixtures.
"""
self.course = CourseFactory.create()
CourseModeFactory.create(course_id=self.course.id, min_price=50)
self.instructor = InstructorFactory(course_key=self.course.id)
self.client.login(username=self.instructor.username, password='test')
CourseSalesAdminRole(self.course.id).add_users(self.instructor)
url = reverse('generate_registration_codes',
kwargs={'course_id': self.course.id.to_deprecated_string()})
data = {
'total_registration_codes': 12, 'company_name': 'Test Group', 'company_contact_name': 'Test@company.com',
'company_contact_email': 'Test@company.com', 'sale_price': 122.45, 'recipient_name': 'Test123',
'recipient_email': 'test@123.com', 'address_line_1': 'Portland Street',
'address_line_2': '', 'address_line_3': '', 'city': '', 'state': '', 'zip': '', 'country': '',
'customer_reference_number': '123A23F', 'internal_reference': '', 'invoice': ''
}
response = self.client.post(url, data, **{'HTTP_HOST': 'localhost'})
self.assertEqual(response.status_code, 200, response.content)
for i in range(5):
order = Order(user=self.instructor, status='purchased')
order.save()
# Spent(used) Registration Codes
for i in range(5):
i += 1
registration_code_redemption = RegistrationCodeRedemption(
registration_code_id=i,
redeemed_by=self.instructor
)
registration_code_redemption.save()
@override_settings(FINANCE_EMAIL='finance@example.com')
def test_finance_email_in_recipient_list_when_generating_registration_codes(self):
"""
Test to verify that the invoice will also be sent to the FINANCE_EMAIL when
generating registration codes
"""
url_reg_code = reverse('generate_registration_codes',
kwargs={'course_id': self.course.id.to_deprecated_string()})
data = {
'total_registration_codes': 5, 'company_name': 'Group Alpha', 'company_contact_name': 'Test@company.com',
'company_contact_email': 'Test@company.com', 'sale_price': 121.45, 'recipient_name': 'Test123',
'recipient_email': 'test@123.com', 'address_line_1': 'Portland Street', 'address_line_2': '',
'address_line_3': '', 'city': '', 'state': '', 'zip': '', 'country': '',
'customer_reference_number': '123A23F', 'internal_reference': '', 'invoice': 'True'
}
response = self.client.post(url_reg_code, data, **{'HTTP_HOST': 'localhost'})
self.assertEqual(response.status_code, 200, response.content)
self.assertEqual(response['Content-Type'], 'text/csv')
# check for the last mail.outbox, The FINANCE_EMAIL has been appended at the
# very end, when generating registration codes
self.assertEqual(mail.outbox[-1].to[0], 'finance@example.com')
def test_user_invoice_copy_preference(self):
"""
Test to remember user invoice copy preference
"""
url_reg_code = reverse('generate_registration_codes',
kwargs={'course_id': self.course.id.to_deprecated_string()})
data = {
'total_registration_codes': 5, 'company_name': 'Group Alpha', 'company_contact_name': 'Test@company.com',
'company_contact_email': 'Test@company.com', 'sale_price': 121.45, 'recipient_name': 'Test123',
'recipient_email': 'test@123.com', 'address_line_1': 'Portland Street', 'address_line_2': '',
'address_line_3': '', 'city': '', 'state': '', 'zip': '', 'country': '',
'customer_reference_number': '123A23F', 'internal_reference': '', 'invoice': 'True'
}
# user invoice copy preference will be saved in api user preference; model
response = self.client.post(url_reg_code, data, **{'HTTP_HOST': 'localhost'})
self.assertEqual(response.status_code, 200, response.content)
self.assertEqual(response['Content-Type'], 'text/csv')
# get user invoice copy preference.
url_user_invoice_preference = reverse('get_user_invoice_preference',
kwargs={'course_id': self.course.id.to_deprecated_string()})
response = self.client.post(url_user_invoice_preference, data)
result = json.loads(response.content)
self.assertEqual(result['invoice_copy'], True)
# updating the user invoice copy preference during code generation flow
data['invoice'] = ''
response = self.client.post(url_reg_code, data, **{'HTTP_HOST': 'localhost'})
self.assertEqual(response.status_code, 200, response.content)
self.assertEqual(response['Content-Type'], 'text/csv')
# get user invoice copy preference.
url_user_invoice_preference = reverse('get_user_invoice_preference',
kwargs={'course_id': self.course.id.to_deprecated_string()})
response = self.client.post(url_user_invoice_preference, data)
result = json.loads(response.content)
self.assertEqual(result['invoice_copy'], False)
def test_generate_course_registration_codes_csv(self):
"""
Test to generate a response of all the generated course registration codes
"""
url = reverse('generate_registration_codes',
kwargs={'course_id': self.course.id.to_deprecated_string()})
data = {
'total_registration_codes': 15, 'company_name': 'Group Alpha', 'company_contact_name': 'Test@company.com',
'company_contact_email': 'Test@company.com', 'sale_price': 122.45, 'recipient_name': 'Test123',
'recipient_email': 'test@123.com', 'address_line_1': 'Portland Street', 'address_line_2': '',
'address_line_3': '', 'city': '', 'state': '', 'zip': '', 'country': '',
'customer_reference_number': '123A23F', 'internal_reference': '', 'invoice': ''
}
response = self.client.post(url, data, **{'HTTP_HOST': 'localhost'})
self.assertEqual(response.status_code, 200, response.content)
self.assertEqual(response['Content-Type'], 'text/csv')
body = response.content.replace('\r', '')
self.assertTrue(body.startswith(EXPECTED_CSV_HEADER))
self.assertEqual(len(body.split('\n')), 17)
@patch.object(instructor.views.api, 'random_code_generator',
Mock(side_effect=['first', 'second', 'third', 'fourth']))
def test_generate_course_registration_codes_matching_existing_coupon_code(self):
"""
Test the generated course registration code is already in the Coupon Table
"""
url = reverse('generate_registration_codes',
kwargs={'course_id': self.course.id.to_deprecated_string()})
coupon = Coupon(code='first', course_id=self.course.id.to_deprecated_string(), created_by=self.instructor)
coupon.save()
data = {
'total_registration_codes': 3, 'company_name': 'Group Alpha', 'company_contact_name': 'Test@company.com',
'company_contact_email': 'Test@company.com', 'sale_price': 122.45, 'recipient_name': 'Test123',
'recipient_email': 'test@123.com', 'address_line_1': 'Portland Street', 'address_line_2': '',
'address_line_3': '', 'city': '', 'state': '', 'zip': '', 'country': '',
'customer_reference_number': '123A23F', 'internal_reference': '', 'invoice': ''
}
response = self.client.post(url, data, **{'HTTP_HOST': 'localhost'})
self.assertEqual(response.status_code, 200, response.content)
self.assertEqual(response['Content-Type'], 'text/csv')
body = response.content.replace('\r', '')
self.assertTrue(body.startswith(EXPECTED_CSV_HEADER))
self.assertEqual(len(body.split('\n')), 5) # 1 for headers, 1 for new line at the end and 3 for the actual data
@patch.object(instructor.views.api, 'random_code_generator',
Mock(side_effect=['first', 'first', 'second', 'third']))
def test_generate_course_registration_codes_integrity_error(self):
"""
Test for the Integrity error against the generated code
"""
url = reverse('generate_registration_codes',
kwargs={'course_id': self.course.id.to_deprecated_string()})
data = {
'total_registration_codes': 2, 'company_name': 'Test Group', 'company_contact_name': 'Test@company.com',
'company_contact_email': 'Test@company.com', 'sale_price': 122.45, 'recipient_name': 'Test123',
'recipient_email': 'test@123.com', 'address_line_1': 'Portland Street', 'address_line_2': '',
'address_line_3': '', 'city': '', 'state': '', 'zip': '', 'country': '',
'customer_reference_number': '123A23F', 'internal_reference': '', 'invoice': ''
}
response = self.client.post(url, data, **{'HTTP_HOST': 'localhost'})
self.assertEqual(response.status_code, 200, response.content)
self.assertEqual(response['Content-Type'], 'text/csv')
body = response.content.replace('\r', '')
self.assertTrue(body.startswith(EXPECTED_CSV_HEADER))
self.assertEqual(len(body.split('\n')), 4)
def test_spent_course_registration_codes_csv(self):
"""
Test to generate a response of all the spent course registration codes
"""
url = reverse('spent_registration_codes',
kwargs={'course_id': self.course.id.to_deprecated_string()})
data = {'spent_company_name': ''}
response = self.client.post(url, data)
self.assertEqual(response.status_code, 200, response.content)
self.assertEqual(response['Content-Type'], 'text/csv')
body = response.content.replace('\r', '')
self.assertTrue(body.startswith(EXPECTED_CSV_HEADER))
self.assertEqual(len(body.split('\n')), 7)
generate_code_url = reverse(
'generate_registration_codes', kwargs={'course_id': self.course.id.to_deprecated_string()}
)
data = {
'total_registration_codes': 9, 'company_name': 'Group Alpha', 'company_contact_name': 'Test@company.com',
'sale_price': 122.45, 'company_contact_email': 'Test@company.com', 'recipient_name': 'Test123',
'recipient_email': 'test@123.com', 'address_line_1': 'Portland Street', 'address_line_2': '',
'address_line_3': '', 'city': '', 'state': '', 'zip': '', 'country': '',
'customer_reference_number': '123A23F', 'internal_reference': '', 'invoice': ''
}
response = self.client.post(generate_code_url, data, **{'HTTP_HOST': 'localhost'})
self.assertEqual(response.status_code, 200, response.content)
for i in range(9):
order = Order(user=self.instructor, status='purchased')
order.save()
# Spent(used) Registration Codes
for i in range(9):
i += 13
registration_code_redemption = RegistrationCodeRedemption(
registration_code_id=i,
redeemed_by=self.instructor
)
registration_code_redemption.save()
data = {'spent_company_name': 'Group Alpha'}
response = self.client.post(url, data)
self.assertEqual(response.status_code, 200, response.content)
self.assertEqual(response['Content-Type'], 'text/csv')
body = response.content.replace('\r', '')
self.assertTrue(body.startswith(EXPECTED_CSV_HEADER))
self.assertEqual(len(body.split('\n')), 11)
def test_active_course_registration_codes_csv(self):
"""
Test to generate a response of all the active course registration codes
"""
url = reverse('active_registration_codes',
kwargs={'course_id': self.course.id.to_deprecated_string()})
data = {'active_company_name': ''}
response = self.client.post(url, data)
self.assertEqual(response.status_code, 200, response.content)
self.assertEqual(response['Content-Type'], 'text/csv')
body = response.content.replace('\r', '')
self.assertTrue(body.startswith(EXPECTED_CSV_HEADER))
self.assertEqual(len(body.split('\n')), 9)
generate_code_url = reverse(
'generate_registration_codes', kwargs={'course_id': self.course.id.to_deprecated_string()}
)
data = {
'total_registration_codes': 9, 'company_name': 'Group Alpha', 'company_contact_name': 'Test@company.com',
'company_contact_email': 'Test@company.com', 'sale_price': 122.45, 'recipient_name': 'Test123',
'recipient_email': 'test@123.com', 'address_line_1': 'Portland Street', 'address_line_2': '',
'address_line_3': '', 'city': '', 'state': '', 'zip': '', 'country': '',
'customer_reference_number': '123A23F', 'internal_reference': '', 'invoice': ''
}
response = self.client.post(generate_code_url, data, **{'HTTP_HOST': 'localhost'})
self.assertEqual(response.status_code, 200, response.content)
data = {'active_company_name': 'Group Alpha'}
response = self.client.post(url, data)
self.assertEqual(response.status_code, 200, response.content)
self.assertEqual(response['Content-Type'], 'text/csv')
body = response.content.replace('\r', '')
self.assertTrue(body.startswith(EXPECTED_CSV_HEADER))
self.assertEqual(len(body.split('\n')), 11)
def test_get_all_course_registration_codes_csv(self):
"""
Test to generate a response of all the course registration codes
"""
url = reverse(
'get_registration_codes', kwargs={'course_id': self.course.id.to_deprecated_string()}
)
data = {'download_company_name': ''}
response = self.client.post(url, data)
self.assertEqual(response.status_code, 200, response.content)
self.assertEqual(response['Content-Type'], 'text/csv')
body = response.content.replace('\r', '')
self.assertTrue(body.startswith(EXPECTED_CSV_HEADER))
self.assertEqual(len(body.split('\n')), 14)
generate_code_url = reverse(
'generate_registration_codes', kwargs={'course_id': self.course.id.to_deprecated_string()}
)
data = {
'total_registration_codes': 9, 'company_name': 'Group Alpha', 'company_contact_name': 'Test@company.com',
'company_contact_email': 'Test@company.com', 'sale_price': 122.45, 'recipient_name': 'Test123',
'recipient_email': 'test@123.com', 'address_line_1': 'Portland Street', 'address_line_2': '',
'address_line_3': '', 'city': '', 'state': '', 'zip': '', 'country': '',
'customer_reference_number': '123A23F', 'internal_reference': '', 'invoice': ''
}
response = self.client.post(generate_code_url, data, **{'HTTP_HOST': 'localhost'})
self.assertEqual(response.status_code, 200, response.content)
data = {'download_company_name': 'Group Alpha'}
response = self.client.post(url, data)
self.assertEqual(response.status_code, 200, response.content)
self.assertEqual(response['Content-Type'], 'text/csv')
body = response.content.replace('\r', '')
self.assertTrue(body.startswith(EXPECTED_CSV_HEADER))
self.assertEqual(len(body.split('\n')), 11)
def test_pdf_file_throws_exception(self):
"""
test to mock the pdf file generation throws an exception
when generating registration codes.
"""
generate_code_url = reverse(
'generate_registration_codes', kwargs={'course_id': self.course.id.to_deprecated_string()}
)
data = {
'total_registration_codes': 9, 'company_name': 'Group Alpha', 'company_contact_name': 'Test@company.com',
'company_contact_email': 'Test@company.com', 'sale_price': 122.45, 'recipient_name': 'Test123',
'recipient_email': 'test@123.com', 'address_line_1': 'Portland Street', 'address_line_2': '',
'address_line_3': '', 'city': '', 'state': '', 'zip': '', 'country': '',
'customer_reference_number': '123A23F', 'internal_reference': '', 'invoice': ''
}
with patch.object(PDFInvoice, 'generate_pdf', side_effect=Exception):
response = self.client.post(generate_code_url, data)
self.assertEqual(response.status_code, 200, response.content)
def test_get_codes_with_sale_invoice(self):
"""
Test to generate a response of all the course registration codes
"""
generate_code_url = reverse(
'generate_registration_codes', kwargs={'course_id': self.course.id.to_deprecated_string()}
)
data = {
'total_registration_codes': 5.5, 'company_name': 'Group Invoice', 'company_contact_name': 'Test@company.com',
'company_contact_email': 'Test@company.com', 'sale_price': 122.45, 'recipient_name': 'Test123',
'recipient_email': 'test@123.com', 'address_line_1': 'Portland Street', 'address_line_2': '',
'address_line_3': '', 'city': '', 'state': '', 'zip': '', 'country': '',
'customer_reference_number': '123A23F', 'internal_reference': '', 'invoice': True
}
response = self.client.post(generate_code_url, data, **{'HTTP_HOST': 'localhost'})
self.assertEqual(response.status_code, 200, response.content)
url = reverse('get_registration_codes',
kwargs={'course_id': self.course.id.to_deprecated_string()})
data = {'download_company_name': 'Group Invoice'}
response = self.client.post(url, data)
self.assertEqual(response.status_code, 200, response.content)
self.assertEqual(response['Content-Type'], 'text/csv')
body = response.content.replace('\r', '')
self.assertTrue(body.startswith(EXPECTED_CSV_HEADER))
def test_get_historical_coupon_codes(self):
"""
Test to download a response of all the active coupon codes
"""
get_coupon_code_url = reverse(
'get_coupon_codes', kwargs={'course_id': self.course.id.to_deprecated_string()}
)
for i in range(10):
coupon = Coupon(
code='test_code{0}'.format(i), description='test_description', course_id=self.course.id,
percentage_discount='{0}'.format(i), created_by=self.instructor, is_active=True
)
coupon.save()
#now create coupons with the expiration dates
for i in range(5):
coupon = Coupon(
code='coupon{0}'.format(i), description='test_description', course_id=self.course.id,
percentage_discount='{0}'.format(i), created_by=self.instructor, is_active=True,
expiration_date=datetime.datetime.now(pytz.UTC) + datetime.timedelta(days=2)
)
coupon.save()
response = self.client.get(get_coupon_code_url)
self.assertEqual(response.status_code, 200, response.content)
# filter all the coupons
for coupon in Coupon.objects.all():
self.assertIn('"{code}","{course_id}","{discount}","0","{description}","{expiration_date}"'.format(
code=coupon.code,
course_id=coupon.course_id,
discount=coupon.percentage_discount,
description=coupon.description,
expiration_date=coupon.display_expiry_date
), response.content)
self.assertEqual(response['Content-Type'], 'text/csv')
body = response.content.replace('\r', '')
self.assertTrue(body.startswith(EXPECTED_COUPON_CSV_HEADER))
@override_settings(MODULESTORE=TEST_DATA_MOCK_MODULESTORE)
class TestBulkCohorting(ModuleStoreTestCase):
"""
Test adding users to cohorts in bulk via CSV upload.
"""
def setUp(self):
super(TestBulkCohorting, self).setUp()
self.course = CourseFactory.create()
self.staff_user = StaffFactory(course_key=self.course.id)
self.non_staff_user = UserFactory.create()
self.tempdir = tempfile.mkdtemp()
def tearDown(self):
if os.path.exists(self.tempdir):
shutil.rmtree(self.tempdir)
def call_add_users_to_cohorts(self, csv_data, suffix='.csv', method='POST'):
"""
Call `add_users_to_cohorts` with a file generated from `csv_data`.
"""
# this temporary file will be removed in `self.tearDown()`
__, file_name = tempfile.mkstemp(suffix=suffix, dir=self.tempdir)
with open(file_name, 'w') as file_pointer:
file_pointer.write(csv_data.encode('utf-8'))
with open(file_name, 'r') as file_pointer:
url = reverse('add_users_to_cohorts', kwargs={'course_id': unicode(self.course.id)})
if method == 'POST':
return self.client.post(url, {'uploaded-file': file_pointer})
elif method == 'GET':
return self.client.get(url, {'uploaded-file': file_pointer})
def expect_error_on_file_content(self, file_content, error, file_suffix='.csv'):
"""
Verify that we get the error we expect for a given file input.
"""
self.client.login(username=self.staff_user.username, password='test')
response = self.call_add_users_to_cohorts(file_content, suffix=file_suffix)
self.assertEqual(response.status_code, 400)
result = json.loads(response.content)
self.assertEqual(result['error'], error)
def verify_success_on_file_content(self, file_content, mock_store_upload, mock_cohort_task):
"""
Verify that `addd_users_to_cohorts` successfully validates the
file content, uploads the input file, and triggers the
background task.
"""
mock_store_upload.return_value = (None, 'fake_file_name.csv')
self.client.login(username=self.staff_user.username, password='test')
response = self.call_add_users_to_cohorts(file_content)
self.assertEqual(response.status_code, 204)
self.assertTrue(mock_store_upload.called)
self.assertTrue(mock_cohort_task.called)
def test_no_cohort_field(self):
"""
Verify that we get a descriptive verification error when we haven't
included a cohort field in the uploaded CSV.
"""
self.expect_error_on_file_content(
'username,email\n', "The file must contain a 'cohort' column containing cohort names."
)
def test_no_username_or_email_field(self):
"""
Verify that we get a descriptive verification error when we haven't
included a username or email field in the uploaded CSV.
"""
self.expect_error_on_file_content(
'cohort\n', "The file must contain a 'username' column, an 'email' column, or both."
)
def test_empty_csv(self):
"""
Verify that we get a descriptive verification error when we haven't
included any data in the uploaded CSV.
"""
self.expect_error_on_file_content(
'', "The file must contain a 'cohort' column containing cohort names."
)
def test_wrong_extension(self):
"""
Verify that we get a descriptive verification error when we haven't
uploaded a file with a '.csv' extension.
"""
self.expect_error_on_file_content(
'', "The file must end with the extension '.csv'.", file_suffix='.notcsv'
)
def test_non_staff_no_access(self):
"""
Verify that we can't access the view when we aren't a staff user.
"""
self.client.login(username=self.non_staff_user.username, password='test')
response = self.call_add_users_to_cohorts('')
self.assertEqual(response.status_code, 403)
def test_post_only(self):
"""
Verify that we can't call the view when we aren't using POST.
"""
self.client.login(username=self.staff_user.username, password='test')
response = self.call_add_users_to_cohorts('', method='GET')
self.assertEqual(response.status_code, 405)
@patch('instructor.views.api.instructor_task.api.submit_cohort_students')
@patch('instructor.views.api.store_uploaded_file')
def test_success_username(self, mock_store_upload, mock_cohort_task):
"""
Verify that we store the input CSV and call a background task when
the CSV has username and cohort columns.
"""
self.verify_success_on_file_content(
'username,cohort\nfoo_username,bar_cohort', mock_store_upload, mock_cohort_task
)
@patch('instructor.views.api.instructor_task.api.submit_cohort_students')
@patch('instructor.views.api.store_uploaded_file')
def test_success_email(self, mock_store_upload, mock_cohort_task):
"""
Verify that we store the input CSV and call the cohorting background
task when the CSV has email and cohort columns.
"""
self.verify_success_on_file_content(
'email,cohort\nfoo_email,bar_cohort', mock_store_upload, mock_cohort_task
)
@patch('instructor.views.api.instructor_task.api.submit_cohort_students')
@patch('instructor.views.api.store_uploaded_file')
def test_success_username_and_email(self, mock_store_upload, mock_cohort_task):
"""
Verify that we store the input CSV and call the cohorting background
task when the CSV has username, email and cohort columns.
"""
self.verify_success_on_file_content(
'username,email,cohort\nfoo_username,bar_email,baz_cohort', mock_store_upload, mock_cohort_task
)
@patch('instructor.views.api.instructor_task.api.submit_cohort_students')
@patch('instructor.views.api.store_uploaded_file')
def test_success_carriage_return(self, mock_store_upload, mock_cohort_task):
"""
Verify that we store the input CSV and call the cohorting background
task when lines in the CSV are delimited by carriage returns.
"""
self.verify_success_on_file_content(
'username,email,cohort\rfoo_username,bar_email,baz_cohort', mock_store_upload, mock_cohort_task
)
@patch('instructor.views.api.instructor_task.api.submit_cohort_students')
@patch('instructor.views.api.store_uploaded_file')
def test_success_carriage_return_line_feed(self, mock_store_upload, mock_cohort_task):
"""
Verify that we store the input CSV and call the cohorting background
task when lines in the CSV are delimited by carriage returns and line
feeds.
"""
self.verify_success_on_file_content(
'username,email,cohort\r\nfoo_username,bar_email,baz_cohort', mock_store_upload, mock_cohort_task
)
|
olexiim/edx-platform
|
lms/djangoapps/instructor/tests/test_api.py
|
Python
|
agpl-3.0
| 162,006
|
[
"VisIt"
] |
2599470907850615b7a61d1a67ff946cf593da226c07bba01863d83e72ae8d2e
|
#!/usr/bin/env python
import os
import sys
import subprocess as sp
import argparse
if sys.version_info.major == 3:
PY3 = True
from urllib.request import urlretrieve
else:
PY3 = True
from urllib import urlretrieve
usage = """
The easy way to test recipes is by using `circleci build`. However this does
not allow local testing recipes using mulled-build (due to the technicalities
of running docker within docker and the CircleCI client).
This script makes it easy to do mulled-build tests. It works by using the same
code used in the .circleci/setup.sh script to build an isolated Miniconda
environment and a custom `activate` script.
Set up the environment like this:
./bootstrap.py /tmp/miniconda
It creates an activate script at ~/.config/bioconda/activate. So you can then use:
source ~/.config/bioconda/activate
and then use that isolated root environment independent of any other conda
installations you might have.
"""
ap = argparse.ArgumentParser(usage)
ap.add_argument('bootstrap', help='''Location to which a new Miniconda
installation plus bioconda-utils should be installed. This will
be separate from any existing conda installations.''')
ap.add_argument('--no-docker', action='store_true', help='''By default we
expect Docker to be present. Use this arg to disable that
behavior. This will reduce functionality, but is useful if
you're unable to install docker.''')
args = ap.parse_args()
# This is the "common" step in the CircleCI config which gets the versions of
# Miniconda and bioconda-utils that we're using.
urlretrieve(
'https://raw.githubusercontent.com/bioconda/bioconda-common/master/common.sh',
filename='.circleci/common.sh')
# TODO: this mimics the override in the "common" job in .circleci/config.yaml
with open('.circleci/common.sh', 'w') as fout:
fout.write("MINICONDA_VER=4.5.4\nBIOCONDA_UTILS_TAG=master\n")
local_config_path = os.path.expanduser('~/.config/bioconda/activate')
def _write_custom_activate(install_path):
"""
Once the isolated Miniconda version has been installed, copy its activate
script over to a custom location, and then hard-code the paths and PS1. We
don't need a matching `deactivate` because the activate script properly
keeps track of the new location.
"""
config_dir = os.path.dirname(local_config_path)
if not os.path.exists(config_dir):
os.makedirs(config_dir)
activate = os.path.join(install_path, 'miniconda/bin/activate')
lines = [i.rstrip() for i in open(activate)]
# The following is code from cb2; disabling but keeping it around for now:
if 0:
# Exact matches to lines we want to replace in the activate script, leading
# space included.
substitutions = [
(
'_CONDA_DIR=$(dirname "$_SCRIPT_LOCATION")',
'_CONDA_DIR="{0}/miniconda/bin"'.format(install_path)
),
(
' export PS1="(${CONDA_DEFAULT_ENV}) $PS1"',
' export PS1="(BIOCONDA-UTILS) $PS1"',
)
]
for orig, sub in substitutions:
# Be very picky so that we'll know if/when the activate script changes.
try:
pos = lines.index(orig)
except ValueError:
raise ValueError(
"Expecting '{0}' to be in {1} but couldn't find it"
.format(orig, activate)
)
lines[pos] = sub
with open(local_config_path, 'w') as fout:
for line in lines:
fout.write(line + '\n')
use_docker = "true"
if args.no_docker:
use_docker = "false"
env = {
'WORKSPACE': args.bootstrap,
'BOOTSTRAP': "true",
'USE_DOCKER': use_docker,
'PATH': os.environ.get('PATH', ""),
'HTTPS_PROXY': os.environ.get('HTTPS_PROXY', ""),
'https_proxy': os.environ.get('https_proxy', "")
}
sp.check_call(['.circleci/setup.sh'], env=env)
_write_custom_activate(args.bootstrap)
print("""
An isolated version of bioconda-utils has been installed to {1}. This is
separate from any other conda installations you might have.
To use it, source this custom activate script:
source ~/.config/bioconda/activate
When done:
source deactivate
""")
|
zachcp/bioconda-recipes
|
bootstrap.py
|
Python
|
mit
| 4,380
|
[
"Bioconda"
] |
70503e2c043753c448b35a76aa8b5f161d943c2d2a97d17ded9f6f95da166ca9
|
# Functionality exposed as an API
# Author: Evgeny Blokhin
__version__ = "0.8.0"
import os, sys
import re
from fractions import gcd
import inspect
import traceback
import datetime
import importlib
from functools import reduce
from numpy import dot, array
from tilde.core.common import u, is_binary_string, generate_cif, html_formula, hrsize
from tilde.core.symmetry import SymmetryHandler
from tilde.core.settings import BASE_DIR, settings, virtualize_path, get_hierarchy
from tilde.core.electron_structure import ElectronStructureError
from tilde.parsers import Output
import tilde.core.model as model
from ase.data import chemical_symbols
from ase.geometry import cell_to_cellpar
from sqlalchemy import exists, func
from sqlalchemy.orm.exc import NoResultFound
import ujson as json
import six
class API:
version = __version__
__shared_state = {}
formula_sequence = ['Fr','Cs','Rb','K','Na','Li', 'Be','Mg','Ca','Sr','Ba','Ra', 'Sc','Y','La','Ce','Pr','Nd','Pm','Sm','Eu','Gd','Tb','Dy','Ho','Er','Tm','Yb', 'Ac','Th','Pa','U','Np','Pu', 'Ti','Zr','Hf', 'V','Nb','Ta', 'Cr','Mo','W', 'Fe','Ru','Os', 'Co','Rh','Ir', 'Mn','Tc','Re', 'Ni','Pd','Pt', 'Cu','Ag','Au', 'Zn','Cd','Hg', 'B','Al','Ga','In','Tl', 'Pb','Sn','Ge','Si','C', 'N','P','As','Sb','Bi', 'H', 'Po','Te','Se','S','O', 'At','I','Br','Cl','F', 'He','Ne','Ar','Kr','Xe','Rn']
def __init__(self, settings=settings):
self.settings = settings
# Default hierarchy is set in the file init-data.sql
# Conventionally, the hierarchy values are set by hexadecimal numbers (with leading 0x)
self.hierarchy, self.hierarchy_groups, self.hierarchy_values = get_hierarchy(settings)
# *parser API*
# Subfolder "parsers" contains directories with parsers.
# Parser will be active if:
# (1) its class defines a fingerprints method
# (2) it is enabled by its manifest file
# (3) its filename repeats the name of parser folder
All_parsers, self.Parsers = {}, {}
for parsername in os.listdir( os.path.realpath(BASE_DIR + '/../parsers') ):
if self.settings.get('no_parse'): continue
if not os.path.isfile( os.path.realpath(BASE_DIR + '/../parsers') + '/' + parsername + '/manifest.json' ): continue
if not os.path.isfile( os.path.realpath(BASE_DIR + '/../parsers') + '/' + parsername + '/' + parsername + '.py' ):
raise RuntimeError('Parser API Error: Parser code for ' + parsername + ' is missing!')
try: parsermanifest = json.loads( open( os.path.realpath(BASE_DIR + '/../parsers') + '/' + parsername + '/manifest.json' ).read() )
except: raise RuntimeError('Parser API Error: Parser manifest for ' + parsername + ' has corrupted format!')
if (not 'enabled' in parsermanifest or not parsermanifest['enabled']) and not self.settings['debug_regime']: continue
All_parsers[parsername] = importlib.import_module('tilde.parsers.' + parsername + '.' + parsername) # all imported modules will be stored here
# replace modules by classes and check *fingerprints* method
for parser, module in All_parsers.items():
for name, cls in inspect.getmembers(module):
if inspect.isclass(cls):
if inspect.isclass(cls) and hasattr(cls, 'fingerprints'):
self.Parsers[cls.__name__] = cls
# *module API*
# Tilde module (app) is a subfolder (%appfolder%) of apps folder
# contains manifest.json and %appfolder%.py files
# the following tags in manifest.json matter:
# ((*onprocess* - invoking during processing: therefore %appfolder%.py must provide the class %Appfolder%))
# *appcaption* - module caption (used as column caption in GUI data table & as atomic structure rendering pane overlay caption)
# *appdata* - a new property defined by app
# *apptarget* - conditions on whether an app should be executed, based on hierarchy values
# *on3d* - app provides the data which may be shown in GUI on atomic structure rendering pane (used only by make3d of daemon.py)
# *plottable* - column provided may be plotted in GUI
# NB. GUI (has_column) is supported only if the class %Appfolder% defines cell_wrapper
self.Apps = {}
n = 1
for appname in os.listdir( os.path.realpath(BASE_DIR + '/../apps') ):
if self.settings.get('no_parse'): continue
if os.path.isfile( os.path.realpath(BASE_DIR + '/../apps') + '/' + appname + '/manifest.json' ):
try: appmanifest = json.loads( open( os.path.realpath(BASE_DIR + '/../apps') + '/' + appname + '/manifest.json' ).read() )
except: raise RuntimeError('Module API Error: Module manifest for ' + appname + ' has corrupted format!')
# tags processing
if not 'appdata' in appmanifest: raise RuntimeError('Module API Error: no appdata tag for ' + appname + '!')
if 'onprocess' in appmanifest:
try: app = __import__('tilde.apps.' + appname + '.' + appname, fromlist=[appname.capitalize()]) # this means: from foo import Foo
except ImportError:
raise RuntimeError('Module API Error: module ' + appname + ' is invalid or not found!')
self.Apps[appname] = {'appmodule': getattr(app, appname.capitalize()), 'appdata': appmanifest['appdata'], 'apptarget': appmanifest.get('apptarget', None), 'appcaption': appmanifest['appcaption'], 'on3d': appmanifest.get('on3d', 0)}
# compiling table columns:
if hasattr(self.Apps[appname]['appmodule'], 'cell_wrapper'):
self.hierarchy.append( {'cid': (2000+n), 'category': appmanifest['appcaption'], 'sort': (2000+n), 'has_column': True, 'cell_wrapper': getattr(self.Apps[appname]['appmodule'], 'cell_wrapper')} )
if appmanifest.get('plottable', False): self.hierarchy[-1].update({'plottable': 1})
n += 1
self.hierarchy = sorted( self.hierarchy, key=lambda x: x['sort'] )
# *connector API*
# Every connector implements reading methods:
# *list* (if applicable) and *report* (obligatory)
self.Conns = {}
for connectname in os.listdir( os.path.realpath(BASE_DIR + '/../connectors') ):
if connectname.endswith('.py') and connectname != '__init__.py':
connectname = connectname[0:-3]
conn = importlib.import_module('tilde.connectors.' + connectname) # this means: from foo import Foo
self.Conns[connectname] = {'list': getattr(conn, 'list'), 'report': getattr(conn, 'report')}
# *hierarchy API*
# This is used for classification
self.Classifiers = []
for classifier in os.listdir( os.path.realpath(BASE_DIR + '/../classifiers') ):
if self.settings.get('no_parse'): continue
if classifier.endswith('.py') and classifier != '__init__.py':
classifier = classifier[0:-3]
obj = importlib.import_module('tilde.classifiers.' + classifier) # this means: from foo import Foo
if getattr(obj, '__order__') is None: raise RuntimeError('Classifier %s has not defined an order to apply!' % classifier)
self.Classifiers.append({
'classify': getattr(obj, 'classify'),\
'order': getattr(obj, '__order__'),\
'class': classifier})
self.Classifiers = sorted(self.Classifiers, key = lambda x: x['order'])
def assign_parser(self, name):
'''
Restricts parsing
**name** is a name of the parser class
NB: this is the PUBLIC method
@procedure
'''
for n, p in list(self.Parsers.items()):
if n != name:
del self.Parsers[n]
if len(self.Parsers) != 1: raise RuntimeError('Parser cannot be assigned!')
def formula(self, atom_sequence):
'''
Constructs standardized chemical formula
NB: this is the PUBLIC method
@returns formula_str
'''
labels = {}
types = []
y = 0
for k, atomi in enumerate(atom_sequence):
lbl = re.sub("[0-9]+", "", atomi).capitalize()
if lbl not in labels:
labels[lbl] = y
types.append([k+1])
y += 1
else:
types[ labels[lbl] ].append(k+1)
atoms = list(labels.keys())
atoms = [x for x in self.formula_sequence if x in atoms] + [x for x in atoms if x not in self.formula_sequence] # accordingly
formula = ''
for atom in atoms:
n = len(types[labels[atom]])
if n==1: n = ''
else: n = str(n)
formula += atom + n
return formula
def count(self, session):
return session.query(func.count(model.Calculation.checksum)).one()[0]
def savvyize(self, input_string, recursive=False, stemma=False):
'''
Determines which files should be processed
NB: this is the PUBLIC method
@returns filenames_list
'''
input_string = os.path.abspath(input_string)
tasks = []
restricted = [ symbol for symbol in self.settings['skip_if_path'] ] if self.settings['skip_if_path'] else []
# given folder
if os.path.isdir(input_string):
if recursive:
for root, dirs, files in os.walk(input_string): # beware of broken links on unix! (NB find ~ -type l -exec rm -f {} \;)
# skip_if_path directive
to_filter = []
for dir in dirs:
dir = u(dir)
for rs in restricted:
if dir.startswith(rs) or dir.endswith(rs):
to_filter.append(dir)
break
dirs[:] = [x for x in dirs if x not in to_filter]
for filename in files:
# skip_if_path directive
filename = u(filename)
if restricted:
for rs in restricted:
if filename.startswith(rs) or filename.endswith(rs): break
else: tasks.append(root + os.sep + filename)
else: tasks.append(root + os.sep + filename)
else:
for filename in os.listdir(input_string):
filename = u(filename)
if os.path.isfile(input_string + os.sep + filename):
# skip_if_path directive
if restricted:
for rs in restricted:
if filename.startswith(rs) or filename.endswith(rs): break
else: tasks.append(input_string + os.sep + filename)
else: tasks.append(input_string + os.sep + filename)
# given full filename
elif os.path.isfile(input_string):
tasks.append(input_string) # skip_if_path directive is not applicable here
# given filename stemma
else:
if stemma:
parent = os.path.dirname(input_string)
for filename in os.listdir(parent):
filename = u(filename)
if input_string in parent + os.sep + filename and not os.path.isdir(parent + os.sep + filename):
# skip_if_path directive
if restricted:
for rs in restricted:
if filename.startswith(rs) or filename.endswith(rs): break
else: tasks.append(parent + os.sep + filename)
else: tasks.append(parent + os.sep + filename)
return tasks
def _parse(self, parsable, parser_name):
'''
Low-level parsing
NB: this is the PRIVATE method
@returns tilde_obj, error
'''
calc, error = None, None
try:
for calc in self.Parsers[parser_name].iparse(parsable):
yield calc, None
return
except RuntimeError as e: error = "routine %s parser error in %s: %s" % ( parser_name, parsable, e )
except:
exc_type, exc_value, exc_tb = sys.exc_info()
error = "unexpected %s parser error in %s:\n %s" % ( parser_name, parsable, "".join(traceback.format_exception( exc_type, exc_value, exc_tb )) )
yield None, error
def parse(self, parsable):
'''
High-level parsing:
determines the data format
and combines parent-children outputs
NB: this is the PUBLIC method
@returns tilde_obj, error
'''
calc, error = None, None
try:
f = open(parsable, 'rb')
if is_binary_string(f.read(2048)):
yield None, 'was read (binary data)...'
return
f.close()
except IOError:
yield None, 'read error!'
return
f = open(parsable, 'r', errors='surrogateescape') if six.PY3 else open(parsable, 'r') # open the file once again with right mode
f.seek(0)
i, detected = 0, False
while not detected:
if i>700: break # criterion: parser must detect its working format in first N lines of output
fingerprint = f.readline()
if not fingerprint: break
for name, Parser in self.Parsers.items():
if Parser.fingerprints(fingerprint):
for calc, error in self._parse(parsable, name):
detected = True
# check if we parsed something reasonable
if not error and calc:
if not len(calc.structures) or not len(calc.structures[-1]): error = 'Valid structure is not present!'
if calc.info['finished'] == 0x1: calc.warning( 'This calculation is not correctly finished!' )
if not calc.info['H']: error = 'XC potential is not present!'
yield calc, error
if detected: break
i += 1
f.close()
# unsupported data occured
if not detected: yield None, 'was read...'
def classify(self, calc, symprec=None):
'''
Reasons on normalization, invokes hierarchy API and prepares calc for saving
NB: this is the PUBLIC method
@returns tilde_obj, error
'''
error = None
symbols = calc.structures[-1].get_chemical_symbols()
calc.info['formula'] = self.formula(symbols)
calc.info['cellpar'] = cell_to_cellpar(calc.structures[-1].cell).tolist()
if calc.info['input']:
try: calc.info['input'] = str(calc.info['input'], errors='ignore')
except: pass
# applying filter: todo
if (calc.info['finished'] == 0x1 and self.settings['skip_unfinished']) or \
(not calc.info['energy'] and self.settings['skip_notenergy']):
return None, 'data do not satisfy the active filter'
# naive elements extraction
fragments = re.findall(r'([A-Z][a-z]?)(\d*[?:.\d+]*)?', calc.info['formula'])
for i in fragments:
if i[0] == 'X': continue
calc.info['elements'].append(i[0])
calc.info['contents'].append(int(i[1])) if i[1] else calc.info['contents'].append(1)
# extend hierarchy with modules
for C_obj in self.Classifiers:
try: calc = C_obj['classify'](calc)
except:
exc_type, exc_value, exc_tb = sys.exc_info()
error = "Fatal error during classification:\n %s" % "".join(traceback.format_exception( exc_type, exc_value, exc_tb ))
return None, error
# chemical ratios
if not len(calc.info['standard']):
if len(calc.info['elements']) == 1: calc.info['expanded'] = 1
if not calc.info['expanded']: calc.info['expanded'] = reduce(gcd, calc.info['contents'])
for n, i in enumerate([x//calc.info['expanded'] for x in calc.info['contents']]):
if i==1: calc.info['standard'] += calc.info['elements'][n]
else: calc.info['standard'] += calc.info['elements'][n] + str(i)
if not calc.info['expanded']: del calc.info['expanded']
calc.info['nelem'] = len(calc.info['elements'])
if calc.info['nelem'] > 13: calc.info['nelem'] = 13
calc.info['natom'] = len(symbols)
# periodicity
if calc.info['periodicity'] == 0: calc.info['periodicity'] = 0x4
elif calc.info['periodicity'] == -1: calc.info['periodicity'] = 0x5
# general calculation type reasoning
if (calc.structures[-1].get_initial_charges() != 0).sum(): calc.info['calctypes'].append(0x4) # numpy count_nonzero implementation
if (calc.structures[-1].get_initial_magnetic_moments() != 0).sum(): calc.info['calctypes'].append(0x5)
if calc.phonons['modes']: calc.info['calctypes'].append(0x6)
if calc.phonons['ph_k_degeneracy']: calc.info['calctypes'].append(0x7)
if calc.phonons['dielectric_tensor']: calc.info['calctypes'].append(0x8) # CRYSTAL-only!
if len(calc.tresholds) > 1:
calc.info['calctypes'].append(0x3)
calc.info['optgeom'] = True
if calc.electrons['dos'] or calc.electrons['bands']: calc.info['calctypes'].append(0x2)
if calc.info['energy']: calc.info['calctypes'].append(0x1)
calc.info['spin'] = 0x2 if calc.info['spin'] else 0x1
# TODO: standardize
if 'vac' in calc.info:
if 'X' in symbols: calc.info['techs'].append('vacancy defect: ghost')
else: calc.info['techs'].append('vacancy defect: void space')
calc.info['lata'] = round(calc.info['cellpar'][0], 3)
calc.info['latb'] = round(calc.info['cellpar'][1], 3)
calc.info['latc'] = round(calc.info['cellpar'][2], 3)
calc.info['latalpha'] = round(calc.info['cellpar'][3], 2)
calc.info['latbeta'] = round(calc.info['cellpar'][4], 2)
calc.info['latgamma'] = round(calc.info['cellpar'][5], 2)
# invoke symmetry finder
found = SymmetryHandler(calc, symprec)
if found.error:
return None, found.error
calc.info['sg'] = found.i
calc.info['ng'] = found.n
calc.info['symmetry'] = found.symmetry
calc.info['spg'] = "%s — %s" % (found.n, found.i)
calc.info['pg'] = found.pg
calc.info['dg'] = found.dg
# phonons
if calc.phonons['dfp_magnitude']: calc.info['dfp_magnitude'] = round(calc.phonons['dfp_magnitude'], 3)
if calc.phonons['dfp_disps']: calc.info['dfp_disps'] = len(calc.phonons['dfp_disps'])
if calc.phonons['modes']:
calc.info['n_ph_k'] = len(calc.phonons['ph_k_degeneracy']) if calc.phonons['ph_k_degeneracy'] else 1
#calc.info['rgkmax'] = calc.electrons['rgkmax'] # LAPW
# electronic properties reasoning by bands
if calc.electrons['bands']:
if calc.electrons['bands'].is_conductor():
calc.info['etype'] = 0x2
calc.info['bandgap'] = 0.0
calc.info['bandgaptype'] = 0x1
else:
try: gap, is_direct = calc.electrons['bands'].get_bandgap()
except ElectronStructureError as e:
calc.electrons['bands'] = None
calc.warning(e.value)
else:
calc.info['etype'] = 0x1
calc.info['bandgap'] = round(gap, 2)
calc.info['bandgaptype'] = 0x2 if is_direct else 0x3
# electronic properties reasoning by DOS
if calc.electrons['dos']:
try: gap = round(calc.electrons['dos'].get_bandgap(), 2)
except ElectronStructureError as e:
calc.electrons['dos'] = None
calc.warning(e.value)
else:
if calc.electrons['bands']: # check coincidence
if abs(calc.info['bandgap'] - gap) > 0.2: calc.warning('Bans gaps in DOS and bands data differ considerably! The latter will be considered.')
else:
calc.info['bandgap'] = gap
if gap: calc.info['etype'] = 0x1
else:
calc.info['etype'] = 0x2
calc.info['bandgaptype'] = 0x1
# TODO: beware to add something new to an existing item!
# TODO2: unknown or absent?
for entity in self.hierarchy:
if entity['creates_topic'] and not entity['optional'] and not calc.info.get(entity['source']):
if entity['enumerated']:
calc.info[ entity['source'] ] = [0x0] if entity['multiple'] else 0x0
else:
calc.info[ entity['source'] ] = ['none'] if entity['multiple'] else 'none'
calc.benchmark() # this call must be at the very end of parsing
return calc, error
def postprocess(self, calc, with_module=None, dry_run=None):
'''
Invokes module(s) API
NB: this is the PUBLIC method
@returns apps_dict
'''
for appname, appclass in self.Apps.items():
if with_module and with_module != appname: continue
run_permitted = False
# scope-conditions
if appclass['apptarget']:
for key in appclass['apptarget']:
negative = False
if str(appclass['apptarget'][key]).startswith('!'):
negative = True
scope_prop = appclass['apptarget'][key][1:]
else:
scope_prop = appclass['apptarget'][key]
if key in calc.info:
# non-strict comparison ("CRYSTAL" matches "CRYSTAL09 v2.0")
if (str(scope_prop) in str(calc.info[key]) or scope_prop == calc.info[key]) != negative: # true if only one, but not both
run_permitted = True
else:
run_permitted = False
break
else: run_permitted = True
# module code running
if run_permitted:
calc.apps[appname] = {'error': None, 'data': None}
if dry_run: continue
try: AppInstance = appclass['appmodule'](calc)
except:
exc_type, exc_value, exc_tb = sys.exc_info()
errmsg = "Fatal error in %s module:\n %s" % ( appname, " ".join(traceback.format_exception( exc_type, exc_value, exc_tb )) )
calc.apps[appname]['error'] = errmsg
calc.warning( errmsg )
else:
try: calc.apps[appname]['data'] = getattr(AppInstance, appclass['appdata'])
except AttributeError:
errmsg = 'No appdata-defined property found for %s module!' % appname
calc.apps[appname]['error'] = errmsg
calc.warning( errmsg )
return calc
def save(self, calc, session):
'''
Saves tilde_obj into the database
NB: this is the PUBLIC method
@returns checksum, error
'''
checksum = calc.get_checksum()
try: existing_calc = session.query(model.Calculation).filter(model.Calculation.checksum == checksum).one()
except NoResultFound: pass
else:
del calc
return None, "This calculation already exists!"
if not calc.download_size:
for f in calc.related_files:
calc.download_size += os.stat(f).st_size
ormcalc = model.Calculation(checksum = checksum)
if calc._calcset:
ormcalc.meta_data = model.Metadata(chemical_formula = calc.info['standard'], download_size = calc.download_size)
for child in session.query(model.Calculation).filter(model.Calculation.checksum.in_(calc._calcset)).all():
ormcalc.children.append(child)
ormcalc.siblings_count = len(ormcalc.children)
ormcalc.nested_depth = calc._nested_depth
else:
# prepare phonon data for saving
# this is actually a dict to list conversion TODO re-structure this
if calc.phonons['modes']:
phonons_json = []
for bzpoint, frqset in calc.phonons['modes'].items():
# re-orientate eigenvectors
for i in range(0, len(calc.phonons['ph_eigvecs'][bzpoint])):
for j in range(0, len(calc.phonons['ph_eigvecs'][bzpoint][i])//3):
eigv = array([calc.phonons['ph_eigvecs'][bzpoint][i][j*3], calc.phonons['ph_eigvecs'][bzpoint][i][j*3+1], calc.phonons['ph_eigvecs'][bzpoint][i][j*3+2]])
R = dot( eigv, calc.structures[-1].cell ).tolist()
calc.phonons['ph_eigvecs'][bzpoint][i][j*3], calc.phonons['ph_eigvecs'][bzpoint][i][j*3+1], calc.phonons['ph_eigvecs'][bzpoint][i][j*3+2] = [round(x, 3) for x in R]
try: irreps = calc.phonons['irreps'][bzpoint]
except KeyError:
empty = []
for i in range(len(frqset)): empty.append('')
irreps = empty
phonons_json.append({ 'bzpoint':bzpoint, 'freqs':frqset, 'irreps':irreps, 'ph_eigvecs':calc.phonons['ph_eigvecs'][bzpoint] })
if bzpoint == '0 0 0':
phonons_json[-1]['ir_active'] = calc.phonons['ir_active']
phonons_json[-1]['raman_active'] = calc.phonons['raman_active']
if calc.phonons['ph_k_degeneracy']:
phonons_json[-1]['ph_k_degeneracy'] = calc.phonons['ph_k_degeneracy'][bzpoint]
ormcalc.phonons = model.Phonons()
ormcalc.spectra.append( model.Spectra(kind = model.Spectra.PHONON, eigenvalues = json.dumps(phonons_json)) )
# prepare electron data for saving TODO re-structure this
for i in ['dos', 'bands']: # projected?
if calc.electrons[i]: calc.electrons[i] = calc.electrons[i].todict()
if calc.electrons['dos'] or calc.electrons['bands']:
ormcalc.electrons = model.Electrons(gap = calc.info['bandgap'])
if 'bandgaptype' in calc.info: ormcalc.electrons.is_direct = 1 if calc.info['bandgaptype'] == 'direct' else -1
ormcalc.spectra.append(model.Spectra(
kind = model.Spectra.ELECTRON,
dos = json.dumps(calc.electrons['dos']),
bands = json.dumps(calc.electrons['bands']),
projected = json.dumps(calc.electrons['projected']),
eigenvalues = json.dumps(calc.electrons['eigvals']))
)
# construct ORM for other props
calc.related_files = list(map(virtualize_path, calc.related_files))
ormcalc.meta_data = model.Metadata(location = calc.info['location'], finished = calc.info['finished'], raw_input = calc.info['input'], modeling_time = calc.info['duration'], chemical_formula = html_formula(calc.info['standard']), download_size = calc.download_size, filenames = json.dumps(calc.related_files))
codefamily = model.Codefamily.as_unique(session, content = calc.info['framework'])
codeversion = model.Codeversion.as_unique(session, content = calc.info['prog'])
codeversion.instances.append( ormcalc.meta_data )
codefamily.versions.append( codeversion )
pot = model.Pottype.as_unique(session, name = calc.info['H'])
pot.instances.append(ormcalc)
ormcalc.recipinteg = model.Recipinteg(kgrid = calc.info['k'], kshift = calc.info['kshift'], smearing = calc.info['smear'], smeartype = calc.info['smeartype'])
ormcalc.basis = model.Basis(kind = calc.info['ansatz'], content = json.dumps(calc.electrons['basis_set']) if calc.electrons['basis_set'] else None)
ormcalc.energy = model.Energy(convergence = json.dumps(calc.convergence), total = calc.info['energy'])
ormcalc.spacegroup = model.Spacegroup(n=calc.info['ng'])
ormcalc.struct_ratios = model.Struct_ratios(chemical_formula=calc.info['standard'], formula_units=calc.info['expanded'], nelem=calc.info['nelem'], dimensions=calc.info['dims'])
if len(calc.tresholds) > 1: ormcalc.struct_optimisation = model.Struct_optimisation(tresholds=json.dumps(calc.tresholds), ncycles=json.dumps(calc.ncycles))
for n, ase_repr in enumerate(calc.structures):
is_final = True if n == len(calc.structures)-1 else False
struct = model.Structure(step = n, final = is_final)
s = cell_to_cellpar(ase_repr.cell)
struct.lattice = model.Lattice(a=s[0], b=s[1], c=s[2], alpha=s[3], beta=s[4], gamma=s[5], a11=ase_repr.cell[0][0], a12=ase_repr.cell[0][1], a13=ase_repr.cell[0][2], a21=ase_repr.cell[1][0], a22=ase_repr.cell[1][1], a23=ase_repr.cell[1][2], a31=ase_repr.cell[2][0], a32=ase_repr.cell[2][1], a33=ase_repr.cell[2][2])
#rmts = ase_repr.get_array('rmts') if 'rmts' in ase_repr.arrays else [None for j in range(len(ase_repr))]
charges = ase_repr.get_array('charges') if 'charges' in ase_repr.arrays else [None for j in range(len(ase_repr))]
magmoms = ase_repr.get_array('magmoms') if 'magmoms' in ase_repr.arrays else [None for j in range(len(ase_repr))]
for n, i in enumerate(ase_repr):
struct.atoms.append( model.Atom( number=chemical_symbols.index(i.symbol), x=i.x, y=i.y, z=i.z, charge=charges[n], magmom=magmoms[n] ) )
ormcalc.structures.append(struct)
# TODO Forces
ormcalc.uigrid = model.Grid(info=json.dumps(calc.info))
# tags ORM
uitopics = []
for entity in self.hierarchy:
if not entity['creates_topic']: continue
if entity['multiple'] or calc._calcset:
for item in calc.info.get( entity['source'], [] ):
uitopics.append( model.topic(cid=entity['cid'], topic=item) )
else:
topic = calc.info.get(entity['source'])
if topic or not entity['optional']: uitopics.append( model.topic(cid=entity['cid'], topic=topic) )
uitopics = [model.Topic.as_unique(session, cid=x.cid, topic="%s" % x.topic) for x in uitopics]
ormcalc.uitopics.extend(uitopics)
if calc._calcset: session.add(ormcalc)
else: session.add_all([codefamily, codeversion, pot, ormcalc])
session.commit()
del calc, ormcalc
return checksum, None
def purge(self, session, checksum):
'''
Deletes calc entry by checksum entirely from the database
NB source files on disk are not deleted
NB: this is the PUBLIC method
@returns error
'''
C = session.query(model.Calculation).get(checksum)
if not C: return 'Calculation does not exist!'
# dataset deletion includes editing the whole dataset hierarchical tree (if any)
if C.siblings_count:
C_meta = session.query(model.Metadata).get(checksum)
higher_lookup = {}
more = C.parent
distance = 0
while True:
distance += 1
higher, more = more, []
if not higher: break
for i in higher:
try: higher_lookup[distance].add(i)
except KeyError: higher_lookup[distance] = set([i])
if i.parent:
more += i.parent
for distance, members in higher_lookup.items():
for i in members:
if distance == 1:
i.siblings_count -= 1
if not i.siblings_count:
return 'The parent dataset contains only one (current) item, please, delete parent dataset first!'
i.meta_data.download_size -= C_meta.download_size
session.add(i)
# low-level entry deletion deals with additional tables
else:
session.execute( model.delete( model.Spectra ).where( model.Spectra.checksum == checksum) )
session.execute( model.delete( model.Electrons ).where( model.Electrons.checksum == checksum ) )
session.execute( model.delete( model.Phonons ).where( model.Phonons.checksum == checksum ) )
session.execute( model.delete( model.Recipinteg ).where( model.Recipinteg.checksum == checksum ) )
session.execute( model.delete( model.Basis ).where( model.Basis.checksum == checksum ) )
session.execute( model.delete( model.Energy ).where( model.Energy.checksum == checksum ) )
session.execute( model.delete( model.Spacegroup ).where( model.Spacegroup.checksum == checksum ) )
session.execute( model.delete( model.Struct_ratios ).where( model.Struct_ratios.checksum == checksum ) )
session.execute( model.delete( model.Struct_optimisation ).where( model.Struct_optimisation.checksum == checksum ) )
struct_ids = [ int(i[0]) for i in session.query(model.Structure.struct_id).filter(model.Structure.checksum == checksum).all() ]
for struct_id in struct_ids:
session.execute( model.delete( model.Atom ).where( model.Atom.struct_id == struct_id ) )
session.execute( model.delete( model.Lattice ).where( model.Lattice.struct_id == struct_id ) )
session.execute( model.delete( model.Structure ).where( model.Structure.checksum == checksum ) )
# for all types of entries
if len(C.references):
left_references = [ int(i[0]) for i in session.query(model.Reference.reference_id).join(model.metadata_references, model.Reference.reference_id == model.metadata_references.c.reference_id).filter(model.metadata_references.c.checksum == checksum).all() ]
session.execute( model.delete( model.metadata_references ).where( model.metadata_references.c.checksum == checksum ) )
# remove the whole citation?
for lc in left_references:
if not (session.query(model.metadata_references.c.checksum).filter(model.metadata_references.c.reference_id == lc).count()):
session.execute( model.delete( model.Reference ).where(model.Reference.reference_id == lc) )
# TODO rewrite with cascading
session.execute( model.delete( model.Metadata ).where( model.Metadata.checksum == checksum ) )
session.execute( model.delete( model.Grid ).where( model.Grid.checksum == checksum ) )
session.execute( model.delete( model.tags ).where( model.tags.c.checksum == checksum ) )
session.execute( model.delete( model.calcsets ).where( model.calcsets.c.children_checksum == checksum ) )
session.execute( model.delete( model.calcsets ).where( model.calcsets.c.parent_checksum == checksum ) )
session.execute( model.delete( model.Calculation ).where( model.Calculation.checksum == checksum ) )
session.commit()
# NB tables topics, codefamily, codeversion, pottype are mostly irrelevant and, if needed, should be cleaned manually
return False
def merge(self, session, checksums, title):
'''
Merges calcs into a new calc called DATASET
NB: this is the PUBLIC method
@returns DATASET, error
'''
calc = Output(calcset=checksums)
cur_depth = 0
for nested_depth, grid_item, download_size in session.query(model.Calculation.nested_depth, model.Grid.info, model.Metadata.download_size).filter(model.Calculation.checksum == model.Grid.checksum, model.Grid.checksum == model.Metadata.checksum, model.Calculation.checksum.in_(checksums)).all():
if nested_depth > cur_depth: cur_depth = nested_depth
grid_item = json.loads(grid_item)
for entity in self.hierarchy:
topic = grid_item.get(entity['source'])
if not topic: continue
if not isinstance(topic, list): topic = [ topic ]
calc.info[ entity['source'] ] = list(set( calc.info.get(entity['source'], []) + topic ))
calc.download_size += download_size
if not calc.download_size: return None, 'Wrong parameters provided!'
calc._nested_depth = cur_depth + 1
calc.info['standard'] = title
# generate fake checksum
calc._checksum = calc.get_collective_checksum()
return calc, None
def augment(self, session, parent, addendum):
'''
Augments a DATASET with some calcs
NB: this is the PUBLIC method
@returns error
'''
parent_calc = session.query(model.Calculation).get(parent)
if not parent_calc or not parent_calc.siblings_count: return 'Dataset is erroneously selected!'
existing_children, filtered_addendum = [child.checksum for child in parent_calc.children], []
for child in addendum:
if not child in existing_children: filtered_addendum.append(child)
if not filtered_addendum: return 'All these data are already present in this dataset.'
if parent_calc.checksum in filtered_addendum: return 'A dataset cannot be added into itself.'
higher_lookup = {}
more = parent_calc.parent
distance = 0
while True:
distance += 1
higher, more = more, []
if not higher: break
for i in higher:
try: higher_lookup[distance].add(i)
except KeyError: higher_lookup[distance] = set([i])
if i.parent:
more += i.parent
for members in list(higher_lookup.values()):
for i in members:
if i.checksum in filtered_addendum: return 'A parent dataset cannot be added to its children dataset.'
parent_meta = session.query(model.Metadata).get(parent)
parent_grid = session.query(model.Grid).get(parent)
info_obj = json.loads(parent_grid.info)
for nested_depth, grid_item, download_size in session.query(model.Calculation.nested_depth, model.Grid.info, model.Metadata.download_size).filter(model.Calculation.checksum == model.Grid.checksum, model.Grid.checksum == model.Metadata.checksum, model.Calculation.checksum.in_(filtered_addendum)).all():
if nested_depth >= parent_calc.nested_depth: parent_calc.nested_depth = nested_depth + 1
grid_item = json.loads(grid_item)
for entity in self.hierarchy:
topic = grid_item.get(entity['source'])
if not topic: continue
if entity['source'] == 'standard': topic = []
if not isinstance(topic, list): topic = [ topic ]
existing_term = info_obj.get(entity['source'], [])
if not isinstance(existing_term, list): existing_term = [ existing_term ] # TODO
info_obj[ entity['source'] ] = list(set( existing_term + topic ))
parent_meta.download_size += download_size
info_obj['standard'] = info_obj['standard'][0] # TODO
parent_grid.info = json.dumps(info_obj)
# tags ORM
for entity in self.hierarchy:
if not entity['creates_topic']: continue
for item in info_obj.get( entity['source'], [] ):
parent_calc.uitopics.append( model.Topic.as_unique(session, cid=entity['cid'], topic="%s" % item) )
for child in session.query(model.Calculation).filter(model.Calculation.checksum.in_(filtered_addendum)).all():
parent_calc.children.append(child)
parent_calc.siblings_count = len(parent_calc.children)
for distance, members in higher_lookup.items():
for i in members:
d = parent_calc.nested_depth - i.nested_depth + distance
if d > 0:
i.nested_depth += d
i.meta_data.download_size += parent_meta.download_size # fixme
session.add(i)
session.add_all([parent_calc, parent_meta, parent_grid])
session.commit()
return False
|
ansobolev/tilde
|
tilde/core/api.py
|
Python
|
mit
| 41,103
|
[
"ASE",
"CRYSTAL"
] |
5157969fe4f9b8d300d6d36a2a19ce652a914c9d2d07d217890c0d87f040c54b
|
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
AIRPORTS = {
'MLC': { 'latitude':'34.883333', 'longitude': '-95.783333', 'name':'Mc Alester' },
'HEM': { 'latitude':'60.258333', 'longitude': '25.05', 'name':'Helsinki-malmi' },
'HEN': { 'latitude':'51.583333', 'longitude': '-0.233333', 'name':'Hendon' },
'SPY': { 'latitude':'4.733333', 'longitude': '-6.666667', 'name':'San Pedro' },
'SPZ': { 'latitude':'36.183333', 'longitude': '-94.133333', 'name':'Springdale Muni' },
'HEO': { 'latitude':'-9.133333', 'longitude': '147.583333', 'name':'Haelogo' },
'SPP': { 'latitude':'-14.633333', 'longitude': '17.733333', 'name':'Menongue' },
'HEH': { 'latitude':'20.733333', 'longitude': '96.783333', 'name':'Heho' },
'SPR': { 'latitude':'17.916667', 'longitude': '-87.966667', 'name':'San Pedro' },
'SPS': { 'latitude':'33.983333', 'longitude': '-98.516667', 'name':'Sheppard AFB' },
'SPT': { 'latitude':'5.083333', 'longitude': '115.55', 'name':'Sipitang' },
'SPU': { 'latitude':'43.533333', 'longitude': '16.3', 'name':'Split' },
'SPV': { 'latitude':'-3.9', 'longitude': '143.683333', 'name':'Sepik Plains' },
'SPW': { 'latitude':'43.166667', 'longitude': '-95.183333', 'name':'Municipal' },
'SPH': { 'latitude':'-9.0', 'longitude': '147.766667', 'name':'Sopu' },
'SPI': { 'latitude':'39.85', 'longitude': '-89.683333', 'name':'Capital' },
'SPJ': { 'latitude':'37.936389', 'longitude': '23.944444', 'name':'Eleftherios Venizelos' },
'SPM': { 'latitude':'49.983333', 'longitude': '6.683333', 'name':'Spangdahlem' },
'SPN': { 'latitude':'15.133333', 'longitude': '145.7', 'name':'International' },
'SPO': { 'latitude':'37.418056', 'longitude': '-5.893056', 'name':'San Pablo' },
'SPA': { 'latitude':'34.915833', 'longitude': '-81.956389', 'name':'Spartanburg, Downtown Memorial' },
'SPB': { 'latitude':'18.35', 'longitude': '-64.9167', 'name':'Saint Thomas Sea Plane Base' },
'HEK': { 'latitude':'50.25', 'longitude': '127.3', 'name':'Heihe' },
'SPD': { 'latitude':'25.766667', 'longitude': '88.766667', 'name':'Saidpur' },
'SPE': { 'latitude':'4.716667', 'longitude': '116.466667', 'name':'Sepulot' },
'SPF': { 'latitude':'44.483333', 'longitude': '-103.85', 'name':'Black Hills' },
'IXJ': { 'latitude':'32.683333', 'longitude': '74.833333', 'name':'Satwari' },
'IXK': { 'latitude':'21.316944', 'longitude': '70.270278', 'name':'Keshod' },
'IXH': { 'latitude':'24.316667', 'longitude': '92.016667', 'name':'Kailashahar' },
'IXI': { 'latitude':'27.266667', 'longitude': '94.1', 'name':'Lilabari' },
'IXN': { 'latitude':'24.066667', 'longitude': '91.633333', 'name':'Khowai' },
'IXL': { 'latitude':'34.166667', 'longitude': '77.583333', 'name':'Bakula Rimpoche' },
'IXM': { 'latitude':'9.834444', 'longitude': '78.093333', 'name':'Madurai' },
'IXB': { 'latitude':'26.733333', 'longitude': '88.333333', 'name':'Bagdogra' },
'IXC': { 'latitude':'30.666667', 'longitude': '76.8', 'name':'Chandigarh' },
'XPA': { 'latitude':'11.25', 'longitude': '0.7', 'name':'Pama' },
'IXA': { 'latitude':'23.9', 'longitude': '91.25', 'name':'Singerbhil' },
'IXG': { 'latitude':'15.85', 'longitude': '74.6', 'name':'Sambre' },
'IXD': { 'latitude':'25.433333', 'longitude': '81.733333', 'name':'Bamrauli' },
'IXE': { 'latitude':'12.961389', 'longitude': '74.89', 'name':'Bajpe' },
'IXZ': { 'latitude':'11.666667', 'longitude': '92.733333', 'name':'Port Blair' },
'IXY': { 'latitude':'23.116667', 'longitude': '70.1', 'name':'Kandla' },
'IXR': { 'latitude':'23.314167', 'longitude': '85.321667', 'name':'Birsa Munda International' },
'IXS': { 'latitude':'24.966667', 'longitude': '92.516667', 'name':'Kumbhirgram' },
'IXP': { 'latitude':'32.233333', 'longitude': '75.633333', 'name':'Pathankot' },
'IXQ': { 'latitude':'24.133333', 'longitude': '91.816667', 'name':'Kamalpur' },
'IXV': { 'latitude':'28.416667', 'longitude': '94.841667', 'name':'Along' },
'IXW': { 'latitude':'22.816667', 'longitude': '86.166667', 'name':'Sonari' },
'IXT': { 'latitude':'28.066667', 'longitude': '95.366667', 'name':'Pasighat' },
'IXU': { 'latitude':'19.883333', 'longitude': '75.416667', 'name':'Chikkalthana' },
'JNS': { 'latitude':'60.916667', 'longitude': '-46.05', 'name':'Heliport' },
'JNP': { 'latitude':'33.6', 'longitude': '-117.883333', 'name':'Heliport' },
'JNU': { 'latitude':'58.35', 'longitude': '-134.583333', 'name':'Boundary Bay' },
'JNZ': { 'latitude':'41.116667', 'longitude': '121.016667', 'name':'Jinzhou' },
'JNX': { 'latitude':'37.080556', 'longitude': '25.368056', 'name':'Naxos Airport' },
'PQM': { 'latitude':'17.5', 'longitude': '-92.008333', 'name':'Palenque' },
'JNB': { 'latitude':'-26.139167', 'longitude': '28.246111', 'name':'Oliver Reginald Tambo International' },
'JNA': { 'latitude':'-15.473889', 'longitude': '-44.385556', 'name':'Januaria' },
'PQS': { 'latitude':'61.933333', 'longitude': '-162.883333', 'name':'Pilot Station' },
'JNG': { 'latitude':'35.416667', 'longitude': '116.533333', 'name':'Jining' },
'JNI': { 'latitude':'-34.583333', 'longitude': '-60.966667', 'name':'Junin' },
'JNH': { 'latitude':'7.716667', 'longitude': '40.916667', 'name':'North Park Inn H/P' },
'JNN': { 'latitude':'60.15', 'longitude': '-45.216667', 'name':'Nanortalik' },
'BEJ': { 'latitude':'2.155556', 'longitude': '117.432222', 'name':'Kalimaru' },
'BEK': { 'latitude':'26.216667', 'longitude': '81.233333', 'name':'Bareli' },
'BEH': { 'latitude':'42.133333', 'longitude': '-86.433333', 'name':'Ross Field' },
'BEI': { 'latitude':'9.383333', 'longitude': '34.533333', 'name':'Beica' },
'BEN': { 'latitude':'32.116667', 'longitude': '20.066667', 'name':'Benina Intl' },
'BEO': { 'latitude':'-33.033333', 'longitude': '151.666667', 'name':'Belmont' },
'BEL': { 'latitude':'-1.383611', 'longitude': '-48.468611', 'name':'Val De Cans' },
'BEM': { 'latitude':'5.266667', 'longitude': '17.65', 'name':'Bossembele' },
'BEB': { 'latitude':'57.483333', 'longitude': '-7.366667', 'name':'Benbecula' },
'BEC': { 'latitude':'37.686389', 'longitude': '-97.221111', 'name':'Beech' },
'BEA': { 'latitude':'-8.65', 'longitude': '146.483333', 'name':'Bereina' },
'BEF': { 'latitude':'12.033333', 'longitude': '-83.983333', 'name':'Bluefields' },
'BEG': { 'latitude':'44.819167', 'longitude': '20.306944', 'name':'Nikola Tesla' },
'BED': { 'latitude':'42.466667', 'longitude': '-71.283333', 'name':'Hanscom Field' },
'BEE': { 'latitude':'-12.983333', 'longitude': '141.6', 'name':'Beagle Bay' },
'BEZ': { 'latitude':'-1.333333', 'longitude': '176.0', 'name':'Beru' },
'BEY': { 'latitude':'33.820833', 'longitude': '35.488333', 'name':'Beirut Rafic Hariri Airport' },
'BES': { 'latitude':'48.45', 'longitude': '-4.416667', 'name':'Brest Lesquin' },
'BEP': { 'latitude':'15.162778', 'longitude': '76.882778', 'name':'Bellary' },
'BEQ': { 'latitude':'52.35', 'longitude': '0.766667', 'name':'Honington' },
'BEV': { 'latitude':'31.25', 'longitude': '34.8', 'name':'Beer Sheba' },
'BEW': { 'latitude':'-19.8', 'longitude': '34.9', 'name':'Beira' },
'BET': { 'latitude':'60.783333', 'longitude': '-161.833333', 'name':'Bethel Airport' },
'BEU': { 'latitude':'-24.333333', 'longitude': '139.366667', 'name':'Bedourie' },
'GRV': { 'latitude':'43.333333', 'longitude': '45.7', 'name':'Groznyj' },
'GRW': { 'latitude':'39.066667', 'longitude': '-28.0', 'name':'Graciosa Island' },
'GRT': { 'latitude':'32.566667', 'longitude': '74.083333', 'name':'Gujrat' },
'GRU': { 'latitude':'-23.431944', 'longitude': '-46.469444', 'name':'Aeroporto Internacional Guarulhos' },
'GRR': { 'latitude':'42.883333', 'longitude': '-85.533333', 'name':'Kent County Intl' },
'GRS': { 'latitude':'42.75', 'longitude': '11.066667', 'name':'Baccarini' },
'GRP': { 'latitude':'-11.666667', 'longitude': '-49.216667', 'name':'Gurupi' },
'GRQ': { 'latitude':'53.119722', 'longitude': '6.579444', 'name':'Eelde' },
'GRZ': { 'latitude':'47.066667', 'longitude': '15.45', 'name':'Thalerhof' },
'GRX': { 'latitude':'37.188611', 'longitude': '-3.777222', 'name':'Granada' },
'GRY': { 'latitude':'66.566667', 'longitude': '-18.016667', 'name':'Grimsey' },
'GRF': { 'latitude':'35.339167', 'longitude': '-77.960556', 'name':'Gray Aaf' },
'GRG': { 'latitude':'33.616667', 'longitude': '69.116667', 'name':'Gardez' },
'GRD': { 'latitude':'34.25', 'longitude': '-82.15', 'name':'Greenwood' },
'GRE': { 'latitude':'38.883333', 'longitude': '-89.416667', 'name':'Municipal' },
'GRB': { 'latitude':'44.483333', 'longitude': '-88.133333', 'name':'Austin-straubel Field' },
'GRC': { 'latitude':'4.6', 'longitude': '-8.166667', 'name':'Grand Cess' },
'GRA': { 'latitude':'8.2', 'longitude': '-73.783333', 'name':'Gamarra' },
'GRN': { 'latitude':'42.8', 'longitude': '-102.2', 'name':'Gordon' },
'GRO': { 'latitude':'41.900833', 'longitude': '2.760556', 'name':'Girona-Costa Brava' },
'GRL': { 'latitude':'-7.95', 'longitude': '147.183333', 'name':'Garasa' },
'GRM': { 'latitude':'47.75', 'longitude': '-91.333333', 'name':'Devils Track' },
'GRJ': { 'latitude':'-33.966667', 'longitude': '22.416667', 'name':'George' },
'GRK': { 'latitude':'31.067222', 'longitude': '-97.828889', 'name':'Gray Aaf' },
'GRH': { 'latitude':'-10.316667', 'longitude': '150.683333', 'name':'Garuahi' },
'GRI': { 'latitude':'40.9675', 'longitude': '-98.309722', 'name':'Grand Island' },
'NOL': { 'latitude':'50.483333', 'longitude': '21.45', 'name':'Nakolik River' },
'NOM': { 'latitude':'-6.65', 'longitude': '142.116667', 'name':'Nomad River' },
'TJC': { 'latitude':'9.416667', 'longitude': '-78.483333', 'name':'Ticantiki' },
'NOO': { 'latitude':'-9.083333', 'longitude': '147.033333', 'name':'Naoro' },
'NOH': { 'latitude':'17.8', 'longitude': '-88.3', 'name':'Chicago NAS' },
'HLZ': { 'latitude':'-37.866667', 'longitude': '175.333333', 'name':'Hamilton' },
'HLY': { 'latitude':'53.316667', 'longitude': '-4.633333', 'name':'Anglesey Airport' },
'NOK': { 'latitude':'-27.083333', 'longitude': '-52.333333', 'name':'Nova Xavantina' },
'HLW': { 'latitude':'-28.016667', 'longitude': '32.25', 'name':'Hluhluwe' },
'HLV': { 'latitude':'-15.683333', 'longitude': '145.2', 'name':'Helenvale' },
'HLU': { 'latitude':'-21.25', 'longitude': '165.616667', 'name':'Houailou' },
'NOG': { 'latitude':'18.816667', 'longitude': '-97.166667', 'name':'Nogales' },
'HLS': { 'latitude':'-41.0', 'longitude': '148.175', 'name':'St Helens' },
'HLR': { 'latitude':'31.138611', 'longitude': '-97.714444', 'name':'Fort Hood AAF' },
'NOB': { 'latitude':'9.8', 'longitude': '-85.533333', 'name':'Nosara Beach' },
'NOC': { 'latitude':'53.912778', 'longitude': '-8.811944', 'name':'Ireland West Airport Knock' },
'TJQ': { 'latitude':'-2.75', 'longitude': '107.65', 'name':'Tanjung Pandan' },
'HLN': { 'latitude':'46.6', 'longitude': '-111.983333', 'name':'Helena' },
'HLM': { 'latitude':'42.783333', 'longitude': '-86.116667', 'name':'Park Township' },
'HLL': { 'latitude':'-17.0', 'longitude': '128.008333', 'name':'Hillside' },
'TJU': { 'latitude':'37.9167', 'longitude': '69.7833', 'name':'Kulyab' },
'HLI': { 'latitude':'36.85', 'longitude': '-121.4', 'name':'Hollister' },
'HLH': { 'latitude':'46.083333', 'longitude': '122.083333', 'name':'Ulanhot' },
'HLG': { 'latitude':'16.196389', 'longitude': '122.103611', 'name':'Ohio County' },
'HLF': { 'latitude':'57.525833', 'longitude': '15.823333', 'name':'Hultsfred - Vimmerby' },
'NOV': { 'latitude':'-12.783333', 'longitude': '15.766667', 'name':'Huambo' },
'HLD': { 'latitude':'49.2', 'longitude': '119.7', 'name':'Hailar' },
'HLC': { 'latitude':'39.366667', 'longitude': '-99.85', 'name':'Hill City' },
'HLB': { 'latitude':'39.3', 'longitude': '-85.216667', 'name':'Hillenbrand' },
'HLA': { 'latitude':'-25.947222', 'longitude': '27.915', 'name':'Lanseria' },
'NOS': { 'latitude':'-13.311944', 'longitude': '48.314722', 'name':'Fascene' },
'RFD': { 'latitude':'42.2', 'longitude': '-89.1', 'name':'Greater Rockford Airport' },
'MLH': { 'latitude':'47.59', 'longitude': '7.529167', 'name':'EuroAirport' },
'WSB': { 'latitude':'55.55', 'longitude': '-133.633333', 'name':'SPB' },
'FJR': { 'latitude':'25.112222', 'longitude': '56.323889', 'name':'Fujairah Intl' },
'WSG': { 'latitude':'40.166667', 'longitude': '-80.25', 'name':'County' },
'WSF': { 'latitude':'31.1', 'longitude': '-1.383333', 'name':'Sarichef' },
'PLW': { 'latitude':'-0.833333', 'longitude': '119.841667', 'name':'Mutiara' },
'WSM': { 'latitude':'67.416667', 'longitude': '-150.116667', 'name':'Wiseman' },
'PLV': { 'latitude':'49.583333', 'longitude': '34.533333', 'name':'Poltava' },
'WSO': { 'latitude':'5.216667', 'longitude': '-57.183333', 'name':'Washabo' },
'EDB': { 'latitude':'18.25', 'longitude': '31.25', 'name':'Eldebba' },
'LMY': { 'latitude':'-6.85', 'longitude': '141.416667', 'name':'Lake Murray' },
'LMZ': { 'latitude':'-10.766667', 'longitude': '40.483333', 'name':'Palma' },
'EDA': { 'latitude':'55.95', 'longitude': '-133.666667', 'name':'Edna Bay' },
'EDF': { 'latitude':'61.251389', 'longitude': '-149.806389', 'name':'Elmendorf Afb' },
'EDG': { 'latitude':'49.783333', 'longitude': '-1.133333', 'name':'Weide AAF' },
'EDD': { 'latitude':'-25.25', 'longitude': '133.2', 'name':'Erldunda' },
'EDE': { 'latitude':'36.066667', 'longitude': '-76.65', 'name':'Municipal' },
'LMP': { 'latitude':'35.333333', 'longitude': '12.583333', 'name':'Lampedusa' },
'EDK': { 'latitude':'37.766667', 'longitude': '-96.866667', 'name':'El Dorado' },
'LMR': { 'latitude':'-28.366667', 'longitude': '23.45', 'name':'Lime Acres' },
'EDI': { 'latitude':'55.95', 'longitude': '-3.35', 'name':'Turnhouse' },
'LMT': { 'latitude':'42.166667', 'longitude': '-121.733333', 'name':'Kingsley Field' },
'EDO': { 'latitude':'39.554722', 'longitude': '27.013889', 'name':'Edremit/korfez' },
'EDL': { 'latitude':'0.533333', 'longitude': '35.266667', 'name':'Eldoret' },
'EDM': { 'latitude':'46.7', 'longitude': '-1.383333', 'name':'Les Ajoncs' },
'EDR': { 'latitude':'-14.9', 'longitude': '141.616667', 'name':'Edward River' },
'LMI': { 'latitude':'-3.483333', 'longitude': '142.033333', 'name':'Lumi' },
'EDQ': { 'latitude':'14.133333', 'longitude': '-88.416667', 'name':'Erandique' },
'LML': { 'latitude':'8.916667', 'longitude': '166.25', 'name':'Lae Island' },
'EDW': { 'latitude':'34.9', 'longitude': '-117.883333', 'name':'Edwards AFB' },
'LMN': { 'latitude':'4.666667', 'longitude': '115.0', 'name':'Limbang' },
'LMO': { 'latitude':'57.716667', 'longitude': '-3.266667', 'name':'RAF Station' },
'RLU': { 'latitude':'67.1', 'longitude': '-156.933333', 'name':'Bornite Upper' },
'LMA': { 'latitude':'63.883333', 'longitude': '-152.316667', 'name':'Lake Minchumina' },
'LMB': { 'latitude':'-13.75', 'longitude': '34.566667', 'name':'Salima' },
'LMC': { 'latitude':'3.316667', 'longitude': '-73.9', 'name':'Lamacarena' },
'LMD': { 'latitude':'-40.833333', 'longitude': '-68.133333', 'name':'Los Menucos' },
'LME': { 'latitude':'48.0', 'longitude': '1.25', 'name':'Arnage' },
'LMG': { 'latitude':'-4.7', 'longitude': '152.75', 'name':'Lamassa' },
'XPK': { 'latitude':'55.8', 'longitude': '-101.416667', 'name':'Pukatawagan' },
'DPU': { 'latitude':'-5.833333', 'longitude': '145.75', 'name':'Dumpu' },
'DPS': { 'latitude':'-8.748056', 'longitude': '115.167222', 'name':'Ngurah Rai International' },
'XPJ': { 'latitude':'45.633333', 'longitude': '-0.75', 'name':'Montpellier Railway' },
'PLT': { 'latitude':'9.8', 'longitude': '-74.783333', 'name':'Plato' },
'DPG': { 'latitude':'48.583333', 'longitude': '-81.016667', 'name':'Michael AAF' },
'DPE': { 'latitude':'49.933333', 'longitude': '1.083333', 'name':'Dieppe' },
'DPA': { 'latitude':'41.914444', 'longitude': '-88.246389', 'name':'Dupage County' },
'DPO': { 'latitude':'-41.166667', 'longitude': '146.416667', 'name':'Devonport' },
'DPL': { 'latitude':'8.6', 'longitude': '123.35', 'name':'Dipolog' },
'DPK': { 'latitude':'40.766667', 'longitude': '-73.333333', 'name':'Deer Park' },
'XPL': { 'latitude':'14.3825', 'longitude': '-87.621111', 'name':'Coronel Enrique Soto Cano AB' },
'CFN': { 'latitude':'55.044167', 'longitude': '-8.341111', 'name':'Donegal' },
'CFO': { 'latitude':'-10.633333', 'longitude': '-51.566667', 'name':'Confreza' },
'PNZ': { 'latitude':'-9.383333', 'longitude': '-40.5', 'name':'Internacional' },
'CFK': { 'latitude':'36.212222', 'longitude': '1.331667', 'name':'Chlef' },
'CFH': { 'latitude':'-26.516667', 'longitude': '139.45', 'name':'Clifton Hills' },
'CFI': { 'latitude':'-17.15', 'longitude': '131.35', 'name':'Camfield' },
'CFF': { 'latitude':'-8.766667', 'longitude': '18.0', 'name':'Cafunfo' },
'CFG': { 'latitude':'22.166667', 'longitude': '-80.516667', 'name':'Cienfuegos' },
'CFD': { 'latitude':'18.433333', 'longitude': '-77.466667', 'name':'Coulter Field' },
'CFE': { 'latitude':'45.783333', 'longitude': '3.166667', 'name':'Aulnat' },
'CFB': { 'latitude':'-22.883333', 'longitude': '-42.016667', 'name':'Cabo Frio' },
'CFC': { 'latitude':'-26.783333', 'longitude': '-51.0', 'name':'Cacador' },
'CFA': { 'latitude':'58.230556', 'longitude': '-157.5', 'name':'Coffee Point' },
'PNI': { 'latitude':'7.016667', 'longitude': '158.233333', 'name':'Pohnpei' },
'PNH': { 'latitude':'11.55', 'longitude': '104.85', 'name':'Phnom Penh International' },
'PNK': { 'latitude':'-0.05', 'longitude': '109.383333', 'name':'Supadio' },
'PNJ': { 'latitude':'42.446389', 'longitude': '119.573611', 'name':'Peng Lai/Sha He Kou' },
'PNL': { 'latitude':'36.816667', 'longitude': '11.966667', 'name':'Pantelleria' },
'PNO': { 'latitude':'16.35', 'longitude': '-98.066667', 'name':'Pinotepa Nacional' },
'PNN': { 'latitude':'45.202778', 'longitude': '-67.566667', 'name':'Princeton' },
'CFV': { 'latitude':'17.533333', 'longitude': '-88.166667', 'name':'Municipal' },
'CFT': { 'latitude':'32.95', 'longitude': '-109.2', 'name':'Morenci' },
'CFU': { 'latitude':'39.601389', 'longitude': '19.901944', 'name':'Ioannis Kapodistrias' },
'CFR': { 'latitude':'49.183333', 'longitude': '-0.45', 'name':'Carpiquet' },
'CFS': { 'latitude':'-30.320556', 'longitude': '153.116389', 'name':'Coffs Harbour' },
'CFP': { 'latitude':'-18.783333', 'longitude': '144.35', 'name':'Carpentaria Downs' },
'CFQ': { 'latitude':'49.036944', 'longitude': '-116.498333', 'name':'Creston Valley Airport' },
'PLP': { 'latitude':'8.366667', 'longitude': '-78.133333', 'name':'La Palma' },
'XPR': { 'latitude':'43.016667', 'longitude': '-102.516667', 'name':'Pine Ridge' },
'XPQ': { 'latitude':'3.0', 'longitude': '101.4', 'name':'Ferry' },
'XPP': { 'latitude':'53.0', 'longitude': '-97.4', 'name':'Poplar River' },
'XPU': { 'latitude':'70.333333', 'longitude': '-149.333333', 'name':'West Kuparuk' },
'MRX': { 'latitude':'30.556111', 'longitude': '49.151944', 'name':'Mahshahr' },
'MRY': { 'latitude':'36.583333', 'longitude': '-121.85', 'name':'Monterey Peninsula' },
'MRZ': { 'latitude':'-29.5', 'longitude': '149.833333', 'name':'Moree' },
'MRT': { 'latitude':'-14.816667', 'longitude': '133.7', 'name':'Moroak' },
'MRU': { 'latitude':'-20.430278', 'longitude': '57.683611', 'name':'Sir Seewoosagur Ramgoolam Int' },
'MRV': { 'latitude':'44.225', 'longitude': '43.081944', 'name':'Mineralnye Vodyj' },
'MRW': { 'latitude':'54.685833', 'longitude': '11.435', 'name':'Maribo' },
'MRP': { 'latitude':'-27.033333', 'longitude': '133.116667', 'name':'Marla' },
'MRQ': { 'latitude':'13.35', 'longitude': '121.816667', 'name':'Marinduque' },
'MRR': { 'latitude':'-4.383333', 'longitude': '-79.933333', 'name':'Macara' },
'MRS': { 'latitude':'43.436667', 'longitude': '5.215', 'name':'Marseille Provence Airport' },
'MRL': { 'latitude':'-20.066667', 'longitude': '145.583333', 'name':'Miners Lake' },
'MRM': { 'latitude':'-9.2', 'longitude': '147.6', 'name':'Manare' },
'MRN': { 'latitude':'35.75', 'longitude': '-81.725', 'name':'Lenoir' },
'MRO': { 'latitude':'-40.966667', 'longitude': '175.633333', 'name':'Masterton' },
'MRH': { 'latitude':'34.73416666', 'longitude': '-76.66027777', 'name':'May River' },
'MRI': { 'latitude':'61.2', 'longitude': '-149.833333', 'name':'Merrill Field' },
'MRJ': { 'latitude':'14.133333', 'longitude': '-88.033333', 'name':'Marcala' },
'MRK': { 'latitude':'25.933333', 'longitude': '-81.716667', 'name':'Marco Island' },
'MRD': { 'latitude':'8.583333', 'longitude': '-71.166667', 'name':'A Carnevalli' },
'MRE': { 'latitude':'-1.183333', 'longitude': '35.1', 'name':'Mara Lodges' },
'MRF': { 'latitude':'30.233333', 'longitude': '-103.866667', 'name':'Municipal' },
'MRG': { 'latitude':'-17.0', 'longitude': '145.433333', 'name':'Mareeba' },
'MRA': { 'latitude':'32.333333', 'longitude': '15.066667', 'name':'Misurata' },
'MRB': { 'latitude':'39.401667', 'longitude': '-77.984444', 'name':'Eastern Wv Regional Airport/Shepherd Field' },
'MRC': { 'latitude':'-10.75', 'longitude': '-67.866667', 'name':'Maury County' },
'APZ': { 'latitude':'-38.916667', 'longitude': '-70.083333', 'name':'Zapala' },
'APX': { 'latitude':'-23.383333', 'longitude': '-51.95', 'name':'Arapongas' },
'APY': { 'latitude':'-9.1', 'longitude': '-45.966667', 'name':'Alto Parnaiba' },
'APR': { 'latitude':'-4.3', 'longitude': '142.433333', 'name':'April River' },
'APS': { 'latitude':'-16.362222', 'longitude': '-48.926944', 'name':'Anapolis' },
'APQ': { 'latitude':'-9.75', 'longitude': '-36.65', 'name':'Arapiraca' },
'APV': { 'latitude':'34.575278', 'longitude': '-117.186111', 'name':'Apple Valley' },
'APW': { 'latitude':'-13.833333', 'longitude': '-172.0', 'name':'Faleolo' },
'APT': { 'latitude':'35.066667', 'longitude': '-85.633333', 'name':'Marion County' },
'APU': { 'latitude':'-23.55', 'longitude': '-51.483333', 'name':'Apucarana' },
'APK': { 'latitude':'-15.416667', 'longitude': '-146.083333', 'name':'Apataki' },
'APH': { 'latitude':'38.05', 'longitude': '-77.35', 'name':'Camp A P Hill' },
'API': { 'latitude':'4.068889', 'longitude': '-73.051944', 'name':'Apiay' },
'APN': { 'latitude':'45.083333', 'longitude': '-83.55', 'name':'Alpena County Regional' },
'APO': { 'latitude':'7.8119556', 'longitude': '-76.7164278', 'name':'Apartado' },
'APL': { 'latitude':'-15.1', 'longitude': '39.283333', 'name':'Nampula' },
'PQI': { 'latitude':'46.683333', 'longitude': '-68.05', 'name':'Municipal' },
'APB': { 'latitude':'-14.716667', 'longitude': '-68.5', 'name':'Apolo' },
'APC': { 'latitude':'38.45', 'longitude': '-122.216667', 'name':'Napa County' },
'APA': { 'latitude':'39.566667', 'longitude': '-104.833333', 'name':'Arapahoe Co' },
'APF': { 'latitude':'26.15', 'longitude': '-81.766667', 'name':'Naples' },
'APG': { 'latitude':'52.316667', 'longitude': '-1.283333', 'name':'Phillips AAF' },
'APE': { 'latitude':'-15.35', 'longitude': '-75.166667', 'name':'San Juan Aposento' },
'PQQ': { 'latitude':'-31.633333', 'longitude': '152.916667', 'name':'Port Macquarie' },
'PQT': { 'latitude':'71.283333', 'longitude': '-51.75', 'name':'Heliport' },
'KXK': { 'latitude':'50.4', 'longitude': '136.95', 'name':'Komsomolsk Na Amure' },
'KXA': { 'latitude':'55.5', 'longitude': '-132.5', 'name':'Kasaan SPB' },
'KXE': { 'latitude':'-26.966667', 'longitude': '26.65', 'name':'Klerksdorp' },
'KXF': { 'latitude':'-17.316667', 'longitude': '179.383333', 'name':'Koro Island' },
'KXR': { 'latitude':'-5.283333', 'longitude': '154.6', 'name':'Karoola' },
'KXU': { 'latitude':'-16.339444', 'longitude': '-144.403056', 'name':'Katiu' },
'YBS': { 'latitude':'-39.8', 'longitude': '176.683333', 'name':'Musselwhite' },
'YAY': { 'latitude':'51.366667', 'longitude': '-55.583333', 'name':'St Anthony' },
'YAX': { 'latitude':'53.251944', 'longitude': '-89.565', 'name':'Angling Lake' },
'YAZ': { 'latitude':'49.082222', 'longitude': '-125.7725', 'name':'Tofino Airport' },
'YAU': { 'latitude':'61.662778', 'longitude': '-73.321389', 'name':'Kattiniq/Donaldson' },
'YAT': { 'latitude':'52.927778', 'longitude': '-82.431389', 'name':'Attawapiskat' },
'YAW': { 'latitude':'44.639722', 'longitude': '-63.499444', 'name':'Shearwater' },
'YAV': { 'latitude':'48.866667', 'longitude': '-123.3', 'name':'Miners Bay' },
'YAQ': { 'latitude':'48.816667', 'longitude': '-1.6', 'name':'Maple Bay' },
'YAP': { 'latitude':'9.516667', 'longitude': '138.1', 'name':'Yap International' },
'YAS': { 'latitude':'-16.783333', 'longitude': '177.516667', 'name':'Yasawa Island' },
'YAR': { 'latitude':'53.55', 'longitude': '-76.2', 'name':'Lagrande 3' },
'YAM': { 'latitude':'46.483333', 'longitude': '-84.5', 'name':'Sault Ste Marie' },
'YAL': { 'latitude':'50.583333', 'longitude': '-126.933333', 'name':'Alert Bay' },
'YAO': { 'latitude':'3.833611', 'longitude': '11.523611', 'name':'Yaounde Airport' },
'YAN': { 'latitude':'0.8', 'longitude': '24.45', 'name':'Yangambi' },
'YAI': { 'latitude':'-36.566667', 'longitude': '-72.033333', 'name':'Chillan' },
'YAH': { 'latitude':'53.75', 'longitude': '-73.65', 'name':'Lagrande 4' },
'YAK': { 'latitude':'59.5', 'longitude': '-139.666667', 'name':'Yakutat' },
'YAJ': { 'latitude':'48.8', 'longitude': '-1.2', 'name':'Lyall Harbour' },
'YAE': { 'latitude':'50.116667', 'longitude': '-1.983333', 'name':'Alta Lake' },
'YAG': { 'latitude':'48.6', 'longitude': '-93.4', 'name':'Municipal' },
'YAF': { 'latitude':'45.766667', 'longitude': '-71.95', 'name':'Asbestos Hill' },
'YAA': { 'latitude':'52.466667', 'longitude': '-125.3', 'name':'Anahim Lake' },
'YAC': { 'latitude':'51.666667', 'longitude': '-91.833333', 'name':'Cat Lake' },
'YAB': { 'latitude':'73.037778', 'longitude': '-85.1525', 'name':'Arctic Bay' },
'CLL': { 'latitude':'30.588611', 'longitude': '-96.363889', 'name':'Easterwood Field' },
'CLO': { 'latitude':'3.4575', 'longitude': '-76.496389', 'name':'Alfonso B. Aragon' },
'CLI': { 'latitude':'43.6', 'longitude': '-81.533333', 'name':'Clintonville' },
'CLK': { 'latitude':'43.6', 'longitude': '-81.533333', 'name':'Municipal' },
'CLD': { 'latitude':'33.116667', 'longitude': '-117.266667', 'name':'Mc Clellan-Palomar Airport' },
'PDV': { 'latitude':'42.067778', 'longitude': '24.850833', 'name':'Plovdiv' },
'PDU': { 'latitude':'-32.366667', 'longitude': '-58.05', 'name':'Paysandu' },
'VCA': { 'latitude':'10.085', 'longitude': '105.711944', 'name':'Can Tho' },
'VCB': { 'latitude':'55.080556', 'longitude': '-133.016667', 'name':'View Cove' },
'PDT': { 'latitude':'45.7', 'longitude': '-118.833333', 'name':'Pendleton' },
'VCD': { 'latitude':'-16.405', 'longitude': '131.003333', 'name':'Victoria River Downs' },
'VCE': { 'latitude':'45.505278', 'longitude': '12.351944', 'name':'Marco Polo' },
'VCF': { 'latitude':'-40.7', 'longitude': '-66.15', 'name':'Valcheta' },
'VCH': { 'latitude':'-31.766667', 'longitude': '-54.616667', 'name':'Vichadero' },
'PDS': { 'latitude':'28.7', 'longitude': '-100.55', 'name':'Piedras Negras' },
'VCL': { 'latitude':'15.405833', 'longitude': '108.7', 'name':'Chulai' },
'CLA': { 'latitude':'23.433333', 'longitude': '91.183333', 'name':'Comilla' },
'VCP': { 'latitude':'-23.0075', 'longitude': '-47.134444', 'name':'Viracopos' },
'VCR': { 'latitude':'10.175556', 'longitude': '-70.065278', 'name':'Carora' },
'VCS': { 'latitude':'10.371389', 'longitude': '106.633333', 'name':'Con Dao' },
'VCT': { 'latitude':'28.85', 'longitude': '-96.916667', 'name':'County-Foster' },
'CLB': { 'latitude':'53.848333', 'longitude': '-9.280278', 'name':'Castlebar' },
'VCV': { 'latitude':'34.5975', 'longitude': '-117.383056', 'name':'Southern California Logistics' },
'CLC': { 'latitude':'29.5575', 'longitude': '-95.139167', 'name':'Metroport' },
'WKI': { 'latitude':'-18.366667', 'longitude': '26.483333', 'name':'Hwange' },
'WKK': { 'latitude':'59.266667', 'longitude': '-158.633333', 'name':'Aleknagik' },
'WKJ': { 'latitude':'45.4', 'longitude': '141.816667', 'name':'Hokkaido' },
'WKL': { 'latitude':'19.916667', 'longitude': '-155.866667', 'name':'Waikoloa Airport' },
'PDN': { 'latitude':'-35.8', 'longitude': '137.216667', 'name':'Parndana' },
'WKA': { 'latitude':'-44.733333', 'longitude': '169.25', 'name':'Wanaka' },
'WKB': { 'latitude':'-36.333333', 'longitude': '142.25', 'name':'Warracknabeal' },
'WKF': { 'latitude':'-25.83', 'longitude': '28.2225', 'name':'Waterkloof AFB' },
'PDK': { 'latitude':'33.875556', 'longitude': '-84.301944', 'name':'Dekalb-Peachtree' },
'CLY': { 'latitude':'42.533333', 'longitude': '8.8', 'name':'Ste Catherine' },
'PDI': { 'latitude':'-6.5', 'longitude': '147.583333', 'name':'Pindiu' },
'PDG': { 'latitude':'-0.786944', 'longitude': '100.280556', 'name':'Minangkabau International Airport' },
'PDF': { 'latitude':'-17.35', 'longitude': '-39.216667', 'name':'Prado' },
'PDE': { 'latitude':'-26.133333', 'longitude': '139.383333', 'name':'Pandie Pandie' },
'IMZ': { 'latitude':'31.1', 'longitude': '61.933333', 'name':'Nimroz' },
'PDC': { 'latitude':'-21.35', 'longitude': '165.0', 'name':'Mueo' },
'PDB': { 'latitude':'59.783333', 'longitude': '-154.116667', 'name':'Pedro Bay' },
'PDA': { 'latitude':'4.016667', 'longitude': '-67.716667', 'name':'Puerto Inirida' },
'ZXP': { 'latitude':'56.4', 'longitude': '-3.433333', 'name':'ScotRail' },
'ZXS': { 'latitude':'42.878333', 'longitude': '-78.875278', 'name':'Exchangest Railway Svc' },
'ZXT': { 'latitude':'40.45', 'longitude': '50.066667', 'name':'Heydar Aliyev' },
'DMB': { 'latitude':'42.9', 'longitude': '71.366667', 'name':'Zhambyl' },
'DMD': { 'latitude':'-18.0', 'longitude': '138.833333', 'name':'Doomadgee' },
'DME': { 'latitude':'55.419444', 'longitude': '37.885833', 'name':'Domodedovo' },
'DMK': { 'latitude':'13.9125', 'longitude': '100.606667', 'name':'Don Muang' },
'DMM': { 'latitude':'26.471111', 'longitude': '49.797778', 'name':'King Fahd International Airport' },
'DMN': { 'latitude':'26.951667', 'longitude': '108.578889', 'name':'Deming' },
'DMO': { 'latitude':'38.833333', 'longitude': '-93.416667', 'name':'Sedalia' },
'DMR': { 'latitude':'14.533333', 'longitude': '44.433333', 'name':'Dhamar' },
'DMT': { 'latitude':'-14.416667', 'longitude': '-56.45', 'name':'Diamantino' },
'DMU': { 'latitude':'25.9', 'longitude': '93.733333', 'name':'Dimapur' },
'ZEM': { 'latitude':'52.25', 'longitude': '-78.516667', 'name':'East Main' },
'XRH': { 'latitude':'48.166667', 'longitude': '-65.833333', 'name':'Richmond AFB' },
'XRJ': { 'latitude':'41.966667', 'longitude': '12.666667', 'name':'Termini Rail Stn.' },
'XRF': { 'latitude':'47.066667', 'longitude': '3.0', 'name':'Marseille Railway' },
'XRY': { 'latitude':'36.744722', 'longitude': '-6.06', 'name':'Jerez De La Frontera' },
'XRR': { 'latitude':'61.983333', 'longitude': '-132.45', 'name':'Ross River' },
'PSJ': { 'latitude':'-1.383333', 'longitude': '120.733333', 'name':'Poso' },
'PSK': { 'latitude':'37.116667', 'longitude': '-80.683333', 'name':'New River Valley' },
'PSH': { 'latitude':'54.316667', 'longitude': '8.683333', 'name':'St Peter' },
'PSI': { 'latitude':'25.3', 'longitude': '63.366667', 'name':'Pasni' },
'PSN': { 'latitude':'31.779722', 'longitude': '-95.706389', 'name':'Palestine Municipal Airport' },
'JLP': { 'latitude':'43.566667', 'longitude': '7.1', 'name':'Juan Les Pins' },
'PSL': { 'latitude':'56.4', 'longitude': '-3.466667', 'name':'Perth' },
'JLR': { 'latitude':'22.666667', 'longitude': '79.925', 'name':'Jabalpur' },
'PSB': { 'latitude':'60.933333', 'longitude': '7.2', 'name':'Bellefonte' },
'PSC': { 'latitude':'46.264722', 'longitude': '-119.119167', 'name':'Tri-cities' },
'PSA': { 'latitude':'43.683333', 'longitude': '10.4', 'name':'Galileo Galilei' },
'PSF': { 'latitude':'42.433333', 'longitude': '-73.3', 'name':'Pittsfield' },
'PSG': { 'latitude':'56.8', 'longitude': '-132.983333', 'name':'Petersburg James A Johnson' },
'PSD': { 'latitude':'31.283333', 'longitude': '32.233333', 'name':'Port Said' },
'PSE': { 'latitude':'17.983333', 'longitude': '-66.4', 'name':'Mercedita' },
'PSZ': { 'latitude':'-18.966667', 'longitude': '-57.866667', 'name':'Puerto Suarez' },
'JLD': { 'latitude':'56.305556', 'longitude': '12.85', 'name':'Heliport' },
'PSX': { 'latitude':'28.7', 'longitude': '-96.216667', 'name':'Palacios' },
'PSY': { 'latitude':'-51.75', 'longitude': '-59.0', 'name':'Port Stanley' },
'JLA': { 'latitude':'60.483333', 'longitude': '-149.85', 'name':'Quartz Creek' },
'JLB': { 'latitude':'-53.2', 'longitude': '73.483333', 'name':'Heliport' },
'PSR': { 'latitude':'42.466667', 'longitude': '14.216667', 'name':'Liberi' },
'PSS': { 'latitude':'-27.416667', 'longitude': '-55.95', 'name':'Posadas' },
'JLO': { 'latitude':'45.5', 'longitude': '12.6', 'name':'Jesolo' },
'JLN': { 'latitude':'37.151944', 'longitude': '-94.498333', 'name':'Joplin Regional' },
'JLH': { 'latitude':'-6.3', 'longitude': '155.833333', 'name':'US Army Heliport' },
'PST': { 'latitude':'20.75', 'longitude': '-75.65', 'name':'Preston' },
'PSU': { 'latitude':'0.833333', 'longitude': '112.933333', 'name':'Putussibau' },
'BCL': { 'latitude':'10.783333', 'longitude': '-83.583333', 'name':'Barra Colorado' },
'BCM': { 'latitude':'46.6', 'longitude': '26.883333', 'name':'Bacau' },
'BCN': { 'latitude':'41.3', 'longitude': '2.083333', 'name':'El Prat De Llobregat' },
'BCO': { 'latitude':'5.783333', 'longitude': '36.55', 'name':'Jinka' },
'BCH': { 'latitude':'-8.485556', 'longitude': '126.399444', 'name':'Cakung International' },
'BCI': { 'latitude':'-23.666667', 'longitude': '145.333333', 'name':'Barcaldine' },
'BCJ': { 'latitude':'37.966667', 'longitude': '-105.766667', 'name':'Baca Grande' },
'BCK': { 'latitude':'-17.4', 'longitude': '144.166667', 'name':'Bolwarra' },
'BCD': { 'latitude':'10.633333', 'longitude': '122.933333', 'name':'Bacolod' },
'BCE': { 'latitude':'37.7', 'longitude': '-112.15', 'name':'Bryce' },
'BCF': { 'latitude':'6.5', 'longitude': '18.283333', 'name':'Bouca' },
'BCG': { 'latitude':'7.7', 'longitude': '-59.166667', 'name':'Bemichi' },
'HNM': { 'latitude':'20.8', 'longitude': '-156.016667', 'name':'Hana' },
'BCA': { 'latitude':'20.25', 'longitude': '-74.35', 'name':'Baracoa' },
'BCB': { 'latitude':'37.233333', 'longitude': '-80.416667', 'name':'Virginia Tech' },
'BCC': { 'latitude':'57.6175', 'longitude': '-155.867222', 'name':'Bear Creek' },
'HNS': { 'latitude':'59.25', 'longitude': '-135.516667', 'name':'Municipal' },
'BCX': { 'latitude':'53.933333', 'longitude': '58.333333', 'name':'Beloreck' },
'BCY': { 'latitude':'6.216667', 'longitude': '36.666667', 'name':'Bulchi' },
'BCZ': { 'latitude':'-13.783333', 'longitude': '137.8', 'name':'Bickerton Island' },
'BCT': { 'latitude':'26.366667', 'longitude': '-80.116667', 'name':'Public' },
'BCU': { 'latitude':'10.316667', 'longitude': '9.833333', 'name':'Bauchi' },
'BCV': { 'latitude':'17.25', 'longitude': '-88.766667', 'name':'Belmopan' },
'BCW': { 'latitude':'-23.733333', 'longitude': '35.116667', 'name':'Benguera Island' },
'BCP': { 'latitude':'5.866667', 'longitude': '35.283333', 'name':'Bambu' },
'BCQ': { 'latitude':'-22.783333', 'longitude': '17.466667', 'name':'Brack' },
'BCR': { 'latitude':'-8.633333', 'longitude': '-67.416667', 'name':'Boca Do Acre' },
'BCS': { 'latitude':'30.05', 'longitude': '-90.233333', 'name':'Southern Seaplane' },
'SRB': { 'latitude':'-14.166667', 'longitude': '-66.883333', 'name':'Santa Rosa' },
'SRC': { 'latitude':'35.25', 'longitude': '-91.733333', 'name':'Searcy' },
'SRA': { 'latitude':'-27.866667', 'longitude': '-54.483333', 'name':'Santa Rosa' },
'SRF': { 'latitude':'8.45', 'longitude': '-73.916667', 'name':'Hamilton Field' },
'SRG': { 'latitude':'-6.983333', 'longitude': '110.383333', 'name':'Achmad Yani' },
'SRD': { 'latitude':'-13.283333', 'longitude': '-64.7', 'name':'San Ramon' },
'SRE': { 'latitude':'-19.006944', 'longitude': '-65.288611', 'name':'Juana Azurduy de Padilla' },
'SRJ': { 'latitude':'-14.816667', 'longitude': '-66.833333', 'name':'Capitan G Q Guardia' },
'SRK': { 'latitude':'8.5', 'longitude': '-13.508333', 'name':'Sierra Leone' },
'SRH': { 'latitude':'9.15', 'longitude': '18.383333', 'name':'Sarh' },
'SRI': { 'latitude':'-0.5', 'longitude': '117.15', 'name':'Samarinda' },
'SRN': { 'latitude':'-42.15', 'longitude': '145.3', 'name':'Strahan' },
'SRO': { 'latitude':'2.216667', 'longitude': '-75.25', 'name':'Santana Ramos' },
'SRL': { 'latitude':'27.333333', 'longitude': '-112.266667', 'name':'Santa Rosalia' },
'SRM': { 'latitude':'-24.05', 'longitude': '139.066667', 'name':'Sandringham' },
'SRR': { 'latitude':'47.266667', 'longitude': '10.783333', 'name':'Dunwich' },
'SRS': { 'latitude':'8.666667', 'longitude': '-75.133333', 'name':'Cartagena' },
'SRP': { 'latitude':'59.792778', 'longitude': '5.339722', 'name':'Stord Airport' },
'SRQ': { 'latitude':'27.395556', 'longitude': '-82.554444', 'name':'Sarasota-Bradenton International Airport' },
'SRV': { 'latitude':'61.783333', 'longitude': '-156.583333', 'name':'Stony River' },
'SRW': { 'latitude':'35.633333', 'longitude': '-80.516667', 'name':'Rowan County' },
'SRT': { 'latitude':'1.716667', 'longitude': '33.616667', 'name':'Soroti' },
'SRU': { 'latitude':'2.166667', 'longitude': '-76.1', 'name':'Skypark' },
'SRZ': { 'latitude':'-17.8', 'longitude': '-63.166667', 'name':'El Trompillo' },
'SRX': { 'latitude':'30.833333', 'longitude': '16.0', 'name':'Sert' },
'SRY': { 'latitude':'36.616667', 'longitude': '53.183333', 'name':'Dashte Naz' },
'NOI': { 'latitude':'44.75', 'longitude': '37.75', 'name':'Novorossijsk' },
'TDK': { 'latitude':'45.015556', 'longitude': '78.373889', 'name':'Taldy-Kurgan' },
'TDJ': { 'latitude':'11.785278', 'longitude': '42.884444', 'name':'Tadjoura' },
'NMT': { 'latitude':'23.083333', 'longitude': '97.4', 'name':'Namtu' },
'NMU': { 'latitude':'8.0', 'longitude': '168.166667', 'name':'Namu' },
'NMR': { 'latitude':'-27.633333', 'longitude': '141.083333', 'name':'Nappa Merry' },
'NMS': { 'latitude':'20.883333', 'longitude': '97.75', 'name':'Namsang' },
'NMP': { 'latitude':'-20.166667', 'longitude': '143.966667', 'name':'New Moon' },
'TDL': { 'latitude':'-37.233333', 'longitude': '-59.216667', 'name':'Tandil' },
'TDB': { 'latitude':'-0.8', 'longitude': '174.466667', 'name':'Tetabedi' },
'TDA': { 'latitude':'5.416667', 'longitude': '-71.666667', 'name':'Trinidad' },
'TDG': { 'latitude':'9.083333', 'longitude': '126.083333', 'name':'Tandag' },
'TDD': { 'latitude':'-14.683333', 'longitude': '-64.833333', 'name':'Trinidad' },
'NMG': { 'latitude':'8.45', 'longitude': '-78.916667', 'name':'San Miguel' },
'NME': { 'latitude':'60.483333', 'longitude': '-164.0', 'name':'Nightmute' },
'NMB': { 'latitude':'20.416667', 'longitude': '72.85', 'name':'Daman' },
'NMA': { 'latitude':'40.983333', 'longitude': '71.6', 'name':'Namangan' },
'NMN': { 'latitude':'-6.316667', 'longitude': '145.066667', 'name':'Nomane' },
'TDR': { 'latitude':'51.433333', 'longitude': '-1.916667', 'name':'Theodore' },
'TDW': { 'latitude':'35.166667', 'longitude': '-101.833333', 'name':'Tradewind' },
'TDV': { 'latitude':'-16.116667', 'longitude': '45.466667', 'name':'Tanandava' },
'TDT': { 'latitude':'-24.283333', 'longitude': '31.3', 'name':'Tanda Tula' },
'LOC': { 'latitude':'-33.566667', 'longitude': '135.766667', 'name':'Lock' },
'HLT': { 'latitude':'-37.65', 'longitude': '142.066667', 'name':'Hamilton' },
'LOF': { 'latitude':'7.8', 'longitude': '168.283333', 'name':'Loen' },
'LOG': { 'latitude':'46.116667', 'longitude': '-122.883333', 'name':'Longview' },
'LOD': { 'latitude':'-15.366667', 'longitude': '167.95', 'name':'Longana' },
'LOE': { 'latitude':'17.45', 'longitude': '101.733333', 'name':'Loei' },
'LOK': { 'latitude':'3.15', 'longitude': '35.6', 'name':'Lodwar' },
'LOH': { 'latitude':'-3.993611', 'longitude': '-79.373611', 'name':'Loja' },
'LOI': { 'latitude':'-4.383333', 'longitude': '-51.916667', 'name':'Helmuth Baungartem' },
'LOO': { 'latitude':'33.833333', 'longitude': '2.983333', 'name':'Laghouat' },
'LOL': { 'latitude':'40.058333', 'longitude': '-118.566667', 'name':'Derby Field' },
'NOA': { 'latitude':'-34.933333', 'longitude': '150.566667', 'name':'Nowra' },
'LOR': { 'latitude':'53.116667', 'longitude': '22.45', 'name':'Lowe Army Heliport' },
'LOS': { 'latitude':'6.5775', 'longitude': '3.321111', 'name':'Murtala Muhammed' },
'LOP': { 'latitude':'-8.75914', 'longitude': '116.27655', 'name':'Lombok International Airport' },
'LOQ': { 'latitude':'-25.2', 'longitude': '25.666667', 'name':'Lobatse' },
'LOV': { 'latitude':'26.95', 'longitude': '-101.483333', 'name':'Monclova' },
'LOT': { 'latitude':'41.6', 'longitude': '-88.05', 'name':'Lewis Lockport' },
'FHZ': { 'latitude':'-16.0', 'longitude': '-140.0', 'name':'Fakahina' },
'FHU': { 'latitude':'31.588333', 'longitude': '-110.344444', 'name':'Municipal' },
'HLP': { 'latitude':'-6.266667', 'longitude': '106.883333', 'name':'Halim Perdana Kusuma' },
'TJS': { 'latitude':'-0.3', 'longitude': '100.6', 'name':'Tanjung Selor' },
'OUN': { 'latitude':'35.158333', 'longitude': '-97.466667', 'name':'Max Westheimer' },
'NOZ': { 'latitude':'53.75', 'longitude': '87.1', 'name':'Novokuznetsk' },
'TJV': { 'latitude':'10.7225', 'longitude': '79.101667', 'name':'Thanjavur' },
'NOT': { 'latitude':'38.1', 'longitude': '-122.566667', 'name':'Novato' },
'NOU': { 'latitude':'-22.266667', 'longitude': '166.45', 'name':'Tontouta' },
'EBD': { 'latitude':'13.166667', 'longitude': '30.25', 'name':'El Obeid' },
'EBG': { 'latitude':'7.616667', 'longitude': '-74.816667', 'name':'El Bagre' },
'EBA': { 'latitude':'42.766667', 'longitude': '10.283333', 'name':'Marina Di Campo' },
'EBB': { 'latitude':'0.060278', 'longitude': '32.45', 'name':'Entebbe' },
'EBL': { 'latitude':'36.2375', 'longitude': '43.963056', 'name':'Erbil International' },
'EBM': { 'latitude':'31.717222', 'longitude': '9.267222', 'name':'El Borma' },
'EBN': { 'latitude':'9.333333', 'longitude': '166.8', 'name':'Ebadon' },
'EBJ': { 'latitude':'55.5', 'longitude': '8.483333', 'name':'Esbjerg' },
'EBU': { 'latitude':'45.5', 'longitude': '4.5', 'name':'Boutheon' },
'EBW': { 'latitude':'2.85', 'longitude': '11.183333', 'name':'Ebolowa' },
'NOR': { 'latitude':'65.15', 'longitude': '-13.7', 'name':'Nordfjordur' },
'EBR': { 'latitude':'6.45', 'longitude': '17.366667', 'name':'Downtown' },
'EBS': { 'latitude':'42.466667', 'longitude': '-93.8', 'name':'Municipal' },
'RJN': { 'latitude':'30.297778', 'longitude': '56.051111', 'name':'Rafsanjan' },
'RJL': { 'latitude':'42.456944', 'longitude': '-2.323611', 'name':'Logrono' },
'RJK': { 'latitude':'45.333333', 'longitude': '14.591667', 'name':'Rijeka' },
'RJI': { 'latitude':'33.368611', 'longitude': '74.3025', 'name':'Rajouri' },
'RJH': { 'latitude':'24.416667', 'longitude': '88.508333', 'name':'Rajshahi' },
'DRS': { 'latitude':'51.133333', 'longitude': '13.766667', 'name':'Dresden Arpt' },
'DRR': { 'latitude':'-25.6', 'longitude': '140.25', 'name':'Durrie' },
'DRU': { 'latitude':'46.616667', 'longitude': '-113.2', 'name':'Drummond' },
'DRT': { 'latitude':'29.366667', 'longitude': '-100.916667', 'name':'International' },
'DRW': { 'latitude':'-12.416667', 'longitude': '130.866667', 'name':'Darwin' },
'DRI': { 'latitude':'53.2', 'longitude': '5.45', 'name':'Beauregard Parish' },
'DRH': { 'latitude':'-2.8', 'longitude': '138.316667', 'name':'Dabra' },
'DRK': { 'latitude':'8.7294444444', 'longitude': '-83.6469444444', 'name':'Drake Bay Airport' },
'DRM': { 'latitude':'41.15', 'longitude': '24.133333', 'name':'Drama' },
'DRO': { 'latitude':'37.15', 'longitude': '-107.75', 'name':'La Plata' },
'DRN': { 'latitude':'-28.5', 'longitude': '148.258333', 'name':'Dirranbandi' },
'DRA': { 'latitude':'-29.133333', 'longitude': '29.733333', 'name':'Desert Rock' },
'DRC': { 'latitude':'-17.966667', 'longitude': '20.783333', 'name':'Dirico' },
'DRB': { 'latitude':'-17.366667', 'longitude': '123.65', 'name':'Derby' },
'DRE': { 'latitude':'46.016667', 'longitude': '-83.75', 'name':'Drummond Island' },
'DRD': { 'latitude':'-16.516667', 'longitude': '142.366667', 'name':'Dorunda Station' },
'DRG': { 'latitude':'66.083333', 'longitude': '-162.766667', 'name':'Deering' },
'DRF': { 'latitude':'60.583333', 'longitude': '-152.15', 'name':'Drift River' },
'VNX': { 'latitude':'-22.033333', 'longitude': '35.3', 'name':'Vilanculos' },
'CXP': { 'latitude':'7.733333', 'longitude': '109.0', 'name':'Tunggul Wulung' },
'CXQ': { 'latitude':'-18.916667', 'longitude': '125.916667', 'name':'Christmas Creek' },
'CXR': { 'latitude':'12.2275', 'longitude': '109.192222', 'name':'Nha Trang' },
'CXT': { 'latitude':'-20.05', 'longitude': '146.266667', 'name':'Charters Towers' },
'CXY': { 'latitude':'24.315', 'longitude': '-75.453611', 'name':'Cat Cays' },
'CXA': { 'latitude':'7.626111', 'longitude': '-66.165', 'name':'Caicara Del Orinoco' },
'CXB': { 'latitude':'21.45', 'longitude': '91.966667', 'name':'Cox\'s Bazar' },
'CXC': { 'latitude':'61.566667', 'longitude': '-144.416667', 'name':'Chitina Arpt' },
'CXF': { 'latitude':'67.266667', 'longitude': '-150.166667', 'name':'Coldfoot' },
'CXH': { 'latitude':'49.289722', 'longitude': '-123.115833', 'name':'Coal Harbour' },
'CXI': { 'latitude':'1.986111', 'longitude': '-157.349722', 'name':'Cassidy International Airport' },
'CXJ': { 'latitude':'-29.196944', 'longitude': '-51.1875', 'name':'Campo Dos Bugres' },
'CXL': { 'latitude':'32.666667', 'longitude': '-115.516667', 'name':'International' },
'CXN': { 'latitude':'11.833333', 'longitude': '49.958333', 'name':'Candala' },
'CXO': { 'latitude':'30.316667', 'longitude': '-95.45', 'name':'Montgomery Co' },
'GOM': { 'latitude':'-1.670833', 'longitude': '29.238333', 'name':'Goma' },
'AJY': { 'latitude':'16.966667', 'longitude': '7.983333', 'name':'Agades' },
'MLA': { 'latitude':'35.866667', 'longitude': '14.483333', 'name':'Malta International' },
'GOI': { 'latitude':'15.5', 'longitude': '73.841667', 'name':'Dabolim' },
'MLG': { 'latitude':'-7.926667', 'longitude': '112.708889', 'name':'Abdul Rahman Saleh' },
'GOK': { 'latitude':'35.883333', 'longitude': '-97.416667', 'name':'Guthrie' },
'GOJ': { 'latitude':'56.333333', 'longitude': '44.0', 'name':'Nizhniy Novgorod' },
'MLJ': { 'latitude':'33.15', 'longitude': '-83.25', 'name':'Baldwin County' },
'GOG': { 'latitude':'-22.140278', 'longitude': '19.072222', 'name':'Gobabis' },
'GOF': { 'latitude':'43.816667', 'longitude': '12.8', 'name':'Goodfellow AFB' },
'GOA': { 'latitude':'44.43', 'longitude': '8.8375', 'name':'Cristoforo Colombo' },
'AJU': { 'latitude':'-10.983611', 'longitude': '-37.067778', 'name':'Santa Maria' },
'GOC': { 'latitude':'-8.416667', 'longitude': '147.666667', 'name':'Gora' },
'MLM': { 'latitude':'19.7', 'longitude': '-101.2', 'name':'Francisco J. Múgica Internacional' },
'MPF': { 'latitude':'-7.966667', 'longitude': '143.166667', 'name':'Mapoda' },
'MPG': { 'latitude':'-6.533333', 'longitude': '147.716667', 'name':'Makini' },
'MPD': { 'latitude':'25.533333', 'longitude': '69.016667', 'name':'Mirpur Khas' },
'MPE': { 'latitude':'41.283333', 'longitude': '-72.6', 'name':'Griswold' },
'AVX': { 'latitude':'33.333333', 'longitude': '-118.35', 'name':'Avalon Bay' },
'MPC': { 'latitude':'-2.55', 'longitude': '101.1', 'name':'Muko-Muko' },
'AJI': { 'latitude':'39.65', 'longitude': '43.033333', 'name':'A?ri' },
'MPN': { 'latitude':'-51.822778', 'longitude': '-58.447222', 'name':'Mount Pleasant' },
'AVU': { 'latitude':'-9.85', 'longitude': '160.416667', 'name':'Avu Avu' },
'AVV': { 'latitude':'-38.033333', 'longitude': '144.466667', 'name':'Avalon' },
'MPM': { 'latitude':'-25.916667', 'longitude': '32.566667', 'name':'Maputo International' },
'AVP': { 'latitude':'41.338333', 'longitude': '-75.723333', 'name':'Wilkes-Barre/Scranton International Airport' },
'AJJ': { 'latitude':'19.733333', 'longitude': '-14.383333', 'name':'Akjoujt' },
'MPH': { 'latitude':'11.925833', 'longitude': '121.952222', 'name':'Malay' },
'MPI': { 'latitude':'9.578333', 'longitude': '-79.843056', 'name':'Mamitupo' },
'AVL': { 'latitude':'35.436111', 'longitude': '-82.541667', 'name':'Asheville Regional Airport' },
'MPW': { 'latitude':'47.1', 'longitude': '37.55', 'name':'Mariupol' },
'AVN': { 'latitude':'43.906667', 'longitude': '4.901944', 'name':'Avignon-Caumont' },
'AVO': { 'latitude':'27.6', 'longitude': '-81.516667', 'name':'Municipal' },
'MPR': { 'latitude':'38.35', 'longitude': '-97.683333', 'name':'Mcpherson' },
'AVI': { 'latitude':'22.025', 'longitude': '-78.791389', 'name':'Maximo Gomez' },
'MPP': { 'latitude':'8.933333', 'longitude': '-77.766667', 'name':'Mulatupo' },
'AVK': { 'latitude':'46.266667', 'longitude': '102.783333', 'name':'Arvaikheer' },
'GOY': { 'latitude':'7.333333', 'longitude': '81.616667', 'name':'Amparai' },
'AVF': { 'latitude':'46.2', 'longitude': '6.766667', 'name':'Avoriaz' },
'AVG': { 'latitude':'-15.75', 'longitude': '129.916667', 'name':'Auvergne' },
'MPZ': { 'latitude':'40.966667', 'longitude': '-91.55', 'name':'Municipal' },
'AVA': { 'latitude':'33.216667', 'longitude': '120.95', 'name':'An Shun/Huang Guo Shu' },
'AVB': { 'latitude':'46.066667', 'longitude': '12.6', 'name':'Aviano' },
'MPY': { 'latitude':'3.666667', 'longitude': '-54.033333', 'name':'Maripasoula' },
'AJN': { 'latitude':'-12.133333', 'longitude': '44.433333', 'name':'Ouani' },
'GOZ': { 'latitude':'43.151389', 'longitude': '25.712778', 'name':'Gorna Oriahovitsa' },
'DEZ': { 'latitude':'35.333333', 'longitude': '40.15', 'name':'Al Jafrah' },
'GOU': { 'latitude':'9.333333', 'longitude': '13.366667', 'name':'Garoua' },
'AJA': { 'latitude':'41.916667', 'longitude': '8.8', 'name':'Campo Dell Oro' },
'GOV': { 'latitude':'-12.166667', 'longitude': '136.675', 'name':'Nhulunbuy' },
'WHU': { 'latitude':'-2.533333', 'longitude': '24.966667', 'name':'Wuhu' },
'AJF': { 'latitude':'29.933333', 'longitude': '40.2', 'name':'Jouf' },
'PJG': { 'latitude':'26.95', 'longitude': '64.133333', 'name':'Panjgur' },
'DES': { 'latitude':'-4.999722', 'longitude': '55.016667', 'name':'Desroches' },
'DET': { 'latitude':'42.409167', 'longitude': '-83.009722', 'name':'Detroit City' },
'KZS': { 'latitude':'36.133333', 'longitude': '29.566667', 'name':'Kastelorizo' },
'NRL': { 'latitude':'59.366667', 'longitude': '-2.433333', 'name':'North Ronaldsay' },
'KZB': { 'latitude':'57.55', 'longitude': '-153.75', 'name':'Zachar Bay SPB' },
'KZC': { 'latitude':'12.233333', 'longitude': '104.666667', 'name':'Kompong-Chhna' },
'KZF': { 'latitude':'-7.8', 'longitude': '145.883333', 'name':'Kaintiba' },
'KZG': { 'latitude':'49.733333', 'longitude': '10.2', 'name':'Kitzingen' },
'KZD': { 'latitude':'12.533333', 'longitude': '104.15', 'name':'Krakor' },
'XGG': { 'latitude':'14.433333', 'longitude': '-0.233333', 'name':'Gorom-Gorom' },
'KZK': { 'latitude':'12.716667', 'longitude': '104.9', 'name':'Kompong Thom' },
'KZH': { 'latitude':'57.583333', 'longitude': '-153.15', 'name':'Kizhuyak' },
'KZI': { 'latitude':'40.283333', 'longitude': '21.833333', 'name':'Philippos Airport' },
'KZN': { 'latitude':'55.8', 'longitude': '49.0', 'name':'Kazan' },
'KZO': { 'latitude':'44.852778', 'longitude': '65.509167', 'name':'Kzyl-Orda' },
'DEO': { 'latitude':'42.312778', 'longitude': '-83.218889', 'name':'Hyatt Regency H/P' },
'DEA': { 'latitude':'29.961111', 'longitude': '70.485833', 'name':'Dera Ghazi Khan' },
'XGA': { 'latitude':'10.333333', 'longitude': '-3.183333', 'name':'Gaoua' },
'NZW': { 'latitude':'42.166667', 'longitude': '-70.95', 'name':'South Weymouth' },
'YGG': { 'latitude':'48.85', 'longitude': '-123.5', 'name':'Ganges Harbor' },
'YGE': { 'latitude':'50.083333', 'longitude': '-124.95', 'name':'Gorge Harbor' },
'YGC': { 'latitude':'51.2', 'longitude': '-96.45', 'name':'Grande Cache' },
'YGB': { 'latitude':'49.7', 'longitude': '-124.533333', 'name':'Gillies Bay' },
'YGA': { 'latitude':'51.95', 'longitude': '-68.133333', 'name':'Gagnon' },
'YGO': { 'latitude':'54.55', 'longitude': '-94.483333', 'name':'Gods Narrows' },
'YGN': { 'latitude':'50.85', 'longitude': '-126.85', 'name':'Greenway Sound' },
'YGM': { 'latitude':'50.633333', 'longitude': '-96.983333', 'name':'Gimli' },
'YGL': { 'latitude':'53.583333', 'longitude': '-77.683333', 'name':'La Grande' },
'YGK': { 'latitude':'44.233333', 'longitude': '-76.583333', 'name':'Kingston' },
'YGJ': { 'latitude':'35.45', 'longitude': '133.316667', 'name':'Miho' },
'YGH': { 'latitude':'66.266667', 'longitude': '-128.65', 'name':'Fort Good Hope' },
'YGW': { 'latitude':'55.266667', 'longitude': '-77.783333', 'name':'Kuujjuarapik' },
'YGV': { 'latitude':'50.25', 'longitude': '-63.583333', 'name':'Havre St Pierre' },
'YGT': { 'latitude':'69.4', 'longitude': '-81.816667', 'name':'Igloolik' },
'YGS': { 'latitude':'55.616667', 'longitude': '-124.833333', 'name':'Germansen' },
'YGR': { 'latitude':'47.416667', 'longitude': '-61.866667', 'name':'Iles De La Madeleine' },
'YGQ': { 'latitude':'49.733333', 'longitude': '-86.95', 'name':'Geraldton' },
'YGP': { 'latitude':'48.775278', 'longitude': '-64.478611', 'name':'Gaspe' },
'YGZ': { 'latitude':'76.425', 'longitude': '-82.945833', 'name':'Grise Fiord' },
'YGY': { 'latitude':'62.116667', 'longitude': '-74.616667', 'name':'Deception' },
'YGX': { 'latitude':'56.35', 'longitude': '-94.716667', 'name':'Gillam' },
'LMX': { 'latitude':'3.05', 'longitude': '-77.55', 'name':'Lopez De Micay' },
'VAH': { 'latitude':'41.616667', 'longitude': '13.866667', 'name':'Vallegrande' },
'VAI': { 'latitude':'-2.683333', 'longitude': '141.3', 'name':'Vanimo' },
'VAN': { 'latitude':'38.45', 'longitude': '43.316667', 'name':'Ferit Melen Airport' },
'VAO': { 'latitude':'-7.566667', 'longitude': '158.666667', 'name':'Suavanao' },
'VAL': { 'latitude':'-13.366667', 'longitude': '-39.066667', 'name':'Valenca' },
'VAB': { 'latitude':'1.116667', 'longitude': '-70.75', 'name':'Yavarate' },
'VAC': { 'latitude':'52.616667', 'longitude': '8.733333', 'name':'Varrelbusch' },
'VAA': { 'latitude':'63.05', 'longitude': '21.766667', 'name':'Vaasa' },
'VAF': { 'latitude':'44.916667', 'longitude': '4.966667', 'name':'Chabeuil' },
'RLO': { 'latitude':'-32.35', 'longitude': '-65.033333', 'name':'Valle Del Conlara' },
'VAD': { 'latitude':'46.286111', 'longitude': '12.437778', 'name':'Moody AFB' },
'VAR': { 'latitude':'43.2325', 'longitude': '27.825556', 'name':'Varna' },
'VAS': { 'latitude':'39.766667', 'longitude': '37.016667', 'name':'Sivas' },
'VAP': { 'latitude':'-33.05', 'longitude': '-71.416667', 'name':'Valparaiso' },
'VAW': { 'latitude':'70.355278', 'longitude': '31.045', 'name':'Vardoe' },
'VAT': { 'latitude':'-19.283333', 'longitude': '48.833333', 'name':'Vatomandry' },
'VAU': { 'latitude':'-17.5', 'longitude': '177.841667', 'name':'Vatukoula' },
'WUS': { 'latitude':'27.716667', 'longitude': '117.966667', 'name':'Wuyishan' },
'WUV': { 'latitude':'-1.75', 'longitude': '142.833333', 'name':'Wuvulu Is' },
'WUU': { 'latitude':'7.733333', 'longitude': '27.983333', 'name':'Wau' },
'WUZ': { 'latitude':'23.5', 'longitude': '111.333333', 'name':'Changzhoudao' },
'WUX': { 'latitude':'31.494444', 'longitude': '120.429444', 'name':'Wuxi' },
'WUA': { 'latitude':'39.794722', 'longitude': '106.799167', 'name':'Wu Hai' },
'WUG': { 'latitude':'-3.783333', 'longitude': '143.883333', 'name':'Wau' },
'LMQ': { 'latitude':'30.5', 'longitude': '19.166667', 'name':'Marsa Brega' },
'WUK': { 'latitude':'52.95', 'longitude': '-2.833333', 'name':'Off Line Point' },
'WUH': { 'latitude':'30.783889', 'longitude': '114.208056', 'name':'Tianhe International' },
'RLG': { 'latitude':'54.118333', 'longitude': '12.125278', 'name':'Laage' },
'NZY': { 'latitude':'32.699167', 'longitude': '-117.215278', 'name':'North Island Nas' },
'LMS': { 'latitude':'33.15', 'longitude': '-89.066667', 'name':'Winston County' },
'RLA': { 'latitude':'38.133333', 'longitude': '-91.783333', 'name':'National' },
'LMH': { 'latitude':'15.866667', 'longitude': '-85.55', 'name':'Limon' },
'UVL': { 'latitude':'25.456944', 'longitude': '30.570278', 'name':'Kharga' },
'UVO': { 'latitude':'-5.416667', 'longitude': '151.833333', 'name':'Uvol' },
'UVA': { 'latitude':'29.2', 'longitude': '-99.733333', 'name':'Garner Fld' },
'UVE': { 'latitude':'-20.5', 'longitude': '166.666667', 'name':'Ouvea' },
'UVF': { 'latitude':'13.75', 'longitude': '-60.95', 'name':'Hewanorra' },
'LMM': { 'latitude':'25.685278', 'longitude': '-109.080833', 'name':'Federal' },
'ZVK': { 'latitude':'16.533333', 'longitude': '104.75', 'name':'Savannakhet' },
'ZVM': { 'latitude':'49.466667', 'longitude': '-96.833333', 'name':'Messe-BF Railway Servi' },
'ZVA': { 'latitude':'-19.55', 'longitude': '45.45', 'name':'Miandrivazo' },
'ZVG': { 'latitude':'-17.8', 'longitude': '127.633333', 'name':'Springvale' },
'ZVE': { 'latitude':'6.083333', 'longitude': '-58.133333', 'name':'New Haven Rail' },
'UPC': { 'latitude':'28.4', 'longitude': '-16.55', 'name':'Puerto La Cruz' },
'RLT': { 'latitude':'18.783333', 'longitude': '7.366667', 'name':'Arlit' },
'ZVR': { 'latitude':'49.466667', 'longitude': '-96.833333', 'name':'Hanover Railway' },
'RWB': { 'latitude':'56.75', 'longitude': '-134.133333', 'name':'Rowan Bay' },
'RWF': { 'latitude':'44.533333', 'longitude': '-95.116667', 'name':'Redwood Falls Muni' },
'RWI': { 'latitude':'35.856389', 'longitude': '-77.891944', 'name':'Rocky Mount-wilson' },
'RWL': { 'latitude':'41.8', 'longitude': '-107.2', 'name':'Rawlins' },
'RWN': { 'latitude':'50.6', 'longitude': '26.15', 'name':'Rovno' },
'RLP': { 'latitude':'-18.433333', 'longitude': '144.466667', 'name':'Rosella Plains' },
'RWS': { 'latitude':'-22.8', 'longitude': '-47.283333', 'name':'Sumare' },
'DOK': { 'latitude':'48.083333', 'longitude': '37.75', 'name':'Donetsk International Airport' },
'DOH': { 'latitude':'25.261111', 'longitude': '51.565', 'name':'Doha' },
'DOI': { 'latitude':'-10.716667', 'longitude': '150.716667', 'name':'Doini' },
'DON': { 'latitude':'17.633333', 'longitude': '-89.666667', 'name':'Dos Lagunas' },
'DOO': { 'latitude':'-9.5', 'longitude': '147.8', 'name':'Dorobisoro' },
'DOL': { 'latitude':'49.366667', 'longitude': '0.166667', 'name':'St Gatien' },
'DOM': { 'latitude':'15.533333', 'longitude': '-61.3', 'name':'Melville Hall' },
'DOC': { 'latitude':'57.883333', 'longitude': '-4.083333', 'name':'Dornoch' },
'DOA': { 'latitude':'-14.366667', 'longitude': '49.516667', 'name':'Doany' },
'DOF': { 'latitude':'55.2125', 'longitude': '-132.266667', 'name':'Dora Bay' },
'DOG': { 'latitude':'19.183333', 'longitude': '30.433333', 'name':'Dongola' },
'DOD': { 'latitude':'-6.170556', 'longitude': '35.7525', 'name':'Dodoma' },
'DOE': { 'latitude':'4.0', 'longitude': '-55.483333', 'name':'Djoemoe' },
'DOX': { 'latitude':'-29.25', 'longitude': '114.933333', 'name':'Dongara' },
'DOY': { 'latitude':'37.454444', 'longitude': '118.471944', 'name':'Dongying' },
'DOR': { 'latitude':'14.033333', 'longitude': '-0.033333', 'name':'Dori' },
'DOS': { 'latitude':'-5.55', 'longitude': '154.966667', 'name':'Dios' },
'DOP': { 'latitude':'29.0', 'longitude': '82.816667', 'name':'Dolpa' },
'DOV': { 'latitude':'39.129444', 'longitude': '-75.466111', 'name':'Dover AFB' },
'DOU': { 'latitude':'-22.2', 'longitude': '-54.866667', 'name':'Dourados' },
'XTV': { 'latitude':'34.596667', 'longitude': '43.676944', 'name':'Tikrit' },
'XTR': { 'latitude':'-27.161667', 'longitude': '150.476944', 'name':'Tara' },
'XTG': { 'latitude':'-28.0', 'longitude': '143.816667', 'name':'Thargomindah' },
'XTF': { 'latitude':'39.142222', 'longitude': '117.176667', 'name':'Port Free Trade Zone' },
'XTA': { 'latitude':'39.142222', 'longitude': '117.176667', 'name':'Econ/Tech Dev. Area' },
'XTO': { 'latitude':'-25.65', 'longitude': '149.8', 'name':'Taroom' },
'XTM': { 'latitude':'33.423889', 'longitude': '43.3025', 'name':'Ramadi' },
'XTL': { 'latitude':'58.708611', 'longitude': '-98.512778', 'name':'Tadoule Lake' },
'PUL': { 'latitude':'47.733333', 'longitude': '-122.65', 'name':'Poulsbo' },
'PUM': { 'latitude':'-4.183333', 'longitude': '121.616667', 'name':'Pomala' },
'PUN': { 'latitude':'-1.366667', 'longitude': '26.333333', 'name':'Punia' },
'PUO': { 'latitude':'54.95', 'longitude': '-1.85', 'name':'Prudhoe Bay' },
'PUH': { 'latitude':'15.7', 'longitude': '-96.466667', 'name':'Pochutla' },
'PUI': { 'latitude':'-5.833333', 'longitude': '142.833333', 'name':'Pureni' },
'PUJ': { 'latitude':'18.5675', 'longitude': '-68.363333', 'name':'Punta Cana International' },
'PUK': { 'latitude':'-18.266667', 'longitude': '-137.0', 'name':'Pukarua' },
'PUD': { 'latitude':'-47.716667', 'longitude': '-65.916667', 'name':'Puerto Deseado' },
'PUE': { 'latitude':'8.683333', 'longitude': '-77.533333', 'name':'Puerto Obaldia' },
'JJU': { 'latitude':'60.75', 'longitude': '-46.0', 'name':'Heliport' },
'PUG': { 'latitude':'-32.540278', 'longitude': '137.716667', 'name':'Port Augusta' },
'PUA': { 'latitude':'-2.4', 'longitude': '150.233333', 'name':'Puas' },
'PUB': { 'latitude':'38.283333', 'longitude': '-104.5', 'name':'Memorial' },
'PUC': { 'latitude':'39.602778', 'longitude': '-110.75', 'name':'Carbon County' },
'JJN': { 'latitude':'24.9', 'longitude': '118.583333', 'name':'Jinjiang' },
'PUX': { 'latitude':'-33.966667', 'longitude': '-70.816667', 'name':'Puerto Varas' },
'PUY': { 'latitude':'44.883333', 'longitude': '13.916667', 'name':'Pula' },
'JJI': { 'latitude':'-7.15', 'longitude': '-76.716667', 'name':'Juanjui' },
'PUT': { 'latitude':'10.816667', 'longitude': '76.2', 'name':'Puttaprathe' },
'PUU': { 'latitude':'0.5', 'longitude': '-76.416667', 'name':'Puerto Asis' },
'PUW': { 'latitude':'46.75', 'longitude': '-117.116667', 'name':'Pullman-Moscow Regional Airport' },
'PUP': { 'latitude':'11.166667', 'longitude': '-1.15', 'name':'Po' },
'PUQ': { 'latitude':'-53.1', 'longitude': '-70.883333', 'name':'Pres Ibanez' },
'PUR': { 'latitude':'-11.116667', 'longitude': '-67.5', 'name':'Puerto Rico' },
'PUS': { 'latitude':'35.179444', 'longitude': '128.938333', 'name':'Gimhae' },
'BAV': { 'latitude':'40.666667', 'longitude': '109.983333', 'name':'Baotou' },
'BAW': { 'latitude':'-0.666667', 'longitude': '9.45', 'name':'Biawonque' },
'BAT': { 'latitude':'-20.583611', 'longitude': '-48.585278', 'name':'Airport Chafei Amsei' },
'BAU': { 'latitude':'-22.333333', 'longitude': '-49.05', 'name':'Bauru' },
'BAR': { 'latitude':'0.216667', 'longitude': '-176.516667', 'name':'Baker Aaf' },
'BAS': { 'latitude':'-6.983333', 'longitude': '155.883333', 'name':'Balalae' },
'BAP': { 'latitude':'-10.333333', 'longitude': '149.633333', 'name':'Baibara' },
'BAQ': { 'latitude':'10.883333', 'longitude': '-74.783333', 'name':'E Cortissoz' },
'BAZ': { 'latitude':'-0.966944', 'longitude': '-62.933611', 'name':'Barbelos' },
'BAX': { 'latitude':'53.363889', 'longitude': '83.538611', 'name':'Barnaul' },
'BAY': { 'latitude':'47.633333', 'longitude': '23.516667', 'name':'Baia Mare' },
'BAG': { 'latitude':'16.366667', 'longitude': '120.616667', 'name':'Loakan' },
'BAE': { 'latitude':'44.388333', 'longitude': '6.610278', 'name':'Barcelonnette' },
'BAC': { 'latitude':'4.583333', 'longitude': '-72.966667', 'name':'Barranca De Upia' },
'BAA': { 'latitude':'-5.316667', 'longitude': '151.033333', 'name':'Bialla' },
'BAN': { 'latitude':'-4.166667', 'longitude': '20.333333', 'name':'Basongo' },
'BAO': { 'latitude':'17.383333', 'longitude': '102.783333', 'name':'Udorn' },
'BAL': { 'latitude':'37.866667', 'longitude': '41.116667', 'name':'Batman' },
'BAM': { 'latitude':'40.633333', 'longitude': '-116.933333', 'name':'Lander County' },
'BAH': { 'latitude':'26.0', 'longitude': '50.5', 'name':'Bahrain International' },
'BAI': { 'latitude':'9.163611', 'longitude': '-83.33', 'name':'Buenos Aires' },
'EQS': { 'latitude':'-42.916667', 'longitude': '-71.15', 'name':'Esquel' },
'STD': { 'latitude':'7.583333', 'longitude': '-72.066667', 'name':'Mayo Guerrero' },
'STE': { 'latitude':'41.433333', 'longitude': '20.166667', 'name':'Stevens Point' },
'STF': { 'latitude':'-9.5', 'longitude': '143.566667', 'name':'Stephen Island' },
'STG': { 'latitude':'56.6', 'longitude': '-169.533333', 'name':'St George Island' },
'STA': { 'latitude':'55.983333', 'longitude': '8.35', 'name':'Stauning Vestjyllands Airport' },
'STB': { 'latitude':'9.033333', 'longitude': '-71.95', 'name':'L Delicias' },
'STC': { 'latitude':'45.583333', 'longitude': '-94.183333', 'name':'Municipal' },
'STL': { 'latitude':'38.748611', 'longitude': '-90.37', 'name':'Lambert-St. Louis International' },
'STM': { 'latitude':'-2.416667', 'longitude': '-54.7', 'name':'Eduardo Gomes' },
'STN': { 'latitude':'51.883333', 'longitude': '0.233333', 'name':'Stansted' },
'STH': { 'latitude':'-17.833333', 'longitude': '142.533333', 'name':'Strathmore' },
'STI': { 'latitude':'19.406111', 'longitude': '-70.604722', 'name':'Cibao International Airport' },
'STJ': { 'latitude':'39.766667', 'longitude': '-94.916667', 'name':'Rosecrans Memorial' },
'STK': { 'latitude':'40.616667', 'longitude': '-103.266667', 'name':'Crosson Field' },
'STT': { 'latitude':'18.337222', 'longitude': '-64.973333', 'name':'Cyril E King Airport' },
'STU': { 'latitude':'18.275', 'longitude': '-88.458333', 'name':'Santa Cruz' },
'STV': { 'latitude':'29.3', 'longitude': '73.916667', 'name':'Surat' },
'STW': { 'latitude':'45.333333', 'longitude': '42.008333', 'name':'Stavropol' },
'STP': { 'latitude':'44.933333', 'longitude': '-93.066667', 'name':'Downtown' },
'STR': { 'latitude':'48.683333', 'longitude': '9.2', 'name':'Stuttgart Echterdingen' },
'STS': { 'latitude':'38.516667', 'longitude': '-122.8', 'name':'Sonoma County' },
'STX': { 'latitude':'17.716667', 'longitude': '-64.783333', 'name':'Henry E Rohlsen' },
'STY': { 'latitude':'-31.433333', 'longitude': '-57.983333', 'name':'Salto' },
'STZ': { 'latitude':'-10.464444', 'longitude': '-50.052778', 'name':'Confresa' },
'TFM': { 'latitude':'-5.133333', 'longitude': '141.583333', 'name':'Telefomin' },
'NCY': { 'latitude':'45.925', 'longitude': '6.091667', 'name':'Annecy-Meythe' },
'TFN': { 'latitude':'28.482778', 'longitude': '-16.341667', 'name':'Tenerife Norte' },
'TFI': { 'latitude':'-9.083333', 'longitude': '149.316667', 'name':'Tufi' },
'NCP': { 'latitude':'16.0', 'longitude': '121.0', 'name':'Cubi Pt NAS' },
'NCQ': { 'latitude':'34.351111', 'longitude': '-84.287222', 'name':'Atlanta Nas' },
'NCR': { 'latitude':'11.766667', 'longitude': '-86.1', 'name':'San Carlos' },
'NCS': { 'latitude':'-27.75', 'longitude': '30.0', 'name':'Newcastle' },
'NCT': { 'latitude':'10.2', 'longitude': '-85.466667', 'name':'Guanacaste' },
'NCU': { 'latitude':'42.483333', 'longitude': '59.633333', 'name':'Nukus' },
'TFC': { 'latitude':'37.85', 'longitude': '15.283333', 'name':'Taormina Harbour' },
'TFB': { 'latitude':'-5.1', 'longitude': '141.466667', 'name':'Tifalmin' },
'NCH': { 'latitude':'-10.366667', 'longitude': '38.8', 'name':'Nachingwea' },
'NCI': { 'latitude':'8.45', 'longitude': '-76.783333', 'name':'Necocli' },
'NCL': { 'latitude':'55.033333', 'longitude': '-1.7', 'name':'Newcastle Airport' },
'NCN': { 'latitude':'60.001111', 'longitude': '-148.008333', 'name':'New Chenega' },
'NCA': { 'latitude':'21.883333', 'longitude': '-71.95', 'name':'North Caicos' },
'NCE': { 'latitude':'43.665278', 'longitude': '7.215', 'name':'Cote D\'azur International Airport' },
'TFS': { 'latitude':'28.044444', 'longitude': '-16.5725', 'name':'Sur Reina Sofia' },
'NCG': { 'latitude':'30.3975', 'longitude': '-107.875', 'name':'Nueva Casas Grandes' },
'LID': { 'latitude':'52.166111', 'longitude': '4.418056', 'name':'Valkenburg' },
'ACC': { 'latitude':'5.6', 'longitude': '-0.166667', 'name':'Kotoka' },
'LIF': { 'latitude':'-20.766667', 'longitude': '167.233333', 'name':'Lifou' },
'FNT': { 'latitude':'42.965556', 'longitude': '-83.743611', 'name':'Bishop International Airport' },
'FNR': { 'latitude':'58.233333', 'longitude': '-134.916667', 'name':'SPB' },
'LIB': { 'latitude':'-17.333333', 'longitude': '129.833333', 'name':'Limbunya' },
'LIC': { 'latitude':'39.266667', 'longitude': '-103.683333', 'name':'Municipal' },
'LIL': { 'latitude':'50.566667', 'longitude': '3.1', 'name':'Lesquin' },
'LIM': { 'latitude':'-12.021944', 'longitude': '-77.114444', 'name':'Jorge Chavez International' },
'LIN': { 'latitude':'45.45', 'longitude': '9.283333', 'name':'Linate' },
'LIO': { 'latitude':'10.083333', 'longitude': '-82.966667', 'name':'Limon' },
'LIH': { 'latitude':'21.983333', 'longitude': '-159.35', 'name':'Lihue' },
'LII': { 'latitude':'-3.166667', 'longitude': '136.166667', 'name':'Mulia' },
'LIK': { 'latitude':'9.816667', 'longitude': '169.316667', 'name':'Likiep Island' },
'FNG': { 'latitude':'12.066667', 'longitude': '0.35', 'name':'Fada Ngourma' },
'FNE': { 'latitude':'-8.6', 'longitude': '147.233333', 'name':'Fane' },
'LIW': { 'latitude':'19.691389', 'longitude': '97.214722', 'name':'Loikaw' },
'FNC': { 'latitude':'32.697778', 'longitude': '-16.774444', 'name':'Madeira' },
'FNB': { 'latitude':'53.6', 'longitude': '13.3', 'name':'Neubrandenburg' },
'FNA': { 'latitude':'8.616667', 'longitude': '-13.2', 'name':'Lungi International' },
'LIS': { 'latitude':'38.781389', 'longitude': '-9.135833', 'name':'Portela' },
'FNL': { 'latitude':'40.583333', 'longitude': '-105.083333', 'name':'Municipal Airport' },
'FNK': { 'latitude':'69.5', 'longitude': '-147.583333', 'name':'Fin Creek' },
'FNJ': { 'latitude':'39.224167', 'longitude': '125.670278', 'name':'Sunan International' },
'FNI': { 'latitude':'43.85', 'longitude': '4.416667', 'name':'Garons' },
'ACK': { 'latitude':'41.266667', 'longitude': '-70.066667', 'name':'Nantucket Memorial' },
'NEG': { 'latitude':'18.308333', 'longitude': '-78.333333', 'name':'Negril' },
'ACI': { 'latitude':'49.7', 'longitude': '-2.216667', 'name':'The Blaye' },
'SYB': { 'latitude':'58.166667', 'longitude': '-152.5', 'name':'Seal Bay' },
'ACN': { 'latitude':'29.3', 'longitude': '-100.916667', 'name':'International' },
'QBC': { 'latitude':'52.3875', 'longitude': '-126.595833', 'name':'Bella Coola' },
'ACL': { 'latitude':'4.75', 'longitude': '-73.0', 'name':'Aguaclara' },
'KAC': { 'latitude':'37.033333', 'longitude': '41.083333', 'name':'Kameshli' },
'KAB': { 'latitude':'-16.516667', 'longitude': '28.883333', 'name':'Kariba' },
'KAA': { 'latitude':'-10.216667', 'longitude': '31.133333', 'name':'Kasama' },
'KAG': { 'latitude':'37.75', 'longitude': '128.95', 'name':'Gangneung' },
'KAF': { 'latitude':'-6.283333', 'longitude': '155.35', 'name':'Karato' },
'KAE': { 'latitude':'56.966667', 'longitude': '-133.95', 'name':'SPB' },
'KAD': { 'latitude':'10.6', 'longitude': '7.45', 'name':'Kaduna' },
'KAK': { 'latitude':'-6.233333', 'longitude': '143.483333', 'name':'Kar' },
'KAJ': { 'latitude':'64.283333', 'longitude': '27.683333', 'name':'Kajaani' },
'KAI': { 'latitude':'5.15', 'longitude': '-59.483333', 'name':'Kaieteur' },
'KAH': { 'latitude':'-37.716667', 'longitude': '145.0', 'name':'City Heliport' },
'KAO': { 'latitude':'65.9875', 'longitude': '29.239444', 'name':'Kuusamo' },
'KAN': { 'latitude':'12.0475', 'longitude': '8.524722', 'name':'Aminu Kano Intl Apt' },
'KAM': { 'latitude':'15.366667', 'longitude': '42.583333', 'name':'Kamaran Is' },
'KAL': { 'latitude':'64.333333', 'longitude': '-158.7', 'name':'Kaltag' },
'KAS': { 'latitude':'-28.0', 'longitude': '18.716667', 'name':'Karasburg' },
'KAR': { 'latitude':'5.883333', 'longitude': '-60.616667', 'name':'Kamarang' },
'KAQ': { 'latitude':'-8.133333', 'longitude': '146.816667', 'name':'Kamulai' },
'KAP': { 'latitude':'-8.333333', 'longitude': '22.666667', 'name':'Kapanga' },
'KAW': { 'latitude':'10.05', 'longitude': '98.533333', 'name':'Kawthaung' },
'KAV': { 'latitude':'5.666667', 'longitude': '-61.766667', 'name':'Kavanayen' },
'KAU': { 'latitude':'63.1', 'longitude': '23.083333', 'name':'Kauhava' },
'KAT': { 'latitude':'-35.066667', 'longitude': '173.283333', 'name':'Kaitaia' },
'RHA': { 'latitude':'65.333333', 'longitude': '-20.583333', 'name':'Reykholar' },
'KAZ': { 'latitude':'1.166667', 'longitude': '127.883333', 'name':'Kau' },
'KAY': { 'latitude':'-17.616667', 'longitude': '179.0', 'name':'Wakaya Island' },
'KAX': { 'latitude':'-27.866667', 'longitude': '114.133333', 'name':'Kalbarri' },
'RHE': { 'latitude':'49.316667', 'longitude': '4.066667', 'name':'Reims' },
'RHD': { 'latitude':'-27.466667', 'longitude': '-64.916667', 'name':'Rio Hondo' },
'RHG': { 'latitude':'-1.5', 'longitude': '29.633333', 'name':'Ruhengeri' },
'VQQ': { 'latitude':'30.218611', 'longitude': '-81.876667', 'name':'Cecil Field' },
'ACT': { 'latitude':'31.616667', 'longitude': '-97.233333', 'name':'Municipal' },
'HFA': { 'latitude':'32.8', 'longitude': '35.05', 'name':'Haifa' },
'NEW': { 'latitude':'30.049444', 'longitude': '-90.028889', 'name':'Lakefront' },
'ACY': { 'latitude':'39.466667', 'longitude': '-74.583333', 'name':'Atlantic City Intl' },
'ACX': { 'latitude':'25.05', 'longitude': '104.983333', 'name':'Xingyi' },
'HFE': { 'latitude':'31.95', 'longitude': '117.283333', 'name':'Shanghai' },
'HFD': { 'latitude':'41.766667', 'longitude': '-72.683333', 'name':'Brainard' },
'OXY': { 'latitude':'-25.366667', 'longitude': '141.466667', 'name':'Morney' },
'OXR': { 'latitude':'34.2', 'longitude': '-119.2', 'name':'Ventura' },
'OXO': { 'latitude':'-28.133333', 'longitude': '141.533333', 'name':'Orientos' },
'OXD': { 'latitude':'45.733333', 'longitude': '-63.866667', 'name':'Miami University' },
'OXF': { 'latitude':'51.833333', 'longitude': '-1.25', 'name':'Oxford' },
'OXB': { 'latitude':'11.894722', 'longitude': '-15.653611', 'name':'Osvaldo Vieira International' },
'OXC': { 'latitude':'41.478611', 'longitude': '-73.135278', 'name':'Waterbury-oxford' },
'CZZ': { 'latitude':'18.45', 'longitude': '-72.1', 'name':'Campo' },
'CZX': { 'latitude':'31.7', 'longitude': '119.966667', 'name':'Changzhou' },
'CZY': { 'latitude':'-24.5', 'longitude': '139.5', 'name':'Cluny' },
'CZS': { 'latitude':'-7.599444', 'longitude': '-72.769444', 'name':'Intl. Airpt. Cruzeiro Do Sul' },
'CZP': { 'latitude':'55.966667', 'longitude': '-133.783333', 'name':'Cape Pole' },
'CZW': { 'latitude':'50.816667', 'longitude': '19.1', 'name':'Czestochowa' },
'CZT': { 'latitude':'28.516667', 'longitude': '-99.866667', 'name':'Carrizo Springs' },
'CZU': { 'latitude':'9.333333', 'longitude': '-75.283333', 'name':'Corozal' },
'CZJ': { 'latitude':'9.016667', 'longitude': '-77.983333', 'name':'Corazon De Jesus' },
'CZK': { 'latitude':'45.666667', 'longitude': '-121.9', 'name':'Cascade Locks/Stevens' },
'CZH': { 'latitude':'18.333333', 'longitude': '-88.5', 'name':'Corozal' },
'CZN': { 'latitude':'62.083333', 'longitude': '-142.05', 'name':'Chisana Field' },
'CZO': { 'latitude':'62.566667', 'longitude': '-144.666667', 'name':'Chistochina' },
'CZL': { 'latitude':'36.285278', 'longitude': '6.619167', 'name':'Ain El Bey' },
'CZM': { 'latitude':'20.516667', 'longitude': '-86.933333', 'name':'Cozumel' },
'CZB': { 'latitude':'-28.633333', 'longitude': '-53.5', 'name':'Carlos Ruhl' },
'CZC': { 'latitude':'42.483333', 'longitude': '12.65', 'name':'Copper Centre' },
'CZA': { 'latitude':'20.666667', 'longitude': '-88.566667', 'name':'Chichen Itza' },
'CZF': { 'latitude':'61.733333', 'longitude': '-166.0', 'name':'Cape Romanzof' },
'CZE': { 'latitude':'11.416667', 'longitude': '-69.666667', 'name':'Coro' },
'ATF': { 'latitude':'-1.2', 'longitude': '-78.566667', 'name':'Chachoan' },
'ATG': { 'latitude':'33.874167', 'longitude': '72.241389', 'name':'Attock' },
'ATD': { 'latitude':'-8.866667', 'longitude': '161.033333', 'name':'Atoifi' },
'ATE': { 'latitude':'34.233333', 'longitude': '-95.616667', 'name':'Antlers' },
'ATB': { 'latitude':'17.7', 'longitude': '33.983333', 'name':'Atbara' },
'ATC': { 'latitude':'24.629417', 'longitude': '-75.673775', 'name':'Arthur\'s Town Airport' },
'ATA': { 'latitude':'-13.483333', 'longitude': '-72.133333', 'name':'Anta' },
'ATN': { 'latitude':'-3.666667', 'longitude': '152.45', 'name':'Namatanai' },
'ATO': { 'latitude':'39.333333', 'longitude': '-82.1', 'name':'Ohio University' },
'ATL': { 'latitude':'33.636667', 'longitude': '-84.428056', 'name':'Hartsfield-jackson Atlanta International' },
'ATM': { 'latitude':'-3.253889', 'longitude': '-52.253889', 'name':'Altamira' },
'ATJ': { 'latitude':'-19.083333', 'longitude': '47.066667', 'name':'Antsirabe' },
'ATK': { 'latitude':'70.466667', 'longitude': '-157.333333', 'name':'Atqasuk' },
'ATH': { 'latitude':'37.936389', 'longitude': '23.944444', 'name':'Eleftherios Venizelos' },
'ATI': { 'latitude':'-30.416667', 'longitude': '-56.516667', 'name':'Artigas' },
'ATV': { 'latitude':'13.233333', 'longitude': '18.316667', 'name':'Ati' },
'ATW': { 'latitude':'44.266667', 'longitude': '-88.516667', 'name':'Outagamie County' },
'ATT': { 'latitude':'61.0', 'longitude': '-162.75', 'name':'Atmautluak' },
'ATU': { 'latitude':'52.833333', 'longitude': '173.183333', 'name':'Casco Cove' },
'ATR': { 'latitude':'20.5', 'longitude': '-13.05', 'name':'Mouakchott' },
'ATS': { 'latitude':'32.85', 'longitude': '-104.466667', 'name':'Artesia' },
'ATP': { 'latitude':'-3.133333', 'longitude': '142.35', 'name':'Airstrip' },
'ATQ': { 'latitude':'31.709722', 'longitude': '74.797222', 'name':'Raja Sansi' },
'RGT': { 'latitude':'-0.4', 'longitude': '102.333333', 'name':'Japura' },
'ATZ': { 'latitude':'27.05', 'longitude': '31.016667', 'name':'Assiut' },
'ATX': { 'latitude':'51.883333', 'longitude': '68.4', 'name':'Atbasar' },
'ATY': { 'latitude':'44.916667', 'longitude': '-97.15', 'name':'Watertown' },
'OBA': { 'latitude':'-21.233333', 'longitude': '139.033333', 'name':'Oban' },
'PNY': { 'latitude':'11.968611', 'longitude': '79.81', 'name':'Pondicherry' },
'PNX': { 'latitude':'33.633333', 'longitude': '-96.583333', 'name':'Grayson County' },
'RGA': { 'latitude':'-53.783333', 'longitude': '-67.766667', 'name':'Rio Grande' },
'PNQ': { 'latitude':'18.583333', 'longitude': '73.916667', 'name':'Lohegaon' },
'PNP': { 'latitude':'-8.766667', 'longitude': '148.216667', 'name':'Girua' },
'PNS': { 'latitude':'30.466667', 'longitude': '-87.183333', 'name':'Regional' },
'RGE': { 'latitude':'-5.5', 'longitude': '143.083333', 'name':'Porgera' },
'PNR': { 'latitude':'-4.816111', 'longitude': '11.886667', 'name':'Pointe Noire' },
'PNU': { 'latitude':'37.833333', 'longitude': '-112.383333', 'name':'Panguitch' },
'PNT': { 'latitude':'-51.683333', 'longitude': '-72.516667', 'name':'Teniente J. Gallardo' },
'PNV': { 'latitude':'55.733333', 'longitude': '24.35', 'name':'Panevezys' },
'RGL': { 'latitude':'-51.65', 'longitude': '-69.2', 'name':'Internacional' },
'PNA': { 'latitude':'42.766667', 'longitude': '-1.641667', 'name':'Pamplona' },
'PNC': { 'latitude':'36.733333', 'longitude': '-97.1', 'name':'Ponca City' },
'PNB': { 'latitude':'-10.716667', 'longitude': '-48.4', 'name':'Porto Nacional' },
'PNE': { 'latitude':'40.083333', 'longitude': '-75.016667', 'name':'North Philadelphia' },
'PND': { 'latitude':'16.166667', 'longitude': '-88.7', 'name':'Punta Gorda' },
'PNG': { 'latitude':'-25.516667', 'longitude': '-48.5', 'name':'Municipal' },
'SJM': { 'latitude':'18.833333', 'longitude': '-71.233333', 'name':'San Juan' },
'PDD': { 'latitude':'-26.183333', 'longitude': '36.966667', 'name':'Ponta de Ouro' },
'SJG': { 'latitude':'4.65', 'longitude': '-73.333333', 'name':'San Pedro Jagua' },
'MEE': { 'latitude':'-21.566667', 'longitude': '168.0', 'name':'Mare' },
'XIC': { 'latitude':'27.966667', 'longitude': '102.216667', 'name':'Xichang' },
'XIE': { 'latitude':'19.616667', 'longitude': '100.825', 'name':'Xienglom' },
'GDQ': { 'latitude':'12.516667', 'longitude': '37.416667', 'name':'Gondar' },
'XIH': { 'latitude':'33.8525', 'longitude': '42.5475', 'name':'Khan Al Baghdadi' },
'XIJ': { 'latitude':'29.076944', 'longitude': '48.083889', 'name':'Ahmed Al Jaber' },
'XIK': { 'latitude':'45.5', 'longitude': '9.5', 'name':'Central Station' },
'XIL': { 'latitude':'43.966667', 'longitude': '116.066667', 'name':'Xilinhot' },
'XIN': { 'latitude':'24.15', 'longitude': '115.75', 'name':'Xingning' },
'XIQ': { 'latitude':'69.083333', 'longitude': '-51.116667', 'name':'Harbour' },
'XIX': { 'latitude':'45.416667', 'longitude': '11.033333', 'name':'Porta Nuova Rail' },
'GDT': { 'latitude':'21.566667', 'longitude': '-71.166667', 'name':'Grand Turk Is' },
'YEI': { 'latitude':'40.255278', 'longitude': '29.5625', 'name':'Yenisehir' },
'YEH': { 'latitude':'27.481111', 'longitude': '52.6', 'name':'Persian Gulf International' },
'YEK': { 'latitude':'61.116667', 'longitude': '-94.05', 'name':'Arviat' },
'YEM': { 'latitude':'45.8475', 'longitude': '-81.862778', 'name':'East Manitoulin' },
'GDV': { 'latitude':'47.133333', 'longitude': '-104.683333', 'name':'Dawson Community' },
'YEO': { 'latitude':'51.016667', 'longitude': '-2.633333', 'name':'Yeovilton' },
'YEN': { 'latitude':'49.066667', 'longitude': '-103.0', 'name':'Estevan' },
'YEC': { 'latitude':'36.625', 'longitude': '128.355', 'name':'Yecheon' },
'GDW': { 'latitude':'43.983333', 'longitude': '-84.483333', 'name':'Gladwin' },
'YED': { 'latitude':'53.319444', 'longitude': '-113.6', 'name':'Namao Fld' },
'YEG': { 'latitude':'53.309722', 'longitude': '-113.579722', 'name':'Edmonton International' },
'YEY': { 'latitude':'48.583333', 'longitude': '-78.116667', 'name':'Amos' },
'GDX': { 'latitude':'59.916667', 'longitude': '150.716667', 'name':'Magadan' },
'YEQ': { 'latitude':'-5.1', 'longitude': '143.916667', 'name':'Yenkis' },
'YEP': { 'latitude':'49.383333', 'longitude': '-126.55', 'name':'Estevan Point' },
'YER': { 'latitude':'56.0', 'longitude': '-87.633333', 'name':'Fort Severn' },
'YEU': { 'latitude':'79.983333', 'longitude': '-85.816667', 'name':'Eureka' },
'GDZ': { 'latitude':'44.566667', 'longitude': '38.016667', 'name':'Gelendzik' },
'YEV': { 'latitude':'68.304167', 'longitude': '-133.482778', 'name':'Inuvik/mike Zubko' },
'MET': { 'latitude':'-12.75', 'longitude': '142.766667', 'name':'Moreton' },
'NWU': { 'latitude':'32.333333', 'longitude': '-64.75', 'name':'NAS' },
'MEQ': { 'latitude':'4.136667', 'longitude': '96.129444', 'name':'Seunagan' },
'GDE': { 'latitude':'5.9', 'longitude': '43.633333', 'name':'Gode/Iddidole' },
'PRE': { 'latitude':'5.733333', 'longitude': '-71.983333', 'name':'Pore' },
'VGN': { 'latitude':'17.55474', 'longitude': '120.35612', 'name':'Vigan' },
'VGO': { 'latitude':'42.216667', 'longitude': '-8.616667', 'name':'Vigo' },
'VGD': { 'latitude':'59.2825', 'longitude': '39.944444', 'name':'Vologda' },
'GDG': { 'latitude':'53.466667', 'longitude': '125.8', 'name':'Magdagachi' },
'PRG': { 'latitude':'50.066667', 'longitude': '14.433333', 'name':'Prague - Ruzyne International' },
'PRF': { 'latitude':'55.122222', 'longitude': '-132.05', 'name':'Port Johnson' },
'VGZ': { 'latitude':'1.066667', 'longitude': '-76.716667', 'name':'Villagarzon' },
'VGT': { 'latitude':'36.216667', 'longitude': '-115.2', 'name':'North Air Terminal' },
'PRA': { 'latitude':'-31.783333', 'longitude': '-60.483333', 'name':'Parana' },
'VGS': { 'latitude':'-35.033333', 'longitude': '-63.016667', 'name':'General Villegas' },
'WWT': { 'latitude':'60.933333', 'longitude': '-164.633333', 'name':'Newtok' },
'WWP': { 'latitude':'56.666667', 'longitude': '-133.833333', 'name':'Whale Pass' },
'WWS': { 'latitude':'53.616667', 'longitude': '-1.25', 'name':'USAF Heliport' },
'WWR': { 'latitude':'36.433333', 'longitude': '-99.516667', 'name':'West Woodward' },
'GDL': { 'latitude':'20.523889', 'longitude': '-103.3125', 'name':'Guadalajara' },
'WWY': { 'latitude':'-33.933333', 'longitude': '147.25', 'name':'West Wyalong' },
'GDM': { 'latitude':'42.566667', 'longitude': '-72.0', 'name':'Municipal' },
'WWD': { 'latitude':'39.0', 'longitude': '-74.916667', 'name':'Cape May County' },
'WWG': { 'latitude':'16.233333', 'longitude': '32.604167', 'name':'Al Koude' },
'WWA': { 'latitude':'61.583333', 'longitude': '-149.433333', 'name':'Wasilla' },
'GDO': { 'latitude':'7.233333', 'longitude': '-70.8', 'name':'Vare Maria' },
'WWK': { 'latitude':'-3.6', 'longitude': '143.666667', 'name':'Boram' },
'FSC': { 'latitude':'41.583333', 'longitude': '9.25', 'name':'Sud Corse' },
'FSD': { 'latitude':'43.581944', 'longitude': '-96.741944', 'name':'Joe Foss Field Airport' },
'FSI': { 'latitude':'19.833333', 'longitude': '-72.5', 'name':'Henry Post AAF' },
'FSK': { 'latitude':'37.8', 'longitude': '-94.766667', 'name':'Municipal' },
'FSL': { 'latitude':'-18.2', 'longitude': '125.75', 'name':'Fossil Downs' },
'FSM': { 'latitude':'35.333333', 'longitude': '-94.366667', 'name':'Regional' },
'FSN': { 'latitude':'19.833333', 'longitude': '-72.5', 'name':'Haley AAF' },
'FSP': { 'latitude':'46.916667', 'longitude': '-56.166667', 'name':'Saint-pierre Pointe-blanche' },
'FSS': { 'latitude':'57.65', 'longitude': '-3.566667', 'name':'Kinloss' },
'FST': { 'latitude':'30.916667', 'longitude': '-102.916667', 'name':'Pecos County' },
'FSU': { 'latitude':'34.466667', 'longitude': '-104.25', 'name':'Fort Sumner' },
'FSZ': { 'latitude':'34.7961', 'longitude': '138.1894', 'name':'Shizuoka Airport' },
'PRV': { 'latitude':'49.425833', 'longitude': '17.404722', 'name':'Prerov' },
'PRP': { 'latitude':'41.666667', 'longitude': '8.9', 'name':'Propriano' },
'ZTM': { 'latitude':'55.866667', 'longitude': '-92.083333', 'name':'Shamattawa' },
'ZTL': { 'latitude':'42.095278', 'longitude': '8.709722', 'name':'Bus Station' },
'ZTN': { 'latitude':'29.483333', 'longitude': '31.066667', 'name':'Trenton Rail STN' },
'ZTI': { 'latitude':'22.826667', 'longitude': '113.671667', 'name':'Humen Port' },
'ZTH': { 'latitude':'37.750278', 'longitude': '20.883611', 'name':'Zakinthos International Airport' },
'ZTJ': { 'latitude':'48.416667', 'longitude': '-53.6', 'name':'Princeton JT Rail' },
'ZTE': { 'latitude':'49.916667', 'longitude': '-0.966667', 'name':'Rochester NY Rail' },
'ZTD': { 'latitude':'50.35', 'longitude': '21.383333', 'name':'Schenectady Rail' },
'PRR': { 'latitude':'5.816667', 'longitude': '-61.016667', 'name':'Paruima' },
'ZTA': { 'latitude':'-20.816457', 'longitude': '-138.504639', 'name':'Tureia' },
'ZTB': { 'latitude':'50.7', 'longitude': '-59.333333', 'name':'Tete-a-La Baleine' },
'ZTZ': { 'latitude':'53.583333', 'longitude': '13.15', 'name':'Chemnitz Railway Stn.' },
'ZTT': { 'latitude':'51.778889', 'longitude': '14.364444', 'name':'Cottbus Railway Stn.' },
'ZTR': { 'latitude':'50.273056', 'longitude': '28.735556', 'name':'Zhitomir Airport' },
'RUK': { 'latitude':'28.95', 'longitude': '82.266667', 'name':'Rukumkot' },
'RUH': { 'latitude':'24.957778', 'longitude': '46.698889', 'name':'King Khaled Intl' },
'RUI': { 'latitude':'33.416667', 'longitude': '-105.583333', 'name':'Municipal' },
'RUN': { 'latitude':'-20.883333', 'longitude': '55.533333', 'name':'Gillot' },
'RUM': { 'latitude':'27.333333', 'longitude': '86.55', 'name':'Rumjatar' },
'PRY': { 'latitude':'-25.65', 'longitude': '28.216667', 'name':'Wonderboom Apt.' },
'RUA': { 'latitude':'3.05', 'longitude': '30.9', 'name':'Arua' },
'RUG': { 'latitude':'32.388333', 'longitude': '120.555278', 'name':'Rugao' },
'PRX': { 'latitude':'33.633333', 'longitude': '-95.45', 'name':'Cox Field' },
'RUY': { 'latitude':'14.833333', 'longitude': '-89.133333', 'name':'Copan' },
'RUR': { 'latitude':'-22.433333', 'longitude': '-151.333333', 'name':'Rurutu' },
'RUS': { 'latitude':'-8.5', 'longitude': '161.25', 'name':'Marau Sound' },
'RUP': { 'latitude':'26.15', 'longitude': '89.916667', 'name':'Rupsi' },
'RUV': { 'latitude':'15.833333', 'longitude': '-90.333333', 'name':'Rubelsanto' },
'RUT': { 'latitude':'43.533333', 'longitude': '-72.95', 'name':'Rutland' },
'RUU': { 'latitude':'-5.3', 'longitude': '144.25', 'name':'Ruti' },
'DIL': { 'latitude':'-8.546389', 'longitude': '125.524722', 'name':'Presidente Nicolau Lobato International Airport' },
'DIM': { 'latitude':'6.65', 'longitude': '-4.7', 'name':'Dimbokro' },
'JHC': { 'latitude':'40.744444', 'longitude': '-73.608333', 'name':'Island Heliport' },
'DIO': { 'latitude':'65.75', 'longitude': '-168.95', 'name':'Diomede Island' },
'JHE': { 'latitude':'56.05', 'longitude': '12.7', 'name':'Heliport' },
'JHG': { 'latitude':'22.016667', 'longitude': '100.8', 'name':'Gasa' },
'DIK': { 'latitude':'46.8', 'longitude': '-102.8', 'name':'Dickinson' },
'DIE': { 'latitude':'-12.35', 'longitude': '49.3', 'name':'Antsiranana/Arrachart' },
'DIG': { 'latitude':'27.789722', 'longitude': '99.677778', 'name':'Diqing' },
'JHM': { 'latitude':'20.963056', 'longitude': '-156.673056', 'name':'Kapalua West Maui' },
'DIB': { 'latitude':'27.483333', 'longitude': '94.9', 'name':'Dibrugarh' },
'DIC': { 'latitude':'-8.566667', 'longitude': '125.533333', 'name':'Dili City Heliport' },
'JHQ': { 'latitude':'-20.283333', 'longitude': '148.75', 'name':'Shute Harbour H/P' },
'JHS': { 'latitude':'66.933333', 'longitude': '-53.7', 'name':'Sisimiut' },
'DIY': { 'latitude':'37.9', 'longitude': '40.2', 'name':'Diyarbakir' },
'JHW': { 'latitude':'42.15', 'longitude': '-79.25', 'name':'Jamestown' },
'JHY': { 'latitude':'42.366667', 'longitude': '-71.102778', 'name':'Hyatt Regency H/P' },
'DIU': { 'latitude':'20.733333', 'longitude': '70.983333', 'name':'Diu' },
'DIV': { 'latitude':'5.833333', 'longitude': '-5.366667', 'name':'Divo' },
'DIW': { 'latitude':'6.966667', 'longitude': '81.0', 'name':'Mawella Lagoon' },
'DIP': { 'latitude':'12.05', 'longitude': '1.783333', 'name':'Diapaga' },
'DIQ': { 'latitude':'-20.75', 'longitude': '-41.883333', 'name':'Divinopolis' },
'DIR': { 'latitude':'9.633333', 'longitude': '41.866667', 'name':'Aba Tenna D Yilma' },
'DIS': { 'latitude':'-4.216667', 'longitude': '12.5', 'name':'Loubomo' },
'UTB': { 'latitude':'-22.588056', 'longitude': '144.526667', 'name':'Muttaburra' },
'UTC': { 'latitude':'52.128333', 'longitude': '5.276944', 'name':'Soesterberg' },
'UTA': { 'latitude':'-18.966667', 'longitude': '32.45', 'name':'Mutare' },
'UTG': { 'latitude':'-30.5', 'longitude': '27.6', 'name':'Quthing' },
'UTD': { 'latitude':'-15.833333', 'longitude': '134.166667', 'name':'Nutwood Downs' },
'UTE': { 'latitude':'-32.383333', 'longitude': '28.066667', 'name':'Butterworth' },
'IRP': { 'latitude':'2.783333', 'longitude': '27.65', 'name':'Matari' },
'UTK': { 'latitude':'11.233333', 'longitude': '169.866667', 'name':'Utirik Island' },
'UTH': { 'latitude':'17.386389', 'longitude': '102.788333', 'name':'Udon Thani' },
'IRS': { 'latitude':'41.8', 'longitude': '-85.416667', 'name':'Kirsch Municipal' },
'UTN': { 'latitude':'-28.416667', 'longitude': '21.266667', 'name':'Upington' },
'UTO': { 'latitude':'65.983333', 'longitude': '-153.683333', 'name':'Indian Mountain AFS' },
'UTL': { 'latitude':'38.916667', 'longitude': '-5.7', 'name':'Torremolinos' },
'UTR': { 'latitude':'17.669444', 'longitude': '100.243889', 'name':'Uttaradit' },
'IRI': { 'latitude':'-7.633333', 'longitude': '35.766667', 'name':'Nduli' },
'IRJ': { 'latitude':'-29.381667', 'longitude': '-66.795833', 'name':'Capitan Vicente Almando' },
'IRK': { 'latitude':'40.1', 'longitude': '-92.55', 'name':'Municipal' },
'IRM': { 'latitude':'63.2', 'longitude': '64.45', 'name':'Igrim' },
'IRN': { 'latitude':'15.95', 'longitude': '-85.183333', 'name':'Iriona' },
'IRO': { 'latitude':'10.5', 'longitude': '22.55', 'name':'Birao' },
'IRA': { 'latitude':'-10.5', 'longitude': '161.833333', 'name':'Kirakira' },
'IRB': { 'latitude':'30.9', 'longitude': '-101.9', 'name':'Municipal' },
'IRC': { 'latitude':'65.833333', 'longitude': '-144.083333', 'name':'Circle City' },
'IRD': { 'latitude':'24.15', 'longitude': '89.05', 'name':'Ishurdi' },
'IRE': { 'latitude':'-11.3', 'longitude': '-41.866667', 'name':'Irece' },
'IRG': { 'latitude':'-12.783333', 'longitude': '143.3', 'name':'Lockhart River' },
'PWT': { 'latitude':'47.483333', 'longitude': '-122.75', 'name':'Bremerton' },
'PWR': { 'latitude':'56.383333', 'longitude': '-134.65', 'name':'Port Walter' },
'PWQ': { 'latitude':'52.183333', 'longitude': '77.066667', 'name':'Pavlodar' },
'PWD': { 'latitude':'48.766667', 'longitude': '-104.55', 'name':'Sherwood' },
'PWE': { 'latitude':'69.783333', 'longitude': '170.6', 'name':'Pevek' },
'PWA': { 'latitude':'35.534167', 'longitude': '-97.666667', 'name':'Wiley Post' },
'PWN': { 'latitude':'22.833333', 'longitude': '-74.35', 'name':'Pitts Town' },
'PWO': { 'latitude':'-8.466667', 'longitude': '28.883333', 'name':'Pweto' },
'PWL': { 'latitude':'7.45', 'longitude': '109.416667', 'name':'Purwokerto' },
'PWM': { 'latitude':'43.65', 'longitude': '-70.3', 'name':'Intl Jetport' },
'PWK': { 'latitude':'42.0', 'longitude': '-87.966667', 'name':'Pal-Waukee' },
'PWI': { 'latitude':'11.333333', 'longitude': '36.416667', 'name':'Beles' },
'BOX': { 'latitude':'-16.083333', 'longitude': '136.3', 'name':'Borroloola' },
'HBL': { 'latitude':'-25.403056', 'longitude': '28.279444', 'name':'Babelegi Heliport' },
'BOZ': { 'latitude':'6.316667', 'longitude': '16.383333', 'name':'Bozoum' },
'NAA': { 'latitude':'-30.333333', 'longitude': '149.833333', 'name':'Narrabri' },
'HBI': { 'latitude':'25.5', 'longitude': '-76.75', 'name':'Harbour Island' },
'NAG': { 'latitude':'21.083333', 'longitude': '79.05', 'name':'Sonegaon' },
'NAD': { 'latitude':'2.566667', 'longitude': '-67.583333', 'name':'Macanal' },
'ILG': { 'latitude':'39.683333', 'longitude': '-75.6', 'name':'Greater Wilmington' },
'NAJ': { 'latitude':'39.333333', 'longitude': '45.5', 'name':'Nakhichevan' },
'BOQ': { 'latitude':'-6.266667', 'longitude': '155.216667', 'name':'Boku' },
'NAH': { 'latitude':'3.716667', 'longitude': '125.366667', 'name':'Naha' },
'NAI': { 'latitude':'3.75', 'longitude': '-59.0', 'name':'Annai' },
'HBA': { 'latitude':'-42.836111', 'longitude': '147.510278', 'name':'Hobart' },
'NAO': { 'latitude':'30.8', 'longitude': '106.066667', 'name':'Nanchong' },
'BOV': { 'latitude':'-3.366667', 'longitude': '153.333333', 'name':'Boang' },
'NAM': { 'latitude':'-3.3', 'longitude': '127.1', 'name':'Namlea' },
'BOH': { 'latitude':'50.78', 'longitude': '-1.8425', 'name':'Bournemouth International' },
'NAS': { 'latitude':'25.038889', 'longitude': '-77.466111', 'name':'Nassau International' },
'NAP': { 'latitude':'40.886111', 'longitude': '14.290833', 'name':'Capodichino' },
'BOK': { 'latitude':'42.05', 'longitude': '-124.283333', 'name':'Brookings State' },
'BOL': { 'latitude':'55.166667', 'longitude': '-6.766667', 'name':'Bally Kelly' },
'BOM': { 'latitude':'19.088611', 'longitude': '72.868056', 'name':'Chhatrapati Shivaji International' },
'NAT': { 'latitude':'-5.833333', 'longitude': '-35.2', 'name':'Augusto Severo' },
'NAU': { 'latitude':'-14.166667', 'longitude': '-141.583333', 'name':'Napuka Island' },
'NAZ': { 'latitude':'-10.783333', 'longitude': '162.3', 'name':'Nana' },
'BOA': { 'latitude':'-5.816667', 'longitude': '13.066667', 'name':'Boma' },
'BOB': { 'latitude':'-16.433333', 'longitude': '-151.75', 'name':'Motu-mute' },
'NAY': { 'latitude':'40.25', 'longitude': '116.5', 'name':'Nanyuan Airport' },
'BOD': { 'latitude':'44.828611', 'longitude': '-0.715278', 'name':'Mérignac' },
'BOE': { 'latitude':'-1.033333', 'longitude': '15.383333', 'name':'Boundji' },
'BOF': { 'latitude':'49.0', 'longitude': '-72.5', 'name':'Bolling AFB' },
'BOG': { 'latitude':'4.703056', 'longitude': '-74.138333', 'name':'Eldorado International' },
'PEZ': { 'latitude':'53.216667', 'longitude': '45.0', 'name':'Penza' },
'ILA': { 'latitude':'-3.833333', 'longitude': '137.583333', 'name':'Illaga' },
'ILN': { 'latitude':'39.416667', 'longitude': '-83.8', 'name':'Clinton Field' },
'ILO': { 'latitude':'10.713056', 'longitude': '122.545278', 'name':'Iloilo International' },
'SVN': { 'latitude':'32.01', 'longitude': '-81.145556', 'name':'Hunter AAF' },
'SVO': { 'latitude':'55.972778', 'longitude': '37.414722', 'name':'Sheremetyevo' },
'SVL': { 'latitude':'61.916667', 'longitude': '28.9', 'name':'Savonlinna' },
'ILM': { 'latitude':'34.270556', 'longitude': '-77.9025', 'name':'Wilmington International' },
'SVJ': { 'latitude':'68.233333', 'longitude': '14.55', 'name':'Svolvær Airport' },
'SVK': { 'latitude':'16.733333', 'longitude': '-88.333333', 'name':'Silver Creek' },
'SVH': { 'latitude':'35.766667', 'longitude': '-80.95', 'name':'Municipal' },
'SVI': { 'latitude':'2.15', 'longitude': '-74.766667', 'name':'San Vicente' },
'SVF': { 'latitude':'8.033333', 'longitude': '2.483333', 'name':'Save' },
'SVG': { 'latitude':'58.876667', 'longitude': '5.637778', 'name':'Sola' },
'SVD': { 'latitude':'13.25', 'longitude': '-61.366667', 'name':'E. T. Joshua' },
'SVE': { 'latitude':'40.4', 'longitude': '-120.65', 'name':'Susanville' },
'SVB': { 'latitude':'-14.276944', 'longitude': '50.175', 'name':'Sambava' },
'SVC': { 'latitude':'32.633333', 'longitude': '-108.166667', 'name':'Grant County' },
'PEQ': { 'latitude':'31.4', 'longitude': '-103.516667', 'name':'Pecos City' },
'SVZ': { 'latitude':'7.783333', 'longitude': '-72.45', 'name':'San Antonio' },
'SVX': { 'latitude':'56.85', 'longitude': '60.6', 'name':'Koltsovo International Airport' },
'SVY': { 'latitude':'-9.166667', 'longitude': '159.833333', 'name':'Savo' },
'SVW': { 'latitude':'61.083333', 'longitude': '-155.566667', 'name':'Sparrevohn AFS' },
'SVT': { 'latitude':'-18.616667', 'longitude': '24.066667', 'name':'Savuti' },
'PES': { 'latitude':'61.783333', 'longitude': '34.333333', 'name':'Petrozavodsk' },
'SVR': { 'latitude':'11.083333', 'longitude': '105.805556', 'name':'Svay Rieng' },
'SVS': { 'latitude':'66.033333', 'longitude': '-149.1', 'name':'Stevens Village' },
'SVP': { 'latitude':'-12.404722', 'longitude': '16.9475', 'name':'Kuito' },
'SVQ': { 'latitude':'37.433333', 'longitude': '-5.9', 'name':'San Pablo' },
'PEL': { 'latitude':'-30.55', 'longitude': '27.916667', 'name':'Pelaneng' },
'GXF': { 'latitude':'15.983333', 'longitude': '48.891667', 'name':'Seiyun' },
'GXG': { 'latitude':'-7.516667', 'longitude': '15.833333', 'name':'Negage' },
'GXH': { 'latitude':'51.416667', 'longitude': '-1.7', 'name':'NAF' },
'PEN': { 'latitude':'5.3', 'longitude': '100.266667', 'name':'Penang International' },
'COB': { 'latitude':'-15.666667', 'longitude': '130.966667', 'name':'Coolibah' },
'GXQ': { 'latitude':'-45.5', 'longitude': '-72.516667', 'name':'Ten. Vidal' },
'PEH': { 'latitude':'-35.8', 'longitude': '-61.883333', 'name':'Pehuajo' },
'GXX': { 'latitude':'10.360278', 'longitude': '15.237222', 'name':'Yagoua' },
'GXY': { 'latitude':'40.333333', 'longitude': '-104.616667', 'name':'Weld County' },
'PEI': { 'latitude':'4.8', 'longitude': '-75.75', 'name':'Matecana' },
'LKN': { 'latitude':'68.153611', 'longitude': '13.608889', 'name':'Leknes' },
'LKO': { 'latitude':'26.766667', 'longitude': '80.883333', 'name':'Amausi' },
'LKL': { 'latitude':'70.05', 'longitude': '24.983333', 'name':'Banak' },
'LKK': { 'latitude':'58.966667', 'longitude': '-155.083333', 'name':'Kulik Lake' },
'LKH': { 'latitude':'13.3', 'longitude': '114.783333', 'name':'Long Akah' },
'LKI': { 'latitude':'-19.233333', 'longitude': '18.2', 'name':'Lakeside USAF' },
'LKG': { 'latitude':'4.2', 'longitude': '34.35', 'name':'Lokichoggio' },
'LKD': { 'latitude':'-16.166667', 'longitude': '145.5', 'name':'Lakeland Downs' },
'FLR': { 'latitude':'43.81', 'longitude': '11.205', 'name':'Peretola' },
'FLU': { 'latitude':'40.779167', 'longitude': '-73.833333', 'name':'Flushing' },
'LKC': { 'latitude':'-2.316667', 'longitude': '14.6', 'name':'Lekana' },
'FLW': { 'latitude':'39.466667', 'longitude': '-31.15', 'name':'Santa Cruz' },
'LKA': { 'latitude':'-8.35', 'longitude': '122.983333', 'name':'Larantuka' },
'FLI': { 'latitude':'65.983333', 'longitude': '-23.7', 'name':'Flateyri' },
'FLH': { 'latitude':'58.5', 'longitude': '-3.0', 'name':'Flotta' },
'FLJ': { 'latitude':'60.0325', 'longitude': '-148.008333', 'name':'Falls Bay' },
'LKZ': { 'latitude':'52.366667', 'longitude': '-1.4', 'name':'Lakenheath RAF' },
'FLL': { 'latitude':'26.0725', 'longitude': '-80.152778', 'name':'Fort Lauderdale/hollywood International' },
'FLO': { 'latitude':'34.183333', 'longitude': '-79.716667', 'name':'Florence' },
'FLN': { 'latitude':'-27.670556', 'longitude': '-48.547222', 'name':'Hercilio Luz' },
'FLA': { 'latitude':'1.583333', 'longitude': '-75.533333', 'name':'Capitolio' },
'FLC': { 'latitude':'-34.983333', 'longitude': '150.6', 'name':'Falls Creek' },
'FLB': { 'latitude':'-6.833333', 'longitude': '-43.0', 'name':'Cangapara' },
'FLE': { 'latitude':'52.3', 'longitude': '5.833333', 'name':'Fort Lee AAF' },
'FLD': { 'latitude':'43.766667', 'longitude': '-88.483333', 'name':'Fond Du Lac' },
'FLG': { 'latitude':'35.133333', 'longitude': '-111.683333', 'name':'Pulliam Field' },
'FLF': { 'latitude':'54.783333', 'longitude': '9.383333', 'name':'Schaferhaus' },
'PEG': { 'latitude':'43.095833', 'longitude': '12.513333', 'name':'Sant Egidio' },
'ILZ': { 'latitude':'49.233333', 'longitude': '18.766667', 'name':'Zilina' },
'PEA': { 'latitude':'-35.733333', 'longitude': '137.933333', 'name':'Penneshaw' },
'ILX': { 'latitude':'-5.483333', 'longitude': '145.833333', 'name':'Ileg' },
'ILY': { 'latitude':'55.683333', 'longitude': '-6.25', 'name':'Glenegedale' },
'KCE': { 'latitude':'-20.55', 'longitude': '147.866667', 'name':'Collinsville' },
'KCD': { 'latitude':'-4.4', 'longitude': '136.683333', 'name':'Kamur' },
'KCG': { 'latitude':'56.3', 'longitude': '-158.4', 'name':'Fisheries' },
'KCF': { 'latitude':'27.166667', 'longitude': '69.316667', 'name':'Kadanwari' },
'KCA': { 'latitude':'41.166667', 'longitude': '83.7', 'name':'Kuqa' },
'KCC': { 'latitude':'56.0', 'longitude': '-132.833333', 'name':'Coffman Cove SPB' },
'KCM': { 'latitude':'37.538889', 'longitude': '36.953333', 'name':'Kahramanmaras' },
'KCL': { 'latitude':'56.3', 'longitude': '-158.533333', 'name':'Lagoon' },
'KCO': { 'latitude':'40.916667', 'longitude': '29.916667', 'name':'Cengiz Topel' },
'KCN': { 'latitude':'53.416667', 'longitude': '-167.55', 'name':'SPB' },
'KCH': { 'latitude':'1.484722', 'longitude': '110.346944', 'name':'Kuching' },
'KCK': { 'latitude':'39.116667', 'longitude': '-94.65', 'name':'Fairfax Municipal' },
'KCJ': { 'latitude':'-7.216667', 'longitude': '143.6', 'name':'Komaio' },
'KCU': { 'latitude':'1.683333', 'longitude': '31.716667', 'name':'Masindi' },
'KCT': { 'latitude':'5.983333', 'longitude': '80.333333', 'name':'Koggala' },
'KCQ': { 'latitude':'56.261111', 'longitude': '-158.777778', 'name':'Chignik' },
'KCP': { 'latitude':'48.693333', 'longitude': '26.606667', 'name':'Kamenets-podolskiy' },
'KCS': { 'latitude':'24.383333', 'longitude': '131.683333', 'name':'Kings Creek Station' },
'KCR': { 'latitude':'-17.2', 'longitude': '129.366667', 'name':'Colorado Creek' },
'KCZ': { 'latitude':'33.55', 'longitude': '133.683333', 'name':'Kochi' },
'OZC': { 'latitude':'8.166667', 'longitude': '123.75', 'name':'Labo' },
'OZA': { 'latitude':'30.735278', 'longitude': '-101.202778', 'name':'Ozona Municipal' },
'OZH': { 'latitude':'47.8675', 'longitude': '35.315833', 'name':'Zaporozhye' },
'OZI': { 'latitude':'13.383333', 'longitude': '-87.933333', 'name':'Bobadilla' },
'OZU': { 'latitude':'7.566667', 'longitude': '-80.6', 'name':'Montilla' },
'OZR': { 'latitude':'53.116667', 'longitude': '22.45', 'name':'Cairns AAF' },
'OZP': { 'latitude':'13.816667', 'longitude': '-88.716667', 'name':'Moron' },
'OZZ': { 'latitude':'30.916667', 'longitude': '-6.916667', 'name':'Ouarzazate' },
'AZI': { 'latitude':'24.428333', 'longitude': '54.458056', 'name':'Bateen' },
'QDM': { 'latitude':'22.183333', 'longitude': '113.9', 'name':'Shek Mum' },
'AZN': { 'latitude':'40.733333', 'longitude': '72.3', 'name':'Andizhan' },
'AZO': { 'latitude':'42.235', 'longitude': '-85.551944', 'name':'Kalamazoo/Battle Creek Intl' },
'AZA': { 'latitude':'33.3078', 'longitude': '-111.6556', 'name':'Phoenix-Mesa Gateway' },
'AZB': { 'latitude':'-10.3', 'longitude': '149.333333', 'name':'Amazon Bay' },
'AZD': { 'latitude':'31.9', 'longitude': '54.283333', 'name':'Yazd' },
'AZG': { 'latitude':'19.083333', 'longitude': '-102.383333', 'name':'Apatzingan' },
'AZZ': { 'latitude':'-7.883333', 'longitude': '13.15', 'name':'Ambriz' },
'AZP': { 'latitude':'19.35', 'longitude': '-99.116667', 'name':'Atizapan' },
'AZR': { 'latitude':'27.883333', 'longitude': '-0.283333', 'name':'Adrar' },
'AZS': { 'latitude':'19.25', 'longitude': '-69.7', 'name':'Samaná El Catey International' },
'AZT': { 'latitude':'6.816667', 'longitude': '-73.283333', 'name':'Zapatoca' },
'QDU': { 'latitude':'51.2075', 'longitude': '6.773333', 'name':'Station' },
'TKG': { 'latitude':'-5.242222', 'longitude': '105.178889', 'name':'Branti' },
'TKD': { 'latitude':'4.883333', 'longitude': '-1.75', 'name':'Takoradi' },
'WAB': { 'latitude':'-5.483333', 'longitude': '143.733333', 'name':'Wabag' },
'EZE': { 'latitude':'-34.822222', 'longitude': '-58.535833', 'name':'Ezeiza Ministro Pistarini' },
'TKB': { 'latitude':'-7.633333', 'longitude': '146.566667', 'name':'Tekadu' },
'TKC': { 'latitude':'4.089167', 'longitude': '9.360556', 'name':'Tiko' },
'TKA': { 'latitude':'62.320556', 'longitude': '150.093611', 'name':'Talkeetna' },
'TKN': { 'latitude':'33.95', 'longitude': '131.316667', 'name':'Tokunoshima' },
'TKL': { 'latitude':'59.783333', 'longitude': '-1.25', 'name':'Taku SPB' },
'TKK': { 'latitude':'7.0', 'longitude': '152.0', 'name':'Truk' },
'TKH': { 'latitude':'15.277222', 'longitude': '100.295833', 'name':'Nakhon Sawan' },
'WAV': { 'latitude':'-17.65', 'longitude': '130.883333', 'name':'Kalkgurung' },
'TKV': { 'latitude':'-17.283333', 'longitude': '-138.333333', 'name':'Tatakoto' },
'NLC': { 'latitude':'36.333056', 'longitude': '-119.951944', 'name':'Lemoore NAS' },
'TKU': { 'latitude':'60.514167', 'longitude': '22.262778', 'name':'Turku' },
'TKR': { 'latitude':'26.033333', 'longitude': '88.466667', 'name':'Thakurgaon' },
'WAP': { 'latitude':'-43.633333', 'longitude': '-71.816667', 'name':'Alto Palena' },
'NLD': { 'latitude':'27.45', 'longitude': '-99.516667', 'name':'Intl Quetzalcoatl' },
'NLG': { 'latitude':'56.016667', 'longitude': '-161.15', 'name':'Nelson Lagoon' },
'TKQ': { 'latitude':'-4.883333', 'longitude': '29.666667', 'name':'Kigoma' },
'NLL': { 'latitude':'-21.75', 'longitude': '120.2', 'name':'Nullagine' },
'TKX': { 'latitude':'-14.5', 'longitude': '-144.966667', 'name':'Takaroa' },
'UFA': { 'latitude':'54.5575', 'longitude': '55.874444', 'name':'Ufa' },
'TKY': { 'latitude':'-30.333333', 'longitude': '142.75', 'name':'Turkey Creek' },
'XKH': { 'latitude':'19.5', 'longitude': '103.0', 'name':'Xieng Khouang' },
'XKO': { 'latitude':'53.566667', 'longitude': '-127.933333', 'name':'Kemano' },
'XKC': { 'latitude':'66.0', 'longitude': '12.583333', 'name':'Sandnes Rail St.' },
'XKA': { 'latitude':'12.483333', 'longitude': '1.516667', 'name':'Kantchari' },
'XKY': { 'latitude':'13.083333', 'longitude': '-1.083333', 'name':'Kaya' },
'XKS': { 'latitude':'53.533333', 'longitude': '-88.75', 'name':'Kasabonika' },
'TCB': { 'latitude':'26.745278', 'longitude': '-77.391389', 'name':'Treasure Cay' },
'GNR': { 'latitude':'-39.033333', 'longitude': '-67.583333', 'name':'General Roca' },
'GNS': { 'latitude':'1.166389', 'longitude': '97.704722', 'name':'Binaka' },
'AIY': { 'latitude':'39.366667', 'longitude': '-74.45', 'name':'Bader Field' },
'GNT': { 'latitude':'35.15', 'longitude': '-107.866667', 'name':'Milan' },
'GNU': { 'latitude':'59.116667', 'longitude': '-161.516667', 'name':'Goodnews Bay' },
'AIU': { 'latitude':'-20.033333', 'longitude': '-158.1', 'name':'Atiu Island' },
'MKN': { 'latitude':'-4.016667', 'longitude': '153.675', 'name':'Malekolon' },
'AIW': { 'latitude':'-27.983333', 'longitude': '17.583056', 'name':'Ai-ais' },
'VEV': { 'latitude':'-7.833333', 'longitude': '156.7', 'name':'Barakoma' },
'MKL': { 'latitude':'35.6', 'longitude': '-88.915556', 'name':'Mc Kellar-Sipes Regional' },
'VER': { 'latitude':'19.133333', 'longitude': '-96.2', 'name':'Las Bajadas' },
'MKJ': { 'latitude':'-0.033333', 'longitude': '15.616667', 'name':'Makoua' },
'VEG': { 'latitude':'5.55', 'longitude': '-59.283333', 'name':'Maikwak' },
'VEE': { 'latitude':'67.016667', 'longitude': '-146.416667', 'name':'Venetie' },
'VEL': { 'latitude':'40.45', 'longitude': '-109.516667', 'name':'Vernal' },
'VEJ': { 'latitude':'55.7', 'longitude': '9.533333', 'name':'Vejle' },
'MKW': { 'latitude':'-0.883333', 'longitude': '134.05', 'name':'Rendani' },
'MKV': { 'latitude':'-25.966667', 'longitude': '133.2', 'name':'Mt Cavenagh' },
'AIO': { 'latitude':'41.4', 'longitude': '-95.016667', 'name':'Municipal' },
'GNA': { 'latitude':'53.666667', 'longitude': '23.8', 'name':'Grodna' },
'PDZ': { 'latitude':'9.966667', 'longitude': '-62.233333', 'name':'Pedernales' },
'SST': { 'latitude':'-35.266667', 'longitude': '-59.633333', 'name':'Santa Teresita' },
'MKS': { 'latitude':'11.683333', 'longitude': '38.15', 'name':'Mekane Selam' },
'SYD': { 'latitude':'-33.946111', 'longitude': '151.177222', 'name':'Kingsford Smith' },
'MKR': { 'latitude':'-26.6', 'longitude': '118.55', 'name':'Meekatharra' },
'GND': { 'latitude':'12.004167', 'longitude': '-61.786111', 'name':'Point Salines International' },
'WRG': { 'latitude':'56.466667', 'longitude': '-132.383333', 'name':'Wrangell SPB' },
'MKP': { 'latitude':'-16.583333', 'longitude': '-143.666667', 'name':'Makemo' },
'GNI': { 'latitude':'23.1', 'longitude': '121.466667', 'name':'Green Island' },
'GNN': { 'latitude':'7.15', 'longitude': '40.716667', 'name':'Ghinnir' },
'WRA': { 'latitude':'6.966667', 'longitude': '45.333333', 'name':'Warder' },
'SSO': { 'latitude':'-22.1', 'longitude': '-45.033333', 'name':'Sao Lourenco' },
'PDX': { 'latitude':'45.588611', 'longitude': '-122.5975', 'name':'Portland International' },
'MKY': { 'latitude':'-21.166667', 'longitude': '149.183333', 'name':'Mackay' },
'WRO': { 'latitude':'51.102778', 'longitude': '16.885833', 'name':'Copernicus Airport' },
'GNM': { 'latitude':'-14.216667', 'longitude': '-42.783333', 'name':'Guanambi' },
'SSH': { 'latitude':'27.977222', 'longitude': '34.395', 'name':'Ophira International' },
'ZRV': { 'latitude':'4.616667', 'longitude': '-54.4', 'name':'Providence Rail' },
'ZRR': { 'latitude':'67.45', 'longitude': '-133.75', 'name':'Harbour' },
'ZRP': { 'latitude':'40.733333', 'longitude': '-74.166667', 'name':'Pennsylvania Railroad Station' },
'ZRZ': { 'latitude':'49.0', 'longitude': '-72.5', 'name':'New Carrolton RR' },
'ZRF': { 'latitude':'-32.85', 'longitude': '24.166667', 'name':'Park & Ride Bus Svc' },
'ZRD': { 'latitude':'48.166667', 'longitude': '-65.833333', 'name':'Richmond VA Rail' },
'ZRC': { 'latitude':'-32.816667', 'longitude': '-70.666667', 'name':'Bus Station' },
'ZRM': { 'latitude':'-1.883333', 'longitude': '138.766667', 'name':'Sarmi' },
'ZRL': { 'latitude':'40.066667', 'longitude': '38.766667', 'name':'Lancaster PA Rail' },
'ZRK': { 'latitude':'-32.85', 'longitude': '24.166667', 'name':'VanGalder Bus Termina' },
'ZRJ': { 'latitude':'52.95', 'longitude': '-91.316667', 'name':'Round Lake' },
'ZRI': { 'latitude':'-1.416667', 'longitude': '136.233333', 'name':'Serui' },
'ZRH': { 'latitude':'47.464722', 'longitude': '8.549167', 'name':'Zürich-Kloten' },
'RSL': { 'latitude':'38.883333', 'longitude': '-98.85', 'name':'Russell' },
'RSN': { 'latitude':'32.516667', 'longitude': '-92.616667', 'name':'Ruston' },
'SSF': { 'latitude':'6.233333', 'longitude': '-76.733333', 'name':'Stinson Municipal' },
'RSH': { 'latitude':'61.783333', 'longitude': '-161.333333', 'name':'Russian SPB' },
'RSI': { 'latitude':'9.316667', 'longitude': '-79.283333', 'name':'Rio Sidra' },
'RSJ': { 'latitude':'48.633333', 'longitude': '-122.85', 'name':'Rosario SPB' },
'RSK': { 'latitude':'-1.5', 'longitude': '134.25', 'name':'Ransiki' },
'RSD': { 'latitude':'24.95', 'longitude': '-76.083333', 'name':'S Eleuthera' },
'RSE': { 'latitude':'-33.866667', 'longitude': '151.266667', 'name':'Rose Bay' },
'RSG': { 'latitude':'-5.95', 'longitude': '-49.65', 'name':'Serra Pelada' },
'RSA': { 'latitude':'-36.616667', 'longitude': '-64.283333', 'name':'Santa Rosa' },
'RSB': { 'latitude':'-25.783333', 'longitude': '139.616667', 'name':'Roseberth' },
'RSX': { 'latitude':'44.984722', 'longitude': '-73.352222', 'name':'Rouses Point' },
'RST': { 'latitude':'43.908333', 'longitude': '-92.5', 'name':'International' },
'RSU': { 'latitude':'34.733333', 'longitude': '127.766667', 'name':'Yeosu' },
'RSW': { 'latitude':'26.542222', 'longitude': '-81.755278', 'name':'Southwest Florida Reg' },
'RSP': { 'latitude':'58.166667', 'longitude': '-154.833333', 'name':'Raspberry Strait' },
'RSS': { 'latitude':'11.783333', 'longitude': '34.4', 'name':'Roseires' },
'JFK': { 'latitude':'40.633333', 'longitude': '-73.783333', 'name':'John F Kennedy Intl' },
'DKR': { 'latitude':'14.739722', 'longitude': '-17.490278', 'name':'Dakar-Yoff-Léopold Sédar Senghor International' },
'JFN': { 'latitude':'41.733333', 'longitude': '-80.766667', 'name':'Ashtabula' },
'JFM': { 'latitude':'-32.043333', 'longitude': '115.739444', 'name':'Heliport' },
'JFR': { 'latitude':'62.0', 'longitude': '-49.65', 'name':'Frederikshab' },
'DKK': { 'latitude':'42.483333', 'longitude': '-79.333333', 'name':'Dunkirk' },
'DKI': { 'latitude':'-17.933333', 'longitude': '146.166667', 'name':'Dunk Island' },
'URD': { 'latitude':'54.433333', 'longitude': '11.2', 'name':'Burg Feuerstein' },
'URG': { 'latitude':'-29.783333', 'longitude': '-57.033333', 'name':'Ruben Berta' },
'URA': { 'latitude':'51.150833', 'longitude': '51.543056', 'name':'Uralsk / Podstepnyy' },
'URB': { 'latitude':'-20.8', 'longitude': '-51.566667', 'name':'Ernesto Pochler' },
'URC': { 'latitude':'43.933333', 'longitude': '87.733333', 'name':'Urumqi' },
'URM': { 'latitude':'5.341667', 'longitude': '-62.758333', 'name':'Uriman' },
'URO': { 'latitude':'49.383333', 'longitude': '1.183333', 'name':'Boos' },
'URI': { 'latitude':'3.216667', 'longitude': '-74.4', 'name':'Uribe' },
'URJ': { 'latitude':'60.116667', 'longitude': '64.833333', 'name':'Uraj' },
'URT': { 'latitude':'9.1', 'longitude': '99.333333', 'name':'Surat Thani' },
'URR': { 'latitude':'6.333333', 'longitude': '-76.183333', 'name':'Urrao' },
'URS': { 'latitude':'51.750556', 'longitude': '36.295556', 'name':'Kursk' },
'URY': { 'latitude':'31.333333', 'longitude': '37.416667', 'name':'Gurayat' },
'URZ': { 'latitude':'32.9', 'longitude': '66.616667', 'name':'Uruzgan' },
'PYX': { 'latitude':'12.95', 'longitude': '100.883333', 'name':'Pattaya' },
'IPC': { 'latitude':'-27.164722', 'longitude': '-109.416667', 'name':'Mataveri Intl' },
'IPA': { 'latitude':'-18.75', 'longitude': '169.183333', 'name':'Ipota' },
'IPG': { 'latitude':'-3.333333', 'longitude': '-69.416667', 'name':'Ipiranga' },
'IPE': { 'latitude':'7.783333', 'longitude': '122.583333', 'name':'Ipil' },
'IPH': { 'latitude':'4.568056', 'longitude': '101.092222', 'name':'Sultan Azlan Shah Airport' },
'IPI': { 'latitude':'0.866667', 'longitude': '-77.7', 'name':'San Luis' },
'IPN': { 'latitude':'-19.5', 'longitude': '-42.533333', 'name':'Usiminas' },
'IPL': { 'latitude':'32.833333', 'longitude': '-115.566667', 'name':'Imperial County' },
'PYH': { 'latitude':'5.6', 'longitude': '-67.5', 'name':'Puerto Ayacucho' },
'PYJ': { 'latitude':'66.416667', 'longitude': '112.05', 'name':'Polyarnyj' },
'PYL': { 'latitude':'60.683333', 'longitude': '-147.916667', 'name':'Perry SPB' },
'IPW': { 'latitude':'52.033333', 'longitude': '1.2', 'name':'Ipswich' },
'IPT': { 'latitude':'41.25', 'longitude': '-76.916667', 'name':'Lycoming County' },
'IPU': { 'latitude':'-14.133333', 'longitude': '-39.733333', 'name':'Ipiau' },
'PYA': { 'latitude':'5.75', 'longitude': '-74.4', 'name':'Puerto Boyaca' },
'PYB': { 'latitude':'18.85', 'longitude': '82.583333', 'name':'Jeypore' },
'PYC': { 'latitude':'9.574444', 'longitude': '-79.605833', 'name':'Playon Chico' },
'PYE': { 'latitude':'-9.016667', 'longitude': '-158.033333', 'name':'Penrhyn Island' },
'NGD': { 'latitude':'18.733333', 'longitude': '-64.316667', 'name':'Anegada' },
'NGE': { 'latitude':'7.35', 'longitude': '13.566667', 'name':'Ngaoundere' },
'HDS': { 'latitude':'-24.368611', 'longitude': '31.048611', 'name':'Hoedspruit Airport' },
'NGA': { 'latitude':'-34.25', 'longitude': '148.25', 'name':'Young' },
'NGB': { 'latitude':'29.826667', 'longitude': '121.461944', 'name':'Lishe International Airport' },
'NGC': { 'latitude':'36.183333', 'longitude': '-112.133333', 'name':'North Rim' },
'NGL': { 'latitude':'-14.1', 'longitude': '32.65', 'name':'Ngala Airfield' },
'NGM': { 'latitude':'13.449722', 'longitude': '144.75', 'name':'Agana NAS' },
'NGN': { 'latitude':'9.066667', 'longitude': '-78.016667', 'name':'Nargana' },
'NGO': { 'latitude':'34.858333', 'longitude': '136.805278', 'name':'Centrair' },
'NGI': { 'latitude':'-18.033333', 'longitude': '179.3', 'name':'Ngau Island' },
'HDY': { 'latitude':'7.016667', 'longitude': '100.45', 'name':'Hat Yai' },
'HDG': { 'latitude':'36.5258', 'longitude': '114.425', 'name':'Hebei Handan' },
'NGU': { 'latitude':'36.937778', 'longitude': '-76.289444', 'name':'Nas Chambers' },
'NGV': { 'latitude':'23.076111', 'longitude': '34.374444', 'name':'Ngiva' },
'HDD': { 'latitude':'25.3', 'longitude': '68.383333', 'name':'Hyderabad' },
'HDB': { 'latitude':'49.393333', 'longitude': '8.6525', 'name':'Heidelberg' },
'NGR': { 'latitude':'-5.666667', 'longitude': '141.116667', 'name':'Ningerum' },
'NGS': { 'latitude':'32.933333', 'longitude': '129.933333', 'name':'Nagasaki' },
'HDN': { 'latitude':'40.519444', 'longitude': '-106.869444', 'name':'Yampa Valley' },
'HDM': { 'latitude':'34.85', 'longitude': '48.55', 'name':'Hamadan' },
'NGX': { 'latitude':'28.666667', 'longitude': '84.25', 'name':'Manang' },
'NGZ': { 'latitude':'49.266667', 'longitude': '-1.283333', 'name':'NAS' },
'HDH': { 'latitude':'3.866667', 'longitude': '154.983333', 'name':'Dillingham Airfield' },
'BMB': { 'latitude':'2.3', 'longitude': '22.55', 'name':'Bumba' },
'BMC': { 'latitude':'41.533333', 'longitude': '-112.05', 'name':'Brigham City' },
'PDP': { 'latitude':'-34.858333', 'longitude': '-55.091667', 'name':'Capitan Corbeta CA Curbelo International Airport' },
'BMA': { 'latitude':'59.352778', 'longitude': '17.95', 'name':'Bromma' },
'BMF': { 'latitude':'5.733333', 'longitude': '22.8', 'name':'Bakouma' },
'BMG': { 'latitude':'39.133333', 'longitude': '-86.616667', 'name':'Bloomington' },
'BMD': { 'latitude':'-20.733333', 'longitude': '44.05', 'name':'Belo' },
'BME': { 'latitude':'-17.944722', 'longitude': '122.231667', 'name':'Broome' },
'BMJ': { 'latitude':'5.433333', 'longitude': '-58.55', 'name':'Baramita' },
'BMK': { 'latitude':'53.6', 'longitude': '6.7', 'name':'Borkum' },
'BMH': { 'latitude':'-6.366667', 'longitude': '144.633333', 'name':'Bomai' },
'BMI': { 'latitude':'40.477222', 'longitude': '-88.915833', 'name':'Central Illinois Regional Airport at Bloomington-Normal' },
'BMN': { 'latitude':'37.115556', 'longitude': '43.266667', 'name':'Bamerny' },
'BMO': { 'latitude':'24.266667', 'longitude': '97.25', 'name':'Bhamo' },
'BML': { 'latitude':'44.575278', 'longitude': '-71.175833', 'name':'Berlin Municipal Airport' },
'BMM': { 'latitude':'2.075556', 'longitude': '11.493333', 'name':'Bitam' },
'BMR': { 'latitude':'53.731111', 'longitude': '7.375833', 'name':'Baltrum' },
'BMS': { 'latitude':'-14.216667', 'longitude': '-41.666667', 'name':'Brumado' },
'BMP': { 'latitude':'-20.783333', 'longitude': '149.233333', 'name':'Brampton Island' },
'BMQ': { 'latitude':'-3.95', 'longitude': '39.733333', 'name':'Bamburi' },
'BMV': { 'latitude':'12.666667', 'longitude': '108.1', 'name':'Phung-Duc' },
'BMW': { 'latitude':'21.133333', 'longitude': '1.066667', 'name':'Bordj Badji Mokhtar' },
'BMT': { 'latitude':'18.5', 'longitude': '-73.95', 'name':'Beaumont Muni' },
'BMU': { 'latitude':'-8.466667', 'longitude': '118.716667', 'name':'Bima' },
'BMZ': { 'latitude':'-7.833333', 'longitude': '143.233333', 'name':'Bamu' },
'BMX': { 'latitude':'59.366667', 'longitude': '-155.266667', 'name':'Big Mountain' },
'BMY': { 'latitude':'-19.75', 'longitude': '163.666667', 'name':'Belep Island' },
'SHP': { 'latitude':'39.933333', 'longitude': '119.5', 'name':'Qinhuangdao' },
'SHQ': { 'latitude':'-27.951944', 'longitude': '153.417778', 'name':'Southport' },
'SHR': { 'latitude':'44.766667', 'longitude': '-106.966667', 'name':'Sheridan' },
'SHS': { 'latitude':'30.316667', 'longitude': '112.233333', 'name':'Shashi' },
'SHT': { 'latitude':'-36.433333', 'longitude': '145.4', 'name':'Shepparton' },
'SHU': { 'latitude':'-11.166667', 'longitude': '133.833333', 'name':'Smith Point' },
'SHV': { 'latitude':'32.45', 'longitude': '-93.816667', 'name':'Regional' },
'RMS': { 'latitude':'49.45', 'longitude': '7.55', 'name':'Ramstein' },
'SHX': { 'latitude':'62.633333', 'longitude': '-159.583333', 'name':'Shageluk' },
'SHY': { 'latitude':'-3.666667', 'longitude': '33.433333', 'name':'Shinyanga' },
'SHZ': { 'latitude':'-30.583333', 'longitude': '28.0', 'name':'Seshutes' },
'SHA': { 'latitude':'31.2', 'longitude': '121.341111', 'name':'Hongqiao' },
'SHB': { 'latitude':'43.580278', 'longitude': '144.96', 'name':'Nakashibetsu' },
'SHC': { 'latitude':'12.983333', 'longitude': '39.133333', 'name':'Indaselassie' },
'SHD': { 'latitude':'38.266667', 'longitude': '-78.9', 'name':'Shenandoah Valley' },
'SHE': { 'latitude':'41.871667', 'longitude': '123.433333', 'name':'Shenyang' },
'SHF': { 'latitude':'39.983333', 'longitude': '119.75', 'name':'Shanhaiguan' },
'SHG': { 'latitude':'66.883333', 'longitude': '-157.05', 'name':'Shungnak' },
'SHH': { 'latitude':'66.25', 'longitude': '-166.05', 'name':'Shishmaref' },
'SHI': { 'latitude':'24.816667', 'longitude': '125.15', 'name':'Shimojishima' },
'SHJ': { 'latitude':'25.328611', 'longitude': '55.517222', 'name':'Sharjah' },
'SHK': { 'latitude':'-29.9', 'longitude': '28.25', 'name':'Sehonghong' },
'SHL': { 'latitude':'25.703611', 'longitude': '91.978611', 'name':'Barapani' },
'SHM': { 'latitude':'33.661389', 'longitude': '135.358056', 'name':'Shirahama' },
'SHN': { 'latitude':'47.241667', 'longitude': '-123.133333', 'name':'Sanderson Field' },
'SHO': { 'latitude':'38.2', 'longitude': '128.6', 'name':'Seolak' },
'MGC': { 'latitude':'41.7', 'longitude': '-86.816667', 'name':'Michigan City Arpt' },
'GZO': { 'latitude':'-8.166667', 'longitude': '157.0', 'name':'Gizo' },
'MGA': { 'latitude':'12.133333', 'longitude': '-86.183333', 'name':'Augusto C Sandino' },
'GZM': { 'latitude':'36.041667', 'longitude': '14.208333', 'name':'Gozo Heliport' },
'MGG': { 'latitude':'-6.033333', 'longitude': '143.366667', 'name':'Margarima' },
'MGF': { 'latitude':'-23.416667', 'longitude': '-51.966667', 'name':'Regional De Maringa SBMG' },
'MGE': { 'latitude':'33.912222', 'longitude': '-84.515278', 'name':'Dobbins Afb' },
'MGD': { 'latitude':'-13.033333', 'longitude': '-64.416667', 'name':'Magdalena' },
'MGK': { 'latitude':'20.283333', 'longitude': '98.9', 'name':'Mong Ton' },
'MGJ': { 'latitude':'41.51', 'longitude': '-74.264722', 'name':'Orange County' },
'MGI': { 'latitude':'11.116944', 'longitude': '124.466944', 'name':'Aransas National Wildlife Refuge' },
'MGH': { 'latitude':'-30.8575', 'longitude': '30.343056', 'name':'Margate' },
'MGO': { 'latitude':'-1.733333', 'longitude': '10.216667', 'name':'Manega' },
'MGN': { 'latitude':'9.266667', 'longitude': '-74.883333', 'name':'Baracoa' },
'MGM': { 'latitude':'32.3', 'longitude': '-86.4', 'name':'Dannelly Fld' },
'MGL': { 'latitude':'51.230278', 'longitude': '6.504444', 'name':'Moenchen-gl. - Dus Exp' },
'MGS': { 'latitude':'-21.916667', 'longitude': '-157.916667', 'name':'Mangaia Island' },
'MGR': { 'latitude':'31.083333', 'longitude': '-83.8', 'name':'Moultrie Municipal' },
'MGQ': { 'latitude':'2.014444', 'longitude': '45.304722', 'name':'Mogadishu International Airport' },
'MGP': { 'latitude':'-4.15', 'longitude': '153.016667', 'name':'Manga' },
'MGW': { 'latitude':'39.633333', 'longitude': '-79.916667', 'name':'Morgantown' },
'MGV': { 'latitude':'-18.616667', 'longitude': '126.883333', 'name':'Margaret River' },
'MGU': { 'latitude':'15.133333', 'longitude': '97.916667', 'name':'Manaung' },
'MGT': { 'latitude':'-12.1', 'longitude': '134.9', 'name':'Milingimbi' },
'TBA': { 'latitude':'-5.6', 'longitude': '144.683333', 'name':'Tabibuga' },
'MGZ': { 'latitude':'12.45', 'longitude': '98.616667', 'name':'Myeik' },
'GZT': { 'latitude':'37.066667', 'longitude': '37.333333', 'name':'Gaziantep' },
'MGX': { 'latitude':'-2.25', 'longitude': '11.0', 'name':'Moabi' },
'TBE': { 'latitude':'-4.183333', 'longitude': '143.516667', 'name':'Timbunke' },
'TBD': { 'latitude':'2.75', 'longitude': '-77.583333', 'name':'Timbiqui' },
'GZP': { 'latitude':'36.2993', 'longitude': '32.3014', 'name':'Gazipasa' },
'TBF': { 'latitude':'-1.333333', 'longitude': '174.833333', 'name':'Tabiteuea North' },
'LUP': { 'latitude':'21.183333', 'longitude': '-156.966667', 'name':'Kalaupapa' },
'LUQ': { 'latitude':'-33.266667', 'longitude': '-66.333333', 'name':'San Luis' },
'LUR': { 'latitude':'68.866667', 'longitude': '-166.1', 'name':'Cape Lisburne' },
'LUS': { 'latitude':'-4.833333', 'longitude': '18.733333', 'name':'Lusanga' },
'LUT': { 'latitude':'-15.433333', 'longitude': '144.816667', 'name':'Laura Station' },
'LUU': { 'latitude':'-15.666667', 'longitude': '144.166667', 'name':'Laura' },
'LUV': { 'latitude':'-5.65', 'longitude': '132.725', 'name':'Langgur' },
'LUW': { 'latitude':'-0.933333', 'longitude': '122.783333', 'name':'Luwuk' },
'LUX': { 'latitude':'49.616667', 'longitude': '6.2', 'name':'Findel' },
'LUY': { 'latitude':'-4.783333', 'longitude': '38.283333', 'name':'Lushoto' },
'LUZ': { 'latitude':'29.633333', 'longitude': '115.95', 'name':'Lushan' },
'LUA': { 'latitude':'27.7', 'longitude': '86.733333', 'name':'Lukla' },
'LUB': { 'latitude':'2.4', 'longitude': '-59.433333', 'name':'Lumid Pau' },
'LUC': { 'latitude':'-16.75', 'longitude': '179.416667', 'name':'Laucala Is' },
'LUD': { 'latitude':'-26.666667', 'longitude': '15.341667', 'name':'Luderitz' },
'LUE': { 'latitude':'48.35', 'longitude': '19.741667', 'name':'Lucenec' },
'LUF': { 'latitude':'6.466667', 'longitude': '-57.65', 'name':'Luke Afb' },
'LUG': { 'latitude':'46.002685', 'longitude': '8.908882', 'name':'Lugano' },
'LUH': { 'latitude':'30.9', 'longitude': '75.85', 'name':'Amritsar' },
'LUI': { 'latitude':'15.133333', 'longitude': '-86.583333', 'name':'La Union' },
'LUJ': { 'latitude':'-31.366667', 'longitude': '29.583333', 'name':'Lusikisiki' },
'LUK': { 'latitude':'39.103333', 'longitude': '-84.418611', 'name':'Cincinnati Municipal-Lunken Field' },
'LUL': { 'latitude':'31.673056', 'longitude': '-89.172778', 'name':'Hesler-Noble Field' },
'LUM': { 'latitude':'24.483333', 'longitude': '98.516667', 'name':'Mangshi' },
'LUN': { 'latitude':'-15.416667', 'longitude': '28.333333', 'name':'Lusaka' },
'LUO': { 'latitude':'-11.768056', 'longitude': '19.897778', 'name':'Luena' },
'SOL': { 'latitude':'64.583333', 'longitude': '-164.3', 'name':'Solomon' },
'RMB': { 'latitude':'24.25', 'longitude': '55.783333', 'name':'Buraimi' },
'RMA': { 'latitude':'-26.55', 'longitude': '148.766667', 'name':'Roma' },
'LNI': { 'latitude':'70.916667', 'longitude': '-153.25', 'name':'Dew Station' },
'LNH': { 'latitude':'-21.0', 'longitude': '137.916667', 'name':'Lake Nash' },
'UOX': { 'latitude':'34.383333', 'longitude': '-89.533333', 'name':'University-Oxford' },
'RMD': { 'latitude':'18.766667', 'longitude': '79.4', 'name':'Ramagundam' },
'LNJ': { 'latitude':'23.9', 'longitude': '100.033333', 'name':'Lincang' },
'QFQ': { 'latitude':'61.929444', 'longitude': '5.119167', 'name':'Harbour' },
'QFI': { 'latitude':'68.7', 'longitude': '-52.966667', 'name':'Heliport' },
'QFK': { 'latitude':'62.049167', 'longitude': '5.348056', 'name':'Harbour' },
'KEO': { 'latitude':'9.55', 'longitude': '-7.566667', 'name':'Odienne' },
'KEN': { 'latitude':'7.866667', 'longitude': '-11.2', 'name':'Kenema' },
'KEM': { 'latitude':'65.783333', 'longitude': '24.583333', 'name':'Kemi/Tornio' },
'KEL': { 'latitude':'54.379444', 'longitude': '10.145278', 'name':'Kiel-Holtenau' },
'KEK': { 'latitude':'59.366667', 'longitude': '-157.483333', 'name':'Ekwok' },
'KEJ': { 'latitude':'55.333333', 'longitude': '86.083333', 'name':'Kemerovo' },
'KEI': { 'latitude':'-6.533333', 'longitude': '139.3', 'name':'Kepi' },
'KEH': { 'latitude':'47.738333', 'longitude': '-122.268056', 'name':'Kenmore Air Harbor' },
'KEG': { 'latitude':'-5.808333', 'longitude': '145.083333', 'name':'Keglsugl' },
'KEF': { 'latitude':'63.983333', 'longitude': '-22.6', 'name':'Keflavik International' },
'KEE': { 'latitude':'-0.1', 'longitude': '14.55', 'name':'Kelle' },
'KED': { 'latitude':'16.166667', 'longitude': '-13.516667', 'name':'Kaedi' },
'KEC': { 'latitude':'-10.35', 'longitude': '28.633333', 'name':'Kasenga' },
'KEB': { 'latitude':'59.366667', 'longitude': '-151.916667', 'name':'Nanwalek' },
'KEA': { 'latitude':'-7.666667', 'longitude': '140.5', 'name':'Keisah' },
'KEZ': { 'latitude':'6.85', 'longitude': '80.55', 'name':'Kelaniya River' },
'KEY': { 'latitude':'-0.366667', 'longitude': '35.508333', 'name':'Kericho' },
'KEX': { 'latitude':'-7.766667', 'longitude': '145.9', 'name':'Kanabea' },
'KEW': { 'latitude':'52.992222', 'longitude': '-92.838889', 'name':'Keewaywin' },
'KEV': { 'latitude':'61.866667', 'longitude': '24.8', 'name':'Halli' },
'KEU': { 'latitude':'50.6', 'longitude': '-4.266667', 'name':'Kelly Bar' },
'KET': { 'latitude':'21.3', 'longitude': '99.616667', 'name':'Keng Tung' },
'KES': { 'latitude':'56.25', 'longitude': '-96.966667', 'name':'Kelsey' },
'KER': { 'latitude':'30.266667', 'longitude': '56.966667', 'name':'Kerman' },
'KEQ': { 'latitude':'-0.633333', 'longitude': '133.116667', 'name':'Kebar' },
'KEP': { 'latitude':'28.0', 'longitude': '81.633333', 'name':'Nepalganj' },
'SDN': { 'latitude':'61.766667', 'longitude': '6.216667', 'name':'Sandane' },
'OTH': { 'latitude':'43.416667', 'longitude': '-124.25', 'name':'North Bend' },
'OTI': { 'latitude':'2.046111', 'longitude': '128.324722', 'name':'Morotai Island' },
'OTJ': { 'latitude':'-21.733333', 'longitude': '18.25', 'name':'Otjiwarongo' },
'OTL': { 'latitude':'17.533333', 'longitude': '-14.716667', 'name':'Boutilimit' },
'OTM': { 'latitude':'41.1', 'longitude': '-92.45', 'name':'Industrial' },
'OTN': { 'latitude':'38.866667', 'longitude': '-87.433333', 'name':'Green' },
'OTO': { 'latitude':'35.072222', 'longitude': '-105.935556', 'name':'Vor' },
'OTA': { 'latitude':'11.066667', 'longitude': '37.883333', 'name':'Mota' },
'OTC': { 'latitude':'13.433333', 'longitude': '14.733333', 'name':'Bol' },
'OTD': { 'latitude':'8.666667', 'longitude': '-79.583333', 'name':'Contadora' },
'OTG': { 'latitude':'43.65', 'longitude': '-95.583333', 'name':'Worthington' },
'OTY': { 'latitude':'-6.583333', 'longitude': '155.683333', 'name':'Oria' },
'OTZ': { 'latitude':'66.866667', 'longitude': '-162.633333', 'name':'Kotzebue' },
'OTP': { 'latitude':'44.580556', 'longitude': '26.088889', 'name':'Henri Coanda International' },
'OTR': { 'latitude':'8.566667', 'longitude': '-82.933333', 'name':'Coto 47' },
'OTS': { 'latitude':'48.5', 'longitude': '-122.616667', 'name':'Anacortes' },
'OTU': { 'latitude':'6.983333', 'longitude': '-74.716667', 'name':'Otu' },
'OTV': { 'latitude':'-5.333333', 'longitude': '159.5', 'name':'Ontong Java' },
'AXR': { 'latitude':'-15.35', 'longitude': '-146.666667', 'name':'Arutua' },
'AXS': { 'latitude':'34.702778', 'longitude': '-99.333333', 'name':'Municipal' },
'AXP': { 'latitude':'22.45', 'longitude': '-73.966667', 'name':'Springpoint Arpt' },
'AXV': { 'latitude':'40.566667', 'longitude': '-84.183333', 'name':'Neil Armstrong' },
'AXT': { 'latitude':'39.615556', 'longitude': '140.218611', 'name':'Akita' },
'AXU': { 'latitude':'14.120833', 'longitude': '38.7125', 'name':'Axum' },
'AXX': { 'latitude':'36.416667', 'longitude': '-105.283333', 'name':'Angel Fire' },
'AXB': { 'latitude':'44.2525', 'longitude': '-75.901389', 'name':'Alexandria Bay' },
'AXC': { 'latitude':'-23.083333', 'longitude': '145.25', 'name':'Aramac' },
'AXA': { 'latitude':'18.204722', 'longitude': '-63.055', 'name':'Wallblake' },
'AXG': { 'latitude':'43.066667', 'longitude': '-94.233333', 'name':'Algona' },
'AXD': { 'latitude':'40.851111', 'longitude': '25.951111', 'name':'Dimokritos' },
'AXE': { 'latitude':'-26.883333', 'longitude': '-52.383333', 'name':'Xanxere' },
'AXK': { 'latitude':'13.866667', 'longitude': '46.3', 'name':'Ataq' },
'AXN': { 'latitude':'45.783333', 'longitude': '-95.266667', 'name':'Alexandria' },
'AXL': { 'latitude':'-19.116667', 'longitude': '136.766667', 'name':'Alexandria' },
'AXM': { 'latitude':'4.516667', 'longitude': '-75.666667', 'name':'El Eden' },
'OFK': { 'latitude':'41.983333', 'longitude': '-97.433333', 'name':'Stefan Field' },
'MZT': { 'latitude':'23.233333', 'longitude': '-106.416667', 'name':'Gen Rafael Buelna' },
'MZU': { 'latitude':'26.333333', 'longitude': '85.508333', 'name':'Muzaffarpur' },
'MZV': { 'latitude':'4.048333', 'longitude': '114.805', 'name':'Mulu, Sarawak' },
'MZW': { 'latitude':'33.55', 'longitude': '-0.283333', 'name':'Mechria' },
'MZP': { 'latitude':'-41.116667', 'longitude': '173.0', 'name':'Motueka' },
'MZQ': { 'latitude':'-27.633333', 'longitude': '32.05', 'name':'Mkuze' },
'MZR': { 'latitude':'36.706944', 'longitude': '67.209722', 'name':'Mazar-i-sharif' },
'MZX': { 'latitude':'6.35', 'longitude': '39.716667', 'name':'Mena' },
'EPL': { 'latitude':'48.333333', 'longitude': '6.069444', 'name':'Mirecourt' },
'MZZ': { 'latitude':'40.483333', 'longitude': '-85.683333', 'name':'Marion' },
'MZD': { 'latitude':'-2.716667', 'longitude': '-78.316667', 'name':'Mendez' },
'MZE': { 'latitude':'17.25', 'longitude': '-89.6', 'name':'Manatee' },
'MZF': { 'latitude':'-30.85', 'longitude': '29.766667', 'name':'Mzamba' },
'MZG': { 'latitude':'23.533333', 'longitude': '119.583333', 'name':'Makung' },
'MZA': { 'latitude':'29.483333', 'longitude': '77.7', 'name':'Muzaffarnagar' },
'MZB': { 'latitude':'-11.35', 'longitude': '40.35', 'name':'Mocimboa Praia' },
'MZC': { 'latitude':'0.783333', 'longitude': '11.566667', 'name':'Mitzic' },
'MZL': { 'latitude':'5.083333', 'longitude': '-75.666667', 'name':'Santaguida' },
'MZM': { 'latitude':'50.066667', 'longitude': '3.066667', 'name':'Frescaty' },
'MZN': { 'latitude':'-5.866667', 'longitude': '144.666667', 'name':'Minj' },
'MZO': { 'latitude':'20.286389', 'longitude': '-77.093889', 'name':'Manzanillo' },
'MZH': { 'latitude':'40.829444', 'longitude': '35.521944', 'name':'Merzifon' },
'MZI': { 'latitude':'14.5', 'longitude': '-4.2', 'name':'Mopti' },
'MZJ': { 'latitude':'32.509722', 'longitude': '-111.325278', 'name':'Marana' },
'MZK': { 'latitude':'1.983333', 'longitude': '173.666667', 'name':'Marakei' },
'BOY': { 'latitude':'11.166667', 'longitude': '-4.316667', 'name':'Borgo' },
'KQL': { 'latitude':'-5.666667', 'longitude': '144.8', 'name':'Kol' },
'ZOF': { 'latitude':'52.283333', 'longitude': '-127.766667', 'name':'Ocean Falls' },
'ZOS': { 'latitude':'-40.6', 'longitude': '-73.033333', 'name':'Canal Balo' },
'VVZ': { 'latitude':'26.483333', 'longitude': '8.466667', 'name':'Illizi' },
'MBG': { 'latitude':'34.741667', 'longitude': '73.625', 'name':'Mobridge' },
'VVO': { 'latitude':'43.216667', 'longitude': '131.666667', 'name':'Vladivostok' },
'VVK': { 'latitude':'57.75', 'longitude': '16.633333', 'name':'Vastervik' },
'XML': { 'latitude':'-34.766667', 'longitude': '137.6', 'name':'Minlaton' },
'XMN': { 'latitude':'24.466667', 'longitude': '118.116667', 'name':'Xiamen' },
'XMH': { 'latitude':'-14.433333', 'longitude': '-146.066667', 'name':'Manihi' },
'VVI': { 'latitude':'-17.644722', 'longitude': '-63.135278', 'name':'Viru Viru Intl' },
'XMD': { 'latitude':'44.0', 'longitude': '-97.116667', 'name':'Madison' },
'XMG': { 'latitude':'28.966667', 'longitude': '80.15', 'name':'Mahendranagar' },
'XMA': { 'latitude':'7.816667', 'longitude': '124.95', 'name':'Maramag' },
'XMC': { 'latitude':'-37.6', 'longitude': '149.716667', 'name':'Mallacoota' },
'SXX': { 'latitude':'-6.634444', 'longitude': '-51.984444', 'name':'Sao Felix Do Xingu' },
'XMY': { 'latitude':'-10.483333', 'longitude': '142.45', 'name':'Yam Island' },
'XMP': { 'latitude':'62.866667', 'longitude': '-135.916667', 'name':'Macmillan Pass' },
'XMS': { 'latitude':'-2.299167', 'longitude': '-78.120833', 'name':'Macas' },
'YYU': { 'latitude':'49.416667', 'longitude': '-82.433333', 'name':'Kapuskasing' },
'YYT': { 'latitude':'47.618611', 'longitude': '-52.751944', 'name':'St. John´s International' },
'YYW': { 'latitude':'50.297222', 'longitude': '-88.971944', 'name':'Armstrong' },
'YYQ': { 'latitude':'58.739167', 'longitude': '-94.065', 'name':'Metropolitan Area' },
'YYR': { 'latitude':'53.316667', 'longitude': '-60.416667', 'name':'Goose Bay' },
'YYY': { 'latitude':'48.6', 'longitude': '-68.2', 'name':'Mont Joli' },
'YYZ': { 'latitude':'43.677222', 'longitude': '-79.630556', 'name':'Lester B. Pearson International' },
'YYE': { 'latitude':'58.833333', 'longitude': '-122.583333', 'name':'Fort Nelson' },
'YYD': { 'latitude':'54.816667', 'longitude': '-127.183333', 'name':'Smithers' },
'YYG': { 'latitude':'46.283333', 'longitude': '-63.133333', 'name':'Charlottetown' },
'YYF': { 'latitude':'49.466667', 'longitude': '-119.6', 'name':'Penticton' },
'YYA': { 'latitude':'50.4', 'longitude': '-123.133333', 'name':'Big Bay Yacht Club' },
'YYC': { 'latitude':'51.113889', 'longitude': '-114.020278', 'name':'Calgary International Airport' },
'YYB': { 'latitude':'46.366667', 'longitude': '-79.416667', 'name':'North Bay' },
'YYM': { 'latitude':'49.566667', 'longitude': '-114.083333', 'name':'Cowley' },
'YYL': { 'latitude':'56.866667', 'longitude': '-101.066667', 'name':'Lynn Lake' },
'YYN': { 'latitude':'50.283333', 'longitude': '-107.683333', 'name':'Swift Current' },
'YYI': { 'latitude':'50.033333', 'longitude': '-100.2', 'name':'Rivers' },
'MXT': { 'latitude':'-18.05', 'longitude': '44.033333', 'name':'Maintirano' },
'YYJ': { 'latitude':'48.65', 'longitude': '-123.433333', 'name':'Victoria International' },
'WSA': { 'latitude':'-8.283333', 'longitude': '142.866667', 'name':'Wasua' },
'HYA': { 'latitude':'41.669444', 'longitude': '-70.280278', 'name':'Barnstable' },
'HYC': { 'latitude':'51.633333', 'longitude': '-0.766667', 'name':'High Wycombe' },
'HYD': { 'latitude':'17.453056', 'longitude': '78.4675', 'name':'Chennai Airport' },
'WSD': { 'latitude':'61.833333', 'longitude': '-1.833333', 'name':'Condron AAF' },
'HYF': { 'latitude':'-3.633333', 'longitude': '143.05', 'name':'Hayfields' },
'HYG': { 'latitude':'55.2', 'longitude': '-132.833333', 'name':'SPB' },
'WSH': { 'latitude':'40.783333', 'longitude': '-72.916667', 'name':'Brookhaven' },
'WSJ': { 'latitude':'57.733333', 'longitude': '-153.3', 'name':'San Juan SPB' },
'HYL': { 'latitude':'55.483333', 'longitude': '-132.65', 'name':'SPB' },
'HYN': { 'latitude':'28.416667', 'longitude': '122.366667', 'name':'Huangyan' },
'WSN': { 'latitude':'58.7', 'longitude': '-157.0', 'name':'South Naknek' },
'WSP': { 'latitude':'14.583333', 'longitude': '-84.083333', 'name':'Waspam' },
'HYR': { 'latitude':'46.033333', 'longitude': '-91.45', 'name':'Municipal' },
'HYS': { 'latitude':'38.85', 'longitude': '-99.266667', 'name':'Municipal' },
'WSU': { 'latitude':'-6.0', 'longitude': '147.25', 'name':'Wasu' },
'WST': { 'latitude':'41.333333', 'longitude': '-71.766667', 'name':'Westerly State' },
'WSY': { 'latitude':'-20.283333', 'longitude': '148.783333', 'name':'Whitsunday Airstrip' },
'WSX': { 'latitude':'48.666667', 'longitude': '-122.883333', 'name':'Westsound' },
'WSZ': { 'latitude':'-41.738056', 'longitude': '171.576667', 'name':'Westport' },
'BOR': { 'latitude':'47.65', 'longitude': '7.016667', 'name':'Fontaine' },
'BOS': { 'latitude':'42.363056', 'longitude': '-71.0', 'name':'Logan International' },
'VKT': { 'latitude':'67.483333', 'longitude': '63.983333', 'name':'Vorkuta' },
'VKW': { 'latitude':'69.666667', 'longitude': '-146.916667', 'name':'West Kavik' },
'VKO': { 'latitude':'55.583333', 'longitude': '37.266667', 'name':'Vnukovo' },
'VKG': { 'latitude':'9.995278', 'longitude': '105.095833', 'name':'Rach Gia' },
'POX': { 'latitude':'49.096667', 'longitude': '2.040833', 'name':'Paris Cergy Pontoise' },
'POY': { 'latitude':'44.866667', 'longitude': '-108.8', 'name':'Powell' },
'POW': { 'latitude':'45.473333', 'longitude': '13.615', 'name':'Portoroz' },
'FWL': { 'latitude':'62.516667', 'longitude': '-153.9', 'name':'Farewell' },
'FWM': { 'latitude':'56.816667', 'longitude': '-5.116667', 'name':'Heliport' },
'POU': { 'latitude':'41.633333', 'longitude': '-73.883333', 'name':'Dutchess County' },
'FWH': { 'latitude':'32.769167', 'longitude': '-97.441667', 'name':'Fort Worth NAS Jrb/Carswell Field' },
'YVC': { 'latitude':'55.083333', 'longitude': '-105.333333', 'name':'La Ronge' },
'FWA': { 'latitude':'41.116667', 'longitude': '-85.116667', 'name':'Municipal/Baer Field' },
'PON': { 'latitude':'16.35', 'longitude': '-89.433333', 'name':'Poptun' },
'POO': { 'latitude':'-21.841389', 'longitude': '-46.5675', 'name':'Pocos De Caldas' },
'POL': { 'latitude':'-12.986667', 'longitude': '40.5225', 'name':'Porto Amelia' },
'POJ': { 'latitude':'-18.671667', 'longitude': '-46.490833', 'name':'Patos De Minas' },
'POH': { 'latitude':'42.75', 'longitude': '-94.65', 'name':'Municipal' },
'TBX': { 'latitude':'6.233333', 'longitude': '-5.133333', 'name':'Taabo' },
'ZPH': { 'latitude':'28.233333', 'longitude': '-82.166667', 'name':'Zephyrhills' },
'ZPO': { 'latitude':'55.516667', 'longitude': '-106.6', 'name':'Pine House' },
'ZPC': { 'latitude':'-39.283333', 'longitude': '-71.933333', 'name':'Pucon' },
'ZPB': { 'latitude':'53.816667', 'longitude': '-92.133333', 'name':'Sachigo Lake' },
'POD': { 'latitude':'16.666667', 'longitude': '-14.966667', 'name':'Podor' },
'POB': { 'latitude':'35.170833', 'longitude': '-79.014444', 'name':'Pope AFB' },
'POA': { 'latitude':'-29.984444', 'longitude': '-51.171389', 'name':'Salgado Filho' },
'JDM': { 'latitude':'10.016667', 'longitude': '-73.65', 'name':'Downtown Heliport' },
'JDO': { 'latitude':'-7.218056', 'longitude': '-39.270556', 'name':'Regional Do Cariri' },
'JDN': { 'latitude':'47.316667', 'longitude': '-106.916667', 'name':'Jordan' },
'JDH': { 'latitude':'26.25', 'longitude': '73.05', 'name':'Jodhpur' },
'DEP': { 'latitude':'31.016111', 'longitude': '50.073889', 'name':'Deparizo' },
'DER': { 'latitude':'-6.1', 'longitude': '146.816667', 'name':'Derim' },
'JDF': { 'latitude':'-21.75', 'longitude': '-43.333333', 'name':'Francisco De Assis' },
'JDA': { 'latitude':'44.416667', 'longitude': '-118.95', 'name':'John Day' },
'JDB': { 'latitude':'32.766667', 'longitude': '-97.316667', 'name':'Downtown Heliport' },
'DEH': { 'latitude':'43.316667', 'longitude': '-91.833333', 'name':'Municipal' },
'DEI': { 'latitude':'-3.8', 'longitude': '55.666667', 'name':'Denis Island' },
'ILF': { 'latitude':'56.066667', 'longitude': '-95.583333', 'name':'Ilford' },
'VCC': { 'latitude':'4.016667', 'longitude': '9.2', 'name':'Limbe' },
'JDY': { 'latitude':'33.956389', 'longitude': '-118.120556', 'name':'Heliport' },
'DEM': { 'latitude':'8.55', 'longitude': '34.866667', 'name':'Dembidollo' },
'DEN': { 'latitude':'39.861667', 'longitude': '-104.673056', 'name':'Denver International' },
'JDZ': { 'latitude':'29.266667', 'longitude': '117.183333', 'name':'Jingdezhen' },
'JDT': { 'latitude':'8.316667', 'longitude': '40.033333', 'name':'Downtown Heliport' },
'DEB': { 'latitude':'47.481389', 'longitude': '21.602778', 'name':'Debrecen' },
'DEC': { 'latitude':'39.833333', 'longitude': '-88.866667', 'name':'Decatur Arpt' },
'DED': { 'latitude':'30.189722', 'longitude': '78.180278', 'name':'Dehra Dun' },
'JDP': { 'latitude':'48.833056', 'longitude': '2.273056', 'name':'Heliport De Paris' },
'DEF': { 'latitude':'32.380278', 'longitude': '48.404722', 'name':'Dezful' },
'JDR': { 'latitude':'-21.0839', 'longitude': '-43.2172', 'name':'Sao Joao Del Rei' },
'UPN': { 'latitude':'19.416667', 'longitude': '-102.05', 'name':'Uruapan' },
'UPL': { 'latitude':'10.783333', 'longitude': '-85.033333', 'name':'Upala' },
'GGT': { 'latitude':'23.55', 'longitude': '-75.883333', 'name':'Exuma International' },
'UPF': { 'latitude':'48.9', 'longitude': '8.7', 'name':'Pforheim' },
'UPG': { 'latitude':'-5.116667', 'longitude': '119.4', 'name':'Hasanudin' },
'UPB': { 'latitude':'23.131944', 'longitude': '-82.364167', 'name':'Playa Baracoa' },
'GGW': { 'latitude':'48.216667', 'longitude': '-106.616667', 'name':'International' },
'UPA': { 'latitude':'22.383333', 'longitude': '-78.816667', 'name':'Punta Alegre' },
'UPV': { 'latitude':'51.283333', 'longitude': '-1.816667', 'name':'Upavon' },
'UPR': { 'latitude':'-8.533333', 'longitude': '142.633333', 'name':'Upiara' },
'UPP': { 'latitude':'20.266667', 'longitude': '-155.85', 'name':'Upolu Point' },
'IVG': { 'latitude':'42.833333', 'longitude': '19.85', 'name':'Ivangrad' },
'IVA': { 'latitude':'-13.65', 'longitude': '48.466667', 'name':'Ambanja' },
'IVC': { 'latitude':'-46.415', 'longitude': '168.32', 'name':'Invercargill' },
'IVL': { 'latitude':'68.6', 'longitude': '27.416667', 'name':'Ivalo' },
'IVO': { 'latitude':'10.016667', 'longitude': '-74.683333', 'name':'Chivolo' },
'IVH': { 'latitude':'69.4', 'longitude': '-148.25', 'name':'Ivishak' },
'IVW': { 'latitude':'-17.766667', 'longitude': '129.233333', 'name':'Inverway' },
'IVR': { 'latitude':'-29.833333', 'longitude': '151.533333', 'name':'Inverell' },
'NEN': { 'latitude':'30.333333', 'longitude': '-81.883333', 'name':'Olf Usn' },
'ACB': { 'latitude':'44.983333', 'longitude': '-85.202778', 'name':'Antrim County' },
'ACA': { 'latitude':'16.756944', 'longitude': '-99.753611', 'name':'General Juan N. Alvarez International' },
'NEK': { 'latitude':'9.033333', 'longitude': '36.583333', 'name':'Nekemt' },
'ACE': { 'latitude':'28.945556', 'longitude': '-13.605278', 'name':'Lanzarote' },
'ACD': { 'latitude':'8.5', 'longitude': '-73.633333', 'name':'Acandi' },
'NEF': { 'latitude':'56.1', 'longitude': '54.35', 'name':'Neftekamsk' },
'ACJ': { 'latitude':'8.35', 'longitude': '80.383333', 'name':'Anuradhapura' },
'HFS': { 'latitude':'60.0175', 'longitude': '13.569167', 'name':'Hagfors' },
'ACH': { 'latitude':'47.483333', 'longitude': '9.55', 'name':'Altenrhein' },
'ACO': { 'latitude':'46.159444', 'longitude': '8.766667', 'name':'Ascona' },
'HFT': { 'latitude':'70.7', 'longitude': '23.666667', 'name':'Hammerfest' },
'ACM': { 'latitude':'-2.133333', 'longitude': '-71.783333', 'name':'Arica' },
'NEA': { 'latitude':'51.679444', 'longitude': '-3.628056', 'name':'Brunswick Golden Isles' },
'ACS': { 'latitude':'56.266667', 'longitude': '90.566667', 'name':'Achinsk' },
'ACR': { 'latitude':'-0.383333', 'longitude': '-72.3', 'name':'Araracuara' },
'ACP': { 'latitude':'37.733333', 'longitude': '46.45', 'name':'Sahand' },
'ACV': { 'latitude':'40.983333', 'longitude': '-124.1', 'name':'Arcata' },
'ACU': { 'latitude':'9.576389', 'longitude': '-79.724444', 'name':'Achutupo' },
'HFN': { 'latitude':'64.233333', 'longitude': '-15.233333', 'name':'Hornafjordur' },
'NEV': { 'latitude':'17.166667', 'longitude': '-62.583333', 'name':'Newcastle' },
'ACZ': { 'latitude':'31.0', 'longitude': '61.25', 'name':'Zabol A/P' },
'NET': { 'latitude':'17.266667', 'longitude': '-87.85', 'name':'New Bight' },
'NEU': { 'latitude':'20.416667', 'longitude': '104.066667', 'name':'Sam Neua' },
'NER': { 'latitude':'56.65', 'longitude': '124.6', 'name':'Neryungri' },
'NES': { 'latitude':'40.7425', 'longitude': '-73.971944', 'name':'East 34th St Landing' },
'HFF': { 'latitude':'-40.2', 'longitude': '-72.166667', 'name':'Mackall AAF' },
'BKD': { 'latitude':'32.75', 'longitude': '-98.9', 'name':'Stephens County' },
'BKE': { 'latitude':'44.833333', 'longitude': '-117.816667', 'name':'Baker' },
'BKF': { 'latitude':'58.554722', 'longitude': '-155.7775', 'name':'Lake Brooks SPB' },
'BKA': { 'latitude':'55.617222', 'longitude': '38.06', 'name':'Bykovo' },
'BKB': { 'latitude':'28.016667', 'longitude': '73.3', 'name':'Bikaner' },
'BKC': { 'latitude':'65.983333', 'longitude': '-161.166667', 'name':'Buckland' },
'BKL': { 'latitude':'41.511111', 'longitude': '-81.688889', 'name':'Burke Lakefront' },
'BKM': { 'latitude':'3.966667', 'longitude': '115.616667', 'name':'Bakalalan' },
'BKN': { 'latitude':'13.8', 'longitude': '5.25', 'name':'Birni Nkoni' },
'BKO': { 'latitude':'12.633333', 'longitude': '-8.016667', 'name':'Bamako' },
'BKH': { 'latitude':'22.024722', 'longitude': '-159.789444', 'name':'Barking Sands PMRF' },
'BKI': { 'latitude':'5.937222', 'longitude': '116.05', 'name':'Kota-Kinabalu International Airport' },
'BKJ': { 'latitude':'10.966667', 'longitude': '-14.283333', 'name':'Boke' },
'BKK': { 'latitude':'13.681111', 'longitude': '100.747222', 'name':'Suvarnabhumi International' },
'BKT': { 'latitude':'37.083333', 'longitude': '-77.95', 'name':'Blackstone AAF' },
'BKU': { 'latitude':'-23.733333', 'longitude': '44.383333', 'name':'Betioky' },
'BKW': { 'latitude':'37.783333', 'longitude': '-81.116667', 'name':'Beckley' },
'BKP': { 'latitude':'-21.033333', 'longitude': '138.25', 'name':'Barkly Downs' },
'BKQ': { 'latitude':'-24.416667', 'longitude': '145.416667', 'name':'Blackall' },
'BKR': { 'latitude':'12.833333', 'longitude': '17.25', 'name':'Bokoro' },
'BKS': { 'latitude':'-3.766667', 'longitude': '102.3', 'name':'Padangkemiling' },
'BKX': { 'latitude':'44.3', 'longitude': '-96.816667', 'name':'Brookings' },
'BKY': { 'latitude':'-2.30889', 'longitude': '28.80861', 'name':'Bukavu' },
'BKZ': { 'latitude':'-1.3', 'longitude': '31.8', 'name':'Bukoba' },
'SJZ': { 'latitude':'38.662778', 'longitude': '-28.244444', 'name':'Sao Jorge Island' },
'SJX': { 'latitude':'18.3', 'longitude': '-88.333333', 'name':'Sartaneja' },
'SJY': { 'latitude':'62.692222', 'longitude': '22.832222', 'name':'Ilmajoki' },
'SJR': { 'latitude':'8.766667', 'longitude': '-76.533333', 'name':'San Juan D Ur' },
'SJS': { 'latitude':'-17.816667', 'longitude': '-60.75', 'name':'San Jose' },
'SJP': { 'latitude':'-20.8', 'longitude': '-49.383333', 'name':'Sao Jose Do Rio Preto' },
'SJQ': { 'latitude':'-17.45', 'longitude': '24.366667', 'name':'Sesheke' },
'SJV': { 'latitude':'-16.233333', 'longitude': '-62.416667', 'name':'San Javier' },
'SJW': { 'latitude':'38.05', 'longitude': '114.466667', 'name':'Daguocun' },
'SJT': { 'latitude':'31.357778', 'longitude': '-100.496389', 'name':'Mathis Fld' },
'SJU': { 'latitude':'18.439444', 'longitude': '-66.001944', 'name':'Luis Munoz Marin Intl' },
'SJJ': { 'latitude':'43.816667', 'longitude': '18.35', 'name':'Sarajevo' },
'SJK': { 'latitude':'-23.183333', 'longitude': '-46.116667', 'name':'Sao Jose Dos Campos' },
'SJH': { 'latitude':'10.766667', 'longitude': '-73.016667', 'name':'San Juan Del Cesar' },
'SJI': { 'latitude':'12.366667', 'longitude': '121.033333', 'name':'Mcguire Fld' },
'SJN': { 'latitude':'34.518889', 'longitude': '-109.3775', 'name':'St Johns' },
'SJO': { 'latitude':'9.993889', 'longitude': '-84.208889', 'name':'Juan Santamaría International' },
'SJL': { 'latitude':'-0.119133', 'longitude': '-67.082176', 'name':'Sao Gabriel' },
'GGL': { 'latitude':'8.333333', 'longitude': '-77.083333', 'name':'Gilgal' },
'SJB': { 'latitude':'-13.083333', 'longitude': '-64.8', 'name':'San Joaquin' },
'SJC': { 'latitude':'37.352778', 'longitude': '-121.919444', 'name':'Mineta San Jose International Airport' },
'SJA': { 'latitude':'-15.35', 'longitude': '-75.15', 'name':'San Juan' },
'SJF': { 'latitude':'18.333333', 'longitude': '-64.75', 'name':'St John Island' },
'GGO': { 'latitude':'6.55', 'longitude': '-7.483333', 'name':'Guiglo' },
'SJD': { 'latitude':'23.151944', 'longitude': '-109.721111', 'name':'Los Cabos' },
'SJE': { 'latitude':'2.583333', 'longitude': '-72.666667', 'name':'San Jose Del Gua' },
'GDP': { 'latitude':'-6.781944', 'longitude': '-43.581667', 'name':'Guadalupe' },
'MED': { 'latitude':'24.533333', 'longitude': '39.716667', 'name':'Mohammad Bin Abdulaziz' },
'MEG': { 'latitude':'-9.533333', 'longitude': '16.333333', 'name':'Malange' },
'MEF': { 'latitude':'11.05', 'longitude': '17.95', 'name':'Melfi' },
'MEA': { 'latitude':'-22.383333', 'longitude': '-41.783333', 'name':'Macae' },
'MEC': { 'latitude':'-0.95', 'longitude': '-80.683333', 'name':'Manta' },
'MEB': { 'latitude':'-37.7', 'longitude': '144.866667', 'name':'Essendon' },
'MEM': { 'latitude':'35.066667', 'longitude': '-89.966667', 'name':'Memphis International' },
'MEL': { 'latitude':'-37.673333', 'longitude': '144.843333', 'name':'Tullamarine' },
'MEO': { 'latitude':'35.911111', 'longitude': '-75.7', 'name':'Dare County Regional' },
'MEN': { 'latitude':'44.5', 'longitude': '3.533333', 'name':'Brenoux' },
'MEI': { 'latitude':'32.333333', 'longitude': '-88.75', 'name':'Key Field' },
'MEH': { 'latitude':'71.033333', 'longitude': '27.833333', 'name':'Mehamn' },
'MEK': { 'latitude':'33.883333', 'longitude': '-5.516667', 'name':'Meknes' },
'MEJ': { 'latitude':'41.619444', 'longitude': '-80.2', 'name':'Meadville' },
'MEU': { 'latitude':'-0.884444', 'longitude': '-52.6', 'name':'Monte Dourado' },
'GDA': { 'latitude':'9.333333', 'longitude': '21.183333', 'name':'Gounda' },
'MEW': { 'latitude':'-4.85', 'longitude': '21.55', 'name':'Mweka' },
'MEV': { 'latitude':'39.0', 'longitude': '-119.75', 'name':'Douglas County' },
'GDD': { 'latitude':'-18.833333', 'longitude': '128.533333', 'name':'Gordon Downs' },
'MEP': { 'latitude':'2.433333', 'longitude': '103.833333', 'name':'Mersing' },
'MES': { 'latitude':'3.566667', 'longitude': '98.683333', 'name':'Polonia' },
'MER': { 'latitude':'37.380556', 'longitude': '-120.568056', 'name':'Castle AFB' },
'GDH': { 'latitude':'59.746944', 'longitude': '-158.874722', 'name':'Golden Horn Lodge SPB' },
'GDI': { 'latitude':'9.733333', 'longitude': '21.583333', 'name':'Gordil' },
'GDJ': { 'latitude':'-6.733333', 'longitude': '23.95', 'name':'Gandajika' },
'MEY': { 'latitude':'27.577778', 'longitude': '84.231389', 'name':'Meghauli' },
'MEX': { 'latitude':'19.436389', 'longitude': '-99.072222', 'name':'Internacional Benito Juarez' },
'GDN': { 'latitude':'54.3775', 'longitude': '18.466111', 'name':'Lech Walesa' },
'MEZ': { 'latitude':'-22.366667', 'longitude': '29.983333', 'name':'Messina' },
'LWY': { 'latitude':'4.85', 'longitude': '115.4', 'name':'Lawas' },
'LWR': { 'latitude':'53.228611', 'longitude': '5.760556', 'name':'Leeuwarden' },
'LWS': { 'latitude':'46.383333', 'longitude': '-117.033333', 'name':'Nez Perce County Rgnl' },
'LWV': { 'latitude':'38.766667', 'longitude': '-87.6', 'name':'Municipal' },
'LWT': { 'latitude':'47.05', 'longitude': '-109.466667', 'name':'Municipal' },
'LWK': { 'latitude':'60.2', 'longitude': '-1.125', 'name':'Lerwick/Tingwall' },
'LWH': { 'latitude':'-18.633333', 'longitude': '138.633333', 'name':'Lawn Hill' },
'LWI': { 'latitude':'-6.316667', 'longitude': '146.583333', 'name':'Lowai' },
'LWN': { 'latitude':'40.716667', 'longitude': '43.833333', 'name':'Gyoumri' },
'LWO': { 'latitude':'49.8125', 'longitude': '23.956111', 'name':'Snilow' },
'LWL': { 'latitude':'41.116667', 'longitude': '-114.966667', 'name':'Harriet Field' },
'LWM': { 'latitude':'42.716667', 'longitude': '-71.116667', 'name':'Lawrence' },
'LWB': { 'latitude':'37.783333', 'longitude': '-80.336111', 'name':'Greenbrier Valley' },
'LWC': { 'latitude':'38.95', 'longitude': '-95.283333', 'name':'Lawrence' },
'LWE': { 'latitude':'-8.383333', 'longitude': '123.4', 'name':'Lewoleba' },
'CAR': { 'latitude':'46.866667', 'longitude': '-68.016667', 'name':'Municipal' },
'ZMM': { 'latitude':'19.983333', 'longitude': '-102.266667', 'name':'Zamora' },
'SBX': { 'latitude':'48.533333', 'longitude': '-111.866667', 'name':'Shelby' },
'SBY': { 'latitude':'38.333333', 'longitude': '-75.516667', 'name':'Wicomico Regional' },
'KGP': { 'latitude':'62.190556', 'longitude': '74.533889', 'name':'Kogalym International' },
'KGS': { 'latitude':'36.793333', 'longitude': '27.091667', 'name':'Kos Island International Airport' },
'KGR': { 'latitude':'-25.833333', 'longitude': '133.5', 'name':'Kulgera' },
'KGU': { 'latitude':'5.366667', 'longitude': '116.166667', 'name':'Keningau' },
'KGT': { 'latitude':'38.1339', 'longitude': '101.7339', 'name':'Kangding' },
'KGW': { 'latitude':'-9.05', 'longitude': '146.833333', 'name':'Kagi' },
'KGY': { 'latitude':'-26.580833', 'longitude': '151.841111', 'name':'Kingaroy' },
'KGX': { 'latitude':'62.666667', 'longitude': '-160.008333', 'name':'Grayling' },
'EZV': { 'latitude':'63.9167', 'longitude': '65.0167', 'name':'Berezovo' },
'KGZ': { 'latitude':'61.45', 'longitude': '-142.4', 'name':'Glacier Creek' },
'EZS': { 'latitude':'38.6', 'longitude': '39.283333', 'name':'Elazig' },
'KGA': { 'latitude':'-5.9', 'longitude': '22.466667', 'name':'Kananga' },
'KGC': { 'latitude':'-35.713889', 'longitude': '137.521389', 'name':'Kingscote' },
'KGB': { 'latitude':'-6.133333', 'longitude': '147.65', 'name':'Konge' },
'KGE': { 'latitude':'-8.165', 'longitude': '157.586111', 'name':'Kagau' },
'KGD': { 'latitude':'54.726389', 'longitude': '20.575278', 'name':'Kaliningrad Devau' },
'KGG': { 'latitude':'12.583333', 'longitude': '-12.0', 'name':'Kedougou' },
'KGF': { 'latitude':'49.833333', 'longitude': '73.166667', 'name':'Karaganda' },
'KGI': { 'latitude':'-30.789444', 'longitude': '121.461667', 'name':'Kalgoorlie' },
'KGH': { 'latitude':'-8.583333', 'longitude': '147.5', 'name':'Yongai' },
'KGK': { 'latitude':'59.783333', 'longitude': '-157.333333', 'name':'New Koliganek' },
'KGJ': { 'latitude':'-9.95', 'longitude': '33.916667', 'name':'Karonga' },
'KGM': { 'latitude':'-5.183333', 'longitude': '39.783333', 'name':'Kungum' },
'KGL': { 'latitude':'-1.968611', 'longitude': '30.139444', 'name':'Gregoire Kayibanda' },
'KGO': { 'latitude':'48.55', 'longitude': '32.3', 'name':'Kirovograd' },
'KGN': { 'latitude':'-6.466667', 'longitude': '16.816667', 'name':'Kasongo Lunda' },
'CPH': { 'latitude':'55.618056', 'longitude': '12.655833', 'name':'Kastrup' },
'CPI': { 'latitude':'-52.0', 'longitude': '-61.066667', 'name':'Cape Orford' },
'CPL': { 'latitude':'3.7', 'longitude': '-75.75', 'name':'Chaparral' },
'CPM': { 'latitude':'33.89', 'longitude': '-118.243611', 'name':'Compton' },
'CPN': { 'latitude':'-10.183333', 'longitude': '148.366667', 'name':'Cape Rodney' },
'CPO': { 'latitude':'-27.2612472', 'longitude': '-70.779222', 'name':'Copiapo' },
'CPA': { 'latitude':'4.383333', 'longitude': '-7.7', 'name':'A. Tubman' },
'CPB': { 'latitude':'8.633333', 'longitude': '-77.333333', 'name':'Capurgana' },
'CPC': { 'latitude':'-40.083333', 'longitude': '-71.133333', 'name':'Chapelco' },
'CPD': { 'latitude':'-29.05', 'longitude': '134.75', 'name':'Coober Pedy' },
'CPE': { 'latitude':'19.833333', 'longitude': '-90.516667', 'name':'Campeche International' },
'CPF': { 'latitude':'-7.183333', 'longitude': '111.533333', 'name':'Cepu' },
'CPG': { 'latitude':'-40.8', 'longitude': '-62.983333', 'name':'Carmen De Patagones' },
'CPX': { 'latitude':'18.316667', 'longitude': '-65.3', 'name':'Culebra' },
'KOF': { 'latitude':'-25.440833', 'longitude': '31.930278', 'name':'Komatipoort' },
'CPQ': { 'latitude':'-23.0', 'longitude': '-47.133333', 'name':'International' },
'CPR': { 'latitude':'42.908056', 'longitude': '-106.464444', 'name':'Natrona County International Airport' },
'CPS': { 'latitude':'38.570833', 'longitude': '-90.156111', 'name':'St. Louis Downtown Airport' },
'CPT': { 'latitude':'-33.964722', 'longitude': '18.601667', 'name':'Cape Town International' },
'CPU': { 'latitude':'-1.8', 'longitude': '-44.866667', 'name':'Cururupu' },
'CPV': { 'latitude':'-7.266667', 'longitude': '-35.9', 'name':'Joao Suassuna' },
'NUX': { 'latitude':'66.083333', 'longitude': '76.516667', 'name':'Novy Urengoy' },
'OVR': { 'latitude':'-35.7', 'longitude': '-63.0', 'name':'Olavarria' },
'OVS': { 'latitude':'61.3172', 'longitude': '63.6007', 'name':'Sovetsky' },
'OVB': { 'latitude':'55.033333', 'longitude': '83.0', 'name':'Tolmachevo' },
'OVA': { 'latitude':'-24.233333', 'longitude': '45.3', 'name':'Bekily' },
'OVG': { 'latitude':'50.75', 'longitude': '3.866667', 'name':'Overberg' },
'OVD': { 'latitude':'43.333333', 'longitude': '-6.0', 'name':'Asturias' },
'OVE': { 'latitude':'39.483333', 'longitude': '-121.633333', 'name':'Oroville' },
'OVL': { 'latitude':'-30.4', 'longitude': '-71.2', 'name':'Ovalle' },
'TRL': { 'latitude':'-21.8', 'longitude': '121.033333', 'name':'Terrell Field' },
'TRB': { 'latitude':'8.0', 'longitude': '-76.583333', 'name':'Gonzalo' },
'NUT': { 'latitude':'-5.633333', 'longitude': '151.383333', 'name':'Nutuve' },
'MQD': { 'latitude':'-41.25', 'longitude': '-68.733333', 'name':'Maquinchao' },
'MXZ': { 'latitude':'24.35', 'longitude': '116.133333', 'name':'Meixian' },
'MXX': { 'latitude':'61.0', 'longitude': '14.55', 'name':'Mora' },
'MXY': { 'latitude':'61.416667', 'longitude': '-142.916667', 'name':'Mccarthy' },
'MXV': { 'latitude':'49.633333', 'longitude': '100.166667', 'name':'Moron' },
'MXW': { 'latitude':'45.766667', 'longitude': '106.283333', 'name':'Mandalgobi' },
'ILB': { 'latitude':'-20.383333', 'longitude': '-51.333333', 'name':'Ilha Solteira' },
'MXU': { 'latitude':'-28.55', 'longitude': '115.516667', 'name':'Mullewa' },
'MXR': { 'latitude':'49.966667', 'longitude': '33.6', 'name':'Mirgorod' },
'MXS': { 'latitude':'-13.735556', 'longitude': '-172.253333', 'name':'Maota Savaii Is' },
'MXP': { 'latitude':'45.633333', 'longitude': '8.733333', 'name':'Malpensa' },
'MXQ': { 'latitude':'-15.666667', 'longitude': '141.8', 'name':'Mitchell River' },
'MXN': { 'latitude':'48.6', 'longitude': '-3.816667', 'name':'Morlaix' },
'MXO': { 'latitude':'40.65', 'longitude': '15.016667', 'name':'Municipal' },
'MXL': { 'latitude':'32.65', 'longitude': '-115.45', 'name':'Mexicali' },
'MXM': { 'latitude':'-21.75', 'longitude': '43.366667', 'name':'Morombe' },
'MXJ': { 'latitude':'9.616667', 'longitude': '6.533333', 'name':'Minna' },
'MXK': { 'latitude':'-6.216667', 'longitude': '147.616667', 'name':'Mindik' },
'MXH': { 'latitude':'-6.364444', 'longitude': '143.254444', 'name':'Moro' },
'MXI': { 'latitude':'6.949444', 'longitude': '126.273056', 'name':'Imelda Romualdez Marcos' },
'MXG': { 'latitude':'42.333333', 'longitude': '-71.55', 'name':'Marlborough' },
'MXD': { 'latitude':'-23.5', 'longitude': '139.666667', 'name':'Marion Downs' },
'MXE': { 'latitude':'34.733333', 'longitude': '-79.35', 'name':'Maxton' },
'MXB': { 'latitude':'-2.533333', 'longitude': '120.333333', 'name':'Masamba' },
'MXC': { 'latitude':'37.866667', 'longitude': '-109.35', 'name':'San Juan County' },
'MXA': { 'latitude':'4.766667', 'longitude': '-74.433333', 'name':'Municipal' },
'SBG': { 'latitude':'5.916667', 'longitude': '95.316667', 'name':'Narita' },
'MQL': { 'latitude':'-34.233333', 'longitude': '142.083333', 'name':'Mildura' },
'MQN': { 'latitude':'66.316667', 'longitude': '14.0', 'name':'Mo I Rana' },
'SBD': { 'latitude':'34.095278', 'longitude': '-117.235', 'name':'Norton Afb' },
'MQP': { 'latitude':'-25.185', 'longitude': '31.116667', 'name':'Kruger Mpumalanga' },
'MQS': { 'latitude':'12.887778', 'longitude': '-61.180278', 'name':'Mustique' },
'MQU': { 'latitude':'5.216667', 'longitude': '-74.883333', 'name':'Mariquita' },
'ZMK': { 'latitude':'3.166667', 'longitude': '113.033333', 'name':'Bintulu Port' },
'ZMH': { 'latitude':'51.736667', 'longitude': '-121.333611', 'name':'108 Mile Ranch' },
'ZMO': { 'latitude':'44.5', 'longitude': '10.9', 'name':'Bus Station' },
'ZML': { 'latitude':'32.466667', 'longitude': '171.916667', 'name':'Milwaukee General Mitchell' },
'HTF': { 'latitude':'51.765', 'longitude': '-0.248333', 'name':'Hatfield' },
'MQV': { 'latitude':'43.247778', 'longitude': '17.785556', 'name':'Mostaganem' },
'ZMD': { 'latitude':'-9.066667', 'longitude': '-68.666667', 'name':'Sena Madureira' },
'ZME': { 'latitude':'40.919444', 'longitude': '74.169444', 'name':'Metropark Rail' },
'ZMY': { 'latitude':'30.55', 'longitude': '116.433333', 'name':'Harbour' },
'ZMR': { 'latitude':'45.7', 'longitude': '7.666667', 'name':'Bus Station' },
'ZMP': { 'latitude':'53.4803', 'longitude': '-2.2375', 'name':'Manchester Bus Stn.' },
'ZMT': { 'latitude':'54.016667', 'longitude': '-132.166667', 'name':'Masset' },
'MQZ': { 'latitude':'-18.633333', 'longitude': '126.866667', 'name':'Margaret River' },
'SBI': { 'latitude':'12.483333', 'longitude': '-13.3', 'name':'Sambailo' },
'XOZ': { 'latitude':'25.25', 'longitude': '51.5', 'name':'Doha Free Zone' },
'SBO': { 'latitude':'39.029167', 'longitude': '-111.8375', 'name':'Salina' },
'SBL': { 'latitude':'-13.766667', 'longitude': '-65.583333', 'name':'Yacuma' },
'SBM': { 'latitude':'43.762222', 'longitude': '-87.850833', 'name':'Memorial' },
'NUI': { 'latitude':'70.216667', 'longitude': '-150.916667', 'name':'Nuiqsut' },
'RLD': { 'latitude':'46.3', 'longitude': '-119.3', 'name':'Richland' },
'TYL': { 'latitude':'-4.566667', 'longitude': '-81.283333', 'name':'Talara' },
'TYM': { 'latitude':'24.1525', 'longitude': '-76.433889', 'name':'Staniel Cay' },
'TYN': { 'latitude':'37.858056', 'longitude': '112.580833', 'name':'Taiyuan' },
'VIA': { 'latitude':'27.0', 'longitude': '-51.133333', 'name':'Vienna' },
'VIG': { 'latitude':'8.633333', 'longitude': '-71.65', 'name':'El Vigia' },
'VID': { 'latitude':'43.983333', 'longitude': '22.816667', 'name':'Vidin' },
'VIE': { 'latitude':'48.110278', 'longitude': '16.569722', 'name':'Schwechat International' },
'TYD': { 'latitude':'55.166667', 'longitude': '124.716667', 'name':'Tynda' },
'VIK': { 'latitude':'39.733333', 'longitude': '36.4', 'name':'Airstrip' },
'TYF': { 'latitude':'60.1575', 'longitude': '12.991111', 'name':'Torsby Airport' },
'TYG': { 'latitude':'-26.066667', 'longitude': '143.466667', 'name':'Thylungra' },
'VIN': { 'latitude':'49.233333', 'longitude': '28.483333', 'name':'Vinnica' },
'TYA': { 'latitude':'59.483333', 'longitude': '28.133333', 'name':'Tula' },
'TYB': { 'latitude':'-29.433333', 'longitude': '142.016667', 'name':'Tibooburra' },
'VIR': { 'latitude':'-29.770556', 'longitude': '31.058333', 'name':'Virginia' },
'VIS': { 'latitude':'36.316667', 'longitude': '-119.4', 'name':'Visalia' },
'VIQ': { 'latitude':'-8.883333', 'longitude': '126.366667', 'name':'Viqueque' },
'VIV': { 'latitude':'-9.3', 'longitude': '150.316667', 'name':'Vivigani' },
'TYZ': { 'latitude':'56.15', 'longitude': '-1.666667', 'name':'Taylor' },
'VIU': { 'latitude':'-8.466667', 'longitude': '157.766667', 'name':'Viru Harbour Airstrip' },
'TYT': { 'latitude':'48.016667', 'longitude': '-4.583333', 'name':'Treinta-y-Tres' },
'VIX': { 'latitude':'-20.3', 'longitude': '-40.25', 'name':'Eurico Sales' },
'TYP': { 'latitude':'-22.283333', 'longitude': '137.916667', 'name':'Tobermorey' },
'TYR': { 'latitude':'32.354167', 'longitude': '-95.4025', 'name':'Tyler Pounds Regional Airport' },
'TYS': { 'latitude':'35.95', 'longitude': '-83.916667', 'name':'Mc Ghee Tyson' },
'FUT': { 'latitude':'-14.25', 'longitude': '-178.15', 'name':'Futuna Island' },
'NUG': { 'latitude':'-3.333333', 'longitude': '154.75', 'name':'Nuguria' },
'FUG': { 'latitude':'32.866667', 'longitude': '115.7', 'name':'Fuyang' },
'FUE': { 'latitude':'28.516667', 'longitude': '-13.9', 'name':'Fuerteventura' },
'FUB': { 'latitude':'-6.15', 'longitude': '150.65', 'name':'Fulleborn' },
'FUN': { 'latitude':'-8.516667', 'longitude': '179.216667', 'name':'International' },
'ABD': { 'latitude':'30.366667', 'longitude': '48.233333', 'name':'Abadan' },
'FUL': { 'latitude':'33.866667', 'longitude': '-117.966667', 'name':'Municipal' },
'FUM': { 'latitude':'-6.383333', 'longitude': '142.433333', 'name':'Fuma' },
'FUJ': { 'latitude':'32.666667', 'longitude': '128.833333', 'name':'Fukue' },
'FUK': { 'latitude':'33.583333', 'longitude': '130.45', 'name':'Fukuoka' },
'ABJ': { 'latitude':'5.25', 'longitude': '-3.933333', 'name':'Felix Houphouet Boigny' },
'ABK': { 'latitude':'6.733333', 'longitude': '44.266667', 'name':'Kabri Dar' },
'UEL': { 'latitude':'-17.866667', 'longitude': '36.85', 'name':'Quelimane' },
'ABL': { 'latitude':'67.1', 'longitude': '-157.816667', 'name':'Ambler' },
'ABM': { 'latitude':'-10.950833', 'longitude': '142.459444', 'name':'Bamaga Injinoo' },
'HGN': { 'latitude':'19.3', 'longitude': '97.966667', 'name':'Mae Hong Son' },
'HGO': { 'latitude':'9.416667', 'longitude': '-5.616667', 'name':'Korhogo' },
'HGL': { 'latitude':'54.183333', 'longitude': '7.916667', 'name':'Helgoland' },
'JBT': { 'latitude':'60.8', 'longitude': '-161.766667', 'name':'City Landing' },
'JBS': { 'latitude':'37.699722', 'longitude': '-121.9', 'name':'Hacienda Bus.Park H/P' },
'JBR': { 'latitude':'35.833333', 'longitude': '-90.65', 'name':'Jonesboro' },
'JBP': { 'latitude':'33.986667', 'longitude': '-118.159722', 'name':'Commerce Bus. Plaza' },
'HGI': { 'latitude':'53.966667', 'longitude': '113.766667', 'name':'Higlieg' },
'JBC': { 'latitude':'42.343889', 'longitude': '-71.049444', 'name':'Boston City Heliport' },
'ABY': { 'latitude':'31.533333', 'longitude': '-84.2', 'name':'Dougherty County' },
'JBK': { 'latitude':'37.95', 'longitude': '-122.3', 'name':'Berkeley' },
'HGD': { 'latitude':'-20.833333', 'longitude': '144.2', 'name':'Hughenden' },
'DGB': { 'latitude':'58.083333', 'longitude': '-152.75', 'name':'Danger Bay' },
'DGC': { 'latitude':'8.233333', 'longitude': '43.583333', 'name':'Degahbur' },
'DGA': { 'latitude':'17.183333', 'longitude': '-88.583333', 'name':'Dangriga' },
'DGF': { 'latitude':'31.468889', 'longitude': '-109.653611', 'name':'Bisbee-douglas International' },
'DGD': { 'latitude':'-27.766667', 'longitude': '117.033333', 'name':'Dalgaranga' },
'DGE': { 'latitude':'-32.783333', 'longitude': '149.166667', 'name':'Mudgee' },
'DGK': { 'latitude':'6.900278', 'longitude': '124.854722', 'name':'Dugong' },
'DGN': { 'latitude':'77.533333', 'longitude': '15.35', 'name':'NAF' },
'DGO': { 'latitude':'24.0', 'longitude': '-104.666667', 'name':'Guadalupe Victoria' },
'DGL': { 'latitude':'12.616667', 'longitude': '14.983333', 'name':'Douglas Municipal' },
'DGM': { 'latitude':'27.066667', 'longitude': '105.2', 'name':'Dongguan' },
'DGR': { 'latitude':'-35.933333', 'longitude': '173.866667', 'name':'Dargaville' },
'DGP': { 'latitude':'55.933333', 'longitude': '29.683333', 'name':'Daugavpils' },
'DGW': { 'latitude':'42.75', 'longitude': '-105.4', 'name':'Converse County' },
'DGT': { 'latitude':'9.3', 'longitude': '123.3', 'name':'Dumaguete' },
'DGU': { 'latitude':'12.466667', 'longitude': '-3.483333', 'name':'Dedougou' },
'UNR': { 'latitude':'47.316667', 'longitude': '110.666667', 'name':'Underkhaan' },
'UNS': { 'latitude':'26.8', 'longitude': '98.083333', 'name':'Umnak' },
'UNT': { 'latitude':'60.75', 'longitude': '-0.85', 'name':'Baltasound' },
'UNU': { 'latitude':'43.426389', 'longitude': '-88.703889', 'name':'Dodge County' },
'UNA': { 'latitude':'-15.355278', 'longitude': '-38.998889', 'name':'Una' },
'UNC': { 'latitude':'8.033333', 'longitude': '-77.083333', 'name':'Unguia' },
'UND': { 'latitude':'36.65', 'longitude': '68.883333', 'name':'Kunduz' },
'UNE': { 'latitude':'-30.1', 'longitude': '28.7', 'name':'Qachas Nek' },
'UET': { 'latitude':'30.25', 'longitude': '66.933333', 'name':'Quetta' },
'UNI': { 'latitude':'12.616667', 'longitude': '-61.433333', 'name':'Union Island' },
'UNK': { 'latitude':'63.883333', 'longitude': '-160.783333', 'name':'Unalakleet' },
'UNN': { 'latitude':'9.852778', 'longitude': '98.629167', 'name':'Ranong' },
'ITN': { 'latitude':'-14.8', 'longitude': '-39.383333', 'name':'Itabuna' },
'ITO': { 'latitude':'19.716667', 'longitude': '-155.05', 'name':'Hilo International' },
'OMA': { 'latitude':'41.3', 'longitude': '-95.9', 'name':'Eppley Airfield' },
'ITM': { 'latitude':'34.785278', 'longitude': '135.438056', 'name':'Itami' },
'OMG': { 'latitude':'-18.0', 'longitude': '22.066667', 'name':'Omega' },
'ITK': { 'latitude':'-9.516667', 'longitude': '147.3', 'name':'Itokama' },
'ITH': { 'latitude':'42.483333', 'longitude': '-76.466667', 'name':'Tompkins County' },
'ITI': { 'latitude':'-18.016667', 'longitude': '-41.7', 'name':'Itambacuri' },
'OMK': { 'latitude':'48.4', 'longitude': '-119.533333', 'name':'Municipal' },
'OMJ': { 'latitude':'35.083333', 'longitude': '140.1', 'name':'Omura' },
'OMI': { 'latitude':'30.872222', 'longitude': '49.541111', 'name':'Omidieh' },
'ITE': { 'latitude':'-13.7', 'longitude': '-39.2', 'name':'Itubera' },
'ITB': { 'latitude':'-4.266667', 'longitude': '-55.983333', 'name':'Itaituba' },
'OMN': { 'latitude':'18.15', 'longitude': '76.1', 'name':'Osmanabad' },
'OMM': { 'latitude':'18.133333', 'longitude': '55.266667', 'name':'Marmul' },
'ITA': { 'latitude':'-3.2', 'longitude': '-58.5', 'name':'Itacoatiara' },
'OMS': { 'latitude':'54.966667', 'longitude': '73.3', 'name':'Omsk' },
'OMR': { 'latitude':'47.016667', 'longitude': '21.9', 'name':'Oradea' },
'OMY': { 'latitude':'13.816667', 'longitude': '104.966667', 'name':'Oddor Meanche' },
'ITR': { 'latitude':'-18.444722', 'longitude': '-49.213333', 'name':'Hidroeletrica' },
'ITP': { 'latitude':'-21.2', 'longitude': '-41.9', 'name':'Itaperuna' },
'ITQ': { 'latitude':'-29.166667', 'longitude': '-56.533333', 'name':'Itaqui' },
'AAE': { 'latitude':'36.833333', 'longitude': '8.0', 'name':'Les Salines' },
'AAD': { 'latitude':'17.592778', 'longitude': '33.959167', 'name':'Ad-Dabbah' },
'AAG': { 'latitude':'-24.166667', 'longitude': '-49.666667', 'name':'Arapoti' },
'AAF': { 'latitude':'29.733333', 'longitude': '-85.033333', 'name':'Municipal' },
'AAA': { 'latitude':'-17.416667', 'longitude': '-145.5', 'name':'Anaa' },
'AAC': { 'latitude':'31.073333', 'longitude': '33.835833', 'name':'Al Arish International Airport' },
'AAB': { 'latitude':'-26.75', 'longitude': '141.0', 'name':'Arrabury' },
'AAM': { 'latitude':'-24.8', 'longitude': '31.533333', 'name':'Mala Mala' },
'AAL': { 'latitude':'57.1', 'longitude': '9.85', 'name':'Aalborg' },
'AAO': { 'latitude':'9.416667', 'longitude': '-64.466667', 'name':'Anaco' },
'AAN': { 'latitude':'24.261667', 'longitude': '55.609167', 'name':'Al Ain' },
'AAI': { 'latitude':'-12.916667', 'longitude': '-46.933333', 'name':'Arraias' },
'AAH': { 'latitude':'50.823056', 'longitude': '6.186111', 'name':'Aachen/Merzbruck' },
'AAK': { 'latitude':'0.216667', 'longitude': '174.0', 'name':'Aranuka' },
'AAJ': { 'latitude':'3.896667', 'longitude': '-55.579167', 'name':'Cayana Airstrip' },
'AAU': { 'latitude':'-13.458333', 'longitude': '-172.6', 'name':'Asau' },
'AAT': { 'latitude':'47.74972', 'longitude': '88.08472', 'name':'Altay' },
'AAW': { 'latitude':'34.2', 'longitude': '73.25', 'name':'Abbottabad' },
'AAV': { 'latitude':'6.366944', 'longitude': '124.751389', 'name':'Allah Valley' },
'AAQ': { 'latitude':'44.9', 'longitude': '37.316667', 'name':'Anapa' },
'AAP': { 'latitude':'29.723889', 'longitude': '-95.588333', 'name':'Andrau Airpark' },
'AAS': { 'latitude':'-3.916667', 'longitude': '139.25', 'name':'Apalapsili' },
'AAR': { 'latitude':'56.307222', 'longitude': '10.626111', 'name':'Aarhus Airport' },
'AAY': { 'latitude':'16.2', 'longitude': '52.183333', 'name':'Al Ghaydah' },
'AAX': { 'latitude':'-19.568056', 'longitude': '-46.929167', 'name':'Araxa' },
'AAZ': { 'latitude':'-7.862222', 'longitude': '13.116111', 'name':'Ambriz' },
'BIN': { 'latitude':'34.8', 'longitude': '67.816667', 'name':'Bamiyan' },
'BIO': { 'latitude':'43.301111', 'longitude': '-2.910556', 'name':'Sondica' },
'BIL': { 'latitude':'45.8', 'longitude': '-108.533333', 'name':'Billings' },
'BIM': { 'latitude':'25.7', 'longitude': '-79.283333', 'name':'International' },
'BIJ': { 'latitude':'-5.583333', 'longitude': '146.35', 'name':'Biliau' },
'BIK': { 'latitude':'-1.19', 'longitude': '136.108056', 'name':'Frans Kaisepo' },
'BIH': { 'latitude':'37.366667', 'longitude': '-118.35', 'name':'Bishop' },
'BII': { 'latitude':'11.5', 'longitude': '165.55', 'name':'Enyu Airfield' },
'BIF': { 'latitude':'31.849444', 'longitude': '-106.38', 'name':'Biggs Aaf' },
'BIG': { 'latitude':'64.0', 'longitude': '-145.733333', 'name':'Intermediate Field' },
'BID': { 'latitude':'41.169444', 'longitude': '-71.583333', 'name':'Block Island' },
'BIE': { 'latitude':'40.316667', 'longitude': '-96.75', 'name':'Beatrice' },
'BIB': { 'latitude':'3.066667', 'longitude': '43.8', 'name':'Baidoa' },
'BIC': { 'latitude':'58.3', 'longitude': '-157.516667', 'name':'Big Creek' },
'BIA': { 'latitude':'42.7', 'longitude': '9.45', 'name':'Poretta' },
'BIZ': { 'latitude':'-5.283333', 'longitude': '142.016667', 'name':'Bimin' },
'BIX': { 'latitude':'28.666667', 'longitude': '-88.433333', 'name':'Keesler AFB' },
'BIY': { 'latitude':'-32.833333', 'longitude': '27.333333', 'name':'Bisho' },
'BIV': { 'latitude':'6.533333', 'longitude': '21.983333', 'name':'Bria' },
'BIW': { 'latitude':'-19.583333', 'longitude': '127.633333', 'name':'Billiluna' },
'BIT': { 'latitude':'29.533333', 'longitude': '80.433333', 'name':'Baitadi' },
'BIU': { 'latitude':'65.833333', 'longitude': '-23.983333', 'name':'Bildudalur' },
'BIR': { 'latitude':'26.434722', 'longitude': '87.283333', 'name':'Biratnagar' },
'BIS': { 'latitude':'46.783333', 'longitude': '-100.75', 'name':'Bismarck' },
'BIP': { 'latitude':'-16.15', 'longitude': '143.75', 'name':'Bulimba' },
'BIQ': { 'latitude':'43.466667', 'longitude': '-1.533333', 'name':'Biarritz Parme' },
'SLX': { 'latitude':'21.333333', 'longitude': '-71.201667', 'name':'Salt Cay' },
'SLY': { 'latitude':'66.583333', 'longitude': '66.6', 'name':'Salekhard' },
'SLZ': { 'latitude':'-2.585278', 'longitude': '-44.234167', 'name':'Marechal Cunha Machado' },
'SLT': { 'latitude':'38.55', 'longitude': '-106.033333', 'name':'Salida' },
'SLU': { 'latitude':'14.019167', 'longitude': '-60.992778', 'name':'St Lucia Vigie' },
'SLV': { 'latitude':'31.116667', 'longitude': '77.15', 'name':'Simla' },
'SLW': { 'latitude':'25.55', 'longitude': '-100.933333', 'name':'Saltillo' },
'SLP': { 'latitude':'22.183333', 'longitude': '-100.983333', 'name':'San Luis Potosi' },
'SLQ': { 'latitude':'61.7', 'longitude': '-157.116667', 'name':'Sleetmute' },
'SLR': { 'latitude':'33.133333', 'longitude': '-95.6', 'name':'Sulphur Springs' },
'SLS': { 'latitude':'44.016667', 'longitude': '27.183333', 'name':'Silistra' },
'SLL': { 'latitude':'17.033333', 'longitude': '54.1', 'name':'Salalah' },
'SLM': { 'latitude':'40.966667', 'longitude': '-5.65', 'name':'Matacan' },
'SLN': { 'latitude':'38.816667', 'longitude': '-97.566667', 'name':'Salina' },
'SLO': { 'latitude':'38.616667', 'longitude': '-88.933333', 'name':'Leckrone' },
'SLH': { 'latitude':'-13.883333', 'longitude': '167.55', 'name':'Sola' },
'SLI': { 'latitude':'-12.172222', 'longitude': '26.366667', 'name':'Solwezi' },
'SLJ': { 'latitude':'33.319444', 'longitude': '-111.9', 'name':'Stellar Air Park' },
'SLK': { 'latitude':'44.4', 'longitude': '-74.2', 'name':'Adirondack' },
'SLD': { 'latitude':'48.633333', 'longitude': '19.133333', 'name':'Sliac' },
'SLE': { 'latitude':'44.916667', 'longitude': '-123.0', 'name':'Mcnary Field' },
'SLF': { 'latitude':'20.466667', 'longitude': '45.616667', 'name':'Sulayel' },
'RDZ': { 'latitude':'44.366667', 'longitude': '2.516667', 'name':'Marcillac' },
'SLA': { 'latitude':'-24.85', 'longitude': '-65.483333', 'name':'Gen Belgrano' },
'SLB': { 'latitude':'42.6', 'longitude': '-95.233333', 'name':'Municipal' },
'SLC': { 'latitude':'40.788333', 'longitude': '-111.966667', 'name':'Salt Lake City International' },
'MCO': { 'latitude':'28.429444', 'longitude': '-81.308889', 'name':'Orlando International' },
'MCN': { 'latitude':'32.683333', 'longitude': '-83.65', 'name':'Lewis B Wilson' },
'MCM': { 'latitude':'43.733333', 'longitude': '7.416667', 'name':'Fontvieille Heliport' },
'MCL': { 'latitude':'63.733333', 'longitude': '-148.9', 'name':'Mt Mckinley' },
'MCK': { 'latitude':'40.2', 'longitude': '-100.583333', 'name':'Mccook' },
'MCJ': { 'latitude':'11.383333', 'longitude': '-72.233333', 'name':'Maicao' },
'MCI': { 'latitude':'39.291667', 'longitude': '-94.730556', 'name':'Kansas City International Airport' },
'MCH': { 'latitude':'-3.266667', 'longitude': '-79.983333', 'name':'Machala' },
'MCG': { 'latitude':'62.966667', 'longitude': '-155.633333', 'name':'Mcgrath' },
'MCF': { 'latitude':'54.433333', 'longitude': '23.65', 'name':'Mac Dill AFB' },
'MCE': { 'latitude':'37.283333', 'longitude': '-120.516667', 'name':'Merced Municipal Arpt' },
'MCD': { 'latitude':'45.865', 'longitude': '-84.637222', 'name':'Mackinac Island' },
'MCC': { 'latitude':'10.783333', 'longitude': '-74.15', 'name':'Mcclellan AFB' },
'MCB': { 'latitude':'31.15', 'longitude': '-90.433333', 'name':'Pike County' },
'MCA': { 'latitude':'8.533333', 'longitude': '-9.466667', 'name':'Macenta' },
'GFK': { 'latitude':'47.95', 'longitude': '-97.183333', 'name':'Grand Forks' },
'GFN': { 'latitude':'-29.666667', 'longitude': '153.0', 'name':'Grafton' },
'MCZ': { 'latitude':'-9.633333', 'longitude': '-35.7', 'name':'Palmares' },
'MCY': { 'latitude':'-26.603333', 'longitude': '153.091111', 'name':'Maroochydore' },
'MCX': { 'latitude':'42.966667', 'longitude': '47.5', 'name':'Makhachkala' },
'MCW': { 'latitude':'43.157778', 'longitude': '-93.331389', 'name':'Mason City Municipal' },
'MCV': { 'latitude':'-16.466667', 'longitude': '136.083333', 'name':'Mcarthur River' },
'MCU': { 'latitude':'46.35', 'longitude': '2.6', 'name':'Gueret' },
'MCT': { 'latitude':'23.633333', 'longitude': '58.533333', 'name':'Seeb' },
'MCS': { 'latitude':'-30.266667', 'longitude': '-57.633333', 'name':'Monte Caseros' },
'MCR': { 'latitude':'17.091667', 'longitude': '-89.158333', 'name':'Melchor De Menco' },
'MCQ': { 'latitude':'48.138889', 'longitude': '20.794444', 'name':'Miskolc' },
'GFE': { 'latitude':'-33.9', 'longitude': '148.166667', 'name':'Grenfell' },
'EXM': { 'latitude':'-22.383333', 'longitude': '114.116667', 'name':'Exmouth Gulf' },
'EXI': { 'latitude':'58.416667', 'longitude': '-135.433333', 'name':'SPB' },
'LQM': { 'latitude':'-0.3', 'longitude': '-74.583333', 'name':'Puerto Leguizamo' },
'EXT': { 'latitude':'50.733333', 'longitude': '-3.416667', 'name':'Exeter' },
'LQK': { 'latitude':'34.816667', 'longitude': '-82.7', 'name':'Pickens' },
'RDN': { 'latitude':'5.765278', 'longitude': '103.006944', 'name':'Redang' },
'LEA': { 'latitude':'-22.233333', 'longitude': '114.1', 'name':'Learmonth' },
'KIZ': { 'latitude':'-8.65', 'longitude': '147.916667', 'name':'Kikinonda' },
'KIY': { 'latitude':'-8.916667', 'longitude': '39.533333', 'name':'Kilwa' },
'KIX': { 'latitude':'34.427222', 'longitude': '135.243889', 'name':'Kansai International' },
'KIS': { 'latitude':'-0.083333', 'longitude': '34.733333', 'name':'Kisumu' },
'KIR': { 'latitude':'52.066667', 'longitude': '-9.5', 'name':'Kerry' },
'KIQ': { 'latitude':'-7.633333', 'longitude': '147.083333', 'name':'Kira' },
'KIP': { 'latitude':'33.9', 'longitude': '-98.5', 'name':'Kickapoo' },
'KIW': { 'latitude':'-12.839444', 'longitude': '28.230556', 'name':'Southdowns' },
'KIV': { 'latitude':'46.928889', 'longitude': '28.926667', 'name':'International Airport Chisinau' },
'KIU': { 'latitude':'-1.75', 'longitude': '41.483333', 'name':'Kiunga' },
'KIT': { 'latitude':'36.15', 'longitude': '22.983333', 'name':'Kithira' },
'KIK': { 'latitude':'35.516667', 'longitude': '44.3', 'name':'Kirkuk' },
'KIJ': { 'latitude':'37.95', 'longitude': '139.116667', 'name':'Niigata' },
'KII': { 'latitude':'-2.366667', 'longitude': '25.683333', 'name':'Kibuli' },
'KIH': { 'latitude':'26.483333', 'longitude': '53.95', 'name':'Kish Island' },
'KIO': { 'latitude':'5.65', 'longitude': '169.2', 'name':'Kili Island' },
'KIN': { 'latitude':'17.933333', 'longitude': '-76.783333', 'name':'Norman Manley' },
'KIM': { 'latitude':'-28.8', 'longitude': '24.766667', 'name':'Kimberley' },
'KIL': { 'latitude':'-9.3', 'longitude': '28.383333', 'name':'Kilwa' },
'KIC': { 'latitude':'36.233333', 'longitude': '-121.116667', 'name':'Mesa Del Rey' },
'KIB': { 'latitude':'55.9', 'longitude': '-159.483333', 'name':'SPB' },
'KIA': { 'latitude':'-6.266667', 'longitude': '146.25', 'name':'Kaiapit' },
'KIG': { 'latitude':'-30.2', 'longitude': '17.266667', 'name':'Koinghaas' },
'LEJ': { 'latitude':'51.4325', 'longitude': '12.241667', 'name':'Leipzig-halle' },
'KIE': { 'latitude':'-6.333333', 'longitude': '155.591667', 'name':'Aropa' },
'KID': { 'latitude':'55.920556', 'longitude': '14.085278', 'name':'Kristianstad' },
'CRR': { 'latitude':'-29.866667', 'longitude': '-61.833333', 'name':'Ceres' },
'CRS': { 'latitude':'32.1', 'longitude': '-96.466667', 'name':'Corsicana' },
'CRP': { 'latitude':'27.770278', 'longitude': '-97.501111', 'name':'Corpus Christi International Airport' },
'CRQ': { 'latitude':'-17.65', 'longitude': '-39.25', 'name':'Caravelas' },
'CRV': { 'latitude':'39.0', 'longitude': '17.083333', 'name':'Crotone' },
'CRW': { 'latitude':'38.366667', 'longitude': '-81.6', 'name':'Yeager' },
'CRT': { 'latitude':'33.133333', 'longitude': '-91.966667', 'name':'Municipal' },
'CRU': { 'latitude':'12.466667', 'longitude': '-61.466667', 'name':'Carriacou Is' },
'CRZ': { 'latitude':'39.083333', 'longitude': '63.616667', 'name':'Turkmenabad' },
'CRX': { 'latitude':'34.9', 'longitude': '-88.6', 'name':'Roscoe Turner' },
'CRY': { 'latitude':'-15.7', 'longitude': '128.5', 'name':'Carlton Hill' },
'LEM': { 'latitude':'45.916667', 'longitude': '-102.1', 'name':'Lemmon' },
'CRB': { 'latitude':'-29.525833', 'longitude': '148.575833', 'name':'Collarenebri' },
'CRC': { 'latitude':'4.766667', 'longitude': '-75.933333', 'name':'Cartago' },
'CRA': { 'latitude':'44.433333', 'longitude': '23.8', 'name':'Craiova' },
'CRF': { 'latitude':'4.933333', 'longitude': '15.9', 'name':'Carnot' },
'CRG': { 'latitude':'30.333889', 'longitude': '-81.5025', 'name':'Craig Municipal' },
'CRD': { 'latitude':'-45.783333', 'longitude': '-67.466667', 'name':'Comodoro Rivadavia' },
'CRE': { 'latitude':'33.811667', 'longitude': '-78.723889', 'name':'Grand Strand Airport' },
'CRJ': { 'latitude':'-31.9', 'longitude': '132.3', 'name':'Coorabie' },
'CRK': { 'latitude':'15.183333', 'longitude': '120.533333', 'name':'Diosdado Macapagal International' },
'CRH': { 'latitude':'-27.65', 'longitude': '151.95', 'name':'Cherribah' },
'CRI': { 'latitude':'22.75', 'longitude': '-74.15', 'name':'Crooked Island' },
'CRN': { 'latitude':'57.65', 'longitude': '-4.05', 'name':'Cromarty' },
'CRO': { 'latitude':'36.1', 'longitude': '-119.55', 'name':'Corcoran' },
'CRL': { 'latitude':'50.46', 'longitude': '4.452778', 'name':'Charleroi Brussels South' },
'CRM': { 'latitude':'12.516667', 'longitude': '124.633333', 'name':'National' },
'LET': { 'latitude':'-4.2', 'longitude': '-69.933333', 'name':'Gen. A.V. Cobo' },
'LEV': { 'latitude':'-17.683333', 'longitude': '178.833333', 'name':'Levuka Airfield' },
'LEW': { 'latitude':'44.05', 'longitude': '-70.283333', 'name':'Auburn' },
'LEX': { 'latitude':'38.036389', 'longitude': '-84.605833', 'name':'Blue Grass' },
'OPU': { 'latitude':'-8.033333', 'longitude': '142.933333', 'name':'Balimo' },
'OPW': { 'latitude':'-18.066667', 'longitude': '13.833333', 'name':'Opuwa' },
'OPS': { 'latitude':'-12.084722', 'longitude': '-55.633889', 'name':'Sinop' },
'OPF': { 'latitude':'25.906944', 'longitude': '-80.278333', 'name':'Opa Locka' },
'OPA': { 'latitude':'66.416667', 'longitude': '-16.483333', 'name':'Kopasker' },
'OPB': { 'latitude':'-4.933333', 'longitude': '151.666667', 'name':'Open Bay' },
'OPL': { 'latitude':'30.55', 'longitude': '-92.1', 'name':'St Landry Parish' },
'OPO': { 'latitude':'41.248056', 'longitude': '-8.681389', 'name':'Francisco Sá Carneiro' },
'OPI': { 'latitude':'-12.333333', 'longitude': '133.083333', 'name':'Oenpelli' },
'PSO': { 'latitude':'1.466667', 'longitude': '-77.25', 'name':'Cano' },
'PSM': { 'latitude':'43.078056', 'longitude': '-70.823333', 'name':'Pease International' },
'EYK': { 'latitude':'63.6833', 'longitude': '66.6833', 'name':'Beloyarsky' },
'ZKL': { 'latitude':'-2.102778', 'longitude': '133.516667', 'name':'Steenkool' },
'ZKM': { 'latitude':'-2.533333', 'longitude': '9.766667', 'name':'Sette Cama' },
'ZKE': { 'latitude':'52.281944', 'longitude': '-81.678333', 'name':'Kaschechewan' },
'ZKG': { 'latitude':'50.188889', 'longitude': '-61.291667', 'name':'Kegaska' },
'ZKB': { 'latitude':'-8.516667', 'longitude': '30.666667', 'name':'Kasaba Bay' },
'ZKP': { 'latitude':'-12.566667', 'longitude': '27.9', 'name':'Kasompe' },
'PSP': { 'latitude':'33.833333', 'longitude': '-116.5', 'name':'Municipal' },
'PSQ': { 'latitude':'29.483333', 'longitude': '31.066667', 'name':'SPB' },
'EYP': { 'latitude':'5.35', 'longitude': '-72.383333', 'name':'El Yopal' },
'EYS': { 'latitude':'3.216667', 'longitude': '35.966667', 'name':'Eliye Springs' },
'PSW': { 'latitude':'-20.716667', 'longitude': '-46.616667', 'name':'Passos' },
'YZU': { 'latitude':'54.15', 'longitude': '-115.683333', 'name':'Whitecourt' },
'LPL': { 'latitude':'53.333611', 'longitude': '-2.849722', 'name':'Liverpool John Lennon' },
'HNA': { 'latitude':'39.733333', 'longitude': '141.116667', 'name':'Hanamaki' },
'EYW': { 'latitude':'24.55', 'longitude': '-81.766667', 'name':'International' },
'HNC': { 'latitude':'35.216667', 'longitude': '-75.686111', 'name':'Hatteras' },
'HNB': { 'latitude':'38.3', 'longitude': '-86.95', 'name':'Municipal' },
'HNE': { 'latitude':'35.742778', 'longitude': '52.508611', 'name':'Tahneta Pass' },
'HND': { 'latitude':'35.552222', 'longitude': '139.779722', 'name':'Tokyo Haneda International' },
'HNG': { 'latitude':'-20.683333', 'longitude': '164.933333', 'name':'Hienghene' },
'HNI': { 'latitude':'-7.4', 'longitude': '146.466667', 'name':'Heiweni' },
'HNH': { 'latitude':'58.1', 'longitude': '-135.433333', 'name':'Hoonah' },
'HNK': { 'latitude':'-18.383333', 'longitude': '146.283333', 'name':'Hinchinbrook Island' },
'VIB': { 'latitude':'25.058333', 'longitude': '-111.7', 'name':'Villa Constitucion' },
'VIC': { 'latitude':'45.574167', 'longitude': '11.516667', 'name':'Vicenza' },
'XAP': { 'latitude':'-27.133333', 'longitude': '-52.651944', 'name':'Aeroporto Municipal Chapeco' },
'XAR': { 'latitude':'14.233333', 'longitude': '-0.866667', 'name':'Aribinda' },
'XAU': { 'latitude':'3.616667', 'longitude': '-53.2', 'name':'Saul' },
'HNL': { 'latitude':'21.333333', 'longitude': '-157.933333', 'name':'Honolulu International' },
'XAL': { 'latitude':'27.016667', 'longitude': '-108.933333', 'name':'Alamos' },
'HNO': { 'latitude':'42.566667', 'longitude': '18.533333', 'name':'Hercegnovi' },
'HNN': { 'latitude':'-6.233333', 'longitude': '142.216667', 'name':'Honinabi' },
'VIJ': { 'latitude':'18.5', 'longitude': '-64.5', 'name':'Virgin Gorda' },
'VIH': { 'latitude':'38.316667', 'longitude': '-90.833333', 'name':'Rolla National' },
'ICK': { 'latitude':'5.933333', 'longitude': '-56.983333', 'name':'Nieuw Nickerie' },
'VII': { 'latitude':'18.7', 'longitude': '105.633333', 'name':'Vinh City' },
'ICI': { 'latitude':'-17.75', 'longitude': '-179.333333', 'name':'Cicia' },
'HNY': { 'latitude':'26.905278', 'longitude': '112.627778', 'name':'Hengyang' },
'VIL': { 'latitude':'23.733333', 'longitude': '-15.916667', 'name':'Dakhla' },
'HNX': { 'latitude':'51.631389', 'longitude': '-111.904167', 'name':'Hanna' },
'CNR': { 'latitude':'-26.316667', 'longitude': '-70.616667', 'name':'Chanaral' },
'ICN': { 'latitude':'37.469167', 'longitude': '126.450556', 'name':'Incheon International' },
'ICL': { 'latitude':'40.733333', 'longitude': '-95.033333', 'name':'Municipal' },
'WBW': { 'latitude':'41.297222', 'longitude': '-75.851111', 'name':'Wilkes-Barre/Wyoming Valley' },
'VIT': { 'latitude':'42.85', 'longitude': '-2.666667', 'name':'Vitoria.' },
'VOG': { 'latitude':'48.75', 'longitude': '44.5', 'name':'Volgograd' },
'VOL': { 'latitude':'39.333333', 'longitude': '22.841667', 'name':'Nea Anchialos' },
'VOH': { 'latitude':'-13.366667', 'longitude': '50.0', 'name':'Vohemar' },
'ICY': { 'latitude':'59.983333', 'longitude': '-141.65', 'name':'Icy Bay' },
'VOK': { 'latitude':'43.916667', 'longitude': '-90.266667', 'name':'Volk Field' },
'VOT': { 'latitude':'-20.4', 'longitude': '-49.983333', 'name':'Votuporanga' },
'UII': { 'latitude':'16.091667', 'longitude': '-86.8875', 'name':'Utila' },
'VOZ': { 'latitude':'51.814167', 'longitude': '39.229722', 'name':'Chertovitskoye' },
'TBI': { 'latitude':'24.315', 'longitude': '-75.453611', 'name':'The Bight' },
'ICR': { 'latitude':'20.983333', 'longitude': '-75.975', 'name':'Nicaro' },
'CNI': { 'latitude':'39.266667', 'longitude': '122.516667', 'name':'Changhai' },
'CIC': { 'latitude':'39.8', 'longitude': '-121.85', 'name':'Chico' },
'CIB': { 'latitude':'33.416389', 'longitude': '-118.416389', 'name':'Ap In The Sky' },
'CIA': { 'latitude':'41.799444', 'longitude': '12.595', 'name':'Ciampino' },
'CIG': { 'latitude':'40.5', 'longitude': '-107.583333', 'name':'Craig-Moffat' },
'CIF': { 'latitude':'42.333333', 'longitude': '119.008333', 'name':'Chifeng' },
'CIE': { 'latitude':'-33.35', 'longitude': '116.15', 'name':'Collie' },
'CID': { 'latitude':'41.884722', 'longitude': '-91.710833', 'name':'Cedar Rapids' },
'CIK': { 'latitude':'66.65', 'longitude': '-143.75', 'name':'Chalkyitsik' },
'CIJ': { 'latitude':'-11.016667', 'longitude': '-68.733333', 'name':'E. Beltram' },
'CIH': { 'latitude':'36.183333', 'longitude': '113.133333', 'name':'Changzhi' },
'CIO': { 'latitude':'4.066667', 'longitude': '-73.733333', 'name':'MCAL Lopez' },
'CIN': { 'latitude':'42.05', 'longitude': '-94.783333', 'name':'Carroll' },
'CIM': { 'latitude':'6.483333', 'longitude': '-74.033333', 'name':'Cimitarra' },
'CIL': { 'latitude':'64.9', 'longitude': '-163.733333', 'name':'Melsing Creek' },
'CIS': { 'latitude':'-2.833333', 'longitude': '-171.666667', 'name':'Canton Island' },
'CIR': { 'latitude':'4.666667', 'longitude': '-76.016667', 'name':'Cairo' },
'CIQ': { 'latitude':'14.8', 'longitude': '-89.55', 'name':'Chiquimula' },
'CIP': { 'latitude':'-13.55', 'longitude': '32.6', 'name':'Chipata' },
'CIW': { 'latitude':'12.716667', 'longitude': '-61.333333', 'name':'Canouan Island' },
'CIV': { 'latitude':'55.216667', 'longitude': '-132.216667', 'name':'Chomley' },
'CIU': { 'latitude':'46.25', 'longitude': '-84.466667', 'name':'Chippewa County' },
'FUO': { 'latitude':'23.133333', 'longitude': '113.283333', 'name':'Fuoshan' },
'CIZ': { 'latitude':'-4.083333', 'longitude': '-63.133333', 'name':'Coari' },
'CIY': { 'latitude':'37.0', 'longitude': '14.6', 'name':'Comiso' },
'CIX': { 'latitude':'-6.783333', 'longitude': '-79.833333', 'name':'Cornel Ruiz' },
'DAD': { 'latitude':'16.033333', 'longitude': '108.183333', 'name':'Da Nang' },
'DAE': { 'latitude':'27.5', 'longitude': '94.333333', 'name':'Daparizo' },
'DAF': { 'latitude':'-4.741667', 'longitude': '145.958333', 'name':'Daup' },
'DAG': { 'latitude':'34.85', 'longitude': '-116.783333', 'name':'Barstow-Daggett' },
'DAA': { 'latitude':'38.716667', 'longitude': '-77.183333', 'name':'Davison AAF' },
'DAB': { 'latitude':'29.183333', 'longitude': '-81.05', 'name':'Regional' },
'DAC': { 'latitude':'23.780555', 'longitude': '90.386111', 'name':'Zia International' },
'DAL': { 'latitude':'32.852778', 'longitude': '-96.85', 'name':'Love Field' },
'DAM': { 'latitude':'33.483333', 'longitude': '36.233333', 'name':'International' },
'DAN': { 'latitude':'36.566667', 'longitude': '-79.35', 'name':'Municipal' },
'DAO': { 'latitude':'13.133333', 'longitude': '42.166667', 'name':'Dabo' },
'DAH': { 'latitude':'13.866667', 'longitude': '46.133333', 'name':'Dathina' },
'DAI': { 'latitude':'26.75', 'longitude': '88.25', 'name':'Darjeeling' },
'DAJ': { 'latitude':'-9.433333', 'longitude': '142.516667', 'name':'Dauan Island' },
'DAK': { 'latitude':'25.5', 'longitude': '29.166667', 'name':'Dakhla' },
'DAT': { 'latitude':'40.05554', 'longitude': '113.48136', 'name':'Datong Airport' },
'DAU': { 'latitude':'-9.083333', 'longitude': '143.2', 'name':'Daru' },
'DAV': { 'latitude':'8.390833', 'longitude': '-82.435', 'name':'Enrique Malek' },
'DAP': { 'latitude':'29.666667', 'longitude': '80.5', 'name':'Darchula' },
'DAR': { 'latitude':'-6.875556', 'longitude': '39.201944', 'name':'International' },
'DAS': { 'latitude':'66.0', 'longitude': '-1.0', 'name':'Great Bear Lake' },
'DAX': { 'latitude':'31.3', 'longitude': '107.5', 'name':'Daxian' },
'DAY': { 'latitude':'39.75', 'longitude': '-84.183333', 'name':'James Cox Dayton Intl' },
'DAZ': { 'latitude':'38.466667', 'longitude': '70.883333', 'name':'Darwaz' },
'ULZ': { 'latitude':'47.75', 'longitude': '96.85', 'name':'Uliastai' },
'ULX': { 'latitude':'-24.783333', 'longitude': '31.35', 'name':'Ulusaba' },
'ULY': { 'latitude':'54.401111', 'longitude': '48.800278', 'name':'Vostochny' },
'ULS': { 'latitude':'8.65', 'longitude': '-76.75', 'name':'Mulatos' },
'ULP': { 'latitude':'-26.633333', 'longitude': '144.3', 'name':'Quilpie' },
'ULQ': { 'latitude':'4.083333', 'longitude': '-76.0', 'name':'Farfan' },
'ULU': { 'latitude':'2.783333', 'longitude': '32.3', 'name':'Gulu' },
'ULI': { 'latitude':'9.966667', 'longitude': '139.666667', 'name':'Ulithi' },
'ULN': { 'latitude':'47.843056', 'longitude': '106.766667', 'name':'Chinggis Khaan International' },
'ULO': { 'latitude':'49.983333', 'longitude': '92.066667', 'name':'Ulaangom' },
'ULL': { 'latitude':'56.416667', 'longitude': '-6.333333', 'name':'Mull' },
'ULM': { 'latitude':'44.316667', 'longitude': '-94.5', 'name':'New Ulm' },
'ULB': { 'latitude':'-16.333333', 'longitude': '168.294444', 'name':'Ulei' },
'ULC': { 'latitude':'19.333333', 'longitude': '-72.2', 'name':'Los Cerrillos' },
'ULA': { 'latitude':'-49.3', 'longitude': '-67.75', 'name':'San Julian' },
'ULG': { 'latitude':'48.966667', 'longitude': '89.966667', 'name':'Ulgit' },
'ULD': { 'latitude':'-28.283333', 'longitude': '31.433333', 'name':'Ulundi' },
'ULE': { 'latitude':'-4.966667', 'longitude': '151.316667', 'name':'Sule' },
'OOA': { 'latitude':'41.283333', 'longitude': '-92.633333', 'name':'Municipal' },
'IJU': { 'latitude':'-28.418611', 'longitude': '-53.916667', 'name':'J. Batista Bos Filho Airport' },
'IJX': { 'latitude':'39.766667', 'longitude': '-90.233333', 'name':'Municipal' },
'OOL': { 'latitude':'-28.181111', 'longitude': '153.5', 'name':'Gold Coast' },
'OOK': { 'latitude':'60.531944', 'longitude': '-165.108333', 'name':'Toksook Bay' },
'OOT': { 'latitude':'-1.866667', 'longitude': '175.566667', 'name':'Onotoa' },
'OOR': { 'latitude':'-25.245', 'longitude': '140.980833', 'name':'Mooraberree' },
'IJK': { 'latitude':'56.833333', 'longitude': '53.466667', 'name':'Izhevsk' },
'AGO': { 'latitude':'33.233333', 'longitude': '-93.216667', 'name':'Municipal' },
'AGN': { 'latitude':'57.5', 'longitude': '-134.583333', 'name':'Angoon' },
'AGM': { 'latitude':'65.666667', 'longitude': '-37.666667', 'name':'Tasiilaq' },
'AGL': { 'latitude':'-9.333333', 'longitude': '149.15', 'name':'Wanigela' },
'AGK': { 'latitude':'-6.333333', 'longitude': '143.833333', 'name':'Kagua' },
'AGJ': { 'latitude':'26.833333', 'longitude': '127.166667', 'name':'Aguni' },
'AGI': { 'latitude':'5.766667', 'longitude': '-56.683333', 'name':'Wageningen' },
'AGH': { 'latitude':'56.283333', 'longitude': '12.833333', 'name':'Angelholm' },
'AGG': { 'latitude':'-4.066667', 'longitude': '144.1', 'name':'Angoram' },
'AGF': { 'latitude':'44.183333', 'longitude': '0.6', 'name':'La Garenne' },
'AGE': { 'latitude':'53.783333', 'longitude': '7.916667', 'name':'Flugplatz' },
'AGD': { 'latitude':'-1.383333', 'longitude': '133.866667', 'name':'Anggi' },
'AGC': { 'latitude':'40.35', 'longitude': '-79.933333', 'name':'Allegheny County' },
'AGB': { 'latitude':'48.383333', 'longitude': '10.883333', 'name':'Augsburg - Muehlhausen' },
'AGA': { 'latitude':'30.383333', 'longitude': '-9.55', 'name':'Agadir Almassira' },
'NYU': { 'latitude':'21.2', 'longitude': '94.966667', 'name':'Nyaung-u' },
'NYK': { 'latitude':'0.066667', 'longitude': '37.033333', 'name':'Nanyuki' },
'NYI': { 'latitude':'7.333333', 'longitude': '-2.333333', 'name':'Sunyani' },
'NYN': { 'latitude':'-31.55', 'longitude': '147.183333', 'name':'Nyngan' },
'AGZ': { 'latitude':'-29.273333', 'longitude': '18.813889', 'name':'Aggeneys' },
'AGY': { 'latitude':'-16.35', 'longitude': '128.75', 'name':'Argyle Downs' },
'AGX': { 'latitude':'10.833333', 'longitude': '72.2', 'name':'Agatti Island' },
'AGW': { 'latitude':'-12.15', 'longitude': '142.15', 'name':'Agnew' },
'AGV': { 'latitude':'9.55', 'longitude': '-69.233333', 'name':'Acarigua' },
'AGU': { 'latitude':'21.866667', 'longitude': '-102.25', 'name':'Aguascalients' },
'AGT': { 'latitude':'-25.455556', 'longitude': '-54.843611', 'name':'Alejo Garcia' },
'AGS': { 'latitude':'33.366667', 'longitude': '-81.966667', 'name':'Bush Field' },
'AGR': { 'latitude':'27.15', 'longitude': '77.966667', 'name':'Kheria' },
'AGQ': { 'latitude':'38.6', 'longitude': '21.383333', 'name':'Agrinion' },
'AGP': { 'latitude':'36.675', 'longitude': '-4.499167', 'name':'Pablo Ruiz Picasso' },
'BWP': { 'latitude':'-3.083333', 'longitude': '141.1', 'name':'Bewani' },
'BWQ': { 'latitude':'-29.966667', 'longitude': '146.816667', 'name':'Brewarrina' },
'BWS': { 'latitude':'48.966667', 'longitude': '-122.833333', 'name':'Blaine' },
'BWT': { 'latitude':'-41.0', 'longitude': '145.733333', 'name':'Burnie Wynyard' },
'BWU': { 'latitude':'-33.916667', 'longitude': '150.983333', 'name':'Sydney Bankstown' },
'BWY': { 'latitude':'52.1', 'longitude': '1.316667', 'name':'Bentwaters St' },
'BWA': { 'latitude':'27.505833', 'longitude': '83.418889', 'name':'Bhairawa' },
'BWB': { 'latitude':'-20.8', 'longitude': '115.383333', 'name':'Barrow Island' },
'BWC': { 'latitude':'32.983333', 'longitude': '-115.516667', 'name':'Brawley' },
'BWD': { 'latitude':'31.8', 'longitude': '-98.95', 'name':'Brownwood' },
'BWE': { 'latitude':'52.319167', 'longitude': '10.556111', 'name':'Braunschweig' },
'BWF': { 'latitude':'54.116667', 'longitude': '-3.233333', 'name':'Walney Island' },
'BWG': { 'latitude':'36.966667', 'longitude': '-86.416667', 'name':'Warren County' },
'BWH': { 'latitude':'5.416667', 'longitude': '100.4', 'name':'Butterworth' },
'BWI': { 'latitude':'39.175278', 'longitude': '-76.668333', 'name':'Baltimore/Washington International Thurgood Marshall' },
'BWJ': { 'latitude':'-6.4', 'longitude': '146.9', 'name':'Bawan' },
'BWK': { 'latitude':'43.261944', 'longitude': '16.655', 'name':'Bol' },
'BWL': { 'latitude':'36.8', 'longitude': '-97.283333', 'name':'Blackwell' },
'BWM': { 'latitude':'46.133333', 'longitude': '-103.583333', 'name':'Bowman' },
'BWN': { 'latitude':'4.944167', 'longitude': '114.928333', 'name':'Bandar Seri Begwan International Airport' },
'BWO': { 'latitude':'51.866667', 'longitude': '47.75', 'name':'Balakovo' },
'TDO': { 'latitude':'6.533333', 'longitude': '-75.783333', 'name':'Winlock' },
'TDN': { 'latitude':'38.086389', 'longitude': '27.737778', 'name':'Theda Station' },
'MAQ': { 'latitude':'16.716667', 'longitude': '98.566667', 'name':'Mae Sot' },
'MAP': { 'latitude':'-10.3', 'longitude': '149.533333', 'name':'Mamai' },
'MAS': { 'latitude':'-2.016667', 'longitude': '147.0', 'name':'Momote' },
'MAR': { 'latitude':'10.68', 'longitude': '-71.660278', 'name':'La Chinita' },
'MAU': { 'latitude':'-16.433333', 'longitude': '-152.25', 'name':'Maupiti' },
'MAT': { 'latitude':'-5.8', 'longitude': '13.433333', 'name':'Matadi' },
'MAW': { 'latitude':'36.6', 'longitude': '-89.983333', 'name':'Malden' },
'MAV': { 'latitude':'8.75', 'longitude': '171.1', 'name':'Maloelap Island' },
'MAY': { 'latitude':'24.216667', 'longitude': '-77.666667', 'name':'Mangrove Cay' },
'MAX': { 'latitude':'15.6', 'longitude': '-13.316667', 'name':'Matam' },
'SNL': { 'latitude':'35.316667', 'longitude': '-96.916667', 'name':'Municipal' },
'MAZ': { 'latitude':'18.233333', 'longitude': '-67.133333', 'name':'Eugenio M De Hostos' },
'SNJ': { 'latitude':'22.085278', 'longitude': '-84.150278', 'name':'San Julian' },
'SNK': { 'latitude':'32.7', 'longitude': '-100.95', 'name':'Winston Field' },
'SNH': { 'latitude':'-28.633333', 'longitude': '151.966667', 'name':'Stanthorpe' },
'SNI': { 'latitude':'5.033333', 'longitude': '-9.064444', 'name':'R.E. Murray' },
'MAA': { 'latitude':'12.994722', 'longitude': '80.175278', 'name':'Madras International' },
'SNW': { 'latitude':'18.466667', 'longitude': '94.35', 'name':'Thandwe' },
'MAC': { 'latitude':'50.033333', 'longitude': '4.2', 'name':'Smart' },
'MAB': { 'latitude':'-5.366667', 'longitude': '-49.166667', 'name':'Maraba' },
'MAE': { 'latitude':'-13.083333', 'longitude': '49.083333', 'name':'Madera' },
'MAD': { 'latitude':'40.466667', 'longitude': '-3.566667', 'name':'Barajas' },
'MAG': { 'latitude':'-5.208333', 'longitude': '145.783333', 'name':'Madang' },
'MAF': { 'latitude':'31.9425', 'longitude': '-102.201944', 'name':'Midland International' },
'MAH': { 'latitude':'39.8625', 'longitude': '4.218611', 'name':'Mahon' },
'MAK': { 'latitude':'9.55', 'longitude': '31.816667', 'name':'Malakal' },
'MAJ': { 'latitude':'7.25', 'longitude': '171.366667', 'name':'Amata Kabua Intl' },
'MAM': { 'latitude':'25.766667', 'longitude': '-97.516667', 'name':'Matamoros' },
'MAL': { 'latitude':'-1.883333', 'longitude': '125.833333', 'name':'Mangole' },
'MAO': { 'latitude':'-3.038611', 'longitude': '-60.047222', 'name':'Eduardo Gomes Intl' },
'MAN': { 'latitude':'53.35', 'longitude': '-2.266667', 'name':'Manchester' },
'EVH': { 'latitude':'-29.1', 'longitude': '153.416667', 'name':'Evans Head' },
'EVM': { 'latitude':'47.433333', 'longitude': '-92.5', 'name':'Eveleth' },
'EVN': { 'latitude':'40.147222', 'longitude': '44.395833', 'name':'Zvartnots' },
'EVA': { 'latitude':'30.35', 'longitude': '-94.066667', 'name':'Landing Strip' },
'EVD': { 'latitude':'-18.083333', 'longitude': '134.866667', 'name':'Eva Downs' },
'EVE': { 'latitude':'68.5', 'longitude': '16.683333', 'name':'Evenes' },
'EVG': { 'latitude':'62.033333', 'longitude': '14.333333', 'name':'Sveg' },
'EVX': { 'latitude':'49.016667', 'longitude': '1.15', 'name':'Evreux' },
'EVV': { 'latitude':'38.036944', 'longitude': '-87.5325', 'name':'Evansville Regional Airport' },
'EVW': { 'latitude':'41.35', 'longitude': '-111.016667', 'name':'Evanston' },
'LSF': { 'latitude':'32.337222', 'longitude': '-84.991389', 'name':'Lawson Aaf' },
'LSD': { 'latitude':'38.083333', 'longitude': '-84.316667', 'name':'Blue Grass Station Army Heliport' },
'LSE': { 'latitude':'43.883333', 'longitude': '-91.25', 'name':'Municipal' },
'LSB': { 'latitude':'32.416667', 'longitude': '-108.666667', 'name':'Lordsburg' },
'LSC': { 'latitude':'-29.913333', 'longitude': '-71.197778', 'name':'La Serena' },
'LSA': { 'latitude':'-8.5', 'longitude': '151.083333', 'name':'Losuia' },
'LSN': { 'latitude':'37.066667', 'longitude': '-120.85', 'name':'Los Banos' },
'LSO': { 'latitude':'46.483333', 'longitude': '-1.75', 'name':'Talmont' },
'LSL': { 'latitude':'11.0', 'longitude': '-84.833333', 'name':'Los Chiles' },
'LSM': { 'latitude':'4.216667', 'longitude': '115.6', 'name':'Lawas' },
'LSJ': { 'latitude':'-5.366667', 'longitude': '147.016667', 'name':'Long Island' },
'LSH': { 'latitude':'22.966667', 'longitude': '97.75', 'name':'Lashio' },
'LSI': { 'latitude':'59.878889', 'longitude': '-1.295556', 'name':'Sumburgh' },
'LSV': { 'latitude':'36.236111', 'longitude': '-115.034167', 'name':'Nellis AFB' },
'LSW': { 'latitude':'5.216667', 'longitude': '96.933333', 'name':'Lhoksumawe' },
'LST': { 'latitude':'-41.546667', 'longitude': '147.212778', 'name':'Launceston' },
'LSU': { 'latitude':'4.55', 'longitude': '115.5', 'name':'Long Sukang' },
'LSR': { 'latitude':'65.4', 'longitude': '-167.15', 'name':'Lost River' },
'LSS': { 'latitude':'15.866667', 'longitude': '-61.583333', 'name':'Terre-de-Haut' },
'LSP': { 'latitude':'11.733333', 'longitude': '-70.2', 'name':'Josefa Camejo' },
'LSQ': { 'latitude':'-37.416667', 'longitude': '-72.35', 'name':'Los Angeles' },
'LSZ': { 'latitude':'44.95', 'longitude': '14.416667', 'name':'Losinj Arpt' },
'LSX': { 'latitude':'5.05', 'longitude': '97.316667', 'name':'Lhok Sukon' },
'LSY': { 'latitude':'-28.833333', 'longitude': '153.266667', 'name':'Lismore' },
'KKY': { 'latitude':'52.65', 'longitude': '-7.25', 'name':'Kilkenny' },
'KKX': { 'latitude':'28.433333', 'longitude': '130.008333', 'name':'Kikaiga Shima' },
'KKZ': { 'latitude':'11.633333', 'longitude': '102.966667', 'name':'Koh Kong' },
'KKU': { 'latitude':'58.816667', 'longitude': '-158.55', 'name':'Ekuk' },
'KKT': { 'latitude':'40.766667', 'longitude': '-87.45', 'name':'Kentland' },
'KKW': { 'latitude':'-5.416667', 'longitude': '18.95', 'name':'Kikwit' },
'KKP': { 'latitude':'-15.583333', 'longitude': '143.95', 'name':'Koolburra' },
'KKR': { 'latitude':'-15.75', 'longitude': '-146.7', 'name':'Kaukura Atoll' },
'KKM': { 'latitude':'14.8', 'longitude': '100.616667', 'name':'Lop Buri' },
'KKL': { 'latitude':'40.05', 'longitude': '26.966667', 'name':'Karluk Lake SPB' },
'KKO': { 'latitude':'-35.45', 'longitude': '173.816667', 'name':'Kaikohe' },
'KKN': { 'latitude':'69.716667', 'longitude': '29.9', 'name':'Hoeybuktmoen' },
'KKI': { 'latitude':'60.916667', 'longitude': '-161.433333', 'name':'Spb' },
'KKH': { 'latitude':'59.966667', 'longitude': '-162.75', 'name':'Kongiganak' },
'KKK': { 'latitude':'64.416667', 'longitude': '-156.833333', 'name':'Kalakaket AFS' },
'KKJ': { 'latitude':'33.845556', 'longitude': '131.035', 'name':'Kita Kyushu' },
'KKE': { 'latitude':'-35.262778', 'longitude': '173.911944', 'name':'Kerikeri/Bay of Islands' },
'KKD': { 'latitude':'-8.883333', 'longitude': '147.733333', 'name':'Kokoda' },
'KKG': { 'latitude':'5.216667', 'longitude': '-59.0', 'name':'Konawaruk' },
'KKA': { 'latitude':'64.916667', 'longitude': '-161.133333', 'name':'Koyuk' },
'KKC': { 'latitude':'16.45', 'longitude': '102.833333', 'name':'Khon Kaen' },
'KKB': { 'latitude':'58.183333', 'longitude': '-152.35', 'name':'SPB' },
'CTT': { 'latitude':'43.255556', 'longitude': '5.788889', 'name':'Le Castellet' },
'CTU': { 'latitude':'30.578611', 'longitude': '103.947222', 'name':'Shuangliu' },
'CTW': { 'latitude':'34.733333', 'longitude': '-112.033333', 'name':'Cottonwood' },
'CTP': { 'latitude':'-1.25', 'longitude': '-46.016667', 'name':'Carutapera' },
'CTQ': { 'latitude':'-18.833333', 'longitude': '-50.133333', 'name':'Do Palmar' },
'CTR': { 'latitude':'-17.583333', 'longitude': '131.0', 'name':'Cattle Creek' },
'CTS': { 'latitude':'42.8', 'longitude': '141.666667', 'name':'New Chitose Airport' },
'CTX': { 'latitude':'36.5', 'longitude': '33.616667', 'name':'Cortland' },
'CTY': { 'latitude':'29.65', 'longitude': '-83.116667', 'name':'Cross City' },
'CTZ': { 'latitude':'35.0', 'longitude': '-78.333333', 'name':'Sampson County' },
'CTD': { 'latitude':'7.983333', 'longitude': '-80.416667', 'name':'Chitre' },
'CTE': { 'latitude':'9.316667', 'longitude': '-79.1', 'name':'Carti' },
'CTF': { 'latitude':'14.166667', 'longitude': '-90.15', 'name':'Coatepeque Airport' },
'CTG': { 'latitude':'10.45', 'longitude': '-75.516667', 'name':'Rafael Nunez' },
'CTA': { 'latitude':'37.466667', 'longitude': '15.066667', 'name':'Fontanarossa' },
'CTB': { 'latitude':'48.633333', 'longitude': '-112.333333', 'name':'Cut Bank' },
'CTC': { 'latitude':'-28.448333', 'longitude': '-65.779722', 'name':'Catamarca' },
'CTL': { 'latitude':'-26.416667', 'longitude': '146.266667', 'name':'Charleville' },
'CTM': { 'latitude':'18.483333', 'longitude': '-88.316667', 'name':'Chetumal' },
'CTN': { 'latitude':'-15.45', 'longitude': '145.183333', 'name':'Cooktown' },
'CTO': { 'latitude':'40.916667', 'longitude': '-72.75', 'name':'Peconic River' },
'CTH': { 'latitude':'39.966667', 'longitude': '-75.816667', 'name':'Chestercounty Carlson' },
'CTI': { 'latitude':'-15.166667', 'longitude': '19.166667', 'name':'Cuito Cuanavale' },
'CTK': { 'latitude':'43.3', 'longitude': '-96.583333', 'name':'Canton' },
'LOM': { 'latitude':'22.056944', 'longitude': '-104.070833', 'name':'Francisco P. V. Y R.' },
'ORZ': { 'latitude':'18.066667', 'longitude': '-88.558333', 'name':'Orange Walk' },
'ORX': { 'latitude':'-1.666667', 'longitude': '-55.833333', 'name':'Oriximina' },
'ORY': { 'latitude':'48.716667', 'longitude': '2.383333', 'name':'Orly' },
'ORV': { 'latitude':'66.833333', 'longitude': '-161.033333', 'name':'Curtis Memorial' },
'ORW': { 'latitude':'25.274722', 'longitude': '64.585833', 'name':'Ormara' },
'ORT': { 'latitude':'62.95', 'longitude': '-141.95', 'name':'Northway' },
'ORU': { 'latitude':'-17.95', 'longitude': '-67.1', 'name':'Oruro' },
'ORR': { 'latitude':'-35.033333', 'longitude': '137.6', 'name':'Yorketown' },
'ORS': { 'latitude':'-18.633333', 'longitude': '146.483333', 'name':'Waterport' },
'ORP': { 'latitude':'-21.133333', 'longitude': '25.65', 'name':'Orapa' },
'ORQ': { 'latitude':'41.116667', 'longitude': '-73.45', 'name':'Heliport' },
'ORN': { 'latitude':'35.616667', 'longitude': '-0.616667', 'name':'Es Senia' },
'ORO': { 'latitude':'15.125', 'longitude': '-87.141667', 'name':'Yoro' },
'ORL': { 'latitude':'28.533333', 'longitude': '-81.35', 'name':'Orlando Executive' },
'ORM': { 'latitude':'52.3', 'longitude': '-0.783333', 'name':'Northampton' },
'ORJ': { 'latitude':'4.716667', 'longitude': '-60.033333', 'name':'Orinduik' },
'ORK': { 'latitude':'51.847222', 'longitude': '-8.497222', 'name':'Cork' },
'ORH': { 'latitude':'42.267222', 'longitude': '-71.875833', 'name':'Worcester Regional Airport' },
'ORI': { 'latitude':'57.883333', 'longitude': '-152.85', 'name':'Port Lions SPB' },
'ORF': { 'latitude':'36.9', 'longitude': '-76.2', 'name':'Norfolk International Airport' },
'ORG': { 'latitude':'5.491667', 'longitude': '-55.183333', 'name':'Zorg En Hoop' },
'ORD': { 'latitude':'41.978611', 'longitude': '-87.904722', 'name':'Chicago O\'hare International' },
'ORE': { 'latitude':'47.916667', 'longitude': '1.9', 'name':'Orleans' },
'ORB': { 'latitude':'59.25', 'longitude': '15.233333', 'name':'Orebro-bofors' },
'ORC': { 'latitude':'4.792222', 'longitude': '-71.356389', 'name':'Orocue' },
'ORA': { 'latitude':'-23.15', 'longitude': '-64.316667', 'name':'Oran' },
'LOU': { 'latitude':'38.227778', 'longitude': '-85.663611', 'name':'Bowman Field Airport' },
'MJF': { 'latitude':'65.783333', 'longitude': '13.216667', 'name':'Kjaerstad' },
'WBO': { 'latitude':'-21.6', 'longitude': '45.133333', 'name':'Beroroha' },
'LOZ': { 'latitude':'37.083333', 'longitude': '-84.066667', 'name':'Corbin-London' },
'GIT': { 'latitude':'-2.866667', 'longitude': '32.166667', 'name':'Geita' },
'GIR': { 'latitude':'4.283333', 'longitude': '-74.8', 'name':'Girardot' },
'LOY': { 'latitude':'2.7525', 'longitude': '36.717222', 'name':'Loyangalani' },
'MJI': { 'latitude':'32.9', 'longitude': '13.283333', 'name':'Mitiga' },
'MJT': { 'latitude':'39.056667', 'longitude': '26.598333', 'name':'Mytilene International Airport' },
'GIF': { 'latitude':'28.066667', 'longitude': '-81.75', 'name':'Gilbert Field' },
'MJW': { 'latitude':'-21.116667', 'longitude': '32.383333', 'name':'Mahenye' },
'MJP': { 'latitude':'-34.233333', 'longitude': '116.15', 'name':'Manjimup' },
'MJQ': { 'latitude':'43.616667', 'longitude': '-95.016667', 'name':'Jackson' },
'SNV': { 'latitude':'4.6', 'longitude': '-61.1', 'name':'Santa Elena' },
'MJZ': { 'latitude':'62.533333', 'longitude': '114.033333', 'name':'Mirnyj' },
'ZIV': { 'latitude':'57.083333', 'longitude': '-4.666667', 'name':'ScotRail' },
'ZIU': { 'latitude':'50.770833', 'longitude': '6.105278', 'name':'Railway' },
'WBI': { 'latitude':'-30.783333', 'longitude': '121.483333', 'name':'Broker Inn' },
'ZIP': { 'latitude':'38.466667', 'longitude': '14.95', 'name':'Harbour' },
'NPL': { 'latitude':'-39.033333', 'longitude': '174.183333', 'name':'New Plymouth' },
'ZIY': { 'latitude':'23.216667', 'longitude': '113.433333', 'name':'Lianhuashan Port' },
'ZIF': { 'latitude':'45.416667', 'longitude': '-75.7', 'name':'Fallowfield Railway' },
'ZIG': { 'latitude':'12.55', 'longitude': '-16.283333', 'name':'Ziguinchor' },
'ZIE': { 'latitude':'38.4', 'longitude': '14.966667', 'name':'Harbour' },
'ZIC': { 'latitude':'-38.216667', 'longitude': '-72.333333', 'name':'Victoria' },
'ZIH': { 'latitude':'17.633333', 'longitude': '-101.55', 'name':'Internacional' },
'PVE': { 'latitude':'9.0', 'longitude': '-81.0', 'name':'El Porvenir' },
'NPG': { 'latitude':'-6.133333', 'longitude': '143.366667', 'name':'Nipa' },
'YSK': { 'latitude':'56.55', 'longitude': '-79.216667', 'name':'Sanikiluaq' },
'YSJ': { 'latitude':'45.316667', 'longitude': '-65.883333', 'name':'Saint John' },
'YSI': { 'latitude':'45.266667', 'longitude': '-80.0', 'name':'Sans Souci' },
'SNU': { 'latitude':'22.492222', 'longitude': '-79.943611', 'name':'Abel Santa Maria' },
'YSO': { 'latitude':'54.916667', 'longitude': '-59.766667', 'name':'Postville' },
'YSN': { 'latitude':'50.683333', 'longitude': '-119.233333', 'name':'Salmon Arm' },
'YSM': { 'latitude':'60.016667', 'longitude': '-111.966667', 'name':'Fort Smith' },
'YSL': { 'latitude':'47.183333', 'longitude': '-67.9', 'name':'St Leonard' },
'YSC': { 'latitude':'45.433333', 'longitude': '-71.683333', 'name':'Sherbrooke' },
'YSB': { 'latitude':'46.616667', 'longitude': '-80.8', 'name':'Sudbury' },
'YSA': { 'latitude':'43.916667', 'longitude': '-59.833333', 'name':'Sable Island' },
'YSG': { 'latitude':'62.418611', 'longitude': '-110.075557', 'name':'Lutselke/Snowdrift' },
'YSF': { 'latitude':'59.25', 'longitude': '-105.833333', 'name':'Stony Rapids' },
'YSE': { 'latitude':'49.781667', 'longitude': '-123.161944', 'name':'Squamish' },
'YSD': { 'latitude':'50.2', 'longitude': '-111.166667', 'name':'Suffield' },
'YSZ': { 'latitude':'50.05', 'longitude': '-124.916667', 'name':'Squirrel Cove' },
'YSY': { 'latitude':'72.0', 'longitude': '-125.0', 'name':'Sachs Harbour' },
'YSX': { 'latitude':'52.133333', 'longitude': '-128.066667', 'name':'Shearwater' },
'YSS': { 'latitude':'54.155556', 'longitude': '-1.644444', 'name':'Slate Island' },
'YSR': { 'latitude':'63.066667', 'longitude': '-71.416667', 'name':'Nanisivik' },
'YSQ': { 'latitude':'59.45', 'longitude': '-1.783333', 'name':'Spring Island' },
'YSP': { 'latitude':'48.75', 'longitude': '-86.35', 'name':'Marathon' },
'YSV': { 'latitude':'58.466667', 'longitude': '-62.633333', 'name':'Saglek' },
'YSU': { 'latitude':'46.433333', 'longitude': '-63.833333', 'name':'Summerside' },
'YST': { 'latitude':'53.833333', 'longitude': '-94.833333', 'name':'Ste Therese Point' },
'NQY': { 'latitude':'50.43936', 'longitude': '-5.00633', 'name':'Newquay' },
'AHZ': { 'latitude':'45.083333', 'longitude': '6.083333', 'name':'Alpe D Huez' },
'SNP': { 'latitude':'57.166667', 'longitude': '-170.216667', 'name':'Saint Paul Island' },
'XCH': { 'latitude':'-10.450556', 'longitude': '105.690278', 'name':'Christmas Island' },
'XCN': { 'latitude':'12.0', 'longitude': '120.2', 'name':'Coron Airport' },
'XCO': { 'latitude':'-38.333333', 'longitude': '143.583333', 'name':'Colac' },
'XCL': { 'latitude':'58.383333', 'longitude': '-109.516667', 'name':'Cluff Lake' },
'XCM': { 'latitude':'42.4', 'longitude': '-82.183333', 'name':'Chatham' },
'XCR': { 'latitude':'48.7678', 'longitude': '4.2011', 'name':'Paris-Vatry' },
'SNQ': { 'latitude':'30.5', 'longitude': '-116.0', 'name':'San Quintin' },
'TSN': { 'latitude':'39.142222', 'longitude': '117.176667', 'name':'Tianjin Binhai International' },
'WYS': { 'latitude':'44.683333', 'longitude': '-111.116667', 'name':'Yellowstone' },
'TSO': { 'latitude':'49.95', 'longitude': '-6.316667', 'name':'Tresco' },
'TSL': { 'latitude':'21.533333', 'longitude': '-98.108333', 'name':'Tamuin' },
'WYE': { 'latitude':'8.616667', 'longitude': '-11.05', 'name':'Yengema' },
'WYB': { 'latitude':'55.916667', 'longitude': '-131.8', 'name':'SPB' },
'WYA': { 'latitude':'-33.05', 'longitude': '137.516667', 'name':'Whyalla' },
'TSJ': { 'latitude':'34.283333', 'longitude': '129.316667', 'name':'Tsushima' },
'TSH': { 'latitude':'-6.438333', 'longitude': '20.794722', 'name':'Tshikapa' },
'TSG': { 'latitude':'45.228056', 'longitude': '18.073333', 'name':'Intermediate' },
'TSD': { 'latitude':'-8.05', 'longitude': '24.516667', 'name':'Tshipise' },
'TSE': { 'latitude':'51.167222', 'longitude': '71.466944', 'name':'Astana' },
'TSA': { 'latitude':'25.069722', 'longitude': '121.5525', 'name':'Taipei Songshan' },
'TUX': { 'latitude':'51.783611', 'longitude': '-4.109722', 'name':'Tumbler Ridge' },
'TUY': { 'latitude':'20.216667', 'longitude': '-87.466667', 'name':'Tulum' },
'TUZ': { 'latitude':'-0.183333', 'longitude': '-50.05', 'name':'Tucuma' },
'VMI': { 'latitude':'-26.033333', 'longitude': '-57.25', 'name':'INC' },
'TUP': { 'latitude':'34.268056', 'longitude': '-88.77', 'name':'Lemons Municipal' },
'TUQ': { 'latitude':'13.066667', 'longitude': '-3.066667', 'name':'Tougan' },
'TUR': { 'latitude':'-3.7', 'longitude': '-49.7', 'name':'Tucurui' },
'TUS': { 'latitude':'32.116111', 'longitude': '-110.941111', 'name':'Tucson International Airport' },
'TUT': { 'latitude':'-5.85', 'longitude': '145.916667', 'name':'Tauta' },
'TUU': { 'latitude':'28.383333', 'longitude': '36.583333', 'name':'Tabuk' },
'TUV': { 'latitude':'9.068611', 'longitude': '-62.049167', 'name':'Tucupita' },
'TUW': { 'latitude':'8.833333', 'longitude': '-77.666667', 'name':'Tubala' },
'TUH': { 'latitude':'52.777222', 'longitude': '-8.404167', 'name':'Arnold AFS' },
'TUI': { 'latitude':'31.695', 'longitude': '38.631667', 'name':'Turaif' },
'TUJ': { 'latitude':'9.55', 'longitude': '38.683333', 'name':'Tum' },
'TUK': { 'latitude':'25.983333', 'longitude': '63.066667', 'name':'Turbat' },
'TUL': { 'latitude':'36.198333', 'longitude': '-95.888056', 'name':'Tulsa International' },
'TUM': { 'latitude':'-35.3', 'longitude': '148.216667', 'name':'Tumut' },
'TUN': { 'latitude':'36.853611', 'longitude': '10.228611', 'name':'Carthage' },
'TUO': { 'latitude':'-38.683333', 'longitude': '176.083333', 'name':'Taupo' },
'TUA': { 'latitude':'-0.8', 'longitude': '-77.716667', 'name':'Tulcan' },
'TUB': { 'latitude':'-23.35', 'longitude': '-149.466667', 'name':'Tubuai' },
'TUC': { 'latitude':'-26.816667', 'longitude': '-65.216667', 'name':'Benj Matienzo' },
'TUD': { 'latitude':'13.5', 'longitude': '-13.75', 'name':'Tambacounda' },
'TUE': { 'latitude':'9.5725', 'longitude': '-79.487222', 'name':'Tupile' },
'TUF': { 'latitude':'47.418056', 'longitude': '0.723056', 'name':'St Symphorien' },
'TUG': { 'latitude':'17.616667', 'longitude': '121.75', 'name':'Tuguegarao' },
'WYN': { 'latitude':'-15.516667', 'longitude': '128.15', 'name':'Wyndham' },
'TST': { 'latitude':'7.55', 'longitude': '99.6', 'name':'Trang' },
'TSU': { 'latitude':'-1.483333', 'longitude': '174.933333', 'name':'Tabiteuea South' },
'FYN': { 'latitude':'45.0', 'longitude': '90.008333', 'name':'Fuyun' },
'FYM': { 'latitude':'35.15', 'longitude': '-86.583333', 'name':'Municipal' },
'FYV': { 'latitude':'36.0', 'longitude': '-94.166667', 'name':'Municipal' },
'FYT': { 'latitude':'17.933333', 'longitude': '19.133333', 'name':'Faya' },
'FYU': { 'latitude':'66.566667', 'longitude': '-145.266667', 'name':'Fort Yukon' },
'RJB': { 'latitude':'26.516667', 'longitude': '86.733333', 'name':'Rajbiraj' },
'RJA': { 'latitude':'16.983333', 'longitude': '81.783333', 'name':'Rajahmundry' },
'TBQ': { 'latitude':'12.3', 'longitude': '22.75', 'name':'Tarabo' },
'QSG': { 'latitude':'54.966667', 'longitude': '9.783333', 'name':'Sonderborg' },
'QSF': { 'latitude':'36.191389', 'longitude': '5.409444', 'name':'Setif' },
'QSR': { 'latitude':'40.676472', 'longitude': '14.772491', 'name':'Salerno Costa d\'Amalfi Airport' },
'CKE': { 'latitude':'39.033333', 'longitude': '-122.833333', 'name':'Clear Lake' },
'CKD': { 'latitude':'61.866667', 'longitude': '-158.133333', 'name':'Crooked Creek' },
'CKG': { 'latitude':'29.719167', 'longitude': '106.641667', 'name':'Chongqing Jiangbei International' },
'PAS': { 'latitude':'37.066667', 'longitude': '25.133333', 'name':'Paros' },
'CKA': { 'latitude':'26.283333', 'longitude': '-77.033333', 'name':'Kegelman Af' },
'CKC': { 'latitude':'49.416667', 'longitude': '32.0', 'name':'Cherkassy' },
'CKB': { 'latitude':'39.3', 'longitude': '-80.233333', 'name':'Benedum' },
'CKM': { 'latitude':'34.299722', 'longitude': '-90.512222', 'name':'Fletcher Field' },
'CKL': { 'latitude':'51.75', 'longitude': '55.383333', 'name':'Chkalovsky' },
'CKO': { 'latitude':'-23.152222', 'longitude': '-50.602222', 'name':'Cornelio Procopio' },
'CKN': { 'latitude':'47.85', 'longitude': '-96.616667', 'name':'Municipal' },
'CKI': { 'latitude':'-11.083333', 'longitude': '132.5', 'name':'Croker Island' },
'CKH': { 'latitude':'70.633333', 'longitude': '147.883333', 'name':'Chokurdah' },
'CKK': { 'latitude':'36.283333', 'longitude': '-91.5', 'name':'Cherokee' },
'CKU': { 'latitude':'9.633333', 'longitude': '-74.783333', 'name':'City' },
'CKT': { 'latitude':'35.994722', 'longitude': '51.307778', 'name':'Sarakhs' },
'PAB': { 'latitude':'22.5', 'longitude': '82.166667', 'name':'Bilaspur' },
'CKV': { 'latitude':'36.621944', 'longitude': '-87.415', 'name':'Outlaw Field' },
'PAD': { 'latitude':'51.716667', 'longitude': '8.75', 'name':'Paderborn/lippstadt' },
'PAE': { 'latitude':'47.919444', 'longitude': '-122.283611', 'name':'Snohomish County' },
'CKS': { 'latitude':'-6.0', 'longitude': '-51.333333', 'name':'Carajas' },
'CKR': { 'latitude':'48.6', 'longitude': '-123.0', 'name':'Crane Island' },
'PAH': { 'latitude':'37.060278', 'longitude': '-88.773056', 'name':'Barkley Regional' },
'PAI': { 'latitude':'12.85', 'longitude': '102.583333', 'name':'Pailin' },
'PAJ': { 'latitude':'33.913889', 'longitude': '70.083333', 'name':'Para Chinar' },
'PAK': { 'latitude':'21.916667', 'longitude': '-159.583333', 'name':'Port Allen' },
'CKY': { 'latitude':'9.566667', 'longitude': '-13.616667', 'name':'Conakry' },
'CKX': { 'latitude':'64.083333', 'longitude': '-141.916667', 'name':'Chicken' },
'PAN': { 'latitude':'6.783333', 'longitude': '101.166667', 'name':'Pattani' },
'CKZ': { 'latitude':'40.133333', 'longitude': '26.433333', 'name':'Canakkale' },
'DCN': { 'latitude':'-17.5672', 'longitude': '123.8172', 'name':'Derby Curtin' },
'DCM': { 'latitude':'43.555833', 'longitude': '2.285556', 'name':'Mazamet' },
'DCK': { 'latitude':'66.933333', 'longitude': '-156.9', 'name':'Dahl Creek Arpt' },
'DCI': { 'latitude':'39.316667', 'longitude': '8.966667', 'name':'Rafsu Decimomannu' },
'DCF': { 'latitude':'15.336667', 'longitude': '-61.392222', 'name':'Cane Field' },
'DCA': { 'latitude':'38.851944', 'longitude': '-77.037778', 'name':'Ronald Reagan Washington National Airport' },
'DCT': { 'latitude':'22.183333', 'longitude': '-75.733333', 'name':'Duncan Town' },
'DCR': { 'latitude':'40.833333', 'longitude': '-84.933333', 'name':'Decatur Hi-Way' },
'OMC': { 'latitude':'11.05', 'longitude': '124.566667', 'name':'Ormoc' },
'OMB': { 'latitude':'-1.6', 'longitude': '9.266667', 'name':'Omboue' },
'RAS': { 'latitude':'37.333333', 'longitude': '49.6', 'name':'Rasht' },
'UJE': { 'latitude':'9.083333', 'longitude': '165.666667', 'name':'Ujae Island' },
'OMF': { 'latitude':'32.333333', 'longitude': '36.233333', 'name':'King Hussein' },
'OIM': { 'latitude':'34.783333', 'longitude': '139.366667', 'name':'Oshima' },
'OIL': { 'latitude':'41.434444', 'longitude': '-79.830833', 'name':'Splane Memorial' },
'OME': { 'latitude':'64.516667', 'longitude': '-165.433333', 'name':'Nome' },
'IHR': { 'latitude':'27.236944', 'longitude': '60.724167', 'name':'Iran Shahr' },
'OMD': { 'latitude':'-28.583333', 'longitude': '16.45', 'name':'Oranjemund' },
'OIC': { 'latitude':'42.983333', 'longitude': '-80.6', 'name':'Eaton' },
'OIA': { 'latitude':'41.416667', 'longitude': '-8.016667', 'name':'Ourilandia' },
'IHU': { 'latitude':'-7.9', 'longitude': '145.383333', 'name':'Ihu' },
'IHN': { 'latitude':'15.433333', 'longitude': '51.7', 'name':'Qishn' },
'IHO': { 'latitude':'-22.401389', 'longitude': '46.133333', 'name':'Ihosy' },
'IHC': { 'latitude':'-26.0', 'longitude': '32.933333', 'name':'Inhaca' },
'IHA': { 'latitude':'33.95', 'longitude': '133.3', 'name':'Niihama' },
'OIR': { 'latitude':'42.166667', 'longitude': '139.516667', 'name':'Okushiri' },
'GBF': { 'latitude':'-6.583333', 'longitude': '144.666667', 'name':'Negarbo' },
'AEP': { 'latitude':'-34.559167', 'longitude': '-58.415556', 'name':'Arpt. Jorge Newbery' },
'GBD': { 'latitude':'38.35', 'longitude': '-98.866667', 'name':'Great Bend' },
'AER': { 'latitude':'43.45', 'longitude': '39.933333', 'name':'Adler/Sochi' },
'GBB': { 'latitude':'26.15', 'longitude': '-7.35', 'name':'Gara Djebilet' },
'GBC': { 'latitude':'-6.1', 'longitude': '141.733333', 'name':'Gasuke' },
'GBA': { 'latitude':'-16.05', 'longitude': '167.35', 'name':'Big Bay' },
'AEY': { 'latitude':'65.65', 'longitude': '-18.083333', 'name':'Akureyri' },
'GBO': { 'latitude':'39.186111', 'longitude': '-76.683333', 'name':'Baltimore Greenbelt T' },
'GBL': { 'latitude':'-11.666667', 'longitude': '133.416667', 'name':'Goulburn Island' },
'GBM': { 'latitude':'3.333333', 'longitude': '42.183333', 'name':'Garbaharey' },
'GBJ': { 'latitude':'15.366667', 'longitude': '-61.266667', 'name':'Les Bases' },
'GBK': { 'latitude':'7.800278', 'longitude': '-12.366667', 'name':'Gbangbatok' },
'GBH': { 'latitude':'68.466667', 'longitude': '-149.483333', 'name':'Galbraith Lake' },
'GBI': { 'latitude':'26.631944', 'longitude': '-78.359167', 'name':'Auxiliary Airfield' },
'AEA': { 'latitude':'0.483333', 'longitude': '173.85', 'name':'Abemama Atoll' },
'GBT': { 'latitude':'36.909444', 'longitude': '54.401389', 'name':'Gorgan' },
'AEB': { 'latitude':'23.7172', 'longitude': '106.9506', 'name':'Baise' },
'GBR': { 'latitude':'42.184167', 'longitude': '-73.403333', 'name':'Walter J. Koladza Airport' },
'GBS': { 'latitude':'-36.183333', 'longitude': '175.333333', 'name':'Port Fitzroy' },
'AEG': { 'latitude':'1.383333', 'longitude': '99.45', 'name':'Aek Godang' },
'GBQ': { 'latitude':'26.257222', 'longitude': '50.611944', 'name':'Muharraq' },
'AEI': { 'latitude':'36.183333', 'longitude': '-5.45', 'name':'Algeciras' },
'AEH': { 'latitude':'13.85', 'longitude': '20.85', 'name':'Abecher' },
'AEK': { 'latitude':'-7.366667', 'longitude': '146.283333', 'name':'Aseki' },
'OML': { 'latitude':'-6.183333', 'longitude': '144.966667', 'name':'Omkalai' },
'GBZ': { 'latitude':'-36.166667', 'longitude': '175.333333', 'name':'Great Barrier Island' },
'AEL': { 'latitude':'43.683333', 'longitude': '-93.366667', 'name':'Albert Lea' },
'AEO': { 'latitude':'16.7', 'longitude': '-9.65', 'name':'Aioun El Atrouss' },
'TBV': { 'latitude':'-54.15', 'longitude': '-72.4', 'name':'Tabal' },
'BUZ': { 'latitude':'28.95', 'longitude': '50.816667', 'name':'Bushehr' },
'BUX': { 'latitude':'1.566667', 'longitude': '30.216667', 'name':'Bunia' },
'BUY': { 'latitude':'-33.378333', 'longitude': '115.676667', 'name':'Bunbury' },
'BUR': { 'latitude':'34.2', 'longitude': '-118.35', 'name':'Bob Hope' },
'BUS': { 'latitude':'41.610278', 'longitude': '41.599722', 'name':'Batum' },
'BUP': { 'latitude':'30.166667', 'longitude': '74.966667', 'name':'Bhatinda' },
'BUQ': { 'latitude':'-20.016667', 'longitude': '28.633333', 'name':'Bulawayo' },
'BUV': { 'latitude':'-30.333333', 'longitude': '-57.083333', 'name':'Bella Union' },
'BUW': { 'latitude':'-5.466667', 'longitude': '122.633333', 'name':'Baubau' },
'BUT': { 'latitude':'53.416667', 'longitude': '-2.583333', 'name':'Burtonwood' },
'BUU': { 'latitude':'6.266667', 'longitude': '-7.05', 'name':'Buyo' },
'BUJ': { 'latitude':'35.3325', 'longitude': '4.206389', 'name':'Ain Eddis' },
'BUK': { 'latitude':'15.833333', 'longitude': '43.766667', 'name':'Albuq' },
'BUI': { 'latitude':'-3.716667', 'longitude': '138.65', 'name':'Bokondini' },
'BUN': { 'latitude':'3.833333', 'longitude': '-77.0', 'name':'Buenaventura' },
'BUO': { 'latitude':'9.516667', 'longitude': '45.566667', 'name':'Burao' },
'BUL': { 'latitude':'-7.2', 'longitude': '146.65', 'name':'Bulolo' },
'BUM': { 'latitude':'38.25', 'longitude': '-94.316667', 'name':'Butler' },
'BUB': { 'latitude':'41.783333', 'longitude': '-99.133333', 'name':'Municipal' },
'BUC': { 'latitude':'-17.75', 'longitude': '139.533333', 'name':'Burketown' },
'BUA': { 'latitude':'-5.42222', 'longitude': '154.6725', 'name':'Buka' },
'BUF': { 'latitude':'42.940556', 'longitude': '-78.732222', 'name':'Buffalo Niagara International' },
'BUG': { 'latitude':'-12.608889', 'longitude': '13.403611', 'name':'Gen V Deslandes' },
'BUD': { 'latitude':'47.436667', 'longitude': '19.255556', 'name':'Ferihegy' },
'MOZ': { 'latitude':'-17.5', 'longitude': '-149.833333', 'name':'Temae' },
'MOY': { 'latitude':'4.916667', 'longitude': '-72.85', 'name':'Monterrey' },
'MOX': { 'latitude':'-16.166389', 'longitude': '38.721944', 'name':'Municipal' },
'MOS': { 'latitude':'64.7', 'longitude': '-162.05', 'name':'Intermediate' },
'MOR': { 'latitude':'36.183333', 'longitude': '-83.366667', 'name':'Moore-Murrell' },
'MOQ': { 'latitude':'-20.283333', 'longitude': '44.316667', 'name':'Morondava' },
'MOP': { 'latitude':'43.616667', 'longitude': '-84.733333', 'name':'Municipal' },
'MOV': { 'latitude':'-22.116667', 'longitude': '149.533333', 'name':'Moranbah' },
'MOU': { 'latitude':'62.083333', 'longitude': '-163.733333', 'name':'Mountain Village' },
'MOT': { 'latitude':'48.266667', 'longitude': '-101.283333', 'name':'International' },
'MOK': { 'latitude':'8.45', 'longitude': '-6.866667', 'name':'Mankono' },
'MOJ': { 'latitude':'5.6', 'longitude': '-54.4', 'name':'Moengo' },
'MOI': { 'latitude':'-19.816667', 'longitude': '-157.716667', 'name':'Mitiaro Island' },
'MOH': { 'latitude':'27.483333', 'longitude': '95.016667', 'name':'Mohanbari' },
'MOO': { 'latitude':'-28.133333', 'longitude': '140.233333', 'name':'Moomba' },
'MON': { 'latitude':'-43.783333', 'longitude': '170.133333', 'name':'Mount Cook Airport' },
'MOM': { 'latitude':'17.75', 'longitude': '-12.5', 'name':'Moudjeria' },
'MOL': { 'latitude':'62.744722', 'longitude': '7.2625', 'name':'Aro' },
'MOC': { 'latitude':'-16.716667', 'longitude': '-43.816667', 'name':'Montes Claros' },
'MOB': { 'latitude':'30.691111', 'longitude': '-88.242778', 'name':'Mobile Regional Airport' },
'MOA': { 'latitude':'20.5', 'longitude': '-74.883333', 'name':'Orestes Acosta' },
'MOG': { 'latitude':'20.516667', 'longitude': '99.266667', 'name':'Mong Hsat' },
'MOF': { 'latitude':'-8.633333', 'longitude': '122.25', 'name':'Waioti' },
'MOE': { 'latitude':'23.1', 'longitude': '96.65', 'name':'Momeik' },
'MOD': { 'latitude':'37.625833', 'longitude': '-120.954444', 'name':'Municipal' },
'KMG': { 'latitude':'24.9925', 'longitude': '102.743611', 'name':'Kunming' },
'KMF': { 'latitude':'-7.25', 'longitude': '145.533333', 'name':'Kamina' },
'KME': { 'latitude':'-2.45', 'longitude': '28.95', 'name':'Kamembe' },
'KMD': { 'latitude':'-1.666667', 'longitude': '10.416667', 'name':'Mandji' },
'KMC': { 'latitude':'27.900833', 'longitude': '45.528056', 'name':'King Khalid Military' },
'KMB': { 'latitude':'-5.5', 'longitude': '144.633333', 'name':'Koinambe' },
'KMA': { 'latitude':'-7.966667', 'longitude': '145.766667', 'name':'Kerema' },
'KMO': { 'latitude':'58.966667', 'longitude': '-159.05', 'name':'Manokotak SPB' },
'KMN': { 'latitude':'-8.641111', 'longitude': '25.25', 'name':'Kamina' },
'KMM': { 'latitude':'-7.966667', 'longitude': '138.9', 'name':'Kimam' },
'KML': { 'latitude':'-19.5', 'longitude': '140.083333', 'name':'Kamileroi' },
'KMK': { 'latitude':'-3.483333', 'longitude': '12.616667', 'name':'Makabana' },
'KMJ': { 'latitude':'32.8', 'longitude': '130.766667', 'name':'Kumamoto' },
'KMI': { 'latitude':'31.866667', 'longitude': '131.45', 'name':'Miyazaki' },
'KMH': { 'latitude':'-27.466667', 'longitude': '23.466667', 'name':'Kuruman' },
'ETB': { 'latitude':'43.416667', 'longitude': '-88.183333', 'name':'West Bend' },
'KMV': { 'latitude':'23.183333', 'longitude': '94.05', 'name':'Kalemyo' },
'KMU': { 'latitude':'-0.416667', 'longitude': '42.841667', 'name':'Kismayu' },
'KMT': { 'latitude':'10.633333', 'longitude': '104.166667', 'name':'Kampot' },
'KMS': { 'latitude':'6.716667', 'longitude': '-1.583333', 'name':'Kumasi' },
'KMR': { 'latitude':'-6.5', 'longitude': '144.833333', 'name':'Karimui' },
'KMQ': { 'latitude':'36.383333', 'longitude': '136.416667', 'name':'Komatsu' },
'ETE': { 'latitude':'12.933333', 'longitude': '36.166667', 'name':'Genda Wuha' },
'ETH': { 'latitude':'29.55', 'longitude': '34.95', 'name':'Eilat' },
'ETN': { 'latitude':'32.416667', 'longitude': '-98.8', 'name':'Municipal' },
'KMZ': { 'latitude':'-14.8', 'longitude': '24.783333', 'name':'Kaoma' },
'KMY': { 'latitude':'57.0', 'longitude': '-154.166667', 'name':'Moser Bay' },
'KMX': { 'latitude':'18.3', 'longitude': '42.8', 'name':'Khamis Mushait' },
'QNY': { 'latitude':'40.733889', 'longitude': '-73.972778', 'name':'Marine Air Terminal' },
'GAP': { 'latitude':'-6.05', 'longitude': '145.966667', 'name':'Gusap' },
'CVT': { 'latitude':'52.369722', 'longitude': '-1.479722', 'name':'West Midlands International' },
'CVU': { 'latitude':'39.7', 'longitude': '-31.1', 'name':'Corvo Island' },
'CVR': { 'latitude':'34.016667', 'longitude': '-118.4', 'name':'Hughes' },
'CVS': { 'latitude':'19.15', 'longitude': '-72.55', 'name':'Cannon AFB' },
'CVQ': { 'latitude':'-24.883333', 'longitude': '113.666667', 'name':'Carnarvon' },
'CVN': { 'latitude':'34.416667', 'longitude': '-103.083333', 'name':'Municipal' },
'CVO': { 'latitude':'44.5', 'longitude': '-123.283333', 'name':'Albany' },
'CVL': { 'latitude':'-9.7', 'longitude': '150.05', 'name':'Cape Vogel' },
'CVM': { 'latitude':'23.716667', 'longitude': '-98.866667', 'name':'Ciudad Victoria' },
'CVJ': { 'latitude':'18.834722', 'longitude': '-99.261389', 'name':'General Mariano Matamoros Airport' },
'CVH': { 'latitude':'-37.916667', 'longitude': '-71.013889', 'name':'Caviahue' },
'CVI': { 'latitude':'-46.433333', 'longitude': '-67.516667', 'name':'Caleta Olivia' },
'CVF': { 'latitude':'45.5', 'longitude': '6.666667', 'name':'Courchevel' },
'CVG': { 'latitude':'39.048889', 'longitude': '-84.667778', 'name':'Cincinnati/northern Kentucky' },
'CVE': { 'latitude':'9.4', 'longitude': '-75.733333', 'name':'Covenas' },
'CVB': { 'latitude':'-4.8', 'longitude': '144.733333', 'name':'Chungribu' },
'CVC': { 'latitude':'-33.7', 'longitude': '136.5', 'name':'Cleve' },
'TBC': { 'latitude':'13.466667', 'longitude': '-14.2', 'name':'Tuba City' },
'WDA': { 'latitude':'14.866667', 'longitude': '45.55', 'name':'Wadi Ain' },
'WDB': { 'latitude':'55.45', 'longitude': '-131.783333', 'name':'Deep Bay' },
'WDG': { 'latitude':'36.383333', 'longitude': '-97.783333', 'name':'Enid Woodring Mun.' },
'WDH': { 'latitude':'-22.48', 'longitude': '17.470833', 'name':'Hosea Kutako International' },
'WDI': { 'latitude':'-26.316667', 'longitude': '151.866667', 'name':'Wondai' },
'WDR': { 'latitude':'33.983333', 'longitude': '-83.666667', 'name':'Winder' },
'WDY': { 'latitude':'56.866667', 'longitude': '-1.25', 'name':'Kodiak Fss' },
'REP': { 'latitude':'13.416667', 'longitude': '103.816667', 'name':'Siem Reap' },
'REW': { 'latitude':'24.533333', 'longitude': '81.3', 'name':'Rewa' },
'RET': { 'latitude':'67.483333', 'longitude': '12.083333', 'name':'Stolport' },
'REA': { 'latitude':'-18.5', 'longitude': '-136.4', 'name':'Reao' },
'ZGY': { 'latitude':'5.966667', 'longitude': '100.55', 'name':'Kuching Port' },
'ZGR': { 'latitude':'52.066667', 'longitude': '-95.466667', 'name':'Little Grand Rapids' },
'ZGS': { 'latitude':'50.333333', 'longitude': '-60.666667', 'name':'Gethsemani' },
'ZGU': { 'latitude':'-14.25', 'longitude': '167.5', 'name':'Gaua' },
'ZGW': { 'latitude':'54.085', 'longitude': '13.418056', 'name':'Greifswald Railway' },
'ZGI': { 'latitude':'54.683333', 'longitude': '-94.166667', 'name':'Gods River' },
'ZGL': { 'latitude':'-25.683333', 'longitude': '142.116667', 'name':'South Galway' },
'ZGM': { 'latitude':'-15.966667', 'longitude': '25.95', 'name':'Ngoma' },
'ZGN': { 'latitude':'22.516667', 'longitude': '113.366667', 'name':'Zhongshan Ferry Port' },
'ZGO': { 'latitude':'51.416667', 'longitude': '12.6', 'name':'Gotha Railway' },
'ZGA': { 'latitude':'12.566667', 'longitude': '36.15', 'name':'Gera Railway' },
'ZGC': { 'latitude':'36.016667', 'longitude': '103.716667', 'name':'Zhongchuan' },
'ZGD': { 'latitude':'-8.735278', 'longitude': '125.352222', 'name':'New London Rail' },
'ZGE': { 'latitude':'51.166667', 'longitude': '15.0', 'name':'Goerlitz Railway' },
'ZGF': { 'latitude':'49.033333', 'longitude': '-118.466667', 'name':'Grand Forks' },
'RBG': { 'latitude':'43.233333', 'longitude': '-123.35', 'name':'Municipal' },
'YQM': { 'latitude':'46.112222', 'longitude': '-64.678611', 'name':'Greater Moncton International Airport' },
'YQL': { 'latitude':'49.633333', 'longitude': '-112.8', 'name':'Lethbridge' },
'YQN': { 'latitude':'50.166667', 'longitude': '-86.7', 'name':'Nakina' },
'YQI': { 'latitude':'43.826944', 'longitude': '-66.088056', 'name':'Yarmouth' },
'YQH': { 'latitude':'60.116667', 'longitude': '-128.816667', 'name':'Watson Lake' },
'YQK': { 'latitude':'49.816667', 'longitude': '-94.366667', 'name':'Kenora' },
'YQE': { 'latitude':'49.683333', 'longitude': '-115.983333', 'name':'Kimberley' },
'YQD': { 'latitude':'53.823354', 'longitude': '-101.252747', 'name':'The Pas' },
'YQG': { 'latitude':'42.266667', 'longitude': '-82.966667', 'name':'Windsor' },
'YQF': { 'latitude':'52.183333', 'longitude': '-113.9', 'name':'Red Deer' },
'YQA': { 'latitude':'44.974722', 'longitude': '-79.303333', 'name':'Muskoka' },
'YQC': { 'latitude':'61.333333', 'longitude': '-69.633333', 'name':'Quaqtaq' },
'YQB': { 'latitude':'46.791111', 'longitude': '-71.393333', 'name':'Québec' },
'YQY': { 'latitude':'46.166667', 'longitude': '-60.05', 'name':'Sydney' },
'YQX': { 'latitude':'48.95', 'longitude': '-54.566667', 'name':'Gander International' },
'YQZ': { 'latitude':'53.033333', 'longitude': '-122.516667', 'name':'Quesnel' },
'YQU': { 'latitude':'55.183333', 'longitude': '-118.883333', 'name':'Grande Prairie' },
'YQT': { 'latitude':'48.371667', 'longitude': '-89.323889', 'name':'Thunder Bay' },
'YQW': { 'latitude':'52.766667', 'longitude': '-108.25', 'name':'North Battleford' },
'YQV': { 'latitude':'51.266667', 'longitude': '-102.466667', 'name':'Yorkton' },
'YQQ': { 'latitude':'49.710833', 'longitude': '-124.886667', 'name':'Comox' },
'YQS': { 'latitude':'42.77', 'longitude': '-81.11', 'name':'Pembroke Area Mncpl' },
'YQR': { 'latitude':'50.433333', 'longitude': '-104.666667', 'name':'Regina' },
'SLG': { 'latitude':'36.183333', 'longitude': '-94.533333', 'name':'Smith Field' },
'FCA': { 'latitude':'48.316667', 'longitude': '-114.266667', 'name':'Glacier Park International' },
'FCB': { 'latitude':'-28.825', 'longitude': '27.908333', 'name':'Ficksburg Sentra Oes' },
'GFY': { 'latitude':'-19.6', 'longitude': '18.133333', 'name':'Grootfontein' },
'XEA': { 'latitude':'49.25', 'longitude': '-1.133333', 'name':'Vancouver Rail Stn.' },
'XEN': { 'latitude':'40.733333', 'longitude': '118.616667', 'name':'Xingcheng' },
'GFR': { 'latitude':'48.882778', 'longitude': '-1.563889', 'name':'Granville' },
'XES': { 'latitude':'42.566667', 'longitude': '-88.416667', 'name':'Municipal' },
'XEZ': { 'latitude':'59.2', 'longitude': '17.616667', 'name':'Sodertalje S Railway' },
'TWB': { 'latitude':'-27.542778', 'longitude': '151.916389', 'name':'Toowoomba' },
'TWA': { 'latitude':'59.166667', 'longitude': '-159.991667', 'name':'Twin Hills' },
'TWF': { 'latitude':'42.481667', 'longitude': '-114.487778', 'name':'Joslin Field - Magic Valley Regional' },
'TWD': { 'latitude':'48.116667', 'longitude': '-122.766667', 'name':'Port Townsend' },
'TWE': { 'latitude':'56.15', 'longitude': '-1.666667', 'name':'Taylor' },
'TWH': { 'latitude':'41.633333', 'longitude': '-120.05', 'name':'Two Harbors' },
'TWN': { 'latitude':'-26.383333', 'longitude': '153.033333', 'name':'Tewantin' },
'TWP': { 'latitude':'-26.583333', 'longitude': '147.55', 'name':'Torwood' },
'HQM': { 'latitude':'46.966667', 'longitude': '-123.933333', 'name':'Bowerman' },
'TWT': { 'latitude':'5.166667', 'longitude': '120.0', 'name':'Tawitawi' },
'TWU': { 'latitude':'4.333333', 'longitude': '117.833333', 'name':'Tawau' },
'TWZ': { 'latitude':'-43.6', 'longitude': '170.166667', 'name':'Pukaki/Twizel' },
'TWY': { 'latitude':'52.25', 'longitude': '15.833333', 'name':'Tawa' },
'YIB': { 'latitude':'48.75', 'longitude': '-91.616667', 'name':'Atikokan' },
'GFO': { 'latitude':'6.416667', 'longitude': '-58.583333', 'name':'Bartica' },
'GFL': { 'latitude':'43.35', 'longitude': '-73.616667', 'name':'Warren County' },
'GFB': { 'latitude':'-0.333333', 'longitude': '122.0', 'name':'Togiak Fish' },
'PTL': { 'latitude':'56.297222', 'longitude': '-134.6625', 'name':'Port Armstrong' },
'GFA': { 'latitude':'27.083333', 'longitude': '-77.0', 'name':'Malmstrom AFB' },
'VST': { 'latitude':'59.589444', 'longitude': '16.633611', 'name':'Vasteras/Hasslo' },
'GFF': { 'latitude':'-34.25', 'longitude': '146.066667', 'name':'Griffith' },
'VSA': { 'latitude':'18.0', 'longitude': '-92.983333', 'name':'Capitan Carlos Rovirosa' },
'YIV': { 'latitude':'54.208333', 'longitude': '-94.791667', 'name':'Island Lk/Garden Hill' },
'GFD': { 'latitude':'6.716667', 'longitude': '-57.95', 'name':'Pope Field' },
'VSF': { 'latitude':'43.333333', 'longitude': '-72.516667', 'name':'State' },
'PTF': { 'latitude':'-17.783056', 'longitude': '177.216389', 'name':'Malololailai' },
'MCP': { 'latitude':'0.066667', 'longitude': '-51.066667', 'name':'Internacional' },
'VSO': { 'latitude':'9.433333', 'longitude': '105.466667', 'name':'Phuoclong' },
'RYN': { 'latitude':'45.633333', 'longitude': '-0.966667', 'name':'Medis' },
'RYO': { 'latitude':'-51.6', 'longitude': '-72.216667', 'name':'Rio Turbio' },
'RYK': { 'latitude':'28.4', 'longitude': '70.283333', 'name':'Rahim Yar Khan' },
'EOK': { 'latitude':'40.466667', 'longitude': '-91.433333', 'name':'Keokuk' },
'RYG': { 'latitude':'59.3789', 'longitude': '10.7856', 'name':'Oslo Rygge' },
'EOI': { 'latitude':'59.2', 'longitude': '-2.783333', 'name':'Eday' },
'EOH': { 'latitude':'6.216667', 'longitude': '-75.583333', 'name':'Enrique Olaya Herrera International Airport' },
'RYB': { 'latitude':'58.099444', 'longitude': '38.9175', 'name':'Rybinsk' },
'EOS': { 'latitude':'36.866667', 'longitude': '-94.366667', 'name':'Neosho' },
'EOR': { 'latitude':'6.733333', 'longitude': '-61.583333', 'name':'El Dorado' },
'EOZ': { 'latitude':'7.166667', 'longitude': '-69.533333', 'name':'Elorza' },
'PTZ': { 'latitude':'-1.516667', 'longitude': '-78.041667', 'name':'Pastaza' },
'PTX': { 'latitude':'1.85', 'longitude': '-76.033333', 'name':'Pitalito' },
'PTW': { 'latitude':'40.233333', 'longitude': '-75.65', 'name':'Pottstown/Limerick' },
'PTV': { 'latitude':'36.033333', 'longitude': '-119.066667', 'name':'Porterville' },
'LQN': { 'latitude':'34.95', 'longitude': '63.666667', 'name':'Qala Nau' },
'PTQ': { 'latitude':'-1.738889', 'longitude': '-52.244444', 'name':'Porto de Moz' },
'CMO': { 'latitude':'5.366667', 'longitude': '48.516667', 'name':'Obbia' },
'CMN': { 'latitude':'33.366667', 'longitude': '-7.583333', 'name':'Mohamed V' },
'CMM': { 'latitude':'17.5', 'longitude': '-90.166667', 'name':'Carmelita' },
'CML': { 'latitude':'-19.916667', 'longitude': '138.133333', 'name':'Camooweal' },
'CMK': { 'latitude':'-14.3', 'longitude': '35.133333', 'name':'Club Makokola' },
'CMJ': { 'latitude':'23.25', 'longitude': '119.416667', 'name':'Chi Mei' },
'CMI': { 'latitude':'40.033333', 'longitude': '-88.283333', 'name':'University Of Illinois Willard' },
'CMH': { 'latitude':'40.0', 'longitude': '-82.883333', 'name':'Port Columbus Intl' },
'CMG': { 'latitude':'-19.011389', 'longitude': '-57.666944', 'name':'Intl. Airport Corumba' },
'CMF': { 'latitude':'45.566667', 'longitude': '5.916667', 'name':'Chambery' },
'CME': { 'latitude':'18.7', 'longitude': '-91.633333', 'name':'Ciudad Del Carmen' },
'CMD': { 'latitude':'-34.633333', 'longitude': '148.05', 'name':'Cootamundra' },
'CMC': { 'latitude':'-2.9', 'longitude': '-40.833333', 'name':'Camocim' },
'CMB': { 'latitude':'7.179167', 'longitude': '79.883056', 'name':'Bandaranayake' },
'CMA': { 'latitude':'-28.033333', 'longitude': '145.616667', 'name':'Cunnamulla' },
'PCU': { 'latitude':'30.516667', 'longitude': '-89.705556', 'name':'Pearl River County' },
'PCJ': { 'latitude':'-22.333333', 'longitude': '-57.916667', 'name':'Puerto La Victoria' },
'PCK': { 'latitude':'67.25', 'longitude': '-150.283333', 'name':'Porcupine Creek' },
'PCH': { 'latitude':'15.0', 'longitude': '-89.0', 'name':'Palacios' },
'PCN': { 'latitude':'-41.35', 'longitude': '174.033333', 'name':'Koromiko' },
'CMZ': { 'latitude':'-25.316667', 'longitude': '32.966667', 'name':'Caia' },
'CMY': { 'latitude':'43.95', 'longitude': '-90.783333', 'name':'Fort Mccoy' },
'CMX': { 'latitude':'47.123611', 'longitude': '-88.573333', 'name':'Houghton County' },
'CMW': { 'latitude':'21.416667', 'longitude': '-77.866667', 'name':'Ign Agramonte Intl' },
'CMV': { 'latitude':'-36.75', 'longitude': '175.5', 'name':'Coromandel' },
'CMU': { 'latitude':'-5.983333', 'longitude': '144.983333', 'name':'Chimbu' },
'CMT': { 'latitude':'-2.25', 'longitude': '-49.5', 'name':'Cameta' },
'CMS': { 'latitude':'10.5', 'longitude': '50.458333', 'name':'Scusciuban' },
'CMR': { 'latitude':'48.083333', 'longitude': '7.366667', 'name':'Colmar-houssen' },
'CMQ': { 'latitude':'-22.866667', 'longitude': '147.5', 'name':'Clermont' },
'CMP': { 'latitude':'-9.333333', 'longitude': '-50.333333', 'name':'Campo Alegre' },
'VND': { 'latitude':'-23.35', 'longitude': '47.6', 'name':'Vangaindrano' },
'OKQ': { 'latitude':'-8.1', 'longitude': '139.7', 'name':'Okaba' },
'OKP': { 'latitude':'-5.466667', 'longitude': '141.566667', 'name':'Oksapmin' },
'OKS': { 'latitude':'41.4', 'longitude': '-102.333333', 'name':'Oshkosh' },
'OKR': { 'latitude':'-9.733333', 'longitude': '143.416667', 'name':'Yorke Island' },
'INX': { 'latitude':'-2.133333', 'longitude': '132.166667', 'name':'Inanwatan' },
'INY': { 'latitude':'-24.783333', 'longitude': '31.383333', 'name':'Inyati' },
'INZ': { 'latitude':'27.25', 'longitude': '2.516667', 'name':'In Salah' },
'OKV': { 'latitude':'-3.916667', 'longitude': '116.2', 'name':'Okao' },
'INT': { 'latitude':'36.133333', 'longitude': '-80.219444', 'name':'Smith-Reynolds' },
'INU': { 'latitude':'-0.5475', 'longitude': '166.919167', 'name':'Nauru International' },
'INV': { 'latitude':'57.533333', 'longitude': '-4.05', 'name':'Inverness' },
'INW': { 'latitude':'35.021944', 'longitude': '-110.7225', 'name':'Winslow-Lindbergh' },
'INQ': { 'latitude':'53.033333', 'longitude': '-9.433333', 'name':'Inisheer' },
'INS': { 'latitude':'46.283333', 'longitude': '22.1', 'name':'Af Aux' },
'INL': { 'latitude':'48.566667', 'longitude': '-93.4', 'name':'Falls Intl' },
'INM': { 'latitude':'-27.833333', 'longitude': '140.833333', 'name':'Innamincka' },
'INN': { 'latitude':'47.266667', 'longitude': '11.35', 'name':'Innsbruck-kranebitten' },
'INO': { 'latitude':'-1.966667', 'longitude': '18.266667', 'name':'Inongo' },
'INH': { 'latitude':'-23.866667', 'longitude': '35.416667', 'name':'Inhambane' },
'INI': { 'latitude':'43.337222', 'longitude': '21.853611', 'name':'Constantine The Great International' },
'INJ': { 'latitude':'-25.85', 'longitude': '148.55', 'name':'Injune' },
'INK': { 'latitude':'31.783333', 'longitude': '-103.2', 'name':'Wink' },
'IND': { 'latitude':'39.717222', 'longitude': '-86.294722', 'name':'Indianapolis International' },
'INE': { 'latitude':'-18.616667', 'longitude': '36.4', 'name':'Chinde' },
'INF': { 'latitude':'19.566667', 'longitude': '5.75', 'name':'Newark Liberty International' },
'ING': { 'latitude':'-50.333333', 'longitude': '-72.25', 'name':'Lago Argentino' },
'OKM': { 'latitude':'35.616667', 'longitude': '-95.966667', 'name':'Okmulgee' },
'INA': { 'latitude':'66.066667', 'longitude': '60.1', 'name':'Inta' },
'INB': { 'latitude':'16.533333', 'longitude': '-88.433333', 'name':'Independence' },
'INC': { 'latitude':'38.366667', 'longitude': '106.366667', 'name':'Yinchuan' },
'GLH': { 'latitude':'33.477222', 'longitude': '-90.985', 'name':'Greenville' },
'GLI': { 'latitude':'-29.683333', 'longitude': '151.7', 'name':'Glen Innes' },
'AKY': { 'latitude':'20.116667', 'longitude': '92.866667', 'name':'Civil' },
'AKX': { 'latitude':'50.25', 'longitude': '57.216667', 'name':'Aktyubinsk' },
'GLL': { 'latitude':'60.783333', 'longitude': '9.05', 'name':'Klanten Arpt' },
'GLM': { 'latitude':'-22.283333', 'longitude': '138.316667', 'name':'Glenormiston' },
'GLN': { 'latitude':'29.016667', 'longitude': '-10.066667', 'name':'Goulimime' },
'CAZ': { 'latitude':'-31.533333', 'longitude': '145.8', 'name':'Cobar' },
'AKS': { 'latitude':'-8.697778', 'longitude': '160.680833', 'name':'Auki' },
'AKR': { 'latitude':'7.25', 'longitude': '5.2', 'name':'Akure' },
'AKQ': { 'latitude':'-4.616667', 'longitude': '105.233333', 'name':'Gunung Batin' },
'AKP': { 'latitude':'68.133333', 'longitude': '-151.733333', 'name':'Anaktuvuk' },
'AKW': { 'latitude':'36.583333', 'longitude': '46.616667', 'name':'Aghajari' },
'AKV': { 'latitude':'60.733333', 'longitude': '-78.583333', 'name':'Akulivik' },
'AKU': { 'latitude':'41.166667', 'longitude': '80.333333', 'name':'Aksu' },
'AKT': { 'latitude':'34.604167', 'longitude': '32.958333', 'name':'Akrotiri Raf' },
'AKK': { 'latitude':'56.95', 'longitude': '-154.166667', 'name':'Akhiok SPB' },
'AKJ': { 'latitude':'43.5', 'longitude': '142.508333', 'name':'Asahikawa' },
'GLZ': { 'latitude':'51.568056', 'longitude': '4.933056', 'name':'Gilze-Rijen' },
'AKH': { 'latitude':'24.062778', 'longitude': '47.580556', 'name':'Prince Sultan Air Base' },
'AKO': { 'latitude':'40.175556', 'longitude': '-103.221944', 'name':'Colorado Plains Regional Airport' },
'AKN': { 'latitude':'58.516667', 'longitude': '-156.633333', 'name':'King Salmon' },
'AKM': { 'latitude':'10.883333', 'longitude': '19.816667', 'name':'Zakouma' },
'AKL': { 'latitude':'-37.008056', 'longitude': '174.791667', 'name':'Auckland International' },
'AKC': { 'latitude':'-26.8', 'longitude': '23.75', 'name':'Fulton International' },
'AKB': { 'latitude':'52.2', 'longitude': '-174.2', 'name':'Atka' },
'AKA': { 'latitude':'32.5', 'longitude': '109.008333', 'name':'Ankang' },
'GLS': { 'latitude':'29.266667', 'longitude': '-94.866667', 'name':'Scholes Field' },
'GLT': { 'latitude':'-23.8', 'longitude': '151.25', 'name':'Gladstone' },
'AKF': { 'latitude':'24.2', 'longitude': '23.316667', 'name':'Kufrah' },
'AKE': { 'latitude':'-1.172222', 'longitude': '13.916667', 'name':'Akieni' },
'AKD': { 'latitude':'20.698889', 'longitude': '77.058611', 'name':'Akola' },
'BSX': { 'latitude':'16.8', 'longitude': '94.783333', 'name':'Bassein' },
'BSY': { 'latitude':'2.35', 'longitude': '42.333333', 'name':'Bardera' },
'BSZ': { 'latitude':'58.266667', 'longitude': '-157.483333', 'name':'Bartletts' },
'BST': { 'latitude':'31.55', 'longitude': '64.366667', 'name':'Bost' },
'BSU': { 'latitude':'1.216667', 'longitude': '19.8', 'name':'Basankusu' },
'BSV': { 'latitude':'-7.233333', 'longitude': '141.083333', 'name':'Besakoa' },
'BSW': { 'latitude':'60.4', 'longitude': '-146.133333', 'name':'Boswell Bay' },
'BSP': { 'latitude':'-8.85', 'longitude': '141.25', 'name':'Bensbach' },
'BSQ': { 'latitude':'31.363889', 'longitude': '-109.881111', 'name':'Bisbee Municipal Arpt' },
'BSR': { 'latitude':'30.55', 'longitude': '47.766667', 'name':'International' },
'BSS': { 'latitude':'-7.5', 'longitude': '-46.033333', 'name':'Balsas' },
'BSL': { 'latitude':'47.6', 'longitude': '7.533333', 'name':'Euroairport Basel Mulhouse Freiburg' },
'BSM': { 'latitude':'36.655278', 'longitude': '52.349722', 'name':'Bishe-kola' },
'BSN': { 'latitude':'6.5', 'longitude': '17.433333', 'name':'Bossangoa' },
'BSO': { 'latitude':'20.433333', 'longitude': '121.983333', 'name':'Basco' },
'BSH': { 'latitude':'50.833333', 'longitude': '-0.133333', 'name':'Brighton' },
'BSI': { 'latitude':'40.433333', 'longitude': '-79.266667', 'name':'Blairsville' },
'BSJ': { 'latitude':'-37.883333', 'longitude': '147.566667', 'name':'Bairnsdale' },
'BSK': { 'latitude':'34.8', 'longitude': '5.733333', 'name':'Biskra' },
'BSD': { 'latitude':'25.15', 'longitude': '99.15', 'name':'Baoshan' },
'BSE': { 'latitude':'1.8', 'longitude': '109.766667', 'name':'Sematan' },
'BSF': { 'latitude':'66.15', 'longitude': '25.866667', 'name':'Bradshaw AAF' },
'BSG': { 'latitude':'1.9', 'longitude': '9.8', 'name':'Bata' },
'BSA': { 'latitude':'11.283333', 'longitude': '49.183333', 'name':'Bossaso' },
'BSB': { 'latitude':'-15.871111', 'longitude': '-47.918611', 'name':'Presidente Juscelino Kubitschek' },
'BSC': { 'latitude':'6.183333', 'longitude': '-77.4', 'name':'Bahia Solano' },
'GGS': { 'latitude':'-48.766667', 'longitude': '-70.2', 'name':'Gobernador Gregores' },
'CAW': { 'latitude':'-21.75', 'longitude': '-41.3', 'name':'Bartolomeu Lisandro' },
'CAV': { 'latitude':'-11.883333', 'longitude': '22.933333', 'name':'Cazombo' },
'MPB': { 'latitude':'25.775', 'longitude': '-80.175', 'name':'SPB' },
'RDV': { 'latitude':'61.833333', 'longitude': '-157.333333', 'name':'Red Devil' },
'SBR': { 'latitude':'-9.4', 'longitude': '142.666667', 'name':'Saibai Island' },
'GGR': { 'latitude':'8.416667', 'longitude': '48.483333', 'name':'Garoe' },
'SBP': { 'latitude':'35.236944', 'longitude': '-120.641944', 'name':'San Luis County Regional Airport' },
'SBQ': { 'latitude':'29.583333', 'longitude': '67.85', 'name':'Sibi' },
'MMY': { 'latitude':'24.783333', 'longitude': '125.333333', 'name':'Hirara' },
'MMX': { 'latitude':'55.55', 'longitude': '13.366667', 'name':'Sturup' },
'SBT': { 'latitude':'34.1', 'longitude': '-117.266667', 'name':'Tri-City' },
'MMZ': { 'latitude':'35.916667', 'longitude': '64.733333', 'name':'Maimana' },
'MMU': { 'latitude':'40.8', 'longitude': '-74.416667', 'name':'Municipal' },
'MMT': { 'latitude':'-10.75', 'longitude': '-67.866667', 'name':'Mc Entire ANG Base' },
'MMW': { 'latitude':'-16.75', 'longitude': '39.216667', 'name':'Moma' },
'MMV': { 'latitude':'11.381111', 'longitude': '-69.126667', 'name':'Mal' },
'MMQ': { 'latitude':'-8.870833', 'longitude': '31.333333', 'name':'Mbala' },
'CAI': { 'latitude':'30.121944', 'longitude': '31.405556', 'name':'Cairo International' },
'MMM': { 'latitude':'-22.8025', 'longitude': '148.704722', 'name':'Middlemount' },
'MML': { 'latitude':'44.444167', 'longitude': '-95.82', 'name':'Municipal-Ryan Field' },
'MMO': { 'latitude':'15.25', 'longitude': '-23.166667', 'name':'Vila Do Maio' },
'MMN': { 'latitude':'42.433333', 'longitude': '-71.502778', 'name':'Minute Man Airfield' },
'MMI': { 'latitude':'35.45', 'longitude': '-84.6', 'name':'McMinn County' },
'MMH': { 'latitude':'37.616667', 'longitude': '-118.85', 'name':'Mammoth Lakes' },
'MMK': { 'latitude':'68.781667', 'longitude': '32.750833', 'name':'Murmansk Airport Murmashi' },
'MMJ': { 'latitude':'36.283333', 'longitude': '138.0', 'name':'Matsumoto' },
'MME': { 'latitude':'54.666667', 'longitude': '-1.75', 'name':'Durham Tees Valley' },
'MMD': { 'latitude':'25.833333', 'longitude': '131.25', 'name':'Maridor' },
'MMG': { 'latitude':'-28.083333', 'longitude': '117.85', 'name':'Mount Magnet' },
'MMF': { 'latitude':'5.716667', 'longitude': '9.3', 'name':'Mamfe' },
'SBN': { 'latitude':'41.7', 'longitude': '-86.316667', 'name':'South Bend Regional' },
'MPL': { 'latitude':'43.583333', 'longitude': '3.966667', 'name':'Montpellier Méditerranée' },
'MMC': { 'latitude':'22.75', 'longitude': '-99.0', 'name':'Ciudad Mante' },
'MMB': { 'latitude':'43.9', 'longitude': '144.166667', 'name':'Memanbetsu' },
'KOI': { 'latitude':'58.933333', 'longitude': '-2.9', 'name':'Orkney Island' },
'ERU': { 'latitude':'-8.416667', 'longitude': '147.083333', 'name':'Erume' },
'KOK': { 'latitude':'63.833333', 'longitude': '23.15', 'name':'Kruunupyy' },
'KOJ': { 'latitude':'31.803333', 'longitude': '130.719444', 'name':'Kagoshima' },
'KOM': { 'latitude':'-6.133333', 'longitude': '143.633333', 'name':'Komo-Manda' },
'KOL': { 'latitude':'8.5', 'longitude': '21.25', 'name':'Koumala' },
'KOO': { 'latitude':'-5.4', 'longitude': '27.0', 'name':'Kongolo' },
'KON': { 'latitude':'14.35', 'longitude': '108.016667', 'name':'Kontum' },
'KOA': { 'latitude':'19.738889', 'longitude': '-156.045556', 'name':'Kona International Airport' },
'MPJ': { 'latitude':'-16.166389', 'longitude': '38.721944', 'name':'Petit Jean Park' },
'KOC': { 'latitude':'-20.5', 'longitude': '164.416667', 'name':'Koumac' },
'KOB': { 'latitude':'5.0', 'longitude': '10.008333', 'name':'Koutaba' },
'KOE': { 'latitude':'-10.166667', 'longitude': '123.666667', 'name':'Eltari' },
'KOD': { 'latitude':'-0.266667', 'longitude': '116.583333', 'name':'Sabiha Gökçen Havaalan?' },
'ERZ': { 'latitude':'39.956389', 'longitude': '41.170278', 'name':'Budrum' },
'MPK': { 'latitude':'34.761111', 'longitude': '126.386111', 'name':'Mokpo' },
'ERD': { 'latitude':'46.733333', 'longitude': '36.783333', 'name':'Berdyansk' },
'ERE': { 'latitude':'-6.633333', 'longitude': '144.0', 'name':'Erave' },
'ERF': { 'latitude':'50.983333', 'longitude': '10.966667', 'name':'Erfurt' },
'KOZ': { 'latitude':'57.916667', 'longitude': '-152.483333', 'name':'Ouzinkie SPB' },
'ERA': { 'latitude':'10.633333', 'longitude': '47.366667', 'name':'Erigavo' },
'ERB': { 'latitude':'-26.266667', 'longitude': '132.166667', 'name':'Ernabella' },
'ERC': { 'latitude':'39.716667', 'longitude': '39.516667', 'name':'Erzincan' },
'KOQ': { 'latitude':'51.75', 'longitude': '11.966667', 'name':'Koethen' },
'KOP': { 'latitude':'17.4', 'longitude': '104.766667', 'name':'Nakhon Phanom' },
'KOS': { 'latitude':'10.6', 'longitude': '103.683333', 'name':'Sihanoukville' },
'KOR': { 'latitude':'-7.816667', 'longitude': '146.55', 'name':'Kokoro' },
'ERH': { 'latitude':'31.9475', 'longitude': '-4.398333', 'name':'Moulay Ali Cherif' },
'ERI': { 'latitude':'42.083333', 'longitude': '-80.183333', 'name':'International' },
'KOW': { 'latitude':'25.9', 'longitude': '114.916667', 'name':'Ganzhou' },
'KOV': { 'latitude':'53.316667', 'longitude': '69.4', 'name':'Kokshetau' },
'MPV': { 'latitude':'44.203611', 'longitude': '-72.562222', 'name':'Edward F Knapp State' },
'MPT': { 'latitude':'-8.172222', 'longitude': '125.008333', 'name':'Maliana' },
'MPU': { 'latitude':'-2.916667', 'longitude': '151.416667', 'name':'Mapua' },
'MPS': { 'latitude':'33.15', 'longitude': '-94.966667', 'name':'Mount Pleasant' },
'YFS': { 'latitude':'61.75', 'longitude': '-121.233333', 'name':'Fort Simpson' },
'MPQ': { 'latitude':'30.166667', 'longitude': '35.8', 'name':'Maan' },
'RDR': { 'latitude':'58.4', 'longitude': '-1.75', 'name':'Grand Forks AFB' },
'QLX': { 'latitude':'47.483056', 'longitude': '9.733056', 'name':'Lauterach' },
'MPX': { 'latitude':'-4.9', 'longitude': '141.616667', 'name':'Miyanmin' },
'PGM': { 'latitude':'59.35', 'longitude': '-151.833333', 'name':'Port Graham' },
'DEL': { 'latitude':'28.569444', 'longitude': '77.118056', 'name':'Indira Gandhi Intl' },
'PGH': { 'latitude':'29.031944', 'longitude': '79.473611', 'name':'Pantnagar' },
'PGI': { 'latitude':'-7.35', 'longitude': '20.95', 'name':'Chitato' },
'PGV': { 'latitude':'35.633333', 'longitude': '-77.4', 'name':'Pitt-Greenville' },
'QJI': { 'latitude':'72.233333', 'longitude': '-55.05', 'name':'Heliport' },
'GGE': { 'latitude':'33.316667', 'longitude': '-79.316667', 'name':'Georgetown' },
'WFK': { 'latitude':'47.35', 'longitude': '-68.383333', 'name':'Frenchville' },
'WFI': { 'latitude':'-21.45', 'longitude': '47.1', 'name':'Fianarantsoa' },
'WFB': { 'latitude':'55.366667', 'longitude': '-131.65', 'name':'Waterfront SPB' },
'WFD': { 'latitude':'51.116667', 'longitude': '-1.833333', 'name':'Woodford' },
'GGG': { 'latitude':'32.383333', 'longitude': '-94.716667', 'name':'Kilgore' },
'TEK': { 'latitude':'41.633333', 'longitude': '24.95', 'name':'Tatitlek' },
'RDE': { 'latitude':'-1.583333', 'longitude': '133.333333', 'name':'Merdey' },
'KIF': { 'latitude':'53.033333', 'longitude': '-89.833333', 'name':'Kingfisher Lake' },
'QJV': { 'latitude':'57.716667', 'longitude': '10.533333', 'name':'Limousine Service' },
'TEA': { 'latitude':'18.45', 'longitude': '-70.733333', 'name':'Tela' },
'TEE': { 'latitude':'35.466667', 'longitude': '8.15', 'name':'Tbessa' },
'TEF': { 'latitude':'-23.083333', 'longitude': '115.683333', 'name':'Telfer' },
'RDG': { 'latitude':'40.383333', 'longitude': '-75.966667', 'name':'Municipal/Spaatz Fld' },
'TEP': { 'latitude':'-5.95', 'longitude': '146.566667', 'name':'Teptep' },
'TEQ': { 'latitude':'41.0', 'longitude': '27.5', 'name':'Corlu' },
'TER': { 'latitude':'38.761944', 'longitude': '-27.090833', 'name':'Lajes Ab' },
'OGX': { 'latitude':'31.916667', 'longitude': '5.4', 'name':'Ain Beida' },
'ZEC': { 'latitude':'-26.533333', 'longitude': '29.166667', 'name':'Secunda' },
'ZEF': { 'latitude':'39.966667', 'longitude': '119.783333', 'name':'Nanhai Ferry' },
'ZEG': { 'latitude':'-5.983333', 'longitude': '139.366667', 'name':'Senggo' },
'TET': { 'latitude':'-16.104722', 'longitude': '33.640278', 'name':'Matundo' },
'OGZ': { 'latitude':'43.2', 'longitude': '44.6', 'name':'Vladikavkaz' },
'ZEN': { 'latitude':'-6.95', 'longitude': '146.616667', 'name':'Zenag' },
'ZEL': { 'latitude':'52.166667', 'longitude': '-128.1', 'name':'Bella Bella' },
'TEU': { 'latitude':'-45.533056', 'longitude': '167.65', 'name':'Manapouri' },
'ZER': { 'latitude':'27.566667', 'longitude': '93.833333', 'name':'Zero' },
'JYV': { 'latitude':'62.233333', 'longitude': '25.733333', 'name':'Jyvaskyla' },
'OGV': { 'latitude':'-22.183333', 'longitude': '18.533333', 'name':'Ongava Game Reserve' },
'JYR': { 'latitude':'27.75', 'longitude': '58.0', 'name':'Jiroft' },
'YWR': { 'latitude':'48.583333', 'longitude': '-85.25', 'name':'White River' },
'YWQ': { 'latitude':'43.083333', 'longitude': '-79.066667', 'name':'Chute-Des-Passes' },
'YWP': { 'latitude':'53.0', 'longitude': '-87.333333', 'name':'Webequie' },
'YWY': { 'latitude':'63.2', 'longitude': '-123.416667', 'name':'Wrigley' },
'YWG': { 'latitude':'49.91', 'longitude': '-97.24', 'name':'James Armstrong Richardson International Airport' },
'YWF': { 'latitude':'44.65', 'longitude': '-63.6', 'name':'Dwtown Waterfront H/P' },
'YWB': { 'latitude':'61.6', 'longitude': '-71.966667', 'name':'Kangiqsujuaq' },
'YWA': { 'latitude':'45.9', 'longitude': '-77.283333', 'name':'Petawawa' },
'YWO': { 'latitude':'65.758889', 'longitude': '-111.248889', 'name':'Lupin' },
'YWN': { 'latitude':'55.25', 'longitude': '-85.116667', 'name':'Winisk' },
'YWM': { 'latitude':'52.333333', 'longitude': '-56.0', 'name':'Williams Harbour' },
'YWL': { 'latitude':'52.183333', 'longitude': '-122.05', 'name':'Williams Lake' },
'YWK': { 'latitude':'52.916667', 'longitude': '-66.866667', 'name':'Wabush' },
'YWJ': { 'latitude':'65.183333', 'longitude': '-123.416667', 'name':'Deline' },
'YWH': { 'latitude':'48.422778', 'longitude': '-123.3875', 'name':'Victoria Inner Harbor' },
'OGL': { 'latitude':'6.8', 'longitude': '-58.105556', 'name':'Ogle' },
'GGN': { 'latitude':'6.133333', 'longitude': '-5.933333', 'name':'Gagnoa' },
'UDE': { 'latitude':'51.656389', 'longitude': '5.708611', 'name':'Volkel' },
'RDM': { 'latitude':'44.25', 'longitude': '-121.15', 'name':'Roberts Field' },
'UDJ': { 'latitude':'48.634167', 'longitude': '22.263333', 'name':'Uzhgorod' },
'XGN': { 'latitude':'-16.75', 'longitude': '14.967222', 'name':'Xangongo' },
'XGL': { 'latitude':'56.3', 'longitude': '-100.5', 'name':'Granville Lake' },
'UDN': { 'latitude':'46.033333', 'longitude': '13.183333', 'name':'Airfield' },
'UDO': { 'latitude':'19.133333', 'longitude': '103.816667', 'name':'Udomxay' },
'XGZ': { 'latitude':'47.5', 'longitude': '9.766667', 'name':'Railway Station' },
'OGB': { 'latitude':'33.45', 'longitude': '-80.85', 'name':'Municipal' },
'XGR': { 'latitude':'58.533333', 'longitude': '-65.9', 'name':'Kangiqsualujjuaq' },
'MII': { 'latitude':'-22.216667', 'longitude': '-49.933333', 'name':'Dr Gastao Vidigal' },
'GHU': { 'latitude':'-33.016667', 'longitude': '-58.583333', 'name':'Gualeguaychu' },
'TQN': { 'latitude':'36.5', 'longitude': '69.5', 'name':'Taluqan' },
'TQR': { 'latitude':'42.116667', 'longitude': '15.483333', 'name':'San Domino Island' },
'HSB': { 'latitude':'37.733333', 'longitude': '-88.55', 'name':'Raleigh' },
'HSC': { 'latitude':'24.833333', 'longitude': '113.616667', 'name':'Shaoguan' },
'HSG': { 'latitude':'33.149722', 'longitude': '130.302222', 'name':'Saga' },
'HSK': { 'latitude':'42.07756', 'longitude': '-0.316111', 'name':'Huesca' },
'HSH': { 'latitude':'35.968333', 'longitude': '-115.119167', 'name':'Henderson Sky Harbor' },
'HSI': { 'latitude':'40.6', 'longitude': '-98.433333', 'name':'Hastings' },
'HSN': { 'latitude':'28.083333', 'longitude': '122.366667', 'name':'Zhoushan' },
'HSL': { 'latitude':'65.7', 'longitude': '-156.416667', 'name':'Huslia' },
'HSM': { 'latitude':'-36.5', 'longitude': '141.841667', 'name':'Horsham' },
'HSS': { 'latitude':'29.166667', 'longitude': '75.8', 'name':'Hissar' },
'HSP': { 'latitude':'37.95', 'longitude': '-79.816667', 'name':'Ingalls Field' },
'HSV': { 'latitude':'34.637222', 'longitude': '-86.775', 'name':'Huntsville International - Carl T. Jones Field' },
'HST': { 'latitude':'25.483333', 'longitude': '-80.483333', 'name':'AFB' },
'HSZ': { 'latitude':'24.818056', 'longitude': '120.941389', 'name':'Hsinchu' },
'MIB': { 'latitude':'48.41555555', 'longitude': '-101.35722222', 'name':'Minot AFB' },
'MIF': { 'latitude':'31.6', 'longitude': '-102.9', 'name':'Roy Hurd Memorial' },
'SYC': { 'latitude':'-11.883333', 'longitude': '-69.2', 'name':'Shiringayoc' },
'GHD': { 'latitude':'9.166667', 'longitude': '35.833333', 'name':'Ghimbi' },
'SYA': { 'latitude':'52.716667', 'longitude': '174.1', 'name':'Shemya AFB' },
'SYG': { 'latitude':'78.0', 'longitude': '20.0', 'name':'Spitsberg' },
'SYF': { 'latitude':'3.483333', 'longitude': '-77.2', 'name':'Silva Bay' },
'SYE': { 'latitude':'16.966667', 'longitude': '43.733333', 'name':'Sadah' },
'GHE': { 'latitude':'8.083333', 'longitude': '-78.333333', 'name':'Garachine' },
'SYK': { 'latitude':'65.1', 'longitude': '-22.8', 'name':'Stykkisholmur' },
'SYJ': { 'latitude':'29.5', 'longitude': '55.5', 'name':'Sirjan' },
'SYI': { 'latitude':'35.566667', 'longitude': '-86.45', 'name':'Bomar Field' },
'SYH': { 'latitude':'28.783333', 'longitude': '83.7', 'name':'Syangboche' },
'SYO': { 'latitude':'38.809444', 'longitude': '139.790556', 'name':'Shonai' },
'SYN': { 'latitude':'44.468056', 'longitude': '-93.0', 'name':'Carleton' },
'SYM': { 'latitude':'22.833333', 'longitude': '101.0', 'name':'Simao' },
'SYL': { 'latitude':'80.0', 'longitude': '-75.866667', 'name':'Roberts AAF' },
'SYS': { 'latitude':'34.833889', 'longitude': '127.616944', 'name':'Yeosu' },
'SYR': { 'latitude':'43.116667', 'longitude': '-76.116667', 'name':'Syracuse Hancock International Airport' },
'SYQ': { 'latitude':'9.956944', 'longitude': '-84.139722', 'name':'Tobias Bolaños International' },
'SYP': { 'latitude':'-27.116667', 'longitude': '-56.766667', 'name':'Santiago' },
'SYW': { 'latitude':'26.416667', 'longitude': '67.85', 'name':'Sehwen Sharif' },
'SYV': { 'latitude':'31.516667', 'longitude': '-83.833333', 'name':'Sylvester' },
'SYU': { 'latitude':'-10.516667', 'longitude': '142.366667', 'name':'Warraber Island' },
'SYT': { 'latitude':'46.4', 'longitude': '4.033333', 'name':'Charolais Bourgogne S.' },
'SYZ': { 'latitude':'29.533333', 'longitude': '52.633333', 'name':'Shiraz' },
'SYY': { 'latitude':'58.216667', 'longitude': '-6.333333', 'name':'Stornoway' },
'SYX': { 'latitude':'18.302778', 'longitude': '109.412222', 'name':'Fenghuang International' },
'EME': { 'latitude':'53.366667', 'longitude': '7.2', 'name':'Emden' },
'EMD': { 'latitude':'-23.633333', 'longitude': '148.133333', 'name':'Emerald' },
'EMG': { 'latitude':'-28.733333', 'longitude': '31.9', 'name':'Empangeni' },
'RGS': { 'latitude':'42.357275', 'longitude': '-3.621025', 'name':'Burgos' },
'EMA': { 'latitude':'52.831111', 'longitude': '-1.328056', 'name':'East Midlands' },
'EMB': { 'latitude':'-38.7', 'longitude': '-60.016667', 'name':'Embarkadero' },
'EMM': { 'latitude':'41.85', 'longitude': '-110.55', 'name':'Kemerer' },
'EML': { 'latitude':'47.0925', 'longitude': '8.305', 'name':'Emmen' },
'EMO': { 'latitude':'-8.733333', 'longitude': '147.783333', 'name':'Emo' },
'EMN': { 'latitude':'16.6', 'longitude': '-7.283333', 'name':'Nema' },
'EMI': { 'latitude':'-1.65', 'longitude': '149.966667', 'name':'Emirau' },
'EMK': { 'latitude':'62.766667', 'longitude': '-164.5', 'name':'Emmonak' },
'XWW': { 'latitude':'48.25', 'longitude': '16.416667', 'name':'Westbahnhof Rail' },
'EMT': { 'latitude':'34.1', 'longitude': '-118.033333', 'name':'El Monte' },
'EMP': { 'latitude':'38.333333', 'longitude': '-96.183333', 'name':'Emporia' },
'EMS': { 'latitude':'-9.366667', 'longitude': '148.466667', 'name':'Embessa' },
'MIP': { 'latitude':'30.6', 'longitude': '34.8', 'name':'Mitspeh Ramon' },
'RGH': { 'latitude':'25.216667', 'longitude': '88.783333', 'name':'Balurghat' },
'RGI': { 'latitude':'-14.966667', 'longitude': '-147.666667', 'name':'Rangiroa' },
'EMY': { 'latitude':'28.083333', 'longitude': '30.733333', 'name':'El Minya' },
'EMX': { 'latitude':'-42.068056', 'longitude': '-71.155556', 'name':'El Maiten' },
'RGN': { 'latitude':'16.852778', 'longitude': '96.133333', 'name':'Mingaladon' },
'LDC': { 'latitude':'-20.45', 'longitude': '149.05', 'name':'Lindeman Island' },
'LDB': { 'latitude':'-23.333333', 'longitude': '-51.133333', 'name':'Londrina' },
'LDA': { 'latitude':'25.033333', 'longitude': '88.15', 'name':'Malda' },
'LDG': { 'latitude':'64.9', 'longitude': '45.75', 'name':'Leshukonskoye' },
'LDE': { 'latitude':'43.181944', 'longitude': '0.000278', 'name':'Tarbes Ossun Lourdes' },
'LDK': { 'latitude':'58.466667', 'longitude': '13.168611', 'name':'Hovby' },
'LDJ': { 'latitude':'40.633333', 'longitude': '-74.25', 'name':'Linden' },
'LDI': { 'latitude':'-9.833333', 'longitude': '39.783333', 'name':'Kikwetu' },
'LDH': { 'latitude':'-31.516667', 'longitude': '159.05', 'name':'Lord Howe Island' },
'LDO': { 'latitude':'4.383333', 'longitude': '-55.416667', 'name':'Ladouanie' },
'LDN': { 'latitude':'27.3', 'longitude': '86.75', 'name':'Lamidanda' },
'LDM': { 'latitude':'50.8', 'longitude': '24.05', 'name':'Mason County' },
'LDR': { 'latitude':'13.883333', 'longitude': '45.866667', 'name':'Lodar' },
'LDW': { 'latitude':'-17.583333', 'longitude': '126.833333', 'name':'Lansdowne' },
'LDU': { 'latitude':'5.05', 'longitude': '118.316667', 'name':'Lahad Datu' },
'LDZ': { 'latitude':'-24.8', 'longitude': '31.5', 'name':'Londolozi' },
'LDY': { 'latitude':'55.042778', 'longitude': '-7.161111', 'name':'Eglinton' },
'LDX': { 'latitude':'5.483333', 'longitude': '-54.033333', 'name':'St-Laurent du Maroni' },
'SPQ': { 'latitude':'33.75', 'longitude': '-118.366667', 'name':'Catalina SPB' },
'AOA': { 'latitude':'-9.033333', 'longitude': '146.75', 'name':'Aroa' },
'QWG': { 'latitude':'35.213889', 'longitude': '-80.67', 'name':'Wilgrove Air Park' },
'QWF': { 'latitude':'19.833333', 'longitude': '-72.5', 'name':'Fort Collins Bus Servi' },
'QWP': { 'latitude':'11.033333', 'longitude': '3.65', 'name':'Van Service' },
'COQ': { 'latitude':'48.133333', 'longitude': '114.9', 'name':'Choibalsan' },
'COP': { 'latitude':'42.629167', 'longitude': '-74.891111', 'name':'Cooperstown - Westville Airport' },
'COS': { 'latitude':'38.816667', 'longitude': '-104.716667', 'name':'Colorado Springs' },
'COR': { 'latitude':'-31.316667', 'longitude': '-64.216667', 'name':'Pajas Blancas' },
'COU': { 'latitude':'38.95', 'longitude': '-92.333333', 'name':'Columbia Regional' },
'COT': { 'latitude':'28.433333', 'longitude': '-99.233333', 'name':'Cotulla' },
'COW': { 'latitude':'-33.45', 'longitude': '-57.733333', 'name':'Coquimbo' },
'COV': { 'latitude':'40.283333', 'longitude': '-7.5', 'name':'Covilha' },
'COY': { 'latitude':'-21.8', 'longitude': '117.766667', 'name':'Coolawanyah' },
'COX': { 'latitude':'24.15', 'longitude': '-77.586111', 'name':'Congo Town' },
'ILL': { 'latitude':'45.116667', 'longitude': '-95.1', 'name':'Willmar' },
'COZ': { 'latitude':'18.9', 'longitude': '-70.716667', 'name':'Constanza' },
'PEP': { 'latitude':'-14.15', 'longitude': '130.1', 'name':'Peppimenarti' },
'ILK': { 'latitude':'-19.75', 'longitude': '48.816667', 'name':'Ilaka' },
'PER': { 'latitude':'-31.940278', 'longitude': '115.966944', 'name':'Perth International' },
'ILI': { 'latitude':'59.733333', 'longitude': '-154.966667', 'name':'Iliamna' },
'COA': { 'latitude':'38.033333', 'longitude': '-120.416667', 'name':'Columbia' },
'PEM': { 'latitude':'-12.583333', 'longitude': '-69.233333', 'name':'Puerto Maldonado' },
'COC': { 'latitude':'-31.3', 'longitude': '-58.016667', 'name':'Concordia' },
'ILU': { 'latitude':'-2.9', 'longitude': '38.066667', 'name':'Kilaguni' },
'ILR': { 'latitude':'8.5', 'longitude': '4.533333', 'name':'Ilorin' },
'COD': { 'latitude':'44.516667', 'longitude': '-109.033333', 'name':'Yellowstone Regional' },
'COG': { 'latitude':'5.1', 'longitude': '-76.616667', 'name':'Mandinga' },
'ILQ': { 'latitude':'-14.899722', 'longitude': '-71.956389', 'name':'Ilo' },
'COI': { 'latitude':'28.133333', 'longitude': '-80.633333', 'name':'Merritt Island' },
'COH': { 'latitude':'26.333333', 'longitude': '89.466667', 'name':'Cooch Behar' },
'COK': { 'latitude':'10.151944', 'longitude': '76.401944', 'name':'Cochin International' },
'COJ': { 'latitude':'-31.333333', 'longitude': '149.266667', 'name':'Coonabarabran' },
'COM': { 'latitude':'31.833333', 'longitude': '-99.433333', 'name':'Coleman' },
'COL': { 'latitude':'56.616667', 'longitude': '-6.616667', 'name':'Isle Of Coll' },
'COO': { 'latitude':'6.35', 'longitude': '2.383333', 'name':'Cotonou' },
'CON': { 'latitude':'6.683333', 'longitude': '-57.9', 'name':'Concord' },
'AOT': { 'latitude':'45.738611', 'longitude': '7.3625', 'name':'Aosta' },
'MIV': { 'latitude':'39.366667', 'longitude': '-75.083333', 'name':'Millville' },
'OES': { 'latitude':'-40.733333', 'longitude': '-64.933333', 'name':'San Antonio Oeste' },
'OER': { 'latitude':'63.408333', 'longitude': '18.991667', 'name':'Ornskoldsvik' },
'OEO': { 'latitude':'45.316667', 'longitude': '-92.7', 'name':'Municipal' },
'OEL': { 'latitude':'52.983333', 'longitude': '36.1', 'name':'Orel' },
'OEC': { 'latitude':'-9.25', 'longitude': '124.4', 'name':'Ocussi' },
'OEA': { 'latitude':'38.666667', 'longitude': '-87.516667', 'name':'Oneal' },
'MKG': { 'latitude':'43.166667', 'longitude': '-86.233333', 'name':'Muskegon' },
'MKF': { 'latitude':'-12.5625', 'longitude': '39.896389', 'name':'Mckenna AAF' },
'MKE': { 'latitude':'42.95', 'longitude': '-87.9', 'name':'General Mitchell International' },
'MKD': { 'latitude':'11.033333', 'longitude': '36.466667', 'name':'Chagni' },
'MKC': { 'latitude':'39.116667', 'longitude': '-94.583333', 'name':'Downtown' },
'MKB': { 'latitude':'0.966667', 'longitude': '13.95', 'name':'Mekambo' },
'MKA': { 'latitude':'49.983333', 'longitude': '12.716667', 'name':'Marianske Lazne' },
'AIZ': { 'latitude':'38.1', 'longitude': '-92.55', 'name':'Lee C Fine Memorial' },
'MKO': { 'latitude':'35.666667', 'longitude': '-95.366667', 'name':'Davis Field' },
'AIT': { 'latitude':'-18.85', 'longitude': '-159.75', 'name':'Aitutaki' },
'MKM': { 'latitude':'2.9', 'longitude': '112.066667', 'name':'Mukah' },
'AIV': { 'latitude':'33.1', 'longitude': '-88.2', 'name':'George Downer' },
'MKK': { 'latitude':'21.166667', 'longitude': '-157.116667', 'name':'Molokai' },
'AIP': { 'latitude':'7.266667', 'longitude': '168.816667', 'name':'Ailinglapalap Island' },
'AIS': { 'latitude':'-2.633333', 'longitude': '176.816667', 'name':'Arorae Island' },
'MKH': { 'latitude':'-29.366667', 'longitude': '29.033333', 'name':'Mokhotlong' },
'AIM': { 'latitude':'10.2', 'longitude': '169.983333', 'name':'Ailuk Island' },
'AIL': { 'latitude':'9.233333', 'longitude': '-78.016667', 'name':'Ailigandi' },
'MKU': { 'latitude':'0.566667', 'longitude': '12.866667', 'name':'Makokou' },
'AIN': { 'latitude':'70.633333', 'longitude': '-160.033333', 'name':'Wainwright' },
'AII': { 'latitude':'11.15', 'longitude': '42.716667', 'name':'Alisabieh' },
'AIH': { 'latitude':'-7.35', 'longitude': '141.266667', 'name':'Aiambak' },
'AIK': { 'latitude':'33.65', 'longitude': '-81.683333', 'name':'Municipal' },
'GNE': { 'latitude':'51.05', 'longitude': '3.716667', 'name':'Ghent' },
'AIE': { 'latitude':'-5.133333', 'longitude': '144.733333', 'name':'Aiome' },
'AID': { 'latitude':'32.4', 'longitude': '34.866667', 'name':'Municipal' },
'AIG': { 'latitude':'6.516667', 'longitude': '23.25', 'name':'Yalinga' },
'AIF': { 'latitude':'22.666667', 'longitude': '-50.416667', 'name':'Assis' },
'AIA': { 'latitude':'42.066667', 'longitude': '-102.8', 'name':'Alliance' },
'MKZ': { 'latitude':'2.264167', 'longitude': '102.253333', 'name':'Malacca' },
'AIC': { 'latitude':'7.1', 'longitude': '171.233333', 'name':'Airok' },
'AIB': { 'latitude':'56.233333', 'longitude': '-132.383333', 'name':'Anita Bay' },
'NSH': { 'latitude':'36.666667', 'longitude': '51.466667', 'name':'Now Shahr' },
'NSI': { 'latitude':'3.7225', 'longitude': '11.553333', 'name':'Nsimalen International' },
'NSK': { 'latitude':'69.316667', 'longitude': '87.316667', 'name':'Norilsk' },
'NSM': { 'latitude':'-32.2', 'longitude': '121.75', 'name':'Norseman' },
'NSN': { 'latitude':'-41.3', 'longitude': '173.216667', 'name':'Nelson' },
'NSO': { 'latitude':'-32.166667', 'longitude': '150.916667', 'name':'Scone' },
'NSA': { 'latitude':'26.25', 'longitude': '153.166667', 'name':'Noosa' },
'NSB': { 'latitude':'25.775', 'longitude': '-79.25', 'name':'North SPB' },
'NSE': { 'latitude':'43.516667', 'longitude': '-79.883333', 'name':'Whiting Field NAS' },
'NSF': { 'latitude':'19.35', 'longitude': '100.55', 'name':'Andrews NAF' },
'NSX': { 'latitude':'18.5', 'longitude': '-64.366667', 'name':'Hovercraft/Launch Pt' },
'NSY': { 'latitude':'37.4', 'longitude': '14.916667', 'name':'Sigonella NAF' },
'NSP': { 'latitude':'14.495833', 'longitude': '120.918611', 'name':'NAF' },
'NST': { 'latitude':'8.433333', 'longitude': '99.966667', 'name':'Nakhon Si Thammarat' },
'NSV': { 'latitude':'-26.4', 'longitude': '153.066667', 'name':'Noosaville' },
'YTZ': { 'latitude':'43.6275', 'longitude': '-79.396111', 'name':'Toronto City Centre Airport' },
'RKP': { 'latitude':'28.083333', 'longitude': '-97.033333', 'name':'Aransas County' },
'SDT': { 'latitude':'34.816389', 'longitude': '72.352778', 'name':'Saidu Sharif' },
'SDU': { 'latitude':'-22.833333', 'longitude': '-43.25', 'name':'Santos Dumont' },
'SDV': { 'latitude':'31.871389', 'longitude': '34.677222', 'name':'Sde Dov' },
'SDW': { 'latitude':'22.666667', 'longitude': '91.166667', 'name':'Sandwip' },
'SDP': { 'latitude':'55.316667', 'longitude': '-160.516667', 'name':'Municipal' },
'SDQ': { 'latitude':'18.429722', 'longitude': '-69.668889', 'name':'Las Americas' },
'SDR': { 'latitude':'43.433333', 'longitude': '-3.816667', 'name':'Santander' },
'SDS': { 'latitude':'43.0', 'longitude': '142.675', 'name':'Sado Shima' },
'RKS': { 'latitude':'41.6', 'longitude': '-109.066667', 'name':'Sweetwater County' },
'SDX': { 'latitude':'34.866667', 'longitude': '-111.766667', 'name':'Sedona' },
'SDY': { 'latitude':'47.716667', 'longitude': '-104.183333', 'name':'Richland Municipal' },
'SDD': { 'latitude':'-14.916667', 'longitude': '13.483333', 'name':'Lubango' },
'SDE': { 'latitude':'-27.766667', 'longitude': '-64.283333', 'name':'Santiago Del Estero' },
'SDF': { 'latitude':'38.174444', 'longitude': '-85.736111', 'name':'Louisville International' },
'SDG': { 'latitude':'35.3', 'longitude': '47.016667', 'name':'Sanandaj' },
'SDA': { 'latitude':'33.25', 'longitude': '44.233333', 'name':'Baghdad International' },
'SDB': { 'latitude':'-32.968889', 'longitude': '18.160278', 'name':'Langebaanweg' },
'SDC': { 'latitude':'3.0', 'longitude': '-59.516667', 'name':'Sandcreek' },
'SDL': { 'latitude':'62.383333', 'longitude': '17.3', 'name':'Sundsvall/harnosand' },
'SDM': { 'latitude':'32.572222', 'longitude': '-116.98', 'name':'Brown Field Municipal' },
'RFR': { 'latitude':'10.333333', 'longitude': '-83.883333', 'name':'Rio Frio' },
'SDO': { 'latitude':'38.083333', 'longitude': '138.433333', 'name':'Ryotsu Sado Is' },
'SDH': { 'latitude':'14.816667', 'longitude': '-88.75', 'name':'Santa Rosa Copan' },
'SDI': { 'latitude':'-5.616667', 'longitude': '146.466667', 'name':'Saidor' },
'SDJ': { 'latitude':'38.133333', 'longitude': '140.916667', 'name':'Sendai' },
'SDK': { 'latitude':'5.9', 'longitude': '118.066667', 'name':'Sandakan' },
'RBW': { 'latitude':'32.9', 'longitude': '-80.666667', 'name':'Municipal' },
'EPT': { 'latitude':'-5.033333', 'longitude': '141.666667', 'name':'Eliptamin' },
'EPU': { 'latitude':'58.416667', 'longitude': '24.483333', 'name':'Parnu' },
'EPR': { 'latitude':'-33.683333', 'longitude': '121.816667', 'name':'Esperance' },
'EPS': { 'latitude':'19.190278', 'longitude': '-69.429722', 'name':'Arroyo Barril International' },
'EPN': { 'latitude':'1.366667', 'longitude': '17.483333', 'name':'Epena' },
'KQB': { 'latitude':'-31.966667', 'longitude': '133.45', 'name':'Koonibba' },
'KQA': { 'latitude':'54.116667', 'longitude': '-165.75', 'name':'Akutan' },
'EPK': { 'latitude':'34.666667', 'longitude': '32.9', 'name':'Episkopi' },
'EPH': { 'latitude':'47.3', 'longitude': '-119.516667', 'name':'Ephrata' },
'EPI': { 'latitude':'-16.75', 'longitude': '168.333333', 'name':'Epi' },
'EPG': { 'latitude':'40.866667', 'longitude': '-96.133333', 'name':'Browns' },
'EPA': { 'latitude':'-28.083333', 'longitude': '-64.283333', 'name':'El Palomar' },
'LYT': { 'latitude':'-24.116667', 'longitude': '152.7', 'name':'Lady Elliot Island' },
'LYU': { 'latitude':'47.9', 'longitude': '-91.85', 'name':'Ely' },
'LYP': { 'latitude':'31.516667', 'longitude': '73.0', 'name':'Faisalabad' },
'LYR': { 'latitude':'78.191667', 'longitude': '15.9', 'name':'Svalbard' },
'LYS': { 'latitude':'45.725556', 'longitude': '5.081111', 'name':'St-Exupéry' },
'LYX': { 'latitude':'50.95', 'longitude': '0.933333', 'name':'Lydd' },
'LYE': { 'latitude':'51.516667', 'longitude': '-1.966667', 'name':'RAF Station' },
'LYG': { 'latitude':'34.55', 'longitude': '119.25', 'name':'Lianyungang' },
'LYA': { 'latitude':'34.683333', 'longitude': '112.466667', 'name':'Luoyang' },
'LYB': { 'latitude':'19.666667', 'longitude': '-80.083333', 'name':'Little Cayman' },
'LYC': { 'latitude':'64.6', 'longitude': '18.666667', 'name':'Lycksele' },
'LYN': { 'latitude':'45.729722', 'longitude': '4.939444', 'name':'Bron' },
'LYH': { 'latitude':'37.333333', 'longitude': '-79.2', 'name':'Preston-Glenn Field' },
'LYI': { 'latitude':'35.063056', 'longitude': '118.342778', 'name':'Linyi' },
'LYK': { 'latitude':'-8.95', 'longitude': '117.233333', 'name':'Lunyuk' },
'BQE': { 'latitude':'11.3', 'longitude': '-15.85', 'name':'Bubaque' },
'BQB': { 'latitude':'-33.6925', 'longitude': '115.395278', 'name':'Bussellton' },
'BQA': { 'latitude':'15.729722', 'longitude': '121.5', 'name':'Baler' },
'BQN': { 'latitude':'18.416667', 'longitude': '-67.15', 'name':'Borinquen' },
'BQO': { 'latitude':'9.254444', 'longitude': '-3.031667', 'name':'Bouna' },
'BQL': { 'latitude':'-22.966667', 'longitude': '139.966667', 'name':'Boulia' },
'BQK': { 'latitude':'31.25', 'longitude': '-81.45', 'name':'Glynco Jetport' },
'BQI': { 'latitude':'11.4', 'longitude': '-7.85', 'name':'Bagani' },
'BQV': { 'latitude':'58.45', 'longitude': '-135.883333', 'name':'Bartlett SPB' },
'BQW': { 'latitude':'-20.133333', 'longitude': '127.8', 'name':'Balgo Hills' },
'BQT': { 'latitude':'52.116667', 'longitude': '23.883333', 'name':'Brest' },
'BQU': { 'latitude':'12.988333', 'longitude': '-61.261944', 'name':'J.F. Mitchell' },
'BQS': { 'latitude':'50.416667', 'longitude': '127.4', 'name':'Blagoveschensk' },
'BQQ': { 'latitude':'-11.066667', 'longitude': '-43.166667', 'name':'Barra' },
'RKO': { 'latitude':'-2.083333', 'longitude': '99.683333', 'name':'Sipora' },
'GME': { 'latitude':'52.416667', 'longitude': '31.0', 'name':'Gomel' },
'RKH': { 'latitude':'34.933333', 'longitude': '-81.016667', 'name':'Rock Hill' },
'RKI': { 'latitude':'-0.95', 'longitude': '100.75', 'name':'Rokot' },
'SFW': { 'latitude':'8.533333', 'longitude': '-81.083333', 'name':'Santa Fe' },
'YJF': { 'latitude':'60.25', 'longitude': '-123.466667', 'name':'Fort Liard' },
'YJN': { 'latitude':'45.316667', 'longitude': '-73.266667', 'name':'St Jean' },
'YJO': { 'latitude':'56.666667', 'longitude': '-131.116667', 'name':'Johnny Mountain' },
'YJP': { 'latitude':'53.319167', 'longitude': '-117.753056', 'name':'Jasper-hinton' },
'YJT': { 'latitude':'48.533056', 'longitude': '-58.549722', 'name':'Stephenville' },
'SFQ': { 'latitude':'37.085278', 'longitude': '38.85', 'name':'Sanliurfa' },
'BZP': { 'latitude':'-15.216667', 'longitude': '144.633333', 'name':'Bizant' },
'OLA': { 'latitude':'63.7', 'longitude': '9.616667', 'name':'Orland' },
'TFY': { 'latitude':'27.95', 'longitude': '-12.91', 'name':'Tarfaya' },
'SPC': { 'latitude':'28.683333', 'longitude': '-17.75', 'name':'La Palma' },
'OLQ': { 'latitude':'-5.383333', 'longitude': '141.5', 'name':'Olsobip' },
'IKL': { 'latitude':'-1.2', 'longitude': '23.283333', 'name':'Ikela' },
'ZCD': { 'latitude':'49.920556', 'longitude': '10.914167', 'name':'Breitenau AAF' },
'ZCA': { 'latitude':'36.5', 'longitude': '117.333333', 'name':'Tai Shan' },
'ZCL': { 'latitude':'22.783333', 'longitude': '-102.583333', 'name':'La Calera' },
'ZCO': { 'latitude':'-38.766944', 'longitude': '-72.637222', 'name':'Maquehue' },
'ZCU': { 'latitude':'22.466667', 'longitude': '114.433333', 'name':'She Kou Ferry' },
'YUY': { 'latitude':'48.216667', 'longitude': '-78.833333', 'name':'Rouyn-Noranda' },
'YUX': { 'latitude':'68.783333', 'longitude': '-81.233333', 'name':'Hall Beach' },
'YUT': { 'latitude':'66.533333', 'longitude': '-86.25', 'name':'Repulse Bay' },
'YUM': { 'latitude':'32.65', 'longitude': '-114.6', 'name':'International' },
'YUL': { 'latitude':'45.470556', 'longitude': '-73.740833', 'name':'Montréal-pierre Elliott Trudeau International Airport' },
'JWN': { 'latitude':'36.583333', 'longitude': '48.25', 'name':'Zanjan' },
'YUA': { 'latitude':'25.65', 'longitude': '101.916667', 'name':'Yuanmou' },
'JWA': { 'latitude':'-25.05', 'longitude': '25.283333', 'name':'Jwaneng' },
'YUB': { 'latitude':'69.429103', 'longitude': '-133.034477', 'name':'Tuktoyaktuk' },
'YUE': { 'latitude':'-22.266667', 'longitude': '131.783333', 'name':'Yuendumu' },
'YUD': { 'latitude':'56.55', 'longitude': '-76.55', 'name':'Umiujaq' },
'RFG': { 'latitude':'-41.066667', 'longitude': '-72.466667', 'name':'Rooke Field' },
'XYQ': { 'latitude':'59.683333', 'longitude': '15.816667', 'name':'Angelholm Railway Svc.' },
'XYR': { 'latitude':'-3.883333', 'longitude': '141.783333', 'name':'Yellow River' },
'XYT': { 'latitude':'46.483333', 'longitude': '-0.633333', 'name':'Montaudran' },
'XYU': { 'latitude':'56.066667', 'longitude': '14.616667', 'name':'Solvesborg' },
'XYV': { 'latitude':'45.75', 'longitude': '4.85', 'name':'Lyon Satolas Rail Svc' },
'XYX': { 'latitude':'45.470556', 'longitude': '19.705833', 'name':'Sala' },
'XYA': { 'latitude':'-9.066667', 'longitude': '159.233333', 'name':'Yandina' },
'XYB': { 'latitude':'57.033333', 'longitude': '14.85', 'name':'Borlange Railway Svc.' },
'XYC': { 'latitude':'58.018611', 'longitude': '13.101389', 'name':'Herrljunga' },
'XYD': { 'latitude':'46.235278', 'longitude': '5.151667', 'name':'Lyon Part-dieu Rail Sv' },
'XYE': { 'latitude':'15.25', 'longitude': '97.85', 'name':'Ye' },
'XYH': { 'latitude':'59.683333', 'longitude': '15.816667', 'name':'Helsingborg Railway' },
'XYI': { 'latitude':'57.5', 'longitude': '15.566667', 'name':'Flen' },
'XYL': { 'latitude':'45.75', 'longitude': '4.85', 'name':'Lyon Perrache Rail Svc' },
'XYM': { 'latitude':'49.65', 'longitude': '22.75', 'name':'Falkenberg Rail' },
'XYN': { 'latitude':'56.0', 'longitude': '14.15', 'name':'Kristinehamn Rail' },
'XYO': { 'latitude':'49.0', 'longitude': '8.666667', 'name':'Karlshamn' },
'GUC': { 'latitude':'38.533333', 'longitude': '-106.933333', 'name':'Gunnison' },
'GUB': { 'latitude':'28.666667', 'longitude': '-114.166667', 'name':'Guerrero Negro' },
'GUA': { 'latitude':'14.566667', 'longitude': '-90.533333', 'name':'La Aurora' },
'GUG': { 'latitude':'-8.1', 'longitude': '146.883333', 'name':'Guari' },
'GUF': { 'latitude':'30.289722', 'longitude': '-87.671667', 'name':'Edwards' },
'GUE': { 'latitude':'-3.583333', 'longitude': '141.583333', 'name':'Guriaso' },
'GUD': { 'latitude':'16.35', 'longitude': '-3.6', 'name':'Goundam' },
'TSF': { 'latitude':'45.651667', 'longitude': '12.198889', 'name':'S. Angelo' },
'GUJ': { 'latitude':'-22.791667', 'longitude': '-45.204722', 'name':'Guaratingueta' },
'GUI': { 'latitude':'10.566667', 'longitude': '-62.3', 'name':'Guiria' },
'GUH': { 'latitude':'-30.95', 'longitude': '150.233333', 'name':'Gunnedah' },
'GUO': { 'latitude':'15.083333', 'longitude': '-86.033333', 'name':'Gualaco' },
'GUN': { 'latitude':'51.066667', 'longitude': '-1.166667', 'name':'Gunter AFB' },
'GUM': { 'latitude':'13.483889', 'longitude': '144.797222', 'name':'Guam International' },
'GUL': { 'latitude':'-33.833333', 'longitude': '151.833333', 'name':'Goulburn' },
'GUS': { 'latitude':'40.648056', 'longitude': '-86.152222', 'name':'Grissom Afb' },
'GUR': { 'latitude':'-10.333333', 'longitude': '150.35', 'name':'Gurney' },
'GUQ': { 'latitude':'9.033333', 'longitude': '-69.75', 'name':'Guanare' },
'GUP': { 'latitude':'35.516667', 'longitude': '-108.783333', 'name':'Senator Clark' },
'GUW': { 'latitude':'47.121944', 'longitude': '51.821389', 'name':'Atyrau International' },
'GUV': { 'latitude':'-6.283333', 'longitude': '142.416667', 'name':'Mougulu' },
'GUU': { 'latitude':'64.966667', 'longitude': '-23.166667', 'name':'Grundarfjordur' },
'GUT': { 'latitude':'51.9', 'longitude': '8.383333', 'name':'Guetersloh' },
'TSV': { 'latitude':'-19.2525', 'longitude': '146.765278', 'name':'Townsville International' },
'GUZ': { 'latitude':'-20.666667', 'longitude': '-40.5', 'name':'Guarapari' },
'GUY': { 'latitude':'36.683333', 'longitude': '-101.483333', 'name':'Guymon' },
'GUX': { 'latitude':'24.483333', 'longitude': '77.316667', 'name':'Guna' },
'TSR': { 'latitude':'45.816667', 'longitude': '21.333333', 'name':'Timisoara' },
'TSS': { 'latitude':'40.744444', 'longitude': '-73.970833', 'name':'East 34th St Heliport' },
'TSP': { 'latitude':'35.135', 'longitude': '-118.439167', 'name':'Kern County' },
'TSQ': { 'latitude':'10.166667', 'longitude': '-70.25', 'name':'Torres' },
'HUD': { 'latitude':'42.733333', 'longitude': '-94.216667', 'name':'Humboldt' },
'HUE': { 'latitude':'14.25', 'longitude': '36.583333', 'name':'Humera' },
'HUF': { 'latitude':'10.733333', 'longitude': '-61.35', 'name':'Hulman Field' },
'HUG': { 'latitude':'15.333333', 'longitude': '-91.466667', 'name':'Huehuetenango' },
'HUB': { 'latitude':'-16.483333', 'longitude': '130.633333', 'name':'Humbert River' },
'HUC': { 'latitude':'18.133333', 'longitude': '-65.816667', 'name':'Humacao Arpt' },
'HUL': { 'latitude':'46.133333', 'longitude': '-67.8', 'name':'International' },
'HUM': { 'latitude':'29.583333', 'longitude': '-90.666667', 'name':'Terrebonne' },
'HUN': { 'latitude':'24.016667', 'longitude': '121.366667', 'name':'Hualien' },
'HUH': { 'latitude':'-16.683333', 'longitude': '-151.033333', 'name':'Huahine' },
'HUI': { 'latitude':'16.401389', 'longitude': '107.7025', 'name':'Phu Bai' },
'HUJ': { 'latitude':'34.016667', 'longitude': '-95.516667', 'name':'Hugo' },
'HUK': { 'latitude':'-23.983333', 'longitude': '21.75', 'name':'Hukuntsi' },
'HUT': { 'latitude':'38.066667', 'longitude': '-97.866667', 'name':'Hutchinson' },
'HUU': { 'latitude':'-9.908333', 'longitude': '-76.213889', 'name':'Huanuco' },
'HUV': { 'latitude':'61.733333', 'longitude': '17.116667', 'name':'Hudiksvall' },
'HUQ': { 'latitude':'29.05', 'longitude': '15.933333', 'name':'Houn' },
'HUS': { 'latitude':'66.033333', 'longitude': '-154.233333', 'name':'Municipal' },
'HUX': { 'latitude':'15.768333', 'longitude': '-96.235556', 'name':'Huatulco' },
'HUY': { 'latitude':'53.574444', 'longitude': '-0.350833', 'name':'Humberside International' },
'HUZ': { 'latitude':'23.083333', 'longitude': '114.4', 'name':'Huizhou' },
'YTQ': { 'latitude':'53.666667', 'longitude': '-69.916667', 'name':'Tasiujuaq' },
'YTJ': { 'latitude':'48.783333', 'longitude': '-87.1', 'name':'Terrace Bay' },
'EKO': { 'latitude':'40.825', 'longitude': '-115.791667', 'name':'Elko Regional' },
'EKN': { 'latitude':'38.883333', 'longitude': '-79.85', 'name':'Elkins' },
'REX': { 'latitude':'26.066667', 'longitude': '-98.266667', 'name':'Gen Lucio Blanco' },
'REY': { 'latitude':'-14.316667', 'longitude': '-67.266667', 'name':'Reyes' },
'EKI': { 'latitude':'41.716667', 'longitude': '-85.983333', 'name':'Municipal' },
'RER': { 'latitude':'14.533333', 'longitude': '-91.683333', 'name':'Base Aerea Del Sur' },
'RES': { 'latitude':'-27.466667', 'longitude': '-58.983333', 'name':'Resistencia' },
'EKE': { 'latitude':'6.666667', 'longitude': '-60.85', 'name':'Ekereku' },
'EKD': { 'latitude':'-21.033333', 'longitude': '135.25', 'name':'Elkedra' },
'EKB': { 'latitude':'51.583333', 'longitude': '75.216667', 'name':'Ekibastuz' },
'EKA': { 'latitude':'40.803333', 'longitude': '-124.112778', 'name':'Murray Field' },
'REU': { 'latitude':'41.15', 'longitude': '1.116667', 'name':'Reus' },
'REH': { 'latitude':'38.716667', 'longitude': '-75.133333', 'name':'Rehoboth Beach' },
'REI': { 'latitude':'4.316667', 'longitude': '-52.133333', 'name':'Regina' },
'REN': { 'latitude':'51.783333', 'longitude': '55.116667', 'name':'Orenburg' },
'REO': { 'latitude':'42.590556', 'longitude': '-117.867222', 'name':'State' },
'REL': { 'latitude':'-43.210556', 'longitude': '-65.270278', 'name':'Almirante Zar' },
'EKX': { 'latitude':'37.7', 'longitude': '-85.866667', 'name':'Elizabethtown' },
'REB': { 'latitude':'53.35', 'longitude': '12.733333', 'name':'Rechlin' },
'REC': { 'latitude':'-8.125833', 'longitude': '-34.923889', 'name':'Guararapes Intl' },
'EKT': { 'latitude':'59.383333', 'longitude': '16.45', 'name':'Eskilstuna' },
'REG': { 'latitude':'38.066667', 'longitude': '15.65', 'name':'Tito Menniti' },
'RED': { 'latitude':'40.683333', 'longitude': '-77.616667', 'name':'Mifflin County' },
'REE': { 'latitude':'-18.55', 'longitude': '126.75', 'name':'Reese AFB' },
'FCS': { 'latitude':'38.682268', 'longitude': '-104.7599052', 'name':'Butts AAF' },
'FCT': { 'latitude':'56.8', 'longitude': '41.266667', 'name':'Firing Center AAF' },
'LFB': { 'latitude':'-15.010556', 'longitude': '40.666389', 'name':'Lumbo' },
'LFM': { 'latitude':'27.372778', 'longitude': '53.188889', 'name':'Lamerd' },
'FCY': { 'latitude':'34.95', 'longitude': '-90.766667', 'name':'Municipal' },
'LFO': { 'latitude':'5.583333', 'longitude': '44.183333', 'name':'Kelafo' },
'LFN': { 'latitude':'36.1', 'longitude': '-78.3', 'name':'Franklin' },
'LFI': { 'latitude':'52.166667', 'longitude': '-2.016667', 'name':'Langley AFB' },
'LFK': { 'latitude':'31.25', 'longitude': '-94.752778', 'name':'Lufkin Angelina County' },
'LFT': { 'latitude':'30.205278', 'longitude': '-91.9875', 'name':'Lafayette Regional' },
'LFW': { 'latitude':'6.166667', 'longitude': '1.25', 'name':'Lome' },
'LFP': { 'latitude':'-14.916667', 'longitude': '144.333333', 'name':'Lakefield' },
'LFR': { 'latitude':'8.283333', 'longitude': '-72.283333', 'name':'La Fria' },
'FCH': { 'latitude':'19.291389', 'longitude': '-99.425833', 'name':'Fresno-Chandler' },
'FCM': { 'latitude':'44.827222', 'longitude': '-93.456944', 'name':'Flying Cloud' },
'FCN': { 'latitude':'53.883333', 'longitude': '8.7', 'name':'Cuxhaven/Nordholz' },
'FCO': { 'latitude':'41.804444', 'longitude': '12.250833', 'name':'Leonardo da Vinci International' },
'QUP': { 'latitude':'65.266667', 'longitude': '-50.8', 'name':'Heliport' },
'QUB': { 'latitude':'26.6', 'longitude': '12.768889', 'name':'Ubari' },
'QUF': { 'latitude':'59.715', 'longitude': '24.710833', 'name':'Pirita Harbour' },
'IBI': { 'latitude':'-5.583333', 'longitude': '149.2', 'name':'Iboki' },
'CAY': { 'latitude':'4.933333', 'longitude': '-52.333333', 'name':'Rochambeau' },
'CAX': { 'latitude':'54.933333', 'longitude': '-2.8', 'name':'Carlisle' },
'IBL': { 'latitude':'-21.705833', 'longitude': '35.451389', 'name':'Indigo Bay Lodge' },
'IBO': { 'latitude':'-12.333333', 'longitude': '40.583333', 'name':'Ibo' },
'IBA': { 'latitude':'7.433333', 'longitude': '3.9', 'name':'Ibadan' },
'CAQ': { 'latitude':'7.6', 'longitude': '-75.25', 'name':'Caucasia' },
'CAP': { 'latitude':'19.783333', 'longitude': '-72.2', 'name':'Cap Haitien' },
'LOA': { 'latitude':'-19.083333', 'longitude': '139.966667', 'name':'Lorraine' },
'IBE': { 'latitude':'4.416667', 'longitude': '-75.15', 'name':'Ibague' },
'CAU': { 'latitude':'-8.283333', 'longitude': '-35.966667', 'name':'Caruaru' },
'CAT': { 'latitude':'24.3', 'longitude': '-75.452222', 'name':'New Bight' },
'CAK': { 'latitude':'40.916111', 'longitude': '-81.442222', 'name':'Akron/canton Regional' },
'CAJ': { 'latitude':'6.25', 'longitude': '-62.833333', 'name':'Canaima' },
'IBZ': { 'latitude':'38.866667', 'longitude': '1.35', 'name':'Ibiza' },
'CAH': { 'latitude':'9.166667', 'longitude': '105.15', 'name':'Ca Mau' },
'CAO': { 'latitude':'36.45', 'longitude': '-103.183333', 'name':'Clayton' },
'CAN': { 'latitude':'23.3925', 'longitude': '113.298889', 'name':'New Baiyun' },
'CAM': { 'latitude':'-20.016667', 'longitude': '-63.566667', 'name':'Camiri' },
'CAL': { 'latitude':'55.416667', 'longitude': '-5.6', 'name':'Machrihanish' },
'CAC': { 'latitude':'-24.95', 'longitude': '-53.483333', 'name':'Cascavel' },
'CAB': { 'latitude':'-5.55', 'longitude': '12.183333', 'name':'Cabinda' },
'CAA': { 'latitude':'14.883333', 'longitude': '-85.883333', 'name':'Catacamas' },
'CAG': { 'latitude':'39.251389', 'longitude': '9.05', 'name':'Elmas' },
'CAF': { 'latitude':'-4.9', 'longitude': '-66.916667', 'name':'Carauari' },
'CAE': { 'latitude':'33.95', 'longitude': '-81.116667', 'name':'Metropolitan Airport' },
'CAD': { 'latitude':'44.275833', 'longitude': '-85.422222', 'name':'Cadillac' },
'PGF': { 'latitude':'42.740833', 'longitude': '2.869722', 'name':'Llabanere' },
'PGG': { 'latitude':'-6.95', 'longitude': '-55.45', 'name':'Progresso' },
'PGD': { 'latitude':'26.916667', 'longitude': '-81.983333', 'name':'Charlotte County' },
'PGE': { 'latitude':'-7.133333', 'longitude': '146.15', 'name':'Yegepa' },
'PGB': { 'latitude':'-7.016667', 'longitude': '141.55', 'name':'Pangoa' },
'PGC': { 'latitude':'39.0', 'longitude': '-79.116667', 'name':'Grant County' },
'PGA': { 'latitude':'36.933333', 'longitude': '-111.45', 'name':'Page' },
'PGN': { 'latitude':'-6.35', 'longitude': '144.116667', 'name':'Pangia' },
'DYU': { 'latitude':'38.5', 'longitude': '68.5', 'name':'Dushanbe' },
'DYW': { 'latitude':'-16.266667', 'longitude': '133.366667', 'name':'Daly Waters' },
'PGK': { 'latitude':'-2.160556', 'longitude': '106.141111', 'name':'Pangkalpinang' },
'DYR': { 'latitude':'64.733333', 'longitude': '177.75', 'name':'Anadyr' },
'DYS': { 'latitude':'54.1075', 'longitude': '-1.483611', 'name':'Dyess AFB' },
'DYL': { 'latitude':'40.316667', 'longitude': '-75.133333', 'name':'Doylestown' },
'DYM': { 'latitude':'-23.866667', 'longitude': '141.25', 'name':'Diamantina Lakes' },
'PGU': { 'latitude':'27.3672', 'longitude': '52.7339', 'name':'Asaloyeh Persian Gulf International' },
'PGR': { 'latitude':'36.05', 'longitude': '-90.5', 'name':'Municipal' },
'PGS': { 'latitude':'35.533333', 'longitude': '-113.416667', 'name':'Peach Springs' },
'PGP': { 'latitude':'0.033333', 'longitude': '6.533333', 'name':'Porto Alegre' },
'DYG': { 'latitude':'29.133333', 'longitude': '110.483333', 'name':'Dayong' },
'DYA': { 'latitude':'-22.533333', 'longitude': '149.383333', 'name':'Dysart' },
'PGX': { 'latitude':'45.1975', 'longitude': '0.815278', 'name':'Bassillac' },
'SOA': { 'latitude':'9.603333', 'longitude': '105.98', 'name':'Soc Trang' },
'SOC': { 'latitude':'-7.5', 'longitude': '110.75', 'name':'Adi Sumarmo' },
'VAG': { 'latitude':'-21.55', 'longitude': '-45.433333', 'name':'Maj. Brig. Trompowsky' },
'SOB': { 'latitude':'46.686111', 'longitude': '17.163889', 'name':'Saarmelleek/balaton' },
'SOE': { 'latitude':'2.083333', 'longitude': '14.05', 'name':'Souanke' },
'GAZ': { 'latitude':'-9.233333', 'longitude': '152.95', 'name':'Guasopa' },
'UDR': { 'latitude':'24.616667', 'longitude': '73.883333', 'name':'Dabok' },
'GAY': { 'latitude':'24.75', 'longitude': '84.95', 'name':'Gaya' },
'LHV': { 'latitude':'41.133333', 'longitude': '-77.45', 'name':'W T Piper Memorial' },
'HGH': { 'latitude':'30.3', 'longitude': '120.283333', 'name':'Hangzhou' },
'GAX': { 'latitude':'-2.766667', 'longitude': '9.983333', 'name':'Gamba' },
'OGS': { 'latitude':'44.683333', 'longitude': '-75.466667', 'name':'Ogdensburg' },
'OGR': { 'latitude':'10.289444', 'longitude': '15.383333', 'name':'Bongor' },
'GAW': { 'latitude':'22.166667', 'longitude': '94.133333', 'name':'Gangaw' },
'OGO': { 'latitude':'6.733333', 'longitude': '-3.483333', 'name':'Abengourou' },
'OGN': { 'latitude':'24.466667', 'longitude': '122.983333', 'name':'Yonaguni Jima' },
'UDD': { 'latitude':'33.733333', 'longitude': '-116.266667', 'name':'Bermuda Dunes' },
'GAV': { 'latitude':'-0.45', 'longitude': '130.883333', 'name':'Gag Island' },
'OGE': { 'latitude':'-6.433333', 'longitude': '147.333333', 'name':'Ogeranang' },
'OGD': { 'latitude':'41.2', 'longitude': '-112.016667', 'name':'Municipal' },
'OGG': { 'latitude':'20.898611', 'longitude': '-156.430556', 'name':'Kahului' },
'UDI': { 'latitude':'-18.882778', 'longitude': '-48.225556', 'name':'Eduardo Gomes' },
'OGA': { 'latitude':'41.133333', 'longitude': '-101.716667', 'name':'Searle Field' },
'GAU': { 'latitude':'26.106111', 'longitude': '91.585833', 'name':'Borjhar' },
'LHR': { 'latitude':'51.469722', 'longitude': '-0.451389', 'name':'London Heathrow' },
'GHT': { 'latitude':'24.966667', 'longitude': '10.166667', 'name':'Ghat' },
'MIH': { 'latitude':'-14.783333', 'longitude': '125.816667', 'name':'Mitchell Plateau' },
'MIK': { 'latitude':'61.7', 'longitude': '27.216667', 'name':'Mikkeli' },
'MIJ': { 'latitude':'6.083333', 'longitude': '171.75', 'name':'Mili Island' },
'MIM': { 'latitude':'-36.916667', 'longitude': '149.883333', 'name':'Merimbula' },
'MIO': { 'latitude':'10.016667', 'longitude': '-73.65', 'name':'Miami' },
'MIN': { 'latitude':'-32.833333', 'longitude': '135.133333', 'name':'Minnipa' },
'MIA': { 'latitude':'25.783333', 'longitude': '-80.266667', 'name':'Miami International Airport' },
'MIC': { 'latitude':'45.061944', 'longitude': '-93.353889', 'name':'Crystal' },
'LHP': { 'latitude':'-6.416667', 'longitude': '155.7', 'name':'Lehu' },
'MIE': { 'latitude':'40.233333', 'longitude': '-85.4', 'name':'Delaware County' },
'MID': { 'latitude':'20.933333', 'longitude': '-89.666667', 'name':'Rejon' },
'MIG': { 'latitude':'31.483333', 'longitude': '104.733333', 'name':'Mian Yang' },
'GAR': { 'latitude':'-7.866667', 'longitude': '147.133333', 'name':'Garaina' },
'MIY': { 'latitude':'-18.5', 'longitude': '136.266667', 'name':'Mittiebah' },
'MIX': { 'latitude':'-1.133333', 'longitude': '-70.25', 'name':'Miriti' },
'GHF': { 'latitude':'49.266667', 'longitude': '7.516667', 'name':'Giebelstadt' },
'MIZ': { 'latitude':'-14.3', 'longitude': '134.083333', 'name':'Mainoru' },
'MKX': { 'latitude':'14.533333', 'longitude': '49.133333', 'name':'Mukalla' },
'GHA': { 'latitude':'32.383333', 'longitude': '3.816667', 'name':'Noumerate' },
'GHB': { 'latitude':'25.283333', 'longitude': '-76.333333', 'name':'Governors Harbour' },
'GHC': { 'latitude':'25.750278', 'longitude': '-77.85', 'name':'Great Harbour' },
'MIQ': { 'latitude':'10.599444', 'longitude': '-66.9825', 'name':'Simón Bolívar International' },
'GHM': { 'latitude':'35.783333', 'longitude': '-87.466667', 'name':'Municipal' },
'MIS': { 'latitude':'-10.689167', 'longitude': '152.838333', 'name':'Misima Island' },
'MIR': { 'latitude':'35.758056', 'longitude': '10.754722', 'name':'Habib Bourguiba' },
'MIU': { 'latitude':'11.85', 'longitude': '13.083333', 'name':'Maiduguri' },
'MIT': { 'latitude':'35.5', 'longitude': '-119.266667', 'name':'Kern County' },
'MIW': { 'latitude':'42.116667', 'longitude': '-92.916667', 'name':'Municipal' },
'GHK': { 'latitude':'31.083333', 'longitude': '35.3', 'name':'Gush Katif' },
'AOG': { 'latitude':'41.166667', 'longitude': '123.033333', 'name':'Anshan' },
'SOQ': { 'latitude':'-0.933333', 'longitude': '131.116667', 'name':'Jefman' },
'AOE': { 'latitude':'39.811667', 'longitude': '30.528611', 'name':'Anadolu University' },
'AOD': { 'latitude':'11.466667', 'longitude': '19.283333', 'name':'Abou Deia' },
'AOC': { 'latitude':'50.983333', 'longitude': '12.508333', 'name':'Altenburg Nobitz' },
'AOB': { 'latitude':'-4.916667', 'longitude': '144.666667', 'name':'Annanberg' },
'NQT': { 'latitude':'52.966667', 'longitude': '-1.166667', 'name':'Nottingham Airport' },
'NQU': { 'latitude':'5.7', 'longitude': '-77.283333', 'name':'Nuqui' },
'AOO': { 'latitude':'40.3', 'longitude': '-78.316667', 'name':'Martinsburg' },
'AON': { 'latitude':'-6.25', 'longitude': '145.966667', 'name':'Arona' },
'AOL': { 'latitude':'-29.683333', 'longitude': '-57.15', 'name':'Paso De Los Libres' },
'AOK': { 'latitude':'35.5', 'longitude': '27.233333', 'name':'Karpathos' },
'AOJ': { 'latitude':'40.733333', 'longitude': '140.7', 'name':'Aomori' },
'AOI': { 'latitude':'43.633333', 'longitude': '13.5', 'name':'Falconara' },
'AOH': { 'latitude':'40.716667', 'longitude': '-84.033333', 'name':'Allen County' },
'AOU': { 'latitude':'14.8', 'longitude': '106.816667', 'name':'Attopeu' },
'NQA': { 'latitude':'35.356667', 'longitude': '-89.870278', 'name':'Millington Regional Jetport' },
'AOS': { 'latitude':'57.466667', 'longitude': '-153.833333', 'name':'Amook' },
'AOR': { 'latitude':'6.189722', 'longitude': '100.398056', 'name':'Alor Setar' },
'GAK': { 'latitude':'62.3', 'longitude': '-145.3', 'name':'Gakona' },
'NQI': { 'latitude':'51.366667', 'longitude': '-0.283333', 'name':'NAS' },
'NQN': { 'latitude':'-38.95', 'longitude': '-68.133333', 'name':'Neuquen' },
'NQL': { 'latitude':'-14.45', 'longitude': '-48.45', 'name':'Niquelandia' },
'GAJ': { 'latitude':'38.4', 'longitude': '140.366667', 'name':'Junmachi' },
'MBZ': { 'latitude':'-3.416667', 'longitude': '-57.666667', 'name':'Maues' },
'SOV': { 'latitude':'59.45', 'longitude': '-151.7', 'name':'Seldovia' },
'GAG': { 'latitude':'36.316667', 'longitude': '-99.75', 'name':'Gage' },
'MBU': { 'latitude':'-9.733333', 'longitude': '160.75', 'name':'Mbambanakira' },
'MBV': { 'latitude':'-6.35', 'longitude': '147.633333', 'name':'Masa' },
'GAD': { 'latitude':'33.966667', 'longitude': '-86.083333', 'name':'Municipal' },
'SFZ': { 'latitude':'41.920833', 'longitude': '-71.491389', 'name':'North Central' },
'SFX': { 'latitude':'8.35', 'longitude': '-62.633333', 'name':'San Felix' },
'SFV': { 'latitude':'-20.216667', 'longitude': '-50.933333', 'name':'Santa Fe Do Sul' },
'GAC': { 'latitude':'14.5', 'longitude': '-88.533333', 'name':'Gracias' },
'SFT': { 'latitude':'64.633333', 'longitude': '21.083333', 'name':'Skelleftea' },
'SFU': { 'latitude':'-9.583333', 'longitude': '148.633333', 'name':'Safia' },
'SFR': { 'latitude':'9.083333', 'longitude': '-74.333333', 'name':'San Fernando' },
'SFP': { 'latitude':'-28.0', 'longitude': '153.433333', 'name':'Surfers Paradise' },
'MBQ': { 'latitude':'-0.616667', 'longitude': '30.65', 'name':'Mbarara' },
'SFN': { 'latitude':'-31.716667', 'longitude': '-60.816667', 'name':'Santa Fe' },
'SFO': { 'latitude':'37.618889', 'longitude': '-122.375', 'name':'San Francisco International' },
'SFL': { 'latitude':'14.9', 'longitude': '-24.516667', 'name':'Sao Filipe' },
'SFM': { 'latitude':'43.383333', 'longitude': '-70.7', 'name':'Sanford' },
'SFJ': { 'latitude':'67.016944', 'longitude': '-50.689167', 'name':'Kangerlussuaq' },
'MBR': { 'latitude':'16.0', 'longitude': '-12.508333', 'name':'Mbout' },
'SFH': { 'latitude':'31.166667', 'longitude': '-114.833333', 'name':'San Felipe' },
'SFI': { 'latitude':'32.333333', 'longitude': '-9.283333', 'name':'Safi' },
'SFF': { 'latitude':'47.666667', 'longitude': '-117.325', 'name':'Felts Field' },
'SFG': { 'latitude':'18.052778', 'longitude': '-63.116667', 'name':'Esperance' },
'SFD': { 'latitude':'7.866667', 'longitude': '-67.433333', 'name':'Las Flecheras' },
'SFE': { 'latitude':'16.6', 'longitude': '120.3', 'name':'San Fernando' },
'SFB': { 'latitude':'28.783333', 'longitude': '-81.25', 'name':'Orlando Sanford Intl' },
'SFC': { 'latitude':'16.25', 'longitude': '-61.283333', 'name':'St Francois' },
'SFA': { 'latitude':'34.716667', 'longitude': '10.683333', 'name':'Sfax Thyna' },
'KSU': { 'latitude':'63.116667', 'longitude': '7.85', 'name':'Kvernberget' },
'KST': { 'latitude':'13.183333', 'longitude': '32.733333', 'name':'Kosti' },
'KSW': { 'latitude':'33.215833', 'longitude': '35.595556', 'name':'Kiryat Shmona' },
'KSV': { 'latitude':'-23.666667', 'longitude': '140.75', 'name':'Springvale' },
'KSQ': { 'latitude':'38.8', 'longitude': '65.766667', 'name':'Karshi' },
'KSP': { 'latitude':'-8.558333', 'longitude': '147.466667', 'name':'Kosipe' },
'KSS': { 'latitude':'11.316667', 'longitude': '-5.666667', 'name':'Sikasso' },
'KSR': { 'latitude':'56.233333', 'longitude': '-160.233056', 'name':'Sandy River' },
'KSY': { 'latitude':'40.551667', 'longitude': '43.085833', 'name':'Kars' },
'KSX': { 'latitude':'-6.6', 'longitude': '146.183333', 'name':'Yasuru' },
'KSZ': { 'latitude':'61.233333', 'longitude': '46.7', 'name':'Kotlas' },
'KSE': { 'latitude':'0.166667', 'longitude': '30.1', 'name':'Kasese' },
'KSD': { 'latitude':'59.366667', 'longitude': '13.466667', 'name':'Karlstad' },
'KSG': { 'latitude':'-6.35', 'longitude': '146.716667', 'name':'Kisengan' },
'KSF': { 'latitude':'51.4', 'longitude': '9.383333', 'name':'Kassel-Calden' },
'KSA': { 'latitude':'5.316667', 'longitude': '162.983333', 'name':'Kosrae' },
'KSC': { 'latitude':'48.663056', 'longitude': '21.241111', 'name':'Barca' },
'KSB': { 'latitude':'-6.383333', 'longitude': '147.016667', 'name':'Kasanombe' },
'KSM': { 'latitude':'62.05', 'longitude': '-163.183333', 'name':'Saint Marys' },
'KSL': { 'latitude':'15.3875', 'longitude': '36.328889', 'name':'Kassala' },
'KSO': { 'latitude':'40.483333', 'longitude': '21.283333', 'name':'Aristoteles Airport' },
'KSN': { 'latitude':'53.2', 'longitude': '63.55', 'name':'Kostanay' },
'KSI': { 'latitude':'9.166667', 'longitude': '-10.116667', 'name':'Kissidougou' },
'KSH': { 'latitude':'34.266667', 'longitude': '47.1', 'name':'Kermanshah' },
'KSK': { 'latitude':'59.333333', 'longitude': '14.516667', 'name':'Karlskoga' },
'KSJ': { 'latitude':'35.421389', 'longitude': '26.916667', 'name':'Kasos Island' },
'WUD': { 'latitude':'-33.016667', 'longitude': '135.619444', 'name':'Wudinna' },
'WUN': { 'latitude':'-26.633333', 'longitude': '120.216667', 'name':'Wiluna' },
'YHK': { 'latitude':'68.633333', 'longitude': '-95.95', 'name':'Gjoa Haven' },
'YHH': { 'latitude':'49.946389', 'longitude': '-125.265556', 'name':'Campbell River Harbor SPB' },
'YHI': { 'latitude':'70.716667', 'longitude': '-117.716667', 'name':'Holman' },
'YHN': { 'latitude':'49.216667', 'longitude': '-84.783333', 'name':'Hornepayne' },
'YHO': { 'latitude':'55.466667', 'longitude': '-60.216667', 'name':'Hopedale' },
'YHM': { 'latitude':'43.166667', 'longitude': '-79.933333', 'name':'Hamilton' },
'YHB': { 'latitude':'52.816667', 'longitude': '-102.311389', 'name':'Hudson Bay' },
'YHC': { 'latitude':'51.733333', 'longitude': '-128.116667', 'name':'Hakai Pass' },
'YHA': { 'latitude':'52.533333', 'longitude': '-56.3', 'name':'Port Hope Simpson' },
'YHF': { 'latitude':'49.683333', 'longitude': '-83.666667', 'name':'Hearst' },
'YHG': { 'latitude':'52.766667', 'longitude': '-56.1', 'name':'Charlottetown' },
'YHD': { 'latitude':'49.783333', 'longitude': '-92.833333', 'name':'Municipal' },
'YHE': { 'latitude':'49.383333', 'longitude': '-121.433333', 'name':'Hope' },
'YHZ': { 'latitude':'44.880833', 'longitude': '-63.508611', 'name':'Halifax International' },
'YHY': { 'latitude':'60.85', 'longitude': '-115.766667', 'name':'Hay River' },
'YHR': { 'latitude':'50.5', 'longitude': '-59.5', 'name':'Chevery' },
'YHS': { 'latitude':'49.466667', 'longitude': '-123.75', 'name':'Sechelt' },
'YHP': { 'latitude':'52.083333', 'longitude': '-94.3', 'name':'Poplar Hill' },
'YHT': { 'latitude':'60.75', 'longitude': '-137.5', 'name':'Haines Junction' },
'YHU': { 'latitude':'45.5', 'longitude': '-73.6', 'name':'Montreal St Hubert' },
'SVU': { 'latitude':'-16.766667', 'longitude': '179.383333', 'name':'Savusavu' },
'TDZ': { 'latitude':'6.533333', 'longitude': '-75.783333', 'name':'Toledo' },
'VTA': { 'latitude':'14.933333', 'longitude': '-87.25', 'name':'Victoria' },
'WBU': { 'latitude':'40.033333', 'longitude': '-105.233333', 'name':'Municipal' },
'WBR': { 'latitude':'43.716667', 'longitude': '-85.5', 'name':'Big Rapids' },
'TLR': { 'latitude':'39.156389', 'longitude': '-119.326111', 'name':'Mefford Field' },
'WBG': { 'latitude':'51.25', 'longitude': '13.016667', 'name':'Schleswig-jagel' },
'WBD': { 'latitude':'-15.2', 'longitude': '48.483333', 'name':'Befandriana' },
'TLP': { 'latitude':'-4.783333', 'longitude': '141.0', 'name':'Tumolbil' },
'WBB': { 'latitude':'63.5', 'longitude': '-162.266667', 'name':'Stebbins' },
'WBA': { 'latitude':'-10.3', 'longitude': '142.683333', 'name':'Wahai' },
'WBN': { 'latitude':'42.466667', 'longitude': '-71.15', 'name':'Cummings Park' },
'VTE': { 'latitude':'17.983333', 'longitude': '102.566667', 'name':'Wattay' },
'WBM': { 'latitude':'-5.566667', 'longitude': '143.716667', 'name':'Wapenamanda' },
'TLV': { 'latitude':'32.014167', 'longitude': '34.886667', 'name':'Ben Gurion Intl' },
'TLU': { 'latitude':'9.5', 'longitude': '-75.533333', 'name':'Tolu' },
'TDX': { 'latitude':'12.268056', 'longitude': '102.316667', 'name':'Trat' },
'TLZ': { 'latitude':'-18.166667', 'longitude': '-47.95', 'name':'Catalao' },
'TLX': { 'latitude':'12.233333', 'longitude': '38.533333', 'name':'Talca' },
'VTN': { 'latitude':'42.85', 'longitude': '-100.55', 'name':'Miller Field' },
'UHE': { 'latitude':'49.041667', 'longitude': '17.45', 'name':'Kunovice' },
'MKQ': { 'latitude':'-8.516667', 'longitude': '140.5', 'name':'Mopah' },
'TLA': { 'latitude':'65.240278', 'longitude': '-166.339444', 'name':'Teller' },
'TLG': { 'latitude':'-9.1', 'longitude': '160.15', 'name':'Tulagi Island' },
'TLD': { 'latitude':'-22.833333', 'longitude': '28.0', 'name':'Limpopo Valley' },
'TLJ': { 'latitude':'62.885278', 'longitude': '-155.968056', 'name':'Tatalina' },
'VTZ': { 'latitude':'17.716667', 'longitude': '83.216667', 'name':'Vishakhapatnam' },
'ZAO': { 'latitude':'44.333333', 'longitude': '1.483333', 'name':'Laberandie' },
'ZAL': { 'latitude':'-39.766667', 'longitude': '-73.233333', 'name':'Pichoy' },
'ZAM': { 'latitude':'6.933333', 'longitude': '122.066667', 'name':'Zamboanga International' },
'ZAJ': { 'latitude':'31.1', 'longitude': '61.883333', 'name':'Zaranj' },
'ZAH': { 'latitude':'29.466667', 'longitude': '60.883333', 'name':'Zahedan' },
'ZAG': { 'latitude':'45.733333', 'longitude': '16.066667', 'name':'Pleso' },
'ZAD': { 'latitude':'44.097778', 'longitude': '15.356667', 'name':'Zadar' },
'ZAC': { 'latitude':'56.083333', 'longitude': '-96.083333', 'name':'York Landing' },
'ZAA': { 'latitude':'55.483333', 'longitude': '-129.483333', 'name':'Alice Arm' },
'ZAZ': { 'latitude':'41.666667', 'longitude': '-1.019444', 'name':'Zaragoza' },
'ZAX': { 'latitude':'25.083333', 'longitude': '119.05', 'name':'Pan Yu Ferry' },
'ZAY': { 'latitude':'51.216667', 'longitude': '4.416667', 'name':'De Keyserlei Bus Stn.' },
'ZAT': { 'latitude':'27.316667', 'longitude': '103.8', 'name':'Zhaotong' },
'ZAU': { 'latitude':'52.6', 'longitude': '14.466667', 'name':'Sachsen Railway Stn.' },
'ZAR': { 'latitude':'11.133333', 'longitude': '7.683333', 'name':'Zaria' },
'ZAS': { 'latitude':'22.840833', 'longitude': '113.245278', 'name':'Shunde Ferry' },
'JUB': { 'latitude':'4.871944', 'longitude': '31.601111', 'name':'Juba' },
'JUJ': { 'latitude':'-24.233333', 'longitude': '-65.266667', 'name':'El Cadillal' },
'JUI': { 'latitude':'53.683333', 'longitude': '7.0', 'name':'Juist' },
'JUN': { 'latitude':'-24.8', 'longitude': '143.033333', 'name':'Jundah' },
'JUO': { 'latitude':'6.516667', 'longitude': '-76.6', 'name':'Jurado' },
'JUL': { 'latitude':'-15.483333', 'longitude': '-70.15', 'name':'Juliaca' },
'JUM': { 'latitude':'29.283333', 'longitude': '82.183333', 'name':'Jumla' },
'JUR': { 'latitude':'-30.269722', 'longitude': '115.05', 'name':'Jurien Bay' },
'JUP': { 'latitude':'-32.266667', 'longitude': '27.183333', 'name':'Cable Heliport' },
'JUV': { 'latitude':'72.8', 'longitude': '-56.15', 'name':'Heliport' },
'JUT': { 'latitude':'14.8', 'longitude': '-86.133333', 'name':'Juticalpa' },
'JUZ': { 'latitude':'28.966667', 'longitude': '118.833333', 'name':'Juzhou' },
'GWE': { 'latitude':'-19.45', 'longitude': '29.816667', 'name':'Gweru' },
'GWD': { 'latitude':'25.230556', 'longitude': '62.338889', 'name':'Gwadar' },
'TMR': { 'latitude':'22.814722', 'longitude': '5.459167', 'name':'Tamanrasset' },
'TMS': { 'latitude':'0.38', 'longitude': '6.720833', 'name':'Sao Tome Is' },
'GWA': { 'latitude':'17.833333', 'longitude': '94.5', 'name':'Gwa' },
'TMU': { 'latitude':'9.733056', 'longitude': '-85.016667', 'name':'Tambor' },
'TMW': { 'latitude':'-31.068611', 'longitude': '150.845556', 'name':'Tamworth Regional Airport' },
'TMX': { 'latitude':'29.233333', 'longitude': '0.283333', 'name':'Timimoun' },
'GWL': { 'latitude':'26.283333', 'longitude': '78.233333', 'name':'Gwalior' },
'GWO': { 'latitude':'33.5', 'longitude': '-90.2', 'name':'Leflore' },
'GWN': { 'latitude':'-6.566667', 'longitude': '146.25', 'name':'Gnarowein' },
'GWT': { 'latitude':'54.916667', 'longitude': '8.35', 'name':'Westerland - Sylt' },
'GWW': { 'latitude':'52.474444', 'longitude': '13.138056', 'name':'Raf Gatow' },
'GWV': { 'latitude':'-17.360556', 'longitude': '31.059722', 'name':'Glendale' },
'TMD': { 'latitude':'16.25', 'longitude': '-8.166667', 'name':'Timbedra' },
'TME': { 'latitude':'6.5', 'longitude': '-71.766667', 'name':'Tame' },
'GWS': { 'latitude':'-32.6', 'longitude': '27.55', 'name':'Glenwood Springs' },
'TMG': { 'latitude':'5.402778', 'longitude': '118.658333', 'name':'Tomanggong' },
'TMH': { 'latitude':'40.0', 'longitude': '104.65', 'name':'Tanahmerah' },
'TMI': { 'latitude':'27.3', 'longitude': '87.2', 'name':'Tumling Tar' },
'TMJ': { 'latitude':'37.224167', 'longitude': '67.278333', 'name':'Termez' },
'GWY': { 'latitude':'53.283333', 'longitude': '-9.033333', 'name':'Carnmore' },
'TMM': { 'latitude':'-18.1', 'longitude': '49.4', 'name':'Tamatave' },
'TMN': { 'latitude':'-2.5', 'longitude': '175.983333', 'name':'Tamana Island' },
'TMO': { 'latitude':'7.233333', 'longitude': '-61.516667', 'name':'Tumeremo' },
'HWN': { 'latitude':'-18.366667', 'longitude': '26.516667', 'name':'Hwange Nat Park' },
'HWO': { 'latitude':'26.001389', 'longitude': '-80.240556', 'name':'North Perry' },
'NJA': { 'latitude':'35.454722', 'longitude': '139.450278', 'name':'Atsugi NAS' },
'NJF': { 'latitude':'31.991667', 'longitude': '44.404167', 'name':'Najaf' },
'HWI': { 'latitude':'58.116667', 'longitude': '-134.733333', 'name':'SPB' },
'NJK': { 'latitude':'32.829167', 'longitude': '-115.671667', 'name':'El Centro NAF' },
'HWD': { 'latitude':'37.666667', 'longitude': '-122.083333', 'name':'Air Terminal' },
'WBQ': { 'latitude':'66.35', 'longitude': '-147.4', 'name':'Beaver' },
'HWA': { 'latitude':'-7.433333', 'longitude': '145.966667', 'name':'Hawabango' },
'WBE': { 'latitude':'-14.533333', 'longitude': '48.7', 'name':'Bealanana' },
'EIS': { 'latitude':'18.443889', 'longitude': '-64.542778', 'name':'Beef Island' },
'RCY': { 'latitude':'23.65', 'longitude': '-74.85', 'name':'Rum Cay' },
'XAY': { 'latitude':'18.666667', 'longitude': '104.716667', 'name':'Xayabury' },
'EIY': { 'latitude':'30.621667', 'longitude': '35.203333', 'name':'Ein Yahav' },
'RCU': { 'latitude':'-33.1', 'longitude': '-64.266667', 'name':'Rio Cuarto' },
'RCP': { 'latitude':'57.083056', 'longitude': '-157.805556', 'name':'Cinder River' },
'RCQ': { 'latitude':'-29.183333', 'longitude': '-59.7', 'name':'Reconquista' },
'RCR': { 'latitude':'49.916667', 'longitude': '-0.966667', 'name':'Fulton County' },
'RCS': { 'latitude':'51.35', 'longitude': '0.5', 'name':'Rochester' },
'EIA': { 'latitude':'-8.2', 'longitude': '147.85', 'name':'Popondetta' },
'RCM': { 'latitude':'-20.716944', 'longitude': '143.116667', 'name':'Richmond' },
'RCN': { 'latitude':'-35.783333', 'longitude': '137.783333', 'name':'American River' },
'EIB': { 'latitude':'52.15', 'longitude': '14.666667', 'name':'Eisenach' },
'EIE': { 'latitude':'58.466667', 'longitude': '92.116667', 'name':'Eniseysk' },
'RCK': { 'latitude':'30.65', 'longitude': '-97.0', 'name':'Coffield' },
'EIH': { 'latitude':'-18.5', 'longitude': '144.1', 'name':'Einasleigh' },
'EIK': { 'latitude':'40.010225', 'longitude': '-105.047975', 'name':'Erie Municipal Airport' },
'EIL': { 'latitude':'64.665556', 'longitude': '-147.101389', 'name':'Eielson AFB' },
'RCB': { 'latitude':'-28.741111', 'longitude': '32.092222', 'name':'Richards Bay' },
'EIN': { 'latitude':'51.45', 'longitude': '5.374444', 'name':'Eindhoven' },
'FAZ': { 'latitude':'29.0', 'longitude': '54.333333', 'name':'Fasa' },
'FAY': { 'latitude':'35.0', 'longitude': '-78.883333', 'name':'Municipal' },
'FAR': { 'latitude':'46.916667', 'longitude': '-96.816667', 'name':'Hector Field' },
'FAS': { 'latitude':'64.916667', 'longitude': '-14.066667', 'name':'Faskrudsfjordur' },
'FAQ': { 'latitude':'-5.166667', 'longitude': '145.816667', 'name':'Freida River' },
'FAV': { 'latitude':'-16.333333', 'longitude': '-145.616667', 'name':'Fakarava' },
'FAT': { 'latitude':'36.766667', 'longitude': '-119.716667', 'name':'Fresno Air Terminal Airport' },
'FAJ': { 'latitude':'18.308056', 'longitude': '-65.661944', 'name':'Diego Jimenez Torres' },
'FAK': { 'latitude':'57.530556', 'longitude': '-135.216667', 'name':'False Island' },
'FAH': { 'latitude':'32.366667', 'longitude': '62.166667', 'name':'Farah' },
'FAI': { 'latitude':'64.816667', 'longitude': '-147.866667', 'name':'Fairbanks International Airport' },
'FAN': { 'latitude':'58.1', 'longitude': '6.633333', 'name':'Lista' },
'FAO': { 'latitude':'37.014444', 'longitude': '-7.965833', 'name':'Faro' },
'FAL': { 'latitude':'26.586111', 'longitude': '-99.1375', 'name':'Falcon State' },
'FAM': { 'latitude':'37.673333', 'longitude': '-90.233889', 'name':'Regional' },
'FAB': { 'latitude':'51.266667', 'longitude': '-0.733333', 'name':'Farnborough' },
'FAC': { 'latitude':'-16.683333', 'longitude': '-145.333333', 'name':'Faaite' },
'FAA': { 'latitude':'10.033333', 'longitude': '-10.75', 'name':'Faranah' },
'FAF': { 'latitude':'19.833333', 'longitude': '-72.5', 'name':'Felker AAF' },
'FAG': { 'latitude':'63.883333', 'longitude': '-16.65', 'name':'Fagurholsmyri' },
'FAE': { 'latitude':'62.063611', 'longitude': '-7.276944', 'name':'Vagar' },
'UCT': { 'latitude':'63.566667', 'longitude': '53.8', 'name':'Ukhta' },
'OAG': { 'latitude':'-33.383611', 'longitude': '149.133611', 'name':'Springhill' },
'CCY': { 'latitude':'43.066667', 'longitude': '-92.666667', 'name':'Municipal' },
'CCX': { 'latitude':'-16.043611', 'longitude': '-57.63', 'name':'Caceres' },
'CCZ': { 'latitude':'25.416667', 'longitude': '-77.883333', 'name':'Chub Cay' },
'CCU': { 'latitude':'22.633333', 'longitude': '88.433333', 'name':'Netaji Subhas Chandra' },
'CCT': { 'latitude':'-37.85', 'longitude': '-67.866667', 'name':'Colonia Catriel' },
'CCW': { 'latitude':'-33.666667', 'longitude': '136.9', 'name':'Cowell' },
'CCV': { 'latitude':'-16.2', 'longitude': '167.5', 'name':'Craig Cove' },
'CCQ': { 'latitude':'-12.6', 'longitude': '-38.966667', 'name':'Cachoeira' },
'CCP': { 'latitude':'-36.79', 'longitude': '-73.084444', 'name':'Carriel Sur' },
'CCS': { 'latitude':'10.603056', 'longitude': '-66.990556', 'name':'Simon Bolivar International Airport' },
'CCR': { 'latitude':'37.983333', 'longitude': '-122.052778', 'name':'Buchanan Fld' },
'CCM': { 'latitude':'-28.7', 'longitude': '-49.366667', 'name':'Criciuma' },
'CCL': { 'latitude':'-26.783333', 'longitude': '150.616667', 'name':'Chinchilla' },
'CCO': { 'latitude':'4.566667', 'longitude': '-71.333333', 'name':'Carimagua' },
'CCN': { 'latitude':'34.533333', 'longitude': '65.266667', 'name':'Chakcharan' },
'CCI': { 'latitude':'-27.25', 'longitude': '-52.033333', 'name':'Concordia' },
'CCH': { 'latitude':'-46.55', 'longitude': '-71.7', 'name':'Chile Chico' },
'CCK': { 'latitude':'-12.183333', 'longitude': '96.833333', 'name':'Cocos Islands' },
'CCJ': { 'latitude':'11.136944', 'longitude': '75.955278', 'name':'Kozhikode Airport' },
'CCG': { 'latitude':'31.4', 'longitude': '-102.35', 'name':'Crane County Arpt' },
'CCF': { 'latitude':'43.216667', 'longitude': '2.316667', 'name':'Salvaza' },
'CCA': { 'latitude':'19.833333', 'longitude': '-72.5', 'name':'Chaffee AFB' },
'CCC': { 'latitude':'22.513333', 'longitude': '-78.510833', 'name':'Cayo Coco' },
'CCB': { 'latitude':'34.111667', 'longitude': '-117.6875', 'name':'Cable Airport' },
'PIH': { 'latitude':'42.916667', 'longitude': '-112.583333', 'name':'Pocatello' },
'PII': { 'latitude':'64.85', 'longitude': '-147.783333', 'name':'Phillips Field' },
'PIK': { 'latitude':'55.509444', 'longitude': '-4.586667', 'name':'Prestwick' },
'PIL': { 'latitude':'-26.85', 'longitude': '-58.316667', 'name':'Pilar' },
'PIM': { 'latitude':'32.833333', 'longitude': '-84.85', 'name':'Garden Harris County' },
'PIN': { 'latitude':'-2.633333', 'longitude': '-56.733333', 'name':'Parintins' },
'PIO': { 'latitude':'-13.745', 'longitude': '-76.220278', 'name':'Pisco' },
'PIA': { 'latitude':'40.666667', 'longitude': '-89.683333', 'name':'Greater Peoria' },
'PIB': { 'latitude':'31.467222', 'longitude': '-89.336944', 'name':'Hattiesburg-Laurel Regional' },
'PIC': { 'latitude':'21.916667', 'longitude': '-71.983333', 'name':'Pine Cay' },
'PID': { 'latitude':'25.083333', 'longitude': '-77.3', 'name':'Paradise Island' },
'PIE': { 'latitude':'27.910556', 'longitude': '-82.6875', 'name':'St. Petersburg-Clearwater International' },
'PIF': { 'latitude':'22.666667', 'longitude': '120.483333', 'name':'Pingtung' },
'PIG': { 'latitude':'0.783611', 'longitude': '-60.078611', 'name':'Pitinga' },
'PIX': { 'latitude':'38.466667', 'longitude': '-28.333333', 'name':'Pico Island' },
'PIZ': { 'latitude':'69.733333', 'longitude': '-163.016667', 'name':'Dew Station' },
'PIP': { 'latitude':'57.580278', 'longitude': '-157.571944', 'name':'Pilot Point' },
'PIQ': { 'latitude':'5.333333', 'longitude': '-60.333333', 'name':'Pipillipai' },
'PIR': { 'latitude':'44.383333', 'longitude': '-100.283333', 'name':'Pierre' },
'PIS': { 'latitude':'46.583333', 'longitude': '0.3', 'name':'Biard' },
'PIT': { 'latitude':'40.491389', 'longitude': '-80.232778', 'name':'Pittsburgh International' },
'PIU': { 'latitude':'-5.2', 'longitude': '-80.616667', 'name':'Piura' },
'PIV': { 'latitude':'-23.4', 'longitude': '-47.0', 'name':'Pirapora' },
'PIW': { 'latitude':'55.583333', 'longitude': '-97.15', 'name':'Pikwitonei' },
'BVR': { 'latitude':'-31.666667', 'longitude': '-56.583333', 'name':'Esperadinha' },
'TJA': { 'latitude':'-21.555833', 'longitude': '-64.701389', 'name':'Tarija' },
'UBT': { 'latitude':'-23.433333', 'longitude': '-45.066667', 'name':'Ubatuba' },
'UBU': { 'latitude':'-14.416667', 'longitude': '126.666667', 'name':'Kalumburu' },
'UBP': { 'latitude':'15.251389', 'longitude': '104.870278', 'name':'Muang Ubon' },
'UBR': { 'latitude':'-3.733333', 'longitude': '140.8', 'name':'Ubrub' },
'UBS': { 'latitude':'33.449722', 'longitude': '-88.365833', 'name':'Lowndes County' },
'UBA': { 'latitude':'-19.75', 'longitude': '-47.95', 'name':'Uberaba' },
'UBB': { 'latitude':'-9.95', 'longitude': '142.183333', 'name':'Mabuiag Island' },
'UBI': { 'latitude':'-6.716667', 'longitude': '155.7', 'name':'Buin' },
'UBJ': { 'latitude':'33.966667', 'longitude': '131.341667', 'name':'Ube' },
'MWS': { 'latitude':'51.916667', 'longitude': '-2.866667', 'name':'Mount Wilson' },
'MWQ': { 'latitude':'20.165556', 'longitude': '94.941111', 'name':'Magwe' },
'MWV': { 'latitude':'5.516667', 'longitude': '72.866667', 'name':'Mundulkiri' },
'MWU': { 'latitude':'-1.5', 'longitude': '149.666667', 'name':'Mussau' },
'MWT': { 'latitude':'-29.916667', 'longitude': '139.716667', 'name':'Moolawatana' },
'MWZ': { 'latitude':'-2.45', 'longitude': '32.933333', 'name':'Mwanza' },
'GJT': { 'latitude':'39.116667', 'longitude': '-108.516667', 'name':'Walker Field' },
'MWX': { 'latitude':'35.1667', 'longitude': '126.9167', 'name':'Gwangju Muan International' },
'GJR': { 'latitude':'65.983333', 'longitude': '-21.35', 'name':'Gjogur' },
'MWC': { 'latitude':'43.110278', 'longitude': '-88.034167', 'name':'Lawrence J Timmerman' },
'MWB': { 'latitude':'-29.204167', 'longitude': '116.0225', 'name':'Morawa' },
'MWA': { 'latitude':'37.752778', 'longitude': '-89.016667', 'name':'Williamson County' },
'GJM': { 'latitude':'-10.833333', 'longitude': '-65.333333', 'name':'Guajara-Mirim' },
'MWG': { 'latitude':'-6.966667', 'longitude': '145.9', 'name':'Marawaka' },
'MWF': { 'latitude':'-15.0', 'longitude': '168.083333', 'name':'Maewo' },
'MWE': { 'latitude':'18.45', 'longitude': '31.833333', 'name':'Merowe' },
'MWD': { 'latitude':'32.563056', 'longitude': '71.570556', 'name':'Mianwali' },
'MWK': { 'latitude':'3.348056', 'longitude': '106.258056', 'name':'Matak' },
'MWJ': { 'latitude':'6.55', 'longitude': '-59.9', 'name':'Matthews Ridge' },
'MWI': { 'latitude':'-5.15', 'longitude': '143.483333', 'name':'Maramuni' },
'MWH': { 'latitude':'47.095', 'longitude': '-119.261389', 'name':'Grant County' },
'MWO': { 'latitude':'39.531111', 'longitude': '-84.395278', 'name':'Hook Field' },
'MWN': { 'latitude':'-3.5', 'longitude': '33.616667', 'name':'Mwadui' },
'MWM': { 'latitude':'43.913333', 'longitude': '-95.109444', 'name':'Windom Municipal' },
'MWL': { 'latitude':'32.783333', 'longitude': '-98.066667', 'name':'Mineral Wells Arpt' },
'NWT': { 'latitude':'-8.5', 'longitude': '143.166667', 'name':'Nowata' },
'AMH': { 'latitude':'6.0', 'longitude': '37.508333', 'name':'Arba Mintch' },
'AMK': { 'latitude':'14.466667', 'longitude': '-87.85', 'name':'Animas Airpark' },
'AMJ': { 'latitude':'-16.183333', 'longitude': '-40.683333', 'name':'Almenara' },
'AMM': { 'latitude':'31.966667', 'longitude': '35.983333', 'name':'Queen Alia Intl' },
'AML': { 'latitude':'8.3', 'longitude': '-82.866667', 'name':'Puerto Armuellas' },
'AMO': { 'latitude':'14.116667', 'longitude': '15.316667', 'name':'Mao' },
'AMN': { 'latitude':'43.383333', 'longitude': '-84.65', 'name':'Gratiot Community' },
'AMA': { 'latitude':'35.226389', 'longitude': '-101.705833', 'name':'Rick Husband Amarillo International' },
'AMC': { 'latitude':'11.033333', 'longitude': '20.266667', 'name':'Am Timan' },
'AMB': { 'latitude':'-13.183333', 'longitude': '48.983333', 'name':'Ambilobe' },
'AME': { 'latitude':'-15.65', 'longitude': '37.683333', 'name':'Alto Molocue' },
'AMD': { 'latitude':'23.077222', 'longitude': '72.634722', 'name':'Ahmedabad' },
'AMG': { 'latitude':'-4.6', 'longitude': '143.5', 'name':'Amboin' },
'AMF': { 'latitude':'-4.166667', 'longitude': '141.666667', 'name':'Ama' },
'AMY': { 'latitude':'-17.683333', 'longitude': '45.666667', 'name':'Ambatomainty' },
'AMX': { 'latitude':'-21.74', 'longitude': '135.24', 'name':'Ammaroo' },
'AMZ': { 'latitude':'-37.029722', 'longitude': '174.973333', 'name':'Ardmore' },
'NWA': { 'latitude':'-12.283333', 'longitude': '43.766667', 'name':'Moheli' },
'AMQ': { 'latitude':'-2.3', 'longitude': '128.083333', 'name':'Ambon' },
'AMP': { 'latitude':'-24.7', 'longitude': '44.733333', 'name':'Ampanihy' },
'AMS': { 'latitude':'52.308611', 'longitude': '4.763889', 'name':'Amsterdam-Schiphol' },
'AMR': { 'latitude':'7.083333', 'longitude': '171.683333', 'name':'Arno' },
'AMU': { 'latitude':'-3.516667', 'longitude': '141.25', 'name':'Amanab' },
'AMT': { 'latitude':'-26.2', 'longitude': '131.116667', 'name':'Amata' },
'AMW': { 'latitude':'42.0', 'longitude': '-93.616667', 'name':'Ames' },
'AMV': { 'latitude':'69.766667', 'longitude': '61.55', 'name':'Amderma' },
'RBR': { 'latitude':'-10.0', 'longitude': '-67.816667', 'name':'Pres. Medici' },
'TJG': { 'latitude':'-0.3', 'longitude': '100.6', 'name':'Tanjung Warukin' },
'KUY': { 'latitude':'57.634444', 'longitude': '-153.998333', 'name':'Kamusi Airport' },
'KUX': { 'latitude':'38.471667', 'longitude': '126.0375', 'name':'Kuyol' },
'KUW': { 'latitude':'-7.433333', 'longitude': '143.1', 'name':'Kugururok River' },
'KUV': { 'latitude':'35.9', 'longitude': '126.616667', 'name':'Gunsan' },
'KUU': { 'latitude':'31.876667', 'longitude': '77.154444', 'name':'Kullu Manali' },
'KUT': { 'latitude':'42.176667', 'longitude': '42.4825', 'name':'Kopitnari' },
'KUS': { 'latitude':'65.566667', 'longitude': '-37.116667', 'name':'Kulusuk' },
'KUR': { 'latitude':'38.4', 'longitude': '71.116667', 'name':'Kuran-O-Munjan' },
'KUQ': { 'latitude':'-7.133333', 'longitude': '143.266667', 'name':'Kuri' },
'KUP': { 'latitude':'-10.066667', 'longitude': '148.216667', 'name':'Kupiano' },
'KUO': { 'latitude':'63.016667', 'longitude': '27.8', 'name':'Kuopio' },
'KUN': { 'latitude':'54.963919', 'longitude': '24.084778', 'name':'Kaunas' },
'KUM': { 'latitude':'30.333333', 'longitude': '130.633333', 'name':'Yakushima' },
'KUL': { 'latitude':'2.745556', 'longitude': '101.71', 'name':'Kuala Lumpur International Airport' },
'KUK': { 'latitude':'60.866667', 'longitude': '-162.533333', 'name':'Kasigluk' },
'KUJ': { 'latitude':'33.433333', 'longitude': '135.783333', 'name':'Kushimoto' },
'KUI': { 'latitude':'-36.466667', 'longitude': '174.833333', 'name':'Kawau Island' },
'KUH': { 'latitude':'43.033333', 'longitude': '144.2', 'name':'Kushiro' },
'KUG': { 'latitude':'-10.25', 'longitude': '142.216667', 'name':'Kubin Island' },
'KUF': { 'latitude':'53.504722', 'longitude': '50.164444', 'name':'Kurumoch' },
'KUE': { 'latitude':'-8.016667', 'longitude': '156.95', 'name':'Kukundu' },
'KUD': { 'latitude':'6.916667', 'longitude': '116.833333', 'name':'Kudat' },
'KUC': { 'latitude':'0.233333', 'longitude': '173.416667', 'name':'Kuria' },
'KUA': { 'latitude':'3.766667', 'longitude': '103.2', 'name':'Kuantan' },
'TJI': { 'latitude':'4.25', 'longitude': '-76.333333', 'name':'Capiro' },
'TJH': { 'latitude':'35.512778', 'longitude': '134.786944', 'name':'Tajima' },
'TJK': { 'latitude':'40.302222', 'longitude': '36.367778', 'name':'Tokat' },
'YNL': { 'latitude':'58.275', 'longitude': '-104.081111', 'name':'Points North Landing' },
'YNM': { 'latitude':'49.766667', 'longitude': '-77.8', 'name':'Matagami' },
'YNN': { 'latitude':'-21.416667', 'longitude': '120.166667', 'name':'Yandi' },
'YNO': { 'latitude':'52.5', 'longitude': '-92.416667', 'name':'North Spirit Lake' },
'YNI': { 'latitude':'53.197222', 'longitude': '-70.908333', 'name':'Nitchequon' },
'YNJ': { 'latitude':'42.882778', 'longitude': '129.451389', 'name':'Yanji' },
'YNK': { 'latitude':'50.083333', 'longitude': '-125.916667', 'name':'Nootka Sound' },
'YND': { 'latitude':'45.521389', 'longitude': '-75.563611', 'name':'Executive Gatineau-Ottawa' },
'YNE': { 'latitude':'53.983333', 'longitude': '-97.8', 'name':'Norway House' },
'YNF': { 'latitude':'48.946944', 'longitude': '-57.943889', 'name':'Deer Lake/Stephenville' },
'YNG': { 'latitude':'41.266667', 'longitude': '-80.666667', 'name':'Youngstown' },
'YNA': { 'latitude':'50.183333', 'longitude': '-61.783333', 'name':'Natashquan' },
'YNB': { 'latitude':'24.083333', 'longitude': '38.05', 'name':'Yanbu' },
'YNC': { 'latitude':'52.997222', 'longitude': '-78.833333', 'name':'Wemindji' },
'YNY': { 'latitude':'38.073889', 'longitude': '128.621111', 'name':'Yangyang' },
'YNZ': { 'latitude':'33.385556', 'longitude': '120.125278', 'name':'Yancheng' },
'YNT': { 'latitude':'37.401667', 'longitude': '121.371667', 'name':'Yantai' },
'YNP': { 'latitude':'55.912778', 'longitude': '-61.185278', 'name':'Natuashish' },
'YNR': { 'latitude':'50.836111', 'longitude': '-96.957222', 'name':'Arnes' },
'YNS': { 'latitude':'49.741667', 'longitude': '-76.741667', 'name':'Nemiscau' },
'TJM': { 'latitude':'57.189567', 'longitude': '65.3243', 'name':'Tyumen' },
'THZ': { 'latitude':'10.85', 'longitude': '15.35', 'name':'Tahoua' },
'WLR': { 'latitude':'55.6', 'longitude': '-131.566667', 'name':'Loring' },
'WLS': { 'latitude':'-13.3', 'longitude': '-176.166667', 'name':'Wallis Island' },
'TJN': { 'latitude':'-15.850556', 'longitude': '-142.266944', 'name':'Takume' },
'WLH': { 'latitude':'-15.416667', 'longitude': '167.7', 'name':'Walaha' },
'WLK': { 'latitude':'66.6', 'longitude': '-159.983333', 'name':'Selawik' },
'WLL': { 'latitude':'-17.216667', 'longitude': '137.916667', 'name':'Wollogorang' },
'WLM': { 'latitude':'42.385278', 'longitude': '-71.251389', 'name':'Waltham' },
'WLN': { 'latitude':'55.866667', 'longitude': '-133.216667', 'name':'Little Naukati' },
'WLO': { 'latitude':'-16.633333', 'longitude': '129.316667', 'name':'Waterloo' },
'WLA': { 'latitude':'-19.766667', 'longitude': '120.65', 'name':'Wallal' },
'WLB': { 'latitude':'56.291667', 'longitude': '-133.658333', 'name':'Labouchere Bay' },
'WLC': { 'latitude':'-30.983333', 'longitude': '151.6', 'name':'Walcha' },
'WLD': { 'latitude':'37.166667', 'longitude': '-97.05', 'name':'Arkansas City' },
'WLG': { 'latitude':'-41.327222', 'longitude': '174.805278', 'name':'Wellington International' },
'PUF': { 'latitude':'43.38', 'longitude': '-0.418611', 'name':'Pau-Pyrénées' },
'PUZ': { 'latitude':'14.047222', 'longitude': '-83.386667', 'name':'Puerto Cabezas' },
'GJA': { 'latitude':'16.5', 'longitude': '-85.925', 'name':'Guanaja' },
'JSD': { 'latitude':'41.249167', 'longitude': '-73.096667', 'name':'Sikorsky Heliport' },
'JSG': { 'latitude':'8.45', 'longitude': '-73.916667', 'name':'San Rafael H/P' },
'JSA': { 'latitude':'26.866667', 'longitude': '70.916667', 'name':'Jaisalmer' },
'JSL': { 'latitude':'39.360556', 'longitude': '-74.420833', 'name':'Steel Pier Hlpt' },
'JSM': { 'latitude':'-44.033333', 'longitude': '-70.466667', 'name':'Jose De San Martin' },
'JSO': { 'latitude':'59.2', 'longitude': '17.616667', 'name':'Sodertalje Heliport' },
'JSH': { 'latitude':'35.7', 'longitude': '26.195278', 'name':'Sitia' },
'JSI': { 'latitude':'39.168611', 'longitude': '23.500833', 'name':'Skiathos' },
'JSK': { 'latitude':'18.766667', 'longitude': '-72.066667', 'name':'Municipal Heliport' },
'JST': { 'latitude':'40.316667', 'longitude': '-78.833333', 'name':'Cambria County' },
'JSU': { 'latitude':'65.4', 'longitude': '-52.866667', 'name':'Heliport' },
'JSP': { 'latitude':'8.416667', 'longitude': '39.633333', 'name':'Seogwipo Heliport' },
'JSR': { 'latitude':'23.183333', 'longitude': '89.166667', 'name':'Jessore' },
'JSS': { 'latitude':'37.333333', 'longitude': '23.25', 'name':'Spetsai Island' },
'JSY': { 'latitude':'37.422778', 'longitude': '24.950833', 'name':'Syros Island' },
'XHN': { 'latitude':'50.633333', 'longitude': '5.566667', 'name':'Guillemins, Raiway Stn' },
'TOZ': { 'latitude':'9.3', 'longitude': '-6.916667', 'name':'Touba' },
'TOX': { 'latitude':'58.133333', 'longitude': '68.233333', 'name':'Tobolsk' },
'TOY': { 'latitude':'36.648333', 'longitude': '137.1875', 'name':'Toyama' },
'GQJ': { 'latitude':'55.783333', 'longitude': '-6.466667', 'name':'RAF Station' },
'TOR': { 'latitude':'51.8', 'longitude': '-1.6', 'name':'Municipal' },
'TOS': { 'latitude':'69.681389', 'longitude': '18.917778', 'name':'Tromso/langnes' },
'TOP': { 'latitude':'-13.35', 'longitude': '32.766667', 'name':'Philip Billard' },
'TOQ': { 'latitude':'-22.083333', 'longitude': '-70.2', 'name':'Barriles' },
'TOV': { 'latitude':'18.45', 'longitude': '-64.6', 'name':'West End SPB' },
'TOW': { 'latitude':'-5.883333', 'longitude': '-73.116667', 'name':'Toledo' },
'TOU': { 'latitude':'-20.35', 'longitude': '164.266667', 'name':'Touho' },
'TOJ': { 'latitude':'40.496667', 'longitude': '-3.445833', 'name':'Torrejon Afb' },
'TOK': { 'latitude':'-6.233333', 'longitude': '155.05', 'name':'Torokina' },
'TOH': { 'latitude':'-13.166667', 'longitude': '166.75', 'name':'Torres' },
'TOI': { 'latitude':'54.912778', 'longitude': '70.348056', 'name':'Municipal' },
'TON': { 'latitude':'40.65', 'longitude': '36.433333', 'name':'Tonu' },
'TOO': { 'latitude':'42.283333', 'longitude': '13.283333', 'name':'San Vito' },
'TOL': { 'latitude':'41.586944', 'longitude': '-83.807778', 'name':'Toledo Express' },
'TOM': { 'latitude':'16.766667', 'longitude': '-3.016667', 'name':'Tombouctou' },
'TOB': { 'latitude':'32.083611', 'longitude': '23.976389', 'name':'Tobruk' },
'TOC': { 'latitude':'42.216667', 'longitude': '13.9', 'name':'Toccoa' },
'TOA': { 'latitude':'33.805', 'longitude': '-118.343889', 'name':'Torrance Airport' },
'TOF': { 'latitude':'56.383333', 'longitude': '85.2', 'name':'Tomsk' },
'TOG': { 'latitude':'59.056667', 'longitude': '-160.382222', 'name':'Togiak Village' },
'GQQ': { 'latitude':'40.733333', 'longitude': '-82.8', 'name':'Galion' },
'TOE': { 'latitude':'33.666667', 'longitude': '7.716667', 'name':'Tozeur' },
'HIP': { 'latitude':'-21.316667', 'longitude': '138.3', 'name':'Headingly' },
'NHD': { 'latitude':'25.026944', 'longitude': '55.366111', 'name':'Minhad AB' },
'HIR': { 'latitude':'-9.416667', 'longitude': '160.0', 'name':'Henderson Intl' },
'NHF': { 'latitude':'15.35', 'longitude': '35.733333', 'name':'New Halfa' },
'NHA': { 'latitude':'12.233333', 'longitude': '109.183333', 'name':'Nha Trang' },
'HIW': { 'latitude':'34.366944', 'longitude': '132.413889', 'name':'Hiroshima West' },
'HIX': { 'latitude':'-9.75', 'longitude': '-139.0', 'name':'Hiva Oa' },
'NHK': { 'latitude':'38.286111', 'longitude': '-76.411667', 'name':'Patuxent River NAS' },
'NHT': { 'latitude':'51.55', 'longitude': '-0.383333', 'name':'Northolt' },
'HIB': { 'latitude':'47.383333', 'longitude': '-92.833333', 'name':'Chisholm' },
'NHV': { 'latitude':'-8.783333', 'longitude': '-140.166667', 'name':'Nuku Hiva' },
'HID': { 'latitude':'-10.536667', 'longitude': '142.29', 'name':'Horn Island' },
'HIE': { 'latitude':'44.366667', 'longitude': '-71.55', 'name':'Regional' },
'NHS': { 'latitude':'29.55', 'longitude': '66.0', 'name':'Nushki' },
'HIG': { 'latitude':'-16.433333', 'longitude': '143.15', 'name':'Highbury' },
'HIH': { 'latitude':'-20.166667', 'longitude': '148.95', 'name':'Hook Island' },
'HII': { 'latitude':'34.568333', 'longitude': '-114.355278', 'name':'Municipal' },
'HIJ': { 'latitude':'34.436111', 'longitude': '132.919444', 'name':'International' },
'HIK': { 'latitude':'21.316111', 'longitude': '-157.926667', 'name':'Hickam AFB' },
'HIM': { 'latitude':'8.033333', 'longitude': '80.95', 'name':'Hingurakgoda' },
'HIN': { 'latitude':'35.25', 'longitude': '128.383333', 'name':'Sacheon' },
'HIO': { 'latitude':'45.516667', 'longitude': '-122.983333', 'name':'Portland' },
'RDU': { 'latitude':'35.877778', 'longitude': '-78.7875', 'name':'Raleigh-durham International Airport' },
'EGX': { 'latitude':'58.216667', 'longitude': '-157.366667', 'name':'Egegik' },
'EGS': { 'latitude':'65.283333', 'longitude': '-14.4', 'name':'Egilsstadir' },
'EGP': { 'latitude':'28.866667', 'longitude': '-100.533333', 'name':'Maverick Co' },
'EGV': { 'latitude':'45.933333', 'longitude': '-89.266667', 'name':'Eagle River' },
'EGI': { 'latitude':'45.660833', 'longitude': '18.418611', 'name':'Duke Field' },
'EGO': { 'latitude':'50.633333', 'longitude': '36.65', 'name':'Belgorod' },
'EGN': { 'latitude':'13.483333', 'longitude': '22.45', 'name':'Geneina' },
'EGM': { 'latitude':'-8.566667', 'longitude': '157.866667', 'name':'Sege' },
'EGL': { 'latitude':'5.283333', 'longitude': '39.7', 'name':'Neghelli' },
'EGC': { 'latitude':'44.833333', 'longitude': '0.516667', 'name':'Roumanieres' },
'EGA': { 'latitude':'-6.916667', 'longitude': '146.1', 'name':'Engati' },
'EGE': { 'latitude':'39.633333', 'longitude': '-106.916667', 'name':'Eagle County' },
'LBQ': { 'latitude':'-0.716667', 'longitude': '10.233333', 'name':'Lambarene' },
'LBP': { 'latitude':'3.2', 'longitude': '115.4', 'name':'Long Banga' },
'LBS': { 'latitude':'-16.466667', 'longitude': '179.333333', 'name':'Labasa' },
'LBR': { 'latitude':'-7.25', 'longitude': '-64.783333', 'name':'Labrea' },
'LBU': { 'latitude':'5.3', 'longitude': '115.25', 'name':'Labuan' },
'LBT': { 'latitude':'34.6', 'longitude': '-79.066667', 'name':'Lumberton' },
'LBW': { 'latitude':'3.883333', 'longitude': '115.7', 'name':'Long Bawan' },
'LBV': { 'latitude':'0.45', 'longitude': '9.416667', 'name':'Libreville' },
'LBY': { 'latitude':'47.289444', 'longitude': '-2.346389', 'name':'Montoir' },
'FGU': { 'latitude':'-16.05', 'longitude': '-141.833333', 'name':'Fangatau' },
'RAL': { 'latitude':'33.95', 'longitude': '-117.433333', 'name':'Riverside Municipal' },
'LBZ': { 'latitude':'-8.416667', 'longitude': '20.75', 'name':'Lukapa' },
'RAJ': { 'latitude':'22.316667', 'longitude': '70.783333', 'name':'Civil' },
'RAK': { 'latitude':'31.606944', 'longitude': '-8.036389', 'name':'Menara' },
'FGR': { 'latitude':'36.533333', 'longitude': '-4.616667', 'name':'Fuengirola' },
'RAI': { 'latitude':'14.925278', 'longitude': '-23.503056', 'name':'Francisco Mendes' },
'FGL': { 'latitude':'-43.4', 'longitude': '170.033333', 'name':'Fox Glacier' },
'LBC': { 'latitude':'53.8', 'longitude': '10.716667', 'name':'Lübeck Blankensee' },
'LBB': { 'latitude':'33.666667', 'longitude': '-101.833333', 'name':'International' },
'LBE': { 'latitude':'40.283333', 'longitude': '-79.4', 'name':'Westmoreland County' },
'LBD': { 'latitude':'40.216667', 'longitude': '69.7', 'name':'Khudzhand' },
'LBG': { 'latitude':'48.966667', 'longitude': '2.45', 'name':'Le Bourget' },
'LBF': { 'latitude':'41.133333', 'longitude': '-100.7', 'name':'Lee Bird Field' },
'FGD': { 'latitude':'22.5', 'longitude': '-12.675', 'name':'Fderik' },
'LBH': { 'latitude':'33.966667', 'longitude': '151.25', 'name':'Palm Beach SPB' },
'LBK': { 'latitude':'0.4', 'longitude': '40.95', 'name':'Liboi' },
'LBJ': { 'latitude':'-8.516667', 'longitude': '119.883333', 'name':'Mutiara' },
'LBM': { 'latitude':'-18.4', 'longitude': '36.1', 'name':'Luabo' },
'LBL': { 'latitude':'37.05', 'longitude': '-100.966667', 'name':'Municipal' },
'LBO': { 'latitude':'-4.966667', 'longitude': '23.383333', 'name':'Lusambo' },
'LBN': { 'latitude':'0.666667', 'longitude': '36.083333', 'name':'Lake Baringo' },
'BFC': { 'latitude':'-15.9', 'longitude': '145.333333', 'name':'Bloomfield' },
'BFB': { 'latitude':'58.183333', 'longitude': '-152.133333', 'name':'Blue Fox Bay' },
'BFA': { 'latitude':'-20.25', 'longitude': '-58.2', 'name':'Bahia Negra' },
'BFG': { 'latitude':'37.55', 'longitude': '-110.708333', 'name':'Bullfrog Basin' },
'BFF': { 'latitude':'41.866667', 'longitude': '-103.6', 'name':'Scotts Bluff County' },
'BFE': { 'latitude':'52.0', 'longitude': '8.5', 'name':'Bielefeld' },
'BFD': { 'latitude':'41.8', 'longitude': '-78.633333', 'name':'Bradford' },
'BFK': { 'latitude':'36.863333', 'longitude': '-99.618611', 'name':'Buffalo Municipal Airport' },
'BFI': { 'latitude':'47.53', 'longitude': '-122.301944', 'name':'Boeing Field/King County International Airport' },
'BFH': { 'latitude':'-25.405', 'longitude': '-49.231944', 'name':'Bacacheri' },
'BFO': { 'latitude':'-21.016667', 'longitude': '31.583333', 'name':'Buffalo Range' },
'BFN': { 'latitude':'-29.1', 'longitude': '26.3', 'name':'Bloemfontein' },
'BFM': { 'latitude':'47.25', 'longitude': '-52.85', 'name':'Mob Aerospace' },
'BFL': { 'latitude':'35.433611', 'longitude': '-119.056667', 'name':'Meadows Field' },
'BFS': { 'latitude':'54.590833', 'longitude': '-5.916667', 'name':'Aldergrove International Airport' },
'BFR': { 'latitude':'38.85', 'longitude': '-86.483333', 'name':'Virgil I Grissom Muni' },
'BFQ': { 'latitude':'7.583333', 'longitude': '-78.166667', 'name':'Bahia Pinas' },
'BFP': { 'latitude':'40.766667', 'longitude': '-80.4', 'name':'Beaver Falls' },
'BFV': { 'latitude':'15.227222', 'longitude': '103.250556', 'name':'Buri Ram' },
'BFU': { 'latitude':'32.940833', 'longitude': '117.360833', 'name':'Bengbu' },
'BFT': { 'latitude':'32.416667', 'longitude': '-80.633333', 'name':'County' },
'BFX': { 'latitude':'5.483333', 'longitude': '10.4', 'name':'Bafoussam' },
'ZJB': { 'latitude':'3.97', 'longitude': '103.438889', 'name':'Kuantan Port' },
'QYW': { 'latitude':'46.866667', 'longitude': '3.65', 'name':'Vieux Port' },
'OCI': { 'latitude':'60.1', 'longitude': '-148.216667', 'name':'Oceanic' },
'OCH': { 'latitude':'31.6', 'longitude': '-94.65', 'name':'A L Mangham Jr. Regional' },
'OCJ': { 'latitude':'18.416667', 'longitude': '-77.133333', 'name':'Boscobel' },
'IFP': { 'latitude':'30.733333', 'longitude': '72.816667', 'name':'Laughlin Bullhead Intl' },
'OCN': { 'latitude':'33.217222', 'longitude': '-117.352778', 'name':'Municipal' },
'OCA': { 'latitude':'25.366667', 'longitude': '-80.266667', 'name':'Ocean Reef' },
'OCC': { 'latitude':'-0.483333', 'longitude': '-76.966667', 'name':'Coca' },
'OCE': { 'latitude':'38.316667', 'longitude': '-75.116667', 'name':'Municipal' },
'OCF': { 'latitude':'29.166667', 'longitude': '-82.216667', 'name':'Taylor Field' },
'IFF': { 'latitude':'-18.916667', 'longitude': '141.25', 'name':'Iffley' },
'IFA': { 'latitude':'42.516667', 'longitude': '-93.266667', 'name':'Iowa Falls' },
'IFL': { 'latitude':'-17.566667', 'longitude': '146.033333', 'name':'Innisfail' },
'IFN': { 'latitude':'32.750833', 'longitude': '51.861389', 'name':'Isfahan International' },
'IFO': { 'latitude':'48.883333', 'longitude': '24.683333', 'name':'Ivano-Frankovsk' },
'IFJ': { 'latitude':'66.059722', 'longitude': '-17.31667', 'name':'Isafjordur' },
'OCV': { 'latitude':'8.25', 'longitude': '-73.783333', 'name':'Aguasclaras' },
'CEG': { 'latitude':'53.133333', 'longitude': '-2.933333', 'name':'Chester' },
'CEF': { 'latitude':'44.633333', 'longitude': '-64.85', 'name':'Westover Metro Arpt' },
'CEE': { 'latitude':'59.283333', 'longitude': '38.066667', 'name':'Cherepovets' },
'CED': { 'latitude':'-32.133333', 'longitude': '133.683333', 'name':'Ceduna' },
'CEC': { 'latitude':'41.783333', 'longitude': '-124.233333', 'name':'Mc Namara Fld' },
'CEB': { 'latitude':'10.331667', 'longitude': '123.906667', 'name':'Cebu' },
'CEA': { 'latitude':'37.648611', 'longitude': '-97.250556', 'name':'Cessna Aircraft Field' },
'PKU': { 'latitude':'0.460833', 'longitude': '101.444444', 'name':'Sultan Syarif Kasim Ii' },
'CEO': { 'latitude':'-13.333333', 'longitude': '14.5', 'name':'Waco Kungo' },
'CEN': { 'latitude':'27.383333', 'longitude': '-109.85', 'name':'Ciudad Obregon' },
'CEM': { 'latitude':'65.566667', 'longitude': '-144.783333', 'name':'Central' },
'CEL': { 'latitude':'24.958333', 'longitude': '-76.45', 'name':'Cape Eleuthera' },
'CEK': { 'latitude':'55.3', 'longitude': '61.5', 'name':'Chelyabinsk' },
'CEJ': { 'latitude':'51.5', 'longitude': '31.3', 'name':'Chernigov' },
'CEI': { 'latitude':'19.883333', 'longitude': '99.816667', 'name':'Chiang Rai' },
'CEH': { 'latitude':'-10.583333', 'longitude': '33.8', 'name':'Chelinda' },
'CEW': { 'latitude':'30.783333', 'longitude': '-86.516667', 'name':'Bob Sikes' },
'CEV': { 'latitude':'39.633333', 'longitude': '-85.133333', 'name':'Mettle Field' },
'CEU': { 'latitude':'34.666667', 'longitude': '-82.883333', 'name':'Oconee County' },
'CET': { 'latitude':'47.066667', 'longitude': '-0.883333', 'name':'Le Pontreau' },
'CES': { 'latitude':'-32.083333', 'longitude': '151.083333', 'name':'Cessnock' },
'CER': { 'latitude':'49.65', 'longitude': '-1.466667', 'name':'Maupertus' },
'CEQ': { 'latitude':'43.546389', 'longitude': '6.954167', 'name':'Mandelieu' },
'CEP': { 'latitude':'-16.233333', 'longitude': '-62.083333', 'name':'Concepcion' },
'PKJ': { 'latitude':'15.083333', 'longitude': '-89.183333', 'name':'Playa Grande' },
'PKK': { 'latitude':'21.333333', 'longitude': '95.1', 'name':'Pakokku' },
'PKH': { 'latitude':'37.3', 'longitude': '23.15', 'name':'Alexion' },
'PKN': { 'latitude':'-2.7', 'longitude': '111.666667', 'name':'Pangkalanbuun' },
'CEZ': { 'latitude':'37.316667', 'longitude': '-108.633333', 'name':'Montezuma County' },
'CEY': { 'latitude':'36.666667', 'longitude': '-88.366667', 'name':'Calloway County' },
'CEX': { 'latitude':'65.05', 'longitude': '-146.05', 'name':'Chena Hot Springs' },
'NEL': { 'latitude':'36.833333', 'longitude': '49.4', 'name':'Naec' },
'MUU': { 'latitude':'40.383333', 'longitude': '-77.883333', 'name':'Mount Union' },
'MUT': { 'latitude':'41.363889', 'longitude': '-91.144722', 'name':'Muscatine' },
'MUW': { 'latitude':'35.75', 'longitude': '0.016667', 'name':'Mascara' },
'MUV': { 'latitude':'29.483333', 'longitude': '31.066667', 'name':'Mustin Alf' },
'MUQ': { 'latitude':'-20.633333', 'longitude': '120.033333', 'name':'Muccan' },
'MUP': { 'latitude':'-25.85', 'longitude': '131.6', 'name':'Mulga Park' },
'MUS': { 'latitude':'24.287778', 'longitude': '153.978333', 'name':'Marcus Island' },
'MUR': { 'latitude':'4.183333', 'longitude': '114.316667', 'name':'Marudi' },
'MUY': { 'latitude':'-3.983333', 'longitude': '13.919444', 'name':'Mouyondzi' },
'MUX': { 'latitude':'30.203333', 'longitude': '71.419167', 'name':'Multan International' },
'MUZ': { 'latitude':'-1.5', 'longitude': '33.8', 'name':'Musoma' },
'MUE': { 'latitude':'20.0', 'longitude': '-155.683333', 'name':'Kamuela' },
'MUD': { 'latitude':'-11.65', 'longitude': '39.55', 'name':'Mueda' },
'MUG': { 'latitude':'26.8875', 'longitude': '-112.0', 'name':'Mulege' },
'MUF': { 'latitude':'-7.383333', 'longitude': '140.333333', 'name':'Muting' },
'MUA': { 'latitude':'-8.333333', 'longitude': '157.416667', 'name':'Munda' },
'MUC': { 'latitude':'48.35', 'longitude': '11.783333', 'name':'Franz Josef Strauss' },
'MUB': { 'latitude':'-19.966667', 'longitude': '23.433333', 'name':'Maun' },
'MUM': { 'latitude':'0.333333', 'longitude': '34.483333', 'name':'Mumias' },
'MUO': { 'latitude':'-32.816667', 'longitude': '27.133333', 'name':'AFB' },
'MUN': { 'latitude':'9.75', 'longitude': '-63.166667', 'name':'Quiriquire' },
'MUI': { 'latitude':'19.833333', 'longitude': '-72.5', 'name':'Muir AAF' },
'MUH': { 'latitude':'31.333333', 'longitude': '27.216667', 'name':'Mersa Matruh' },
'MUK': { 'latitude':'-19.333333', 'longitude': '-158.5', 'name':'Mauke Island' },
'MUJ': { 'latitude':'6.0', 'longitude': '36.0', 'name':'Mui' },
'ASR': { 'latitude':'38.7', 'longitude': '35.5', 'name':'Erkilet International Airport' },
'ASQ': { 'latitude':'39.5', 'longitude': '-117.066667', 'name':'Austin' },
'ASP': { 'latitude':'-23.8', 'longitude': '133.883333', 'name':'Alice Springs' },
'ASW': { 'latitude':'23.964444', 'longitude': '32.82', 'name':'Aswan' },
'ASV': { 'latitude':'-2.633333', 'longitude': '37.25', 'name':'Amboseli' },
'ASU': { 'latitude':'-25.266667', 'longitude': '-57.666667', 'name':'Silvio Pettirossi' },
'AST': { 'latitude':'46.166667', 'longitude': '-123.883333', 'name':'Astoria' },
'NUW': { 'latitude':'48.351667', 'longitude': '-122.655833', 'name':'Whidbey Island NAS' },
'ASY': { 'latitude':'46.033333', 'longitude': '-99.366667', 'name':'Ashley' },
'ASX': { 'latitude':'46.548611', 'longitude': '-90.918889', 'name':'Ashland' },
'NUR': { 'latitude':'-31.433333', 'longitude': '130.916667', 'name':'Nullarbor' },
'NUS': { 'latitude':'-16.066667', 'longitude': '167.383333', 'name':'Norsup' },
'NUP': { 'latitude':'60.883333', 'longitude': '-162.466667', 'name':'Nunapitchuk' },
'NUQ': { 'latitude':'37.383333', 'longitude': '-122.066667', 'name':'Moffett Field' },
'ASC': { 'latitude':'-15.716667', 'longitude': '-63.066667', 'name':'Ascension' },
'ASB': { 'latitude':'37.95', 'longitude': '58.383333', 'name':'Ashgabat' },
'ASA': { 'latitude':'13.071667', 'longitude': '42.645', 'name':'Assab International' },
'ASG': { 'latitude':'-43.9', 'longitude': '171.783333', 'name':'Ashburton' },
'ASF': { 'latitude':'46.35', 'longitude': '48.05', 'name':'Astrakhan' },
'ASE': { 'latitude':'39.223056', 'longitude': '-106.868889', 'name':'Aspen' },
'ASD': { 'latitude':'24.6975', 'longitude': '-77.793889', 'name':'Andros Town' },
'ASK': { 'latitude':'6.9', 'longitude': '-5.366667', 'name':'Yamoussoukro' },
'ASJ': { 'latitude':'28.416667', 'longitude': '129.7', 'name':'Amami O Shima' },
'ASI': { 'latitude':'-7.969722', 'longitude': '-14.393611', 'name':'Wideawake Field' },
'ASH': { 'latitude':'42.781667', 'longitude': '-71.514722', 'name':'Boire Field' },
'ASO': { 'latitude':'10.066667', 'longitude': '34.55', 'name':'Asosa' },
'ASN': { 'latitude':'38.6', 'longitude': '-0.683333', 'name':'Talladega' },
'ASM': { 'latitude':'15.291944', 'longitude': '38.910556', 'name':'Yohannes IV' },
'NUA': { 'latitude':'6.966667', 'longitude': '80.766667', 'name':'Nuwara Eliya' },
'DUJ': { 'latitude':'41.178333', 'longitude': '-78.898611', 'name':'Du Bois-Jefferson County' },
'DUK': { 'latitude':'-28.366667', 'longitude': '32.235556', 'name':'Dukuduk' },
'DUM': { 'latitude':'1.683333', 'longitude': '101.45', 'name':'Pinang Kampai' },
'DUN': { 'latitude':'76.566667', 'longitude': '-68.8', 'name':'Dundas' },
'TFL': { 'latitude':'-17.85', 'longitude': '-41.5', 'name':'Teofilo Otoni' },
'DUA': { 'latitude':'18.083333', 'longitude': '-73.85', 'name':'Eaker' },
'DUB': { 'latitude':'53.433333', 'longitude': '-6.25', 'name':'Dublin' },
'DUC': { 'latitude':'34.466667', 'longitude': '-97.966667', 'name':'Halliburton Field' },
'DUD': { 'latitude':'-45.866667', 'longitude': '170.366667', 'name':'Dunedin International' },
'DUE': { 'latitude':'-7.4', 'longitude': '20.816667', 'name':'Dundo' },
'DUF': { 'latitude':'36.253611', 'longitude': '-75.788611', 'name':'Pine Island Airport' },
'DUG': { 'latitude':'31.466667', 'longitude': '-109.6', 'name':'Bisbee-Douglas Intl' },
'DUQ': { 'latitude':'48.783333', 'longitude': '-123.7', 'name':'Duncan/Quam' },
'DUR': { 'latitude':'-29.97', 'longitude': '30.950556', 'name':'Durban International' },
'DUS': { 'latitude':'51.289444', 'longitude': '6.766667', 'name':'Düsseldorf International Airport' },
'DUT': { 'latitude':'53.9', 'longitude': '-166.533333', 'name':'Emergency Field' },
'TFF': { 'latitude':'-3.366667', 'longitude': '-64.7', 'name':'Tefe' },
'KWA': { 'latitude':'8.75', 'longitude': '167.75', 'name':'Kwajalein' },
'KWB': { 'latitude':'-5.866667', 'longitude': '110.433333', 'name':'Karimunjawa' },
'KWE': { 'latitude':'26.666667', 'longitude': '107.016667', 'name':'Guiyang' },
'KWD': { 'latitude':'-1.95', 'longitude': '124.966667', 'name':'Kawadjia' },
'KWG': { 'latitude':'48.05', 'longitude': '33.216667', 'name':'Krivoy Rog' },
'KWF': { 'latitude':'55.3', 'longitude': '-133.25', 'name':'Waterfall SPB' },
'KWI': { 'latitude':'29.226667', 'longitude': '47.968889', 'name':'Kuwait International' },
'KWH': { 'latitude':'37.883333', 'longitude': '70.2', 'name':'Khwahan' },
'KWK': { 'latitude':'59.816667', 'longitude': '-163.15', 'name':'Kwigillingok' },
'KWJ': { 'latitude':'35.116667', 'longitude': '126.816667', 'name':'Gwangju' },
'KWM': { 'latitude':'-15.487778', 'longitude': '141.76', 'name':'Kowanyama' },
'KWL': { 'latitude':'25.218056', 'longitude': '110.039167', 'name':'Guilin' },
'KWO': { 'latitude':'-7.983333', 'longitude': '142.816667', 'name':'Kawito' },
'KWN': { 'latitude':'59.75', 'longitude': '-161.916667', 'name':'Kwinhagak' },
'KWP': { 'latitude':'57.766667', 'longitude': '-153.55', 'name':'Village SPB' },
'KWS': { 'latitude':'-9.033333', 'longitude': '161.0', 'name':'Kwailabesi Aerodrom' },
'KWR': { 'latitude':'-8.566667', 'longitude': '160.733333', 'name':'Kwai Harbour' },
'KWT': { 'latitude':'60.8', 'longitude': '-161.45', 'name':'Kwethluk' },
'KWV': { 'latitude':'-6.183333', 'longitude': '155.333333', 'name':'Kurwina' },
'KWY': { 'latitude':'-2.016667', 'longitude': '41.266667', 'name':'Kiwayu' },
'KWX': { 'latitude':'-8.5', 'longitude': '143.416667', 'name':'Kiwai Island' },
'KWZ': { 'latitude':'-10.765833', 'longitude': '25.505833', 'name':'Kolwezi' },
'TFT': { 'latitude':'63.35', 'longitude': '18.85', 'name':'Taftan' },
'TFR': { 'latitude':'30.3', 'longitude': '31.75', 'name':'Ramadan' },
'YLW': { 'latitude':'49.956111', 'longitude': '-119.377778', 'name':'Kelowna Airport' },
'YLT': { 'latitude':'82.516667', 'longitude': '-62.283333', 'name':'Alert' },
'YLR': { 'latitude':'56.45', 'longitude': '-100.0', 'name':'Leaf Rapids' },
'YLS': { 'latitude':'49.066667', 'longitude': '-77.0', 'name':'Lebel-Sur-Quevillon' },
'YLP': { 'latitude':'50.283333', 'longitude': '-64.15', 'name':'Mingan' },
'YLQ': { 'latitude':'47.416667', 'longitude': '-72.8', 'name':'La Tuque' },
'YLX': { 'latitude':'59.35', 'longitude': '-94.683333', 'name':'Long Point' },
'YLY': { 'latitude':'49.100833', 'longitude': '-122.630833', 'name':'Langley Regional' },
'YLF': { 'latitude':'54.183333', 'longitude': '-72.483333', 'name':'LaForges' },
'YLG': { 'latitude':'-28.35', 'longitude': '116.666667', 'name':'Yalgoo' },
'YLD': { 'latitude':'47.833333', 'longitude': '-83.4', 'name':'Chapleau' },
'LIG': { 'latitude':'45.860833', 'longitude': '1.180278', 'name':'Bellegarde' },
'YLB': { 'latitude':'54.756667', 'longitude': '-112.0025', 'name':'Lac Biche' },
'YLC': { 'latitude':'62.85', 'longitude': '-69.883333', 'name':'Kimmirut' },
'YLA': { 'latitude':'54.233333', 'longitude': '-133.0', 'name':'Langara' },
'YLN': { 'latitude':'46.316667', 'longitude': '129.566667', 'name':'Yilan' },
'YLO': { 'latitude':'49.8', 'longitude': '-99.633333', 'name':'Shilo' },
'YLL': { 'latitude':'53.309167', 'longitude': '-110.0725', 'name':'Lloydminster' },
'YLM': { 'latitude':'64.466667', 'longitude': '-140.733333', 'name':'Clinton Creek' },
'YLJ': { 'latitude':'54.125278', 'longitude': '-108.522778', 'name':'Meadow Lake' },
'YLH': { 'latitude':'52.216667', 'longitude': '-87.916667', 'name':'Lansdowne House' },
'LIA': { 'latitude':'30.816667', 'longitude': '107.7', 'name':'Liangping' },
'CUL': { 'latitude':'24.764444', 'longitude': '-107.474168', 'name':'Culiacan' },
'NEC': { 'latitude':'-38.666667', 'longitude': '-58.75', 'name':'Necochea' },
'LIT': { 'latitude':'34.729444', 'longitude': '-92.224444', 'name':'Adams Field Airport' },
'LIV': { 'latitude':'65.4725', 'longitude': '-148.669167', 'name':'Livengood' },
'LIP': { 'latitude':'-21.666667', 'longitude': '-49.75', 'name':'Lins' },
'LIQ': { 'latitude':'2.216667', 'longitude': '21.666667', 'name':'Lisala' },
'LIR': { 'latitude':'10.593333', 'longitude': '-85.544444', 'name':'Daniel Oduber International' },
'WNA': { 'latitude':'60.7', 'longitude': '-162.116667', 'name':'Napakiak SPB' },
'WND': { 'latitude':'-28.266667', 'longitude': '121.833333', 'name':'Windarra' },
'WNE': { 'latitude':'-1.35', 'longitude': '9.333333', 'name':'Wora Na Ye' },
'LIX': { 'latitude':'5.333333', 'longitude': '12.75', 'name':'Likoma' },
'WNH': { 'latitude':'23.5583', 'longitude': '104.325', 'name':'Wenshan Puzhehei' },
'WNN': { 'latitude':'52.916667', 'longitude': '-89.166667', 'name':'Wunnummin Lake' },
'WNR': { 'latitude':'-25.416667', 'longitude': '142.666667', 'name':'Windorah' },
'WNS': { 'latitude':'26.2', 'longitude': '68.366667', 'name':'Nawabshah' },
'WNP': { 'latitude':'13.683333', 'longitude': '123.133333', 'name':'Naga' },
'LIZ': { 'latitude':'46.950556', 'longitude': '-67.885833', 'name':'Loring AFB' },
'WNU': { 'latitude':'-4.9', 'longitude': '145.316667', 'name':'Wanuma' },
'WNZ': { 'latitude':'27.95', 'longitude': '120.633333', 'name':'Wenzhou' },
'GKT': { 'latitude':'31.353611', 'longitude': '-84.375', 'name':'Gatlinburg' },
'MHX': { 'latitude':'-10.366667', 'longitude': '-161.0', 'name':'Manihiki Island' },
'MHY': { 'latitude':'-9.0', 'longitude': '141.416667', 'name':'Morehead' },
'GKA': { 'latitude':'-6.058333', 'longitude': '145.388889', 'name':'Goroka' },
'GKE': { 'latitude':'50.95', 'longitude': '6.116667', 'name':'Geilenkirchen' },
'WTE': { 'latitude':'9.45', 'longitude': '170.033333', 'name':'Wotje Island' },
'NVT': { 'latitude':'-26.916667', 'longitude': '-48.583333', 'name':'Navegantes' },
'NVR': { 'latitude':'58.5', 'longitude': '31.25', 'name':'Yerievo' },
'WTK': { 'latitude':'67.583333', 'longitude': '-163.0', 'name':'Noatak' },
'NVP': { 'latitude':'-5.133333', 'longitude': '-60.366667', 'name':'Novo Aripuana' },
'CIT': { 'latitude':'42.3', 'longitude': '69.6', 'name':'Shimkent' },
'IYK': { 'latitude':'35.65', 'longitude': '-117.833333', 'name':'Kern County' },
'NVY': { 'latitude':'11.6', 'longitude': '79.433333', 'name':'Neyveli' },
'PPC': { 'latitude':'66.8', 'longitude': '-150.633333', 'name':'Prospect Creek' },
'PPB': { 'latitude':'-22.177778', 'longitude': '-51.418333', 'name':'Adhemar De Barros' },
'PPA': { 'latitude':'35.533333', 'longitude': '-100.95', 'name':'Perry Lefors Field' },
'PPG': { 'latitude':'-14.333333', 'longitude': '-170.716667', 'name':'International' },
'PPF': { 'latitude':'37.333333', 'longitude': '-95.5', 'name':'Tri-City' },
'PPE': { 'latitude':'31.583333', 'longitude': '-113.833333', 'name':'Puerto Penasco' },
'PPD': { 'latitude':'18.2375', 'longitude': '-66.369167', 'name':'Palmas Del Mar' },
'PPK': { 'latitude':'54.783333', 'longitude': '69.183333', 'name':'Petropavlovsk' },
'PPJ': { 'latitude':'-5.633333', 'longitude': '106.55', 'name':'Pulau Panjang' },
'PPI': { 'latitude':'-33.233333', 'longitude': '138.0', 'name':'Port Pirie' },
'JQE': { 'latitude':'7.75', 'longitude': '-78.25', 'name':'Jaque' },
'PPO': { 'latitude':'24.899722', 'longitude': '-76.360833', 'name':'Powell Point' },
'PPN': { 'latitude':'2.45', 'longitude': '-76.616667', 'name':'Machangara' },
'PPM': { 'latitude':'26.233333', 'longitude': '-80.127778', 'name':'Pompano Beach' },
'JQA': { 'latitude':'70.731944', 'longitude': '-52.702778', 'name':'Qaarsut' },
'PPS': { 'latitude':'9.733333', 'longitude': '118.75', 'name':'Puerto Princesa' },
'PPR': { 'latitude':'0.833333', 'longitude': '100.366667', 'name':'Pasir Pangarayan' },
'PPQ': { 'latitude':'-40.904722', 'longitude': '174.989167', 'name':'Paraparaumu' },
'NVD': { 'latitude':'37.85', 'longitude': '-94.3', 'name':'Nevada' },
'PPW': { 'latitude':'59.416667', 'longitude': '-2.75', 'name':'Papa Westray' },
'PPV': { 'latitude':'56.333333', 'longitude': '-133.666667', 'name':'Port Protection' },
'PPU': { 'latitude':'18.066667', 'longitude': '97.45', 'name':'Papun' },
'PPT': { 'latitude':'-17.556667', 'longitude': '-149.611389', 'name':'Faa\'a' },
'PPZ': { 'latitude':'6.2', 'longitude': '-67.45', 'name':'Puerto Paez' },
'PPY': { 'latitude':'-22.289167', 'longitude': '-45.919167', 'name':'Pouso Alegre' },
'PPX': { 'latitude':'-9.995833', 'longitude': '149.591667', 'name':'Param' },
'NVA': { 'latitude':'2.933333', 'longitude': '-75.283333', 'name':'La Marguita' },
'NVK': { 'latitude':'68.425', 'longitude': '17.425', 'name':'Framnes' },
'NVI': { 'latitude':'40.083333', 'longitude': '65.383333', 'name':'Navoiy' },
'GSQ': { 'latitude':'30.8', 'longitude': '31.8', 'name':'Shark Elowainat' },
'GSP': { 'latitude':'34.895556', 'longitude': '-82.218889', 'name':'Greenville Spartanbur Int\'l Airport' },
'GSS': { 'latitude':'-25.116667', 'longitude': '30.8', 'name':'Sabi Sabi' },
'GSR': { 'latitude':'9.516667', 'longitude': '49.083333', 'name':'Gardo' },
'GSU': { 'latitude':'14.133333', 'longitude': '35.316667', 'name':'Gedaref' },
'GST': { 'latitude':'58.416667', 'longitude': '-135.7', 'name':'Gustavus Arpt' },
'TIZ': { 'latitude':'-5.860556', 'longitude': '142.940556', 'name':'Tari' },
'TMQ': { 'latitude':'14.8', 'longitude': '50.0', 'name':'Tambao' },
'GSY': { 'latitude':'51.333333', 'longitude': '0.033333', 'name':'Binbrook' },
'TIU': { 'latitude':'-44.4', 'longitude': '171.216667', 'name':'Timaru' },
'TIV': { 'latitude':'42.404722', 'longitude': '18.723333', 'name':'Tivat' },
'TIW': { 'latitude':'-16.3', 'longitude': '-67.45', 'name':'Industrial' },
'TIP': { 'latitude':'32.669444', 'longitude': '13.156667', 'name':'Tripoli International' },
'TIQ': { 'latitude':'45.003889', 'longitude': '12.268611', 'name':'Tinian' },
'TIR': { 'latitude':'13.6325', 'longitude': '79.543333', 'name':'Tirupati' },
'GSA': { 'latitude':'5.333333', 'longitude': '117.166667', 'name':'Long Pasia' },
'TIM': { 'latitude':'-4.528333', 'longitude': '136.8875', 'name':'Timika' },
'GSC': { 'latitude':'-25.05', 'longitude': '115.2', 'name':'Gascoyne Junction' },
'TIO': { 'latitude':'21.683333', 'longitude': '94.1', 'name':'Tilin' },
'GSE': { 'latitude':'57.775833', 'longitude': '11.966667', 'name':'Gothenburg City Airport' },
'TII': { 'latitude':'32.628611', 'longitude': '65.8775', 'name':'Tirinkot' },
'TIJ': { 'latitude':'32.541111', 'longitude': '-116.970278', 'name':'General A. L. Rodriguez Intl' },
'TIK': { 'latitude':'35.414722', 'longitude': '-97.386667', 'name':'Tinker AFB' },
'GSI': { 'latitude':'-9.423889', 'longitude': '160.065556', 'name':'Guadalcanal' },
'GSH': { 'latitude':'41.583333', 'longitude': '-85.833333', 'name':'Goshen' },
'TIF': { 'latitude':'21.270278', 'longitude': '40.415833', 'name':'Taif' },
'TIG': { 'latitude':'-2.616667', 'longitude': '149.716667', 'name':'Tingwon' },
'GSM': { 'latitude':'26.7562', 'longitude': '55.894436', 'name':'Gheshm Airport' },
'TIA': { 'latitude':'41.414722', 'longitude': '19.720556', 'name':'Rinas Mother Teresa' },
'GSO': { 'latitude':'36.097778', 'longitude': '-79.937222', 'name':'Piedmont Triad Intl' },
'GSN': { 'latitude':'-31.866667', 'longitude': '138.2', 'name':'Mount Gunson' },
'NNM': { 'latitude':'67.616667', 'longitude': '53.15', 'name':'Naryan-Mar' },
'NNL': { 'latitude':'60.0', 'longitude': '-154.816667', 'name':'Nondalton' },
'NNK': { 'latitude':'58.75', 'longitude': '-156.533333', 'name':'Naknek' },
'NNI': { 'latitude':'-18.816667', 'longitude': '16.916667', 'name':'Namutoni' },
'NNG': { 'latitude':'22.783333', 'longitude': '108.0', 'name':'Nanning' },
'HKS': { 'latitude':'32.333611', 'longitude': '-90.222222', 'name':'Hawkins Field' },
'NND': { 'latitude':'-11.083333', 'longitude': '39.6', 'name':'Nangade' },
'HKV': { 'latitude':'41.966667', 'longitude': '25.5', 'name':'Haskovo' },
'NNB': { 'latitude':'-10.833333', 'longitude': '162.466667', 'name':'Santa Ana' },
'NNA': { 'latitude':'34.3', 'longitude': '-6.6', 'name':'NAF' },
'HKK': { 'latitude':'-42.716667', 'longitude': '170.983333', 'name':'Hokitika Arpt' },
'HKN': { 'latitude':'-5.75', 'longitude': '150.416667', 'name':'Hoskins' },
'NNY': { 'latitude':'33.0', 'longitude': '112.533333', 'name':'Nanyang' },
'NNX': { 'latitude':'4.15', 'longitude': '117.65', 'name':'Nunukan' },
'HKB': { 'latitude':'63.866667', 'longitude': '-148.966667', 'name':'Healy Lake' },
'NNU': { 'latitude':'-17.783333', 'longitude': '-40.683333', 'name':'Nanuque' },
'NNT': { 'latitude':'18.8', 'longitude': '100.783333', 'name':'Nan' },
'NNR': { 'latitude':'53.216667', 'longitude': '9.466667', 'name':'Connemara' },
'HKD': { 'latitude':'41.766667', 'longitude': '140.816667', 'name':'Hakodate' },
'ERT': { 'latitude':'49.066667', 'longitude': '104.15', 'name':'Erdenet' },
'SQZ': { 'latitude':'53.3', 'longitude': '-0.566667', 'name':'RAF Station' },
'SQY': { 'latitude':'-31.366667', 'longitude': '-51.966667', 'name':'Sao Lourenco Do Sul' },
'SQX': { 'latitude':'-26.781667', 'longitude': '-53.503611', 'name':'Sao Miguel do Oeste' },
'TMA': { 'latitude':'31.428889', 'longitude': '-83.488611', 'name':'Henry Tift Myers' },
'SQS': { 'latitude':'5.55', 'longitude': '-75.366667', 'name':'Matthew Spain' },
'SQR': { 'latitude':'-2.531111', 'longitude': '121.357778', 'name':'Inco Soroako Waws' },
'SQQ': { 'latitude':'55.666667', 'longitude': '26.266667', 'name':'Siauliai International' },
'SQP': { 'latitude':'-14.2', 'longitude': '147.166667', 'name':'Starcke' },
'SQW': { 'latitude':'56.55', 'longitude': '9.172778', 'name':'Skive Airport' },
'SQV': { 'latitude':'48.083333', 'longitude': '-123.1', 'name':'Sequim Valley Arpt' },
'SQT': { 'latitude':'-9.666667', 'longitude': '150.8', 'name':'China Straits Airstrip' },
'SQK': { 'latitude':'29.416667', 'longitude': '30.866667', 'name':'Sidi Barani' },
'SQI': { 'latitude':'41.733333', 'longitude': '-89.683333', 'name':'Whiteside County' },
'TMC': { 'latitude':'-9.340278', 'longitude': '119.183056', 'name':'Tambolaka' },
'SQO': { 'latitude':'65.233333', 'longitude': '16.9', 'name':'Gunnarn' },
'SQN': { 'latitude':'-2.066667', 'longitude': '125.966667', 'name':'Sanana' },
'SQM': { 'latitude':'-13.331389', 'longitude': '-50.1975', 'name':'São Miguel de Aragao' },
'RHP': { 'latitude':'27.333333', 'longitude': '86.083333', 'name':'Ramechhap' },
'SQC': { 'latitude':'-31.216667', 'longitude': '119.316667', 'name':'Southern Cross' },
'SQB': { 'latitude':'4.766667', 'longitude': '-75.95', 'name':'Santa Ana' },
'SQA': { 'latitude':'13.816667', 'longitude': '39.2', 'name':'Santa Ynez' },
'SQG': { 'latitude':'0.066667', 'longitude': '111.5', 'name':'Sintang' },
'SQF': { 'latitude':'0.716667', 'longitude': '-75.266667', 'name':'Solano' },
'SQE': { 'latitude':'5.4', 'longitude': '-71.7', 'name':'San Luis De Pale' },
'SQD': { 'latitude':'41.666667', 'longitude': '35.0', 'name':'Sinop' },
'VUP': { 'latitude':'10.433333', 'longitude': '-73.25', 'name':'Valledupar' },
'ERV': { 'latitude':'29.983333', 'longitude': '-99.083333', 'name':'Kerrville' },
'EEN': { 'latitude':'42.9', 'longitude': '-72.266667', 'name':'Dillant-Hopkins' },
'EEK': { 'latitude':'60.216667', 'longitude': '-162.016667', 'name':'Eek' },
'EED': { 'latitude':'34.85', 'longitude': '-114.616667', 'name':'Needles' },
'RHV': { 'latitude':'22.916667', 'longitude': '-80.883333', 'name':'Reid-hillview' },
'ROH': { 'latitude':'-18.85', 'longitude': '143.7', 'name':'Robinhood' },
'RHI': { 'latitude':'45.633333', 'longitude': '-89.45', 'name':'Oneida County' },
'LLY': { 'latitude':'39.983333', 'longitude': '-74.783333', 'name':'Burlington County' },
'LLX': { 'latitude':'44.5', 'longitude': '-72.016667', 'name':'Lyndonville' },
'ROL': { 'latitude':'40.3', 'longitude': '-109.983333', 'name':'Roosevelt' },
'RON': { 'latitude':'6.3', 'longitude': '-71.083333', 'name':'Rondon' },
'ROO': { 'latitude':'-16.433333', 'longitude': '-54.716667', 'name':'Rondonopolis' },
'LLS': { 'latitude':'-24.7', 'longitude': '-60.6', 'name':'Las Lomitas' },
'ROA': { 'latitude':'37.316667', 'longitude': '-79.983333', 'name':'Roanoke Regional Airport' },
'ROB': { 'latitude':'6.252778', 'longitude': '-10.35', 'name':'Roberts Intl' },
'LLP': { 'latitude':'-23.016667', 'longitude': '138.7', 'name':'Linda Downs' },
'LLW': { 'latitude':'-13.789444', 'longitude': '33.781111', 'name':'Kumuzu International Airport' },
'LLT': { 'latitude':'-37.691667', 'longitude': '145.366667', 'name':'Lilydale Airport' },
'ROY': { 'latitude':'-45.719444', 'longitude': '-70.251389', 'name':'Rio Mayo' },
'LLI': { 'latitude':'12.016667', 'longitude': '39.066667', 'name':'Lalibela' },
'LLH': { 'latitude':'15.45', 'longitude': '-87.9', 'name':'Las Limas' },
'LLN': { 'latitude':'-3.75', 'longitude': '138.666667', 'name':'Kelila' },
'LLM': { 'latitude':'3.766667', 'longitude': '114.4', 'name':'Long Lama' },
'LLL': { 'latitude':'-16.5', 'longitude': '128.666667', 'name':'Lissadell' },
'ROP': { 'latitude':'14.166667', 'longitude': '145.25', 'name':'Rota' },
'LLA': { 'latitude':'65.543889', 'longitude': '22.121944', 'name':'Kallax' },
'ROS': { 'latitude':'-32.833333', 'longitude': '-60.716667', 'name':'Fisherton' },
'LLG': { 'latitude':'-17.133333', 'longitude': '144.533333', 'name':'Chillagoe' },
'LLF': { 'latitude':'26.233333', 'longitude': '111.616667', 'name':'LingLing' },
'LLE': { 'latitude':'-25.466667', 'longitude': '31.566667', 'name':'Malelane' },
'RHL': { 'latitude':'-22.633333', 'longitude': '119.966667', 'name':'Roy Hill' },
'BDE': { 'latitude':'54.383333', 'longitude': '19.7', 'name':'Baudette' },
'NJC': { 'latitude':'60.95', 'longitude': '76.483333', 'name':'Nizhnevartovsk' },
'BDG': { 'latitude':'37.583333', 'longitude': '-109.483333', 'name':'Blanding' },
'BDF': { 'latitude':'41.183333', 'longitude': '-89.65', 'name':'Rinkenberger' },
'BDA': { 'latitude':'32.364167', 'longitude': '-64.678611', 'name':'Kindley Field' },
'RHO': { 'latitude':'36.400833', 'longitude': '28.083889', 'name':'Diagoras' },
'BDC': { 'latitude':'-5.466667', 'longitude': '-45.266667', 'name':'Barra Do Corda' },
'BDB': { 'latitude':'-24.903889', 'longitude': '152.318611', 'name':'Bundaberg' },
'BDM': { 'latitude':'40.316667', 'longitude': '27.983333', 'name':'Bandirma' },
'BDL': { 'latitude':'41.938889', 'longitude': '-72.683333', 'name':'Bradley International' },
'BDO': { 'latitude':'-6.900556', 'longitude': '107.576389', 'name':'Husein Sastranegara' },
'BDN': { 'latitude':'24.65', 'longitude': '68.833333', 'name':'Talhar' },
'BDI': { 'latitude':'-3.716667', 'longitude': '55.216667', 'name':'Bird Island' },
'BDH': { 'latitude':'26.55', 'longitude': '54.883333', 'name':'Bandar Lengeh' },
'BDK': { 'latitude':'8.033333', 'longitude': '-2.8', 'name':'Bondoukou' },
'BDJ': { 'latitude':'-3.283333', 'longitude': '114.683333', 'name':'Sjamsudin Noor' },
'BDU': { 'latitude':'69.055833', 'longitude': '18.540278', 'name':'Bardufoss' },
'BDT': { 'latitude':'4.253333', 'longitude': '20.975278', 'name':'Gbadolite' },
'BDW': { 'latitude':'-17.3', 'longitude': '127.466667', 'name':'Bedford Downs' },
'BDV': { 'latitude':'-7.083333', 'longitude': '29.733333', 'name':'Moba' },
'BDQ': { 'latitude':'22.316667', 'longitude': '73.266667', 'name':'Vadodara' },
'BDP': { 'latitude':'26.566667', 'longitude': '88.083333', 'name':'Bhadrapur' },
'BDS': { 'latitude':'40.65', 'longitude': '17.95', 'name':'Papola Casale' },
'BDR': { 'latitude':'41.166667', 'longitude': '-73.133333', 'name':'Igor I. Sikorsky Mem.' },
'BDY': { 'latitude':'43.116667', 'longitude': '-124.416667', 'name':'State' },
'BDX': { 'latitude':'45.45', 'longitude': '-105.416667', 'name':'Broadus' },
'HWK': { 'latitude':'-31.883333', 'longitude': '138.4', 'name':'Wilpena Pound' },
'IDR': { 'latitude':'22.716667', 'longitude': '75.8', 'name':'Devi Ahilyabai Holkar' },
'IDP': { 'latitude':'16.533333', 'longitude': '-88.416667', 'name':'Independence' },
'IDN': { 'latitude':'-6.033333', 'longitude': '147.033333', 'name':'Indagen' },
'IDO': { 'latitude':'-11.572222', 'longitude': '-50.666111', 'name':'Rio' },
'IDK': { 'latitude':'-26.966667', 'longitude': '133.325', 'name':'Indulkana' },
'IDI': { 'latitude':'40.632222', 'longitude': '-79.105556', 'name':'ndiana County Airport' },
'IDF': { 'latitude':'-5.0', 'longitude': '19.508333', 'name':'Idiofa' },
'IDG': { 'latitude':'42.35', 'longitude': '-95.466667', 'name':'Municipal' },
'IDB': { 'latitude':'61.866667', 'longitude': '12.583333', 'name':'Idre' },
'IDC': { 'latitude':'42.533333', 'longitude': '-4.55', 'name':'Ila Da Chilonzuene' },
'IDA': { 'latitude':'43.516667', 'longitude': '-112.066667', 'name':'Fanning Field' },
'CGI': { 'latitude':'37.216667', 'longitude': '-89.566667', 'name':'Cape Girardeau' },
'CGH': { 'latitude':'-23.626667', 'longitude': '-46.655278', 'name':'Congonhas' },
'CGK': { 'latitude':'-6.125556', 'longitude': '106.655833', 'name':'Soekarno-Hatta International' },
'CGJ': { 'latitude':'-12.533333', 'longitude': '27.866667', 'name':'Chingola' },
'CGM': { 'latitude':'9.25', 'longitude': '124.666667', 'name':'Mambajao' },
'PMQ': { 'latitude':'-46.535', 'longitude': '-70.983333', 'name':'Perito Moreno' },
'CGO': { 'latitude':'34.75', 'longitude': '113.416667', 'name':'Zhengzhou' },
'CGN': { 'latitude':'50.866667', 'longitude': '7.15', 'name':'Cologne/bonn' },
'CGA': { 'latitude':'55.483333', 'longitude': '-133.15', 'name':'Craig SPB' },
'CGC': { 'latitude':'-5.459167', 'longitude': '148.4325', 'name':'Cape Gloucester' },
'CGB': { 'latitude':'-15.653056', 'longitude': '-56.116667', 'name':'Intl. Airpt. Marechal Rondon' },
'CGE': { 'latitude':'38.55', 'longitude': '-76.033333', 'name':'Cambridge' },
'CGD': { 'latitude':'29.033333', 'longitude': '111.683333', 'name':'Changde' },
'PMZ': { 'latitude':'8.95', 'longitude': '-83.483333', 'name':'Palmar Sur' },
'CGF': { 'latitude':'41.5525', 'longitude': '-81.483889', 'name':'Cuyahoga County' },
'CGY': { 'latitude':'8.415556', 'longitude': '124.611111', 'name':'Cagayan De Oro Domestic Airport' },
'CGX': { 'latitude':'41.858889', 'longitude': '-87.608333', 'name':'Merrill C Meigs' },
'PMF': { 'latitude':'44.8', 'longitude': '10.333333', 'name':'Giuseppe Verdi' },
'CGZ': { 'latitude':'32.883333', 'longitude': '-111.75', 'name':'Municipal' },
'PMA': { 'latitude':'-5.233333', 'longitude': '39.8', 'name':'Wawi' },
'PMB': { 'latitude':'48.95', 'longitude': '-97.233333', 'name':'Intermediate' },
'PMC': { 'latitude':'-41.483333', 'longitude': '-72.85', 'name':'Tepual' },
'CGQ': { 'latitude':'43.916667', 'longitude': '125.333333', 'name':'Changchun' },
'CGP': { 'latitude':'22.266667', 'longitude': '91.816667', 'name':'Patenga' },
'CGS': { 'latitude':'39.0', 'longitude': '-76.916667', 'name':'College Park' },
'CGR': { 'latitude':'-20.467222', 'longitude': '-54.667222', 'name':'Intl. Airport Campo Grande' },
'CGU': { 'latitude':'8.583333', 'longitude': '-64.216667', 'name':'Ciudad Guayana' },
'CGT': { 'latitude':'20.45', 'longitude': '-12.366667', 'name':'Chinguitti' },
'CGV': { 'latitude':'-32.266667', 'longitude': '125.466667', 'name':'Caiguna' },
'FEG': { 'latitude':'40.383333', 'longitude': '71.766667', 'name':'Fergana' },
'FEB': { 'latitude':'29.233333', 'longitude': '81.216667', 'name':'Sanfebagar' },
'FEC': { 'latitude':'-12.25', 'longitude': '-38.95', 'name':'Feira De Santana' },
'FEA': { 'latitude':'60.583333', 'longitude': '-0.966667', 'name':'Fetlar' },
'FEN': { 'latitude':'-3.85', 'longitude': '-32.416667', 'name':'Fernando De Noronha' },
'FEL': { 'latitude':'48.166667', 'longitude': '11.25', 'name':'Fuerstenfeldbruck' },
'FEJ': { 'latitude':'-7.0', 'longitude': '-36.016667', 'name':'Feijo' },
'FEK': { 'latitude':'9.6', 'longitude': '-5.2', 'name':'Ferkessedougou' },
'FEW': { 'latitude':'32.9875', 'longitude': '65.124167', 'name':'Warren AFB' },
'FET': { 'latitude':'41.433333', 'longitude': '-96.5', 'name':'Municipal' },
'FER': { 'latitude':'62.05', 'longitude': '-93.333333', 'name':'Fergusons Gulf' },
'FES': { 'latitude':'13.483333', 'longitude': '-88.75', 'name':'San Fernando' },
'FEP': { 'latitude':'42.266667', 'longitude': '-89.583333', 'name':'Albertus' },
'FEZ': { 'latitude':'34.033333', 'longitude': '-4.983333', 'name':'Sais' },
'OOM': { 'latitude':'-36.3', 'longitude': '148.966667', 'name':'Cooma' },
'MSZ': { 'latitude':'-15.208611', 'longitude': '12.160833', 'name':'Namibe' },
'MSY': { 'latitude':'29.993333', 'longitude': '-90.258056', 'name':'Louis Armstrong New Orléans International Airport' },
'MSX': { 'latitude':'-2.95', 'longitude': '12.733333', 'name':'Mossendjo' },
'MSW': { 'latitude':'15.67', 'longitude': '39.37', 'name':'Massawa International' },
'MSV': { 'latitude':'41.616667', 'longitude': '-74.7', 'name':'Sullivan County Intl' },
'MSU': { 'latitude':'-29.466667', 'longitude': '27.5', 'name':'Moshoeshoe Intl' },
'MST': { 'latitude':'50.911667', 'longitude': '5.770278', 'name':'Maastricht/aachen' },
'MSS': { 'latitude':'44.933333', 'longitude': '-74.85', 'name':'Richards Field' },
'MSR': { 'latitude':'38.747769', 'longitude': '41.661236', 'name':'Mus' },
'MSQ': { 'latitude':'53.8825', 'longitude': '28.030833', 'name':'Minsk International 2' },
'MSP': { 'latitude':'44.883333', 'longitude': '-93.216944', 'name':'Minneapolis - St. Paul Intl' },
'MSO': { 'latitude':'46.916667', 'longitude': '-114.083333', 'name':'Missoula International' },
'MSN': { 'latitude':'43.139722', 'longitude': '-89.3375', 'name':'Dane County Regional' },
'MSM': { 'latitude':'-4.833333', 'longitude': '17.85', 'name':'Masi Manimba' },
'MSL': { 'latitude':'34.75', 'longitude': '-87.616667', 'name':'Sheffield' },
'MSK': { 'latitude':'36.850833', 'longitude': '27.076111', 'name':'Mastic Point' },
'MSJ': { 'latitude':'40.7', 'longitude': '141.383333', 'name':'Misawa' },
'MSI': { 'latitude':'14.966667', 'longitude': '120.666667', 'name':'Masalembo' },
'MSH': { 'latitude':'20.166667', 'longitude': '58.25', 'name':'Masirah' },
'MSG': { 'latitude':'-29.733333', 'longitude': '28.75', 'name':'Matsaile' },
'MSF': { 'latitude':'-22.666667', 'longitude': '134.916667', 'name':'Mount Swan' },
'MSE': { 'latitude':'51.366667', 'longitude': '1.35', 'name':'Kent International' },
'MSD': { 'latitude':'39.524722', 'longitude': '-111.474444', 'name':'Mt Pleasant' },
'MSC': { 'latitude':'33.45', 'longitude': '-111.716667', 'name':'Falcon Field' },
'MSB': { 'latitude':'18.033333', 'longitude': '-63.1', 'name':'Marigot SPB' },
'MSA': { 'latitude':'53.833333', 'longitude': '-92.0', 'name':'Muskrat Dam' },
'AQP': { 'latitude':'-16.341111', 'longitude': '-71.583056', 'name':'Rodriguez Ballon' },
'AQS': { 'latitude':'-16.75', 'longitude': '179.35', 'name':'Saqani' },
'AQY': { 'latitude':'60.966667', 'longitude': '-149.116667', 'name':'Alyeska' },
'AQG': { 'latitude':'30.516667', 'longitude': '117.033333', 'name':'Anqing' },
'AQA': { 'latitude':'-21.811944', 'longitude': '-48.133056', 'name':'Araraquara' },
'AQB': { 'latitude':'15.366667', 'longitude': '-89.8', 'name':'Quiche Airport' },
'AQM': { 'latitude':'-9.933333', 'longitude': '-63.066667', 'name':'Ariquemes' },
'AQI': { 'latitude':'28.316667', 'longitude': '46.116667', 'name':'Qaisumah' },
'AQJ': { 'latitude':'29.611619', 'longitude': '35.018067', 'name':'King Hussein Intl' },
'DWS': { 'latitude':'28.400278', 'longitude': '-82.438333', 'name':'Walt Disney World' },
'DWB': { 'latitude':'-16.1', 'longitude': '45.366667', 'name':'Soalala' },
'DWA': { 'latitude':'-13.0', 'longitude': '34.133333', 'name':'Dwangwa' },
'DWF': { 'latitude':'46.233333', 'longitude': '-83.333333', 'name':'Wright AFB' },
'DWD': { 'latitude':'24.449722', 'longitude': '44.121111', 'name':'Dawadmi' },
'DWH': { 'latitude':'30.061944', 'longitude': '-95.552778', 'name':'David Wayne Hooks' },
'DWN': { 'latitude':'35.449167', 'longitude': '-97.533056', 'name':'Downtown Airpark' },
'PEX': { 'latitude':'65.116667', 'longitude': '57.133333', 'name':'Pechora' },
'PEY': { 'latitude':'-31.916667', 'longitude': '133.016667', 'name':'Penong' },
'KYK': { 'latitude':'57.566667', 'longitude': '-154.416667', 'name':'Karluk' },
'KYI': { 'latitude':'-31.483333', 'longitude': '131.866667', 'name':'Yalata Mission' },
'KYO': { 'latitude':'54.433333', 'longitude': '23.65', 'name':'Topp Of Tampa' },
'KYN': { 'latitude':'51.716667', 'longitude': '-1.083333', 'name':'Milton Keynes' },
'KYL': { 'latitude':'25.083333', 'longitude': '-80.4', 'name':'Port Largo' },
'KYB': { 'latitude':'-31.466667', 'longitude': '130.066667', 'name':'Yangoonabie' },
'KYA': { 'latitude':'37.983333', 'longitude': '32.566667', 'name':'Konya' },
'KYF': { 'latitude':'-27.277778', 'longitude': '120.075', 'name':'Yeelirrie' },
'KYE': { 'latitude':'31.0', 'longitude': '15.0', 'name':'Kleyate' },
'KYD': { 'latitude':'22.083333', 'longitude': '121.5', 'name':'Orchid Island' },
'KYZ': { 'latitude':'51.7', 'longitude': '94.466667', 'name':'Kyzyl' },
'KYX': { 'latitude':'-6.133333', 'longitude': '146.6', 'name':'Yalumet' },
'KYS': { 'latitude':'14.433333', 'longitude': '-11.433333', 'name':'Kayes' },
'KYP': { 'latitude':'19.433333', 'longitude': '93.533333', 'name':'Kyaukpyu' },
'KYU': { 'latitude':'64.9', 'longitude': '-157.7', 'name':'Koyukuk' },
'KYT': { 'latitude':'21.4', 'longitude': '94.133333', 'name':'Kyauktaw' },
'BYX': { 'latitude':'-13.2', 'longitude': '136.233333', 'name':'Baniyala' },
'BYW': { 'latitude':'48.583333', 'longitude': '-122.833333', 'name':'Blakely Island' },
'BYT': { 'latitude':'51.683333', 'longitude': '-9.45', 'name':'Bantry' },
'BYU': { 'latitude':'49.95', 'longitude': '11.586111', 'name':'Bindlacher-Berg' },
'BYS': { 'latitude':'35.283333', 'longitude': '-116.633333', 'name':'Bicycle Lake AAF' },
'BYQ': { 'latitude':'3.466667', 'longitude': '117.866667', 'name':'Bunyu' },
'BYN': { 'latitude':'46.1', 'longitude': '100.683333', 'name':'Bayankhongor' },
'BYO': { 'latitude':'-21.229444', 'longitude': '-56.456111', 'name':'Bonito Airport' },
'BYL': { 'latitude':'7.366667', 'longitude': '-10.0', 'name':'Bella Yella' },
'BYM': { 'latitude':'20.283333', 'longitude': '-76.5', 'name':'C.M. de Cespedes' },
'BYK': { 'latitude':'7.733333', 'longitude': '-5.066667', 'name':'Bouake' },
'BYH': { 'latitude':'-13.25', 'longitude': '130.7', 'name':'Blytheville AFB' },
'BYI': { 'latitude':'42.533333', 'longitude': '-113.766667', 'name':'Rupert' },
'BYF': { 'latitude':'49.97', 'longitude': '2.69', 'name':'Albert (Picardie Somme)' },
'BYG': { 'latitude':'44.35', 'longitude': '-106.7', 'name':'Municipal' },
'BYD': { 'latitude':'14.133333', 'longitude': '46.55', 'name':'Beidah' },
'BYB': { 'latitude':'25.6', 'longitude': '56.233333', 'name':'Dibaa' },
'BYC': { 'latitude':'-21.966667', 'longitude': '-63.7', 'name':'Yacuiba' },
'PET': { 'latitude':'-31.716667', 'longitude': '-52.316667', 'name':'Federal' },
'BYA': { 'latitude':'64.083333', 'longitude': '-141.116667', 'name':'Boundary' },
'XBN': { 'latitude':'-9.633333', 'longitude': '149.316667', 'name':'Biniguni' },
'PEU': { 'latitude':'15.273056', 'longitude': '-83.780833', 'name':'Puerto Lempira' },
'NYO': { 'latitude':'58.789167', 'longitude': '16.906944', 'name':'Skavsta' },
'YBX': { 'latitude':'51.433333', 'longitude': '-57.183333', 'name':'Blanc Sablon' },
'YBY': { 'latitude':'54.304167', 'longitude': '-110.743611', 'name':'Bonnyville' },
'YBP': { 'latitude':'28.816667', 'longitude': '104.533333', 'name':'Yibin' },
'YBQ': { 'latitude':'48.966667', 'longitude': '-1.666667', 'name':'Telegraph Harbour' },
'YBR': { 'latitude':'49.909722', 'longitude': '-99.950833', 'name':'Brandon' },
'NYM': { 'latitude':'65.483333', 'longitude': '72.716667', 'name':'Nadym' },
'YBT': { 'latitude':'57.883333', 'longitude': '-101.683333', 'name':'Brochet' },
'YBV': { 'latitude':'52.433333', 'longitude': '-97.033333', 'name':'Berens River' },
'YBW': { 'latitude':'48.75', 'longitude': '-123.233333', 'name':'Bedwell Harbor' },
'YBH': { 'latitude':'50.9', 'longitude': '-127.916667', 'name':'Bull Harbour' },
'YBI': { 'latitude':'53.45', 'longitude': '-55.733333', 'name':'Black Tickle' },
'YBJ': { 'latitude':'50.5', 'longitude': '-62.916667', 'name':'Baie Johan Beetz' },
'YBK': { 'latitude':'64.3', 'longitude': '-96.083333', 'name':'Baker Lake' },
'YBL': { 'latitude':'49.95', 'longitude': '-125.266667', 'name':'Campbell River' },
'YBM': { 'latitude':'56.7', 'longitude': '-137.133333', 'name':'Bronson Creek' },
'YBN': { 'latitude':'44.283333', 'longitude': '-79.916667', 'name':'Borden' },
'YBA': { 'latitude':'51.166667', 'longitude': '-115.566389', 'name':'Banff' },
'YBB': { 'latitude':'68.886111', 'longitude': '-89.85', 'name':'Kugaaruk' },
'YBC': { 'latitude':'49.2', 'longitude': '-68.266667', 'name':'Baie Comeau' },
'YBD': { 'latitude':'46.25', 'longitude': '-60.083333', 'name':'New Westminster' },
'YBE': { 'latitude':'59.566667', 'longitude': '-108.483333', 'name':'Uranium City' },
'YBF': { 'latitude':'48.833333', 'longitude': '-125.133333', 'name':'Bamfield' },
'YBG': { 'latitude':'48.333333', 'longitude': '-70.983333', 'name':'Bagotville' },
'NYA': { 'latitude':'62.1017', 'longitude': '65.6025', 'name':'Nyagan' },
'NYG': { 'latitude':'38.503611', 'longitude': '-77.305', 'name':'Quantico Nas' },
'PEW': { 'latitude':'34.033333', 'longitude': '71.616667', 'name':'Peshawar' },
'NYE': { 'latitude':'-0.2', 'longitude': '36.95', 'name':'Nyeri' },
'VBM': { 'latitude':'57.8575', 'longitude': '-157.0867', 'name':'Blue Mountain' },
'VBS': { 'latitude':'45.428889', 'longitude': '10.330556', 'name':'Brescia Montichiari' },
'UNG': { 'latitude':'-6.116667', 'longitude': '141.291667', 'name':'Kiunga' },
'VBV': { 'latitude':'-17.233333', 'longitude': '-178.95', 'name':'Vanuabalavu' },
'VBY': { 'latitude':'57.666667', 'longitude': '18.35', 'name':'Visby' },
'WHD': { 'latitude':'55.916667', 'longitude': '-130.016667', 'name':'SPB' },
'WHF': { 'latitude':'21.367222', 'longitude': '34.453056', 'name':'Wadi Halfa' },
'WHL': { 'latitude':'-38.688889', 'longitude': '146.45', 'name':'Welshpool' },
'WHO': { 'latitude':'-43.3', 'longitude': '170.016667', 'name':'Franz Josef' },
'WHH': { 'latitude':'-30.783333', 'longitude': '121.483333', 'name':'Hiltons Har H' },
'WHK': { 'latitude':'-37.933333', 'longitude': '176.933333', 'name':'Whakatane' },
'WHT': { 'latitude':'29.316667', 'longitude': '-96.1', 'name':'Wharton' },
'RCT': { 'latitude':'43.9', 'longitude': '-85.516667', 'name':'Miller Field' },
'WHP': { 'latitude':'34.259167', 'longitude': '-118.413333', 'name':'Whiteman' },
'WHS': { 'latitude':'60.366667', 'longitude': '-0.983333', 'name':'Whalsay' },
'RCL': { 'latitude':'-18.0', 'longitude': '169.0', 'name':'Redcliffe' },
'RCO': { 'latitude':'45.890556', 'longitude': '-0.980556', 'name':'Saint Agnant' },
'RCH': { 'latitude':'11.533333', 'longitude': '-72.933333', 'name':'Riohacha' },
'RCE': { 'latitude':'48.616667', 'longitude': '-123.116667', 'name':'Roche Harbor' },
'RCA': { 'latitude':'44.145', 'longitude': '-103.103611', 'name':'Ellsworth Afb' },
'VQS': { 'latitude':'18.133333', 'longitude': '-65.4', 'name':'Vieques' },
'TLT': { 'latitude':'61.098889', 'longitude': '-160.964722', 'name':'Tuluksak' },
'XQH': { 'latitude':'52.966667', 'longitude': '-1.166667', 'name':'Railway Station' },
'XQI': { 'latitude':'52.966667', 'longitude': '-1.166667', 'name':'Railway Station' },
'PEJ': { 'latitude':'40.594722', 'longitude': '17.006667', 'name':'Peschiei' },
'XQC': { 'latitude':'33.940278', 'longitude': '44.361667', 'name':'Balad' },
'XQP': { 'latitude':'9.45', 'longitude': '-84.15', 'name':'Quepos' },
'XQU': { 'latitude':'49.350556', 'longitude': '-124.450556', 'name':'Qualicum' },
'XQV': { 'latitude':'33.744722', 'longitude': '44.593333', 'name':'Baqubah' },
'JOP': { 'latitude':'-4.75', 'longitude': '145.016667', 'name':'Josephstaal' },
'PRD': { 'latitude':'-20.133333', 'longitude': '119.583333', 'name':'Pardoo' },
'JOR': { 'latitude':'33.791667', 'longitude': '-117.875', 'name':'The City Heliport' },
'JOS': { 'latitude':'9.639722', 'longitude': '8.869167', 'name':'Jos' },
'JOT': { 'latitude':'41.533333', 'longitude': '-88.083333', 'name':'Municipal' },
'PRC': { 'latitude':'34.65', 'longitude': '-112.416667', 'name':'Prescott' },
'PRB': { 'latitude':'35.666667', 'longitude': '-120.633333', 'name':'Paso Robles' },
'PRM': { 'latitude':'37.133333', 'longitude': '-8.533333', 'name':'Portimao' },
'PRL': { 'latitude':'60.208333', 'longitude': '-147.819444', 'name':'Port Oceanic' },
'PRO': { 'latitude':'18.6', 'longitude': '-74.05', 'name':'Municipal' },
'PRN': { 'latitude':'42.572778', 'longitude': '21.035833', 'name':'Prishtina International Airport' },
'PRI': { 'latitude':'-4.316667', 'longitude': '55.733333', 'name':'Praslin Island' },
'PRH': { 'latitude':'18.116667', 'longitude': '100.016667', 'name':'Phrae' },
'PRK': { 'latitude':'-29.666667', 'longitude': '22.7', 'name':'Prieska' },
'PRJ': { 'latitude':'40.583333', 'longitude': '14.233333', 'name':'Capri' },
'PRU': { 'latitude':'18.933333', 'longitude': '-95.216667', 'name':'Prome' },
'PRT': { 'latitude':'47.533333', 'longitude': '12.516667', 'name':'Coast Guard Heliport' },
'PRW': { 'latitude':'45.55', 'longitude': '-90.283333', 'name':'Prentice' },
'JOC': { 'latitude':'33.670418', 'longitude': '-117.8577', 'name':'Centerport Heliport' },
'PRQ': { 'latitude':'-26.766667', 'longitude': '-60.266667', 'name':'Pres. Roque Saenz Pena' },
'JOE': { 'latitude':'62.666667', 'longitude': '29.633333', 'name':'Joensuu' },
'PRS': { 'latitude':'-9.716667', 'longitude': '161.4', 'name':'Parasi' },
'JOG': { 'latitude':'-7.783333', 'longitude': '110.433333', 'name':'Adisutjipto' },
'JOH': { 'latitude':'-31.616667', 'longitude': '29.533333', 'name':'Port Saint Johns' },
'JOI': { 'latitude':'-26.217778', 'longitude': '-48.800278', 'name':'Lauro Carneiro De Loyola' },
'JOK': { 'latitude':'56.716667', 'longitude': '47.9', 'name':'Joshkar-Ola' },
'JOL': { 'latitude':'6.05', 'longitude': '121.016667', 'name':'Jolo' },
'JOM': { 'latitude':'-9.35', 'longitude': '34.8', 'name':'Njombe' },
'JON': { 'latitude':'16.730556', 'longitude': '-169.535278', 'name':'Johnston Island' },
'PRZ': { 'latitude':'44.3', 'longitude': '-120.85', 'name':'Prineville' },
'SNF': { 'latitude':'10.280278', 'longitude': '-68.753889', 'name':'San Felipe' },
'SNG': { 'latitude':'-16.333333', 'longitude': '-60.816667', 'name':'San Ignacio De Velasco' },
'SND': { 'latitude':'16.666667', 'longitude': '105.016667', 'name':'Seno' },
'SNE': { 'latitude':'16.583333', 'longitude': '-24.25', 'name':'Preguica' },
'XUZ': { 'latitude':'34.266667', 'longitude': '117.183333', 'name':'Xuzhou' },
'SNB': { 'latitude':'-11.333333', 'longitude': '130.75', 'name':'Snake Bay' },
'PEE': { 'latitude':'58.0', 'longitude': '56.25', 'name':'Perm' },
'SNC': { 'latitude':'-2.216667', 'longitude': '-80.966667', 'name':'Salinas' },
'SNA': { 'latitude':'33.666667', 'longitude': '-117.866667', 'name':'John Wayne' },
'SNN': { 'latitude':'52.7', 'longitude': '-8.916667', 'name':'Shannon' },
'SNO': { 'latitude':'17.15', 'longitude': '104.133333', 'name':'Sakon Nakhon' },
'PEF': { 'latitude':'54.15', 'longitude': '13.766667', 'name':'Peenemuende' },
'UYL': { 'latitude':'12.066667', 'longitude': '24.9', 'name':'Nyala' },
'UYN': { 'latitude':'38.333333', 'longitude': '109.483333', 'name':'Yulin' },
'SNM': { 'latitude':'-14.866667', 'longitude': '-65.583333', 'name':'San Ignacio De M' },
'YOJ': { 'latitude':'58.616667', 'longitude': '-117.166667', 'name':'Footner Lake' },
'TKF': { 'latitude':'39.32', 'longitude': '-120.139444', 'name':'Truckee-Tahoe' },
'NLP': { 'latitude':'-25.383056', 'longitude': '31.105556', 'name':'Nelspruit International' },
'NLS': { 'latitude':'-18.041667', 'longitude': '128.9', 'name':'Nicholson' },
'TKE': { 'latitude':'57.783333', 'longitude': '-135.216667', 'name':'Tenakee Springs' },
'NLU': { 'latitude':'19.35', 'longitude': '-99.116667', 'name':'Santa Lucia' },
'NLT': { 'latitude':'43.4322', 'longitude': '83.3822', 'name':'Nalati' },
'NLV': { 'latitude':'47.05', 'longitude': '31.916667', 'name':'Nikolaev' },
'HMT': { 'latitude':'33.75', 'longitude': '-116.966667', 'name':'Ryan Field' },
'TKO': { 'latitude':'-29.233333', 'longitude': '28.966667', 'name':'Tlokoeng' },
'HMV': { 'latitude':'65.8', 'longitude': '15.083333', 'name':'Hemavan' },
'TKM': { 'latitude':'17.216667', 'longitude': '-89.633333', 'name':'El Peten' },
'TKJ': { 'latitude':'63.3', 'longitude': '-143.0', 'name':'Tok' },
'SNT': { 'latitude':'7.666667', 'longitude': '-73.008333', 'name':'Sabana De Torres' },
'HMR': { 'latitude':'60.8', 'longitude': '11.1', 'name':'Hamar Arpt' },
'HMS': { 'latitude':'58.294444', 'longitude': '-135.347222', 'name':'Homeshore' },
'NLA': { 'latitude':'-13.0', 'longitude': '28.65', 'name':'Ndola' },
'TKW': { 'latitude':'-5.3', 'longitude': '142.216667', 'name':'Tekin' },
'HMN': { 'latitude':'32.85138888', 'longitude': '-106.10166666', 'name':'Holloman AFB' },
'HMO': { 'latitude':'29.1', 'longitude': '-111.05', 'name':'Gen Pesqueira Garcia' },
'NLE': { 'latitude':'41.85', 'longitude': '-86.216667', 'name':'Jerry Tyler Memorial' },
'HMI': { 'latitude':'42.483333', 'longitude': '93.505556', 'name':'Hami' },
'HMJ': { 'latitude':'49.416667', 'longitude': '27.0', 'name':'Khmelnitskiy' },
'NLF': { 'latitude':'-9.566667', 'longitude': '143.75', 'name':'Darnley Island' },
'HME': { 'latitude':'31.666667', 'longitude': '6.15', 'name':'Oued Irara Apt' },
'NLK': { 'latitude':'-29.041667', 'longitude': '167.938611', 'name':'Norfolk Island' },
'HMG': { 'latitude':'-23.966667', 'longitude': '132.666667', 'name':'Hermannsburg' },
'TKZ': { 'latitude':'-38.236667', 'longitude': '175.891944', 'name':'Tokoroa' },
'HMA': { 'latitude':'61.028611', 'longitude': '69.091944', 'name':'Khanty-Mansiysk' },
'NLO': { 'latitude':'-4.325', 'longitude': '15.326389', 'name':'Kinshasa N\'Dolo' },
'SNS': { 'latitude':'36.666667', 'longitude': '-121.616667', 'name':'Salinas' },
'DLC': { 'latitude':'38.965556', 'longitude': '121.538611', 'name':'Dalian' },
'DLB': { 'latitude':'56.741667', 'longitude': '23.891111', 'name':'Dalbertis' },
'DLA': { 'latitude':'4.016667', 'longitude': '9.716667', 'name':'Douala' },
'YOD': { 'latitude':'54.45', 'longitude': '-110.166667', 'name':'Cold Lake' },
'DLG': { 'latitude':'59.066667', 'longitude': '-158.466667', 'name':'Municipal' },
'DLF': { 'latitude':'29.516667', 'longitude': '-100.0', 'name':'Laughlin Afb' },
'DLE': { 'latitude':'47.042778', 'longitude': '5.435', 'name':'Tavaux' },
'DLD': { 'latitude':'60.466667', 'longitude': '8.5', 'name':'Dagali Airport' },
'DLK': { 'latitude':'-29.016667', 'longitude': '139.466667', 'name':'Dulkaninna' },
'DLI': { 'latitude':'11.75', 'longitude': '108.366667', 'name':'Lienkhang' },
'DLH': { 'latitude':'46.833333', 'longitude': '-92.183333', 'name':'Duluth International' },
'DLO': { 'latitude':'55.133333', 'longitude': '-132.051389', 'name':'Dolomi' },
'DLN': { 'latitude':'45.216667', 'longitude': '-112.633333', 'name':'Dillon' },
'DLM': { 'latitude':'36.716667', 'longitude': '28.783333', 'name':'Dalaman' },
'DLL': { 'latitude':'34.416667', 'longitude': '-79.366667', 'name':'Dillon' },
'DLS': { 'latitude':'45.618611', 'longitude': '-121.167222', 'name':'Columbia Gorge Regional/The Dalles Municipal Airport' },
'DLP': { 'latitude':'48.8725', 'longitude': '2.775833', 'name':'Disneyland Paris' },
'DLV': { 'latitude':'-12.416667', 'longitude': '130.341667', 'name':'Delissaville' },
'DLU': { 'latitude':'25.566667', 'longitude': '100.233333', 'name':'Dali' },
'DLZ': { 'latitude':'43.966667', 'longitude': '104.683333', 'name':'Dalanzadgad' },
'DLY': { 'latitude':'-18.7', 'longitude': '169.15', 'name':'Dillons Bay' },
'OAM': { 'latitude':'-44.966667', 'longitude': '171.083333', 'name':'Oamaru' },
'SSX': { 'latitude':'41.278056', 'longitude': '36.3', 'name':'Samsun' },
'SSZ': { 'latitude':'-23.916667', 'longitude': '-46.133333', 'name':'Santos' },
'SSU': { 'latitude':'61.833333', 'longitude': '-1.833333', 'name':'Greenbrier' },
'SNZ': { 'latitude':'-21.55', 'longitude': '-42.283333', 'name':'Santa Cruz' },
'SSW': { 'latitude':'48.7', 'longitude': '-123.2', 'name':'Stuart Island' },
'SSV': { 'latitude':'5.55', 'longitude': '120.816667', 'name':'Siasi' },
'SSQ': { 'latitude':'48.916667', 'longitude': '-79.166667', 'name':'La Sarre' },
'SSP': { 'latitude':'-13.983333', 'longitude': '143.55', 'name':'Silver Plains' },
'SSS': { 'latitude':'-5.9', 'longitude': '147.95', 'name':'Siassi' },
'SSR': { 'latitude':'-15.666667', 'longitude': '168.2', 'name':'Sara' },
'SSL': { 'latitude':'1.466667', 'longitude': '-72.233333', 'name':'Santa Rosalia' },
'PEB': { 'latitude':'-17.25', 'longitude': '38.183333', 'name':'Pebane' },
'SSI': { 'latitude':'50.933333', 'longitude': '5.95', 'name':'Mckinnon' },
'SNX': { 'latitude':'19.066667', 'longitude': '-69.383333', 'name':'Sabana De Mar' },
'SSK': { 'latitude':'-19.333333', 'longitude': '128.133333', 'name':'Sturt Creek' },
'SSJ': { 'latitude':'65.95', 'longitude': '12.466667', 'name':'Stokka' },
'SSE': { 'latitude':'17.633333', 'longitude': '75.933333', 'name':'Sholapur' },
'SSD': { 'latitude':'1.916667', 'longitude': '-67.1', 'name':'San Felipe' },
'SSG': { 'latitude':'3.75', 'longitude': '8.783333', 'name':'Santa Isabel' },
'SNY': { 'latitude':'41.1', 'longitude': '-102.983333', 'name':'Sidney' },
'SSA': { 'latitude':'-12.911111', 'longitude': '-38.331111', 'name':'Luis Eduardo Magalhaes' },
'SSC': { 'latitude':'53.283333', 'longitude': '10.9', 'name':'Shaw AFB' },
'SSB': { 'latitude':'17.75', 'longitude': '-64.75', 'name':'St Croix Island SPB' },
'PEC': { 'latitude':'57.95', 'longitude': '-136.233333', 'name':'Pelican SPB' },
'ECG': { 'latitude':'36.260556', 'longitude': '-76.174444', 'name':'Elizabeth City' },
'PVA': { 'latitude':'13.35', 'longitude': '-81.35', 'name':'Providencia' },
'RMP': { 'latitude':'65.5', 'longitude': '-150.15', 'name':'Rampart' },
'RMQ': { 'latitude':'24.265', 'longitude': '120.620833', 'name':'Taichung' },
'LNY': { 'latitude':'20.783333', 'longitude': '-156.95', 'name':'Lanai City' },
'LNX': { 'latitude':'54.8', 'longitude': '32.05', 'name':'Smolensk' },
'ECA': { 'latitude':'44.266667', 'longitude': '-83.483333', 'name':'Emmet County Airport' },
'LNZ': { 'latitude':'48.3', 'longitude': '14.3', 'name':'Blue Danube' },
'ECO': { 'latitude':'-1.616667', 'longitude': '-73.233333', 'name':'El Encanto' },
'ECN': { 'latitude':'35.15', 'longitude': '33.5', 'name':'Ercan' },
'LNV': { 'latitude':'-3.043611', 'longitude': '152.628889', 'name':'Lihir Island' },
'LNQ': { 'latitude':'-10.433333', 'longitude': '150.15', 'name':'Loani' },
'LNP': { 'latitude':'36.983333', 'longitude': '-82.566667', 'name':'Wise' },
'LNS': { 'latitude':'40.116667', 'longitude': '-76.3', 'name':'Lancaster' },
'ECH': { 'latitude':'-36.15', 'longitude': '144.75', 'name':'Echuca' },
'LNM': { 'latitude':'-7.216667', 'longitude': '146.2', 'name':'Langimar' },
'RMC': { 'latitude':'-32.85', 'longitude': '24.166667', 'name':'Machesney' },
'LNO': { 'latitude':'-28.883333', 'longitude': '121.3', 'name':'Leonora' },
'LNN': { 'latitude':'41.633333', 'longitude': '-81.416667', 'name':'Lost Nation' },
'ECS': { 'latitude':'43.883333', 'longitude': '-104.316667', 'name':'Mondell' },
'ECR': { 'latitude':'2.5', 'longitude': '-78.008333', 'name':'El Charco' },
'LNK': { 'latitude':'40.850833', 'longitude': '-96.759167', 'name':'Lincoln' },
'ECP': { 'latitude':'30.357803', 'longitude': '-85.798923', 'name':'Northwest Florida Beaches International Airport' },
'LNE': { 'latitude':'-19.019444', 'longitude': '170.008333', 'name':'Lonorore' },
'LND': { 'latitude':'42.8', 'longitude': '-108.675', 'name':'Hunt Field' },
'LNG': { 'latitude':'-8.166667', 'longitude': '146.116667', 'name':'Lese' },
'LNF': { 'latitude':'-4.866667', 'longitude': '141.216667', 'name':'Munbil' },
'LNA': { 'latitude':'26.593056', 'longitude': '-80.085', 'name':'Palm Beach County Park' },
'LNC': { 'latitude':'-6.366667', 'longitude': '147.366667', 'name':'Lengbati' },
'LNB': { 'latitude':'-16.583333', 'longitude': '168.183333', 'name':'Lamen Bay' },
'BBO': { 'latitude':'10.416667', 'longitude': '45.016667', 'name':'Berbera' },
'BBN': { 'latitude':'3.734722', 'longitude': '115.478333', 'name':'Bario' },
'BBM': { 'latitude':'13.083333', 'longitude': '103.216667', 'name':'Battambang' },
'BBL': { 'latitude':'36.65', 'longitude': '52.666667', 'name':'Babolsar' },
'BBK': { 'latitude':'-17.832778', 'longitude': '25.1625', 'name':'Kasane' },
'BBJ': { 'latitude':'49.95', 'longitude': '6.55', 'name':'Bitburg Air Base' },
'BBI': { 'latitude':'20.244444', 'longitude': '85.817778', 'name':'Bhubaneswar' },
'BBH': { 'latitude':'54.339722', 'longitude': '12.711667', 'name':'Barth' },
'BBG': { 'latitude':'3.083333', 'longitude': '172.816667', 'name':'Butaritari' },
'BBF': { 'latitude':'42.5', 'longitude': '-71.183333', 'name':'Burlington' },
'BBE': { 'latitude':'-27.416667', 'longitude': '117.666667', 'name':'Big Bell' },
'BBD': { 'latitude':'31.133333', 'longitude': '-99.333333', 'name':'Curtis Field' },
'BBC': { 'latitude':'28.983333', 'longitude': '-95.966667', 'name':'Bay City' },
'BBB': { 'latitude':'45.316667', 'longitude': '-95.6', 'name':'Municipal' },
'BBA': { 'latitude':'-45.916667', 'longitude': '-71.7', 'name':'Teniente Vidal' },
'BBZ': { 'latitude':'-13.533333', 'longitude': '23.116667', 'name':'Zambezi' },
'BBY': { 'latitude':'5.85', 'longitude': '20.633333', 'name':'Bambari' },
'BBX': { 'latitude':'40.15', 'longitude': '-75.266667', 'name':'Wings Field' },
'BBW': { 'latitude':'41.4', 'longitude': '-99.633333', 'name':'Broken Bow' },
'BBU': { 'latitude':'44.502778', 'longitude': '26.086111', 'name':'Baneasa' },
'BBT': { 'latitude':'4.216667', 'longitude': '15.783333', 'name':'Berberati' },
'BBS': { 'latitude':'51.330556', 'longitude': '-0.844444', 'name':'Blackbushe' },
'BBR': { 'latitude':'16.166667', 'longitude': '-61.75', 'name':'Baillif' },
'BBQ': { 'latitude':'17.6', 'longitude': '-61.783333', 'name':'Barbuda' },
'BBP': { 'latitude':'50.683333', 'longitude': '-1.083333', 'name':'Bembridge' },
'CYS': { 'latitude':'41.15', 'longitude': '-104.8', 'name':'Cheyenne' },
'CYR': { 'latitude':'-34.45', 'longitude': '-57.766667', 'name':'Laguna De Los Patos' },
'CYP': { 'latitude':'12.083333', 'longitude': '124.55', 'name':'Calbayog' },
'POZ': { 'latitude':'52.421111', 'longitude': '16.826389', 'name':'Lawica' },
'CYU': { 'latitude':'10.85', 'longitude': '121.0', 'name':'Cuyo' },
'CYT': { 'latitude':'60.083333', 'longitude': '-142.483333', 'name':'Intermediate' },
'POV': { 'latitude':'49.029722', 'longitude': '21.315556', 'name':'Presov' },
'CYZ': { 'latitude':'16.916667', 'longitude': '121.75', 'name':'Cauayan' },
'POT': { 'latitude':'18.166667', 'longitude': '-76.45', 'name':'Ken Jones' },
'CYX': { 'latitude':'68.75', 'longitude': '161.35', 'name':'Cherskiy' },
'POR': { 'latitude':'61.466667', 'longitude': '21.8', 'name':'Pori' },
'POS': { 'latitude':'10.65', 'longitude': '-61.516667', 'name':'Piarco International' },
'POP': { 'latitude':'19.8', 'longitude': '-70.666667', 'name':'La Union' },
'POQ': { 'latitude':'55.35', 'longitude': '-132.5', 'name':'Polk Inlet' },
'CYC': { 'latitude':'17.7', 'longitude': '-88.033333', 'name':'Caye Chapel' },
'CYB': { 'latitude':'19.716667', 'longitude': '-79.825', 'name':'Gerrard-Smith' },
'CYA': { 'latitude':'18.266667', 'longitude': '-73.783333', 'name':'Les Cayes' },
'POM': { 'latitude':'-9.433333', 'longitude': '147.22', 'name':'Jackson Fld' },
'CYG': { 'latitude':'-36.25', 'longitude': '147.9', 'name':'Corryong' },
'CYF': { 'latitude':'60.2', 'longitude': '-164.183333', 'name':'Chefornak SPB' },
'CYE': { 'latitude':'41.210278', 'longitude': '-75.832222', 'name':'Crystal Lake' },
'POI': { 'latitude':'-19.533333', 'longitude': '-65.75', 'name':'Potosi' },
'POF': { 'latitude':'36.75', 'longitude': '-90.5', 'name':'Earl Fields Memorial' },
'POG': { 'latitude':'-0.716667', 'longitude': '8.75', 'name':'Port Gentil' },
'CYI': { 'latitude':'23.466667', 'longitude': '120.383333', 'name':'Chiayi' },
'POE': { 'latitude':'31.033333', 'longitude': '-93.183333', 'name':'Polk AAF' },
'CYO': { 'latitude':'21.6175', 'longitude': '-81.550833', 'name':'Cayo Largo Del Sur' },
'POC': { 'latitude':'34.083333', 'longitude': '-117.783333', 'name':'Brackett Field' },
'CYM': { 'latitude':'57.5', 'longitude': '-134.75', 'name':'Chatham SPB' },
'CYL': { 'latitude':'15.483333', 'longitude': '-86.683333', 'name':'Coyoles' },
'FKH': { 'latitude':'52.833333', 'longitude': '-0.833333', 'name':'Sculthorp RAF' },
'FKI': { 'latitude':'0.481667', 'longitude': '25.338056', 'name':'Kisangani' },
'FKJ': { 'latitude':'36.083333', 'longitude': '136.25', 'name':'Fukui' },
'FKL': { 'latitude':'41.383333', 'longitude': '-79.866667', 'name':'Chess-Lambertin' },
'FKN': { 'latitude':'36.683333', 'longitude': '-76.916667', 'name':'Municipal' },
'FKB': { 'latitude':'48.779444', 'longitude': '8.080556', 'name':'Soellingen' },
'FKQ': { 'latitude':'-2.916667', 'longitude': '132.3', 'name':'Fak Fak' },
'FKS': { 'latitude':'37.226665', 'longitude': '140.43279', 'name':'Fukushima Airport' },
'WSR': { 'latitude':'-2.766667', 'longitude': '134.5', 'name':'Wasior' },
'VLA': { 'latitude':'38.95', 'longitude': '-89.083333', 'name':'Vandalia' },
'VLC': { 'latitude':'39.489444', 'longitude': '-0.481667', 'name':'Manises Airport' },
'VLG': { 'latitude':'-38.016667', 'longitude': '-57.583333', 'name':'Villa Gesell' },
'ETZ': { 'latitude':'48.979167', 'longitude': '6.247778', 'name':'Metz-nancy-lorraine' },
'MQA': { 'latitude':'-19.833333', 'longitude': '120.833333', 'name':'Mandora' },
'MQC': { 'latitude':'47.133333', 'longitude': '-56.383333', 'name':'Miquelon Aprt' },
'MQB': { 'latitude':'40.45', 'longitude': '-90.616667', 'name':'Municipal' },
'MQE': { 'latitude':'-22.816667', 'longitude': '137.35', 'name':'Marqua' },
'AWZ': { 'latitude':'31.216667', 'longitude': '48.666667', 'name':'Ahwaz' },
'MQG': { 'latitude':'62.366667', 'longitude': '6.433333', 'name':'Midgard' },
'MQF': { 'latitude':'53.393056', 'longitude': '58.755556', 'name':'Magnitogorsk' },
'MQI': { 'latitude':'42.25', 'longitude': '-71.0', 'name':'Quincy' },
'MQK': { 'latitude':'-11.7', 'longitude': '-66.65', 'name':'San Matias' },
'MQJ': { 'latitude':'37.516667', 'longitude': '36.45', 'name':'Merkez' },
'MQM': { 'latitude':'37.223336', 'longitude': '40.631667', 'name':'Mardin' },
'AWR': { 'latitude':'-4.116667', 'longitude': '144.85', 'name':'Awar' },
'MQO': { 'latitude':'13.25', 'longitude': '6.75', 'name':'Malam' },
'AWP': { 'latitude':'-20.333333', 'longitude': '137.25', 'name':'Austral Downs' },
'MQQ': { 'latitude':'8.633333', 'longitude': '16.066667', 'name':'Moundou' },
'AWN': { 'latitude':'-26.483333', 'longitude': '139.316667', 'name':'Alton Downs' },
'AWM': { 'latitude':'35.133333', 'longitude': '-90.183333', 'name':'Municipal' },
'MQR': { 'latitude':'2.666667', 'longitude': '-78.341667', 'name':'Mosquera' },
'AWK': { 'latitude':'19.283333', 'longitude': '166.65', 'name':'Wake Island' },
'MQT': { 'latitude':'46.533333', 'longitude': '-87.566667', 'name':'Sawyer International' },
'MQW': { 'latitude':'17.366667', 'longitude': '-88.766667', 'name':'Telfair-Wheeler' },
'AWH': { 'latitude':'8.266667', 'longitude': '44.183333', 'name':'Awareh' },
'MQY': { 'latitude':'35.983333', 'longitude': '-86.516667', 'name':'Smyrna' },
'MQX': { 'latitude':'13.466667', 'longitude': '39.516667', 'name':'Makale' },
'AWE': { 'latitude':'-0.75', 'longitude': '9.45', 'name':'Alowe' },
'AWD': { 'latitude':'-19.283333', 'longitude': '169.583333', 'name':'Aniwa' },
'AWB': { 'latitude':'-8.016667', 'longitude': '142.75', 'name':'Awaba' },
'AWA': { 'latitude':'6.966667', 'longitude': '38.402778', 'name':'Awassa' },
'OAL': { 'latitude':'-1.983333', 'longitude': '-46.216667', 'name':'Cacoal' },
'OAK': { 'latitude':'37.716667', 'longitude': '-122.216667', 'name':'Oakland International Airport' },
'OAJ': { 'latitude':'34.716667', 'longitude': '-77.416667', 'name':'Albert J Ellis' },
'DQA': { 'latitude':'46.59', 'longitude': '125.02', 'name':'Saertu' },
'VLS': { 'latitude':'-16.8', 'longitude': '168.2', 'name':'Valesdir' },
'VLU': { 'latitude':'56.383333', 'longitude': '30.616667', 'name':'Velikiye Luki' },
'VLV': { 'latitude':'9.35', 'longitude': '-70.616667', 'name':'Carvajal' },
'OAR': { 'latitude':'36.681944', 'longitude': '-121.762222', 'name':'Marina Municipal' },
'OAX': { 'latitude':'17.0', 'longitude': '-96.5', 'name':'Xoxocotlan' },
'ALO': { 'latitude':'42.55', 'longitude': '-92.383333', 'name':'Waterloo' },
'NAK': { 'latitude':'14.966667', 'longitude': '102.116667', 'name':'Nakhon Ratchasima' },
'WMX': { 'latitude':'-4.083333', 'longitude': '138.933333', 'name':'Wamena' },
'PCQ': { 'latitude':'18.492778', 'longitude': '102.417222', 'name':'Bounneua' },
'WJF': { 'latitude':'34.7', 'longitude': '-118.133333', 'name':'William J Fox' },
'WJA': { 'latitude':'7.466667', 'longitude': '168.566667', 'name':'Woja' },
'PCV': { 'latitude':'27.083333', 'longitude': '-112.0', 'name':'Punta Chivato' },
'WMR': { 'latitude':'-16.166667', 'longitude': '49.766667', 'name':'Mananara' },
'WJU': { 'latitude':'37.351389', 'longitude': '127.945278', 'name':'WonJu' },
'WJR': { 'latitude':'1.766667', 'longitude': '40.6', 'name':'Wajir' },
'TGQ': { 'latitude':'-6.183333', 'longitude': '-35.816667', 'name':'Tangara da Serra' },
'TGT': { 'latitude':'-5.092222', 'longitude': '39.071111', 'name':'Tanga' },
'TGX': { 'latitude':'10.486944', 'longitude': '-6.409722', 'name':'Tingrela' },
'WMN': { 'latitude':'-15.433333', 'longitude': '49.683333', 'name':'Maroantsetra' },
'ZYF': { 'latitude':'9.383333', 'longitude': '38.033333', 'name':'Faro TP' },
'ZYD': { 'latitude':'39.0', 'longitude': '-9.133333', 'name':'Lisbon TP' },
'ZYL': { 'latitude':'24.95', 'longitude': '91.866667', 'name':'Osmani International' },
'ZYK': { 'latitude':'30.7', 'longitude': '114.35', 'name':'Shekou Port' },
'ZYH': { 'latitude':'52.083333', 'longitude': '4.3', 'name':'Holland Spoor Rail Station' },
'ZYI': { 'latitude':'27.666667', 'longitude': '106.833333', 'name':'Zunyi' },
'ZYZ': { 'latitude':'51.216667', 'longitude': '4.416667', 'name':'Berchem Railway Stn.' },
'RVC': { 'latitude':'5.466667', 'longitude': '-9.583333', 'name':'Rivercess' },
'RVA': { 'latitude':'-22.8', 'longitude': '47.833333', 'name':'Farafangana' },
'RVE': { 'latitude':'6.951944', 'longitude': '-71.857222', 'name':'Los Colonizadores' },
'RVD': { 'latitude':'-17.833333', 'longitude': '-50.955278', 'name':'Rio Verde' },
'RVK': { 'latitude':'64.85', 'longitude': '11.233333', 'name':'Ryumsjoen' },
'RVH': { 'latitude':'59.983333', 'longitude': '30.6', 'name':'Rzhevka' },
'RVO': { 'latitude':'-27.6', 'longitude': '24.133333', 'name':'Reivilo' },
'RVN': { 'latitude':'66.561667', 'longitude': '25.830833', 'name':'Rovaniemi' },
'RVR': { 'latitude':'38.966667', 'longitude': '-110.25', 'name':'Green River' },
'RVV': { 'latitude':'-25.883333', 'longitude': '-147.65', 'name':'Rairua' },
'RVT': { 'latitude':'-33.6', 'longitude': '120.116666', 'name':'Ravensthorpe' },
'TGF': { 'latitude':'47.2', 'longitude': '-0.433333', 'name':'Tignes' },
'RVY': { 'latitude':'-31.033333', 'longitude': '-55.616667', 'name':'Rivera' },
'TGG': { 'latitude':'5.386111', 'longitude': '103.107778', 'name':'Sultan Mahmood' },
'TGE': { 'latitude':'46.966667', 'longitude': '17.083333', 'name':'Sharpe Field' },
'TGL': { 'latitude':'-11.333333', 'longitude': '153.216667', 'name':'Tagula' },
'XSP': { 'latitude':'1.366667', 'longitude': '103.966667', 'name':'Seletar' },
'XSC': { 'latitude':'21.5', 'longitude': '-71.5', 'name':'International' },
'XSD': { 'latitude':'62.2', 'longitude': '34.283333', 'name':'Test Range' },
'XSE': { 'latitude':'13.433333', 'longitude': '0.533333', 'name':'Sebba' },
'XSI': { 'latitude':'56.766667', 'longitude': '-98.95', 'name':'South Indian Lake' },
'XSO': { 'latitude':'7.7', 'longitude': '122.133333', 'name':'Siocon' },
'XSM': { 'latitude':'38.283333', 'longitude': '-76.633333', 'name':'St Marys' },
'PTO': { 'latitude':'-26.216667', 'longitude': '-52.666667', 'name':'Municipal' },
'PTN': { 'latitude':'29.75', 'longitude': '-91.308333', 'name':'Williams Memorial' },
'PTM': { 'latitude':'7.566667', 'longitude': '-70.183333', 'name':'Palmarito' },
'JMY': { 'latitude':'8.49', 'longitude': '-13.234167', 'name':'Mammy Yoko Heliport' },
'PTK': { 'latitude':'42.666667', 'longitude': '-83.4', 'name':'Pontiac' },
'PTJ': { 'latitude':'-38.383333', 'longitude': '141.633333', 'name':'Portland' },
'PTI': { 'latitude':'-16.483333', 'longitude': '145.45', 'name':'Port Douglas' },
'PTH': { 'latitude':'56.966667', 'longitude': '-158.633333', 'name':'Port Heiden' },
'PTG': { 'latitude':'-23.916667', 'longitude': '29.466667', 'name':'Polokwane' },
'JMS': { 'latitude':'46.933333', 'longitude': '-98.683333', 'name':'Jamestown' },
'PTE': { 'latitude':'-32.75', 'longitude': '153.8', 'name':'Port Stephens' },
'PTD': { 'latitude':'56.25', 'longitude': '-134.65', 'name':'Port Alexander' },
'PTC': { 'latitude':'55.791667', 'longitude': '-133.6', 'name':'Port Alice' },
'PTB': { 'latitude':'37.183333', 'longitude': '-77.516667', 'name':'Municipal' },
'PTA': { 'latitude':'60.2', 'longitude': '-145.333333', 'name':'Port Alsworth' },
'JMU': { 'latitude':'46.833333', 'longitude': '130.35', 'name':'Jiamusi' },
'JMK': { 'latitude':'37.433333', 'longitude': '25.35', 'name':'Mikonos' },
'JMH': { 'latitude':'42.033333', 'longitude': '-88.083333', 'name':'Marriott Heliport' },
'JMN': { 'latitude':'44.168889', 'longitude': '-93.995', 'name':'Municipal Heliport' },
'JMO': { 'latitude':'28.783333', 'longitude': '83.733333', 'name':'Jomsom' },
'PTY': { 'latitude':'8.966667', 'longitude': '-79.533333', 'name':'Tocumen International' },
'JMM': { 'latitude':'11.383333', 'longitude': '8.283333', 'name':'Malmo Harbour Heliport' },
'JMB': { 'latitude':'-14.700278', 'longitude': '16.083333', 'name':'Jamba' },
'JMC': { 'latitude':'37.879167', 'longitude': '-122.513611', 'name':'Marin County' },
'PTU': { 'latitude':'59.016667', 'longitude': '-161.816667', 'name':'Platinum' },
'PTT': { 'latitude':'37.7', 'longitude': '-98.75', 'name':'Pratt' },
'PTS': { 'latitude':'37.45', 'longitude': '-94.733333', 'name':'Municipal' },
'PTR': { 'latitude':'57.833333', 'longitude': '-153.25', 'name':'Pleasant Harbour' },
'JMD': { 'latitude':'7.716667', 'longitude': '40.916667', 'name':'Market Centre H/P' },
'PTP': { 'latitude':'16.266667', 'longitude': '-61.533333', 'name':'Le Raizet' },
'YWS': { 'latitude':'50.15', 'longitude': '-122.966667', 'name':'Whistler' },
'NAW': { 'latitude':'6.416667', 'longitude': '101.8', 'name':'Narathiwat' },
'UWA': { 'latitude':'42.25', 'longitude': '-72.233333', 'name':'Ware' },
'SUG': { 'latitude':'9.766667', 'longitude': '125.483333', 'name':'Surigao' },
'SUF': { 'latitude':'38.9', 'longitude': '16.233333', 'name':'S Eufemia' },
'SUE': { 'latitude':'44.833333', 'longitude': '-87.416667', 'name':'Door County' },
'SUD': { 'latitude':'35.733333', 'longitude': '-96.65', 'name':'Stroud' },
'SUC': { 'latitude':'44.4', 'longitude': '-104.366667', 'name':'Schloredt' },
'SUB': { 'latitude':'-7.379722', 'longitude': '112.786944', 'name':'Juanda' },
'SUA': { 'latitude':'27.183333', 'longitude': '-80.216667', 'name':'Witham Field' },
'SUO': { 'latitude':'-0.533333', 'longitude': '-88.55', 'name':'Sun River' },
'SUN': { 'latitude':'43.5', 'longitude': '-114.316667', 'name':'Sun Valley' },
'SUM': { 'latitude':'33.9', 'longitude': '-80.116667', 'name':'Municipal' },
'SUL': { 'latitude':'28.633333', 'longitude': '69.2', 'name':'Sui' },
'SUK': { 'latitude':'37.45', 'longitude': '129.133333', 'name':'Samcheok' },
'SUJ': { 'latitude':'47.7', 'longitude': '22.883333', 'name':'Satu Mare' },
'SUI': { 'latitude':'42.866667', 'longitude': '41.116667', 'name':'Babusheri' },
'SUH': { 'latitude':'22.583333', 'longitude': '59.516667', 'name':'Sur' },
'SUW': { 'latitude':'46.733333', 'longitude': '-92.166667', 'name':'Richard I Bong Arpt' },
'SUV': { 'latitude':'-18.033333', 'longitude': '178.566667', 'name':'Nausori' },
'SUU': { 'latitude':'5.816667', 'longitude': '-54.816667', 'name':'Travis AFB' },
'SUT': { 'latitude':'-7.966667', 'longitude': '31.616667', 'name':'Sumbawanga' },
'SUS': { 'latitude':'38.662222', 'longitude': '-90.651944', 'name':'Spirit Of St Louis' },
'SUR': { 'latitude':'52.715278', 'longitude': '-88.5475', 'name':'Summer Beaver' },
'SUQ': { 'latitude':'-2.466667', 'longitude': '-78.183333', 'name':'Sucua' },
'SUP': { 'latitude':'-7.066667', 'longitude': '113.933333', 'name':'Trunojoyo' },
'SUZ': { 'latitude':'-7.166667', 'longitude': '143.916667', 'name':'Suria' },
'SUY': { 'latitude':'66.016667', 'longitude': '-23.833333', 'name':'Sudureyri' },
'SUX': { 'latitude':'42.4', 'longitude': '-96.383333', 'name':'Sioux Gateway' },
'TEH': { 'latitude':'36.766667', 'longitude': '49.5', 'name':'Tetlin' },
'TEI': { 'latitude':'27.916667', 'longitude': '96.166667', 'name':'Tezu' },
'NBX': { 'latitude':'-3.3', 'longitude': '135.883333', 'name':'Nabire' },
'TEL': { 'latitude':'5.65', 'longitude': '117.116667', 'name':'Telupid' },
'TEM': { 'latitude':'-34.433333', 'longitude': '147.533333', 'name':'Temora' },
'TEN': { 'latitude':'27.633333', 'longitude': '109.05', 'name':'Tongren' },
'TEO': { 'latitude':'-8.166667', 'longitude': '146.2', 'name':'Terapo' },
'NBS': { 'latitude':'42.047916', 'longitude': '127.562141', 'name':'Changbaishan' },
'NBR': { 'latitude':'-26.633333', 'longitude': '152.95', 'name':'Nambour' },
'TEB': { 'latitude':'40.85', 'longitude': '-74.060833', 'name':'Teterboro' },
'TEC': { 'latitude':'-24.35', 'longitude': '-50.616667', 'name':'Telemaco Borba' },
'NBW': { 'latitude':'20.144444', 'longitude': '-75.209167', 'name':'Guantanamo NAS' },
'NBV': { 'latitude':'-13.538056', 'longitude': '-48.246944', 'name':'Cana Brava' },
'NBU': { 'latitude':'-32.683333', 'longitude': '151.633333', 'name':'NAS' },
'TEG': { 'latitude':'11.78', 'longitude': '-0.369722', 'name':'Tenkodogo' },
'TEX': { 'latitude':'37.953132', 'longitude': '-107.909088', 'name':'Telluride' },
'TEY': { 'latitude':'65.866667', 'longitude': '-23.5', 'name':'Thingeyri' },
'TEZ': { 'latitude':'26.633333', 'longitude': '92.8', 'name':'Salonibari' },
'NBH': { 'latitude':'-30.65', 'longitude': '153.0', 'name':'Nambucca Heads' },
'NBO': { 'latitude':'-1.316667', 'longitude': '36.930833', 'name':'Nairobi Jomo Kenyatta' },
'NBL': { 'latitude':'9.466667', 'longitude': '-79.0', 'name':'San Blas' },
'NBC': { 'latitude':'55.566667', 'longitude': '52.1', 'name':'Naberevnye Chelny' },
'NBB': { 'latitude':'3.333333', 'longitude': '-70.333333', 'name':'Barrancominas' },
'NBA': { 'latitude':'-6.25', 'longitude': '145.233333', 'name':'Nambaiyufa' },
'TES': { 'latitude':'15.116667', 'longitude': '36.683333', 'name':'Tessenei' },
'NBG': { 'latitude':'7.435556', 'longitude': '123.415', 'name':'NAS/Alvin Callendar' },
'MWY': { 'latitude':'-17.366667', 'longitude': '141.866667', 'name':'Miranda Downs' },
'NBE': { 'latitude':'36.075832', 'longitude': '10.438611', 'name':'Zine El Abidine Ben Ali International Airport' },
'TEW': { 'latitude':'-17.383333', 'longitude': '49.4', 'name':'Tohid' },
'DNE': { 'latitude':'7.716667', 'longitude': '40.916667', 'name':'Dallas North Airport' },
'DND': { 'latitude':'56.4525', 'longitude': '-3.016667', 'name':'Dundee' },
'DNG': { 'latitude':'13.662778', 'longitude': '122.3275', 'name':'Doongan' },
'DNF': { 'latitude':'32.55', 'longitude': '22.766667', 'name':'Martuba' },
'DNA': { 'latitude':'26.355556', 'longitude': '127.7675', 'name':'Kadena AB' },
'DNC': { 'latitude':'7.262778', 'longitude': '-8.159722', 'name':'Danane' },
'DNB': { 'latitude':'-16.083333', 'longitude': '142.416667', 'name':'Dunbar' },
'DNM': { 'latitude':'-25.916667', 'longitude': '113.533333', 'name':'Denham' },
'DNL': { 'latitude':'33.466389', 'longitude': '-82.039444', 'name':'Daniel Field' },
'DNO': { 'latitude':'-11.616667', 'longitude': '-46.85', 'name':'Dianopolis' },
'DNN': { 'latitude':'34.716667', 'longitude': '-84.866667', 'name':'Municipal' },
'DNI': { 'latitude':'14.383333', 'longitude': '33.533333', 'name':'Wad Medani' },
'DNH': { 'latitude':'40.2', 'longitude': '94.683333', 'name':'Dunhuang' },
'DNK': { 'latitude':'48.45', 'longitude': '34.983333', 'name':'Dnepropetrovsk' },
'DNU': { 'latitude':'-6.15', 'longitude': '146.666667', 'name':'Dinangat' },
'DNT': { 'latitude':'33.753853', 'longitude': '-117.868004', 'name':'Downtown Heliport' },
'DNV': { 'latitude':'40.199722', 'longitude': '-87.595556', 'name':'Vermilion County' },
'DNQ': { 'latitude':'-35.55', 'longitude': '144.95', 'name':'Deniliquin' },
'DNP': { 'latitude':'28.116667', 'longitude': '82.316667', 'name':'Dang' },
'DNS': { 'latitude':'41.983333', 'longitude': '-95.383333', 'name':'Municipal' },
'DNR': { 'latitude':'48.583333', 'longitude': '-2.083333', 'name':'Pleurtuit' },
'DNX': { 'latitude':'12.0', 'longitude': '35.5', 'name':'Galegu' },
'DNZ': { 'latitude':'37.787222', 'longitude': '29.703333', 'name':'Cardak' },
'GJL': { 'latitude':'36.8', 'longitude': '5.883333', 'name':'Jijel' },
'QCU': { 'latitude':'68.75', 'longitude': '-52.333333', 'name':'Heliport' },
'QCE': { 'latitude':'49.3', 'longitude': '-1.5', 'name':'Van Service' },
'RKT': { 'latitude':'25.613611', 'longitude': '55.938889', 'name':'Ras Al Khaimah' },
'RKU': { 'latitude':'-8.816667', 'longitude': '146.516667', 'name':'Kairuku' },
'RKV': { 'latitude':'64.13', 'longitude': '-21.940556', 'name':'Keflavik' },
'RKW': { 'latitude':'35.916667', 'longitude': '-84.683333', 'name':'Municipal' },
'EAM': { 'latitude':'17.6', 'longitude': '44.416667', 'name':'Nejran' },
'EAL': { 'latitude':'9.083333', 'longitude': '167.333333', 'name':'Elenak' },
'RKR': { 'latitude':'35.05', 'longitude': '-94.616667', 'name':'Robert S Kerr' },
'EAN': { 'latitude':'42.058333', 'longitude': '-104.919444', 'name':'Phifer Field' },
'EAA': { 'latitude':'64.766667', 'longitude': '-141.15', 'name':'Eagle' },
'EAB': { 'latitude':'15.3', 'longitude': '43.966667', 'name':'Abbse' },
'EAE': { 'latitude':'-17.066667', 'longitude': '168.4', 'name':'Emae' },
'RKY': { 'latitude':'-13.65', 'longitude': '142.616667', 'name':'Rokeby' },
'RKD': { 'latitude':'44.066667', 'longitude': '-69.1', 'name':'Knox County Regional' },
'RKE': { 'latitude':'55.583333', 'longitude': '12.133333', 'name':'Roskilde Airport' },
'RKA': { 'latitude':'-15.4833', 'longitude': '-145.46667', 'name':'Aratika' },
'RKC': { 'latitude':'41.733333', 'longitude': '-122.633333', 'name':'Yreka' },
'EAP': { 'latitude':'47.6', 'longitude': '7.533333', 'name':'Euroairport Basel Mulhouse Freiburg' },
'EAS': { 'latitude':'43.35', 'longitude': '-1.8', 'name':'Donostia - San Sebastian' },
'EAR': { 'latitude':'40.733333', 'longitude': '-99.016667', 'name':'Kearney' },
'EAU': { 'latitude':'44.865833', 'longitude': '-91.484167', 'name':'Chippewa Valley Regional Airport' },
'EAT': { 'latitude':'47.4', 'longitude': '-120.2', 'name':'Pangborn Field' },
'HOF': { 'latitude':'25.285278', 'longitude': '49.485278', 'name':'Alahsa' },
'HOG': { 'latitude':'20.5', 'longitude': '-76.233333', 'name':'Frank Pais' },
'HOD': { 'latitude':'14.747222', 'longitude': '42.982778', 'name':'Hodeidah Arpt' },
'HOE': { 'latitude':'20.5', 'longitude': '103.75', 'name':'Houeisay' },
'HOB': { 'latitude':'32.683333', 'longitude': '-103.216667', 'name':'Lea County' },
'HOC': { 'latitude':'-7.416667', 'longitude': '145.883333', 'name':'Komako' },
'HOA': { 'latitude':'-1.483333', 'longitude': '40.033333', 'name':'Hola' },
'HON': { 'latitude':'44.383333', 'longitude': '-98.233333', 'name':'Howes' },
'HOO': { 'latitude':'11.983333', 'longitude': '107.566667', 'name':'Nhon Co' },
'HOL': { 'latitude':'62.9', 'longitude': '-159.516667', 'name':'Holikachu' },
'HOM': { 'latitude':'59.633333', 'longitude': '-151.5', 'name':'Homer' },
'HOK': { 'latitude':'-18.366667', 'longitude': '130.666667', 'name':'Hooker Creek' },
'HOH': { 'latitude':'47.383333', 'longitude': '9.7', 'name':'Hohenems' },
'HOI': { 'latitude':'-18.2', 'longitude': '-140.816667', 'name':'Hao Island' },
'HOV': { 'latitude':'62.2', 'longitude': '6.15', 'name':'Hovden' },
'HOW': { 'latitude':'8.916667', 'longitude': '-79.583333', 'name':'Howard Afb' },
'HOT': { 'latitude':'34.483333', 'longitude': '-93.1', 'name':'Memorial Field' },
'HOU': { 'latitude':'29.645556', 'longitude': '-95.278889', 'name':'William P Hobby' },
'HOR': { 'latitude':'38.533333', 'longitude': '-28.616667', 'name':'Horta' },
'HOP': { 'latitude':'50.516667', 'longitude': '23.666667', 'name':'Campbell AAF' },
'HOQ': { 'latitude':'50.316667', 'longitude': '11.916667', 'name':'Hof' },
'NWP': { 'latitude':'47.3', 'longitude': '-54.0', 'name':'NS' },
'HOX': { 'latitude':'24.866667', 'longitude': '94.916667', 'name':'Homalin' },
'HOY': { 'latitude':'58.833333', 'longitude': '-3.3', 'name':'Hoy Island' },
'VSE': { 'latitude':'40.65', 'longitude': '-7.916667', 'name':'Viseu' },
'OYS': { 'latitude':'37.85', 'longitude': '-119.55', 'name':'Yosemite Ntl Park' },
'OYP': { 'latitude':'3.9', 'longitude': '-51.8', 'name':'St-Georges de lOyapock' },
'OYN': { 'latitude':'-32.066667', 'longitude': '142.333333', 'name':'Ouyen' },
'OYL': { 'latitude':'3.533333', 'longitude': '39.05', 'name':'Moyale' },
'OYK': { 'latitude':'3.866667', 'longitude': '-51.8', 'name':'Oiapoque' },
'OYG': { 'latitude':'3.65', 'longitude': '31.716667', 'name':'Moyo' },
'OYE': { 'latitude':'1.566667', 'longitude': '11.583333', 'name':'Oyem' },
'ALT': { 'latitude':'-1.938889', 'longitude': '-54.747222', 'name':'Alenquer' },
'OYA': { 'latitude':'-29.1', 'longitude': '-59.25', 'name':'Goya' },
'LHG': { 'latitude':'-29.4', 'longitude': '147.966667', 'name':'Lightning Ridge' },
'LHE': { 'latitude':'31.521667', 'longitude': '74.403611', 'name':'Alama Iqbal International' },
'FIV': { 'latitude':'57.27', 'longitude': '-133.631389', 'name':'Five Finger' },
'LHB': { 'latitude':'54.233333', 'longitude': '-165.6', 'name':'Lost Harbor Sea Port' },
'LHA': { 'latitude':'48.375', 'longitude': '7.838889', 'name':'Black Forest' },
'FIZ': { 'latitude':'-18.166667', 'longitude': '125.55', 'name':'Fitzroy Crossing' },
'LHN': { 'latitude':'24.25', 'longitude': '121.216667', 'name':'Lishan' },
'LHM': { 'latitude':'38.909167', 'longitude': '-121.351389', 'name':'Lincoln Regional Airport' },
'LHK': { 'latitude':'32.266667', 'longitude': '111.633333', 'name':'Guanghua' },
'LHI': { 'latitude':'-3.133333', 'longitude': '139.9', 'name':'Lereh' },
'LHW': { 'latitude':'36.016667', 'longitude': '103.75', 'name':'Lanzhou Airport' },
'FIC': { 'latitude':'55.777778', 'longitude': '-131.5375', 'name':'Fire Cove' },
'LHU': { 'latitude':'-17.833333', 'longitude': '23.0', 'name':'Lianshulu' },
'LHS': { 'latitude':'-46.533333', 'longitude': '-68.95', 'name':'Las Heras' },
'FIG': { 'latitude':'10.35', 'longitude': '-13.566667', 'name':'Fria' },
'FID': { 'latitude':'41.266667', 'longitude': '-72.033333', 'name':'Elizabeth Field' },
'FIE': { 'latitude':'59.5', 'longitude': '-1.666667', 'name':'Fair Isle' },
'FIK': { 'latitude':'-25.583333', 'longitude': '134.6', 'name':'Finke' },
'FIH': { 'latitude':'-4.385833', 'longitude': '15.444444', 'name':'N’djili International' },
'FIN': { 'latitude':'-6.616667', 'longitude': '147.85', 'name':'Finschhafen' },
'FIL': { 'latitude':'38.966667', 'longitude': '-112.333333', 'name':'Municipal' },
'NWH': { 'latitude':'43.333333', 'longitude': '-72.166667', 'name':'Parlin Field' },
'NWI': { 'latitude':'52.516667', 'longitude': '1.25', 'name':'Norwich International Airport' },
'RMT': { 'latitude':'-22.63556', 'longitude': '-152.854156', 'name':'Rimatara' },
'TKS': { 'latitude':'34.132778', 'longitude': '134.606389', 'name':'Tokushima' },
'DSN': { 'latitude':'39.85', 'longitude': '110.033333', 'name':'Dongsheng' },
'DSL': { 'latitude':'8.0', 'longitude': '-10.8', 'name':'Daru' },
'DSM': { 'latitude':'41.533889', 'longitude': '-93.663056', 'name':'Des Moines International' },
'DSK': { 'latitude':'31.833333', 'longitude': '70.841667', 'name':'Dera Ismail Khan' },
'DSI': { 'latitude':'30.388611', 'longitude': '-86.538333', 'name':'Destin-Fort Walton Beach Airport' },
'DSD': { 'latitude':'16.333333', 'longitude': '-61.016667', 'name':'La Desirade' },
'DSE': { 'latitude':'11.066667', 'longitude': '39.716667', 'name':'Combolcha' },
'DSC': { 'latitude':'5.833333', 'longitude': '10.091667', 'name':'Dschang' },
'DSA': { 'latitude':'53.474722', 'longitude': '-1.004444', 'name':'Robin Hood' },
'AUA': { 'latitude':'12.5', 'longitude': '-70.016667', 'name':'Reina Beatrix' },
'AUC': { 'latitude':'7.066667', 'longitude': '-70.733333', 'name':'Arauca' },
'AUB': { 'latitude':'-7.1', 'longitude': '-41.983333', 'name':'Itauba' },
'AUE': { 'latitude':'28.966667', 'longitude': '33.183333', 'name':'Abu Rudeis' },
'AUD': { 'latitude':'-18.666667', 'longitude': '139.933333', 'name':'Augustus Downs' },
'AUG': { 'latitude':'44.316667', 'longitude': '-69.8', 'name':'Augusta' },
'AUF': { 'latitude':'47.846389', 'longitude': '3.496667', 'name':'Auxerre Branches' },
'AUI': { 'latitude':'-1.45', 'longitude': '143.066667', 'name':'Aua Island' },
'AUH': { 'latitude':'24.433056', 'longitude': '54.651111', 'name':'Abu Dhabi International' },
'AUK': { 'latitude':'62.683333', 'longitude': '-164.633333', 'name':'Alakanuk' },
'AUJ': { 'latitude':'-4.25', 'longitude': '142.85', 'name':'Ambunti' },
'AUM': { 'latitude':'43.666667', 'longitude': '-92.933333', 'name':'Austin' },
'AUL': { 'latitude':'8.133333', 'longitude': '171.166667', 'name':'Aur Island' },
'AUO': { 'latitude':'32.616667', 'longitude': '-85.433333', 'name':'Auburn-Opelika' },
'AUN': { 'latitude':'38.9', 'longitude': '-121.066667', 'name':'Auburn' },
'AUQ': { 'latitude':'-9.8', 'longitude': '-139.033333', 'name':'Atuona' },
'AUP': { 'latitude':'-9.916667', 'longitude': '149.333333', 'name':'Agaun' },
'AUS': { 'latitude':'30.194444', 'longitude': '-97.67', 'name':'Austin-bergstrom International' },
'AUR': { 'latitude':'44.8975', 'longitude': '2.4166667', 'name':'Aurillac Tronquiere' },
'AUU': { 'latitude':'-13.166667', 'longitude': '142.25', 'name':'Aurukun Mission' },
'AUT': { 'latitude':'-8.0', 'longitude': '125.675', 'name':'Atauro' },
'AUW': { 'latitude':'44.766667', 'longitude': '-89.680556', 'name':'Municipal' },
'AUV': { 'latitude':'-5.733333', 'longitude': '148.5', 'name':'Aumo' },
'AUY': { 'latitude':'-20.333333', 'longitude': '169.666667', 'name':'Aneityum' },
'AUX': { 'latitude':'-7.2', 'longitude': '-48.2', 'name':'Araguaina' },
'AUZ': { 'latitude':'41.766667', 'longitude': '-88.316667', 'name':'Municipal Airport' },
'HAI': { 'latitude':'6.0', 'longitude': '-9.75', 'name':'Dr Haines' },
'BNY': { 'latitude':'-11.3', 'longitude': '159.816667', 'name':'Bellona' },
'HAK': { 'latitude':'19.983333', 'longitude': '110.033333', 'name':'Haikou' },
'XHW': { 'latitude':'-23.566667', 'longitude': '145.8', 'name':'Alice Springs Railway' },
'XHX': { 'latitude':'-33.1375', 'longitude': '136.303056', 'name':'Adelaide Keswick Rail' },
'YFE': { 'latitude':'48.733333', 'longitude': '-69.1', 'name':'Forestville' },
'YFG': { 'latitude':'54.55', 'longitude': '-71.183333', 'name':'Fontanges' },
'YFA': { 'latitude':'52.241667', 'longitude': '-81.591667', 'name':'Fort Albany' },
'YFB': { 'latitude':'63.75', 'longitude': '-68.55', 'name':'Iqaluit' },
'YFC': { 'latitude':'45.866667', 'longitude': '-66.533333', 'name':'Fredericton' },
'YFL': { 'latitude':'62.711944', 'longitude': '-109.162778', 'name':'Fort Reliance' },
'YFO': { 'latitude':'54.75', 'longitude': '-101.833333', 'name':'Flin Flon' },
'YFH': { 'latitude':'51.55', 'longitude': '-87.983333', 'name':'Fort Hope' },
'YFJ': { 'latitude':'64.1839', 'longitude': '-114.0672', 'name':'Snare Lake' },
'YFR': { 'latitude':'61.183333', 'longitude': '-113.683333', 'name':'Fort Resolution' },
'BNR': { 'latitude':'10.633333', 'longitude': '-4.766667', 'name':'Banfora' },
'YFX': { 'latitude':'52.366667', 'longitude': '-55.683333', 'name':'Fox Harbour' },
'HAB': { 'latitude':'34.116667', 'longitude': '-88.0', 'name':'Marion County' },
'BNP': { 'latitude':'32.966667', 'longitude': '70.533333', 'name':'Bannu' },
'BNW': { 'latitude':'42.066667', 'longitude': '-93.883333', 'name':'Boone' },
'BNV': { 'latitude':'-6.416667', 'longitude': '146.816667', 'name':'Boana' },
'BNU': { 'latitude':'-26.933333', 'longitude': '-49.05', 'name':'Blumenau' },
'BNK': { 'latitude':'-28.868889', 'longitude': '153.5625', 'name':'Ballina Byron Gateway' },
'ONL': { 'latitude':'42.45', 'longitude': '-98.65', 'name':'Municipal' },
'BNI': { 'latitude':'6.316667', 'longitude': '5.616667', 'name':'Benin City' },
'SCM': { 'latitude':'61.866667', 'longitude': '-165.583333', 'name':'SPB' },
'VFA': { 'latitude':'-18.095833', 'longitude': '25.833889', 'name':'Victoria Falls' },
'BNC': { 'latitude':'0.566667', 'longitude': '29.466667', 'name':'Beni' },
'BNB': { 'latitude':'-0.233333', 'longitude': '20.833333', 'name':'Boende' },
'SCL': { 'latitude':'-33.559722', 'longitude': '-70.7', 'name':'Arturo Merino Benitez' },
'WTP': { 'latitude':'-8.55', 'longitude': '147.25', 'name':'Woitape' },
'WTR': { 'latitude':'33.816667', 'longitude': '-109.983333', 'name':'White River' },
'WTS': { 'latitude':'-18.757222', 'longitude': '46.054444', 'name':'Tsiroanomandidy' },
'WTT': { 'latitude':'-6.05', 'longitude': '146.4', 'name':'Wantoat' },
'BNG': { 'latitude':'33.933333', 'longitude': '-116.866667', 'name':'Banning' },
'WTZ': { 'latitude':'-36.833333', 'longitude': '175.7', 'name':'Whitianga' },
'BNF': { 'latitude':'57.083333', 'longitude': '-134.816667', 'name':'Warm Spring Bay SPB' },
'WTA': { 'latitude':'-17.5', 'longitude': '43.833333', 'name':'Tambohorano' },
'WTC': { 'latitude':'40.666667', 'longitude': '-74.016667', 'name':'World Trade Center' },
'WTD': { 'latitude':'26.683333', 'longitude': '-78.983333', 'name':'West End' },
'BNE': { 'latitude':'-27.383333', 'longitude': '153.116667', 'name':'Brisbane International' },
'RMF': { 'latitude':'25.557222', 'longitude': '34.583611', 'name':'Marsa Alam Intl' },
'BND': { 'latitude':'27.2', 'longitude': '56.25', 'name':'Bandar Abbas' },
'WTL': { 'latitude':'60.35', 'longitude': '-162.633333', 'name':'Tuntutuliak' },
'WTN': { 'latitude':'53.166667', 'longitude': '-0.533333', 'name':'RAF Station' },
'WTO': { 'latitude':'10.166667', 'longitude': '166.033333', 'name':'Wotho Island' },
'RMG': { 'latitude':'34.35', 'longitude': '-85.166667', 'name':'Richard B Russell' },
'ONS': { 'latitude':'-21.666667', 'longitude': '115.1', 'name':'Onslow' },
'YEL': { 'latitude':'46.35', 'longitude': '-82.55', 'name':'Elliot Lake' },
'ONQ': { 'latitude':'41.25', 'longitude': '31.833333', 'name':'Zonguldak' },
'ZWH': { 'latitude':'-22.5', 'longitude': '17.0', 'name':'Railway Station' },
'ZWI': { 'latitude':'-32.65', 'longitude': '138.1', 'name':'Wilmington Rail' },
'ZWL': { 'latitude':'58.116667', 'longitude': '-103.158333', 'name':'Wollaston Lake' },
'ZWA': { 'latitude':'-14.65', 'longitude': '49.616667', 'name':'Andapa' },
'ZWB': { 'latitude':'52.166667', 'longitude': '-2.016667', 'name':'Williamsburg Rail' },
'RME': { 'latitude':'43.233889', 'longitude': '-75.406944', 'name':'Griffiss AFB' },
'ZWR': { 'latitude':'5.983333', 'longitude': '116.066667', 'name':'Kota Kinabalu Port' },
'ZWW': { 'latitude':'52.166667', 'longitude': '-2.016667', 'name':'Newport News Rail' },
'RTE': { 'latitude':'55.7', 'longitude': '-131.633333', 'name':'Marguerite Bay' },
'RTD': { 'latitude':'26.866667', 'longitude': '-82.266667', 'name':'Rotunda' },
'RTG': { 'latitude':'-8.6', 'longitude': '120.45', 'name':'Ruteng' },
'RTA': { 'latitude':'-14.5', 'longitude': '172.5', 'name':'Rotuma Island' },
'RTC': { 'latitude':'17.0', 'longitude': '73.316667', 'name':'Ratnagiri' },
'RTB': { 'latitude':'16.316944', 'longitude': '-86.523056', 'name':'Roatan' },
'RTM': { 'latitude':'51.956944', 'longitude': '4.437222', 'name':'Rotterdam Zestienhoven' },
'RTL': { 'latitude':'43.416667', 'longitude': '-95.1', 'name':'Spirit Lake' },
'RTN': { 'latitude':'36.733333', 'longitude': '-104.5', 'name':'Crews Field' },
'RTI': { 'latitude':'-10.483333', 'longitude': '123.366667', 'name':'Roti' },
'RTW': { 'latitude':'51.565', 'longitude': '46.046667', 'name':'Saratov' },
'RTP': { 'latitude':'-15.6', 'longitude': '141.833333', 'name':'Rutland Plains' },
'RTS': { 'latitude':'-32.0', 'longitude': '115.533333', 'name':'Rottnest Island' },
'RTY': { 'latitude':'-29.0', 'longitude': '138.733333', 'name':'Merty' },
'RMK': { 'latitude':'-34.2', 'longitude': '140.683333', 'name':'Renmark' },
'YET': { 'latitude':'53.583333', 'longitude': '-116.433333', 'name':'Edson' },
'ISZ': { 'latitude':'39.246667', 'longitude': '-84.388889', 'name':'Cincinnati-Blue Ash Airport' },
'XUV': { 'latitude':'58.383333', 'longitude': '6.95', 'name':'Storekvina Railway' },
'XUW': { 'latitude':'63.033333', 'longitude': '10.3', 'name':'Storen Railway' },
'ISS': { 'latitude':'43.969444', 'longitude': '-69.716667', 'name':'Wiscasset' },
'RMI': { 'latitude':'44.016667', 'longitude': '12.6', 'name':'Miramare' },
'ISP': { 'latitude':'40.795278', 'longitude': '-73.100278', 'name':'Long Island Mac Arthur' },
'ISW': { 'latitude':'44.766667', 'longitude': '-89.677778', 'name':'Alexander Field' },
'ISU': { 'latitude':'35.5608', 'longitude': '45.314701', 'name':'Sulaymaniyah International' },
'IST': { 'latitude':'40.976944', 'longitude': '28.821111', 'name':'Ataturk' },
'ISK': { 'latitude':'19.966667', 'longitude': '73.816667', 'name':'Gandhinagar Arpt' },
'ISJ': { 'latitude':'21.266667', 'longitude': '-86.75', 'name':'Isla Mujeres' },
'ISI': { 'latitude':'-24.2', 'longitude': '144.416667', 'name':'Isisford' },
'ISH': { 'latitude':'40.633333', 'longitude': '13.833333', 'name':'Ischia' },
'ISO': { 'latitude':'35.333333', 'longitude': '-77.616667', 'name':'Stallings Field' },
'ISN': { 'latitude':'48.183333', 'longitude': '-103.65', 'name':'Sloulin Field Intl' },
'ISM': { 'latitude':'28.283333', 'longitude': '-81.433333', 'name':'Kissimmee Gateway' },
'ISL': { 'latitude':'63.5', 'longitude': '-145.033333', 'name':'Isabel Pass' },
'ISC': { 'latitude':'49.9', 'longitude': '-6.4', 'name':'St Marys' },
'ISB': { 'latitude':'33.616667', 'longitude': '73.1', 'name':'Islamabad International' },
'ISA': { 'latitude':'-20.666667', 'longitude': '139.466667', 'name':'Mount Isa' },
'ISG': { 'latitude':'24.344444', 'longitude': '124.186944', 'name':'Ishigaki' },
'ISE': { 'latitude':'37.866111', 'longitude': '30.382222', 'name':'Isparta' },
'ISD': { 'latitude':'2.441667', 'longitude': '-77.966667', 'name':'Iscuande' },
'PVS': { 'latitude':'64.383333', 'longitude': '173.3', 'name':'Provideniya' },
'PVR': { 'latitude':'20.68', 'longitude': '-105.254167', 'name':'Licenciado Gustavo Díaz Ordaz International' },
'PVU': { 'latitude':'40.233333', 'longitude': '-111.716667', 'name':'Provo' },
'PVW': { 'latitude':'34.166667', 'longitude': '-101.716667', 'name':'Hale County' },
'RMN': { 'latitude':'-5.883333', 'longitude': '141.266667', 'name':'Rumginae' },
'PVY': { 'latitude':'59.316667', 'longitude': '-154.916667', 'name':'Pope Vanoy' },
'PVX': { 'latitude':'64.366667', 'longitude': '173.233333', 'name':'Provedenia' },
'JKV': { 'latitude':'31.869444', 'longitude': '-95.2175', 'name':'Cherokee County' },
'PVZ': { 'latitude':'41.733333', 'longitude': '-81.216667', 'name':'Casement' },
'JKR': { 'latitude':'26.733333', 'longitude': '85.933333', 'name':'Janakpur' },
'JKL': { 'latitude':'36.963333', 'longitude': '26.940556', 'name':'Kalymnos' },
'PVC': { 'latitude':'42.066667', 'longitude': '-70.216667', 'name':'Provincetown' },
'JKH': { 'latitude':'38.335278', 'longitude': '26.134722', 'name':'Chios' },
'PVD': { 'latitude':'41.733333', 'longitude': '-71.433333', 'name':'T. F. Green Airport' },
'PVG': { 'latitude':'31.143333', 'longitude': '121.805278', 'name':'Pu Dong' },
'PVF': { 'latitude':'38.716667', 'longitude': '-120.8', 'name':'Placerville' },
'PVI': { 'latitude':'-23.09', 'longitude': '-52.488611', 'name':'Edu Chaves' },
'PVH': { 'latitude':'-8.709167', 'longitude': '-63.902222', 'name':'Governador Jorge Teixeira' },
'PVK': { 'latitude':'38.926389', 'longitude': '20.765278', 'name':'Aktion' },
'JKG': { 'latitude':'57.7575', 'longitude': '14.068611', 'name':'Axamo' },
'PVO': { 'latitude':'-1.034167', 'longitude': '-80.467222', 'name':'Reales Tamarindos' },
'PVN': { 'latitude':'42.0', 'longitude': '24.5', 'name':'Pleven' },
'FRC': { 'latitude':'-20.583333', 'longitude': '-47.383333', 'name':'Franca' },
'FRB': { 'latitude':'-33.383333', 'longitude': '148.016667', 'name':'Forbes' },
'FRA': { 'latitude':'50.026389', 'longitude': '8.543056', 'name':'Frankfurt International Airport' },
'FRG': { 'latitude':'40.733333', 'longitude': '-73.416667', 'name':'Republic Field' },
'FRF': { 'latitude':'49.683333', 'longitude': '10.533333', 'name':'Rhein-Main AFB' },
'FRE': { 'latitude':'-8.1', 'longitude': '159.583333', 'name':'Fera Island' },
'FRD': { 'latitude':'48.521944', 'longitude': '-123.024444', 'name':'Friday Harbor' },
'FRK': { 'latitude':'-4.583333', 'longitude': '55.95', 'name':'Fregate Is' },
'FRJ': { 'latitude':'43.416667', 'longitude': '6.733333', 'name':'Frejus' },
'FRI': { 'latitude':'39.055278', 'longitude': '-96.764444', 'name':'Marshall AAF' },
'FRH': { 'latitude':'38.55', 'longitude': '-86.616667', 'name':'Municipal' },
'FRO': { 'latitude':'61.5', 'longitude': '5.083333', 'name':'Flora' },
'FRN': { 'latitude':'19.833333', 'longitude': '-72.5', 'name':'Bryant AAF' },
'FRM': { 'latitude':'43.65', 'longitude': '-94.416667', 'name':'Fairmont' },
'FRL': { 'latitude':'44.2', 'longitude': '12.066667', 'name':'Luigi Ridolfi' },
'FRS': { 'latitude':'16.916667', 'longitude': '-89.883333', 'name':'Santa Elena' },
'FRR': { 'latitude':'38.9175', 'longitude': '-78.253611', 'name':'Front Royal-Warren County' },
'FRQ': { 'latitude':'-5.416667', 'longitude': '141.7', 'name':'Feramin' },
'FRP': { 'latitude':'57.845833', 'longitude': '-135.025', 'name':'Fresh Water Bay' },
'FRW': { 'latitude':'-21.16', 'longitude': '27.481111', 'name':'Francistown' },
'FRU': { 'latitude':'43.061389', 'longitude': '74.4775', 'name':'Manas' },
'FRT': { 'latitude':'-19.416667', 'longitude': '-65.366667', 'name':'Frutillar' },
'FRZ': { 'latitude':'51.1', 'longitude': '9.283333', 'name':'Fritzlar Airbase' },
'FRY': { 'latitude':'44.016667', 'longitude': '-70.983333', 'name':'Fryeburg' },
'RML': { 'latitude':'6.819444', 'longitude': '79.8875', 'name':'Colombo Ratmalana' },
'UUU': { 'latitude':'-8.083333', 'longitude': '147.55', 'name':'Manumu' },
'UUS': { 'latitude':'46.883333', 'longitude': '142.716667', 'name':'Yuzhno-Sakhalinsk' },
'UUN': { 'latitude':'46.683333', 'longitude': '113.283333', 'name':'Baruun-Urt' },
'UUK': { 'latitude':'70.416667', 'longitude': '-148.916667', 'name':'Kuparuk' },
'UUD': { 'latitude':'51.833333', 'longitude': '107.5', 'name':'Ulan-ude, Mukhino' },
'UUA': { 'latitude':'54.616667', 'longitude': '52.816667', 'name':'Bugulma' },
'SWI': { 'latitude':'51.566667', 'longitude': '-1.783333', 'name':'Gypsy' },
'SWH': { 'latitude':'-35.383333', 'longitude': '143.55', 'name':'Swan Hill' },
'SWK': { 'latitude':'45.5', 'longitude': '9.5', 'name':'Segrate' },
'SWJ': { 'latitude':'-16.491667', 'longitude': '167.438889', 'name':'South West Bay' },
'SWM': { 'latitude':'-11.666667', 'longitude': '-51.420833', 'name':'Suia-Missu' },
'SWL': { 'latitude':'18.433333', 'longitude': '-77.183333', 'name':'Spanish Wells' },
'SWO': { 'latitude':'36.166667', 'longitude': '-97.083333', 'name':'Searcy Fld' },
'SWN': { 'latitude':'31.883333', 'longitude': '72.316667', 'name':'Sahiwal' },
'SWA': { 'latitude':'23.383333', 'longitude': '116.683333', 'name':'Shantou' },
'SWC': { 'latitude':'-37.066667', 'longitude': '142.766667', 'name':'Stawell' },
'SWB': { 'latitude':'-21.516667', 'longitude': '119.366667', 'name':'Shaw River' },
'SWE': { 'latitude':'-6.283333', 'longitude': '147.55', 'name':'Siwea' },
'SWD': { 'latitude':'60.133333', 'longitude': '-149.416667', 'name':'Seward' },
'SWG': { 'latitude':'-5.883333', 'longitude': '147.95', 'name':'Satwag' },
'SWF': { 'latitude':'41.5', 'longitude': '-74.016667', 'name':'Stewart' },
'SWY': { 'latitude':'4.216667', 'longitude': '100.7', 'name':'Sitiawan' },
'SWX': { 'latitude':'-18.383333', 'longitude': '21.833333', 'name':'Shakawe' },
'SWZ': { 'latitude':'-33.883333', 'longitude': '150.716667', 'name':'Sydney West' },
'SWQ': { 'latitude':'-8.5', 'longitude': '117.416667', 'name':'Brang Bidji' },
'SWP': { 'latitude':'-22.666667', 'longitude': '14.566667', 'name':'Swakopmund' },
'SWS': { 'latitude':'51.6', 'longitude': '-4.066667', 'name':'Fairwood Comm' },
'SWU': { 'latitude':'37.233889', 'longitude': '127.001389', 'name':'Suwon' },
'SWW': { 'latitude':'32.466667', 'longitude': '-100.466667', 'name':'Sweetwater' },
'SWV': { 'latitude':'29.166667', 'longitude': '70.433333', 'name':'Shikarpur' },
'TGR': { 'latitude':'33.1', 'longitude': '6.066667', 'name':'Touggourt' },
'TGS': { 'latitude':'-24.616667', 'longitude': '32.416667', 'name':'Chokwe' },
'GYE': { 'latitude':'-2.154444', 'longitude': '-79.875556', 'name':'Guayaquil' },
'GYD': { 'latitude':'40.4675', 'longitude': '50.046667', 'name':'Heydar Aliyev International' },
'TGV': { 'latitude':'11.917778', 'longitude': '-1.656667', 'name':'Targovishte' },
'GYA': { 'latitude':'-10.8', 'longitude': '-65.383333', 'name':'Guayaramerin' },
'TGU': { 'latitude':'14.25', 'longitude': '-87.166667', 'name':'Toncontin' },
'TGZ': { 'latitude':'16.75', 'longitude': '-93.116667', 'name':'Llano San Juan' },
'GYN': { 'latitude':'-16.631944', 'longitude': '-49.220556', 'name':'Santa Genoveva' },
'GYM': { 'latitude':'27.966667', 'longitude': '-110.933333', 'name':'Gen Jose M Yanez' },
'GYL': { 'latitude':'-16.640833', 'longitude': '128.45', 'name':'Argyle' },
'GYI': { 'latitude':'-1.7', 'longitude': '29.25', 'name':'Gisenyi' },
'TGB': { 'latitude':'8.677222', 'longitude': '117.338056', 'name':'Tagbita' },
'TGC': { 'latitude':'2.17773', 'longitude': '111.202755', 'name':'Tanjung Manis' },
'GYS': { 'latitude':'32.395', 'longitude': '105.699722', 'name':'Guang Yuan' },
'GYR': { 'latitude':'33.433333', 'longitude': '-112.35', 'name':'Litchfield' },
'TGD': { 'latitude':'42.359444', 'longitude': '19.251944', 'name':'Golubovci' },
'GYP': { 'latitude':'-26.283333', 'longitude': '152.7', 'name':'Gympie' },
'TGJ': { 'latitude':'42.588056', 'longitude': '19.147222', 'name':'Tiga' },
'TGH': { 'latitude':'-16.9', 'longitude': '168.55', 'name':'Tongoa' },
'TGI': { 'latitude':'-9.166667', 'longitude': '-76.0', 'name':'Tingo Maria' },
'TGN': { 'latitude':'-38.183333', 'longitude': '146.533333', 'name':'La Trobe Regional' },
'TGO': { 'latitude':'43.6125', 'longitude': '122.265278', 'name':'Tongliao' },
'GYY': { 'latitude':'41.616389', 'longitude': '-87.412778', 'name':'Gary/Chicago International' },
'TGM': { 'latitude':'46.467222', 'longitude': '24.4125', 'name':'Transilvania' },
'DHN': { 'latitude':'31.316667', 'longitude': '-85.45', 'name':'Dothan Arpt' },
'DHM': { 'latitude':'32.3', 'longitude': '76.266667', 'name':'Gaggal Airport' },
'DHL': { 'latitude':'13.7375', 'longitude': '44.729167', 'name':'Dhala' },
'DHI': { 'latitude':'28.25', 'longitude': '80.675', 'name':'Dhangarhi' },
'DHF': { 'latitude':'24.45', 'longitude': '54.383333', 'name':'Al Dhafra Military Apt' },
'DHD': { 'latitude':'-27.066667', 'longitude': '141.916667', 'name':'Durham Downs' },
'DHA': { 'latitude':'26.266667', 'longitude': '50.166667', 'name':'Dhahran' },
'DHT': { 'latitude':'12.186111', 'longitude': '42.89', 'name':'Dalhart' },
'DHR': { 'latitude':'52.924444', 'longitude': '4.780833', 'name':'De Kooy/Den Helder Airport' },
'VTB': { 'latitude':'55.126389', 'longitude': '30.349722', 'name':'Vitebsk' },
'RIZ': { 'latitude':'9.383333', 'longitude': '-78.8', 'name':'Rio Alzucar' },
'RIX': { 'latitude':'56.923611', 'longitude': '23.971111', 'name':'Riga International' },
'RIY': { 'latitude':'14.65', 'longitude': '49.333333', 'name':'Riyan Mukalla' },
'RIV': { 'latitude':'33.880833', 'longitude': '-117.259444', 'name':'March ARB' },
'RIW': { 'latitude':'43.064167', 'longitude': '-108.459722', 'name':'Riverton Regional' },
'RIT': { 'latitude':'9.25', 'longitude': '-78.5', 'name':'Rio Tigre' },
'RIR': { 'latitude':'-29.666667', 'longitude': '30.016667', 'name':'Riverside Fla-Bob' },
'RIS': { 'latitude':'45.183333', 'longitude': '141.25', 'name':'Rishiri' },
'RIN': { 'latitude':'-8.2', 'longitude': '157.033333', 'name':'Ringi Cove' },
'RIL': { 'latitude':'39.516667', 'longitude': '-107.716667', 'name':'Garfield County' },
'RIM': { 'latitude':'-6.333333', 'longitude': '-77.416667', 'name':'Rodriguez De Mendoza' },
'RIJ': { 'latitude':'-6.166667', 'longitude': '-77.083333', 'name':'Rioja' },
'RIF': { 'latitude':'38.75', 'longitude': '-112.1', 'name':'Reynolds' },
'RIG': { 'latitude':'-32.083333', 'longitude': '-52.166667', 'name':'Rio Grande' },
'RID': { 'latitude':'39.757222', 'longitude': '-84.842778', 'name':'Richmond Municipal Airport' },
'RIE': { 'latitude':'45.5', 'longitude': '-91.733333', 'name':'Rice Lake' },
'RIB': { 'latitude':'-11.016667', 'longitude': '-66.083333', 'name':'Gen Buech' },
'RIC': { 'latitude':'37.5', 'longitude': '-77.316667', 'name':'Richmond International Airport' },
'TIL': { 'latitude':'50.5', 'longitude': '-1.033333', 'name':'Inverlake' },
'RIA': { 'latitude':'-29.683056', 'longitude': '-53.691667', 'name':'Base Aerea De Santa Maria' },
'HAH': { 'latitude':'-11.533333', 'longitude': '43.266667', 'name':'Moroni Prince Said Ibrahim In' },
'BNZ': { 'latitude':'-5.783333', 'longitude': '144.616667', 'name':'Banz' },
'HAJ': { 'latitude':'52.461111', 'longitude': '9.685', 'name':'Hanover Arpt' },
'BNX': { 'latitude':'44.766667', 'longitude': '17.183333', 'name':'Banja Luka' },
'HAL': { 'latitude':'-19.966667', 'longitude': '13.066667', 'name':'Halali' },
'HAM': { 'latitude':'53.633333', 'longitude': '9.983333', 'name':'Hamburg Airport' },
'HAN': { 'latitude':'21.221111', 'longitude': '105.807222', 'name':'Noibai International' },
'HAO': { 'latitude':'39.433333', 'longitude': '-84.5', 'name':'Hamilton' },
'BNS': { 'latitude':'8.616667', 'longitude': '-70.216667', 'name':'Barinas' },
'HAA': { 'latitude':'70.483333', 'longitude': '22.033333', 'name':'Hasvik' },
'BNQ': { 'latitude':'7.583333', 'longitude': '126.566667', 'name':'Baganga' },
'HAC': { 'latitude':'33.166667', 'longitude': '139.8', 'name':'Hachijo Jima' },
'HAD': { 'latitude':'56.690833', 'longitude': '12.82', 'name':'Halmstad' },
'HAE': { 'latitude':'36.230556', 'longitude': '-112.669444', 'name':'Havasupai' },
'HAF': { 'latitude':'37.483333', 'longitude': '-122.466667', 'name':'Half Moon' },
'BNT': { 'latitude':'-5.733333', 'longitude': '145.216667', 'name':'Bundi' },
'HAX': { 'latitude':'35.745833', 'longitude': '-95.412778', 'name':'Hatbox Field' },
'HAY': { 'latitude':'65.2', 'longitude': '-161.15', 'name':'Haycock' },
'HAZ': { 'latitude':'-4.333333', 'longitude': '145.166667', 'name':'Hatzfeldthaven' },
'BNH': { 'latitude':'41.766389', 'longitude': '-72.683333', 'name':'Barnes' },
'BNO': { 'latitude':'43.583333', 'longitude': '-118.95', 'name':'Burns' },
'BNN': { 'latitude':'65.483333', 'longitude': '12.216667', 'name':'Bronnoy' },
'BNM': { 'latitude':'-9.083333', 'longitude': '147.5', 'name':'Bodinumu' },
'BNL': { 'latitude':'33.257778', 'longitude': '-81.388333', 'name':'Barnwell Regional' },
'HAP': { 'latitude':'-19.166667', 'longitude': '147.666667', 'name':'Long Island' },
'HAQ': { 'latitude':'6.75', 'longitude': '73.15', 'name':'Hanimaadhoo' },
'BNA': { 'latitude':'36.124444', 'longitude': '-86.678056', 'name':'Nashville International' },
'HAS': { 'latitude':'27.516667', 'longitude': '41.75', 'name':'Hail' },
'HAT': { 'latitude':'-19.720833', 'longitude': '140.583333', 'name':'Heathlands' },
'HAU': { 'latitude':'59.416667', 'longitude': '5.3', 'name':'Haugesund' },
'HAV': { 'latitude':'23.016667', 'longitude': '-82.383333', 'name':'Jose Marti Intl' },
'HAW': { 'latitude':'51.816667', 'longitude': '-4.966667', 'name':'Haverfordwest' },
'RFP': { 'latitude':'-16.716667', 'longitude': '-151.45', 'name':'Raiatea' },
'TPI': { 'latitude':'-8.366667', 'longitude': '146.983333', 'name':'Tapini' },
'TXF': { 'latitude':'-8.5', 'longitude': '-70.533333', 'name':'Teixeira de Freitas' },
'TPH': { 'latitude':'38.06', 'longitude': '-117.086944', 'name':'Tonopah Arpt' },
'LJN': { 'latitude':'29.033333', 'longitude': '-95.45', 'name':'Brazoria County' },
'FOT': { 'latitude':'32.183333', 'longitude': '152.516667', 'name':'Forster' },
'FOU': { 'latitude':'-1.2', 'longitude': '10.783333', 'name':'Fougamou' },
'VGG': { 'latitude':'62.533333', 'longitude': '11.066667', 'name':'Vangrieng' },
'FOR': { 'latitude':'-3.776389', 'longitude': '-38.5325', 'name':'Pinto Martins' },
'FOS': { 'latitude':'-30.838056', 'longitude': '128.115', 'name':'Forrest' },
'LJA': { 'latitude':'-3.416667', 'longitude': '23.45', 'name':'Lodja' },
'FOX': { 'latitude':'64.85', 'longitude': '-147.766667', 'name':'Fox' },
'FOY': { 'latitude':'8.366667', 'longitude': '-10.216667', 'name':'Foya' },
'LJG': { 'latitude':'26.683333', 'longitude': '100.25', 'name':'Lijiang City' },
'VGA': { 'latitude':'16.516667', 'longitude': '80.8', 'name':'Vijayawada' },
'FOD': { 'latitude':'42.551111', 'longitude': '-94.191944', 'name':'Fort Dodge Regional' },
'FOE': { 'latitude':'38.950833', 'longitude': '-95.663611', 'name':'Forbes Field' },
'FOG': { 'latitude':'41.416667', 'longitude': '15.533333', 'name':'Gino Lisa' },
'FOA': { 'latitude':'60.116667', 'longitude': '-2.05', 'name':'Foula' },
'FOB': { 'latitude':'39.474444', 'longitude': '-123.795556', 'name':'Fort Bragg' },
'FOC': { 'latitude':'26.1', 'longitude': '119.283333', 'name':'Fuzhou' },
'FOM': { 'latitude':'5.633333', 'longitude': '10.75', 'name':'Foumban' },
'FON': { 'latitude':'10.4', 'longitude': '-84.483333', 'name':'Fortuna' },
'FOO': { 'latitude':'-0.933333', 'longitude': '134.866667', 'name':'Numfoor' },
'LJU': { 'latitude':'46.223611', 'longitude': '14.4575', 'name':'Brnik' },
'FOK': { 'latitude':'40.833333', 'longitude': '-72.616667', 'name':'Suffolk County' },
'TPT': { 'latitude':'6.492222', 'longitude': '-8.860278', 'name':'Tapeta' },
'SCO': { 'latitude':'43.86', 'longitude': '51.091944', 'name':'Shevchenko' },
'JAX': { 'latitude':'30.416667', 'longitude': '-81.633333', 'name':'Jacksonville,' },
'ZIQ': { 'latitude':'39.733333', 'longitude': '16.116667', 'name':'Harbour' },
'JAV': { 'latitude':'69.25', 'longitude': '-51.0', 'name':'Ilulissat' },
'JAT': { 'latitude':'7.0', 'longitude': '168.983333', 'name':'Jabot' },
'JAU': { 'latitude':'-11.8', 'longitude': '-75.5', 'name':'Jauja' },
'JAR': { 'latitude':'34.133333', 'longitude': '-118.016667', 'name':'Jahrom' },
'JAS': { 'latitude':'30.916667', 'longitude': '-94.016667', 'name':'County' },
'JAP': { 'latitude':'10.95', 'longitude': '-85.85', 'name':'Punta Renes' },
'JAQ': { 'latitude':'-5.6', 'longitude': '151.516667', 'name':'Jacquinot Bay' },
'JAN': { 'latitude':'32.311111', 'longitude': '-90.075833', 'name':'Jackson-evers' },
'JAO': { 'latitude':'9.716667', 'longitude': '-82.983333', 'name':'Beaver Ruin' },
'JAL': { 'latitude':'19.583333', 'longitude': '-96.833333', 'name':'Jalapa' },
'JAM': { 'latitude':'42.516667', 'longitude': '26.483333', 'name':'Jambol' },
'WLW': { 'latitude':'39.516667', 'longitude': '-122.216667', 'name':'Glenn County' },
'JAJ': { 'latitude':'9.716667', 'longitude': '-82.983333', 'name':'Perimeter Mall' },
'JAK': { 'latitude':'18.25', 'longitude': '-72.516667', 'name':'Jacmel' },
'XJE': { 'latitude':'55.283333', 'longitude': '9.3', 'name':'Rialway Service' },
'XJD': { 'latitude':'25.117222', 'longitude': '51.315', 'name':'Al Udeid AB' },
'XJG': { 'latitude':'-33.1', 'longitude': '-57.633333', 'name':'Darwin Railway' },
'JAH': { 'latitude':'43.283333', 'longitude': '5.6', 'name':'Agora Helipad' },
'XJM': { 'latitude':'33.116667', 'longitude': '73.65', 'name':'Mangla' },
'JAI': { 'latitude':'26.816667', 'longitude': '75.8', 'name':'Sanganeer' },
'JAF': { 'latitude':'9.783333', 'longitude': '80.066667', 'name':'Kankesanturai' },
'XJS': { 'latitude':'47.543333', 'longitude': '10.708889', 'name':'Kitzbuehl Railway' },
'JAG': { 'latitude':'28.283333', 'longitude': '68.433333', 'name':'Jacobabad' },
'JAD': { 'latitude':'-32.0975', 'longitude': '115.881111', 'name':'Jandakot' },
'YDN': { 'latitude':'51.1', 'longitude': '-100.05', 'name':'Dauphin' },
'YDO': { 'latitude':'48.883333', 'longitude': '-72.233333', 'name':'St Methode' },
'YDL': { 'latitude':'58.583333', 'longitude': '-130.033333', 'name':'Dease Lake' },
'YDJ': { 'latitude':'58.616667', 'longitude': '-1.666667', 'name':'Hatchet Lake' },
'YDK': { 'latitude':'43.933333', 'longitude': '-76.616667', 'name':'Main Duck Island' },
'YDH': { 'latitude':'67.75', 'longitude': '-1.5', 'name':'Daniels Harbour' },
'YDI': { 'latitude':'55.933333', 'longitude': '-60.95', 'name':'Davis Inlet' },
'YDF': { 'latitude':'49.216667', 'longitude': '-57.4', 'name':'Deer Lake' },
'YDG': { 'latitude':'44.5', 'longitude': '-66.166667', 'name':'Digby' },
'YDE': { 'latitude':'53.433333', 'longitude': '-57.233333', 'name':'Paradise River' },
'YDB': { 'latitude':'61.35', 'longitude': '-139.0', 'name':'Burwash Landings' },
'YDC': { 'latitude':'53.216667', 'longitude': '-114.983333', 'name':'Industrial Airport' },
'YDA': { 'latitude':'64.05', 'longitude': '-139.083333', 'name':'Dawson City' },
'YDX': { 'latitude':'52.05', 'longitude': '-128.083333', 'name':'Doc Creek' },
'YDW': { 'latitude':'8.8', 'longitude': '-80.283333', 'name':'Obre Lake' },
'YDT': { 'latitude':'49.066667', 'longitude': '-123.0', 'name':'Boundary Bay' },
'YDR': { 'latitude':'50.333333', 'longitude': '-102.5', 'name':'Broadview' },
'YDS': { 'latitude':'47.75', 'longitude': '-122.25', 'name':'Desolation Sound' },
'YDP': { 'latitude':'56.533333', 'longitude': '-61.666667', 'name':'Nain' },
'YDQ': { 'latitude':'55.733333', 'longitude': '-120.183333', 'name':'Dawson Creek' },
'VDP': { 'latitude':'9.216667', 'longitude': '-66.016667', 'name':'Valle De Pascua' },
'VDS': { 'latitude':'70.066667', 'longitude': '29.75', 'name':'Vadso' },
'VDR': { 'latitude':'-31.95', 'longitude': '-65.15', 'name':'Villa Dolores' },
'VDZ': { 'latitude':'61.133333', 'longitude': '-146.233333', 'name':'Municipal' },
'VDA': { 'latitude':'29.940556', 'longitude': '34.935833', 'name':'Ovda' },
'VDC': { 'latitude':'-14.883333', 'longitude': '-40.866667', 'name':'Vitoria Da Conquista' },
'TNV': { 'latitude':'3.866667', 'longitude': '-159.35', 'name':'Tabuaeran' },
'VDE': { 'latitude':'27.816667', 'longitude': '-17.883333', 'name':'Hierro' },
'VDD': { 'latitude':'48.25', 'longitude': '16.416667', 'name':'Vienna Danubepier Hov' },
'VDI': { 'latitude':'32.216667', 'longitude': '-82.4', 'name':'Municipal' },
'VDM': { 'latitude':'-40.85', 'longitude': '-63.016667', 'name':'Viedma' },
'TNR': { 'latitude':'-18.796944', 'longitude': '47.478889', 'name':'Antananarivo' },
'WVK': { 'latitude':'-22.116667', 'longitude': '48.016667', 'name':'Manakara' },
'WVI': { 'latitude':'36.916667', 'longitude': '-121.75', 'name':'Watsonville' },
'WVN': { 'latitude':'53.533333', 'longitude': '7.883333', 'name':'Wilhelmshaven' },
'WVL': { 'latitude':'44.533333', 'longitude': '-69.666667', 'name':'Robert Lafleur' },
'WVB': { 'latitude':'-22.98', 'longitude': '14.645278', 'name':'Rooikop' },
'TNG': { 'latitude':'35.731944', 'longitude': '-5.901667', 'name':'Boukhalef' },
'TNF': { 'latitude':'48.749722', 'longitude': '2.111111', 'name':'Toussus-le-noble' },
'TNM': { 'latitude':'62.190833', 'longitude': '-58.986667', 'name':'Teniente R. Marsh Martin' },
'YSH': { 'latitude':'44.833056', 'longitude': '-76.115833', 'name':'Smith Falls' },
'ZUD': { 'latitude':'-41.9', 'longitude': '-73.8', 'name':'Ancud' },
'ZUE': { 'latitude':'7.433333', 'longitude': '-6.05', 'name':'Zuenoula' },
'ZUH': { 'latitude':'22.0', 'longitude': '113.366667', 'name':'Zhuhai' },
'TNO': { 'latitude':'10.916667', 'longitude': '-85.45', 'name':'Tamarindo' },
'ZUL': { 'latitude':'26.3', 'longitude': '44.816667', 'name':'Zilfi' },
'ZUM': { 'latitude':'53.566667', 'longitude': '-64.116667', 'name':'Churchill Falls' },
'RRO': { 'latitude':'40.616667', 'longitude': '14.366667', 'name':'Sorrento' },
'RRN': { 'latitude':'-6.0', 'longitude': '-50.3', 'name':'Serra Norte' },
'RRM': { 'latitude':'-18.290833', 'longitude': '35.945278', 'name':'Marromeu' },
'RRL': { 'latitude':'-34.683333', 'longitude': '149.216667', 'name':'Municipal' },
'RRK': { 'latitude':'22.266667', 'longitude': '84.816667', 'name':'Rourkela' },
'RRI': { 'latitude':'-7.6', 'longitude': '158.4', 'name':'Barora' },
'RRG': { 'latitude':'-19.733333', 'longitude': '63.433333', 'name':'Rodrigues Is' },
'RRE': { 'latitude':'-29.65', 'longitude': '138.066667', 'name':'Marree' },
'RRA': { 'latitude':'36.733333', 'longitude': '-5.166667', 'name':'Ronda' },
'TNH': { 'latitude':'41.676944', 'longitude': '125.753056', 'name':'Tonghua Liuhe' },
'TNK': { 'latitude':'60.570833', 'longitude': '-165.266667', 'name':'Tununak' },
'RRV': { 'latitude':'-16.75', 'longitude': '136.916667', 'name':'Robinson River' },
'RRT': { 'latitude':'-28.05', 'longitude': '117.533333', 'name':'Warroad' },
'RRS': { 'latitude':'62.583333', 'longitude': '11.35', 'name':'Roros' },
'RRR': { 'latitude':'-16.06297', 'longitude': '-142.485809', 'name':'Raroia' },
'HHR': { 'latitude':'33.916667', 'longitude': '-118.35', 'name':'Hawthorne' },
'NKB': { 'latitude':'-18.5', 'longitude': '124.833333', 'name':'Noonkanbah' },
'HHP': { 'latitude':'22.25', 'longitude': '114.183333', 'name':'H K Heliport' },
'HHZ': { 'latitude':'-17.533333', 'longitude': '-142.533333', 'name':'Hikueru' },
'XWZ': { 'latitude':'58.783333', 'longitude': '16.9', 'name':'Nykoping' },
'USO': { 'latitude':'-5.5', 'longitude': '145.433333', 'name':'Usino' },
'IQT': { 'latitude':'-3.75', 'longitude': '-73.216667', 'name':'C.F. Secada' },
'USM': { 'latitude':'9.55', 'longitude': '100.066667', 'name':'Koh Samui' },
'USL': { 'latitude':'-25.966667', 'longitude': '113.116667', 'name':'Useless Loop' },
'IQQ': { 'latitude':'-20.233333', 'longitude': '-70.15', 'name':'Cavancha' },
'XWS': { 'latitude':'51.933333', 'longitude': '-2.1', 'name':'Railway Station' },
'USI': { 'latitude':'8.202778', 'longitude': '-59.808333', 'name':'Mabaruma' },
'USH': { 'latitude':'-54.843333', 'longitude': '-68.295833', 'name':'Islas Malvinas' },
'IQM': { 'latitude':'38.133333', 'longitude': '85.533333', 'name':'Qiemo' },
'USU': { 'latitude':'12.121389', 'longitude': '120.1', 'name':'Puerto Princessa' },
'IQN': { 'latitude':'36.1', 'longitude': '107.783333', 'name':'Qingyang' },
'USS': { 'latitude':'21.972222', 'longitude': '-79.446944', 'name':'Sancti Spiritus' },
'XWK': { 'latitude':'56.266667', 'longitude': '15.266667', 'name':'Karlskrona Rail Svc.' },
'USQ': { 'latitude':'38.678611', 'longitude': '29.471667', 'name':'Usak' },
'XWC': { 'latitude':'48.25', 'longitude': '16.416667', 'name':'Suedbahnhof Rail' },
'PXS': { 'latitude':'42.0', 'longitude': '-8.883333', 'name':'Puerto De Santa Maria' },
'PXR': { 'latitude':'14.883333', 'longitude': '103.5', 'name':'Surin' },
'PXU': { 'latitude':'14.003056', 'longitude': '108.021389', 'name':'Pleiku' },
'PXO': { 'latitude':'33.066667', 'longitude': '-16.35', 'name':'Porto Santo' },
'PXM': { 'latitude':'15.833333', 'longitude': '-97.166667', 'name':'Puerto Escondido' },
'PXL': { 'latitude':'35.833333', 'longitude': '-110.383333', 'name':'Polacca' },
'ZTF': { 'latitude':'21.65', 'longitude': '-72.466667', 'name':'Stamford Rail STN' },
'HHE': { 'latitude':'40.55', 'longitude': '141.483333', 'name':'Hachinohe' },
'FPO': { 'latitude':'26.558611', 'longitude': '-78.695556', 'name':'Grand Bahama International' },
'FPR': { 'latitude':'27.483333', 'longitude': '-80.366667', 'name':'St Lucie County' },
'FPY': { 'latitude':'30.116667', 'longitude': '-83.583333', 'name':'Perry-Foley' },
'PLQ': { 'latitude':'55.916667', 'longitude': '21.05', 'name':'Palanga International' },
'SIS': { 'latitude':'-27.816667', 'longitude': '23.0', 'name':'Sishen' },
'SIR': { 'latitude':'46.172222', 'longitude': '7.214167', 'name':'Sion' },
'SIQ': { 'latitude':'-0.483333', 'longitude': '104.583333', 'name':'Dabo' },
'ROT': { 'latitude':'-38.15', 'longitude': '176.266667', 'name':'Rotorua' },
'SIV': { 'latitude':'39.1', 'longitude': '-87.4', 'name':'County' },
'SIU': { 'latitude':'13.583333', 'longitude': '-84.366667', 'name':'Siuna' },
'SIT': { 'latitude':'57.066667', 'longitude': '-135.35', 'name':'Sitka' },
'SIZ': { 'latitude':'-3.0', 'longitude': '142.05', 'name':'Sissano' },
'SIY': { 'latitude':'41.781389', 'longitude': '-122.466389', 'name':'Siskiyou County' },
'SIX': { 'latitude':'-32.566667', 'longitude': '151.166667', 'name':'Singleton' },
'SIC': { 'latitude':'42.018889', 'longitude': '35.079167', 'name':'Sinop Airport' },
'SIB': { 'latitude':'-3.733333', 'longitude': '13.4', 'name':'Sibiti' },
'SIA': { 'latitude':'34.366667', 'longitude': '108.7', 'name':'Xiguan' },
'SIG': { 'latitude':'18.45', 'longitude': '-66.1', 'name':'Isla Grande' },
'SIF': { 'latitude':'27.0', 'longitude': '85.533333', 'name':'Simara' },
'SIE': { 'latitude':'37.95', 'longitude': '-8.866667', 'name':'Sines' },
'SID': { 'latitude':'16.741389', 'longitude': '-22.949444', 'name':'Amilcar Cabral Intl' },
'SIK': { 'latitude':'36.883333', 'longitude': '-89.566667', 'name':'Memorial' },
'SIJ': { 'latitude':'66.166667', 'longitude': '-18.933333', 'name':'Siglufjordur' },
'SII': { 'latitude':'29.366667', 'longitude': '-10.183333', 'name':'Sidi Ifni' },
'SIH': { 'latitude':'29.266667', 'longitude': '80.983333', 'name':'Silgadi Doti' },
'SIO': { 'latitude':'-40.916667', 'longitude': '145.016667', 'name':'Smithton' },
'SIN': { 'latitude':'1.350278', 'longitude': '103.994444', 'name':'Changi' },
'SIM': { 'latitude':'-4.0', 'longitude': '144.0', 'name':'Simbai' },
'SIL': { 'latitude':'-9.116667', 'longitude': '148.4', 'name':'Sila' },
'TAT': { 'latitude':'49.071944', 'longitude': '20.240278', 'name':'Poprad-Tatry' },
'TAU': { 'latitude':'5.016667', 'longitude': '-72.733333', 'name':'Tauramena' },
'TAV': { 'latitude':'-14.229167', 'longitude': '-169.511111', 'name':'Tau' },
'TAW': { 'latitude':'-32.166667', 'longitude': '-55.5', 'name':'Tacuarembo' },
'TAP': { 'latitude':'14.9', 'longitude': '-92.283333', 'name':'Tapachula International' },
'TAQ': { 'latitude':'-33.433333', 'longitude': '142.583333', 'name':'Tarcoola' },
'TAR': { 'latitude':'40.616667', 'longitude': '17.25', 'name':'M. A. Grottag' },
'TAS': { 'latitude':'41.257778', 'longitude': '69.281111', 'name':'Yuzhny' },
'TAX': { 'latitude':'14.916667', 'longitude': '-91.75', 'name':'Taliabu' },
'TAY': { 'latitude':'58.4', 'longitude': '26.75', 'name':'Tartu' },
'TAD': { 'latitude':'5.416667', 'longitude': '-71.666667', 'name':'Las Animas' },
'TAE': { 'latitude':'35.8', 'longitude': '128.55', 'name':'Daegu' },
'TAF': { 'latitude':'35.716667', 'longitude': '-0.716667', 'name':'Tafaraoui' },
'TAG': { 'latitude':'9.666667', 'longitude': '123.85', 'name':'Tagbilaran' },
'TAA': { 'latitude':'-9.433333', 'longitude': '161.383333', 'name':'Tarapaina' },
'TAB': { 'latitude':'11.25', 'longitude': '-60.666667', 'name':'Crown Point Airport' },
'TAC': { 'latitude':'11.233333', 'longitude': '125.016667', 'name':'D.Z. Romualdez' },
'TAL': { 'latitude':'65.175', 'longitude': '-152.108056', 'name':'Tanana' },
'TAM': { 'latitude':'22.296389', 'longitude': '-97.865833', 'name':'Gen F Javier Mina' },
'TAN': { 'latitude':'-27.178056', 'longitude': '153.373611', 'name':'Tangalooma' },
'TAO': { 'latitude':'36.1', 'longitude': '120.316667', 'name':'Qingdao' },
'TAH': { 'latitude':'-19.455', 'longitude': '169.223889', 'name':'Tanna' },
'TAI': { 'latitude':'13.566667', 'longitude': '44.033333', 'name':'Al Janad' },
'TAJ': { 'latitude':'-3.133333', 'longitude': '142.35', 'name':'Tadji' },
'ROV': { 'latitude':'47.333333', 'longitude': '39.7', 'name':'Rostov' },
'JID': { 'latitude':'34.027222', 'longitude': '-117.958333', 'name':'City Of Industry H/P' },
'JIB': { 'latitude':'11.55', 'longitude': '43.166667', 'name':'Ambouli' },
'JIA': { 'latitude':'-11.5', 'longitude': '-58.883333', 'name':'Juina' },
'JIN': { 'latitude':'0.45', 'longitude': '33.2', 'name':'Jinja' },
'JIO': { 'latitude':'-11.283333', 'longitude': '-74.433333', 'name':'Intl Heliport' },
'JIL': { 'latitude':'43.866667', 'longitude': '126.65', 'name':'Jilin' },
'JIM': { 'latitude':'7.666667', 'longitude': '36.883333', 'name':'Jimma' },
'JIJ': { 'latitude':'9.366667', 'longitude': '42.766667', 'name':'Jijiga' },
'JIK': { 'latitude':'37.682778', 'longitude': '26.346944', 'name':'Ikaria' },
'DJA': { 'latitude':'9.7', 'longitude': '1.666667', 'name':'Djougou' },
'JIW': { 'latitude':'25.083333', 'longitude': '61.816667', 'name':'Jiwani' },
'JIU': { 'latitude':'29.733333', 'longitude': '115.983333', 'name':'Jiujiang' },
'DJE': { 'latitude':'33.875', 'longitude': '10.775556', 'name':'Djerba-Zarzis' },
'JIP': { 'latitude':'-1.333333', 'longitude': '-80.675', 'name':'Jipijapa' },
'DJJ': { 'latitude':'-2.583333', 'longitude': '140.516667', 'name':'Sentani' },
'DJM': { 'latitude':'-2.533333', 'longitude': '14.75', 'name':'Djambala' },
'ROW': { 'latitude':'33.416667', 'longitude': '-104.55', 'name':'Industrial' },
'DJO': { 'latitude':'6.416667', 'longitude': '-6.466667', 'name':'Daloa' },
'DJN': { 'latitude':'64.033333', 'longitude': '-145.683333', 'name':'Delta Junction' },
'GCA': { 'latitude':'2.283333', 'longitude': '-74.95', 'name':'Guacamaya' },
'QGY': { 'latitude':'47.627222', 'longitude': '17.808333', 'name':'Győr-Pér Airport' },
'QGV': { 'latitude':'49.683333', 'longitude': '10.533333', 'name':'Neu Isenburg' },
'GCC': { 'latitude':'44.35', 'longitude': '-105.533333', 'name':'Campbell County' },
'QGQ': { 'latitude':'67.933333', 'longitude': '-53.583333', 'name':'Heliport' },
'KBJ': { 'latitude':'-24.261389', 'longitude': '131.490833', 'name':'Kings Canyon' },
'KBK': { 'latitude':'57.0', 'longitude': '-136.0', 'name':'Klag Bay' },
'KBH': { 'latitude':'29.05', 'longitude': '66.583333', 'name':'Kalat' },
'KBI': { 'latitude':'2.866667', 'longitude': '9.983333', 'name':'Kribi' },
'KBN': { 'latitude':'-6.116667', 'longitude': '24.533333', 'name':'Kabinda' },
'KBO': { 'latitude':'-6.083333', 'longitude': '26.916667', 'name':'Kabalo' },
'KBL': { 'latitude':'34.565833', 'longitude': '69.212222', 'name':'Khwaja Rawash' },
'KBM': { 'latitude':'-6.4', 'longitude': '147.366667', 'name':'Kabwum' },
'KBB': { 'latitude':'-17.766667', 'longitude': '129.216667', 'name':'Kirkimbie' },
'KBC': { 'latitude':'66.266667', 'longitude': '-145.8', 'name':'Birch Creek' },
'KBA': { 'latitude':'9.583333', 'longitude': '-11.55', 'name':'Kabala' },
'KBF': { 'latitude':'-3.75', 'longitude': '138.333333', 'name':'Karubaga' },
'KBG': { 'latitude':'2.333333', 'longitude': '31.5', 'name':'Kabalega Falls' },
'KBD': { 'latitude':'-17.4', 'longitude': '124.366667', 'name':'Kimberley Downs' },
'KBE': { 'latitude':'55.916667', 'longitude': '-131.566667', 'name':'Hot Springs SPB' },
'KBZ': { 'latitude':'-42.425', 'longitude': '173.605278', 'name':'Kaikoura' },
'GCI': { 'latitude':'49.433333', 'longitude': '-2.6', 'name':'Guernsey' },
'KBX': { 'latitude':'-1.0', 'longitude': '132.25', 'name':'Kambuaya' },
'KBY': { 'latitude':'-32.8', 'longitude': '134.233333', 'name':'Streaky Bay' },
'KBR': { 'latitude':'6.166944', 'longitude': '102.293056', 'name':'Sultan Ismail Petra' },
'KBS': { 'latitude':'7.95', 'longitude': '-11.766667', 'name':'Bo' },
'KBP': { 'latitude':'50.35', 'longitude': '30.916667', 'name':'Borispol' },
'KBV': { 'latitude':'8.095833', 'longitude': '98.988889', 'name':'Krabi' },
'GCK': { 'latitude':'37.933333', 'longitude': '-100.733333', 'name':'Garden City Municipal Airport' },
'KBT': { 'latitude':'8.9', 'longitude': '170.85', 'name':'Kaben' },
'KBU': { 'latitude':'-3.333333', 'longitude': '116.333333', 'name':'Kotabaru' },
'HCR': { 'latitude':'62.15', 'longitude': '-159.783333', 'name':'Holy Cross' },
'HCS': { 'latitude':'-28.733333', 'longitude': '19.3', 'name':'Randburg Heliport' },
'HCQ': { 'latitude':'-18.233333', 'longitude': '127.666667', 'name':'Halls Creek' },
'BLY': { 'latitude':'54.233333', 'longitude': '-10.0', 'name':'Belmullet' },
'HCW': { 'latitude':'34.7', 'longitude': '-79.883333', 'name':'Cheraw' },
'BLZ': { 'latitude':'-15.683333', 'longitude': '34.966667', 'name':'Chileka' },
'BLU': { 'latitude':'51.181111', 'longitude': '-3.401389', 'name':'Blue Canyon' },
'BLT': { 'latitude':'-23.583333', 'longitude': '148.883333', 'name':'Blackwater' },
'BLW': { 'latitude':'21.35', 'longitude': '-157.716667', 'name':'Bellows Field' },
'NFL': { 'latitude':'47.5', 'longitude': '6.483333', 'name':'NAS' },
'BLQ': { 'latitude':'44.535556', 'longitude': '11.288611', 'name':'Guglielmo Marconi' },
'BLP': { 'latitude':'-12.025', 'longitude': '-77.133333', 'name':'Bellavista' },
'BLS': { 'latitude':'-28.033333', 'longitude': '147.366667', 'name':'Bollon' },
'BLR': { 'latitude':'12.966667', 'longitude': '77.6', 'name':'Bangalore International Airport' },
'BLM': { 'latitude':'40.185556', 'longitude': '-74.123611', 'name':'Monmouth Executive Airport' },
'BLL': { 'latitude':'55.733333', 'longitude': '9.15', 'name':'Billund' },
'BLO': { 'latitude':'65.666667', 'longitude': '-20.3', 'name':'Blonduos' },
'HCA': { 'latitude':'32.3', 'longitude': '-101.433333', 'name':'Howard County' },
'BLI': { 'latitude':'48.8', 'longitude': '-122.533333', 'name':'Bellingham' },
'BLH': { 'latitude':'33.616667', 'longitude': '-114.716667', 'name':'Blythe' },
'BLK': { 'latitude':'53.771667', 'longitude': '-3.028611', 'name':'Blackpool Airport' },
'BLJ': { 'latitude':'35.55', 'longitude': '6.166667', 'name':'Batna' },
'BLE': { 'latitude':'60.366667', 'longitude': '15.5', 'name':'Dala Airport' },
'BLD': { 'latitude':'8.734444', 'longitude': '-9.798611', 'name':'Boulder City' },
'BLG': { 'latitude':'2.65', 'longitude': '113.766667', 'name':'Belaga' },
'BLF': { 'latitude':'37.3', 'longitude': '-81.2', 'name':'Princeton' },
'HCN': { 'latitude':'21.933333', 'longitude': '120.833333', 'name':'Hengchun' },
'HCM': { 'latitude':'8.0', 'longitude': '49.925', 'name':'Eil' },
'DIN': { 'latitude':'21.383333', 'longitude': '103.016667', 'name':'Dien Bien' },
'GCY': { 'latitude':'36.183333', 'longitude': '-82.816667', 'name':'Municipal' },
'JHB': { 'latitude':'1.45', 'longitude': '103.75', 'name':'Sultan Ismail Intl' },
'OUI': { 'latitude':'20.25', 'longitude': '100.433333', 'name':'Ban Houei' },
'OUH': { 'latitude':'-33.6025', 'longitude': '22.188333', 'name':'Oudtshoorn' },
'DIJ': { 'latitude':'47.266667', 'longitude': '5.083333', 'name':'Dijon' },
'OUM': { 'latitude':'13.266667', 'longitude': '19.716667', 'name':'Oum Hadjer' },
'OUL': { 'latitude':'64.933333', 'longitude': '25.366667', 'name':'Oulu' },
'OUA': { 'latitude':'12.35', 'longitude': '-1.516667', 'name':'Ouagadougou' },
'OUG': { 'latitude':'13.566667', 'longitude': '-2.433333', 'name':'Ouahigouya' },
'AJS': { 'latitude':'26.733333', 'longitude': '-113.583333', 'name':'Abreojos' },
'OUD': { 'latitude':'34.683333', 'longitude': '-1.75', 'name':'Les Angades' },
'OUZ': { 'latitude':'22.7', 'longitude': '-12.5', 'name':'Zouerate' },
'OUS': { 'latitude':'-22.983333', 'longitude': '-49.866667', 'name':'Ourinhos' },
'OUR': { 'latitude':'4.470833', 'longitude': '14.356944', 'name':'Batouri' },
'OUU': { 'latitude':'-2.983333', 'longitude': '10.3', 'name':'Ouanga' },
'OUT': { 'latitude':'10.483333', 'longitude': '16.716667', 'name':'Bousso' },
'LTS': { 'latitude':'34.65', 'longitude': '-99.35', 'name':'Altus AFB' },
'LTR': { 'latitude':'54.95', 'longitude': '-7.733333', 'name':'Letterkenny' },
'LTQ': { 'latitude':'50.516667', 'longitude': '1.616667', 'name':'Le Touquet' },
'LTP': { 'latitude':'-19.2', 'longitude': '144.383333', 'name':'Lyndhurst' },
'LTW': { 'latitude':'38.283333', 'longitude': '-77.633333', 'name':'St Marys County' },
'LTV': { 'latitude':'-17.083333', 'longitude': '141.366667', 'name':'Lotusvale' },
'LTU': { 'latitude':'18.411944', 'longitude': '76.465', 'name':'Latur' },
'FMY': { 'latitude':'26.583333', 'longitude': '-81.866667', 'name':'Page Field' },
'LTX': { 'latitude':'0.933333', 'longitude': '-78.616667', 'name':'Cotopaxi International' },
'FMS': { 'latitude':'40.65', 'longitude': '-91.316667', 'name':'Municipal' },
'LTC': { 'latitude':'9.416667', 'longitude': '16.016667', 'name':'Lai' },
'LTB': { 'latitude':'-41.233333', 'longitude': '146.4', 'name':'Latrobe' },
'LTA': { 'latitude':'-23.783333', 'longitude': '30.116667', 'name':'Letaba' },
'FMM': { 'latitude':'47.988889', 'longitude': '10.239444', 'name':'Memmingen-Allgäu' },
'LTG': { 'latitude':'28.266667', 'longitude': '85.616667', 'name':'Langtang' },
'LTF': { 'latitude':'-2.833333', 'longitude': '141.616667', 'name':'Leitre' },
'FMH': { 'latitude':'41.566667', 'longitude': '-70.633333', 'name':'Otis AFB' },
'FMI': { 'latitude':'-5.883333', 'longitude': '29.25', 'name':'Kalemie' },
'LTK': { 'latitude':'35.416667', 'longitude': '35.983333', 'name':'Latakia' },
'FMG': { 'latitude':'10.416667', 'longitude': '-85.783333', 'name':'Flamingo' },
'LTI': { 'latitude':'46.65', 'longitude': '96.416667', 'name':'Altai' },
'LTH': { 'latitude':'36.666667', 'longitude': '-116.65', 'name':'Lathrop Wells' },
'LTO': { 'latitude':'26.016667', 'longitude': '-111.366667', 'name':'Loreto' },
'LTN': { 'latitude':'51.866667', 'longitude': '-0.366667', 'name':'Luton' },
'LTM': { 'latitude':'3.4', 'longitude': '-59.8', 'name':'Lethem' },
'LTL': { 'latitude':'-0.833333', 'longitude': '12.716667', 'name':'Lastourville' },
'TKP': { 'latitude':'-15.45', 'longitude': '-145.141667', 'name':'Takapoto' },
'TCZ': { 'latitude':'25.025', 'longitude': '98.489167', 'name':'Tengchong' },
'ZNC': { 'latitude':'60.983333', 'longitude': '-159.983333', 'name':'Nyac' },
'ZNA': { 'latitude':'49.1672', 'longitude': '-123.9339', 'name':'Nanaimo Harbour Airport' },
'ZNG': { 'latitude':'53.0', 'longitude': '-97.266667', 'name':'Negginan' },
'ZNE': { 'latitude':'-23.416667', 'longitude': '119.933333', 'name':'Newman' },
'ZND': { 'latitude':'13.783333', 'longitude': '8.983333', 'name':'Zinder' },
'ZNU': { 'latitude':'51.85', 'longitude': '-127.866667', 'name':'Namu' },
'ZNZ': { 'latitude':'-6.216667', 'longitude': '39.216667', 'name':'Kisauni' },
'AJK': { 'latitude':'34.133056', 'longitude': '49.833056', 'name':'Araak' },
'AJL': { 'latitude':'23.733333', 'longitude': '92.716667', 'name':'Aizawl' },
'TCY': { 'latitude':'48.783333', 'longitude': '-87.1', 'name':'Terrace Bay' },
'AYL': { 'latitude':'-18.016667', 'longitude': '135.55', 'name':'Anthony Lagoon' },
'AYO': { 'latitude':'2.05', 'longitude': '33.75', 'name':'Ayolas' },
'AYN': { 'latitude':'36.1', 'longitude': '114.35', 'name':'Anyang' },
'AYI': { 'latitude':'-0.383333', 'longitude': '-72.266667', 'name':'Yari' },
'AYH': { 'latitude':'52.366667', 'longitude': '-0.266667', 'name':'RAF Station' },
'AYK': { 'latitude':'50.316667', 'longitude': '66.966667', 'name':'Arkalyk' },
'AYD': { 'latitude':'-19.3', 'longitude': '135.95', 'name':'Alroy Downs' },
'AYG': { 'latitude':'1.544167', 'longitude': '-73.933333', 'name':'Yaguara' },
'AYA': { 'latitude':'8.3', 'longitude': '-75.15', 'name':'Ayapel' },
'AYC': { 'latitude':'8.6', 'longitude': '-73.616667', 'name':'Ayacucho' },
'AYZ': { 'latitude':'40.666667', 'longitude': '-73.416667', 'name':'Zahns' },
'AYU': { 'latitude':'-6.333333', 'longitude': '145.9', 'name':'Aiyura' },
'AYT': { 'latitude':'36.916667', 'longitude': '30.8', 'name':'Antalya' },
'AYW': { 'latitude':'-1.2', 'longitude': '132.5', 'name':'Ayawasi' },
'AYQ': { 'latitude':'-25.333333', 'longitude': '131.033333', 'name':'Connellan' },
'AYP': { 'latitude':'-13.197222', 'longitude': '-74.247222', 'name':'Yanamilla' },
'AYS': { 'latitude':'31.25', 'longitude': '-82.4', 'name':'Ware County' },
'AYR': { 'latitude':'-19.666667', 'longitude': '147.366667', 'name':'Ayr' },
'FFU': { 'latitude':'-43.183333', 'longitude': '-71.816667', 'name':'Futaleufu' },
'XLO': { 'latitude':'10.483333', 'longitude': '105.45', 'name':'Long Xuyen' },
'XVY': { 'latitude':'41.966667', 'longitude': '12.666667', 'name':'Mestre Rail Stn.' },
'XLM': { 'latitude':'45.5', 'longitude': '-73.583333', 'name':'St Lambert Rail Svce.' },
'FFT': { 'latitude':'38.198611', 'longitude': '-84.906111', 'name':'Capital City' },
'XLJ': { 'latitude':'46.8', 'longitude': '-71.25', 'name':'Quebec Stn. Rail Svce.' },
'XLF': { 'latitude':'59.0', 'longitude': '-69.0', 'name':'Leaf Bay' },
'XLB': { 'latitude':'58.6175', 'longitude': '-101.468889', 'name':'Lac Brochet' },
'AJO': { 'latitude':'15.716667', 'longitude': '44.25', 'name':'Aljouf' },
'TCT': { 'latitude':'62.992778', 'longitude': '-156.065556', 'name':'Takotna' },
'XLW': { 'latitude':'53.135278', 'longitude': '8.617778', 'name':'Lemwerder' },
'XLU': { 'latitude':'11.1', 'longitude': '-2.1', 'name':'Leo' },
'XLS': { 'latitude':'16.05', 'longitude': '-16.45', 'name':'St Louis' },
'YZP': { 'latitude':'53.25', 'longitude': '-131.816667', 'name':'Sandspit' },
'YZR': { 'latitude':'43.0', 'longitude': '-82.3', 'name':'Sarnia' },
'YZS': { 'latitude':'64.2', 'longitude': '-83.366667', 'name':'Coral Harbour' },
'YZT': { 'latitude':'50.683333', 'longitude': '-127.366667', 'name':'Port Hardy' },
'RAO': { 'latitude':'-21.134167', 'longitude': '-47.774167', 'name':'Leite Lopes' },
'YZV': { 'latitude':'50.216667', 'longitude': '-66.266667', 'name':'Sept-Iles' },
'YZW': { 'latitude':'44.463333', 'longitude': '17.925833', 'name':'Teslin' },
'YZX': { 'latitude':'44.983333', 'longitude': '-64.916667', 'name':'Greenwood' },
'YZZ': { 'latitude':'49.055556', 'longitude': '-117.609167', 'name':'Trail' },
'XVQ': { 'latitude':'45.583333', 'longitude': '12.566667', 'name':'Santa Lucia Rail' },
'YZC': { 'latitude':'56.166667', 'longitude': '-120.416667', 'name':'Beatton River' },
'YZD': { 'latitude':'43.7425', 'longitude': '-79.465556', 'name':'Downsview Airport' },
'TCU': { 'latitude':'-29.25', 'longitude': '26.883333', 'name':'Thaba Nchu' },
'YZF': { 'latitude':'62.466667', 'longitude': '-114.45', 'name':'Yellowknife' },
'YZG': { 'latitude':'62.241667', 'longitude': '-75.616667', 'name':'Salluit' },
'YZH': { 'latitude':'55.293056', 'longitude': '-114.777222', 'name':'Slave Lake' },
'YZM': { 'latitude':'48.816667', 'longitude': '-56.866667', 'name':'Buchans' },
'UTI': { 'latitude':'60.9', 'longitude': '26.933333', 'name':'Utti' },
'TCR': { 'latitude':'8.783333', 'longitude': '78.133333', 'name':'Tuticorin' },
'SBU': { 'latitude':'-29.683333', 'longitude': '17.95', 'name':'Springbok' },
'FFD': { 'latitude':'51.7', 'longitude': '-1.783333', 'name':'RAF Station' },
'UTP': { 'latitude':'12.666667', 'longitude': '100.983333', 'name':'Utapao' },
'TCS': { 'latitude':'33.23694444', 'longitude': '-107.27111111', 'name':'Municipal' },
'FFA': { 'latitude':'36.016667', 'longitude': '-75.666667', 'name':'First Flight' },
'UTW': { 'latitude':'-31.916667', 'longitude': '26.883333', 'name':'Queenstown' },
'UTT': { 'latitude':'-31.583333', 'longitude': '28.783333', 'name':'Umtata' },
'VJQ': { 'latitude':'-15.5', 'longitude': '37.016667', 'name':'Gurue' },
'UTU': { 'latitude':'9.416667', 'longitude': '-78.6', 'name':'Ustupo' },
'TCP': { 'latitude':'29.587778', 'longitude': '34.778056', 'name':'Taba International' },
'VJI': { 'latitude':'-0.616667', 'longitude': '-90.883333', 'name':'Virginia Highlands' },
'VJB': { 'latitude':'-25.033333', 'longitude': '33.616667', 'name':'Xai Xai' },
'WPU': { 'latitude':'-54.916667', 'longitude': '-67.633333', 'name':'Puerto Williams' },
'WPR': { 'latitude':'-53.333333', 'longitude': '-70.341667', 'name':'Porvenir' },
'WPL': { 'latitude':'50.183333', 'longitude': '-124.4', 'name':'Powell Lake' },
'WPM': { 'latitude':'-8.75', 'longitude': '142.85', 'name':'Wipim' },
'WPO': { 'latitude':'38.866667', 'longitude': '-107.6', 'name':'North Fork Valley' },
'WPK': { 'latitude':'-16.633333', 'longitude': '144.0', 'name':'Wrotham Park' },
'WPA': { 'latitude':'-45.416667', 'longitude': '-72.7', 'name':'Puerto Aisen' },
'WPB': { 'latitude':'-15.55', 'longitude': '47.666667', 'name':'Port Berge' },
'WPC': { 'latitude':'49.483333', 'longitude': '-113.95', 'name':'Pincher Creek' },
'TCN': { 'latitude':'18.45', 'longitude': '-97.383333', 'name':'Tehuacan' },
'DTD': { 'latitude':'0.716667', 'longitude': '116.483333', 'name':'Datadawai' },
'TCO': { 'latitude':'1.833333', 'longitude': '-78.5', 'name':'La Florida' },
'RAV': { 'latitude':'6.316667', 'longitude': '-70.183333', 'name':'Cravo Norte' },
'ZST': { 'latitude':'55.95', 'longitude': '-129.983333', 'name':'Stewart' },
'ZSU': { 'latitude':'56.966667', 'longitude': '-5.333333', 'name':'Dessau Railway Stn.' },
'ZSW': { 'latitude':'54.286111', 'longitude': '-130.45', 'name':'Seal Cove' },
'ZSP': { 'latitude':'47.75', 'longitude': '-69.416667', 'name':'St Paul' },
'TCL': { 'latitude':'33.220556', 'longitude': '-87.611389', 'name':'Van De Graaf' },
'ZSZ': { 'latitude':'-22.666667', 'longitude': '14.566667', 'name':'Railway Station' },
'ZSE': { 'latitude':'-21.333333', 'longitude': '55.483333', 'name':'St Pierre dela Reunion' },
'ZSF': { 'latitude':'44.633333', 'longitude': '-64.85', 'name':'Springfield MA RR' },
'EUN': { 'latitude':'27.15', 'longitude': '-13.2', 'name':'Hassan I' },
'ZSA': { 'latitude':'24.059722', 'longitude': '-74.533056', 'name':'San Salvador' },
'ZSL': { 'latitude':'-18.233333', 'longitude': '30.816667', 'name':'Bus Station' },
'ZSH': { 'latitude':'1.366667', 'longitude': '-77.033333', 'name':'Bus Station' },
'ZSJ': { 'latitude':'53.066667', 'longitude': '-93.333333', 'name':'Sandy Lake' },
'RPR': { 'latitude':'21.183333', 'longitude': '81.733333', 'name':'Raipur' },
'RPV': { 'latitude':'-15.033333', 'longitude': '134.033333', 'name':'Roper Valley' },
'RPX': { 'latitude':'46.433333', 'longitude': '-108.533333', 'name':'Roundup' },
'RPA': { 'latitude':'28.7', 'longitude': '82.65', 'name':'Rolpa' },
'RAT': { 'latitude':'62.15', 'longitude': '77.333333', 'name':'Raduzhnyi' },
'RPM': { 'latitude':'-14.833333', 'longitude': '134.916667', 'name':'Ngukurr' },
'RPN': { 'latitude':'32.983333', 'longitude': '35.566667', 'name':'Rosh Pina' },
'TCJ': { 'latitude':'-4.016667', 'longitude': '143.133333', 'name':'Torembi Airport' },
'RAU': { 'latitude':'25.75', 'longitude': '89.233333', 'name':'Rangpur' },
'HXX': { 'latitude':'-34.516667', 'longitude': '144.833333', 'name':'Hay' },
'TCK': { 'latitude':'-4.1', 'longitude': '143.383333', 'name':'Tinboli Airport' },
'RAR': { 'latitude':'-21.2', 'longitude': '-159.8', 'name':'Rarotonga' },
'TCH': { 'latitude':'-2.866667', 'longitude': '11.016667', 'name':'Tchibanga' },
'NAC': { 'latitude':'-36.966667', 'longitude': '140.583333', 'name':'Naracoorte' },
'UQE': { 'latitude':'58.883333', 'longitude': '-158.5', 'name':'Queen' },
'HBO': { 'latitude':'40.166667', 'longitude': '-95.95', 'name':'Municipal' },
'HBN': { 'latitude':'12.0', 'longitude': '106.008333', 'name':'Flamingo' },
'NAF': { 'latitude':'2.75', 'longitude': '117.05', 'name':'Banaina' },
'TCI': { 'latitude':'28.47306', 'longitude': '-16.33278', 'name':'Tenerife Metropolitan Area' },
'HBH': { 'latitude':'57.408333', 'longitude': '-133.466667', 'name':'Hobart Bay' },
'IWD': { 'latitude':'46.533333', 'longitude': '-90.133333', 'name':'Gogebic County' },
'PZY': { 'latitude':'48.625278', 'longitude': '17.828333', 'name':'Piestany' },
'IWA': { 'latitude':'57.0', 'longitude': '41.0', 'name':'Ivanova' },
'IWO': { 'latitude':'24.783333', 'longitude': '141.333333', 'name':'Iwo Jima Airbase' },
'NAE': { 'latitude':'10.316667', 'longitude': '1.366667', 'name':'Natitingou' },
'IWJ': { 'latitude':'34.673056', 'longitude': '131.792778', 'name':'Iwami' },
'BOP': { 'latitude':'5.966667', 'longitude': '15.633333', 'name':'Bouar' },
'PZO': { 'latitude':'8.3', 'longitude': '-62.733333', 'name':'Puerto Ordaz' },
'PZI': { 'latitude':'22.0', 'longitude': '103.0', 'name':'Pan Zhi Hua' },
'PZH': { 'latitude':'31.333333', 'longitude': '69.5', 'name':'Zhob' },
'PZK': { 'latitude':'58.053056', 'longitude': '26.237778', 'name':'Puka Puka Is/Attol' },
'HBD': { 'latitude':'25.8', 'longitude': '43.3', 'name':'Habi' },
'PZE': { 'latitude':'50.116667', 'longitude': '-5.666667', 'name':'Penzance' },
'PZA': { 'latitude':'5.783333', 'longitude': '-71.816667', 'name':'Casanare' },
'HBG': { 'latitude':'19.233333', 'longitude': '-72.233333', 'name':'The Hattiesburg-Bobby L. Chain Mun.' },
'PZB': { 'latitude':'-29.648889', 'longitude': '30.398611', 'name':'Pietermaritzburg Oribi' },
'FVL': { 'latitude':'-18.333333', 'longitude': '128.0', 'name':'Flora Valey' },
'NAN': { 'latitude':'-17.75', 'longitude': '177.45', 'name':'Nadi International' },
'BOU': { 'latitude':'47.066667', 'longitude': '2.366667', 'name':'Bourges' },
'NAL': { 'latitude':'43.512778', 'longitude': '43.636667', 'name':'Nalchik' },
'BOW': { 'latitude':'27.933333', 'longitude': '-81.783333', 'name':'Bartow' },
'FVR': { 'latitude':'-15.3', 'longitude': '128.066667', 'name':'Forrest River Airport' },
'NAR': { 'latitude':'6.2', 'longitude': '-74.616667', 'name':'Nare' },
'BOI': { 'latitude':'43.564444', 'longitude': '-116.222778', 'name':'Boise Air Terminal/Gowen Field' },
'BOJ': { 'latitude':'42.566667', 'longitude': '27.5', 'name':'Bourgas' },
'NAQ': { 'latitude':'77.5', 'longitude': '-69.166667', 'name':'Qaanaaq' },
'NAV': { 'latitude':'38.771867', 'longitude': '34.53455', 'name':'Nevsehir' },
'HBX': { 'latitude':'15.361667', 'longitude': '75.084722', 'name':'Hubli' },
'SKU': { 'latitude':'38.883333', 'longitude': '24.55', 'name':'Skiros' },
'SKT': { 'latitude':'32.5', 'longitude': '74.516667', 'name':'Sialkot International' },
'SKW': { 'latitude':'61.95', 'longitude': '-151.2', 'name':'Intermediate' },
'SKV': { 'latitude':'28.5', 'longitude': '33.95', 'name':'Mount Sinai' },
'SKQ': { 'latitude':'-29.966667', 'longitude': '28.45', 'name':'Sekakes' },
'BON': { 'latitude':'12.131111', 'longitude': '-68.268611', 'name':'Flamingo International' },
'SKS': { 'latitude':'55.233333', 'longitude': '9.266667', 'name':'Vojens' },
'SKR': { 'latitude':'5.883333', 'longitude': '38.966667', 'name':'Shakiso' },
'BOO': { 'latitude':'67.266667', 'longitude': '14.366667', 'name':'Bodo' },
'SKY': { 'latitude':'41.433333', 'longitude': '-82.7', 'name':'Griffing Sandusky' },
'SKX': { 'latitude':'54.166667', 'longitude': '45.166667', 'name':'Saransk' },
'SKZ': { 'latitude':'27.733333', 'longitude': '68.783333', 'name':'Sukkur' },
'SKE': { 'latitude':'59.233333', 'longitude': '9.7', 'name':'Skien' },
'SKD': { 'latitude':'39.700556', 'longitude': '66.983889', 'name':'Samarkand' },
'SKG': { 'latitude':'40.519722', 'longitude': '22.970833', 'name':'Macedonia International' },
'SKF': { 'latitude':'6.233333', 'longitude': '-76.733333', 'name':'Kelly AFB' },
'SKC': { 'latitude':'-8.15', 'longitude': '141.716667', 'name':'Suki' },
'HBT': { 'latitude':'27.894444', 'longitude': '45.526389', 'name':'Hafr Albatin' },
'SKM': { 'latitude':'5.877778', 'longitude': '-57.175', 'name':'Skeldon' },
'SKL': { 'latitude':'57.333333', 'longitude': '-6.25', 'name':'Broadford' },
'SKO': { 'latitude':'13.016667', 'longitude': '5.266667', 'name':'Sokoto' },
'SKN': { 'latitude':'68.583333', 'longitude': '15.016667', 'name':'Skagen' },
'SKI': { 'latitude':'36.869444', 'longitude': '6.95', 'name':'Skikda' },
'NAX': { 'latitude':'18.433333', 'longitude': '-72.383333', 'name':'Barbers Point' },
'SKK': { 'latitude':'64.383333', 'longitude': '-161.1', 'name':'Shaktoolik' },
'SKJ': { 'latitude':'56.533333', 'longitude': '-154.133333', 'name':'Sitkinak Cgs' },
'GES': { 'latitude':'6.106389', 'longitude': '125.235278', 'name':'General Santos International' },
'GER': { 'latitude':'21.916667', 'longitude': '-82.75', 'name':'Rafael Cabrera' },
'GHN': { 'latitude':'30.466667', 'longitude': '106.65', 'name':'Guanghan' },
'BOC': { 'latitude':'9.35', 'longitude': '-82.25', 'name':'Bocas Del Toro' },
'GEW': { 'latitude':'-9.3', 'longitude': '148.466667', 'name':'Gewoia' },
'GEV': { 'latitude':'67.0', 'longitude': '20.833333', 'name':'Gallivare' },
'MFF': { 'latitude':'-1.536944', 'longitude': '13.270833', 'name':'Moanda' },
'MFG': { 'latitude':'34.383333', 'longitude': '73.483333', 'name':'Muzaffarabad' },
'TCV': { 'latitude':'-15.914722', 'longitude': '33.158889', 'name':'Tete' },
'MFI': { 'latitude':'44.6375', 'longitude': '-90.188889', 'name':'Municipal' },
'GEY': { 'latitude':'44.516667', 'longitude': '-108.083333', 'name':'South Big Horn County' },
'MFK': { 'latitude':'26.219444', 'longitude': '120.083333', 'name':'Matsu' },
'MFL': { 'latitude':'-19.666667', 'longitude': '144.9', 'name':'Mount Full Stop' },
'MFM': { 'latitude':'22.149444', 'longitude': '113.591667', 'name':'Macau International' },
'MFN': { 'latitude':'-44.616667', 'longitude': '167.933333', 'name':'Milford Sound' },
'MFO': { 'latitude':'27.966667', 'longitude': '34.383333', 'name':'Manguna' },
'GEC': { 'latitude':'35.237222', 'longitude': '33.720278', 'name':'Gecitkale' },
'GEB': { 'latitude':'-0.083333', 'longitude': '129.333333', 'name':'Gebe' },
'GEA': { 'latitude':'-22.266667', 'longitude': '166.466667', 'name':'Magenta' },
'MFS': { 'latitude':'1.033333', 'longitude': '-72.133333', 'name':'Miraflores' },
'MFT': { 'latitude':'-13.166111', 'longitude': '-72.498333', 'name':'Machu Picchu' },
'GEF': { 'latitude':'6.2', 'longitude': '19.183333', 'name':'Geva Airstrip' },
'MFV': { 'latitude':'13.633333', 'longitude': '39.133333', 'name':'Accomack County' },
'GED': { 'latitude':'38.683333', 'longitude': '-75.366667', 'name':'Sussex County' },
'GEK': { 'latitude':'62.983333', 'longitude': '-156.5', 'name':'Ganes Creek' },
'TCG': { 'latitude':'27.6', 'longitude': '99.466667', 'name':'Tacheng' },
'GEI': { 'latitude':'-4.5', 'longitude': '154.166667', 'name':'Green Islands' },
'HBR': { 'latitude':'34.991389', 'longitude': '-99.051389', 'name':'Hobart' },
'GEO': { 'latitude':'6.498611', 'longitude': '-58.254167', 'name':'Cheddi Jagan International' },
'TCC': { 'latitude':'-5.6', 'longitude': '-42.65', 'name':'Tucumcari' },
'GEL': { 'latitude':'-28.266667', 'longitude': '-54.266667', 'name':'Sepe Tiaraju' },
'SOH': { 'latitude':'34.233333', 'longitude': '-71.75', 'name':'Solita' },
'JGL': { 'latitude':'33.885', 'longitude': '-84.462778', 'name':'Galleria Heliport' },
'JGN': { 'latitude':'39.75', 'longitude': '98.25', 'name':'Jiayuguan' },
'JGO': { 'latitude':'69.25', 'longitude': '-53.55', 'name':'Qeqertarsuaq' },
'JGA': { 'latitude':'22.466667', 'longitude': '70.0', 'name':'Govardhanpur' },
'JGB': { 'latitude':'19.066667', 'longitude': '82.033333', 'name':'Jagdalpur' },
'DDP': { 'latitude':'18.5', 'longitude': '-66.25', 'name':'Dorado Beach' },
'JGE': { 'latitude':'34.907778', 'longitude': '128.686944', 'name':'Heliport' },
'DDU': { 'latitude':'26.75', 'longitude': '67.75', 'name':'Dadu' },
'JGX': { 'latitude':'34.133333', 'longitude': '-118.266667', 'name':'Heliport' },
'DDI': { 'latitude':'-20.166667', 'longitude': '148.183333', 'name':'Daydream Is' },
'DDN': { 'latitude':'-16.916667', 'longitude': '141.3', 'name':'Delta Downs' },
'DDM': { 'latitude':'-8.75', 'longitude': '147.45', 'name':'Dodoima' },
'DDC': { 'latitude':'37.766667', 'longitude': '-99.966667', 'name':'Dodge City Municipal' },
'JGR': { 'latitude':'61.233333', 'longitude': '-48.1', 'name':'Heliport' },
'JGS': { 'latitude':'26.899722', 'longitude': '114.7375', 'name':'Ji An' },
'DDG': { 'latitude':'40.2', 'longitude': '124.25', 'name':'Dandong' },
'SOK': { 'latitude':'-29.166667', 'longitude': '28.066667', 'name':'Semongkong' },
'VMU': { 'latitude':'-7.5', 'longitude': '144.8', 'name':'Baimuru' },
'SOJ': { 'latitude':'69.783333', 'longitude': '20.933333', 'name':'Sorkjosen' },
'KDL': { 'latitude':'58.983333', 'longitude': '22.8', 'name':'Kardla' },
'KDM': { 'latitude':'0.488056', 'longitude': '72.995556', 'name':'Kaadedhdhoo' },
'KDN': { 'latitude':'-2.5', 'longitude': '11.166667', 'name':'Ndende' },
'KDO': { 'latitude':'1.859167', 'longitude': '73.521944', 'name':'Kadhdhoo' },
'KDH': { 'latitude':'31.5', 'longitude': '65.85', 'name':'Kandahar' },
'KDI': { 'latitude':'-4.081667', 'longitude': '122.418333', 'name':'Wolter Monginsidi' },
'KDK': { 'latitude':'57.8', 'longitude': '-152.383333', 'name':'Municipal' },
'KDD': { 'latitude':'27.8', 'longitude': '66.6', 'name':'Khuzdar' },
'KDE': { 'latitude':'-5.683333', 'longitude': '142.733333', 'name':'Koroba' },
'KDF': { 'latitude':'7.8', 'longitude': '15.65', 'name':'Kouba' },
'KDG': { 'latitude':'42.102222', 'longitude': '25.218611', 'name':'Kardjali' },
'KDA': { 'latitude':'12.883333', 'longitude': '-14.966667', 'name':'Kolda' },
'KDB': { 'latitude':'-31.2', 'longitude': '121.666667', 'name':'Kambalda' },
'KDC': { 'latitude':'11.133333', 'longitude': '2.933333', 'name':'Kandi' },
'KDY': { 'latitude':'8.458611', 'longitude': '81.231944', 'name':'Mahaweli' },
'KDZ': { 'latitude':'7.2', 'longitude': '80.433333', 'name':'Polgolla Reservoir' },
'KDT': { 'latitude':'16.466667', 'longitude': '99.5', 'name':'Kamphangsaen' },
'KDU': { 'latitude':'35.3', 'longitude': '75.633333', 'name':'Skardu' },
'KDV': { 'latitude':'-19.05', 'longitude': '178.216667', 'name':'Kandavu' },
'KDW': { 'latitude':'7.3', 'longitude': '80.716667', 'name':'Vic. Resevour Kandy' },
'KDP': { 'latitude':'-5.866667', 'longitude': '143.5', 'name':'Kandep' },
'KDQ': { 'latitude':'-3.616667', 'longitude': '141.066667', 'name':'Kamberatoro' },
'KDR': { 'latitude':'-6.216667', 'longitude': '149.55', 'name':'Kandrian' },
'KDS': { 'latitude':'-24.333333', 'longitude': '139.166667', 'name':'Kamaran Downs' },
'NDI': { 'latitude':'-9.45', 'longitude': '148.233333', 'name':'Namudi' },
'PJM': { 'latitude':'8.55', 'longitude': '-83.316667', 'name':'Puerto Jimenez' },
'NDK': { 'latitude':'5.633333', 'longitude': '168.116667', 'name':'Namdrik Island' },
'HEW': { 'latitude':'37.983333', 'longitude': '23.733333', 'name':'Hellinikon' },
'NDM': { 'latitude':'9.816667', 'longitude': '35.083333', 'name':'Mendi' },
'NDL': { 'latitude':'8.4', 'longitude': '20.65', 'name':'Ndele' },
'NDO': { 'latitude':'37.383333', 'longitude': '-6.55', 'name':'La Palma Del Condado' },
'NDN': { 'latitude':'-9.133333', 'longitude': '147.683333', 'name':'Nadunumu' },
'NDA': { 'latitude':'-4.533333', 'longitude': '129.9', 'name':'Bandanaira' },
'NDC': { 'latitude':'19.183333', 'longitude': '77.316667', 'name':'Nanded' },
'NDB': { 'latitude':'20.9325', 'longitude': '-17.032778', 'name':'Nouadhibou' },
'NDE': { 'latitude':'3.933333', 'longitude': '41.866667', 'name':'Mandera' },
'NDD': { 'latitude':'-11.166667', 'longitude': '13.866667', 'name':'Sumbe' },
'NDG': { 'latitude':'47.316667', 'longitude': '123.916667', 'name':'Qiqihar' },
'NDF': { 'latitude':'-13.783333', 'longitude': '16.716667', 'name':'Ndalatandos' },
'HED': { 'latitude':'55.8', 'longitude': '-160.9', 'name':'Herendeen' },
'HEE': { 'latitude':'34.583333', 'longitude': '-90.666667', 'name':'Thompson-Robbins' },
'NDZ': { 'latitude':'53.768611', 'longitude': '8.644722', 'name':'Cuxhaven' },
'HEA': { 'latitude':'34.183333', 'longitude': '62.233333', 'name':'Herat' },
'HEB': { 'latitude':'17.6', 'longitude': '95.45', 'name':'Henzada' },
'SOO': { 'latitude':'61.3', 'longitude': '17.05', 'name':'Soderhamn' },
'HEL': { 'latitude':'60.317222', 'longitude': '24.963333', 'name':'Helsinki-vantaa' },
'NDP': { 'latitude':'30.526944', 'longitude': '-87.198056', 'name':'Ellyson NAS' },
'NDS': { 'latitude':'-28.0', 'longitude': '119.25', 'name':'Sandstone' },
'NDR': { 'latitude':'35.2', 'longitude': '-2.916667', 'name':'Nador' },
'NDU': { 'latitude':'-17.966667', 'longitude': '19.716667', 'name':'Rundu' },
'HEI': { 'latitude':'54.15', 'longitude': '8.9', 'name':'Heide-Buesum' },
'NDV': { 'latitude':'12.15', 'longitude': '36.366667', 'name':'USN Heliport' },
'BJG': { 'latitude':'-0.960556', 'longitude': '122.111944', 'name':'Bolaang' },
'BJF': { 'latitude':'70.633333', 'longitude': '29.5', 'name':'Batsfjord' },
'BJD': { 'latitude':'66.066667', 'longitude': '-14.75', 'name':'Bakkafjordur' },
'BJC': { 'latitude':'39.933333', 'longitude': '-105.066667', 'name':'Jeffco' },
'BJB': { 'latitude':'37.488333', 'longitude': '57.305556', 'name':'Bojnord' },
'BJA': { 'latitude':'36.75', 'longitude': '5.083333', 'name':'Bejaia' },
'BJO': { 'latitude':'-22.866667', 'longitude': '-64.333333', 'name':'Bermejo' },
'BJN': { 'latitude':'-17.183333', 'longitude': '37.95', 'name':'Bajone' },
'BJM': { 'latitude':'-3.316667', 'longitude': '29.316667', 'name':'International' },
'BJL': { 'latitude':'13.35', 'longitude': '-16.666667', 'name':'Yundum International' },
'BJK': { 'latitude':'-6.083333', 'longitude': '134.25', 'name':'Benjina' },
'BJJ': { 'latitude':'40.8', 'longitude': '-81.933333', 'name':'Wayne County' },
'BJI': { 'latitude':'47.516667', 'longitude': '-94.933333', 'name':'Bemidji' },
'BJH': { 'latitude':'29.55', 'longitude': '81.25', 'name':'Bajhang' },
'BJW': { 'latitude':'-8.783333', 'longitude': '120.966667', 'name':'Bajawa' },
'BJV': { 'latitude':'37.250556', 'longitude': '27.664444', 'name':'Milas' },
'BJU': { 'latitude':'29.35', 'longitude': '81.3', 'name':'Bajura Arpt' },
'BJT': { 'latitude':'6.421111', 'longitude': '79.998889', 'name':'Bentota River' },
'BJR': { 'latitude':'11.766667', 'longitude': '37.416667', 'name':'Bahar Dar' },
'BJP': { 'latitude':'-4.633333', 'longitude': '-39.766667', 'name':'Braganca Paulista' },
'BJZ': { 'latitude':'38.883333', 'longitude': '-6.816667', 'name':'Talaveral La Real' },
'BJY': { 'latitude':'44.935278', 'longitude': '20.2575', 'name':'Batajnica' },
'BJX': { 'latitude':'20.993333', 'longitude': '-101.480833', 'name':'Del Bajío International' },
'PJA': { 'latitude':'67.246667', 'longitude': '23.075', 'name':'Pajala' },
'PJC': { 'latitude':'-22.545', 'longitude': '-55.745', 'name':'Pedro Juan Caballero' },
'PJB': { 'latitude':'34.261111', 'longitude': '-111.341667', 'name':'Payson' },
'OWK': { 'latitude':'44.716667', 'longitude': '-69.8', 'name':'Central Maine Airport of Norridgewock' },
'OWE': { 'latitude':'0.283333', 'longitude': '9.5', 'name':'Owendo' },
'OWD': { 'latitude':'42.183333', 'longitude': '-71.183333', 'name':'Memorial' },
'OWA': { 'latitude':'44.116667', 'longitude': '-93.25', 'name':'Owatonna' },
'OWB': { 'latitude':'37.75', 'longitude': '-87.166667', 'name':'Daviess County' },
'SOP': { 'latitude':'35.215278', 'longitude': '-79.588333', 'name':'Pinehurst-S. Pines' },
'LVP': { 'latitude':'26.8', 'longitude': '53.25', 'name':'Lavan' },
'LVS': { 'latitude':'35.65', 'longitude': '-105.15', 'name':'Las Vegas' },
'LVD': { 'latitude':'61.35', 'longitude': '-155.466667', 'name':'Lime Village' },
'LVA': { 'latitude':'48.066667', 'longitude': '-0.766667', 'name':'Entrammes' },
'LVB': { 'latitude':'-30.85', 'longitude': '-55.6', 'name':'Dos Galpoes' },
'LVM': { 'latitude':'45.666667', 'longitude': '-110.566667', 'name':'Mission Field' },
'LVL': { 'latitude':'36.75', 'longitude': '-77.85', 'name':'Lawrenceville' },
'LVO': { 'latitude':'-28.633333', 'longitude': '122.366667', 'name':'Laverton' },
'SVA': { 'latitude':'63.693333', 'longitude': '-170.459444', 'name':'Savoonga' },
'LVI': { 'latitude':'-17.805278', 'longitude': '25.822778', 'name':'Livingstone' },
'LVK': { 'latitude':'37.683333', 'longitude': '-121.766667', 'name':'Livermore' },
'SOR': { 'latitude':'34.4', 'longitude': '40.166667', 'name':'Al Thaurah' },
'YYH': { 'latitude':'69.533333', 'longitude': '-93.533333', 'name':'Taloyoak' },
'SOU': { 'latitude':'50.95', 'longitude': '-1.35', 'name':'Southampton Airport' },
'MYY': { 'latitude':'4.452778', 'longitude': '114.0', 'name':'Miri' },
'MYX': { 'latitude':'-7.2', 'longitude': '146.016667', 'name':'Menyamya' },
'MYZ': { 'latitude':'-14.1', 'longitude': '34.533333', 'name':'Monkey Bay' },
'MYQ': { 'latitude':'12.3', 'longitude': '76.65', 'name':'Mysore' },
'MYP': { 'latitude':'37.619444', 'longitude': '61.896667', 'name':'Mary' },
'MYS': { 'latitude':'3.466667', 'longitude': '39.1', 'name':'Moyale' },
'MYR': { 'latitude':'33.7', 'longitude': '-78.966667', 'name':'Myrtle Beach Afb' },
'MYU': { 'latitude':'60.383333', 'longitude': '-166.2', 'name':'Ellis Field' },
'MYT': { 'latitude':'25.466667', 'longitude': '97.433333', 'name':'Myitkyina' },
'MYW': { 'latitude':'-10.35', 'longitude': '40.183333', 'name':'Mtwara' },
'MYV': { 'latitude':'39.1', 'longitude': '-121.566667', 'name':'Yuba County' },
'MYI': { 'latitude':'-9.933333', 'longitude': '144.016667', 'name':'Murray Island' },
'MYH': { 'latitude':'36.816667', 'longitude': '-111.65', 'name':'Marble Canyon' },
'MYK': { 'latitude':'61.366667', 'longitude': '-142.683333', 'name':'May Creek' },
'MYJ': { 'latitude':'33.816667', 'longitude': '132.7', 'name':'Matsuyama' },
'MYM': { 'latitude':'4.6', 'longitude': '-59.633333', 'name':'Monkey Mountain' },
'MYL': { 'latitude':'45.883333', 'longitude': '-116.1', 'name':'Mccall' },
'MYO': { 'latitude':'-18.2', 'longitude': '124.2', 'name':'Myroodah' },
'MYN': { 'latitude':'15.483333', 'longitude': '45.333333', 'name':'Mareb' },
'MYA': { 'latitude':'-35.9', 'longitude': '150.133333', 'name':'Moruya' },
'MYC': { 'latitude':'10.25', 'longitude': '-67.6', 'name':'Maracay' },
'MYB': { 'latitude':'-3.45', 'longitude': '10.683333', 'name':'Mayoumba' },
'MYE': { 'latitude':'34.066667', 'longitude': '139.566667', 'name':'Miyake Jima' },
'MYD': { 'latitude':'-3.229444', 'longitude': '40.101667', 'name':'Malindi' },
'MYG': { 'latitude':'22.366667', 'longitude': '-73.016667', 'name':'Mayaguana' },
'MYF': { 'latitude':'32.8', 'longitude': '-117.133333', 'name':'Montgomery Field' },
'CQM': { 'latitude':'38.856389', 'longitude': '-3.97', 'name':'Ciudad Real' },
'SOW': { 'latitude':'34.265556', 'longitude': '-110.005556', 'name':'Show Low' },
'CQA': { 'latitude':'-4.45', 'longitude': '-44.533333', 'name':'Canarana Airport' },
'CQF': { 'latitude':'50.966667', 'longitude': '1.95', 'name':'Calais' },
'CQD': { 'latitude':'32.3', 'longitude': '50.833333', 'name':'Shahre-kord' },
'CQP': { 'latitude':'-18.2', 'longitude': '147.5', 'name':'Cape Flattery' },
'CQT': { 'latitude':'2.033333', 'longitude': '-74.216667', 'name':'Caquetania' },
'ZLG': { 'latitude':'20.85', 'longitude': '-17.083333', 'name':'El Gouera' },
'SOY': { 'latitude':'59.183333', 'longitude': '-2.516667', 'name':'Stronsay' },
'ZLO': { 'latitude':'19.116667', 'longitude': '-104.333333', 'name':'Manzanillo' },
'ZLT': { 'latitude':'51.0', 'longitude': '-59.0', 'name':'La Tabatiere' },
'ZLW': { 'latitude':'5.95', 'longitude': '102.083333', 'name':'Pasir Gudang Port' },
'SOX': { 'latitude':'5.683333', 'longitude': '-72.95', 'name':'Alberto Lleras Camargo' },
'SOZ': { 'latitude':'41.85', 'longitude': '9.383333', 'name':'Solenzara' },
'GNV': { 'latitude':'29.683333', 'longitude': '-82.266667', 'name':'Gainesville Regional' },
'FLY': { 'latitude':'-35.65', 'longitude': '145.583333', 'name':'Finley' },
'XNU': { 'latitude':'12.733333', 'longitude': '-3.866667', 'name':'Nouna' },
'XNT': { 'latitude':'37.071944', 'longitude': '114.484444', 'name':'Xingtai' },
'FLX': { 'latitude':'39.466667', 'longitude': '-118.769444', 'name':'Municipal' },
'XNA': { 'latitude':'36.281667', 'longitude': '-94.306667', 'name':'Northwest Arkansas Regional' },
'XNG': { 'latitude':'15.116667', 'longitude': '108.75', 'name':'Quang Ngai' },
'XNN': { 'latitude':'36.549722', 'longitude': '101.75', 'name':'Xining' },
'YXZ': { 'latitude':'47.983333', 'longitude': '-84.783333', 'name':'Wawa Airport' },
'YXX': { 'latitude':'49.025278', 'longitude': '-122.360556', 'name':'Abbotsford' },
'YXY': { 'latitude':'60.709444', 'longitude': '-135.067222', 'name':'Whitehorse International' },
'YXR': { 'latitude':'47.7', 'longitude': '-79.85', 'name':'Earlton' },
'YXS': { 'latitude':'53.883333', 'longitude': '-122.683333', 'name':'Prince George' },
'YXP': { 'latitude':'66.15', 'longitude': '-65.733333', 'name':'Pangnirtung' },
'YXQ': { 'latitude':'52.733333', 'longitude': '-1.116667', 'name':'Beaver Creek' },
'YXT': { 'latitude':'54.468611', 'longitude': '-128.576111', 'name':'Terrace' },
'YXU': { 'latitude':'43.035556', 'longitude': '-81.153889', 'name':'London International' },
'YXJ': { 'latitude':'56.233333', 'longitude': '-120.733333', 'name':'Fort St John' },
'YXK': { 'latitude':'48.466667', 'longitude': '-68.516667', 'name':'Rimouski' },
'YXH': { 'latitude':'50.018889', 'longitude': '-110.720833', 'name':'Medicine Hat' },
'YXI': { 'latitude':'45.55', 'longitude': '-77.416667', 'name':'Killaloe' },
'YXN': { 'latitude':'62.183333', 'longitude': '-92.6', 'name':'Whale Cove' },
'YXL': { 'latitude':'50.116667', 'longitude': '-91.9', 'name':'Sioux Lookout' },
'FLP': { 'latitude':'36.3', 'longitude': '-92.583333', 'name':'Flippin' },
'YXC': { 'latitude':'49.612222', 'longitude': '-115.781944', 'name':'Cranbrook' },
'YXF': { 'latitude':'65.966667', 'longitude': '-134.166667', 'name':'Snake River' },
'FLS': { 'latitude':'-40.083333', 'longitude': '148.0', 'name':'Flinders Island' },
'YXD': { 'latitude':'53.566667', 'longitude': '-113.516667', 'name':'Edmonton City Center Airport' },
'YXE': { 'latitude':'52.166667', 'longitude': '-106.683333', 'name':'J.G. Diefenbaker International Airport' },
'LKE': { 'latitude':'47.628889', 'longitude': '-122.338611', 'name':'Kenmore Air Harbor SPB' },
'LKB': { 'latitude':'-18.2', 'longitude': '178.833333', 'name':'Lakeba' },
'FLV': { 'latitude':'19.833333', 'longitude': '-72.5', 'name':'Sherman AAF' },
'GNZ': { 'latitude':'-21.7', 'longitude': '21.666667', 'name':'Ghanzi' },
'VDB': { 'latitude':'61.083333', 'longitude': '9.333333', 'name':'Valdres' },
'FLM': { 'latitude':'-22.359444', 'longitude': '-60.053611', 'name':'Filadelfia' },
'VME': { 'latitude':'-33.633333', 'longitude': '-65.416667', 'name':'Villa Mercedes' },
'VHY': { 'latitude':'46.166667', 'longitude': '3.4', 'name':'Charmeil' },
'VHZ': { 'latitude':'-18.583333', 'longitude': '-138.833333', 'name':'Vahitahi' },
'LKY': { 'latitude':'-3.5', 'longitude': '36.416667', 'name':'Lake Manyara' },
'VHM': { 'latitude':'64.616667', 'longitude': '16.65', 'name':'Vilhelmina' },
'LKV': { 'latitude':'42.166667', 'longitude': '-120.4', 'name':'Lake County' },
'VHN': { 'latitude':'31.033333', 'longitude': '-104.816667', 'name':'Culberson County' },
'LKT': { 'latitude':'5.85', 'longitude': '-5.683333', 'name':'Lakota' },
'VHC': { 'latitude':'-9.75', 'longitude': '20.55', 'name':'Saurimo' },
'TXN': { 'latitude':'29.711389', 'longitude': '118.3125', 'name':'Tunxi' },
'TXM': { 'latitude':'-1.433333', 'longitude': '132.016667', 'name':'Teminabuan' },
'LKU': { 'latitude':'3.416667', 'longitude': '35.883333', 'name':'Lake Rudolf' },
'TXK': { 'latitude':'33.456389', 'longitude': '-93.989167', 'name':'Texarkana' },
'TXG': { 'latitude':'24.186389', 'longitude': '120.653889', 'name':'Taichung' },
'LKR': { 'latitude':'11.15', 'longitude': '48.2', 'name':'Las Khoreh' },
'LKS': { 'latitude':'29.847778', 'longitude': '-95.688611', 'name':'Lakeside' },
'LKP': { 'latitude':'44.264444', 'longitude': '-73.961944', 'name':'Lake Placid' },
'TXU': { 'latitude':'4.4', 'longitude': '-7.35', 'name':'Tabou' },
'GNY': { 'latitude':'37.097368', 'longitude': '38.847098', 'name':'Sanliurfa Guney Anadoulu Projesi' },
'TXR': { 'latitude':'-25.833333', 'longitude': '141.916667', 'name':'Tanbar' },
'PAP': { 'latitude':'18.583333', 'longitude': '-72.3', 'name':'Toussaint Louverture International' },
'PAQ': { 'latitude':'61.6', 'longitude': '-149.116667', 'name':'Municipal' },
'ZQW': { 'latitude':'49.209525', 'longitude': '7.400647', 'name':'Zweibrcken' },
'ZQS': { 'latitude':'53.0', 'longitude': '-132.0', 'name':'Queen Charlotte Is' },
'ZQN': { 'latitude':'-45.021111', 'longitude': '168.739167', 'name':'Queenstown' },
'PAT': { 'latitude':'25.590278', 'longitude': '85.089722', 'name':'Patna' },
'PAV': { 'latitude':'-9.383333', 'longitude': '-38.233333', 'name':'Paulo Afonso' },
'PAW': { 'latitude':'-10.583333', 'longitude': '151.083333', 'name':'Pambwa' },
'PAX': { 'latitude':'19.933333', 'longitude': '-72.841667', 'name':'Port De Paix' },
'PAY': { 'latitude':'6.0', 'longitude': '117.4', 'name':'Pamol' },
'PAZ': { 'latitude':'20.55', 'longitude': '-97.05', 'name':'Tajin' },
'NTY': { 'latitude':'-25.333889', 'longitude': '27.173333', 'name':'Pilanesberg' },
'HZG': { 'latitude':'32.983333', 'longitude': '107.183333', 'name':'Hanzhong' },
'WRE': { 'latitude':'-35.766667', 'longitude': '174.366667', 'name':'Whangarei' },
'WRB': { 'latitude':'50.033333', 'longitude': '4.2', 'name':'Robins AFB' },
'HZB': { 'latitude':'50.616667', 'longitude': '2.65', 'name':'Merville/Calonne' },
'HZL': { 'latitude':'40.983333', 'longitude': '-76.0', 'name':'Hazleton' },
'WRL': { 'latitude':'43.965833', 'longitude': '-107.884167', 'name':'Worland' },
'HZH': { 'latitude':'26.335', 'longitude': '109.15', 'name':'Liping' },
'HZK': { 'latitude':'65.966944', 'longitude': '-17.416667', 'name':'Husavik' },
'WRI': { 'latitude':'40.015556', 'longitude': '-74.593611', 'name':'Mc Guire Afb' },
'WRW': { 'latitude':'-20.966667', 'longitude': '120.7', 'name':'Warrawagine' },
'GNB': { 'latitude':'45.363056', 'longitude': '5.332778', 'name':'Grenoble-isere Airport' },
'HZV': { 'latitude':'-25.033333', 'longitude': '31.116667', 'name':'Hazyview' },
'WRZ': { 'latitude':'6.254444', 'longitude': '81.235278', 'name':'Wirawila' },
'WRY': { 'latitude':'59.35', 'longitude': '-2.95', 'name':'Westray' },
'PAA': { 'latitude':'16.883333', 'longitude': '97.666667', 'name':'Pa-an' },
'ALI': { 'latitude':'27.733333', 'longitude': '-98.016667', 'name':'International' },
'NTQ': { 'latitude':'37.4', 'longitude': '136.9', 'name':'Noto Airport' },
'PAC': { 'latitude':'8.973333', 'longitude': '-79.555556', 'name':'Paitilla-Marcos A. Gelabert' },
'UOS': { 'latitude':'35.205278', 'longitude': '-85.898056', 'name':'Franklin County' },
'NTR': { 'latitude':'25.865556', 'longitude': '-100.237222', 'name':'Tuxtla Gutierrez' },
'PAF': { 'latitude':'2.2', 'longitude': '31.616667', 'name':'Pakuba' },
'NTU': { 'latitude':'-41.933333', 'longitude': '145.35', 'name':'NAS' },
'PAG': { 'latitude':'7.833333', 'longitude': '123.483333', 'name':'Pagadian' },
'NTT': { 'latitude':'-15.5', 'longitude': '-174.0', 'name':'Kuini Lavenia' },
'UON': { 'latitude':'20.816667', 'longitude': '102.0', 'name':'Muong Sai' },
'UOL': { 'latitude':'1.166667', 'longitude': '121.433333', 'name':'Buol' },
'IUM': { 'latitude':'54.283333', 'longitude': '-122.633333', 'name':'Summit Lake' },
'IUL': { 'latitude':'-3.75', 'longitude': '138.083333', 'name':'Ilu' },
'PAL': { 'latitude':'5.483333', 'longitude': '-74.65', 'name':'Palanquero' },
'IUE': { 'latitude':'-19.083333', 'longitude': '-169.933333', 'name':'Niue Island' },
'PAM': { 'latitude':'30.07', 'longitude': '-85.576389', 'name':'Tyndall AFB' },
'NTM': { 'latitude':'-9.183333', 'longitude': '-48.5', 'name':'Miracema Do Norte' },
'IUS': { 'latitude':'-5.816667', 'longitude': '155.166667', 'name':'Inus' },
'PAO': { 'latitude':'37.466667', 'longitude': '-122.116667', 'name':'Palo Alto' },
'FTU': { 'latitude':'-25.033333', 'longitude': '46.95', 'name':'Marillac' },
'NTO': { 'latitude':'17.05', 'longitude': '-25.166667', 'name':'Santo Antao' },
'FTW': { 'latitude':'32.855556', 'longitude': '-96.85', 'name':'Meacham Field' },
'FTY': { 'latitude':'9.716667', 'longitude': '-82.983333', 'name':'Fulton County' },
'FTX': { 'latitude':'-0.983333', 'longitude': '16.008333', 'name':'Owando' },
'NTN': { 'latitude':'-17.7', 'longitude': '141.066667', 'name':'Normanton' },
'FTA': { 'latitude':'-19.533333', 'longitude': '170.216667', 'name':'Futuna Airport' },
'ALV': { 'latitude':'42.5', 'longitude': '1.516667', 'name':'Andorra La Vella H/P' },
'FTE': { 'latitude':'-50.280278', 'longitude': '-72.053056', 'name':'El Calafate' },
'FTI': { 'latitude':'-14.216667', 'longitude': '-169.45', 'name':'Fitiuta' },
'FTK': { 'latitude':'19.833333', 'longitude': '-72.5', 'name':'Godman AAF' },
'FTL': { 'latitude':'61.866667', 'longitude': '-162.033333', 'name':'Fortuna Ledge' },
'NTB': { 'latitude':'59.584167', 'longitude': '9.135278', 'name':'Notodden' },
'GNG': { 'latitude':'42.916667', 'longitude': '-114.783333', 'name':'Gooding' },
'NTE': { 'latitude':'47.15', 'longitude': '-1.6', 'name':'Nantes Atlantique' },
'ALS': { 'latitude':'37.433333', 'longitude': '-105.866667', 'name':'Municipal' },
'NTG': { 'latitude':'32.066667', 'longitude': '120.966667', 'name':'Nantong' },
'SMZ': { 'latitude':'5.075', 'longitude': '-55.008333', 'name':'Stoelmans Eiland' },
'SMY': { 'latitude':'13.166667', 'longitude': '-13.166667', 'name':'Simenti' },
'SMX': { 'latitude':'34.9', 'longitude': '-120.45', 'name':'Public' },
'SMW': { 'latitude':'26.733333', 'longitude': '-11.683333', 'name':'Smara' },
'SMV': { 'latitude':'46.534167', 'longitude': '9.884167', 'name':'Samedan' },
'SMU': { 'latitude':'61.8', 'longitude': '-147.666667', 'name':'Sheep Mountain' },
'SMT': { 'latitude':'23.883333', 'longitude': '120.933333', 'name':'Sun Moon Lake' },
'SMS': { 'latitude':'-17.093889', 'longitude': '49.815833', 'name':'Sainte Marie' },
'SMR': { 'latitude':'11.136111', 'longitude': '-74.216667', 'name':'Simon Bolivar' },
'SMQ': { 'latitude':'-3.083333', 'longitude': '113.05', 'name':'Sampit' },
'SMP': { 'latitude':'-4.35', 'longitude': '151.55', 'name':'Stockholm' },
'SMO': { 'latitude':'34.015833', 'longitude': '-118.45', 'name':'Santa Monica' },
'SMN': { 'latitude':'45.183333', 'longitude': '-113.916667', 'name':'Salmon' },
'SMM': { 'latitude':'4.45', 'longitude': '118.6', 'name':'Semporna' },
'SML': { 'latitude':'23.6', 'longitude': '-75.3', 'name':'Estate Airstrip' },
'SMK': { 'latitude':'63.483333', 'longitude': '-162.016667', 'name':'St Michael' },
'SMJ': { 'latitude':'-7.666667', 'longitude': '146.833333', 'name':'Sim' },
'SMI': { 'latitude':'37.684444', 'longitude': '26.902222', 'name':'Samos' },
'SMH': { 'latitude':'-6.083333', 'longitude': '146.75', 'name':'Sapmanga' },
'SMG': { 'latitude':'-11.983333', 'longitude': '-77.0', 'name':'Santa Maria' },
'SMF': { 'latitude':'38.7', 'longitude': '-121.616667', 'name':'Sacramento International' },
'SME': { 'latitude':'37.083333', 'longitude': '-84.6', 'name':'Pulaski County' },
'SMD': { 'latitude':'41.143333', 'longitude': '-85.152778', 'name':'Smith Field' },
'SMC': { 'latitude':'8.166667', 'longitude': '-77.05', 'name':'Santa Maria' },
'SMB': { 'latitude':'-52.666667', 'longitude': '-69.266667', 'name':'Cerro Sombrero' },
'SMA': { 'latitude':'36.971389', 'longitude': '-25.170556', 'name':'Vila Do Porto' },
'MDJ': { 'latitude':'44.633333', 'longitude': '-121.133333', 'name':'City-county' },
'MDK': { 'latitude':'0.023333', 'longitude': '18.292222', 'name':'Mbandaka' },
'MDH': { 'latitude':'37.783333', 'longitude': '-89.25', 'name':'Southern Illinois' },
'MDI': { 'latitude':'7.716667', 'longitude': '8.6', 'name':'Makurdi' },
'MDN': { 'latitude':'38.733333', 'longitude': '-85.366667', 'name':'Jefferson Proving Grd' },
'MDO': { 'latitude':'59.45', 'longitude': '-146.316667', 'name':'Intermediate' },
'MDL': { 'latitude':'21.702222', 'longitude': '95.977778', 'name':'Mandalay International' },
'MDM': { 'latitude':'-4.633333', 'longitude': '143.45', 'name':'Munduku' },
'MDB': { 'latitude':'16.999722', 'longitude': '-88.316667', 'name':'Melinda' },
'MDC': { 'latitude':'1.533333', 'longitude': '124.916667', 'name':'Samratulangi' },
'MDA': { 'latitude':'29.431389', 'longitude': '-98.377778', 'name':'Martindale Army Heliport' },
'MDF': { 'latitude':'45.15', 'longitude': '-90.333333', 'name':'Medford' },
'MDG': { 'latitude':'44.6', 'longitude': '129.5', 'name':'Mudanjiang' },
'MDD': { 'latitude':'44.75', 'longitude': '-79.9', 'name':'Airpark' },
'MDE': { 'latitude':'6.167222', 'longitude': '-75.590556', 'name':'Jose Maria Cordova' },
'MDZ': { 'latitude':'-32.833333', 'longitude': '-68.783333', 'name':'El Plumerillo' },
'GGD': { 'latitude':'-18.7', 'longitude': '139.25', 'name':'Gregory Downs' },
'MDX': { 'latitude':'-29.216944', 'longitude': '-58.083333', 'name':'Mercedes' },
'MDY': { 'latitude':'28.2', 'longitude': '-177.383333', 'name':'Sand Island Field' },
'GGC': { 'latitude':'-14.116667', 'longitude': '21.433333', 'name':'Lumbala' },
'MDR': { 'latitude':'63.1', 'longitude': '-154.716667', 'name':'Medfra' },
'MDS': { 'latitude':'21.783333', 'longitude': '-71.766667', 'name':'Middle Caicos' },
'MDP': { 'latitude':'-5.866667', 'longitude': '147.7', 'name':'Mindiptana' },
'MDQ': { 'latitude':'-37.934167', 'longitude': '-57.573333', 'name':'Mar Del Plata' },
'MDV': { 'latitude':'1.016667', 'longitude': '10.75', 'name':'Medouneu' },
'MDW': { 'latitude':'41.783333', 'longitude': '-87.75', 'name':'Midway' },
'MDT': { 'latitude':'40.193611', 'longitude': '-76.763333', 'name':'Harrisburg International' },
'MDU': { 'latitude':'-6.166667', 'longitude': '143.666667', 'name':'Mendi' },
'JER': { 'latitude':'49.208056', 'longitude': '-2.195556', 'name':'Jersey' },
'OAN': { 'latitude':'15.523611', 'longitude': '-86.635278', 'name':'Olanchito' },
'JEQ': { 'latitude':'-13.85', 'longitude': '-40.083333', 'name':'Jequie' },
'JEV': { 'latitude':'48.616667', 'longitude': '2.416667', 'name':'Heliport' },
'DFW': { 'latitude':'32.896944', 'longitude': '-97.038056', 'name':'Dallas/Fort Worth International' },
'DFP': { 'latitude':'-16.0', 'longitude': '143.033333', 'name':'Drumduff' },
'JEF': { 'latitude':'38.591111', 'longitude': '-92.039444', 'name':'Memorial' },
'JEG': { 'latitude':'68.721944', 'longitude': '-52.784722', 'name':'Aasiaat' },
'JED': { 'latitude':'21.679444', 'longitude': '39.156667', 'name':'King Abdulaziz International' },
'JEE': { 'latitude':'18.666667', 'longitude': '-74.166667', 'name':'Jeremie' },
'JEJ': { 'latitude':'7.583333', 'longitude': '168.916667', 'name':'Jeh' },
'JEM': { 'latitude':'37.95', 'longitude': '-122.336111', 'name':'Heliport' },
'KFS': { 'latitude':'41.272778', 'longitude': '22.894722', 'name':'Kastamonu' },
'KFP': { 'latitude':'54.85', 'longitude': '-163.416667', 'name':'False Pass' },
'QKB': { 'latitude':'-28.833333', 'longitude': '22.616667', 'name':'Van Service' },
'KFG': { 'latitude':'-17.433333', 'longitude': '130.816667', 'name':'Kalkurung' },
'TOD': { 'latitude':'2.818056', 'longitude': '104.16', 'name':'Tioman' },
'KFA': { 'latitude':'16.633333', 'longitude': '-11.4', 'name':'Kiffa' },
'ABA': { 'latitude':'53.716667', 'longitude': '91.433333', 'name':'Abakan' },
'ABB': { 'latitude':'51.666667', 'longitude': '-1.283333', 'name':'RAF Station' },
'ABC': { 'latitude':'38.983333', 'longitude': '-1.85', 'name':'Los Llanos' },
'HGZ': { 'latitude':'66.183333', 'longitude': '-155.666667', 'name':'Hogatza' },
'ABE': { 'latitude':'40.652222', 'longitude': '-75.440278', 'name':'Lehigh Valley International' },
'ABF': { 'latitude':'1.416667', 'longitude': '172.833333', 'name':'Abaiang' },
'ABG': { 'latitude':'-17.666667', 'longitude': '143.2', 'name':'Abingdon' },
'ABH': { 'latitude':'-23.7', 'longitude': '146.583333', 'name':'Alpha' },
'ABI': { 'latitude':'32.416667', 'longitude': '-99.683333', 'name':'Municipal' },
'HGT': { 'latitude':'-7.3', 'longitude': '157.033333', 'name':'Hunter AAF' },
'HGU': { 'latitude':'-5.829167', 'longitude': '144.298056', 'name':'Kagamuga' },
'HGR': { 'latitude':'39.7', 'longitude': '-77.716667', 'name':'Wash. County Regional' },
'HGS': { 'latitude':'8.616111', 'longitude': '-13.183056', 'name':'Hastings' },
'ABN': { 'latitude':'5.483333', 'longitude': '-54.05', 'name':'Albina' },
'ABO': { 'latitude':'5.466667', 'longitude': '-3.2', 'name':'Aboisso' },
'ABP': { 'latitude':'-6.066667', 'longitude': '141.1', 'name':'Atkamba' },
'ABQ': { 'latitude':'35.040278', 'longitude': '-106.609167', 'name':'Albuquerque International' },
'ABR': { 'latitude':'45.45', 'longitude': '-98.433333', 'name':'Municipal' },
'HIS': { 'latitude':'-20.066667', 'longitude': '148.866667', 'name':'Hayman Island' },
'ABT': { 'latitude':'20.285556', 'longitude': '41.633333', 'name':'Al-Baha' },
'ABU': { 'latitude':'-9.333333', 'longitude': '124.9', 'name':'Atambua' },
'ABV': { 'latitude':'9.006667', 'longitude': '7.263056', 'name':'Nnamdi Azikiwe International Airport' },
'ABW': { 'latitude':'-10.166667', 'longitude': '148.7', 'name':'Abau' },
'ABX': { 'latitude':'-36.066667', 'longitude': '146.95', 'name':'Albury' },
'HIT': { 'latitude':'38.328333', 'longitude': '67.627778', 'name':'Hivaro' },
'ABZ': { 'latitude':'57.2', 'longitude': '-2.2', 'name':'Dyce' },
'NZH': { 'latitude':'49.6', 'longitude': '117.433333', 'name':'Manzhouli' },
'NZO': { 'latitude':'0.133333', 'longitude': '34.083333', 'name':'Nzoia' },
'HGA': { 'latitude':'9.483333', 'longitude': '44.1', 'name':'Hargeisa' },
'BHI': { 'latitude':'-38.716667', 'longitude': '-62.183333', 'name':'Comandante' },
'BHH': { 'latitude':'19.983333', 'longitude': '42.65', 'name':'Bisha' },
'BHK': { 'latitude':'39.766667', 'longitude': '64.483333', 'name':'Bukhara' },
'BHJ': { 'latitude':'23.287778', 'longitude': '69.670278', 'name':'Rudra Mata' },
'BHM': { 'latitude':'33.566667', 'longitude': '-86.75', 'name':'Birmingham' },
'BHL': { 'latitude':'28.95', 'longitude': '-113.55', 'name':'Bahia Angeles' },
'BHO': { 'latitude':'23.283333', 'longitude': '77.333333', 'name':'Bhopal' },
'BHN': { 'latitude':'14.783333', 'longitude': '45.733333', 'name':'Beihan' },
'BHA': { 'latitude':'-0.583333', 'longitude': '-80.4', 'name':'Bahia De Caraquez' },
'BHC': { 'latitude':'35.15', 'longitude': '-114.566667', 'name':'Bhurban Heliport' },
'BHB': { 'latitude':'44.45', 'longitude': '-68.366667', 'name':'Bar Harbor' },
'BHE': { 'latitude':'-41.518333', 'longitude': '173.870278', 'name':'Woodbourne Air Station' },
'BHD': { 'latitude':'54.618056', 'longitude': '-5.8725', 'name':'George Best Belfast City' },
'BHG': { 'latitude':'15.833333', 'longitude': '-84.833333', 'name':'Brus Laguna' },
'BHF': { 'latitude':'6.55', 'longitude': '-77.333333', 'name':'Bahia Cupica' },
'BHY': { 'latitude':'21.483333', 'longitude': '109.083333', 'name':'Beihai' },
'BHX': { 'latitude':'52.45', 'longitude': '-1.75', 'name':'Birmingham International Airport' },
'BHQ': { 'latitude':'-32.0', 'longitude': '141.466667', 'name':'Broken Hill' },
'BHP': { 'latitude':'27.166667', 'longitude': '87.05', 'name':'Bhojpur' },
'BHS': { 'latitude':'-33.416667', 'longitude': '149.65', 'name':'Raglan' },
'BHR': { 'latitude':'27.683333', 'longitude': '84.416667', 'name':'Bharatpur Airport' },
'BHU': { 'latitude':'21.75', 'longitude': '72.183333', 'name':'Bhavnagar' },
'BHT': { 'latitude':'-23.5', 'longitude': '141.633333', 'name':'Brighton Downs' },
'BHW': { 'latitude':'32.083611', 'longitude': '72.671111', 'name':'Bhagatanwala Apt' },
'BHV': { 'latitude':'29.4', 'longitude': '71.683333', 'name':'Bahawalpur' },
'TJB': { 'latitude':'1.379722', 'longitude': '102.150556', 'name':'Tanjung Balai' },
'HIC': { 'latitude':'-2.266667', 'longitude': '-79.333333', 'name':'Iscor Heliport' },
'HIF': { 'latitude':'41.123889', 'longitude': '-111.973056', 'name':'Hill Afb' },
'LPY': { 'latitude':'45.083333', 'longitude': '3.766667', 'name':'Loudes' },
'LPX': { 'latitude':'56.516667', 'longitude': '21.1', 'name':'Liepaya' },
'LPW': { 'latitude':'56.383333', 'longitude': '-134.833333', 'name':'Little Port Walter' },
'LPU': { 'latitude':'0.583333', 'longitude': '115.6', 'name':'Long Apung' },
'LPT': { 'latitude':'18.3', 'longitude': '99.516667', 'name':'Lampang' },
'LPS': { 'latitude':'48.483333', 'longitude': '-122.936111', 'name':'Lopez Island' },
'EYL': { 'latitude':'15.133333', 'longitude': '-10.566667', 'name':'Yelimane' },
'LPQ': { 'latitude':'19.9', 'longitude': '102.15', 'name':'Luang Prabang' },
'LPP': { 'latitude':'61.044444', 'longitude': '28.144444', 'name':'Lappeenranta' },
'LPO': { 'latitude':'41.6', 'longitude': '-86.716667', 'name':'Municipal' },
'LPN': { 'latitude':'-6.583333', 'longitude': '146.45', 'name':'Leron Plains' },
'LPM': { 'latitude':'-16.466667', 'longitude': '167.816667', 'name':'Lamap' },
'EYR': { 'latitude':'38.983333', 'longitude': '-119.166667', 'name':'Yerington' },
'LPK': { 'latitude':'52.616667', 'longitude': '39.6', 'name':'Lipetsk' },
'LPJ': { 'latitude':'7.0', 'longitude': '-67.666667', 'name':'Pijiguaos' },
'LPI': { 'latitude':'58.4', 'longitude': '15.516667', 'name':'Linkoping' },
'LPH': { 'latitude':'56.05', 'longitude': '-5.433333', 'name':'Heliport' },
'LPG': { 'latitude':'-34.916667', 'longitude': '-57.95', 'name':'La Plata' },
'LPE': { 'latitude':'3.733333', 'longitude': '-76.216667', 'name':'La Primavera' },
'LPD': { 'latitude':'-1.3', 'longitude': '-69.716667', 'name':'La Pedrera' },
'LPC': { 'latitude':'34.666667', 'longitude': '-120.469444', 'name':'Lompoc Airport' },
'LPB': { 'latitude':'-16.513333', 'longitude': '-68.192222', 'name':'El Alto' },
'LPA': { 'latitude':'27.931944', 'longitude': '-15.386667', 'name':'Gran Canaria' },
'ZUC': { 'latitude':'49.5', 'longitude': '-91.833333', 'name':'Ignace' },
'NHX': { 'latitude':'30.416667', 'longitude': '-87.683333', 'name':'Barin Olf Osn' },
'ZUA': { 'latitude':'37.066667', 'longitude': '10.066667', 'name':'Utica NNY Rail' },
'NHZ': { 'latitude':'50.933333', 'longitude': '5.95', 'name':'NAS' },
'NZE': { 'latitude':'7.816667', 'longitude': '-8.7', 'name':'Nzerekore' },
'CSM': { 'latitude':'35.516667', 'longitude': '-98.983333', 'name':'Sherman' },
'CSO': { 'latitude':'51.85', 'longitude': '11.416667', 'name':'Cochstedt' },
'CSN': { 'latitude':'39.2', 'longitude': '-119.733333', 'name':'Carson City' },
'CSH': { 'latitude':'65.05', 'longitude': '35.666667', 'name':'Solovky' },
'CSK': { 'latitude':'12.4', 'longitude': '-16.75', 'name':'Cap Skirring' },
'CSJ': { 'latitude':'10.35', 'longitude': '107.066667', 'name':'Cape St Jacques' },
'CSD': { 'latitude':'-17.966667', 'longitude': '135.916667', 'name':'Cresswell Downs' },
'CSG': { 'latitude':'32.513815', 'longitude': '-84.941483', 'name':'Columbus Metropolitain' },
'CSF': { 'latitude':'49.266667', 'longitude': '2.483333', 'name':'Creil' },
'CSA': { 'latitude':'56.058889', 'longitude': '-6.243889', 'name':'Isle Of Colonsay' },
'CSC': { 'latitude':'10.416667', 'longitude': '-85.116667', 'name':'Canas' },
'CSB': { 'latitude':'45.5', 'longitude': '22.425', 'name':'Caransebes' },
'CSY': { 'latitude':'56.0903', 'longitude': '47.3473', 'name':'Cheboksary' },
'CSX': { 'latitude':'28.071111', 'longitude': '112.958333', 'name':'Changsha' },
'CSZ': { 'latitude':'-37.466667', 'longitude': '-61.916667', 'name':'Brigadier Hector Ruiz' },
'CSU': { 'latitude':'-29.716667', 'longitude': '-52.433333', 'name':'Santa Cruz Do Sul' },
'CST': { 'latitude':'-17.619444', 'longitude': '177.122222', 'name':'Castaway' },
'CSW': { 'latitude':'-22.816667', 'longitude': '-51.95', 'name':'Colorado do Oeste' },
'CSV': { 'latitude':'35.95', 'longitude': '-85.083333', 'name':'Memorial' },
'CSQ': { 'latitude':'41.066667', 'longitude': '-94.366667', 'name':'Municipal' },
'CSP': { 'latitude':'45.2', 'longitude': '-65.916667', 'name':'Coast Guard Heliport' },
'CSS': { 'latitude':'-19.15', 'longitude': '-51.75', 'name':'Cassilandia' },
'CSR': { 'latitude':'5.833333', 'longitude': '-68.133333', 'name':'Casuarito' },
'OIT': { 'latitude':'33.25', 'longitude': '131.633333', 'name':'Oita' },
'ZJN': { 'latitude':'57.466667', 'longitude': '-1.716667', 'name':'Swan River' },
'ZJK': { 'latitude':'22.3', 'longitude': '113.933333', 'name':'Off Line Point' },
'ZJJ': { 'latitude':'40.766667', 'longitude': '14.033333', 'name':'Harbour' },
'GBG': { 'latitude':'40.933333', 'longitude': '-90.433333', 'name':'Galesburg' },
'ZJG': { 'latitude':'54.6', 'longitude': '-97.666667', 'name':'Jenpeg' },
'ZJE': { 'latitude':'38.633333', 'longitude': '15.066667', 'name':'Harbour' },
'AES': { 'latitude':'62.560278', 'longitude': '6.1', 'name':'Vigra' },
'GBE': { 'latitude':'-24.555278', 'longitude': '25.918333', 'name':'Sir Seretse Khama International' },
'ZJY': { 'latitude':'40.9', 'longitude': '12.966667', 'name':'Harbour' },
'ZJX': { 'latitude':'38.783333', 'longitude': '15.216667', 'name':'Harbour' },
'AEU': { 'latitude':'36.583333', 'longitude': '52.5', 'name':'Abu Musa' },
'ZJT': { 'latitude':'1.583333', 'longitude': '110.483333', 'name':'Tanjung Pelepas Port' },
'ZJS': { 'latitude':'45.6', 'longitude': '22.066667', 'name':'Jena Railway' },
'ZJR': { 'latitude':'5.4', 'longitude': '100.233333', 'name':'Penang Port' },
'AET': { 'latitude':'66.55', 'longitude': '-152.65', 'name':'Allakaket' },
'GBN': { 'latitude':'41.7', 'longitude': '15.733333', 'name':'San Giovanni Rotondo' },
'AEX': { 'latitude':'31.3275', 'longitude': '-92.548611', 'name':'Alexandria International' },
'GBV': { 'latitude':'-16.333333', 'longitude': '126.366667', 'name':'Gibb River' },
'GBU': { 'latitude':'14.926389', 'longitude': '35.888889', 'name':'Khashm El Girba' },
'AED': { 'latitude':'-0.6', 'longitude': '10.083333', 'name':'Aleneva' },
'GBP': { 'latitude':'-16.55', 'longitude': '143.666667', 'name':'Gamboola' },
'VEY': { 'latitude':'63.416667', 'longitude': '-20.266667', 'name':'Vestmannaeyjar' },
'OKU': { 'latitude':'-18.808333', 'longitude': '17.05', 'name':'Mokuti Lodge' },
'VNG': { 'latitude':'18.933333', 'longitude': '102.5', 'name':'Viengxay' },
'VNE': { 'latitude':'47.65', 'longitude': '-2.766667', 'name':'Meucon' },
'OKT': { 'latitude':'54.433333', 'longitude': '53.383333', 'name':'Oktiabrskij' },
'VNC': { 'latitude':'27.071667', 'longitude': '-82.440278', 'name':'Venice Municipal' },
'VNA': { 'latitude':'15.716667', 'longitude': '106.4', 'name':'Saravane' },
'VNO': { 'latitude':'54.633333', 'longitude': '25.283333', 'name':'Vilnius' },
'TZX': { 'latitude':'40.916667', 'longitude': '39.833333', 'name':'Trabzon' },
'TZA': { 'latitude':'17.534722', 'longitude': '-88.302778', 'name':'Municipal' },
'VNS': { 'latitude':'25.45', 'longitude': '82.866667', 'name':'Varanasi' },
'VNR': { 'latitude':'-16.866667', 'longitude': '141.916667', 'name':'Vanrook' },
'TZM': { 'latitude':'21.15', 'longitude': '-88.15', 'name':'Tizimin' },
'TZL': { 'latitude':'44.458611', 'longitude': '18.724722', 'name':'Tuzla International' },
'VNY': { 'latitude':'34.209722', 'longitude': '-118.49', 'name':'Van Nuys' },
'TZN': { 'latitude':'24.233333', 'longitude': '-77.583333', 'name':'South Andros' },
'RGR': { 'latitude':'32.466667', 'longitude': '-98.683333', 'name':'Ranger Municipal' },
'RAG': { 'latitude':'-37.8', 'longitude': '174.883333', 'name':'Raglan' },
'RAD': { 'latitude':'18.45', 'longitude': '-64.6', 'name':'Road Town' },
'RAE': { 'latitude':'30.966667', 'longitude': '40.983333', 'name':'Arar' },
'RAB': { 'latitude':'-4.340556', 'longitude': '152.379722', 'name':'Tokua' },
'RAC': { 'latitude':'42.757778', 'longitude': '-87.820833', 'name':'Horlick' },
'RAA': { 'latitude':'-4.166667', 'longitude': '152.466667', 'name':'Rakanda' },
'RAN': { 'latitude':'44.366667', 'longitude': '12.216667', 'name':'La Spreta' },
'LBX': { 'latitude':'13.865556', 'longitude': '120.105', 'name':'Lubang' },
'UMU': { 'latitude':'-23.75', 'longitude': '-53.333333', 'name':'Ernesto Geisel' },
'UMT': { 'latitude':'69.366667', 'longitude': '-152.133333', 'name':'Umiat' },
'RAM': { 'latitude':'-12.0', 'longitude': '134.816667', 'name':'Ramingining' },
'UMR': { 'latitude':'-31.166667', 'longitude': '136.833333', 'name':'Woomera' },
'UMY': { 'latitude':'50.858333', 'longitude': '34.7625', 'name':'Sumy' },
'UME': { 'latitude':'63.791944', 'longitude': '20.282778', 'name':'Umea' },
'UMD': { 'latitude':'70.666667', 'longitude': '-52.0', 'name':'Uummannaq' },
'UMA': { 'latitude':'20.25', 'longitude': '-74.15', 'name':'Punta De Maisi' },
'RAH': { 'latitude':'29.65', 'longitude': '43.5', 'name':'Rafha' },
'UMC': { 'latitude':'-7.016667', 'longitude': '145.966667', 'name':'Umba' },
'UMB': { 'latitude':'53.366667', 'longitude': '-167.9', 'name':'North Shore' },
'UMM': { 'latitude':'63.333333', 'longitude': '-149.133333', 'name':'Summit' },
'UMI': { 'latitude':'-13.266667', 'longitude': '-70.633333', 'name':'Quincemil' },
'IKS': { 'latitude':'71.697778', 'longitude': '128.903056', 'name':'Tiksi' },
'LBA': { 'latitude':'53.865833', 'longitude': '-1.660556', 'name':'Leeds/bradford' },
'OLB': { 'latitude':'40.898611', 'longitude': '9.5175', 'name':'Costa Smeralda' },
'IKP': { 'latitude':'-16.25', 'longitude': '141.5', 'name':'Inkerman' },
'OLD': { 'latitude':'44.95', 'longitude': '-68.666667', 'name':'Old Town' },
'OLE': { 'latitude':'42.233333', 'longitude': '-78.366667', 'name':'Municipal' },
'OLF': { 'latitude':'48.083333', 'longitude': '-105.566667', 'name':'International' },
'IKT': { 'latitude':'52.5', 'longitude': '104.333333', 'name':'Irkutsk' },
'OLH': { 'latitude':'57.2', 'longitude': '-153.316667', 'name':'Old Harbor SPB' },
'OLI': { 'latitude':'64.911389', 'longitude': '-23.823056', 'name':'Rif' },
'OLJ': { 'latitude':'-14.883333', 'longitude': '166.55', 'name':'Olpoi' },
'OLK': { 'latitude':'-21.033333', 'longitude': '-57.9', 'name':'Fuerte Olimpo' },
'OLM': { 'latitude':'46.966667', 'longitude': '-122.9', 'name':'Olympia' },
'OLN': { 'latitude':'-45.583333', 'longitude': '-69.0', 'name':'Colonia Sarmiento' },
'OLO': { 'latitude':'49.416667', 'longitude': '17.341667', 'name':'Olomouc' },
'OLP': { 'latitude':'-31.0', 'longitude': '136.0', 'name':'Olympic Dam' },
'IKB': { 'latitude':'36.166667', 'longitude': '-81.15', 'name':'Wilkes County' },
'IKA': { 'latitude':'35.4097', 'longitude': '51.1508', 'name':'Imam Khomeini' },
'OLS': { 'latitude':'31.333333', 'longitude': '-110.933333', 'name':'International' },
'OLU': { 'latitude':'41.448056', 'longitude': '-97.342778', 'name':'Columbus Municipal' },
'OLV': { 'latitude':'34.966667', 'longitude': '-89.833333', 'name':'Olive Branch Arpt' },
'USN': { 'latitude':'32.583333', 'longitude': '129.35', 'name':'Ulsan' },
'IKK': { 'latitude':'41.066667', 'longitude': '-87.85', 'name':'Greater Kankakee' },
'OLY': { 'latitude':'38.716667', 'longitude': '-88.083333', 'name':'Olney-Noble' },
'IKI': { 'latitude':'33.75', 'longitude': '129.783333', 'name':'Iki' },
'IKO': { 'latitude':'52.95', 'longitude': '-168.866667', 'name':'Nikolski AFS' },
'FGI': { 'latitude':'-14.166667', 'longitude': '-171.666667', 'name':'Fagali I' },
'RAP': { 'latitude':'44.033333', 'longitude': '-103.05', 'name':'Regional' },
'USK': { 'latitude':'65.95', 'longitude': '57.4', 'name':'Usinsk' },
'RAQ': { 'latitude':'-4.85', 'longitude': '122.716667', 'name':'Sugimanuru' },
'LBI': { 'latitude':'43.933333', 'longitude': '2.15', 'name':'Le Sequestre' },
'FZO': { 'latitude':'51.519444', 'longitude': '-2.590833', 'name':'Filton' },
'XWP': { 'latitude':'56.216667', 'longitude': '13.733333', 'name':'Hassleholm' },
'XWQ': { 'latitude':'59.633333', 'longitude': '17.066667', 'name':'Enkoping' },
'RAZ': { 'latitude':'33.866667', 'longitude': '73.766667', 'name':'Rawala Kot' },
'XWL': { 'latitude':'57.716667', 'longitude': '11.966667', 'name':'Gothenburg Rail' },
'UST': { 'latitude':'29.95', 'longitude': '-81.333333', 'name':'St Augustine' },
'RAX': { 'latitude':'-9.672222', 'longitude': '148.033333', 'name':'Oram' },
'RAY': { 'latitude':'55.85', 'longitude': '-5.05', 'name':'Heliport' },
'MBL': { 'latitude':'44.266667', 'longitude': '-86.25', 'name':'Blacker' },
'MBM': { 'latitude':'-31.283333', 'longitude': '29.966667', 'name':'Mkambati' },
'MBN': { 'latitude':'-16.666667', 'longitude': '125.95', 'name':'Mt Barnett' },
'MBO': { 'latitude':'13.233333', 'longitude': '120.6', 'name':'Mamburao' },
'MBH': { 'latitude':'-25.516667', 'longitude': '152.716667', 'name':'Maryborough' },
'MBI': { 'latitude':'-8.916667', 'longitude': '33.466667', 'name':'Mbeya' },
'MBJ': { 'latitude':'18.5', 'longitude': '-77.916667', 'name':'Sangster International' },
'MBK': { 'latitude':'-10.241667', 'longitude': '-54.954167', 'name':'Matupa' },
'MBD': { 'latitude':'-25.798333', 'longitude': '25.548056', 'name':'Mafikeng International Airport' },
'MBE': { 'latitude':'44.266667', 'longitude': '143.383333', 'name':'Monbetsu' },
'MBF': { 'latitude':'-22.583333', 'longitude': '149.466667', 'name':'Mount Buffalo' },
'GAT': { 'latitude':'44.458333', 'longitude': '6.025', 'name':'Tallard' },
'SOM': { 'latitude':'8.945278', 'longitude': '-64.151111', 'name':'Edmundo Barrios' },
'MBA': { 'latitude':'-4.033333', 'longitude': '39.583333', 'name':'Moi International' },
'MBB': { 'latitude':'-21.25', 'longitude': '119.583333', 'name':'Marble Bar' },
'MBC': { 'latitude':'-1.9', 'longitude': '11.883333', 'name':'Mbigou' },
'GAO': { 'latitude':'20.084722', 'longitude': '-75.158611', 'name':'Los Canos' },
'GAN': { 'latitude':'-0.683333', 'longitude': '73.166667', 'name':'Gan Island' },
'GAM': { 'latitude':'63.766667', 'longitude': '-171.75', 'name':'Gambell' },
'GAL': { 'latitude':'64.716667', 'longitude': '-156.933333', 'name':'Galena' },
'MBX': { 'latitude':'46.479722', 'longitude': '15.686111', 'name':'Maribor International Airport' },
'MBY': { 'latitude':'39.466667', 'longitude': '-92.433333', 'name':'Moberly' },
'GAI': { 'latitude':'39.168333', 'longitude': '-77.166111', 'name':'Montgomery County' },
'GAH': { 'latitude':'-25.616667', 'longitude': '151.616667', 'name':'Gayndah' },
'MBT': { 'latitude':'12.366667', 'longitude': '123.066667', 'name':'Masbate' },
'GAF': { 'latitude':'34.416667', 'longitude': '8.816667', 'name':'Gafsa' },
'GAE': { 'latitude':'33.836111', 'longitude': '10.0', 'name':'Gabes' },
'MBW': { 'latitude':'-37.975833', 'longitude': '145.102222', 'name':'Moorabbin' },
'MBP': { 'latitude':'-5.975', 'longitude': '-77.016667', 'name':'Moyobamba' },
'GAB': { 'latitude':'38.866667', 'longitude': '-117.916667', 'name':'Gabbs' },
'GAA': { 'latitude':'9.15', 'longitude': '-74.233333', 'name':'Guamal' },
'MBS': { 'latitude':'43.533333', 'longitude': '-84.083333', 'name':'Midland' },
'JCT': { 'latitude':'30.483333', 'longitude': '-99.766667', 'name':'Kimble County' },
'JCU': { 'latitude':'35.899167', 'longitude': '-5.338333', 'name':'Ceuta' },
'JCR': { 'latitude':'-6.233611', 'longitude': '-57.768333', 'name':'Jacareacanga' },
'JCY': { 'latitude':'32.333333', 'longitude': '-97.333333', 'name':'Johnson' },
'JCE': { 'latitude':'-17.916667', 'longitude': '142.05', 'name':'Convention Center H/P' },
'JCA': { 'latitude':'43.552778', 'longitude': '7.016667', 'name':'Croisette Heliport' },
'JCB': { 'latitude':'-27.166667', 'longitude': '-51.516667', 'name':'Joacaba' },
'JCC': { 'latitude':'-38.7', 'longitude': '-60.016667', 'name':'China Basin Heliport' },
'JCM': { 'latitude':'-11.183333', 'longitude': '-40.516667', 'name':'Jacobina' },
'JCN': { 'latitude':'37.472222', 'longitude': '126.608333', 'name':'Heliport' },
'JCO': { 'latitude':'36.016667', 'longitude': '14.333333', 'name':'Heliport' },
'JCH': { 'latitude':'68.833333', 'longitude': '-51.0', 'name':'Qasigiannguit' },
'JCI': { 'latitude':'38.830833', 'longitude': '-94.890278', 'name':'New Century Aircenter Airport' },
'JCJ': { 'latitude':'35.173889', 'longitude': '128.383889', 'name':'Chuja Heliport' },
'JCK': { 'latitude':'-20.583333', 'longitude': '141.7', 'name':'Julia Creek' },
'ETS': { 'latitude':'31.316667', 'longitude': '-85.85', 'name':'Municipal' },
'KHY': { 'latitude':'38.4275', 'longitude': '44.973611', 'name':'Khoy' },
'KHZ': { 'latitude':'-15.766667', 'longitude': '-145.116667', 'name':'Kauehi' },
'KHR': { 'latitude':'46.783333', 'longitude': '102.85', 'name':'Kharkhorin' },
'KHS': { 'latitude':'25.999722', 'longitude': '56.25', 'name':'Khasab' },
'KHT': { 'latitude':'33.333333', 'longitude': '69.95', 'name':'Khost' },
'KHU': { 'latitude':'49.1', 'longitude': '33.45', 'name':'Kremenchug' },
'KHV': { 'latitude':'48.833333', 'longitude': '135.416667', 'name':'Novyy' },
'KHW': { 'latitude':'-19.133333', 'longitude': '23.833333', 'name':'Khwai River Lodge' },
'KHH': { 'latitude':'22.5725', 'longitude': '120.345278', 'name':'Kaohsiung' },
'KHI': { 'latitude':'24.906667', 'longitude': '67.160833', 'name':'Quaid-e-azam Intl' },
'KHJ': { 'latitude':'62.463056', 'longitude': '22.394722', 'name':'Kauhajoki' },
'KHK': { 'latitude':'29.3', 'longitude': '50.333333', 'name':'Khark Island' },
'KHL': { 'latitude':'22.8', 'longitude': '89.55', 'name':'Khulna' },
'KHM': { 'latitude':'23.0', 'longitude': '97.008333', 'name':'Khamti' },
'KHN': { 'latitude':'28.633333', 'longitude': '115.8', 'name':'Nanchang' },
'KHO': { 'latitude':'-24.583333', 'longitude': '31.416667', 'name':'Khoka Moya' },
'KHA': { 'latitude':'36.733333', 'longitude': '45.15', 'name':'Khaneh' },
'KHC': { 'latitude':'45.366667', 'longitude': '36.45', 'name':'Kerch' },
'KHD': { 'latitude':'33.438611', 'longitude': '48.280833', 'name':'Khorramabad' },
'KHE': { 'latitude':'46.633333', 'longitude': '32.933333', 'name':'Kherson' },
'KHG': { 'latitude':'39.666667', 'longitude': '76.016667', 'name':'Kashi' },
'NXX': { 'latitude':'-38.083333', 'longitude': '146.2', 'name':'Willow Grove NAS' },
'BVS': { 'latitude':'-1.666667', 'longitude': '-50.466667', 'name':'Breves' },
'KMW': { 'latitude':'57.75', 'longitude': '40.933333', 'name':'Kostroma' },
'BVP': { 'latitude':'-5.383333', 'longitude': '141.7', 'name':'Bolovip' },
'BVW': { 'latitude':'-12.45', 'longitude': '143.25', 'name':'Batavia Downs' },
'BVZ': { 'latitude':'-17.983333', 'longitude': '125.45', 'name':'Beverley Springs' },
'BVY': { 'latitude':'42.516667', 'longitude': '-70.833333', 'name':'Beverly Municiple Airport' },
'BVX': { 'latitude':'35.766667', 'longitude': '-91.65', 'name':'Municipal' },
'BVC': { 'latitude':'16.083333', 'longitude': '-22.833333', 'name':'Rabil' },
'BVB': { 'latitude':'2.833333', 'longitude': '-60.683333', 'name':'Boa Vista' },
'BVA': { 'latitude':'49.45', 'longitude': '2.116667', 'name':'Beauvais-Tille' },
'BVG': { 'latitude':'70.866667', 'longitude': '29.0', 'name':'Berlevag' },
'BVF': { 'latitude':'-16.8', 'longitude': '178.616667', 'name':'Dama' },
'BVE': { 'latitude':'45.15', 'longitude': '1.466667', 'name':'Laroche' },
'BVD': { 'latitude':'53.733333', 'longitude': '-166.316667', 'name':'Sea Port' },
'BVI': { 'latitude':'-25.8975', 'longitude': '139.3475', 'name':'Birdsville' },
'BVH': { 'latitude':'-12.633333', 'longitude': '-60.133333', 'name':'Vilhena' },
'BVO': { 'latitude':'36.766667', 'longitude': '-96.0', 'name':'Bartlesville' },
'BVM': { 'latitude':'-15.85', 'longitude': '-38.9', 'name':'Belmonte' },
'ETD': { 'latitude':'-28.716667', 'longitude': '138.633333', 'name':'Etadunna' },
'KMP': { 'latitude':'-26.533333', 'longitude': '18.1', 'name':'J.G.H. Van Der Wath' },
'OSY': { 'latitude':'64.466667', 'longitude': '11.6', 'name':'Namsos' },
'OSX': { 'latitude':'33.083333', 'longitude': '-89.55', 'name':'Attala County' },
'OSZ': { 'latitude':'54.25', 'longitude': '16.25', 'name':'Koszalin' },
'OSP': { 'latitude':'54.466667', 'longitude': '17.016667', 'name':'Redzikowo' },
'OSS': { 'latitude':'40.608889', 'longitude': '72.793333', 'name':'Osh International Airport' },
'OSR': { 'latitude':'49.696111', 'longitude': '18.110833', 'name':'Mosnov' },
'OSU': { 'latitude':'40.066667', 'longitude': '-83.066667', 'name':'Ohio State University' },
'OST': { 'latitude':'51.2', 'longitude': '2.866667', 'name':'Ostend/Bruges International Airport' },
'OSW': { 'latitude':'51.233333', 'longitude': '58.583333', 'name':'Orsk' },
'OSI': { 'latitude':'45.446111', 'longitude': '18.810278', 'name':'Osijek' },
'OSH': { 'latitude':'43.983333', 'longitude': '-88.55', 'name':'Wittman Field' },
'OSK': { 'latitude':'57.351944', 'longitude': '16.498333', 'name':'Oskarshamn' },
'OSM': { 'latitude':'36.305833', 'longitude': '43.1475', 'name':'Mosul' },
'OSL': { 'latitude':'60.193889', 'longitude': '11.100278', 'name':'Oslo Airport, Gardermoen' },
'OSO': { 'latitude':'35.560833', 'longitude': '45.314722', 'name':'Sulaimaniyah International' },
'OSN': { 'latitude':'37.090556', 'longitude': '127.029444', 'name':'Osan AB' },
'OSC': { 'latitude':'44.433333', 'longitude': '-83.333333', 'name':'Wurtsmith AFB' },
'OSB': { 'latitude':'38.15', 'longitude': '-92.616667', 'name':'Osage Beach' },
'OSE': { 'latitude':'-7.833333', 'longitude': '147.083333', 'name':'Omora' },
'OSD': { 'latitude':'63.183333', 'longitude': '14.5', 'name':'Åre Östersund Airport' },
'OSG': { 'latitude':'-2.916667', 'longitude': '141.3', 'name':'Ossima' },
'EWK': { 'latitude':'38.05', 'longitude': '-97.35', 'name':'City-County' },
'EWI': { 'latitude':'-3.933333', 'longitude': '136.366667', 'name':'Enarotali' },
'EWO': { 'latitude':'-0.883333', 'longitude': '14.8', 'name':'Ewo' },
'EWN': { 'latitude':'35.066667', 'longitude': '-77.05', 'name':'Simmons Nott' },
'EWB': { 'latitude':'41.683333', 'longitude': '-70.966667', 'name':'New Bedford' },
'EWE': { 'latitude':'-5.483333', 'longitude': '138.066667', 'name':'Ewer' },
'EWD': { 'latitude':'56.456389', 'longitude': '-159.762222', 'name':'Wildman Lake' },
'EWY': { 'latitude':'51.4', 'longitude': '-1.316667', 'name':'Greenham RAF' },
'EWR': { 'latitude':'40.6925', 'longitude': '-74.168611', 'name':'Newark Liberty International' },
'LRA': { 'latitude':'39.65', 'longitude': '22.45', 'name':'Larisa' },
'LRC': { 'latitude':'51.6', 'longitude': '6.183333', 'name':'R.A.F.' },
'LRB': { 'latitude':'-28.966667', 'longitude': '28.0', 'name':'Leribe' },
'LRE': { 'latitude':'-23.433333', 'longitude': '144.266667', 'name':'Longreach' },
'LRD': { 'latitude':'27.533333', 'longitude': '-99.466667', 'name':'International' },
'LRG': { 'latitude':'30.366667', 'longitude': '68.616667', 'name':'Lora Lai' },
'LRF': { 'latitude':'34.918056', 'longitude': '-92.146389', 'name':'Little Rock Afb' },
'LRI': { 'latitude':'9.033333', 'longitude': '-75.7', 'name':'Lorica' },
'LRH': { 'latitude':'46.5', 'longitude': '-1.5', 'name':'Laleu' },
'LRK': { 'latitude':'-16.116667', 'longitude': '-68.316667', 'name':'Coast Guard' },
'LRJ': { 'latitude':'42.783333', 'longitude': '-96.15', 'name':'Municipal' },
'LRM': { 'latitude':'18.450833', 'longitude': '-68.911944', 'name':'Casa de Campo International' },
'LRL': { 'latitude':'9.55', 'longitude': '1.2', 'name':'Niamtougou' },
'LRO': { 'latitude':'36.702778', 'longitude': '26.955', 'name':'Sharpe AAF' },
'LRQ': { 'latitude':'56.25', 'longitude': '-101.3', 'name':'Laurie River' },
'LRS': { 'latitude':'37.183333', 'longitude': '26.8', 'name':'Leros' },
'LRR': { 'latitude':'27.673056', 'longitude': '54.387222', 'name':'Lar' },
'LRU': { 'latitude':'32.3', 'longitude': '-106.933333', 'name':'Municipal' },
'LRT': { 'latitude':'47.766667', 'longitude': '-3.45', 'name':'Lann Bihoue' },
'LRV': { 'latitude':'11.833333', 'longitude': '-66.75', 'name':'Los Roques' },
'NOJ': { 'latitude':'63.183333', 'longitude': '75.27', 'name':'Nojabrxsk' },
'VRB': { 'latitude':'27.65', 'longitude': '-80.416667', 'name':'Municipal' },
'NOD': { 'latitude':'53.6', 'longitude': '7.2', 'name':'Norden' },
'CUW': { 'latitude':'58.35', 'longitude': '-133.766667', 'name':'Cube Cove' },
'CUV': { 'latitude':'8.766667', 'longitude': '-72.55', 'name':'Casigua' },
'CUU': { 'latitude':'28.683333', 'longitude': '-106.0', 'name':'Gen Fierro Villalobos' },
'CUT': { 'latitude':'-38.966667', 'longitude': '-69.25', 'name':'Cutral' },
'CUS': { 'latitude':'31.833333', 'longitude': '-107.633333', 'name':'Municipal' },
'CUR': { 'latitude':'12.2', 'longitude': '-68.966667', 'name':'Hato International Airport' },
'CUQ': { 'latitude':'-13.783333', 'longitude': '143.116667', 'name':'Coen' },
'CUP': { 'latitude':'10.666667', 'longitude': '-63.25', 'name':'Carupano' },
'CUZ': { 'latitude':'-13.533333', 'longitude': '-71.966667', 'name':'Velazco Astete' },
'CUY': { 'latitude':'-27.45', 'longitude': '117.916667', 'name':'Cue' },
'CUG': { 'latitude':'-33.3', 'longitude': '148.702778', 'name':'Cudal' },
'CUF': { 'latitude':'44.535278', 'longitude': '7.6175', 'name':'Levaldigi' },
'CUE': { 'latitude':'-2.9', 'longitude': '-78.966667', 'name':'Cuenca' },
'CUD': { 'latitude':'-26.8', 'longitude': '153.15', 'name':'Caloundra' },
'CUC': { 'latitude':'7.916667', 'longitude': '-72.533333', 'name':'Camilo Dazo' },
'CUB': { 'latitude':'-10.75', 'longitude': '-67.866667', 'name':'Owens Field' },
'CUA': { 'latitude':'25.05', 'longitude': '-111.65', 'name':'Ciudad Constitucion' },
'CUO': { 'latitude':'1.033333', 'longitude': '-71.233333', 'name':'Caruru' },
'CUN': { 'latitude':'21.036667', 'longitude': '-86.876944', 'name':'Cancún International' },
'CUM': { 'latitude':'10.45', 'longitude': '-64.183333', 'name':'Cumana' },
'NOE': { 'latitude':'53.616667', 'longitude': '7.15', 'name':'Norddeich' },
'CUK': { 'latitude':'17.75', 'longitude': '-88.05', 'name':'Caye Caulker' },
'CUJ': { 'latitude':'11.883333', 'longitude': '120.016667', 'name':'Culion' },
'CUI': { 'latitude':'4.666667', 'longitude': '-72.0', 'name':'Currillo' },
'CUH': { 'latitude':'35.983333', 'longitude': '-96.766667', 'name':'Municipal' },
'TVF': { 'latitude':'48.066111', 'longitude': '-96.185', 'name':'Thief River Falls' },
'VRO': { 'latitude':'23.036111', 'longitude': '-81.573889', 'name':'Kawama' },
'ZHP': { 'latitude':'55.433333', 'longitude': '-116.483333', 'name':'High Prairie' },
'ZHZ': { 'latitude':'62.216667', 'longitude': '5.566667', 'name':'Halle Railway' },
'ZHA': { 'latitude':'21.266667', 'longitude': '110.466667', 'name':'Zhanjiang' },
'ZHC': { 'latitude':'29.483333', 'longitude': '31.066667', 'name':'N Philadelphia Rail St' },
'ZHM': { 'latitude':'24.398611', 'longitude': '91.921111', 'name':'Shamshernagar' },
'OCW': { 'latitude':'35.55', 'longitude': '-77.05', 'name':'Warren Field' },
'PKR': { 'latitude':'28.233333', 'longitude': '83.866667', 'name':'Pokhara' },
'PKS': { 'latitude':'18.366667', 'longitude': '103.65', 'name':'Paksane' },
'PKP': { 'latitude':'-15.0', 'longitude': '-139.0', 'name':'Puka Puka' },
'PKV': { 'latitude':'57.783889', 'longitude': '28.395556', 'name':'Pskov' },
'PKW': { 'latitude':'-22.883333', 'longitude': '26.916667', 'name':'Selebi-Phikwe' },
'PKT': { 'latitude':'-14.25', 'longitude': '129.533333', 'name':'Port Keats' },
'PKZ': { 'latitude':'15.133333', 'longitude': '105.783333', 'name':'Pakse' },
'PKY': { 'latitude':'-2.216667', 'longitude': '113.933333', 'name':'Palangkaraya' },
'XBW': { 'latitude':'42.65', 'longitude': '-80.816667', 'name':'Killineq' },
'XBR': { 'latitude':'44.583333', 'longitude': '-75.683333', 'name':'Brockville' },
'XBL': { 'latitude':'8.45', 'longitude': '36.333333', 'name':'Buno Bedelle' },
'XBO': { 'latitude':'12.65', 'longitude': '-0.566667', 'name':'Boulsa' },
'SIP': { 'latitude':'45.052222', 'longitude': '33.975278', 'name':'Simferopol' },
'XBJ': { 'latitude':'32.883333', 'longitude': '59.216667', 'name':'Birjand' },
'XBE': { 'latitude':'53.966667', 'longitude': '-91.05', 'name':'Bearskin Lake' },
'XBG': { 'latitude':'12.983333', 'longitude': '-0.133333', 'name':'Bogande' },
'XBB': { 'latitude':'49.8', 'longitude': '-124.633333', 'name':'Blubber Bay' },
'PKB': { 'latitude':'39.35', 'longitude': '-81.433333', 'name':'Wood County' },
'PKC': { 'latitude':'53.016667', 'longitude': '158.65', 'name':'Petropavlovsk-Kamchats' },
'PKA': { 'latitude':'60.7', 'longitude': '-161.7', 'name':'SPB' },
'PKF': { 'latitude':'45.933333', 'longitude': '-90.433333', 'name':'Park Falls' },
'PKD': { 'latitude':'46.9', 'longitude': '-95.066667', 'name':'Park Rapids' },
'PKE': { 'latitude':'-33.133333', 'longitude': '148.233333', 'name':'Parkes' },
'PKO': { 'latitude':'9.35', 'longitude': '2.616667', 'name':'Parakou' },
'PKL': { 'latitude':'-36.35', 'longitude': '174.15', 'name':'Pakatoa Island' },
'PKM': { 'latitude':'8.333333', 'longitude': '-59.633333', 'name':'Port Kaituma' },
'VLI': { 'latitude':'-17.666667', 'longitude': '168.236944', 'name':'Bauerfield' },
'VLK': { 'latitude':'47.683333', 'longitude': '42.083333', 'name':'Volgodonsk' },
'VLM': { 'latitude':'-21.25', 'longitude': '-63.5', 'name':'Villamontes' },
'VLL': { 'latitude':'41.65', 'longitude': '-4.716667', 'name':'Valladolid' },
'VLO': { 'latitude':'38.116667', 'longitude': '-122.233333', 'name':'Stolport' },
'VLN': { 'latitude':'10.15', 'longitude': '-68.033333', 'name':'Valencia' },
'TTS': { 'latitude':'42.588889', 'longitude': '46.095833', 'name':'Tsaratanana' },
'TTR': { 'latitude':'-7.083333', 'longitude': '120.7', 'name':'Tana Toraja' },
'TTQ': { 'latitude':'10.566667', 'longitude': '-83.516667', 'name':'Tortuquero' },
'VLE': { 'latitude':'35.65', 'longitude': '-112.2', 'name':'J t Robidoux' },
'VLD': { 'latitude':'30.783333', 'longitude': '-83.283333', 'name':'Regional' },
'TTU': { 'latitude':'35.594444', 'longitude': '-5.32', 'name':'Sania Ramel' },
'TTT': { 'latitude':'22.75', 'longitude': '121.1', 'name':'Taitung' },
'VLY': { 'latitude':'53.25', 'longitude': '-4.54', 'name':'Anglesey' },
'TTJ': { 'latitude':'35.5', 'longitude': '134.25', 'name':'Tottori' },
'TTI': { 'latitude':'-17.516667', 'longitude': '-1.433333', 'name':'Tetiaroa Is' },
'TTH': { 'latitude':'17.666111', 'longitude': '54.024722', 'name':'Thumrait' },
'TTO': { 'latitude':'45.8', 'longitude': '-97.75', 'name':'Municipal' },
'TTN': { 'latitude':'40.276667', 'longitude': '-74.813333', 'name':'Trenton Mercer Airport' },
'TTM': { 'latitude':'4.366667', 'longitude': '-74.183333', 'name':'Tablon De Tamara' },
'TTL': { 'latitude':'-17.8', 'longitude': '177.316667', 'name':'Turtle Island' },
'TTC': { 'latitude':'-25.4', 'longitude': '-70.483333', 'name':'Taltal' },
'TTB': { 'latitude':'39.925556', 'longitude': '9.657222', 'name':'Arbatax' },
'TTA': { 'latitude':'28.45', 'longitude': '-11.083333', 'name':'Tan Tan' },
'VLR': { 'latitude':'-28.6', 'longitude': '-70.766667', 'name':'Vallenar' },
'TTG': { 'latitude':'-26.216667', 'longitude': '-64.15', 'name':'Tartagal' },
'TTE': { 'latitude':'0.8', 'longitude': '127.4', 'name':'Ternate' },
'TTD': { 'latitude':'54.083333', 'longitude': '-1.166667', 'name':'Troutdale' },
'WOD': { 'latitude':'59.066667', 'longitude': '-157.433333', 'name':'Wood River' },
'WKN': { 'latitude':'-5.866667', 'longitude': '155.233333', 'name':'Wakunai' },
'TAK': { 'latitude':'34.214167', 'longitude': '134.015556', 'name':'Takamatsu' },
'UKY': { 'latitude':'35.0', 'longitude': '135.75', 'name':'Kansai' },
'UKX': { 'latitude':'56.85', 'longitude': '105.733333', 'name':'Ust-Kut' },
'UKU': { 'latitude':'-3.683333', 'longitude': '142.466667', 'name':'Nuku' },
'UKT': { 'latitude':'40.433333', 'longitude': '-75.333333', 'name':'Upper Bucks' },
'UKS': { 'latitude':'44.691667', 'longitude': '33.576667', 'name':'Sevastopol' },
'UKR': { 'latitude':'13.933333', 'longitude': '45.683333', 'name':'Mukeiras' },
'UKN': { 'latitude':'43.266667', 'longitude': '-91.483333', 'name':'Municipal' },
'UKK': { 'latitude':'50.033333', 'longitude': '82.5', 'name':'Ust-kamenogorsk' },
'UKI': { 'latitude':'39.126667', 'longitude': '-123.2', 'name':'Ukiah' },
'DJU': { 'latitude':'64.666667', 'longitude': '-14.166667', 'name':'Djupivogur' },
'UKB': { 'latitude':'34.632778', 'longitude': '135.223889', 'name':'Kobe' },
'UKA': { 'latitude':'-4.296389', 'longitude': '39.571111', 'name':'Ukunda' },
'ONJ': { 'latitude':'40.3', 'longitude': '140.55', 'name':'Odate Noshiro' },
'ONH': { 'latitude':'42.45', 'longitude': '-75.116667', 'name':'Municipal' },
'ONI': { 'latitude':'-3.983333', 'longitude': '136.083333', 'name':'Moanamani' },
'ONN': { 'latitude':'58.233333', 'longitude': '-152.833333', 'name':'Onion Bay' },
'ONO': { 'latitude':'44.020556', 'longitude': '-117.013611', 'name':'Ontario Municipal Airport' },
'IIS': { 'latitude':'-4.333333', 'longitude': '154.341667', 'name':'Nissan Island' },
'ONM': { 'latitude':'34.05', 'longitude': '-106.883333', 'name':'Socorro' },
'ONB': { 'latitude':'-8.583333', 'longitude': '147.2', 'name':'Ononge' },
'ONA': { 'latitude':'50.3', 'longitude': '-1.333333', 'name':'Municipal' },
'ONG': { 'latitude':'-16.583333', 'longitude': '139.3', 'name':'Mornington' },
'OND': { 'latitude':'-17.878333', 'longitude': '15.9525', 'name':'Ondangwa' },
'ONE': { 'latitude':'-9.166667', 'longitude': '161.066667', 'name':'Onepusu' },
'ONX': { 'latitude':'9.356667', 'longitude': '-79.8675', 'name':'Enrique Adolfo Jimenez' },
'ONY': { 'latitude':'33.366667', 'longitude': '-98.75', 'name':'Olney' },
'IIA': { 'latitude':'53.091944', 'longitude': '-9.57', 'name':'Inishmaan' },
'ONR': { 'latitude':'-24.816667', 'longitude': '140.533333', 'name':'Monkira' },
'IIL': { 'latitude':'33.586667', 'longitude': '46.404722', 'name':'Ilaam' },
'ONP': { 'latitude':'44.583333', 'longitude': '-124.05', 'name':'Newport' },
'IIN': { 'latitude':'30.833333', 'longitude': '131.008333', 'name':'Nishinoomote' },
'ONT': { 'latitude':'34.056111', 'longitude': '-117.601111', 'name':'Ontario International' },
'ONU': { 'latitude':'-20.65', 'longitude': '-178.7', 'name':'Ono I Lau' },
'RZE': { 'latitude':'50.043333', 'longitude': '22.016667', 'name':'Jasionka' },
'FXY': { 'latitude':'43.266667', 'longitude': '-93.65', 'name':'Municipal' },
'RZA': { 'latitude':'-50.033333', 'longitude': '-68.583333', 'name':'Santa Cruz' },
'RZN': { 'latitude':'54.641389', 'longitude': '39.569444', 'name':'Ryazan' },
'RZH': { 'latitude':'34.666667', 'longitude': '-118.0', 'name':'Quartz Hill' },
'FXM': { 'latitude':'70.216667', 'longitude': '-146.0', 'name':'Flaxman Island' },
'FXO': { 'latitude':'-14.816667', 'longitude': '36.533333', 'name':'Cuamba' },
'RZS': { 'latitude':'26.966667', 'longitude': '68.866667', 'name':'Sawan' },
'RZR': { 'latitude':'36.666667', 'longitude': '50.75', 'name':'Ramsar' },
'RZP': { 'latitude':'10.816667', 'longitude': '119.516667', 'name':'CLR Airport' },
'FXE': { 'latitude':'26.183333', 'longitude': '-80.166667', 'name':'Executive' },
'RZZ': { 'latitude':'36.466667', 'longitude': '-77.666667', 'name':'Halifax County' },
'DJB': { 'latitude':'-1.638056', 'longitude': '103.644444', 'name':'Sultan Taha Syarifudn' },
'JIR': { 'latitude':'27.633333', 'longitude': '86.233333', 'name':'Jiri' },
'DJG': { 'latitude':'24.45', 'longitude': '9.5', 'name':'Inedbirenne' },
'SAK': { 'latitude':'65.75', 'longitude': '-19.65', 'name':'Saudarkrokur' },
'SAJ': { 'latitude':'25.166667', 'longitude': '91.425', 'name':'Sirajganj' },
'SAH': { 'latitude':'15.476389', 'longitude': '44.219722', 'name':'El Rahaba Airport' },
'SAN': { 'latitude':'32.733333', 'longitude': '-117.183333', 'name':'San Diego International Airport' },
'SAM': { 'latitude':'-10.333333', 'longitude': '150.783333', 'name':'Salamo' },
'SAL': { 'latitude':'13.440833', 'longitude': '-89.055833', 'name':'El Salvador International' },
'SAC': { 'latitude':'38.516667', 'longitude': '-121.483333', 'name':'Executive' },
'SAB': { 'latitude':'17.583333', 'longitude': '-63.333333', 'name':'J. Yrausquin' },
'SAA': { 'latitude':'41.45', 'longitude': '-106.8', 'name':'Shively Field' },
'SAG': { 'latitude':'69.366667', 'longitude': '-148.7', 'name':'Sagwon' },
'SAF': { 'latitude':'35.616667', 'longitude': '-106.083333', 'name':'Santa Fe' },
'SAE': { 'latitude':'2.316667', 'longitude': '125.416667', 'name':'Sangir' },
'SAD': { 'latitude':'32.85', 'longitude': '-109.633333', 'name':'Safford' },
'SAZ': { 'latitude':'4.666667', 'longitude': '-8.433333', 'name':'Sasstown' },
'SAY': { 'latitude':'43.256389', 'longitude': '11.255', 'name':'Siena' },
'SAX': { 'latitude':'8.1', 'longitude': '-78.316667', 'name':'Sambu' },
'SAS': { 'latitude':'33.316667', 'longitude': '-115.983333', 'name':'Salton City' },
'SAR': { 'latitude':'38.116667', 'longitude': '-89.7', 'name':'Sparta Community' },
'SAQ': { 'latitude':'25.05', 'longitude': '-78.033333', 'name':'San Andros' },
'SAP': { 'latitude':'15.452778', 'longitude': '-87.923611', 'name':'Ramon Villeda Morales International' },
'SAW': { 'latitude':'40.898611', 'longitude': '29.309167', 'name':'Sabiha Gokcen' },
'SAV': { 'latitude':'32.133333', 'longitude': '-81.2', 'name':'Savannah/Hilton Head' },
'SAU': { 'latitude':'-10.5', 'longitude': '121.9', 'name':'Sawu' },
'SAT': { 'latitude':'29.533333', 'longitude': '-98.466667', 'name':'San Antonio International' },
'CHA': { 'latitude':'35.035278', 'longitude': '-85.203889', 'name':'Lovell Field' },
'CHB': { 'latitude':'35.416667', 'longitude': '74.083333', 'name':'Chilas' },
'CHC': { 'latitude':'-43.488889', 'longitude': '172.533333', 'name':'Christchurch International' },
'CHD': { 'latitude':'33.307778', 'longitude': '-111.655556', 'name':'Williams Gateway Airport' },
'CHE': { 'latitude':'51.95', 'longitude': '-10.216667', 'name':'Reenroe' },
'CHF': { 'latitude':'35.133333', 'longitude': '128.7', 'name':'Jinhae' },
'CHG': { 'latitude':'42.0', 'longitude': '121.0', 'name':'Chaoyang' },
'CHH': { 'latitude':'-6.05', 'longitude': '-78.033333', 'name':'Chachapoyas' },
'CHJ': { 'latitude':'-20.2', 'longitude': '32.633333', 'name':'Chipinge' },
'CHK': { 'latitude':'35.033333', 'longitude': '-97.966667', 'name':'Municipal' },
'CHL': { 'latitude':'44.5', 'longitude': '-114.233333', 'name':'Challis' },
'CHM': { 'latitude':'-9.083333', 'longitude': '-78.6', 'name':'Chimbote' },
'CHN': { 'latitude':'35.933333', 'longitude': '127.716667', 'name':'Jeonju' },
'CHO': { 'latitude':'38.133333', 'longitude': '-78.45', 'name':'Albemarle' },
'CHP': { 'latitude':'65.466667', 'longitude': '-144.583333', 'name':'Circle Hot Springs' },
'CHQ': { 'latitude':'35.531667', 'longitude': '24.149722', 'name':'Souda' },
'CHR': { 'latitude':'46.816667', 'longitude': '1.7', 'name':'Chateauroux' },
'CHS': { 'latitude':'32.898611', 'longitude': '-80.040556', 'name':'Charleston, AFB Municipal' },
'CHT': { 'latitude':'-43.916667', 'longitude': '176.5', 'name':'Karewa' },
'CHU': { 'latitude':'61.666667', 'longitude': '-159.25', 'name':'Chuathbaluk' },
'CHV': { 'latitude':'41.733333', 'longitude': '-7.466667', 'name':'Chaves' },
'CHW': { 'latitude':'39.766667', 'longitude': '98.483333', 'name':'Jiuhuang' },
'CHX': { 'latitude':'9.45', 'longitude': '-82.466667', 'name':'Changuinola' },
'CHY': { 'latitude':'-6.7', 'longitude': '156.45', 'name':'Choiseul Bay' },
'CHZ': { 'latitude':'42.583333', 'longitude': '-121.866667', 'name':'State' },
'JAE': { 'latitude':'9.716667', 'longitude': '-82.983333', 'name':'Technology Park' },
'JAB': { 'latitude':'-10.216667', 'longitude': '132.566667', 'name':'Jabiru' },
'JAC': { 'latitude':'43.6', 'longitude': '-110.733333', 'name':'Jackson Hole' },
'JAA': { 'latitude':'34.4', 'longitude': '70.5', 'name':'Jalalabad' },
'VUS': { 'latitude':'60.766667', 'longitude': '46.316667', 'name':'Velikij Ustyug' },
'DBM': { 'latitude':'10.283333', 'longitude': '37.766667', 'name':'Debra Marcos' },
'DBO': { 'latitude':'-32.217222', 'longitude': '148.574722', 'name':'Dubbo' },
'DBN': { 'latitude':'32.55', 'longitude': '-82.983333', 'name':'Municipal' },
'DBA': { 'latitude':'28.875278', 'longitude': '64.403889', 'name':'Dalbandin' },
'DBB': { 'latitude':'30.15', 'longitude': '28.083333', 'name':'Alalamain Intl.' },
'DBD': { 'latitude':'23.8', 'longitude': '86.45', 'name':'Dhanbad' },
'DBY': { 'latitude':'-27.155278', 'longitude': '151.267222', 'name':'Dalby' },
'DBQ': { 'latitude':'42.4', 'longitude': '-90.716667', 'name':'Municipal' },
'DBP': { 'latitude':'-6.283333', 'longitude': '141.9', 'name':'Debepare' },
'DBS': { 'latitude':'44.166667', 'longitude': '-112.233333', 'name':'Dubois' },
'DBU': { 'latitude':'-21.522778', 'longitude': '32.896111', 'name':'Dambulu Oya Tank' },
'DBT': { 'latitude':'11.966667', 'longitude': '38.0', 'name':'Debra Tabor' },
'DBV': { 'latitude':'42.561389', 'longitude': '18.268333', 'name':'Dubrovnik' },
'QOW': { 'latitude':'5.39', 'longitude': '7.21', 'name':'Owerri' },
'QOF': { 'latitude':'50.433333', 'longitude': '30.516667', 'name':'Darnitsa Bus Station' },
'QOH': { 'latitude':'50.433333', 'longitude': '30.516667', 'name':'Hotel Rus Bus Station' },
'AFL': { 'latitude':'-9.866111', 'longitude': '-56.106111', 'name':'Alta Floresta' },
'AFN': { 'latitude':'42.8', 'longitude': '-72.0', 'name':'Municipal' },
'AFO': { 'latitude':'42.716667', 'longitude': '-110.933333', 'name':'Municipal' },
'AFI': { 'latitude':'6.916667', 'longitude': '-75.066667', 'name':'Amalfi' },
'AFK': { 'latitude':'7.283333', 'longitude': '81.666667', 'name':'Kondavattavan Tank' },
'AFD': { 'latitude':'-33.583333', 'longitude': '26.883333', 'name':'Port Alfred' },
'AFF': { 'latitude':'38.969722', 'longitude': '-104.813056', 'name':'USAF Academy Airstrip' },
'GCJ': { 'latitude':'-25.986389', 'longitude': '28.14', 'name':'Grand Central' },
'GCM': { 'latitude':'19.292778', 'longitude': '-81.357778', 'name':'Owen Roberts International' },
'AFA': { 'latitude':'-34.583333', 'longitude': '-68.4', 'name':'San Rafael' },
'GCN': { 'latitude':'35.95', 'longitude': '-112.15', 'name':'National Park' },
'AFY': { 'latitude':'38.733333', 'longitude': '30.6', 'name':'Afyon' },
'AFZ': { 'latitude':'36.168056', 'longitude': '57.595278', 'name':'Sabzevar' },
'GCV': { 'latitude':'-29.95', 'longitude': '-50.983333', 'name':'Gravatai' },
'AFT': { 'latitude':'-9.183333', 'longitude': '160.95', 'name':'Afutara Aerodrome' },
'AFW': { 'latitude':'32.987778', 'longitude': '-97.318889', 'name':'Fort Worth Alliance' },
'AFR': { 'latitude':'-9.133333', 'longitude': '148.383333', 'name':'Afore' },
'AFS': { 'latitude':'41.613333', 'longitude': '64.232778', 'name':'Zarafshan' },
'BTU': { 'latitude':'3.2', 'longitude': '113.033333', 'name':'Bintulu' },
'BTT': { 'latitude':'66.916667', 'longitude': '-151.516667', 'name':'Bettles' },
'BTW': { 'latitude':'-3.45', 'longitude': '116.0', 'name':'Batu Licin' },
'BTV': { 'latitude':'44.471944', 'longitude': '-73.153333', 'name':'Burlington International' },
'BTQ': { 'latitude':'-2.6', 'longitude': '29.733333', 'name':'Butare' },
'BTP': { 'latitude':'40.793611', 'longitude': '-79.949722', 'name':'Butler County - Kenny Scholter Field' },
'BTS': { 'latitude':'48.166667', 'longitude': '17.216667', 'name':'M. R. Štefánika' },
'BTR': { 'latitude':'30.533333', 'longitude': '-91.15', 'name':'Ryan' },
'BTY': { 'latitude':'52.9', 'longitude': '-1.783333', 'name':'Beatty' },
'BTX': { 'latitude':'-25.633333', 'longitude': '140.8', 'name':'Betoota' },
'BTZ': { 'latitude':'40.2325', 'longitude': '29.009444', 'name':'Bursa Airport' },
'BTE': { 'latitude':'7.516667', 'longitude': '-12.5', 'name':'Bonthe' },
'BTD': { 'latitude':'-18.633333', 'longitude': '135.933333', 'name':'Brunette Downs' },
'BTG': { 'latitude':'7.3', 'longitude': '18.3', 'name':'Batangafo' },
'BTF': { 'latitude':'40.883333', 'longitude': '-111.883333', 'name':'Salt Lake Skypark' },
'BTA': { 'latitude':'4.583333', 'longitude': '13.683333', 'name':'Yaoundé' },
'BTC': { 'latitude':'7.7', 'longitude': '81.666667', 'name':'Batticaloa' },
'BTB': { 'latitude':'3.05', 'longitude': '18.516667', 'name':'Betou' },
'BTM': { 'latitude':'45.954722', 'longitude': '-112.4975', 'name':'Bert Mooney Airport' },
'BTL': { 'latitude':'42.3', 'longitude': '-85.25', 'name':'WK Kellogg Regional' },
'BTO': { 'latitude':'4.233333', 'longitude': '-55.45', 'name':'Botopasie' },
'BTN': { 'latitude':'34.616667', 'longitude': '-79.683333', 'name':'Bennettsville' },
'BTI': { 'latitude':'70.133333', 'longitude': '-143.633333', 'name':'Barter Island' },
'BTH': { 'latitude':'1.066667', 'longitude': '104.133333', 'name':'Hang Nadim' },
'BTK': { 'latitude':'56.166667', 'longitude': '102.066667', 'name':'Bratsk' },
'BTJ': { 'latitude':'5.416667', 'longitude': '95.341667', 'name':'Sultan Lskandarmuda Airport' },
'NUU': { 'latitude':'-0.3', 'longitude': '36.15', 'name':'Nakuru' },
'NUL': { 'latitude':'64.733333', 'longitude': '-158.1', 'name':'Nulato' },
'NUJ': { 'latitude':'38.483333', 'longitude': '45.966667', 'name':'Nojeh' },
'NUK': { 'latitude':'-19.086111', 'longitude': '-139.0', 'name':'Nukutavake' },
'EUM': { 'latitude':'54.166667', 'longitude': '9.983333', 'name':'Neumuenster' },
'EUO': { 'latitude':'4.383333', 'longitude': '-73.2', 'name':'Paratebueno' },
'KJA': { 'latitude':'56.173056', 'longitude': '92.493333', 'name':'Krasnojarsk' },
'NUH': { 'latitude':'5.65', 'longitude': '-72.2', 'name':'Nunchia' },
'NIK': { 'latitude':'13.075', 'longitude': '-12.716667', 'name':'Niokolo Koba' },
'EUE': { 'latitude':'39.516667', 'longitude': '-115.966667', 'name':'Eureka' },
'KJK': { 'latitude':'50.833333', 'longitude': '3.25', 'name':'Kortrijk' },
'EUG': { 'latitude':'44.116667', 'longitude': '-123.216667', 'name':'Eugene' },
'EUF': { 'latitude':'31.95', 'longitude': '-85.133333', 'name':'Weedon Field' },
'EUA': { 'latitude':'-21.366667', 'longitude': '-174.933333', 'name':'Kaufana' },
'EUC': { 'latitude':'-31.716667', 'longitude': '128.866667', 'name':'Eucla' },
'NUF': { 'latitude':'50.033333', 'longitude': '-1.833333', 'name':'Castlereigh Reservoir' },
'EUX': { 'latitude':'17.5', 'longitude': '-62.966667', 'name':'F D Roosevelt' },
'KJU': { 'latitude':'-2.883333', 'longitude': '151.25', 'name':'Kamiraba' },
'EUQ': { 'latitude':'11.166667', 'longitude': '122.083333', 'name':'Evelio Javier' },
'NUD': { 'latitude':'12.7', 'longitude': '28.416667', 'name':'En Nahud' },
'NUE': { 'latitude':'49.498611', 'longitude': '11.066944', 'name':'Nürnberg' },
'NUB': { 'latitude':'-14.266667', 'longitude': '135.716667', 'name':'Numbulwar' },
'CWP': { 'latitude':'33.766667', 'longitude': '72.366667', 'name':'Campbellpore' },
'CWR': { 'latitude':'-27.716667', 'longitude': '138.333333', 'name':'Cowarie' },
'CWT': { 'latitude':'-33.85', 'longitude': '148.65', 'name':'Cowra' },
'CWW': { 'latitude':'-35.983333', 'longitude': '146.35', 'name':'Corowa' },
'CWI': { 'latitude':'41.833333', 'longitude': '-90.35', 'name':'Clinton' },
'CWL': { 'latitude':'51.4', 'longitude': '-3.35', 'name':'Cardiff' },
'CWO': { 'latitude':'-5.133333', 'longitude': '137.533333', 'name':'Ft Wolter AAF' },
'CWA': { 'latitude':'44.769444', 'longitude': '-89.683056', 'name':'Central Wisconsin' },
'CWC': { 'latitude':'48.266667', 'longitude': '25.966667', 'name':'Chernovtsy' },
'CWB': { 'latitude':'-25.528611', 'longitude': '-49.175833', 'name':'Afonso Pena International Airport' },
'CWG': { 'latitude':'32.833333', 'longitude': '-84.883333', 'name':'Callaway Gardens' },
'VAK': { 'latitude':'61.528611', 'longitude': '-165.590278', 'name':'Chevak' },
'ZFZ': { 'latitude':'50.8', 'longitude': '-1.683333', 'name':'Buffalo Depew Rr' },
'ZFR': { 'latitude':'48.35', 'longitude': '13.116667', 'name':'Frankfurt/Oder Railway' },
'ZFQ': { 'latitude':'48.683333', 'longitude': '1.1', 'name':'Gare de Bordeaux' },
'ZFW': { 'latitude':'56.066667', 'longitude': '-118.383333', 'name':'Fairview' },
'ZFU': { 'latitude':'-23.4', 'longitude': '-46.333333', 'name':'Aruja' },
'ZFJ': { 'latitude':'48.15', 'longitude': '4.85', 'name':'Rennes' },
'ZFN': { 'latitude':'64.9', 'longitude': '-125.583333', 'name':'Tulita' },
'ZFM': { 'latitude':'67.433333', 'longitude': '-134.883333', 'name':'Fort Mcpherson' },
'ZFL': { 'latitude':'52.833333', 'longitude': '-93.666667', 'name':'South Trout Lake' },
'ZFC': { 'latitude':'51.0', 'longitude': '-3.183333', 'name':'Bus Station' },
'ZFB': { 'latitude':'51.583333', 'longitude': '-57.916667', 'name':'Old Fort Bay' },
'ZFA': { 'latitude':'62.166667', 'longitude': '-133.666667', 'name':'Faro' },
'ZFD': { 'latitude':'59.333333', 'longitude': '-107.166667', 'name':'Fond Du Lac' },
'TMP': { 'latitude':'61.415278', 'longitude': '23.587778', 'name':'Tampere-pirkkala' },
'WEA': { 'latitude':'32.75', 'longitude': '-97.783333', 'name':'Parker County' },
'WEF': { 'latitude':'36.71', 'longitude': '119.101944', 'name':'Weifang' },
'WED': { 'latitude':'-10.1', 'longitude': '150.083333', 'name':'Wedau' },
'WEI': { 'latitude':'-12.678333', 'longitude': '141.925', 'name':'Weipa' },
'WEH': { 'latitude':'37.5', 'longitude': '122.083333', 'name':'Weihai' },
'WEM': { 'latitude':'51.3', 'longitude': '0.416667', 'name':'West Malling' },
'WEL': { 'latitude':'-28.0', 'longitude': '26.75', 'name':'Welkom' },
'WES': { 'latitude':'7.283333', 'longitude': '-10.483333', 'name':'Weasua' },
'WEP': { 'latitude':'-8.666667', 'longitude': '141.136111', 'name':'Weam' },
'WEW': { 'latitude':'-30.233333', 'longitude': '149.433333', 'name':'Wee Waa' },
'WET': { 'latitude':'-4.05', 'longitude': '136.266667', 'name':'Wagethe' },
'WEX': { 'latitude':'52.333333', 'longitude': '-6.45', 'name':'Castlebridge' },
'KBW': { 'latitude':'56.296389', 'longitude': '-158.399444', 'name':'Chignik Bay' },
'NFG': { 'latitude':'61.133333', 'longitude': '73.05', 'name':'Nefteyugansk' },
'0A7': { 'latitude':'35.316667', 'longitude': '-82.45', 'name':'Hendersonville Airport' },
'YCM': { 'latitude':'43.2', 'longitude': '-79.166667', 'name':'St Catharines' },
'BLX': { 'latitude':'46.333333', 'longitude': '12.341667', 'name':'Belluno' },
'XDE': { 'latitude':'10.966667', 'longitude': '-3.25', 'name':'Diebougou' },
'XDB': { 'latitude':'50.633333', 'longitude': '3.066667', 'name':'Lille Europe Rail Svc' },
'XDJ': { 'latitude':'14.1', 'longitude': '-1.633333', 'name':'Djibo' },
'XDW': { 'latitude':'54.316667', 'longitude': '-1.333333', 'name':'Pr. Rupert Rail Stn' },
'XDV': { 'latitude':'53.916667', 'longitude': '-1.766667', 'name':'Pr. George Rail Stn' },
'XDY': { 'latitude':'46.5', 'longitude': '-80.966667', 'name':'Sudbury Jct Rail Stn' },
'BLV': { 'latitude':'44.166667', 'longitude': '-77.383333', 'name':'Belleville' },
'UIB': { 'latitude':'5.683333', 'longitude': '-76.633333', 'name':'Quibdo' },
'HCB': { 'latitude':'55.458333', 'longitude': '-131.283333', 'name':'Shoal Cove' },
'OHD': { 'latitude':'41.18', 'longitude': '20.75', 'name':'Ohrid' },
'BLN': { 'latitude':'-36.55', 'longitude': '145.983333', 'name':'Benalla' },
'UIK': { 'latitude':'58.133333', 'longitude': '102.55', 'name':'Ust-Ilimsk' },
'NFR': { 'latitude':'29.2', 'longitude': '21.383333', 'name':'Nafoora' },
'OHA': { 'latitude':'-40.208333', 'longitude': '175.386667', 'name':'Royal Air Force Base' },
'XZF': { 'latitude':'21.516944', 'longitude': '39.219167', 'name':'Dammam Port' },
'OHC': { 'latitude':'63.316667', 'longitude': '-168.966667', 'name':'AFS' },
'VRS': { 'latitude':'38.434722', 'longitude': '-92.816667', 'name':'Versailles' },
'TVY': { 'latitude':'14.1', 'longitude': '98.2', 'name':'Dawe' },
'VRU': { 'latitude':'-26.983333', 'longitude': '24.733333', 'name':'Vryburg' },
'UIP': { 'latitude':'47.966667', 'longitude': '-4.166667', 'name':'Pluguffan' },
'TVU': { 'latitude':'-16.690556', 'longitude': '179.876944', 'name':'Matei' },
'BLA': { 'latitude':'10.121389', 'longitude': '-64.695833', 'name':'Gen J A Anzoategui' },
'VRY': { 'latitude':'67.666667', 'longitude': '12.683333', 'name':'Stolport' },
'VRC': { 'latitude':'13.583333', 'longitude': '124.2', 'name':'Virac' },
'TVL': { 'latitude':'38.883333', 'longitude': '-120.0', 'name':'South Lake Tahoe' },
'VRA': { 'latitude':'23.133333', 'longitude': '-81.3', 'name':'Juan Gualberto Gomez' },
'TVI': { 'latitude':'51.566667', 'longitude': '8.133333', 'name':'Municipal' },
'VRE': { 'latitude':'-31.683333', 'longitude': '18.583333', 'name':'Vredendal' },
'VRK': { 'latitude':'62.3', 'longitude': '27.933333', 'name':'Varkaus' },
'BLB': { 'latitude':'8.95', 'longitude': '-79.566667', 'name':'Balboa' },
'TVA': { 'latitude':'-17.85', 'longitude': '44.916667', 'name':'Morafenobe' },
'VRN': { 'latitude':'45.466667', 'longitude': '10.933333', 'name':'Valerio Catullo' },
'TVC': { 'latitude':'44.741389', 'longitude': '-85.582222', 'name':'Cherry Capital Airport' },
'VRL': { 'latitude':'41.3', 'longitude': '-7.75', 'name':'Vila Real' },
'YRI': { 'latitude':'47.766667', 'longitude': '-69.583333', 'name':'Riviere Du Loup' },
'YRJ': { 'latitude':'48.533333', 'longitude': '-72.266667', 'name':'Roberval' },
'YRL': { 'latitude':'51.066667', 'longitude': '-93.816667', 'name':'Red Lake' },
'YRM': { 'latitude':'52.429722', 'longitude': '-114.904167', 'name':'Rocky Mountain House' },
'YRN': { 'latitude':'51.466667', 'longitude': '-127.583333', 'name':'Rivers Inlet' },
'JZH': { 'latitude':'32.836944', 'longitude': '103.681944', 'name':'Jiu Zhai Huang Long' },
'YRA': { 'latitude':'64.116667', 'longitude': '-117.35', 'name':'Rae Lakes' },
'YRB': { 'latitude':'74.716667', 'longitude': '-94.983333', 'name':'Resolute' },
'YRD': { 'latitude':'52.816667', 'longitude': '-126.966667', 'name':'Dean River' },
'YRE': { 'latitude':'61.5', 'longitude': '-65.0', 'name':'Resolution Island' },
'YRF': { 'latitude':'53.716667', 'longitude': '-57.0', 'name':'Cartwright' },
'YRG': { 'latitude':'54.333333', 'longitude': '-58.416667', 'name':'Rigolet' },
'YRQ': { 'latitude':'46.35', 'longitude': '-72.55', 'name':'Trois-Rivieres' },
'YRR': { 'latitude':'50.416667', 'longitude': '-125.166667', 'name':'Stuart Island' },
'YRS': { 'latitude':'54.166667', 'longitude': '-93.583333', 'name':'Red Sucker Lake' },
'YRT': { 'latitude':'62.811389', 'longitude': '-92.115833', 'name':'Nuuk' },
'YRV': { 'latitude':'50.983333', 'longitude': '-118.2', 'name':'Revelstoke' },
'OHR': { 'latitude':'54.666667', 'longitude': '8.675', 'name':'Wyk Auf Foehr' },
'QRA': { 'latitude':'-26.2425', 'longitude': '28.151111', 'name':'Rand/Germiston' },
'QRO': { 'latitude':'20.617222', 'longitude': '-100.185556', 'name':'Queretaro' },
'QRW': { 'latitude':'5.5', 'longitude': '5.68333', 'name':'Warri' },
'QRY': { 'latitude':'68.533333', 'longitude': '-82.216667', 'name':'Heliport' },
'HPY': { 'latitude':'29.733333', 'longitude': '-94.966667', 'name':'Baytown' },
'HPR': { 'latitude':'-2.266667', 'longitude': '-79.333333', 'name':'Central Hpr' },
'HPP': { 'latitude':'13.656111', 'longitude': '102.5625', 'name':'Poipet' },
'HPV': { 'latitude':'22.2125', 'longitude': '-159.446667', 'name':'Princeville' },
'HPT': { 'latitude':'42.75', 'longitude': '-93.2', 'name':'Municipal' },
'WXF': { 'latitude':'51.883333', 'longitude': '-0.566667', 'name':'Weathersfield Raf' },
'HPH': { 'latitude':'20.816667', 'longitude': '106.566667', 'name':'Catbi' },
'HPN': { 'latitude':'41.066667', 'longitude': '-73.7', 'name':'Westchester County Apt' },
'HPB': { 'latitude':'61.5', 'longitude': '-166.083333', 'name':'Hooper Bay' },
'WXN': { 'latitude':'30.9', 'longitude': '103.466667', 'name':'Wanxian' },
'HPE': { 'latitude':'-14.666667', 'longitude': '144.916667', 'name':'Hope Vale' },
'OHO': { 'latitude':'59.416667', 'longitude': '143.05', 'name':'Okhotsk' },
'OHH': { 'latitude':'53.5172', 'longitude': '142.8839', 'name':'Okha' },
'OHI': { 'latitude':'-17.783333', 'longitude': '15.7', 'name':'Oshakati' },
'IOW': { 'latitude':'41.639167', 'longitude': '-91.546389', 'name':'Iowa City' },
'UIH': { 'latitude':'13.766667', 'longitude': '109.216667', 'name':'Qui Nhon' },
'IOU': { 'latitude':'-22.416667', 'longitude': '166.8', 'name':'Ile Ouen' },
'IOS': { 'latitude':'-14.815833', 'longitude': '-39.033333', 'name':'Eduardo Gomes' },
'IOR': { 'latitude':'53.106667', 'longitude': '-9.653333', 'name':'Kilronan' },
'UIO': { 'latitude':'0.133333', 'longitude': '-78.483333', 'name':'Mariscal Sucre' },
'IOP': { 'latitude':'-8.366667', 'longitude': '147.85', 'name':'Ioma' },
'UIQ': { 'latitude':'-17.55', 'longitude': '168.416667', 'name':'Quine Hill' },
'ION': { 'latitude':'1.616667', 'longitude': '18.066667', 'name':'Impfondo' },
'IOM': { 'latitude':'54.083333', 'longitude': '-4.623889', 'name':'Ronaldsway' },
'UIR': { 'latitude':'-31.490556', 'longitude': '150.513889', 'name':'Quirindi' },
'IOK': { 'latitude':'-8.4', 'longitude': '146.266667', 'name':'Iokea' },
'UIT': { 'latitude':'5.833333', 'longitude': '169.616667', 'name':'Jaluit Island' },
'OHT': { 'latitude':'33.566667', 'longitude': '71.45', 'name':'Kohat' },
'UIZ': { 'latitude':'37.066667', 'longitude': '10.066667', 'name':'Berz-Macomb' },
'OHP': { 'latitude':'-0.566667', 'longitude': '10.283333', 'name':'Heliport' },
'IOA': { 'latitude':'39.7', 'longitude': '20.816667', 'name':'Ioannina' },
'RXA': { 'latitude':'14.45', 'longitude': '47.283333', 'name':'Raudha' },
'RXS': { 'latitude':'11.516667', 'longitude': '122.75', 'name':'Roxas City' },
'MNX': { 'latitude':'-5.816667', 'longitude': '-61.283333', 'name':'Manicore' },
'MNY': { 'latitude':'-7.35', 'longitude': '155.5', 'name':'Mono' },
'MNZ': { 'latitude':'38.716667', 'longitude': '-77.516667', 'name':'Manassas' },
'SCN': { 'latitude':'49.214444', 'longitude': '7.109444', 'name':'Ensheim' },
'SCI': { 'latitude':'7.766667', 'longitude': '-72.233333', 'name':'San Cristobal' },
'SCH': { 'latitude':'42.8525', 'longitude': '-73.928889', 'name':'Schenectady County' },
'SCK': { 'latitude':'37.9', 'longitude': '-121.25', 'name':'Stockton Metropolitan Airport' },
'SCJ': { 'latitude':'55.4375', 'longitude': '-132.341667', 'name':'Smith Cove' },
'MNP': { 'latitude':'8.933333', 'longitude': '-12.516667', 'name':'Maron' },
'MNQ': { 'latitude':'-24.883333', 'longitude': '151.1', 'name':'Monto' },
'MNR': { 'latitude':'-15.216667', 'longitude': '23.15', 'name':'Mongu' },
'MNS': { 'latitude':'-11.1', 'longitude': '28.85', 'name':'Mansa' },
'MNT': { 'latitude':'64.9', 'longitude': '-149.166667', 'name':'Minto' },
'MNU': { 'latitude':'16.433333', 'longitude': '97.666667', 'name':'Maulmyine' },
'MNV': { 'latitude':'-14.116667', 'longitude': '133.833333', 'name':'Mountain Valley' },
'MNW': { 'latitude':'-22.5', 'longitude': '135.166667', 'name':'Macdonald Downs' },
'MNH': { 'latitude':'7.75', 'longitude': '83.0', 'name':'Minneriya' },
'MNI': { 'latitude':'16.791389', 'longitude': '-62.193333', 'name':'Gerald\'s Airport' },
'MNJ': { 'latitude':'-21.201667', 'longitude': '48.358333', 'name':'Mananjary' },
'MNK': { 'latitude':'0.033333', 'longitude': '173.0', 'name':'Maiana' },
'MNL': { 'latitude':'14.516667', 'longitude': '121.016667', 'name':'Ninoy Aquino Intl' },
'MNM': { 'latitude':'45.283333', 'longitude': '-87.633333', 'name':'Menominee' },
'MNN': { 'latitude':'40.616667', 'longitude': '-83.066667', 'name':'Municipal' },
'MNO': { 'latitude':'-7.283333', 'longitude': '27.433333', 'name':'Manono' },
'SCU': { 'latitude':'19.966667', 'longitude': '-75.866667', 'name':'Antonio Maceo' },
'MNA': { 'latitude':'4.05', 'longitude': '126.7', 'name':'Melangguane' },
'MNB': { 'latitude':'-5.933333', 'longitude': '12.35', 'name':'Moanda' },
'MNC': { 'latitude':'-14.483333', 'longitude': '40.716667', 'name':'Nacala' },
'MND': { 'latitude':'4.516667', 'longitude': '-73.283333', 'name':'Medina' },
'MNE': { 'latitude':'-28.016667', 'longitude': '138.666667', 'name':'Mungeranie' },
'MNF': { 'latitude':'-17.661111', 'longitude': '177.119444', 'name':'Mana Island Airstrip' },
'MNG': { 'latitude':'-12.05', 'longitude': '134.216667', 'name':'Maningrida' },
'CJJ': { 'latitude':'36.637222', 'longitude': '127.489722', 'name':'Cheongju' },
'PBT': { 'latitude':'-20.716667', 'longitude': '-57.983333', 'name':'Puerto Leda' },
'CJH': { 'latitude':'51.25', 'longitude': '-1.083333', 'name':'Chilko Lake' },
'CJI': { 'latitude':'24.033333', 'longitude': '-54.1', 'name':'Ciudad Real - Don Quijote Airport' },
'CJN': { 'latitude':'32.826111', 'longitude': '-116.9725', 'name':'Gillespie Field' },
'PBP': { 'latitude':'10.416667', 'longitude': '-85.166667', 'name':'Punta Islita' },
'CJL': { 'latitude':'35.879722', 'longitude': '71.797222', 'name':'Chitral' },
'CJM': { 'latitude':'10.5', 'longitude': '99.166667', 'name':'Chumphon Airport' },
'CJB': { 'latitude':'11.03', 'longitude': '77.043333', 'name':'Peelamedu' },
'CJC': { 'latitude':'-22.483333', 'longitude': '-68.916667', 'name':'El Loa' },
'CJA': { 'latitude':'-7.133333', 'longitude': '-78.5', 'name':'Cajamarca' },
'PBY': { 'latitude':'-35.5', 'longitude': '148.733333', 'name':'Hamilton/Proserpine' },
'PBX': { 'latitude':'-10.860556', 'longitude': '-51.684444', 'name':'Porto Alegre Do Norte' },
'CJD': { 'latitude':'2.066667', 'longitude': '-74.583333', 'name':'Candilejas' },
'PBZ': { 'latitude':'-34.090278', 'longitude': '23.327778', 'name':'Plettenberg Bay' },
'PBE': { 'latitude':'6.483333', 'longitude': '-74.483333', 'name':'Puerto Berrio' },
'PBD': { 'latitude':'21.65', 'longitude': '69.65', 'name':'Porbandar' },
'PBG': { 'latitude':'44.650833', 'longitude': '-73.468056', 'name':'Plattsburgh AFB' },
'PBF': { 'latitude':'34.183333', 'longitude': '-91.933333', 'name':'Grider Field' },
'PBA': { 'latitude':'71.333333', 'longitude': '-156.633333', 'name':'Point Barrow' },
'PBC': { 'latitude':'19.158056', 'longitude': '-98.371389', 'name':'Hermanos Serdan International' },
'PBB': { 'latitude':'-19.666667', 'longitude': '-51.183333', 'name':'Paranaiba' },
'PBM': { 'latitude':'5.452778', 'longitude': '-55.187778', 'name':'Zanderij Intl' },
'CJS': { 'latitude':'31.666667', 'longitude': '-106.433333', 'name':'Intl Abraham Gonzalez' },
'PBO': { 'latitude':'-23.233333', 'longitude': '117.516667', 'name':'Paraburdoo' },
'PBN': { 'latitude':'-10.7', 'longitude': '13.75', 'name':'Porto Amboim' },
'PBI': { 'latitude':'26.683056', 'longitude': '-80.095556', 'name':'Palm Beach International' },
'PBH': { 'latitude':'27.403056', 'longitude': '89.425', 'name':'Paro' },
'CJT': { 'latitude':'16.25', 'longitude': '-92.133333', 'name':'Copalar' },
'CJU': { 'latitude':'33.504722', 'longitude': '126.493056', 'name':'Jeju Airport' },
'TKT': { 'latitude':'16.883333', 'longitude': '99.15', 'name':'Tak' },
'OUE': { 'latitude':'1.533333', 'longitude': '16.05', 'name':'Ouesso' },
'QMQ': { 'latitude':'25.904444', 'longitude': '13.897222', 'name':'Murzuq' },
'QMV': { 'latitude':'43.866667', 'longitude': '1.6', 'name':'Montvale' },
'QMK': { 'latitude':'67.333333', 'longitude': '-53.8', 'name':'Heliport' },
'QMM': { 'latitude':'42.766667', 'longitude': '10.233333', 'name':'Marina Di Massa' },
'ADV': { 'latitude':'51.216667', 'longitude': '-1.466667', 'name':'Andover' },
'ADW': { 'latitude':'38.8', 'longitude': '-76.916667', 'name':'Andrews AFB' },
'GMI': { 'latitude':'-6.3', 'longitude': '150.333333', 'name':'Gasmata Island' },
'ADU': { 'latitude':'38.249444', 'longitude': '48.301389', 'name':'Ardabil' },
'ADR': { 'latitude':'33.45', 'longitude': '-79.566667', 'name':'Andrews' },
'ADS': { 'latitude':'32.968611', 'longitude': '-96.836389', 'name':'Addison Airport' },
'ADP': { 'latitude':'8.3', 'longitude': '80.416667', 'name':'Ampara' },
'ADQ': { 'latitude':'57.75', 'longitude': '-152.483333', 'name':'Kodiak Airport' },
'GMC': { 'latitude':'3.633333', 'longitude': '-71.166667', 'name':'Guerima' },
'GMB': { 'latitude':'8.283333', 'longitude': '34.583333', 'name':'Gambela' },
'GMA': { 'latitude':'3.266667', 'longitude': '19.766667', 'name':'Gemena' },
'ADZ': { 'latitude':'12.583333', 'longitude': '-81.7', 'name':'San Andres Island' },
'ADX': { 'latitude':'56.366667', 'longitude': '-2.866667', 'name':'Leuchars' },
'ADY': { 'latitude':'-22.666667', 'longitude': '29.1', 'name':'Alldays' },
'ADF': { 'latitude':'37.731369', 'longitude': '38.468936', 'name':'Adiyaman' },
'ADG': { 'latitude':'41.9', 'longitude': '-84.033333', 'name':'Lenawee County' },
'ADD': { 'latitude':'8.977778', 'longitude': '38.799444', 'name':'Bole International' },
'ADE': { 'latitude':'12.827778', 'longitude': '45.030556', 'name':'Aden' },
'ADB': { 'latitude':'38.2925', 'longitude': '27.156944', 'name':'Adnan Menderes' },
'ADC': { 'latitude':'-7.133333', 'longitude': '145.733333', 'name':'Andakombe' },
'ADA': { 'latitude':'36.982222', 'longitude': '35.280278', 'name':'Adana' },
'ADN': { 'latitude':'5.666667', 'longitude': '-75.883333', 'name':'Andes' },
'ADO': { 'latitude':'-30.437778', 'longitude': '137.137222', 'name':'Andamooka' },
'ADL': { 'latitude':'-34.945', 'longitude': '138.530556', 'name':'Adelaide International Airport' },
'ADM': { 'latitude':'34.966667', 'longitude': '-86.883333', 'name':'Ardmore Municipal Arpt' },
'ADJ': { 'latitude':'31.972778', 'longitude': '35.991667', 'name':'Marka International Airport' },
'ADK': { 'latitude':'51.878056', 'longitude': '-176.646111', 'name':'Adak Island Ns' },
'ADH': { 'latitude':'58.6', 'longitude': '125.4', 'name':'Aldan' },
'ADI': { 'latitude':'-22.4', 'longitude': '15.0', 'name':'Arandis' },
'BRZ': { 'latitude':'8.733333', 'longitude': '-7.5', 'name':'Borotou' },
'BRY': { 'latitude':'37.816667', 'longitude': '-85.466667', 'name':'Samuels Field' },
'BRX': { 'latitude':'18.216667', 'longitude': '-71.116667', 'name':'Barahona' },
'BRW': { 'latitude':'71.333333', 'longitude': '-156.65', 'name':'Wiley Post/W.Rogers M' },
'BRV': { 'latitude':'53.75', 'longitude': '8.916667', 'name':'Bremerhaven' },
'BRU': { 'latitude':'50.902222', 'longitude': '4.485833', 'name':'Brussels Airport' },
'BRT': { 'latitude':'-11.766667', 'longitude': '130.633333', 'name':'Bathurst Island' },
'BRS': { 'latitude':'51.383333', 'longitude': '-2.716667', 'name':'Bristol' },
'BRR': { 'latitude':'57.016667', 'longitude': '-7.433333', 'name':'North Bay' },
'BRQ': { 'latitude':'49.151389', 'longitude': '16.694444', 'name':'Turany' },
'BRP': { 'latitude':'-7.666667', 'longitude': '146.35', 'name':'Biaru' },
'BRO': { 'latitude':'25.916667', 'longitude': '-97.416667', 'name':'South Padre Is. Intl' },
'BRN': { 'latitude':'46.913889', 'longitude': '7.496944', 'name':'Belp' },
'BRM': { 'latitude':'10.042778', 'longitude': '-69.358611', 'name':'Barquisimeto' },
'BRL': { 'latitude':'40.783333', 'longitude': '-91.116667', 'name':'Burlington' },
'BRK': { 'latitude':'-30.05', 'longitude': '145.95', 'name':'Bourke' },
'BRJ': { 'latitude':'-36.733333', 'longitude': '146.966667', 'name':'Bright' },
'BRI': { 'latitude':'41.133333', 'longitude': '16.783333', 'name':'Palese' },
'BRH': { 'latitude':'-5.7', 'longitude': '145.366667', 'name':'Brahman' },
'BRG': { 'latitude':'37.116667', 'longitude': '-82.816667', 'name':'Municipal' },
'BRF': { 'latitude':'51.0', 'longitude': '-3.183333', 'name':'Bradford' },
'BRE': { 'latitude':'53.05', 'longitude': '8.783333', 'name':'Bremen' },
'BRD': { 'latitude':'46.401667', 'longitude': '-94.135556', 'name':'Brainerd Lakes Regional' },
'BRC': { 'latitude':'-41.133333', 'longitude': '-71.166667', 'name':'International' },
'BRB': { 'latitude':'-2.833333', 'longitude': '-42.833333', 'name':'Barreirinhas' },
'BRA': { 'latitude':'-12.05', 'longitude': '-45.0', 'name':'Barreiras' },
'MPO': { 'latitude':'41.133333', 'longitude': '-75.366667', 'name':'Mt Pocono' },
'LTT': { 'latitude':'43.269706', 'longitude': '6.639175', 'name':'Saint Tropez La Mole' },
'ESW': { 'latitude':'47.233333', 'longitude': '-121.183333', 'name':'State' },
'KLE': { 'latitude':'10.1', 'longitude': '14.45', 'name':'Kaele' },
'ESU': { 'latitude':'31.3975', 'longitude': '-9.681667', 'name':'Essaouira' },
'EST': { 'latitude':'43.4', 'longitude': '-94.833333', 'name':'Municipal' },
'ESS': { 'latitude':'51.416667', 'longitude': '7.0', 'name':'Essen' },
'ESR': { 'latitude':'-26.3', 'longitude': '-69.766667', 'name':'El Salvador' },
'KLB': { 'latitude':'-14.966667', 'longitude': '22.683333', 'name':'Kalabo' },
'ESP': { 'latitude':'41.0', 'longitude': '-75.183333', 'name':'Birchwood-Pocono' },
'KLL': { 'latitude':'59.116667', 'longitude': '-156.883333', 'name':'Levelock' },
'KLN': { 'latitude':'57.533333', 'longitude': '-154.0', 'name':'Larsen SPB' },
'KLO': { 'latitude':'11.7', 'longitude': '122.366667', 'name':'Kalibo' },
'KLH': { 'latitude':'16.664722', 'longitude': '74.289444', 'name':'Kolhapur' },
'KLI': { 'latitude':'-4.166667', 'longitude': '21.75', 'name':'Kota Koli' },
'KLK': { 'latitude':'3.516667', 'longitude': '35.833333', 'name':'Kalokol' },
'ESG': { 'latitude':'-22.045', 'longitude': '-60.621667', 'name':'Mariscal Estigarribia' },
'ESF': { 'latitude':'31.4', 'longitude': '-92.3', 'name':'Esler Field' },
'ESE': { 'latitude':'31.8', 'longitude': '-116.6', 'name':'Ensenada' },
'ESD': { 'latitude':'48.716667', 'longitude': '-122.816667', 'name':'Orcas Island' },
'ESC': { 'latitude':'45.722778', 'longitude': '-87.093611', 'name':'Delta County Arpt' },
'ESB': { 'latitude':'40.133333', 'longitude': '33.0', 'name':'Esenboga' },
'KLR': { 'latitude':'56.685833', 'longitude': '16.290556', 'name':'Kalmar' },
'KLS': { 'latitude':'46.15', 'longitude': '-122.9', 'name':'Longview' },
'ESO': { 'latitude':'36.1', 'longitude': '-106.033333', 'name':'Espanola' },
'ESN': { 'latitude':'38.808333', 'longitude': '-76.075', 'name':'Easton' },
'ESM': { 'latitude':'0.95', 'longitude': '-79.6', 'name':'Esmeraldas' },
'ESL': { 'latitude':'46.366667', 'longitude': '44.333333', 'name':'Elista' },
'ESK': { 'latitude':'39.784167', 'longitude': '30.582222', 'name':'Eskisehir' },
'KLY': { 'latitude':'-2.583333', 'longitude': '26.733333', 'name':'Kalima' },
'ESI': { 'latitude':'-14.933333', 'longitude': '-42.833333', 'name':'Espinosa' },
'ESH': { 'latitude':'50.835278', 'longitude': '-0.301944', 'name':'Shoreham' },
'FMN': { 'latitude':'36.75', 'longitude': '-108.233333', 'name':'Municipal' },
'FMO': { 'latitude':'51.95', 'longitude': '7.616667', 'name':'Greven' },
'SCE': { 'latitude':'40.772222', 'longitude': '-77.883333', 'name':'University Park' },
'SCD': { 'latitude':'14.925', 'longitude': '-87.258333', 'name':'Sulaco' },
'SCG': { 'latitude':'-18.633333', 'longitude': '144.55', 'name':'Spring Creek' },
'SCF': { 'latitude':'33.5', 'longitude': '-111.933333', 'name':'Scottsdale Municipal' },
'SCA': { 'latitude':'8.5', 'longitude': '-76.175', 'name':'Santa Catalina' },
'LTD': { 'latitude':'30.166667', 'longitude': '9.5', 'name':'Ghadames' },
'TIN': { 'latitude':'27.674167', 'longitude': '-8.147778', 'name':'Tindouf' },
'BGC': { 'latitude':'41.816667', 'longitude': '-6.75', 'name':'Braganca' },
'SCC': { 'latitude':'70.333333', 'longitude': '-148.333333', 'name':'Prudhoe Bay/Deadhorse' },
'SCB': { 'latitude':'41.666667', 'longitude': '-96.65', 'name':'State' },
'FME': { 'latitude':'19.833333', 'longitude': '-72.5', 'name':'Tipton AAF' },
'FMC': { 'latitude':'65.916667', 'longitude': '-149.833333', 'name':'Five Mile' },
'SCY': { 'latitude':'-0.910278', 'longitude': '-89.6175', 'name':'San Cristobal' },
'FMA': { 'latitude':'-26.212778', 'longitude': '-58.228056', 'name':'El Pucu' },
'SCX': { 'latitude':'16.166667', 'longitude': '-95.2', 'name':'Salina Cruz' },
'RDT': { 'latitude':'16.433333', 'longitude': '-15.65', 'name':'Richard Toll' },
'SCZ': { 'latitude':'-11.616667', 'longitude': '166.85', 'name':'Santa Cruz Is' },
'TIH': { 'latitude':'-15.119722', 'longitude': '-148.230833', 'name':'Tikehau Atoll' },
'SCT': { 'latitude':'12.5', 'longitude': '54.0', 'name':'Socotra' },
'SCW': { 'latitude':'61.666667', 'longitude': '50.766667', 'name':'Syktyvkar' },
'SCV': { 'latitude':'47.6875', 'longitude': '26.354167', 'name':'Salcea' },
'SCQ': { 'latitude':'42.833333', 'longitude': '-8.55', 'name':'Santiago De Compostela' },
'SCP': { 'latitude':'44.683333', 'longitude': '6.583333', 'name':'St Crepin' },
'YLE': { 'latitude':'63.15', 'longitude': '-117.266667', 'name':'Wha Ti' },
'SCS': { 'latitude':'60.43', 'longitude': '-1.296111', 'name':'Scatsta' },
'UIL': { 'latitude':'47.95', 'longitude': '-124.566667', 'name':'Quillayute State' },
'PBU': { 'latitude':'27.333333', 'longitude': '97.416667', 'name':'Putao' },
'ZDU': { 'latitude':'56.5', 'longitude': '-2.966667', 'name':'ScotRail' },
'PBW': { 'latitude':'9.533333', 'longitude': '-0.216667', 'name':'Palibelo' },
'ZDM': { 'latitude':'32.271944', 'longitude': '35.019444', 'name':'Ramallah Heliport' },
'PBV': { 'latitude':'-21.35', 'longitude': '-51.866667', 'name':'Porto Dos Gauchos' },
'PBQ': { 'latitude':'-11.634722', 'longitude': '-61.168889', 'name':'Pimenta Bueno' },
'PBS': { 'latitude':'7.9', 'longitude': '98.283333', 'name':'Patong Beach' },
'PBR': { 'latitude':'15.8', 'longitude': '-88.5', 'name':'Puerto Barrios' },
'UIN': { 'latitude':'39.933333', 'longitude': '-91.183333', 'name':'Municipal' },
'WGE': { 'latitude':'-30.033333', 'longitude': '148.133333', 'name':'Walgett' },
'WGF': { 'latitude':'-29.066667', 'longitude': '27.733333', 'name':'Off Line Point' },
'WGA': { 'latitude':'-35.166667', 'longitude': '147.466667', 'name':'Forrest Hill' },
'WGC': { 'latitude':'17.914444', 'longitude': '79.602222', 'name':'Warangal' },
'WGB': { 'latitude':'30.0', 'longitude': '73.25', 'name':'Bahawalnagar' },
'WGO': { 'latitude':'39.183333', 'longitude': '-78.166667', 'name':'Municipal' },
'WGN': { 'latitude':'-35.166667', 'longitude': '173.966667', 'name':'Waitangi' },
'WGU': { 'latitude':'-6.8', 'longitude': '146.8', 'name':'Wagau' },
'WGT': { 'latitude':'-36.366667', 'longitude': '146.333333', 'name':'Wangaratta' },
'WGP': { 'latitude':'-9.666667', 'longitude': '120.3', 'name':'Waingapu' },
'WGY': { 'latitude':'-0.516667', 'longitude': '10.433333', 'name':'Wagny' },
'WGZ': { 'latitude':'-25.566667', 'longitude': '146.833333', 'name':'Off Line Point' },
'PBL': { 'latitude':'10.466667', 'longitude': '-68.1', 'name':'Puerto Cabello' },
'XFN': { 'latitude':'32.05', 'longitude': '112.016667', 'name':'Xiangfan' },
'XFA': { 'latitude':'50.633333', 'longitude': '3.066667', 'name':'Lille Flanders Rail Sv' },
'NTX': { 'latitude':'3.95', 'longitude': '108.383333', 'name':'Natuna Ranai' },
'XFY': { 'latitude':'46.8', 'longitude': '-71.25', 'name':'Sainte-Foy Rail Svce.' },
'XFZ': { 'latitude':'46.8', 'longitude': '-71.25', 'name':'Charny' },
'PBK': { 'latitude':'-34.2', 'longitude': '150.616667', 'name':'Pack Creek' },
'PBJ': { 'latitude':'-16.433333', 'longitude': '168.216667', 'name':'Paama' },
'XFW': { 'latitude':'53.516667', 'longitude': '9.866667', 'name':'Finkenwerder' },
'VOI': { 'latitude':'8.416667', 'longitude': '-9.75', 'name':'Voinjama' },
'VXO': { 'latitude':'56.929167', 'longitude': '14.728056', 'name':'Smaland Airport' },
'HDF': { 'latitude':'54.3', 'longitude': '11.0', 'name':'Heringsdorf' },
'GPI': { 'latitude':'2.583333', 'longitude': '-77.9', 'name':'Guapi' },
'VPS': { 'latitude':'30.483333', 'longitude': '-86.525278', 'name':'Eglin AFB' },
'VPY': { 'latitude':'-19.133333', 'longitude': '33.483333', 'name':'Chimoio' },
'VPZ': { 'latitude':'41.45', 'longitude': '-86.983333', 'name':'Porter County' },
'VPE': { 'latitude':'-17.05', 'longitude': '15.6', 'name':'Ongiva' },
'VPN': { 'latitude':'65.756944', 'longitude': '-14.829444', 'name':'Vopnafjordur' },
'YPR': { 'latitude':'54.283333', 'longitude': '-130.45', 'name':'Digby Island' },
'YPS': { 'latitude':'45.616667', 'longitude': '-61.35', 'name':'Port Hawkesbury' },
'YPP': { 'latitude':'61.016667', 'longitude': '-114.25', 'name':'Pine Point' },
'THT': { 'latitude':'17.25', 'longitude': '-10.666667', 'name':'Tamchakett' },
'YPW': { 'latitude':'49.883333', 'longitude': '-124.55', 'name':'Powell River' },
'YPT': { 'latitude':'49.5', 'longitude': '-124.033333', 'name':'Pender Harbor' },
'YPZ': { 'latitude':'54.233333', 'longitude': '-125.766667', 'name':'Burns Lake' },
'YPX': { 'latitude':'60.5', 'longitude': '-77.233333', 'name':'Puvirnituq' },
'YPY': { 'latitude':'58.7', 'longitude': '-111.15', 'name':'Fort Chipewyan' },
'THR': { 'latitude':'35.689167', 'longitude': '51.313333', 'name':'Mehrabad/ghaleh Morghi' },
'YPB': { 'latitude':'49.233333', 'longitude': '-124.8', 'name':'Port Alberni' },
'YPC': { 'latitude':'62.35', 'longitude': '-124.083333', 'name':'Paulatuk' },
'YPA': { 'latitude':'53.216667', 'longitude': '-105.683333', 'name':'Glass Field' },
'YPF': { 'latitude':'48.433333', 'longitude': '-123.4', 'name':'Esquimalt' },
'VXC': { 'latitude':'-13.283333', 'longitude': '35.25', 'name':'Lichinga' },
'YPD': { 'latitude':'45.35', 'longitude': '-80.033333', 'name':'Parry Sound' },
'YPE': { 'latitude':'56.233333', 'longitude': '-117.433333', 'name':'Peace River' },
'YPJ': { 'latitude':'59.066667', 'longitude': '-69.55', 'name':'Aupaluk' },
'YPH': { 'latitude':'58.45', 'longitude': '-78.1', 'name':'Inukjuak' },
'YPI': { 'latitude':'54.55', 'longitude': '-130.416667', 'name':'Port Simpson' },
'YPN': { 'latitude':'49.833333', 'longitude': '-64.283333', 'name':'Port Menier' },
'YPO': { 'latitude':'54.983333', 'longitude': '-85.433333', 'name':'Peawanuck' },
'YPL': { 'latitude':'51.5', 'longitude': '-90.15', 'name':'Pickle Lake' },
'JXN': { 'latitude':'42.266667', 'longitude': '-84.466667', 'name':'Reynolds Municipal' },
'THN': { 'latitude':'58.316667', 'longitude': '12.35', 'name':'Trollhattan' },
'THI': { 'latitude':'18.466667', 'longitude': '-9.5', 'name':'Tichitt' },
'THG': { 'latitude':'-24.493889', 'longitude': '150.576111', 'name':'Thangool' },
'QPJ': { 'latitude':'45.989167', 'longitude': '18.242222', 'name':'Pecs-Pogany' },
'QPG': { 'latitude':'1.360556', 'longitude': '103.909444', 'name':'Paya Lebar' },
'THB': { 'latitude':'-29.05', 'longitude': '28.716667', 'name':'Thaba-Tseka' },
'QPW': { 'latitude':'65.85', 'longitude': '-53.316667', 'name':'Heliport' },
'TPG': { 'latitude':'4.866667', 'longitude': '100.716667', 'name':'Taiping' },
'TPE': { 'latitude':'25.077778', 'longitude': '121.223889', 'name':'Taiwan Taoyuan International' },
'HRY': { 'latitude':'-24.666667', 'longitude': '133.083333', 'name':'Henbury' },
'TPA': { 'latitude':'27.975556', 'longitude': '-82.533056', 'name':'Tampa International' },
'HRZ': { 'latitude':'-27.616667', 'longitude': '-54.316667', 'name':'Horizontina' },
'TPO': { 'latitude':'3.711944', 'longitude': '-75.469444', 'name':'Tanalian Point' },
'HRT': { 'latitude':'54.05', 'longitude': '-1.25', 'name':'Linton-On-Ouse' },
'TPL': { 'latitude':'31.1525', 'longitude': '-97.407778', 'name':'Draughon-miller Central Texas Regional' },
'TPK': { 'latitude':'3.466667', 'longitude': '97.3', 'name':'Tapaktuan' },
'TPJ': { 'latitude':'27.35', 'longitude': '87.666667', 'name':'Taplejung Suketar' },
'HRS': { 'latitude':'-28.233333', 'longitude': '29.1', 'name':'Harrismith Airport' },
'HRR': { 'latitude':'3.216667', 'longitude': '-75.85', 'name':'Herrera' },
'HRL': { 'latitude':'26.2', 'longitude': '-97.75', 'name':'Valley International' },
'HRO': { 'latitude':'36.228333', 'longitude': '-93.109722', 'name':'Boone County' },
'HRN': { 'latitude':'-23.433333', 'longitude': '151.916667', 'name':'Heliport' },
'TPS': { 'latitude':'38.016667', 'longitude': '12.483333', 'name':'Birgi' },
'TPR': { 'latitude':'22.65', 'longitude': '106.066667', 'name':'Tom Price' },
'HRK': { 'latitude':'50.0', 'longitude': '36.25', 'name':'Kharkov' },
'HRJ': { 'latitude':'28.0', 'longitude': '83.838889', 'name':'Chaurjhari' },
'HRE': { 'latitude':'-17.931944', 'longitude': '31.092778', 'name':'Harare' },
'HRG': { 'latitude':'27.178333', 'longitude': '33.799444', 'name':'Hurghada' },
'HRA': { 'latitude':'34.333333', 'longitude': '73.2', 'name':'Mansehra' },
'HRC': { 'latitude':'48.466667', 'longitude': '70.466667', 'name':'Zhairem' },
'HRB': { 'latitude':'46.016667', 'longitude': '126.583333', 'name':'Harbin' },
'HJR': { 'latitude':'24.85', 'longitude': '79.933333', 'name':'Khajuraho' },
'UGI': { 'latitude':'57.883333', 'longitude': '-153.5', 'name':'Uganik' },
'UGO': { 'latitude':'-7.583333', 'longitude': '14.983333', 'name':'Uige' },
'UGN': { 'latitude':'42.35', 'longitude': '-87.833333', 'name':'Memorial' },
'UGC': { 'latitude':'41.666667', 'longitude': '60.533333', 'name':'Urgench' },
'UGB': { 'latitude':'57.433333', 'longitude': '-157.75', 'name':'Ugashik Bay' },
'UGA': { 'latitude':'48.8', 'longitude': '103.55', 'name':'Bulgan' },
'OJC': { 'latitude':'38.85', 'longitude': '-94.733333', 'name':'Johnson Executive' },
'UGU': { 'latitude':'38.766667', 'longitude': '40.333333', 'name':'Zugapa' },
'UGT': { 'latitude':'43.752778', 'longitude': '104.127778', 'name':'Umnugobitour' },
'ENA': { 'latitude':'60.55', 'longitude': '-151.266667', 'name':'Kenai' },
'ENB': { 'latitude':'-30.083333', 'longitude': '114.983333', 'name':'Eneabba West' },
'ENC': { 'latitude':'46.033333', 'longitude': '6.583333', 'name':'Essey' },
'END': { 'latitude':'36.339167', 'longitude': '-97.916389', 'name':'Vance Afb' },
'ENE': { 'latitude':'-8.833333', 'longitude': '121.65', 'name':'Ende' },
'ENF': { 'latitude':'68.35', 'longitude': '23.416667', 'name':'Enontekio' },
'ENH': { 'latitude':'30.283333', 'longitude': '109.316667', 'name':'Enshi' },
'ENI': { 'latitude':'11.205556', 'longitude': '119.412778', 'name':'El Nido' },
'ENJ': { 'latitude':'14.1', 'longitude': '-90.833333', 'name':'El Naranjo' },
'ENK': { 'latitude':'54.398889', 'longitude': '-7.633333', 'name':'Enniskillen St. Angelo' },
'ENL': { 'latitude':'38.516667', 'longitude': '-89.091667', 'name':'Municipal' },
'ENN': { 'latitude':'64.55', 'longitude': '-149.083333', 'name':'Municipal' },
'ENO': { 'latitude':'-27.316667', 'longitude': '-55.833333', 'name':'Teniente Prim Alarcon' },
'ENQ': { 'latitude':'14.369167', 'longitude': '-87.617222', 'name':'Coronel E Soto Cano AB' },
'RFA': { 'latitude':'4.988611', 'longitude': '23.927778', 'name':'Rafai' },
'ENS': { 'latitude':'52.283333', 'longitude': '6.883333', 'name':'Twente' },
'ENT': { 'latitude':'11.340833', 'longitude': '162.327778', 'name':'Enewetak Island' },
'ENU': { 'latitude':'6.466667', 'longitude': '7.55', 'name':'Enugu' },
'ENV': { 'latitude':'40.733333', 'longitude': '-114.033333', 'name':'Wendover' },
'ENW': { 'latitude':'42.583333', 'longitude': '-87.916667', 'name':'Kenosha Regional Airport' },
'ENY': { 'latitude':'36.0', 'longitude': '109.333333', 'name':'Yan\'an' },
'RFN': { 'latitude':'66.416667', 'longitude': '-15.916667', 'name':'Raufarhofn' },
'HJJ': { 'latitude':'27.1106', 'longitude': '109.0381', 'name':'Zhi Jiang' },
'SEW': { 'latitude':'29.35', 'longitude': '25.516667', 'name':'Siwa' },
'SEV': { 'latitude':'48.9', 'longitude': '38.55', 'name':'Severodoneck' },
'SEU': { 'latitude':'-2.416667', 'longitude': '34.833333', 'name':'Seronera' },
'SET': { 'latitude':'15.166667', 'longitude': '-85.8', 'name':'San Esteban' },
'SES': { 'latitude':'32.45', 'longitude': '-86.95', 'name':'Selfield' },
'SER': { 'latitude':'38.95', 'longitude': '-85.883333', 'name':'Freeman Municipal' },
'SEQ': { 'latitude':'1.366667', 'longitude': '102.133333', 'name':'Sungai Pakning' },
'SEP': { 'latitude':'32.216667', 'longitude': '-98.183333', 'name':'Clark Field' },
'SEZ': { 'latitude':'-4.674444', 'longitude': '55.521944', 'name':'Seychelles International Airport' },
'SEY': { 'latitude':'15.183333', 'longitude': '-12.2', 'name':'Selibaby' },
'SEG': { 'latitude':'40.783333', 'longitude': '-76.85', 'name':'Penn Valley' },
'SEF': { 'latitude':'27.456389', 'longitude': '-81.3425', 'name':'Sebring Regional Airport' },
'SEE': { 'latitude':'32.550278', 'longitude': '-116.916389', 'name':'Gillespie Field' },
'SEC': { 'latitude':'44.883333', 'longitude': '6.691667', 'name':'Serre Chevalier' },
'SEB': { 'latitude':'26.986944', 'longitude': '14.4725', 'name':'Sebha' },
'SEA': { 'latitude':'47.448889', 'longitude': '-122.309444', 'name':'Seattle-Tacoma International' },
'SEO': { 'latitude':'7.966667', 'longitude': '-6.666667', 'name':'Seguela' },
'SEN': { 'latitude':'51.569444', 'longitude': '0.7', 'name':'Southend' },
'SEM': { 'latitude':'-12.2', 'longitude': '96.916667', 'name':'Craig AFB' },
'SEK': { 'latitude':'31.95', 'longitude': '-4.4', 'name':'Er Errachidia' },
'SEJ': { 'latitude':'65.266667', 'longitude': '-14.0', 'name':'Seydisfjordur' },
'SEI': { 'latitude':'-10.45', 'longitude': '-40.183333', 'name':'Senhor Do Bonfim' },
'SEH': { 'latitude':'-3.433333', 'longitude': '140.816667', 'name':'Senggeh' },
'IMA': { 'latitude':'-9.5', 'longitude': '150.5', 'name':'Iamalele' },
'CLM': { 'latitude':'48.133333', 'longitude': '-123.5', 'name':'Fairchild Intl' },
'CLN': { 'latitude':'-7.35', 'longitude': '-47.433333', 'name':'Carolina' },
'IMB': { 'latitude':'5.716667', 'longitude': '-60.283333', 'name':'Imbaimadai' },
'CLH': { 'latitude':'-31.833333', 'longitude': '149.7', 'name':'Coolah' },
'IMD': { 'latitude':'-3.35', 'longitude': '141.516667', 'name':'Imonda' },
'CLJ': { 'latitude':'46.785278', 'longitude': '23.686111', 'name':'Cluj Napoca International Airport' },
'IMF': { 'latitude':'24.866667', 'longitude': '93.933333', 'name':'Municipal' },
'IMI': { 'latitude':'6.983333', 'longitude': '171.616667', 'name':'Ine Island' },
'CLE': { 'latitude':'41.416667', 'longitude': '-81.85', 'name':'Hopkins International' },
'IMK': { 'latitude':'29.966667', 'longitude': '81.833333', 'name':'Simikot' },
'CLG': { 'latitude':'36.15', 'longitude': '-120.35', 'name':'Coalinga' },
'IMM': { 'latitude':'26.416667', 'longitude': '-81.416667', 'name':'Immokalee' },
'IML': { 'latitude':'40.516667', 'longitude': '-101.616667', 'name':'Imperial' },
'IMO': { 'latitude':'5.033333', 'longitude': '25.133333', 'name':'Zemio' },
'IMN': { 'latitude':'-6.7', 'longitude': '146.083333', 'name':'Imane' },
'PDO': { 'latitude':'-3.283333', 'longitude': '103.833333', 'name':'Pendopo' },
'IMP': { 'latitude':'-5.5', 'longitude': '-47.416667', 'name':'Imperatriz' },
'PDL': { 'latitude':'37.741111', 'longitude': '-25.697778', 'name':'Nordela' },
'CLX': { 'latitude':'-25.333333', 'longitude': '-57.666667', 'name':'Clorinda' },
'IMT': { 'latitude':'45.816667', 'longitude': '-88.116667', 'name':'Ford' },
'CLZ': { 'latitude':'8.933333', 'longitude': '-67.433333', 'name':'Calabozo' },
'CLT': { 'latitude':'35.216667', 'longitude': '-80.933333', 'name':'Charlotte Douglas' },
'CLU': { 'latitude':'39.133333', 'longitude': '-85.933333', 'name':'Columbus Municipal' },
'CLV': { 'latitude':'-17.724722', 'longitude': '-48.61', 'name':'Caldas Novas' },
'CLW': { 'latitude':'50.433333', 'longitude': '-93.45', 'name':'Executive' },
'CLP': { 'latitude':'58.85', 'longitude': '-158.5', 'name':'Clarks Point' },
'CLQ': { 'latitude':'19.3', 'longitude': '-103.666667', 'name':'Colima' },
'CLR': { 'latitude':'33.133333', 'longitude': '-115.516667', 'name':'Calipatria' },
'CLS': { 'latitude':'46.683333', 'longitude': '-122.983333', 'name':'Centralia' },
'OMH': { 'latitude':'37.668056', 'longitude': '45.068611', 'name':'Urmieh' },
'BPA': { 'latitude':'40.75', 'longitude': '-73.483333', 'name':'Grumman' },
'BPC': { 'latitude':'6.05', 'longitude': '10.116667', 'name':'Bamenda' },
'BPB': { 'latitude':'-9.133333', 'longitude': '147.533333', 'name':'Boridi' },
'BPE': { 'latitude':'5.9', 'longitude': '16.466667', 'name':'Bagan' },
'BPD': { 'latitude':'-7.75', 'longitude': '147.016667', 'name':'Bapi' },
'BPG': { 'latitude':'-15.85', 'longitude': '-52.383333', 'name':'Barra Do Garcas' },
'BPF': { 'latitude':'-8.55', 'longitude': '158.116667', 'name':'Batuna Aerodrome' },
'BPI': { 'latitude':'42.583333', 'longitude': '-110.116667', 'name':'Big Piney-marbleton' },
'BPH': { 'latitude':'8.2', 'longitude': '126.366667', 'name':'Bislig' },
'BPK': { 'latitude':'-6.066667', 'longitude': '144.933333', 'name':'Biangabip' },
'BPN': { 'latitude':'-1.266667', 'longitude': '116.9', 'name':'Sepingan' },
'BPS': { 'latitude':'-16.438611', 'longitude': '-39.080833', 'name':'Porto Seguro' },
'BPU': { 'latitude':'33.3', 'longitude': '131.533333', 'name':'Beppu' },
'BPT': { 'latitude':'30.083333', 'longitude': '-94.1', 'name':'Jefferson County' },
'BPY': { 'latitude':'-16.75', 'longitude': '44.483333', 'name':'Besalampy' },
'BPX': { 'latitude':'30.539722', 'longitude': '97.108889', 'name':'Bangda' },
'GMN': { 'latitude':'-42.461667', 'longitude': '171.19', 'name':'Greymouth' },
'GMM': { 'latitude':'-1.933333', 'longitude': '15.866667', 'name':'Gamboma' },
'MLB': { 'latitude':'28.1', 'longitude': '-80.633333', 'name':'Melbourne International Airport' },
'GOL': { 'latitude':'42.416667', 'longitude': '-124.416667', 'name':'State' },
'GOO': { 'latitude':'-28.521389', 'longitude': '150.320278', 'name':'Goondiwindi' },
'GON': { 'latitude':'41.333333', 'longitude': '-72.05', 'name':'New London' },
'MLF': { 'latitude':'38.433333', 'longitude': '-113.016667', 'name':'Milford' },
'GOH': { 'latitude':'64.166667', 'longitude': '-51.716667', 'name':'Nuuk' },
'MLD': { 'latitude':'42.336111', 'longitude': '-112.3', 'name':'Malad City' },
'MLE': { 'latitude':'4.191944', 'longitude': '73.529167', 'name':'Male International' },
'GOE': { 'latitude':'-5.383333', 'longitude': '151.866667', 'name':'Gonalia' },
'MLK': { 'latitude':'48.35', 'longitude': '-107.866667', 'name':'Malta' },
'AJR': { 'latitude':'65.591389', 'longitude': '19.285556', 'name':'Arvidsjaur' },
'MLI': { 'latitude':'41.45', 'longitude': '-90.516667', 'name':'Quad-City' },
'MLN': { 'latitude':'35.283333', 'longitude': '-2.95', 'name':'Melilla' },
'MLO': { 'latitude':'36.716667', 'longitude': '24.533333', 'name':'Milos' },
'MLL': { 'latitude':'61.883333', 'longitude': '-162.066667', 'name':'Marshall' },
'GOB': { 'latitude':'7.133333', 'longitude': '40.133333', 'name':'Goba' },
'MLR': { 'latitude':'-37.633333', 'longitude': '140.583333', 'name':'Millicent' },
'MLS': { 'latitude':'46.433333', 'longitude': '-105.883333', 'name':'Municipal' },
'MLP': { 'latitude':'7.633333', 'longitude': '124.066667', 'name':'Malabang' },
'MLQ': { 'latitude':'-8.1', 'longitude': '146.166667', 'name':'Malalaua' },
'MLV': { 'latitude':'-13.066667', 'longitude': '142.45', 'name':'Merluna' },
'MLW': { 'latitude':'6.233333', 'longitude': '-10.366667', 'name':'Sprigg Payne' },
'MLT': { 'latitude':'45.65', 'longitude': '-68.7', 'name':'Millinocket' },
'MLU': { 'latitude':'32.5', 'longitude': '-92.033333', 'name':'Municipal' },
'MLZ': { 'latitude':'-32.333333', 'longitude': '-54.2', 'name':'Melo' },
'GOT': { 'latitude':'57.662778', 'longitude': '12.279722', 'name':'Landvetter' },
'MLX': { 'latitude':'38.35', 'longitude': '38.25', 'name':'Malatya' },
'MLY': { 'latitude':'65.0', 'longitude': '-150.633333', 'name':'Manley Hot Springs' },
'GOQ': { 'latitude':'36.4006', 'longitude': '94.7861', 'name':'Golmud' },
'GOP': { 'latitude':'26.733333', 'longitude': '83.45', 'name':'Gorakhpur' },
'GOS': { 'latitude':'-33.433333', 'longitude': '151.35', 'name':'Gosford' },
'GOR': { 'latitude':'8.166667', 'longitude': '35.55', 'name':'Gore' },
'NRK': { 'latitude':'58.616667', 'longitude': '16.083333', 'name':'Kungsangen' },
'NRI': { 'latitude':'36.566667', 'longitude': '-94.85', 'name':'Shangri-la' },
'NRN': { 'latitude':'51.6056', 'longitude': '6.15', 'name':'Dusseldorf Weeze' },
'NRM': { 'latitude':'15.25', 'longitude': '-7.283333', 'name':'Nara' },
'GMZ': { 'latitude':'28.088333', 'longitude': '-17.106667', 'name':'La Gomera' },
'NRC': { 'latitude':'37.4', 'longitude': '-121.066667', 'name':'Aux Field' },
'NRB': { 'latitude':'17.65', 'longitude': '120.583333', 'name':'Ns' },
'NRA': { 'latitude':'-34.7', 'longitude': '146.516667', 'name':'Narrandera' },
'NRG': { 'latitude':'-32.933333', 'longitude': '117.166667', 'name':'Narrogin' },
'GMY': { 'latitude':'51.15', 'longitude': '6.366667', 'name':'Rheindahlen' },
'NRD': { 'latitude':'53.708333', 'longitude': '7.15', 'name':'Norderney' },
'NRY': { 'latitude':'-16.083333', 'longitude': '129.341667', 'name':'Newry' },
'NRS': { 'latitude':'46.216667', 'longitude': '26.1', 'name':'NAS' },
'NRR': { 'latitude':'51.5', 'longitude': '4.5', 'name':'Roosevelt NAS' },
'NRV': { 'latitude':'13.463889', 'longitude': '144.763611', 'name':'USCG Shore Station' },
'NRT': { 'latitude':'35.763889', 'longitude': '140.391667', 'name':'New Tokyo International Airport' },
'DKV': { 'latitude':'-24.866667', 'longitude': '129.116667', 'name':'Docker River' },
'GMS': { 'latitude':'-2.133333', 'longitude': '-44.6', 'name':'Guimaraes' },
'GMR': { 'latitude':'-23.033333', 'longitude': '-134.966667', 'name':'Gambier Is' },
'DKS': { 'latitude':'73.516667', 'longitude': '80.366667', 'name':'Dikson' },
'GMP': { 'latitude':'37.558333', 'longitude': '126.790556', 'name':'Gimpo International' },
'GMV': { 'latitude':'-2.616667', 'longitude': '152.016667', 'name':'Monument Valley' },
'GMU': { 'latitude':'34.848056', 'longitude': '-82.35', 'name':'Greenville Downtown' },
'GMT': { 'latitude':'65.4', 'longitude': '-161.283333', 'name':'Granite Mountain' },
'KNN': { 'latitude':'10.4', 'longitude': '-9.3', 'name':'Kankan' },
'KNO': { 'latitude':'51.416667', 'longitude': '3.258333', 'name':'Knokke/Het Zoute' },
'KNL': { 'latitude':'-6.0', 'longitude': '147.5', 'name':'Kelanoa' },
'KNM': { 'latitude':'-7.583333', 'longitude': '24.15', 'name':'Kaniama' },
'KNJ': { 'latitude':'-3.733333', 'longitude': '14.216667', 'name':'Kindamba' },
'KNK': { 'latitude':'59.433333', 'longitude': '-154.85', 'name':'Kakhonak' },
'KNH': { 'latitude':'24.420556', 'longitude': '118.344444', 'name':'Shang-Yi' },
'KNI': { 'latitude':'-33.7', 'longitude': '117.55', 'name':'Katanning' },
'KNF': { 'latitude':'51.366667', 'longitude': '-0.283333', 'name':'Marham RAF' },
'KNG': { 'latitude':'-3.716667', 'longitude': '133.916667', 'name':'Kaimana' },
'KND': { 'latitude':'-2.919167', 'longitude': '25.915278', 'name':'Kindu' },
'KNE': { 'latitude':'-5.283333', 'longitude': '144.7', 'name':'Kanainj' },
'KNB': { 'latitude':'37.25', 'longitude': '-112.833333', 'name':'Kanab' },
'KNA': { 'latitude':'-33.008056', 'longitude': '-71.519722', 'name':'Vina del Mar' },
'KNZ': { 'latitude':'12.833333', 'longitude': '-11.25', 'name':'Kenieba' },
'KNX': { 'latitude':'-15.833333', 'longitude': '128.75', 'name':'Kununurra' },
'KNY': { 'latitude':'-1.25', 'longitude': '36.7', 'name':'Kinoosao' },
'KNV': { 'latitude':'60.583333', 'longitude': '-64.583333', 'name':'Knights Inlet' },
'KNW': { 'latitude':'59.533333', 'longitude': '-157.333333', 'name':'New Stuyahok' },
'KNT': { 'latitude':'36.233333', 'longitude': '-90.05', 'name':'Municipal' },
'KNU': { 'latitude':'26.433333', 'longitude': '80.366667', 'name':'Kanpur' },
'KNR': { 'latitude':'27.816667', 'longitude': '52.35', 'name':'Jam' },
'KNS': { 'latitude':'-39.883056', 'longitude': '143.883056', 'name':'King Island' },
'KNP': { 'latitude':'-9.766944', 'longitude': '15.450278', 'name':'Capanda' },
'KNQ': { 'latitude':'-21.0', 'longitude': '164.675', 'name':'Kone' },
'LXV': { 'latitude':'39.333333', 'longitude': '-106.5', 'name':'Leadville' },
'LXU': { 'latitude':'-14.366667', 'longitude': '23.266667', 'name':'Lukulu' },
'LXS': { 'latitude':'39.916667', 'longitude': '25.233889', 'name':'Limnos' },
'LXR': { 'latitude':'25.683333', 'longitude': '32.7', 'name':'Luxor' },
'LXG': { 'latitude':'20.966667', 'longitude': '101.4', 'name':'Luang Namtha' },
'LXA': { 'latitude':'29.293056', 'longitude': '90.900278', 'name':'Gonggar/Lhasa' },
'LXN': { 'latitude':'40.783333', 'longitude': '-99.75', 'name':'Lexington' },
'LXI': { 'latitude':'25.95', 'longitude': '109.616667', 'name':'Linxi' },
'YKC': { 'latitude':'58.233333', 'longitude': '-103.666667', 'name':'Collins Bay' },
'YKA': { 'latitude':'50.716667', 'longitude': '-120.416667', 'name':'Kamloops' },
'YKG': { 'latitude':'60.027222', 'longitude': '-69.999167', 'name':'Kangirsuk' },
'YKF': { 'latitude':'43.460833', 'longitude': '-80.378611', 'name':'Kitchener-Waterloo Regional' },
'YKE': { 'latitude':'55.05', 'longitude': '-94.666667', 'name':'Knee Lake' },
'YKD': { 'latitude':'44.201389', 'longitude': '-81.606667', 'name':'Township Airport' },
'YKK': { 'latitude':'53.0', 'longitude': '-130.0', 'name':'Kitkatla' },
'YKJ': { 'latitude':'57.25', 'longitude': '-105.6', 'name':'Key Lake' },
'YKI': { 'latitude':'58.977222', 'longitude': '23.863333', 'name':'Kennosao Lake' },
'YKN': { 'latitude':'42.916667', 'longitude': '-97.383333', 'name':'Chan Gurney' },
'YKM': { 'latitude':'46.566667', 'longitude': '-120.533333', 'name':'Yakima Air Terminal' },
'YKL': { 'latitude':'54.783333', 'longitude': '-64.816667', 'name':'Schefferville' },
'YKS': { 'latitude':'62.083333', 'longitude': '129.766667', 'name':'Yakutsk' },
'YKQ': { 'latitude':'51.4875', 'longitude': '-78.75', 'name':'Waskaganish' },
'YKU': { 'latitude':'53.816667', 'longitude': '-79.0', 'name':'Chisasibi' },
'YKT': { 'latitude':'52.6', 'longitude': '-128.516667', 'name':'Klemtu' },
'YKZ': { 'latitude':'43.862222', 'longitude': '-79.37', 'name':'Buttonville Municipal' },
'YKY': { 'latitude':'51.45', 'longitude': '-109.166667', 'name':'Kindersley' },
'YKX': { 'latitude':'48.210278', 'longitude': '-79.981389', 'name':'Kirkland Lake' },
'VTG': { 'latitude':'10.35', 'longitude': '107.066667', 'name':'Vung Tau' },
'ZBF': { 'latitude':'47.6', 'longitude': '-65.65', 'name':'Bathurst' },
'ZBE': { 'latitude':'49.928333', 'longitude': '18.071111', 'name':'Dolni Benesov' },
'ZBD': { 'latitude':'28.739167', 'longitude': '118.622778', 'name':'Jiang Men Ferry' },
'ZBC': { 'latitude':'52.466667', 'longitude': '-1.916667', 'name':'Colmore Row Bus Stn' },
'ZBA': { 'latitude':'47.416667', 'longitude': '7.75', 'name':'Basel Bad - Railway' },
'ZBO': { 'latitude':'-20.016667', 'longitude': '148.216667', 'name':'Bowen' },
'ZBN': { 'latitude':'46.716667', 'longitude': '11.5', 'name':'Bus Station' },
'ZBM': { 'latitude':'45.297222', 'longitude': '-72.747222', 'name':'Bromont' },
'ZBL': { 'latitude':'-24.4', 'longitude': '150.5', 'name':'Biloela' },
'ZBK': { 'latitude':'43.116667', 'longitude': '19.233333', 'name':'Zabljak' },
'ZBR': { 'latitude':'25.3', 'longitude': '60.616667', 'name':'Chah-Bahar' },
'ZBP': { 'latitude':'4.666667', 'longitude': '-74.516667', 'name':'Baltimore Rail' },
'ZBZ': { 'latitude':'44.018333', 'longitude': '114.955556', 'name':'Xin Hui Ferry' },
'ZBY': { 'latitude':'19.25', 'longitude': '101.7', 'name':'Sayaboury' },
'WAO': { 'latitude':'-7.666667', 'longitude': '145.0', 'name':'Wabo' },
'WAN': { 'latitude':'-25.366667', 'longitude': '141.933333', 'name':'Waverney' },
'WAM': { 'latitude':'-17.8', 'longitude': '48.433333', 'name':'Ambatondrazaka' },
'WAL': { 'latitude':'37.933333', 'longitude': '-75.383333', 'name':'Wallops Flight Center' },
'WAK': { 'latitude':'-22.3', 'longitude': '44.533333', 'name':'Ankazoabo' },
'WAJ': { 'latitude':'-6.95', 'longitude': '142.65', 'name':'Wawoi Falls' },
'WAI': { 'latitude':'-14.916667', 'longitude': '47.95', 'name':'Antsohihy' },
'WAH': { 'latitude':'46.266667', 'longitude': '-96.6', 'name':'Wahpeton' },
'WAG': { 'latitude':'-39.966667', 'longitude': '175.016667', 'name':'Wanganui' },
'WAF': { 'latitude':'32.283333', 'longitude': '69.566667', 'name':'Wana' },
'WAE': { 'latitude':'20.5', 'longitude': '45.166667', 'name':'Wadi Ad Dawasir' },
'WAD': { 'latitude':'-17.45', 'longitude': '47.516667', 'name':'Andriamena' },
'WAC': { 'latitude':'7.166667', 'longitude': '37.166667', 'name':'Waca' },
'MPA': { 'latitude':'-17.5', 'longitude': '24.266667', 'name':'Mpacha' },
'WAA': { 'latitude':'65.666667', 'longitude': '-168.083333', 'name':'Wales' },
'WAZ': { 'latitude':'-28.15', 'longitude': '151.95', 'name':'Warwick' },
'WAY': { 'latitude':'39.9', 'longitude': '-80.144167', 'name':'Greene County' },
'WAX': { 'latitude':'48.9', 'longitude': '-95.3', 'name':'Zwara' },
'WAW': { 'latitude':'52.166667', 'longitude': '20.966667', 'name':'Frederic Chopin' },
'RNO': { 'latitude':'39.499167', 'longitude': '-119.768056', 'name':'Reno-Tahoe International' },
'WAU': { 'latitude':'-31.45', 'longitude': '152.733333', 'name':'Wauchope' },
'WAT': { 'latitude':'52.197222', 'longitude': '-7.088889', 'name':'Waterford' },
'WAR': { 'latitude':'-3.233333', 'longitude': '140.983333', 'name':'Waris' },
'WAQ': { 'latitude':'-18.7', 'longitude': '44.616667', 'name':'Antsalova' },
'RNN': { 'latitude':'55.066667', 'longitude': '14.75', 'name':'Bornholm' },
'HBE': { 'latitude':'30.917778', 'longitude': '29.696389', 'name':'Amiryah West' },
'RNE': { 'latitude':'46.016667', 'longitude': '4.016667', 'name':'Renaison' },
'VTF': { 'latitude':'-18.55', 'longitude': '177.616667', 'name':'Vatulele' },
'RND': { 'latitude':'6.233333', 'longitude': '-76.733333', 'name':'Randolph AFB' },
'XXU': { 'latitude':'60.283333', 'longitude': '15.983333', 'name':'Hedemora' },
'RNZ': { 'latitude':'40.95', 'longitude': '-87.15', 'name':'Rensselaer' },
'XXK': { 'latitude':'59.016667', 'longitude': '16.216667', 'name':'Katrineholm' },
'XXJ': { 'latitude':'47.466667', 'longitude': '19.1', 'name':'Deli Railway' },
'RNS': { 'latitude':'48.066667', 'longitude': '-1.733333', 'name':'St Jacques' },
'RNR': { 'latitude':'-10.15', 'longitude': '148.816667', 'name':'Robinson River' },
'RNP': { 'latitude':'11.15', 'longitude': '166.883333', 'name':'Rongelap Island' },
'RNU': { 'latitude':'5.95', 'longitude': '116.666667', 'name':'Ranau' },
'RNT': { 'latitude':'47.493056', 'longitude': '-122.215833', 'name':'Renton' },
'SXA': { 'latitude':'-6.1', 'longitude': '147.6', 'name':'Sialum' },
'SXB': { 'latitude':'48.583333', 'longitude': '7.633333', 'name':'Entzheim' },
'SXC': { 'latitude':'-21.583333', 'longitude': '-67.583333', 'name':'Avalo Vor/WP' },
'SXD': { 'latitude':'43.616667', 'longitude': '7.05', 'name':'Sophia Antipolis' },
'SXE': { 'latitude':'-38.083333', 'longitude': '146.966667', 'name':'Sale' },
'SXF': { 'latitude':'52.502778', 'longitude': '13.508611', 'name':'Schönefeld' },
'SXG': { 'latitude':'-16.1', 'longitude': '23.266667', 'name':'Senanga' },
'SXH': { 'latitude':'-10.216667', 'longitude': '150.35', 'name':'Sehulea' },
'SXI': { 'latitude':'25.916667', 'longitude': '54.533333', 'name':'Sirri Island' },
'SXJ': { 'latitude':'42.816667', 'longitude': '90.233333', 'name':'Shanshan' },
'SXK': { 'latitude':'-7.966667', 'longitude': '131.316667', 'name':'Saumlaki' },
'SXL': { 'latitude':'54.280278', 'longitude': '-8.599167', 'name':'Collooney' },
'SXM': { 'latitude':'18.040833', 'longitude': '-63.108889', 'name':'Princess Juliana International' },
'SXN': { 'latitude':'-20.55', 'longitude': '26.116667', 'name':'Suapan' },
'SXO': { 'latitude':'-11.633333', 'longitude': '-50.666667', 'name':'Sao Felix Do Araguaia' },
'SXP': { 'latitude':'62.533333', 'longitude': '-164.833333', 'name':'Sheldon SPB' },
'SXQ': { 'latitude':'60.483333', 'longitude': '-151.066667', 'name':'Soldotna' },
'SXR': { 'latitude':'33.983333', 'longitude': '74.783333', 'name':'Srinagar' },
'SXS': { 'latitude':'5.089722', 'longitude': '119.091667', 'name':'Sahabat 16' },
'SXT': { 'latitude':'4.330833', 'longitude': '102.396667', 'name':'Taman Negara' },
'SXU': { 'latitude':'6.833333', 'longitude': '37.75', 'name':'Soddu' },
'SXV': { 'latitude':'11.65', 'longitude': '78.166667', 'name':'Salem' },
'SXW': { 'latitude':'65.483333', 'longitude': '12.133333', 'name':'Sauren' },
'HBB': { 'latitude':'-18.999722', 'longitude': '142.0', 'name':'Industrial Airpark' },
'SXY': { 'latitude':'42.316667', 'longitude': '-75.4', 'name':'Sidney' },
'SXZ': { 'latitude':'37.833333', 'longitude': '42.166667', 'name':'Siirt' },
'VVC': { 'latitude':'4.083333', 'longitude': '-73.55', 'name':'La Vanguardia' },
'VVB': { 'latitude':'-19.833333', 'longitude': '48.8', 'name':'Mahanoro' },
'YVT': { 'latitude':'55.841944', 'longitude': '-108.4175', 'name':'Buffalo Narrows' },
'YVV': { 'latitude':'44.745833', 'longitude': '-81.107222', 'name':'Wiarton/Keppel Airport' },
'YVP': { 'latitude':'58.15', 'longitude': '-68.45', 'name':'Kuujjuaq' },
'YVQ': { 'latitude':'65.283333', 'longitude': '-126.8', 'name':'Norman Wells' },
'YVR': { 'latitude':'49.193889', 'longitude': '-123.183333', 'name':'Vancouver Intl' },
'PYY': { 'latitude':'19.358889', 'longitude': '98.436667', 'name':'Pai' },
'YVZ': { 'latitude':'52.666667', 'longitude': '-94.5', 'name':'Deer Lake' },
'YVD': { 'latitude':'-7.55', 'longitude': '146.166667', 'name':'Yeva' },
'YVE': { 'latitude':'50.25', 'longitude': '-119.333333', 'name':'Vernon Regional Airport' },
'JVI': { 'latitude':'40.524444', 'longitude': '-74.598333', 'name':'Central Jersey Regional Airport' },
'YVG': { 'latitude':'53.366667', 'longitude': '-110.85', 'name':'Vermilion' },
'YVA': { 'latitude':'-11.7', 'longitude': '43.233333', 'name':'Iconi' },
'YVB': { 'latitude':'48.071111', 'longitude': '-65.460278', 'name':'Bonaventure' },
'JVL': { 'latitude':'42.616667', 'longitude': '-89.033333', 'name':'Rock County' },
'YVM': { 'latitude':'67.55', 'longitude': '-64.033333', 'name':'Qikiqtarjuaq' },
'JVA': { 'latitude':'-18.8', 'longitude': '45.283333', 'name':'Ankavandra' },
'YVO': { 'latitude':'48.052778', 'longitude': '-77.782778', 'name':'Val D\'Or' },
'PYR': { 'latitude':'37.683333', 'longitude': '21.466667', 'name':'Andravida' },
'KLD': { 'latitude':'47.383333', 'longitude': '40.433333', 'name':'Migalovo' },
'KLF': { 'latitude':'54.5', 'longitude': '36.266667', 'name':'Kaluga' },
'KLG': { 'latitude':'61.533333', 'longitude': '-160.366667', 'name':'Municipal' },
'PYV': { 'latitude':'8.133333', 'longitude': '-77.7', 'name':'Yaviza' },
'QVL': { 'latitude':'6.423889', 'longitude': '3.416944', 'name':'Victoria Island' },
'KLC': { 'latitude':'14.083333', 'longitude': '-16.5', 'name':'Kaolack' },
'QVY': { 'latitude':'60.866667', 'longitude': '26.7', 'name':'Bus Station' },
'PYM': { 'latitude':'41.966667', 'longitude': '-70.683333', 'name':'Plymouth' },
'TRI': { 'latitude':'36.475278', 'longitude': '-82.4075', 'name':'Tri-cities Regional' },
'TRH': { 'latitude':'35.8125', 'longitude': '-117.327222', 'name':'Trona' },
'TRK': { 'latitude':'3.326667', 'longitude': '117.565556', 'name':'Juwata' },
'TRJ': { 'latitude':'-4.6', 'longitude': '143.316667', 'name':'Tarakbits' },
'TRM': { 'latitude':'46.591111', 'longitude': '13.825556', 'name':'Thermal' },
'PYN': { 'latitude':'1.8', 'longitude': '-78.166667', 'name':'Payan' },
'TRO': { 'latitude':'-31.9', 'longitude': '152.466667', 'name':'Taree' },
'TRN': { 'latitude':'45.200833', 'longitude': '7.649722', 'name':'Sandro Pertini' },
'TRA': { 'latitude':'24.65', 'longitude': '124.7', 'name':'Tarama' },
'TRC': { 'latitude':'25.568333', 'longitude': '-103.410556', 'name':'Francisco Sarabia' },
'PYO': { 'latitude':'0.066667', 'longitude': '-75.866667', 'name':'Putumayo' },
'TRE': { 'latitude':'56.5', 'longitude': '-6.916667', 'name':'Tiree' },
'TRD': { 'latitude':'63.457778', 'longitude': '10.936111', 'name':'Værnes' },
'TRG': { 'latitude':'-37.670833', 'longitude': '176.194444', 'name':'Tauranga' },
'TRF': { 'latitude':'59.186667', 'longitude': '10.258611', 'name':'Sandefjord' },
'TRY': { 'latitude':'-0.684722', 'longitude': '34.183056', 'name':'Tororo' },
'TRX': { 'latitude':'44.1', 'longitude': '-77.583333', 'name':'Memorial' },
'TRZ': { 'latitude':'10.765', 'longitude': '78.713333', 'name':'Tiruchirapally' },
'TRQ': { 'latitude':'-8.166667', 'longitude': '-70.766667', 'name':'Tarauaca' },
'TRP': { 'latitude':'39.983333', 'longitude': '25.266667', 'name':'Coast Guard Heliport' },
'TRS': { 'latitude':'45.826667', 'longitude': '13.472222', 'name':'Ronchi Dei Legionari' },
'TRR': { 'latitude':'8.566667', 'longitude': '81.233333', 'name':'China Bay' },
'TRU': { 'latitude':'-8.09', 'longitude': '-79.115', 'name':'Trujillo' },
'TRT': { 'latitude':'-7.8', 'longitude': '-38.283333', 'name':'Tremonton' },
'TRW': { 'latitude':'1.381667', 'longitude': '173.146944', 'name':'Bonriki' },
'TRV': { 'latitude':'8.482222', 'longitude': '76.92', 'name':'Thiruvananthapuram International' },
'HTG': { 'latitude':'71.966667', 'longitude': '102.5', 'name':'Hatanga' },
'KLT': { 'latitude':'49.433333', 'longitude': '7.75', 'name':'Kaiserslautern' },
'HTB': { 'latitude':'15.883333', 'longitude': '-61.216667', 'name':'Terre-de-Bas' },
'HTA': { 'latitude':'52.033333', 'longitude': '113.3', 'name':'Chita' },
'KLU': { 'latitude':'46.645', 'longitude': '14.326667', 'name':'Alpe Adria' },
'HTO': { 'latitude':'40.966667', 'longitude': '-72.233333', 'name':'East Hampton' },
'HTN': { 'latitude':'37.5', 'longitude': '78.5', 'name':'Hotan' },
'HTM': { 'latitude':'50.451944', 'longitude': '100.166944', 'name':'Khatgal' },
'HTL': { 'latitude':'52.333333', 'longitude': '-1.716667', 'name':'Roscommon County' },
'KLV': { 'latitude':'50.5', 'longitude': '12.841667', 'name':'Karlovy Vary' },
'HTI': { 'latitude':'-20.358056', 'longitude': '148.951667', 'name':'Hamilton Island' },
'HTH': { 'latitude':'38.535278', 'longitude': '-118.633611', 'name':'Hawthorne' },
'HTW': { 'latitude':'42.2525', 'longitude': '-82.494444', 'name':'Lawrence County Airpark' },
'HTU': { 'latitude':'-35.716667', 'longitude': '142.35', 'name':'Hopetoun' },
'KLW': { 'latitude':'55.55', 'longitude': '-133.1', 'name':'Klawock' },
'HTS': { 'latitude':'38.35', 'longitude': '-82.533333', 'name':'Tri-State/Milton' },
'HTR': { 'latitude':'24.05', 'longitude': '123.783333', 'name':'Hateruma' },
'KLP': { 'latitude':'57.558333', 'longitude': '-134.866667', 'name':'Kelp Bay' },
'HTZ': { 'latitude':'6.166667', 'longitude': '-71.75', 'name':'Hato Corozal' },
'HTY': { 'latitude':'36.5736', 'longitude': '36.1539', 'name':'Hatay' },
'KLQ': { 'latitude':'-2.6', 'longitude': '103.95', 'name':'Keluang' },
'HDR': { 'latitude':'46.483333', 'longitude': '24.833333', 'name':'Havadarya' },
'ODY': { 'latitude':'20.583333', 'longitude': '104.166667', 'name':'Oudomxai' },
'UEO': { 'latitude':'26.366667', 'longitude': '126.716667', 'name':'Kumejima' },
'UEE': { 'latitude':'-42.0', 'longitude': '145.508333', 'name':'Queenstown' },
'KLX': { 'latitude':'37.068333', 'longitude': '22.025556', 'name':'Kalamata' },
'ODR': { 'latitude':'-17.35', 'longitude': '128.9', 'name':'Ord River' },
'ODS': { 'latitude':'46.5', 'longitude': '30.616667', 'name':'Odessa International' },
'ODW': { 'latitude':'48.283333', 'longitude': '-122.616667', 'name':'Oak Harbor' },
'ODH': { 'latitude':'51.25', 'longitude': '-0.933333', 'name':'RAF Station' },
'ODJ': { 'latitude':'8.916667', 'longitude': '22.583333', 'name':'Ouanda Djalle' },
'ODL': { 'latitude':'-26.833333', 'longitude': '140.75', 'name':'Cordillo Downs' },
'KLZ': { 'latitude':'-29.683333', 'longitude': '17.066667', 'name':'Kleinzee' },
'ODN': { 'latitude':'4.033333', 'longitude': '115.066667', 'name':'Long Seridan' },
'ODA': { 'latitude':'8.0', 'longitude': '22.416667', 'name':'Ouadda' },
'ODB': { 'latitude':'37.85', 'longitude': '-4.85', 'name':'Cordoba' },
'ODD': { 'latitude':'-27.55', 'longitude': '135.433333', 'name':'Oodnadatta' },
'ODE': { 'latitude':'55.476667', 'longitude': '10.330833', 'name':'Beldringe' },
'UES': { 'latitude':'43.016667', 'longitude': '-88.2', 'name':'Waukesha' },
'UER': { 'latitude':'38.683333', 'longitude': '-4.116667', 'name':'Puertollano' },
'ELJ': { 'latitude':'2.0', 'longitude': '-74.133333', 'name':'El Recreo' },
'ELK': { 'latitude':'35.4', 'longitude': '-99.416667', 'name':'Municipal' },
'ELH': { 'latitude':'25.483333', 'longitude': '-76.683333', 'name':'International' },
'ELI': { 'latitude':'64.616667', 'longitude': '-162.266667', 'name':'Elim' },
'ELN': { 'latitude':'47.033333', 'longitude': '-120.533333', 'name':'Bowers Field' },
'ELO': { 'latitude':'-26.4', 'longitude': '-54.633333', 'name':'Eldorado' },
'ELL': { 'latitude':'-23.666667', 'longitude': '27.616667', 'name':'Ellisras' },
'ELM': { 'latitude':'42.166667', 'longitude': '-76.9', 'name':'Elmira Corning Regional' },
'ELB': { 'latitude':'9.05', 'longitude': '-73.966667', 'name':'San Bernado' },
'ELC': { 'latitude':'-12.016667', 'longitude': '135.566667', 'name':'Elcho Island' },
'ELA': { 'latitude':'29.583333', 'longitude': '-96.333333', 'name':'Eagle Lake' },
'ELF': { 'latitude':'13.616667', 'longitude': '25.316667', 'name':'El Fasher' },
'ELG': { 'latitude':'30.571389', 'longitude': '2.859722', 'name':'Djamet' },
'ELD': { 'latitude':'33.216667', 'longitude': '-92.816667', 'name':'Goodwin Field' },
'ELE': { 'latitude':'8.116667', 'longitude': '-77.716667', 'name':'El Real' },
'ELZ': { 'latitude':'42.116667', 'longitude': '-77.933333', 'name':'Municipal' },
'RDD': { 'latitude':'40.5', 'longitude': '-122.3', 'name':'Redding' },
'ELX': { 'latitude':'10.616667', 'longitude': '-71.733333', 'name':'El Tigre' },
'ELY': { 'latitude':'39.3', 'longitude': '-114.85', 'name':'Yelland' },
'RDA': { 'latitude':'-18.95', 'longitude': '135.2', 'name':'Rockhampton Downs' },
'RDC': { 'latitude':'-8.030278', 'longitude': '-49.98', 'name':'Redencao' },
'RDB': { 'latitude':'68.032222', 'longitude': '-162.899167', 'name':'Red Dog' },
'ELR': { 'latitude':'7.816667', 'longitude': '40.516667', 'name':'Elelim' },
'ELS': { 'latitude':'-33.05', 'longitude': '27.816667', 'name':'East London' },
'ELP': { 'latitude':'31.8', 'longitude': '-106.383333', 'name':'El Paso International Airport' },
'ELQ': { 'latitude':'26.3', 'longitude': '43.816667', 'name':'Gassim Regional Airport' },
'ELV': { 'latitude':'58.183333', 'longitude': '-136.316667', 'name':'Elfin Cove SPB' },
'ELW': { 'latitude':'60.897222', 'longitude': '-146.6125', 'name':'Ellamar' },
'ELT': { 'latitude':'52.368333', 'longitude': '-9.144167', 'name':'Tour Sinai City' },
'ELU': { 'latitude':'33.516667', 'longitude': '6.783333', 'name':'Guemar' },
'FBS': { 'latitude':'48.543611', 'longitude': '-123.006111', 'name':'Friday Harbor SPB' },
'FBR': { 'latitude':'41.316667', 'longitude': '-110.383333', 'name':'Fort Bridger' },
'LEB': { 'latitude':'43.633333', 'longitude': '-72.316667', 'name':'White River' },
'LEC': { 'latitude':'-12.48', 'longitude': '-41.281111', 'name':'Lencois Chapada Diamantina' },
'LED': { 'latitude':'59.95', 'longitude': '30.05', 'name':'Pulkovo' },
'LEE': { 'latitude':'28.833333', 'longitude': '-81.816667', 'name':'Leesburg' },
'LEF': { 'latitude':'-29.783333', 'longitude': '28.583333', 'name':'Lebakeng' },
'LEG': { 'latitude':'17.166667', 'longitude': '-13.95', 'name':'Aleg' },
'LEH': { 'latitude':'49.533333', 'longitude': '0.083333', 'name':'Octeville' },
'LEI': { 'latitude':'36.833333', 'longitude': '-2.45', 'name':'Almeria' },
'FBY': { 'latitude':'40.133333', 'longitude': '-97.183333', 'name':'Municipal' },
'LEK': { 'latitude':'11.328333', 'longitude': '-12.300833', 'name':'Labe' },
'LEL': { 'latitude':'-12.216667', 'longitude': '136.25', 'name':'Lake Evella' },
'HDE': { 'latitude':'40.433333', 'longitude': '-99.366667', 'name':'Brewster Field' },
'LEN': { 'latitude':'42.584444', 'longitude': '-5.650833', 'name':'Leon' },
'LEO': { 'latitude':'-1.683333', 'longitude': '14.3', 'name':'Leconi' },
'LEP': { 'latitude':'-21.516111', 'longitude': '-42.654722', 'name':'Leopoldina' },
'LEQ': { 'latitude':'50.1', 'longitude': '-5.666667', 'name':'Lands End' },
'LER': { 'latitude':'-27.833333', 'longitude': '120.616667', 'name':'Leinster' },
'LES': { 'latitude':'-29.8', 'longitude': '28.133333', 'name':'Lesobeng' },
'FBG': { 'latitude':'19.833333', 'longitude': '-72.5', 'name':'Simmons AAF' },
'LEU': { 'latitude':'42.338611', 'longitude': '1.409167', 'name':'Aeroport De La Seu' },
'FBE': { 'latitude':'-26.083333', 'longitude': '-53.066667', 'name':'Francisco Beltrao' },
'FBD': { 'latitude':'37.083333', 'longitude': '70.5', 'name':'Faizabad' },
'FBK': { 'latitude':'-32.533333', 'longitude': '26.7', 'name':'Ft Wainwright' },
'LEY': { 'latitude':'52.460278', 'longitude': '5.527222', 'name':'Lelystad' },
'LEZ': { 'latitude':'14.2', 'longitude': '-88.166667', 'name':'La Esperanza' },
'FBM': { 'latitude':'-11.583333', 'longitude': '27.516667', 'name':'Luano' },
'FBL': { 'latitude':'44.333333', 'longitude': '-93.316667', 'name':'Municipal' },
'HDA': { 'latitude':'57.066667', 'longitude': '-134.983333', 'name':'Hidden Falls' },
'SGY': { 'latitude':'59.483333', 'longitude': '-135.3', 'name':'Municipal' },
'SGX': { 'latitude':'-10.683333', 'longitude': '35.583333', 'name':'Songea' },
'SGZ': { 'latitude':'7.333333', 'longitude': '100.533333', 'name':'Songkhla' },
'SGQ': { 'latitude':'0.5', 'longitude': '117.333333', 'name':'Sanggata' },
'SGP': { 'latitude':'-20.483333', 'longitude': '120.1', 'name':'Shay Gap' },
'SGS': { 'latitude':'5.233333', 'longitude': '121.15', 'name':'Sanga Sanga' },
'SGR': { 'latitude':'29.622222', 'longitude': '-95.656667', 'name':'Sugar Land Regional' },
'SGU': { 'latitude':'37.083333', 'longitude': '-113.6', 'name':'Municipal' },
'SGT': { 'latitude':'34.599444', 'longitude': '-91.575', 'name':'Stuttgart Municipal' },
'SGW': { 'latitude':'56.866667', 'longitude': '-134.15', 'name':'Saginaw Bay' },
'SGV': { 'latitude':'-41.5', 'longitude': '-65.35', 'name':'Sierra Grande' },
'SGI': { 'latitude':'32.083333', 'longitude': '72.666667', 'name':'Sargodha Apt' },
'SGH': { 'latitude':'44.633333', 'longitude': '-64.85', 'name':'Springfield' },
'SGK': { 'latitude':'-5.083333', 'longitude': '144.766667', 'name':'Sangapi' },
'SGJ': { 'latitude':'-10.383333', 'longitude': '149.833333', 'name':'Sagarai' },
'SGM': { 'latitude':'27.283333', 'longitude': '-112.933333', 'name':'San Ignacio' },
'SGL': { 'latitude':'14.495278', 'longitude': '120.904167', 'name':'Sangley Point NAS' },
'SGO': { 'latitude':'-28.083333', 'longitude': '148.75', 'name':'St George' },
'SGN': { 'latitude':'10.818889', 'longitude': '106.651944', 'name':'Tan Son Nhat International' },
'SGA': { 'latitude':'38.033333', 'longitude': '71.716667', 'name':'Sheghnan' },
'SGC': { 'latitude':'61.233333', 'longitude': '73.333333', 'name':'Surgut' },
'SGB': { 'latitude':'-6.7', 'longitude': '147.133333', 'name':'Singaua' },
'SGE': { 'latitude':'50.707778', 'longitude': '8.083056', 'name':'Siegerland Airport' },
'SGD': { 'latitude':'54.95', 'longitude': '9.766667', 'name':'Sonderborg' },
'SGG': { 'latitude':'1.216667', 'longitude': '111.45', 'name':'Simanggang' },
'SGF': { 'latitude':'37.25', 'longitude': '-93.383333', 'name':'Springfield-Branson Rg' },
'CNV': { 'latitude':'-15.633333', 'longitude': '-38.866667', 'name':'Canavieiras' },
'CNW': { 'latitude':'31.637778', 'longitude': '-97.074167', 'name':'TSTC Waco Airport' },
'CNT': { 'latitude':'-27.216667', 'longitude': '-61.216667', 'name':'Charata' },
'CNU': { 'latitude':'37.683333', 'longitude': '-95.45', 'name':'Martin Johnson' },
'ICO': { 'latitude':'11.45', 'longitude': '123.266667', 'name':'Sicogon Island' },
'CNS': { 'latitude':'-16.883333', 'longitude': '145.75', 'name':'Cairns' },
'CNP': { 'latitude':'70.743056', 'longitude': '-22.658333', 'name':'Neerlerit Inaat' },
'CNQ': { 'latitude':'-27.45', 'longitude': '-58.766667', 'name':'Camba Punta' },
'ICA': { 'latitude':'4.333333', 'longitude': '-61.733333', 'name':'Icabaru' },
'VSG': { 'latitude':'48.566667', 'longitude': '39.333333', 'name':'Lugansk' },
'CNZ': { 'latitude':'-13.683333', 'longitude': '19.883333', 'name':'Cangamba' },
'CNX': { 'latitude':'18.768333', 'longitude': '98.962778', 'name':'Chiang Mai International' },
'CNY': { 'latitude':'38.766667', 'longitude': '-109.75', 'name':'Canyonlands Field' },
'CNF': { 'latitude':'-19.633611', 'longitude': '-43.968889', 'name':'Tancredo Neves International' },
'CNG': { 'latitude':'45.7', 'longitude': '-0.333333', 'name':'Parvaud' },
'CND': { 'latitude':'44.362222', 'longitude': '28.488333', 'name':'Kogalniceanu' },
'CNE': { 'latitude':'38.416667', 'longitude': '-105.1', 'name':'Canon City' },
'CNB': { 'latitude':'-30.983333', 'longitude': '148.383333', 'name':'Coonamble' },
'CNC': { 'latitude':'-10.05', 'longitude': '143.066667', 'name':'Coconut Island' },
'CNA': { 'latitude':'30.983333', 'longitude': '-110.266667', 'name':'Cananea' },
'CNO': { 'latitude':'34.016667', 'longitude': '-117.7', 'name':'Chino' },
'CNL': { 'latitude':'57.483333', 'longitude': '10.216667', 'name':'Sindal' },
'CNM': { 'latitude':'32.333333', 'longitude': '-104.266667', 'name':'Carlsbad' },
'CNJ': { 'latitude':'-20.668611', 'longitude': '140.504444', 'name':'Cloncurry' },
'CNK': { 'latitude':'39.55', 'longitude': '-97.65', 'name':'Blosser Municipal' },
'CNH': { 'latitude':'43.366667', 'longitude': '-72.366667', 'name':'Municipal' },
'ICT': { 'latitude':'37.65', 'longitude': '-97.433333', 'name':'Mid-Continent' },
'PFA': { 'latitude':'58.681389', 'longitude': '-156.8375', 'name':'Paf Warren' },
'PFC': { 'latitude':'45.199722', 'longitude': '-123.962222', 'name':'Pacific City State' },
'PFB': { 'latitude':'-28.25', 'longitude': '-52.333333', 'name':'Passo Fundo' },
'PFD': { 'latitude':'57.95', 'longitude': '-135.65', 'name':'Port Frederick' },
'PFJ': { 'latitude':'65.6', 'longitude': '-23.983333', 'name':'Patreksfjordur' },
'DXR': { 'latitude':'41.371667', 'longitude': '-73.482222', 'name':'Danbury Municipal Airport' },
'PFO': { 'latitude':'34.718056', 'longitude': '32.485833', 'name':'International' },
'PFN': { 'latitude':'30.216667', 'longitude': '-85.683333', 'name':'Bay County' },
'PFQ': { 'latitude':'39.620833', 'longitude': '47.857778', 'name':'Parsabad' },
'PFR': { 'latitude':'-4.316667', 'longitude': '20.566667', 'name':'Ilebo' },
'DXD': { 'latitude':'-15.166667', 'longitude': '143.666667', 'name':'Dixie' },
'DXB': { 'latitude':'25.25', 'longitude': '55.333333', 'name':'Dubai' },
'DXA': { 'latitude':'48.15', 'longitude': '-0.55', 'name':'Deux Alpes' },
'TMT': { 'latitude':'-1.916667', 'longitude': '-55.583334', 'name':'Trombetas' },
'YZA': { 'latitude':'50.716667', 'longitude': '-121.283333', 'name':'Ashcroft' },
'YZE': { 'latitude':'45.885278', 'longitude': '-82.567778', 'name':'Gore Bay' },
'MJD': { 'latitude':'27.166667', 'longitude': '68.008333', 'name':'Mohenjodaro' },
'MJE': { 'latitude':'7.833333', 'longitude': '168.166667', 'name':'Majkin' },
'GIU': { 'latitude':'7.95', 'longitude': '80.75', 'name':'Sigiriya Slaf Base' },
'MJG': { 'latitude':'22.216667', 'longitude': '-79.05', 'name':'Mayajigua' },
'GIS': { 'latitude':'-38.666667', 'longitude': '177.983333', 'name':'Gisborne' },
'MJA': { 'latitude':'-21.416667', 'longitude': '44.316667', 'name':'Manja' },
'MJB': { 'latitude':'10.283333', 'longitude': '170.883333', 'name':'Mejit Island' },
'MJC': { 'latitude':'7.383333', 'longitude': '-7.533333', 'name':'Man' },
'MJL': { 'latitude':'-1.816667', 'longitude': '10.883333', 'name':'Mouila' },
'MJM': { 'latitude':'-6.15', 'longitude': '23.633334', 'name':'Mbuji Mayi' },
'MJN': { 'latitude':'-15.666667', 'longitude': '46.366667', 'name':'Amborovy' },
'MJO': { 'latitude':'-22.8', 'longitude': '17.883333', 'name':'Mount Etjo Lodge' },
'MJH': { 'latitude':'25.933333', 'longitude': '45.366667', 'name':'Majma' },
'GIZ': { 'latitude':'16.933611', 'longitude': '42.566944', 'name':'Jazan' },
'MJJ': { 'latitude':'-5.7', 'longitude': '145.25', 'name':'Moki' },
'MJK': { 'latitude':'-25.8', 'longitude': '113.716667', 'name':'Shark Bay' },
'GIG': { 'latitude':'-22.808889', 'longitude': '-43.243611', 'name':'Galeão–antonio Carlos Jobim International Airport' },
'MJU': { 'latitude':'-2.683333', 'longitude': '118.9', 'name':'Mamuju' },
'MJV': { 'latitude':'37.775', 'longitude': '-0.8125', 'name':'San Javier' },
'GID': { 'latitude':'-3.416667', 'longitude': '29.916667', 'name':'Gitega' },
'GIC': { 'latitude':'-9.266667', 'longitude': '142.2', 'name':'Boigu Island' },
'GIB': { 'latitude':'36.15', 'longitude': '-5.35', 'name':'North Front' },
'MJR': { 'latitude':'-38.216667', 'longitude': '-57.866667', 'name':'Miramar' },
'MJS': { 'latitude':'-25.35', 'longitude': '32.216667', 'name':'Maganja Da Costa' },
'GIM': { 'latitude':'-0.016667', 'longitude': '11.4', 'name':'Miele Mimbale' },
'GIL': { 'latitude':'35.916667', 'longitude': '74.383333', 'name':'Gilgit' },
'MJY': { 'latitude':'-2.733333', 'longitude': '103.566667', 'name':'Mangunjaya' },
'GII': { 'latitude':'11.4', 'longitude': '-9.183333', 'name':'Siguiri' },
'PLR': { 'latitude':'33.583333', 'longitude': '-86.283333', 'name':'St Clair County' },
'AHB': { 'latitude':'18.216667', 'longitude': '42.5', 'name':'Abha' },
'AHC': { 'latitude':'60.572222', 'longitude': '4.951667', 'name':'Amedee AAF' },
'NPO': { 'latitude':'-0.366667', 'longitude': '111.75', 'name':'Nangapinoh' },
'AHA': { 'latitude':'26.2', 'longitude': '127.65', 'name':'Naha Air Force Base' },
'AHF': { 'latitude':'15.316667', 'longitude': '-88.883333', 'name':'Municipal' },
'NPH': { 'latitude':'39.738889', 'longitude': '-111.870833', 'name':'Nephi' },
'AHD': { 'latitude':'-16.933333', 'longitude': '179.9', 'name':'Downtown' },
'AHE': { 'latitude':'-14.428056', 'longitude': '-146.256944', 'name':'Ahe' },
'NPE': { 'latitude':'-39.465833', 'longitude': '176.87', 'name':'Hawkes Bay' },
'AHH': { 'latitude':'45.283333', 'longitude': '-92.366667', 'name':'Municipal' },
'AHI': { 'latitude':'-3.333333', 'longitude': '128.916667', 'name':'Amahai' },
'AHN': { 'latitude':'33.95', 'longitude': '-83.333333', 'name':'Athens' },
'AHO': { 'latitude':'40.633333', 'longitude': '8.283333', 'name':'Fertilia' },
'AHL': { 'latitude':'2.483333', 'longitude': '-59.316667', 'name':'Aishalton' },
'AHS': { 'latitude':'15.441667', 'longitude': '-84.425', 'name':'Ahuas' },
'AHT': { 'latitude':'51.5', 'longitude': '179.0', 'name':'Amchitka' },
'AHU': { 'latitude':'35.183333', 'longitude': '-3.833333', 'name':'Charif Al Idrissi' },
'NPU': { 'latitude':'4.672222', 'longitude': '-76.7275', 'name':'San Pedro Uraba' },
'NPT': { 'latitude':'41.6', 'longitude': '-71.416667', 'name':'State' },
'AHY': { 'latitude':'-20.016667', 'longitude': '45.533333', 'name':'Ambatolahy' },
'NPP': { 'latitude':'-22.633333', 'longitude': '132.833333', 'name':'Napperby' },
'PLZ': { 'latitude':'-33.983333', 'longitude': '25.616667', 'name':'Port Elizabeth' },
'PLY': { 'latitude':'41.366667', 'longitude': '-86.3', 'name':'Plymouth' },
'PLX': { 'latitude':'50.333333', 'longitude': '80.25', 'name':'Semipalatinsk' },
'PLF': { 'latitude':'9.383333', 'longitude': '14.933333', 'name':'Pala' },
'SHW': { 'latitude':'17.416667', 'longitude': '47.1', 'name':'Sharurah' },
'PLD': { 'latitude':'10.25', 'longitude': '-85.416667', 'name':'Playa Samara' },
'PLC': { 'latitude':'8.4', 'longitude': '-75.6', 'name':'Planeta Rica' },
'TMY': { 'latitude':'-3.866667', 'longitude': '138.366667', 'name':'Tiom' },
'PLB': { 'latitude':'44.683333', 'longitude': '-73.516667', 'name':'Clinton County' },
'KPP': { 'latitude':'-14.883333', 'longitude': '144.216667', 'name':'Kalpowar' },
'KPR': { 'latitude':'58.483333', 'longitude': '-152.583333', 'name':'Port Williams SPB' },
'KPS': { 'latitude':'31.066667', 'longitude': '152.766667', 'name':'Kempsey' },
'KPT': { 'latitude':'41.966667', 'longitude': '-114.666667', 'name':'Jackpot' },
'PLA': { 'latitude':'3.3', 'longitude': '-75.7', 'name':'Planadas' },
'KPV': { 'latitude':'55.9', 'longitude': '-159.133333', 'name':'Perryville SPB' },
'KPY': { 'latitude':'57.93', 'longitude': '-153.040556', 'name':'Port Bailey SPB' },
'KPA': { 'latitude':'-5.583333', 'longitude': '145.416667', 'name':'Kopiago' },
'KPB': { 'latitude':'56.366667', 'longitude': '-133.616667', 'name':'Point Baker SPB' },
'KPC': { 'latitude':'65.25', 'longitude': '-166.85', 'name':'Port Clarence' },
'KPD': { 'latitude':'40.083333', 'longitude': '-75.383333', 'name':'King Of Prussia' },
'KPE': { 'latitude':'-4.633333', 'longitude': '141.1', 'name':'Yapsiei' },
'KPF': { 'latitude':'-10.2', 'longitude': '149.7', 'name':'Kondubol' },
'KPG': { 'latitude':'6.466667', 'longitude': '-59.166667', 'name':'Kurupung' },
'KPH': { 'latitude':'54.466667', 'longitude': '-162.7', 'name':'Pauloff Harbor SPB' },
'KPI': { 'latitude':'2.0', 'longitude': '112.916667', 'name':'Kapit' },
'TMZ': { 'latitude':'-37.0', 'longitude': '175.666667', 'name':'Thames' },
'KPK': { 'latitude':'57.416667', 'longitude': '-155.9', 'name':'Parks SPB' },
'KPL': { 'latitude':'-8.633333', 'longitude': '142.85', 'name':'Kapal' },
'KPM': { 'latitude':'-5.333333', 'longitude': '143.916667', 'name':'Kompiam' },
'KPN': { 'latitude':'59.933333', 'longitude': '-164.033333', 'name':'Kipnuk SPB' },
'KPO': { 'latitude':'35.983333', 'longitude': '129.416667', 'name':'Pohang' },
'LZY': { 'latitude':'29.6172', 'longitude': '94.3839', 'name':'Lin Zhi' },
'LZR': { 'latitude':'-14.666667', 'longitude': '145.466667', 'name':'Lizard Island' },
'LZU': { 'latitude':'33.978056', 'longitude': '-83.9625', 'name':'Gwinnett County Airport' },
'PLJ': { 'latitude':'16.516667', 'longitude': '-88.366667', 'name':'Placencia' },
'LZI': { 'latitude':'-4.95', 'longitude': '14.133333', 'name':'Luozi' },
'LZH': { 'latitude':'24.366667', 'longitude': '109.533333', 'name':'Liuzhou' },
'LZM': { 'latitude':'-4.966667', 'longitude': '23.45', 'name':'Luzamba' },
'PLI': { 'latitude':'12.583333', 'longitude': '-61.383333', 'name':'Palm Island' },
'LZO': { 'latitude':'28.883333', 'longitude': '105.35', 'name':'Luzhou' },
'LZN': { 'latitude':'26.159444', 'longitude': '119.958333', 'name':'Nangan' },
'LZA': { 'latitude':'-7.183333', 'longitude': '22.35', 'name':'Luiza' },
'LZC': { 'latitude':'18.0', 'longitude': '-102.216667', 'name':'Lazaro Cardenas' },
'LZD': { 'latitude':'36.016667', 'longitude': '103.683333', 'name':'Lanzhoudong' },
'TBY': { 'latitude':'-26.05', 'longitude': '22.45', 'name':'Tsabong' },
'YIG': { 'latitude':'50.383333', 'longitude': '-125.133333', 'name':'Big Bay Marina' },
'YIF': { 'latitude':'51.216667', 'longitude': '-58.666667', 'name':'Pakuashipi' },
'MGB': { 'latitude':'-37.745556', 'longitude': '140.785278', 'name':'Mount Gambier' },
'YIO': { 'latitude':'72.683333', 'longitude': '-78.0', 'name':'Pond Inlet' },
'YIN': { 'latitude':'43.916667', 'longitude': '81.233333', 'name':'Yining' },
'YIH': { 'latitude':'30.7', 'longitude': '111.183333', 'name':'Yichang' },
'YIK': { 'latitude':'62.416667', 'longitude': '-75.9', 'name':'Ivujivik' },
'YIW': { 'latitude':'29.266667', 'longitude': '120.05', 'name':'Yiwu' },
'TBZ': { 'latitude':'38.131944', 'longitude': '46.240278', 'name':'Tabriz' },
'YIP': { 'latitude':'42.25', 'longitude': '-83.383333', 'name':'Willow Run' },
'GZI': { 'latitude':'33.0', 'longitude': '68.416667', 'name':'Ghazni' },
'SOF': { 'latitude':'42.7', 'longitude': '23.4', 'name':'Sofia' },
'TBP': { 'latitude':'-3.566667', 'longitude': '-80.441389', 'name':'Tumbes' },
'TBS': { 'latitude':'41.669167', 'longitude': '44.954722', 'name':'Lochini' },
'TBR': { 'latitude':'32.482778', 'longitude': '-81.736944', 'name':'Statesboro-Bulloch County Airport' },
'TBU': { 'latitude':'-21.238056', 'longitude': '-175.137222', 'name':'Fua\'amotu International' },
'TBT': { 'latitude':'-4.233333', 'longitude': '-69.933334', 'name':'Tabatinga' },
'TBW': { 'latitude':'52.705556', 'longitude': '41.368611', 'name':'Tambov' },
'KOG': { 'latitude':'14.1', 'longitude': '105.833333', 'name':'Khong' },
'GZA': { 'latitude':'31.235556', 'longitude': '34.268333', 'name':'Gaza - Yaser Arafat International Airport' },
'IBR': { 'latitude':'36.181667', 'longitude': '140.41472', 'name':'Ibaraki Airport' },
'LNR': { 'latitude':'43.183333', 'longitude': '-90.2', 'name':'Tri County' },
'TBH': { 'latitude':'12.366667', 'longitude': '122.0', 'name':'Tablas' },
'TBK': { 'latitude':'-44.766667', 'longitude': '169.1', 'name':'Timber Creek' },
'TBJ': { 'latitude':'36.954444', 'longitude': '8.758056', 'name':'Tabarka' },
'TBM': { 'latitude':'-3.583333', 'longitude': '133.566667', 'name':'Tumbang Samba' },
'TBL': { 'latitude':'10.266667', 'longitude': '-61.266667', 'name':'Tableland' },
'WCR': { 'latitude':'67.5', 'longitude': '-148.5', 'name':'Chandalar' },
'TBO': { 'latitude':'-5.083333', 'longitude': '32.833333', 'name':'Tabora' },
'TMB': { 'latitude':'10.016667', 'longitude': '-73.65', 'name':'Tamiami' },
'TBN': { 'latitude':'37.733333', 'longitude': '-92.15', 'name':'Forney AAF' },
'WCA': { 'latitude':'-42.5', 'longitude': '-73.75', 'name':'Gamboa' },
'GZW': { 'latitude':'35.6', 'longitude': '47.016667', 'name':'Ghazvin' },
'WCH': { 'latitude':'-42.933333', 'longitude': '-72.716667', 'name':'Chaiten' },
'MGY': { 'latitude':'39.588889', 'longitude': '-84.224722', 'name':'Dayton-Wright Brothers Airport' },
'TBB': { 'latitude':'13.049444', 'longitude': '109.333611', 'name':'Tuy Hoa' },
'TBG': { 'latitude':'-5.278611', 'longitude': '141.225833', 'name':'Tabubil' },
'PPH': { 'latitude':'4.566667', 'longitude': '-61.483333', 'name':'Peraitepuy' },
'SOI': { 'latitude':'-20.0', 'longitude': '149.0', 'name':'South Molle Island' },
'PPL': { 'latitude':'27.516667', 'longitude': '86.583056', 'name':'Phaplu' },
'XZU': { 'latitude':'37.716667', 'longitude': '28.966667', 'name':'Off line Point' },
'XZQ': { 'latitude':'37.716667', 'longitude': '28.966667', 'name':'Pass Rail' },
'XZX': { 'latitude':'37.716667', 'longitude': '28.966667', 'name':'Off line Point' },
'XZE': { 'latitude':'37.716667', 'longitude': '28.966667', 'name':'Off line Point' },
'PPP': { 'latitude':'-20.483333', 'longitude': '148.55', 'name':'Whitsunday Coast' },
'XZA': { 'latitude':'11.133333', 'longitude': '-1.0', 'name':'Zabre' },
'XZN': { 'latitude':'46.4', 'longitude': '5.833333', 'name':'Avignon Railway' },
'XZJ': { 'latitude':'37.716667', 'longitude': '28.966667', 'name':'Off line Point' },
'SZJ': { 'latitude':'21.65', 'longitude': '-82.95', 'name':'Siguanea' },
'SZK': { 'latitude':'-24.960833', 'longitude': '31.588611', 'name':'Skukuza' },
'SZH': { 'latitude':'0.966667', 'longitude': '117.133333', 'name':'Senipah' },
'SZN': { 'latitude':'-0.883333', 'longitude': '-72.5', 'name':'Santa Cruz Island' },
'SZL': { 'latitude':'51.083333', 'longitude': '5.683333', 'name':'Whiteman AFB' },
'SZB': { 'latitude':'3.131667', 'longitude': '101.548333', 'name':'Sultan Abdul Aziz Shah' },
'SZC': { 'latitude':'10.25', 'longitude': '-85.616667', 'name':'Guanacaste' },
'SZA': { 'latitude':'-6.146389', 'longitude': '12.363889', 'name':'Soyo' },
'SZF': { 'latitude':'41.25', 'longitude': '36.333333', 'name':'Carsamba' },
'SZG': { 'latitude':'47.793333', 'longitude': '13.004444', 'name':'W. A. Mozart' },
'SZD': { 'latitude':'53.366667', 'longitude': '-1.5', 'name':'Sheffield City Airport' },
'SZE': { 'latitude':'1.55', 'longitude': '110.666667', 'name':'Semera Airport' },
'SZZ': { 'latitude':'53.583333', 'longitude': '14.9', 'name':'Goleniow' },
'SZX': { 'latitude':'22.55', 'longitude': '113.916667', 'name':'Shenzhen' },
'SZY': { 'latitude':'53.483333', 'longitude': '20.933333', 'name':'Mazury' },
'SZR': { 'latitude':'42.433333', 'longitude': '25.616667', 'name':'Stara Zagora' },
'SZS': { 'latitude':'-47.0', 'longitude': '167.866667', 'name':'Stewart Island' },
'SZP': { 'latitude':'34.347222', 'longitude': '-119.061111', 'name':'Oxnard' },
'SZQ': { 'latitude':'-34.616667', 'longitude': '-58.533333', 'name':'Saenz Pena' },
'SZV': { 'latitude':'39.766667', 'longitude': '98.566667', 'name':'Suzhou' },
'SZW': { 'latitude':'53.426944', 'longitude': '11.783333', 'name':'Parchim Airport' },
'SZU': { 'latitude':'13.433333', 'longitude': '-6.283333', 'name':'Segou' },
'JTY': { 'latitude':'36.58', 'longitude': '26.375833', 'name':'Astypalaia' },
'YTX': { 'latitude':'57.9', 'longitude': '-1.15', 'name':'Telegraph Creek' },
'YTT': { 'latitude':'52.836667', 'longitude': '-104.066667', 'name':'Tisdale' },
'YTR': { 'latitude':'44.1', 'longitude': '-77.583333', 'name':'Trenton' },
'YTS': { 'latitude':'48.569722', 'longitude': '-81.376667', 'name':'Timmins' },
'YTP': { 'latitude':'49.133333', 'longitude': '-1.9', 'name':'Seaplane Base' },
'JTR': { 'latitude':'36.4', 'longitude': '25.483333', 'name':'Santorini' },
'YTN': { 'latitude':'50.416667', 'longitude': '-64.666667', 'name':'Riviere Au Tonnerre' },
'YTL': { 'latitude':'53.75', 'longitude': '-90.0', 'name':'Big Trout' },
'YTM': { 'latitude':'46.25', 'longitude': '-74.583333', 'name':'La Macaza' },
'JTI': { 'latitude':'-13.83', 'longitude': '-51.773056', 'name':'Jatai' },
'YTK': { 'latitude':'5.18', 'longitude': '120.486111', 'name':'Tulugak' },
'YTH': { 'latitude':'55.801111', 'longitude': '-97.864167', 'name':'Thompson' },
'YTI': { 'latitude':'46.475556', 'longitude': '14.560278', 'name':'Triple Island' },
'YTF': { 'latitude':'48.55', 'longitude': '-71.65', 'name':'Alma' },
'YTG': { 'latitude':'50.883333', 'longitude': '-126.8', 'name':'Sullivan Bay' },
'YTD': { 'latitude':'55.316667', 'longitude': '-97.7', 'name':'Thicket Portage' },
'YTE': { 'latitude':'64.233333', 'longitude': '-76.533333', 'name':'Cape Dorset' },
'YTB': { 'latitude':'53.416667', 'longitude': '-129.25', 'name':'Hartley Bay' },
'YTC': { 'latitude':'57.2', 'longitude': '-127.15', 'name':'Sturdee' },
'YTA': { 'latitude':'45.864444', 'longitude': '-77.251667', 'name':'Pembroke And Area Apt' },
'TML': { 'latitude':'9.557222', 'longitude': '-0.863333', 'name':'Tamale' },
'PCR': { 'latitude':'6.183333', 'longitude': '-67.633333', 'name':'Puerto Carreno' },
'PCS': { 'latitude':'-7.083333', 'longitude': '-41.466667', 'name':'Picos' },
'PCP': { 'latitude':'1.666667', 'longitude': '7.416667', 'name':'Principe' },
'TLS': { 'latitude':'43.635', 'longitude': '1.367778', 'name':'Blagnac' },
'GTA': { 'latitude':'-8.766667', 'longitude': '158.183333', 'name':'Gatokae' },
'GTB': { 'latitude':'3.7', 'longitude': '98.166667', 'name':'Genting' },
'GTC': { 'latitude':'26.783333', 'longitude': '-77.333333', 'name':'Green Turtle' },
'TLW': { 'latitude':'30.84', 'longitude': '-5.23', 'name':'Talasea' },
'GTE': { 'latitude':'-14.0', 'longitude': '136.5', 'name':'Alyangula' },
'GTF': { 'latitude':'47.5', 'longitude': '-111.366667', 'name':'International' },
'GTG': { 'latitude':'45.783333', 'longitude': '-92.683333', 'name':'Municipal' },
'GTI': { 'latitude':'54.383056', 'longitude': '12.316389', 'name':'Guettin' },
'TLY': { 'latitude':'44.8147', 'longitude': '136.2917', 'name':'Plastun' },
'GTK': { 'latitude':'2.6', 'longitude': '102.916667', 'name':'Sungei Tekai' },
'VTL': { 'latitude':'48.2', 'longitude': '5.95', 'name':'Vittel' },
'GTN': { 'latitude':'-43.901667', 'longitude': '170.118333', 'name':'Glentanner' },
'GTO': { 'latitude':'0.65', 'longitude': '122.916667', 'name':'Tolotio' },
'TLC': { 'latitude':'19.336944', 'longitude': '-99.566111', 'name':'Licenciado Adolfo Lopez Mateos International' },
'TLB': { 'latitude':'34.126389', 'longitude': '72.810278', 'name':'Tarbela' },
'GTR': { 'latitude':'33.466667', 'longitude': '-88.383333', 'name':'Golden Triangle Reg.' },
'GTS': { 'latitude':'-26.966667', 'longitude': '133.616667', 'name':'Granites' },
'GTT': { 'latitude':'-18.416667', 'longitude': '143.783333', 'name':'Georgetown' },
'PCT': { 'latitude':'40.35', 'longitude': '-74.666667', 'name':'Princeton' },
'TLE': { 'latitude':'-23.383333', 'longitude': '43.728333', 'name':'Tulear' },
'GTW': { 'latitude':'49.0', 'longitude': '17.675', 'name':'Holesov' },
'TLK': { 'latitude':'65.65', 'longitude': '-23.966667', 'name':'Talknafjordur' },
'GTY': { 'latitude':'39.833333', 'longitude': '-77.233333', 'name':'Gettysburg' },
'TLI': { 'latitude':'1.0425', 'longitude': '120.813611', 'name':'Tolitoli' },
'TLH': { 'latitude':'30.396389', 'longitude': '-84.350278', 'name':'Tallahassee Regional Airport' },
'TLO': { 'latitude':'-30.816667', 'longitude': '-64.916667', 'name':'Tol' },
'TLN': { 'latitude':'43.097222', 'longitude': '6.146111', 'name':'Le Palyvestre' },
'TLM': { 'latitude':'34.878333', 'longitude': '-1.315', 'name':'Zenata' },
'TLL': { 'latitude':'59.413333', 'longitude': '24.832778', 'name':'Ulemiste' },
'HVK': { 'latitude':'65.7', 'longitude': '-21.7', 'name':'Holmavik' },
'HVM': { 'latitude':'65.416667', 'longitude': '-21.0', 'name':'Hvammstangi' },
'HVN': { 'latitude':'41.266667', 'longitude': '-72.883333', 'name':'New Haven' },
'HVA': { 'latitude':'-14.633333', 'longitude': '47.766667', 'name':'Analalava' },
'HVB': { 'latitude':'-25.0', 'longitude': '153.0', 'name':'Hervey Bay' },
'HVE': { 'latitude':'38.416667', 'longitude': '-110.7', 'name':'Intermediate' },
'HVD': { 'latitude':'48.016667', 'longitude': '91.65', 'name':'Khovd' },
'HVG': { 'latitude':'70.983333', 'longitude': '25.833333', 'name':'Valan' },
'HVS': { 'latitude':'34.4', 'longitude': '-80.116667', 'name':'Municipal' },
'HVR': { 'latitude':'48.55', 'longitude': '-109.766667', 'name':'City County' },
'PCO': { 'latitude':'23.583333', 'longitude': '-109.5', 'name':'Punta Colorada' },
'PCL': { 'latitude':'-8.366667', 'longitude': '-74.583333', 'name':'Captain Rolden International Airport' },
'PCM': { 'latitude':'20.55', 'longitude': '-87.116667', 'name':'Playa Del Carmen' },
'PCB': { 'latitude':'-6.336944', 'longitude': '106.764444', 'name':'Pondok Cabe' },
'PCC': { 'latitude':'1.916667', 'longitude': '-75.166667', 'name':'Puerto Rico' },
'PCA': { 'latitude':'60.833333', 'longitude': '-150.0', 'name':'Portage Creek' },
'ILD': { 'latitude':'41.7278', 'longitude': '0.5358', 'name':'Lleida' },
'UCY': { 'latitude':'36.416667', 'longitude': '-89.05', 'name':'Everett-Stewart' },
'PCG': { 'latitude':'17.266667', 'longitude': '-90.258333', 'name':'Paso Caballos' },
'UCE': { 'latitude':'30.5', 'longitude': '-92.416667', 'name':'Eunice' },
'PCD': { 'latitude':'43.016667', 'longitude': '-91.116667', 'name':'Municipal' },
'UCA': { 'latitude':'43.15', 'longitude': '-75.383333', 'name':'Oneida County' },
'UCN': { 'latitude':'5.9', 'longitude': '-10.083333', 'name':'Buchanan' },
'PCE': { 'latitude':'57.164167', 'longitude': '-157.433056', 'name':'Painter Creek' },
'UCK': { 'latitude':'50.75', 'longitude': '25.333333', 'name':'Lutsk' },
'EJH': { 'latitude':'26.416667', 'longitude': '36.75', 'name':'Wedjh' },
'RBY': { 'latitude':'64.733333', 'longitude': '-155.483333', 'name':'Ruby' },
'ILE': { 'latitude':'31.15', 'longitude': '-97.716667', 'name':'Municipal' },
'RBV': { 'latitude':'-8.165556', 'longitude': '157.639444', 'name':'Ramata' },
'RBU': { 'latitude':'-20.766667', 'longitude': '117.15', 'name':'Roebourne' },
'RBT': { 'latitude':'2.333333', 'longitude': '37.983333', 'name':'Marsabit' },
'RBS': { 'latitude':'-37.7', 'longitude': '148.5', 'name':'Orbost' },
'EJA': { 'latitude':'7.016667', 'longitude': '-73.766667', 'name':'Variguies' },
'RBQ': { 'latitude':'-14.45', 'longitude': '-67.55', 'name':'Rurrenabaque' },
'RBP': { 'latitude':'-9.983333', 'longitude': '149.833333', 'name':'Rabaraba' },
'RBO': { 'latitude':'-18.333333', 'longitude': '-59.75', 'name':'Robore' },
'RBN': { 'latitude':'19.833333', 'longitude': '-72.5', 'name':'Fort Jefferson' },
'RBM': { 'latitude':'48.816667', 'longitude': '12.566667', 'name':'Wallmuhle' },
'RBL': { 'latitude':'40.15', 'longitude': '-122.25', 'name':'Red Bluff Fss' },
'RBK': { 'latitude':'-14.333333', 'longitude': '-66.5', 'name':'French Valley' },
'RBJ': { 'latitude':'45.383333', 'longitude': '141.033333', 'name':'Rebun' },
'RBI': { 'latitude':'-17.033333', 'longitude': '178.916667', 'name':'Rabi' },
'RBH': { 'latitude':'58.55', 'longitude': '-155.8', 'name':'Brooks Lodge' },
'EJT': { 'latitude':'6.133333', 'longitude': '171.916667', 'name':'Enijet' },
'RBF': { 'latitude':'34.266667', 'longitude': '-116.85', 'name':'Big Bear City Arpt' },
'RBE': { 'latitude':'13.833333', 'longitude': '107.0', 'name':'Ratanakiri' },
'RBD': { 'latitude':'7.716667', 'longitude': '40.916667', 'name':'Redbird' },
'RBC': { 'latitude':'-34.65', 'longitude': '142.783333', 'name':'Robinvale' },
'RBB': { 'latitude':'-4.4', 'longitude': '-59.583333', 'name':'Borba' },
'RBA': { 'latitude':'34.05', 'longitude': '-6.75', 'name':'Sale' },
'LGK': { 'latitude':'6.329722', 'longitude': '99.728611', 'name':'Langakawi Intl' },
'LGH': { 'latitude':'-30.466667', 'longitude': '138.416667', 'name':'Leigh Creek' },
'LGI': { 'latitude':'23.25', 'longitude': '-75.133333', 'name':'Deadmans Cay' },
'LGN': { 'latitude':'-5.683333', 'longitude': '149.416667', 'name':'Linga Linga' },
'LGO': { 'latitude':'53.75', 'longitude': '7.483333', 'name':'Langeoog' },
'LGL': { 'latitude':'4.183333', 'longitude': '114.25', 'name':'Long Lellang' },
'LGM': { 'latitude':'-5.533333', 'longitude': '143.483333', 'name':'Laiagam' },
'LGB': { 'latitude':'33.816667', 'longitude': '-118.15', 'name':'Long Beach Municipal' },
'LGC': { 'latitude':'33.016667', 'longitude': '-85.083333', 'name':'Calloway' },
'LGA': { 'latitude':'40.766667', 'longitude': '-73.866667', 'name':'La Guardia' },
'LGF': { 'latitude':'-1.6', 'longitude': '138.716667', 'name':'Laguna AAF' },
'LGG': { 'latitude':'50.636389', 'longitude': '5.442778', 'name':'Liege Airport' },
'LGD': { 'latitude':'45.316667', 'longitude': '-118.033333', 'name':'La Grande' },
'LGE': { 'latitude':'-28.916667', 'longitude': '139.0', 'name':'Lake Gregory' },
'LGZ': { 'latitude':'-0.183333', 'longitude': '-74.75', 'name':'Leguizamo' },
'LGX': { 'latitude':'3.8', 'longitude': '42.05', 'name':'Lugh Ganane' },
'LGY': { 'latitude':'8.516667', 'longitude': '-71.4', 'name':'Lagunillas' },
'LGR': { 'latitude':'-47.333333', 'longitude': '-72.0', 'name':'Cochrane' },
'LGS': { 'latitude':'-35.493611', 'longitude': '-69.574167', 'name':'Malargue' },
'LGP': { 'latitude':'13.166667', 'longitude': '123.733333', 'name':'Legazpi' },
'LGQ': { 'latitude':'0.1', 'longitude': '-76.883333', 'name':'Lago Agrio' },
'LGW': { 'latitude':'51.148056', 'longitude': '-0.190278', 'name':'London Gatwick' },
'LGT': { 'latitude':'4.583333', 'longitude': '-70.833333', 'name':'Las Gaviotas' },
'LGU': { 'latitude':'41.783333', 'longitude': '-111.85', 'name':'Cache' },
'DZA': { 'latitude':'-12.8', 'longitude': '45.283333', 'name':'Dzaoudzi' },
'VYS': { 'latitude':'41.3525', 'longitude': '-89.149722', 'name':'Illinois Valley Regnl' },
'DZI': { 'latitude':'9.6', 'longitude': '-73.45', 'name':'Codazzi' },
'DZO': { 'latitude':'-33.358889', 'longitude': '-56.499167', 'name':'Santa Bernardina' },
'DZN': { 'latitude':'47.7', 'longitude': '67.733333', 'name':'Zhezhazgan' },
'DZU': { 'latitude':'29.7', 'longitude': '105.8', 'name':'Dazu' },
'TIY': { 'latitude':'18.55', 'longitude': '-11.416667', 'name':'Tidjikja' },
'IAM': { 'latitude':'28.051667', 'longitude': '9.642778', 'name':'In Amenas' },
'IAN': { 'latitude':'66.983333', 'longitude': '-160.416667', 'name':'Bob Barker Memorial' },
'IAH': { 'latitude':'29.984444', 'longitude': '-95.341389', 'name':'George Bush Intercontinental' },
'OFJ': { 'latitude':'66.1', 'longitude': '-18.633333', 'name':'Olafsfjordur' },
'IAD': { 'latitude':'38.944444', 'longitude': '-77.455833', 'name':'Washington Dulles International' },
'IAG': { 'latitude':'43.1', 'longitude': '-79.033333', 'name':'International' },
'OFI': { 'latitude':'9.6', 'longitude': '-4.033333', 'name':'Ouango Fitini' },
'IAA': { 'latitude':'67.433333', 'longitude': '86.633333', 'name':'Igarka' },
'OFU': { 'latitude':'-14.183333', 'longitude': '-169.7', 'name':'Ofu' },
'IAU': { 'latitude':'-9.783333', 'longitude': '148.1', 'name':'Iaura' },
'IAQ': { 'latitude':'29.834722', 'longitude': '50.267778', 'name':'Bahregan' },
'IAS': { 'latitude':'47.183333', 'longitude': '27.6', 'name':'Iasi' },
'IAR': { 'latitude':'57.616667', 'longitude': '39.883333', 'name':'Yaroslavl' },
'PHK': { 'latitude':'26.816667', 'longitude': '-80.65', 'name':'Palm Beach Co Glades' },
'PHJ': { 'latitude':'-32.916667', 'longitude': '151.766667', 'name':'Port Hunter' },
'PHH': { 'latitude':'10.9', 'longitude': '108.066667', 'name':'Phan Thiet' },
'PHO': { 'latitude':'68.35', 'longitude': '-166.8', 'name':'Point Hope' },
'PHN': { 'latitude':'42.9', 'longitude': '-82.533333', 'name':'St Clair County Intl' },
'PHM': { 'latitude':'48.683333', 'longitude': '9.016667', 'name':'Boeblingen' },
'PHL': { 'latitude':'39.871944', 'longitude': '-75.241111', 'name':'Philadelphia International' },
'PHC': { 'latitude':'5.015556', 'longitude': '6.949722', 'name':'Port Harcourt' },
'PHB': { 'latitude':'-2.9', 'longitude': '-41.766667', 'name':'Santos Dumont' },
'PHA': { 'latitude':'11.616667', 'longitude': '108.95', 'name':'Phan Rang' },
'PHG': { 'latitude':'4.85', 'longitude': '7.016667', 'name':'Port Harcourt City' },
'PHF': { 'latitude':'37.133333', 'longitude': '-76.5', 'name':'Newport News/williamsb' },
'PHE': { 'latitude':'-20.383333', 'longitude': '118.45', 'name':'Port Hedland' },
'PHD': { 'latitude':'40.466667', 'longitude': '-81.433333', 'name':'Harry Clever' },
'PHZ': { 'latitude':'8.166667', 'longitude': '98.283333', 'name':'Phi Phi Island' },
'PHY': { 'latitude':'16.416667', 'longitude': '101.133333', 'name':'Phetchabun' },
'PHX': { 'latitude':'33.433333', 'longitude': '-112.033333', 'name':'Sky Harbor Intl' },
'PHS': { 'latitude':'16.783333', 'longitude': '100.266667', 'name':'Phitsanulok' },
'PHR': { 'latitude':'-18.183333', 'longitude': '178.233333', 'name':'Pacific Harbor' },
'PHP': { 'latitude':'44.033333', 'longitude': '-101.65', 'name':'Philip' },
'PHW': { 'latitude':'-23.937222', 'longitude': '31.155278', 'name':'Cape Town' },
'PHU': { 'latitude':'11.298611', 'longitude': '106.804167', 'name':'Phu Vinh' },
'PHT': { 'latitude':'36.333333', 'longitude': '-88.383333', 'name':'Henry County' },
'VYD': { 'latitude':'-27.783333', 'longitude': '30.8', 'name':'Vryheid' },
'TID': { 'latitude':'35.466667', 'longitude': '1.35', 'name':'Tiaret' },
'TIE': { 'latitude':'7.2', 'longitude': '35.45', 'name':'Tippi' },
'BDD': { 'latitude':'-10.116667', 'longitude': '142.133333', 'name':'Badu Island' },
'TIB': { 'latitude':'8.648056', 'longitude': '-72.739444', 'name':'Tibu' },
'TIC': { 'latitude':'7.083333', 'longitude': '171.916667', 'name':'Tinak Island' },
'MHN': { 'latitude':'42.05', 'longitude': '-101.066667', 'name':'Mullen' },
'MHO': { 'latitude':'-17.166667', 'longitude': '125.666667', 'name':'Mount House' },
'MHM': { 'latitude':'55.583333', 'longitude': '-3.016667', 'name':'Intermediate' },
'MHK': { 'latitude':'39.133333', 'longitude': '-96.666667', 'name':'Municipal' },
'MHH': { 'latitude':'26.5', 'longitude': '-77.1', 'name':'International' },
'MHI': { 'latitude':'11.333333', 'longitude': '43.016667', 'name':'Musha' },
'MHF': { 'latitude':'1.75', 'longitude': '-69.916667', 'name':'Morichal' },
'MHG': { 'latitude':'49.483333', 'longitude': '8.483333', 'name':'Mannheim Arpt' },
'MHD': { 'latitude':'36.238889', 'longitude': '59.638333', 'name':'Mashad' },
'MHE': { 'latitude':'43.766667', 'longitude': '-98.033333', 'name':'Municipal' },
'MHB': { 'latitude':'-36.966667', 'longitude': '174.916667', 'name':'Mechanics Bay' },
'MHC': { 'latitude':'-15.116667', 'longitude': '-73.75', 'name':'Macmahon Camp 4' },
'MHA': { 'latitude':'5.25', 'longitude': '-59.15', 'name':'Mahdia' },
'GKH': { 'latitude':'28.0', 'longitude': '84.675', 'name':'Gorkha' },
'HKY': { 'latitude':'35.733333', 'longitude': '-81.383333', 'name':'Hickory' },
'MHZ': { 'latitude':'51.416667', 'longitude': '-1.7', 'name':'Mildenhall Arpt' },
'GKL': { 'latitude':'-23.183333', 'longitude': '150.95', 'name':'Great Keppel Island' },
'GKO': { 'latitude':'-0.083333', 'longitude': '11.466667', 'name':'Kongoboumba' },
'GKN': { 'latitude':'62.166667', 'longitude': '-145.466667', 'name':'Gulkana' },
'MHV': { 'latitude':'35.483333', 'longitude': '-118.2', 'name':'Kern County' },
'MHW': { 'latitude':'-19.816667', 'longitude': '-63.983333', 'name':'Monteagudo' },
'MHT': { 'latitude':'42.9325', 'longitude': '-71.435556', 'name':'Manchester Regional Airport' },
'MHU': { 'latitude':'-36.966667', 'longitude': '147.183333', 'name':'Mount Hotham' },
'MHR': { 'latitude':'38.555278', 'longitude': '-121.297222', 'name':'Sacramento Mather Airport' },
'MHS': { 'latitude':'41.316667', 'longitude': '-122.316667', 'name':'Rep' },
'MHP': { 'latitude':'54.0', 'longitude': '28.0', 'name':'Minsk International 1' },
'MHQ': { 'latitude':'60.116667', 'longitude': '19.9', 'name':'Mariehamn' },
'AND': { 'latitude':'34.5', 'longitude': '-82.716667', 'name':'Anderson' },
'ANE': { 'latitude':'47.560278', 'longitude': '-0.312222', 'name':'Marce' },
'ANF': { 'latitude':'-23.439444', 'longitude': '-70.442778', 'name':'Cerro Moreno' },
'ANG': { 'latitude':'45.666667', 'longitude': '0.2', 'name':'Brie-Champniers' },
'ANA': { 'latitude':'33.848333', 'longitude': '-117.850278', 'name':'Orange County Steel Salvage Heliport' },
'ANB': { 'latitude':'33.588056', 'longitude': '-85.858056', 'name':'Anniston Metropolitan' },
'ANC': { 'latitude':'61.174444', 'longitude': '-149.996389', 'name':'Ted Stevens Anchorage International Airport' },
'ANL': { 'latitude':'-11.5', 'longitude': '16.75', 'name':'Andulo' },
'ANM': { 'latitude':'-15.0', 'longitude': '50.333333', 'name':'Antsirabato' },
'ANN': { 'latitude':'55.033333', 'longitude': '-131.566667', 'name':'Annette Island' },
'ANO': { 'latitude':'-16.166667', 'longitude': '39.933333', 'name':'Angoche' },
'ANH': { 'latitude':'-8.983333', 'longitude': '160.5', 'name':'Anuha Island Resort' },
'ANI': { 'latitude':'61.583333', 'longitude': '-159.533333', 'name':'Aniak' },
'ANJ': { 'latitude':'-2.85', 'longitude': '13.833333', 'name':'Zanaga' },
'ANK': { 'latitude':'39.949444', 'longitude': '32.683056', 'name':'Etimesgut' },
'NVG': { 'latitude':'11.666667', 'longitude': '-84.45', 'name':'Nueva Guinea' },
'ANU': { 'latitude':'17.136667', 'longitude': '-61.792778', 'name':'V. C. Bird Intl' },
'ANV': { 'latitude':'62.65', 'longitude': '-160.216667', 'name':'Anvik' },
'ANW': { 'latitude':'42.583333', 'longitude': '-99.983333', 'name':'Ainsworth' },
'ANP': { 'latitude':'38.983333', 'longitude': '-76.5', 'name':'Lee' },
'ANQ': { 'latitude':'41.633333', 'longitude': '-85.0', 'name':'Tri-State Steuben Cty' },
'ANR': { 'latitude':'51.189444', 'longitude': '4.460278', 'name':'Deurne' },
'ANS': { 'latitude':'-13.65', 'longitude': '-73.416667', 'name':'Andahuaylas' },
'ANX': { 'latitude':'69.316667', 'longitude': '16.116667', 'name':'Andenes' },
'ANY': { 'latitude':'37.15', 'longitude': '-98.033333', 'name':'Anthony' },
'ANZ': { 'latitude':'-25.083333', 'longitude': '132.166667', 'name':'Angus Downs' },
'HKT': { 'latitude':'8.113333', 'longitude': '98.316944', 'name':'Phuket International' },
'ZSS': { 'latitude':'4.933333', 'longitude': '-6.133333', 'name':'Sassandra' },
'KRZ': { 'latitude':'-1.45', 'longitude': '19.0', 'name':'Kiri' },
'UHF': { 'latitude':'51.933333', 'longitude': '-1.266667', 'name':'RAF Station' },
'KRX': { 'latitude':'-4.833333', 'longitude': '145.666667', 'name':'Kar Kar' },
'KRY': { 'latitude':'45.616667', 'longitude': '84.883333', 'name':'Karamay' },
'KRR': { 'latitude':'45.034722', 'longitude': '39.170556', 'name':'Pashkovsky' },
'KRS': { 'latitude':'58.2', 'longitude': '8.1', 'name':'Kjevik' },
'KRP': { 'latitude':'56.3', 'longitude': '9.116667', 'name':'Karup' },
'KRQ': { 'latitude':'48.705556', 'longitude': '37.628889', 'name':'Kramatorsk' },
'KRV': { 'latitude':'2.983333', 'longitude': '36.116667', 'name':'Kerio Valley' },
'KRW': { 'latitude':'40.033333', 'longitude': '53.0', 'name':'Turkmanbashi' },
'KRT': { 'latitude':'15.589444', 'longitude': '32.553056', 'name':'Civil' },
'KRU': { 'latitude':'-8.3', 'longitude': '147.083333', 'name':'Kerau' },
'KRJ': { 'latitude':'-8.75', 'longitude': '147.497222', 'name':'Karawari' },
'KRK': { 'latitude':'50.2', 'longitude': '19.983333', 'name':'J. Paul Ii Balice Intl' },
'KRI': { 'latitude':'-7.483333', 'longitude': '144.05', 'name':'Kikori' },
'KRN': { 'latitude':'67.816667', 'longitude': '20.333333', 'name':'Kiruna' },
'KRO': { 'latitude':'55.433333', 'longitude': '65.3', 'name':'Kurgan' },
'KRL': { 'latitude':'41.733333', 'longitude': '86.15', 'name':'Korla' },
'KRM': { 'latitude':'3.75', 'longitude': '-59.316667', 'name':'Karanambo' },
'KRB': { 'latitude':'-17.5', 'longitude': '140.866667', 'name':'Karumba' },
'KRC': { 'latitude':'-1.716667', 'longitude': '101.25', 'name':'Kerinci' },
'KRA': { 'latitude':'-35.75', 'longitude': '143.933333', 'name':'Kerang' },
'KRF': { 'latitude':'62.883333', 'longitude': '17.833333', 'name':'Kramfors' },
'KRG': { 'latitude':'4.016667', 'longitude': '-59.516667', 'name':'Karasabai' },
'KRD': { 'latitude':'-20.5', 'longitude': '134.633333', 'name':'Kurundi' },
'KRE': { 'latitude':'-2.55', 'longitude': '30.1', 'name':'Kirundo' },
'HKA': { 'latitude':'35.933333', 'longitude': '-89.916667', 'name':'Municipal' },
'HKG': { 'latitude':'22.308889', 'longitude': '113.914722', 'name':'Hong Kong International' },
'OKY': { 'latitude':'-27.402778', 'longitude': '151.733333', 'name':'Oakey' },
'OKA': { 'latitude':'26.333333', 'longitude': '127.833333', 'name':'Naha' },
'OKC': { 'latitude':'35.393056', 'longitude': '-97.600833', 'name':'Will Rogers World Airport' },
'OKB': { 'latitude':'-25.0', 'longitude': '153.283333', 'name':'Fraser Island' },
'OKE': { 'latitude':'27.433333', 'longitude': '128.616667', 'name':'Okino Erabu' },
'OKD': { 'latitude':'43.133333', 'longitude': '141.383333', 'name':'Okadama' },
'YOO': { 'latitude':'43.922778', 'longitude': '-78.895', 'name':'Oshawa' },
'YOL': { 'latitude':'9.166667', 'longitude': '12.483333', 'name':'Yola' },
'YOK': { 'latitude':'35.466667', 'longitude': '139.466389', 'name':'Yokohama' },
'OKG': { 'latitude':'-1.466667', 'longitude': '15.066667', 'name':'Okoyo' },
'YOH': { 'latitude':'54.95', 'longitude': '-95.283333', 'name':'Oxford House' },
'YOG': { 'latitude':'51.633333', 'longitude': '-85.95', 'name':'Ogoki' },
'YOE': { 'latitude':'55.733333', 'longitude': '-117.2', 'name':'Falher' },
'OKF': { 'latitude':'-19.166667', 'longitude': '15.933333', 'name':'Okaukuejo' },
'YOC': { 'latitude':'67.566667', 'longitude': '-139.85', 'name':'Old Crow' },
'YOA': { 'latitude':'37.394444', 'longitude': '25.2575', 'name':'Ekati' },
'OKI': { 'latitude':'36.166667', 'longitude': '133.316667', 'name':'Oki Island' },
'YOY': { 'latitude':'46.883333', 'longitude': '-71.483333', 'name':'Valcartier' },
'OKH': { 'latitude':'52.666667', 'longitude': '-0.733333', 'name':'Cottesmor RAF' },
'YOW': { 'latitude':'45.3225', 'longitude': '-75.669167', 'name':'Ottawa Macdonald-Cartier International' },
'YOT': { 'latitude':'29.883333', 'longitude': '35.05', 'name':'Yotvata' },
'YOS': { 'latitude':'44.666667', 'longitude': '-80.916667', 'name':'Billy Bishop Regional' },
'OKK': { 'latitude':'40.533333', 'longitude': '-86.066667', 'name':'Kokomo' },
'YOP': { 'latitude':'58.5', 'longitude': '-119.4', 'name':'Rainbow Lake' },
'OKJ': { 'latitude':'34.583333', 'longitude': '133.933333', 'name':'Okayama' },
'OKL': { 'latitude':'-3.683333', 'longitude': '137.483333', 'name':'Oksibil' },
'OKO': { 'latitude':'35.748611', 'longitude': '139.348611', 'name':'Yokota Afb' },
'OKN': { 'latitude':'-0.7', 'longitude': '13.783333', 'name':'Okondja' },
'ILP': { 'latitude':'-22.583333', 'longitude': '167.45', 'name':'Ile Des Pins' },
'GLK': { 'latitude':'6.85', 'longitude': '47.266667', 'name':'Galcaio' },
'SON': { 'latitude':'-15.666667', 'longitude': '167.2', 'name':'Pekoa' },
'GLO': { 'latitude':'51.894167', 'longitude': '-2.167222', 'name':'Gloucestershire' },
'RPB': { 'latitude':'-14.75', 'longitude': '134.55', 'name':'Roper Bar' },
'GLA': { 'latitude':'55.871944', 'longitude': '-4.433056', 'name':'Glasgow International' },
'GLC': { 'latitude':'6.966667', 'longitude': '46.416667', 'name':'Geladi' },
'GLD': { 'latitude':'39.366667', 'longitude': '-101.7', 'name':'Renner Field' },
'WMP': { 'latitude':'-16.066667', 'longitude': '47.633333', 'name':'Mampikony' },
'WMV': { 'latitude':'-16.45', 'longitude': '46.566667', 'name':'Madirovalo' },
'GLE': { 'latitude':'45.4', 'longitude': '2.9', 'name':'Municipal' },
'WMK': { 'latitude':'55.733333', 'longitude': '-132.2', 'name':'SPB' },
'WMH': { 'latitude':'36.366667', 'longitude': '-92.466667', 'name':'Mountain Home' },
'WMO': { 'latitude':'64.683333', 'longitude': '-163.4', 'name':'White Mountain' },
'GLF': { 'latitude':'8.666667', 'longitude': '-83.083333', 'name':'Golfito' },
'WML': { 'latitude':'-20.35', 'longitude': '45.55', 'name':'Malaimbandy' },
'WMC': { 'latitude':'40.966667', 'longitude': '-117.733333', 'name':'Winnemucca' },
'WMB': { 'latitude':'-38.283333', 'longitude': '142.45', 'name':'Warrnambool' },
'WMA': { 'latitude':'-15.833333', 'longitude': '48.833333', 'name':'Mandritsara' },
'GLG': { 'latitude':'-24.766667', 'longitude': '139.583333', 'name':'Glengyle' },
'WME': { 'latitude':'-27.286389', 'longitude': '120.554722', 'name':'Mount Keith' },
'WMD': { 'latitude':'-21.033333', 'longitude': '44.95', 'name':'Mandabe' },
'GLX': { 'latitude':'-2.183333', 'longitude': '127.833333', 'name':'Galela' },
'GLY': { 'latitude':'-20.083333', 'longitude': '119.666667', 'name':'Goldsworthy' },
'PEK': { 'latitude':'40.063333', 'longitude': '116.584444', 'name':'Beijing Capital Int.' },
'AKI': { 'latitude':'60.9', 'longitude': '-161.233333', 'name':'Akiak' },
'PZU': { 'latitude':'19.433611', 'longitude': '37.234167', 'name':'Port Sudan' },
'GLP': { 'latitude':'-5.283333', 'longitude': '141.516667', 'name':'Gulgubip' },
'GLQ': { 'latitude':'62.116667', 'longitude': '-145.55', 'name':'Glennallen' },
'GLR': { 'latitude':'45.016667', 'longitude': '-84.7', 'name':'Otsego County' },
'DFI': { 'latitude':'41.283333', 'longitude': '-84.366667', 'name':'Memorial' },
'AKG': { 'latitude':'-3.583333', 'longitude': '142.25', 'name':'Anguganak' },
'GLV': { 'latitude':'64.55', 'longitude': '-163.016667', 'name':'Golovin' },
'GLW': { 'latitude':'37.033333', 'longitude': '-85.95', 'name':'Municipal' },
'SQL': { 'latitude':'37.483333', 'longitude': '-122.25', 'name':'San Carlos' },
'PED': { 'latitude':'50.013333', 'longitude': '15.738611', 'name':'Pardubice' },
'OMO': { 'latitude':'43.286667', 'longitude': '17.85', 'name':'Mostar' },
'JRE': { 'latitude':'40.8', 'longitude': '-73.966667', 'name':'East 60th Street H/P' },
'XFR': { 'latitude':'11.383333', 'longitude': '8.283333', 'name':'Malmo South Railway' },
'JRC': { 'latitude':'49.916667', 'longitude': '-0.966667', 'name':'Municipal Heliport' },
'JRB': { 'latitude':'40.701111', 'longitude': '-74.009167', 'name':'Downtown Manhattan H/p' },
'JRA': { 'latitude':'40.754444', 'longitude': '-74.0075', 'name':'West 30th St Heliport' },
'JRO': { 'latitude':'-3.433333', 'longitude': '37.066667', 'name':'Kilimanjaro' },
'JRN': { 'latitude':'-10.305556', 'longitude': '-58.488889', 'name':'Juruena' },
'JRK': { 'latitude':'61.166667', 'longitude': '-48.416667', 'name':'Arsuk' },
'JRH': { 'latitude':'26.716667', 'longitude': '94.166667', 'name':'Rowriah' },
'JRS': { 'latitude':'31.864722', 'longitude': '35.219167', 'name':'Jerusalem' },
'TNU': { 'latitude':'41.7', 'longitude': '-93.05', 'name':'Municipal' },
'TNT': { 'latitude':'25.861944', 'longitude': '-80.896944', 'name':'Dade Collier' },
'GVI': { 'latitude':'-3.916667', 'longitude': '141.166667', 'name':'Green River' },
'TNQ': { 'latitude':'4.716667', 'longitude': '-1.4', 'name':'Teraina' },
'TNP': { 'latitude':'52.116667', 'longitude': '7.4', 'name':'Twentynine Palms' },
'GVL': { 'latitude':'34.266667', 'longitude': '-83.833333', 'name':'Lee Gilmer Memorial' },
'ROI': { 'latitude':'16.066667', 'longitude': '103.65', 'name':'Roi Et Airport' },
'GVA': { 'latitude':'46.238056', 'longitude': '6.108889', 'name':'Geneve-cointrin' },
'TNX': { 'latitude':'13.533333', 'longitude': '106.033333', 'name':'Stung Treng' },
'GVE': { 'latitude':'38.15', 'longitude': '-78.166667', 'name':'Municipal' },
'TNE': { 'latitude':'30.51', 'longitude': '-8.28', 'name':'Tanegashima' },
'TND': { 'latitude':'20.7', 'longitude': '-76.516667', 'name':'Trinidad' },
'GVX': { 'latitude':'60.516667', 'longitude': '17.016667', 'name':'Sandviken' },
'ROK': { 'latitude':'-23.381944', 'longitude': '150.475278', 'name':'Rockhampton' },
'TNA': { 'latitude':'36.75', 'longitude': '116.966667', 'name':'Jinan' },
'TNC': { 'latitude':'65.563056', 'longitude': '-167.921667', 'name':'Tin City Afs' },
'TNB': { 'latitude':'2.95', 'longitude': '99.816667', 'name':'Tanah Grogot' },
'GVR': { 'latitude':'-18.895278', 'longitude': '-41.982222', 'name':'Governador Valadares' },
'TNL': { 'latitude':'50.016667', 'longitude': '23.916667', 'name':'Ternopol' },
'GVP': { 'latitude':'-15.783333', 'longitude': '144.616667', 'name':'Greenvale' },
'TNN': { 'latitude':'22.950278', 'longitude': '120.205833', 'name':'Tainan' },
'TNI': { 'latitude':'24.55', 'longitude': '80.833333', 'name':'Satna' },
'GVW': { 'latitude':'38.883333', 'longitude': '-94.533333', 'name':'Richards-Gebaur' },
'GVT': { 'latitude':'33.133333', 'longitude': '-96.116667', 'name':'Majors Field' },
'TNJ': { 'latitude':'0.922778', 'longitude': '104.532222', 'name':'Kidjang' },
'NKA': { 'latitude':'0.7', 'longitude': '9.983333', 'name':'Nkan' },
'HHQ': { 'latitude':'12.630556', 'longitude': '99.954444', 'name':'Hua Hin Airport' },
'NKC': { 'latitude':'18.089722', 'longitude': '-15.953889', 'name':'Nouakchott' },
'NKD': { 'latitude':'-2.966667', 'longitude': '116.283333', 'name':'Sinak' },
'NKG': { 'latitude':'31.741944', 'longitude': '118.861944', 'name':'Lukou International Airport' },
'NKI': { 'latitude':'55.855556', 'longitude': '-133.183333', 'name':'Naukiti' },
'NKL': { 'latitude':'-1.983333', 'longitude': '16.466667', 'name':'Nkolo' },
'NKM': { 'latitude':'35.255', 'longitude': '136.924444', 'name':'Komaki AFB' },
'NKN': { 'latitude':'-5.833333', 'longitude': '146.45', 'name':'Nankina' },
'NKO': { 'latitude':'-16.566667', 'longitude': '44.466667', 'name':'Ankokoambo' },
'HHA': { 'latitude':'28.189167', 'longitude': '113.219722', 'name':'Huanghua International' },
'NKS': { 'latitude':'4.95', 'longitude': '9.933333', 'name':'Nkongsamba' },
'NKU': { 'latitude':'-29.933333', 'longitude': '28.433333', 'name':'Nkaus' },
'NKV': { 'latitude':'55.849722', 'longitude': '-133.227778', 'name':'Nichen Cove' },
'NKX': { 'latitude':'32.868333', 'longitude': '-117.1425', 'name':'Miramar MCAS' },
'NKY': { 'latitude':'-2.933333', 'longitude': '14.266667', 'name':'Nkayi' },
'HHI': { 'latitude':'13.966667', 'longitude': '-4.433333', 'name':'Wheeler AFB' },
'HHH': { 'latitude':'32.224444', 'longitude': '-80.6975', 'name':'Hilton Head' },
'HHN': { 'latitude':'49.948611', 'longitude': '7.263889', 'name':'Frankfurt-Hahn' },
'ROC': { 'latitude':'43.118889', 'longitude': '-77.6725', 'name':'Greater Rochester International' },
'ROD': { 'latitude':'-33.766667', 'longitude': '19.833333', 'name':'Robertson' },
'ROG': { 'latitude':'36.333333', 'longitude': '-94.116667', 'name':'Rogers' },
'UAX': { 'latitude':'17.383333', 'longitude': '-89.666667', 'name':'Uaxactun' },
'UAQ': { 'latitude':'-31.6', 'longitude': '-68.55', 'name':'San Juan' },
'UAP': { 'latitude':'-9.35', 'longitude': '-140.05', 'name':'Ua Pou' },
'UAS': { 'latitude':'0.466667', 'longitude': '37.566667', 'name':'Samburu' },
'UAI': { 'latitude':'-9.3', 'longitude': '125.283333', 'name':'Suai' },
'UAH': { 'latitude':'-8.933333', 'longitude': '-139.55', 'name':'Ua Huka' },
'UAK': { 'latitude':'61.148611', 'longitude': '-45.372222', 'name':'Narsarsuaq' },
'UAM': { 'latitude':'13.433333', 'longitude': '144.766667', 'name':'Andersen AFB' },
'UAL': { 'latitude':'-10.783333', 'longitude': '20.5', 'name':'Luau' },
'UAC': { 'latitude':'32.45', 'longitude': '-114.8', 'name':'San Luis Rio Colorado' },
'UAB': { 'latitude':'38.633333', 'longitude': '28.883333', 'name':'Adana-Incirlik Airbase' },
'UAE': { 'latitude':'-6.233333', 'longitude': '144.65', 'name':'Mount Aue' },
'EHT': { 'latitude':'41.766667', 'longitude': '-72.65', 'name':'Rentschler' },
'SBS': { 'latitude':'40.516667', 'longitude': '-106.866667', 'name':'Steamboat Springs' },
'SBV': { 'latitude':'-5.583333', 'longitude': '155.05', 'name':'Sabah' },
'EHL': { 'latitude':'-41.966667', 'longitude': '-71.516667', 'name':'El Bolson' },
'EHM': { 'latitude':'58.633333', 'longitude': '-162.066667', 'name':'Cape Newenham' },
'ROR': { 'latitude':'7.367222', 'longitude': '134.544167', 'name':'Babelthuap/Koror' },
'SBW': { 'latitude':'2.333333', 'longitude': '111.833333', 'name':'Sibu' },
'LAL': { 'latitude':'28.083333', 'longitude': '-81.95', 'name':'Municipal' },
'LAM': { 'latitude':'35.883333', 'longitude': '-106.316667', 'name':'Los Alamos' },
'LAN': { 'latitude':'42.783333', 'longitude': '-84.583333', 'name':'Capital City' },
'LAO': { 'latitude':'18.183333', 'longitude': '120.533333', 'name':'Laoag International Airport' },
'LAH': { 'latitude':'-0.616667', 'longitude': '127.483333', 'name':'Labuha' },
'LAI': { 'latitude':'48.75', 'longitude': '-3.483333', 'name':'Servel' },
'LAJ': { 'latitude':'-27.8', 'longitude': '-50.316667', 'name':'Lages' },
'LAK': { 'latitude':'68.216667', 'longitude': '-135.0', 'name':'Aklavik' },
'LAD': { 'latitude':'-8.85', 'longitude': '13.233333', 'name':'4 de Fevereiro' },
'LAE': { 'latitude':'-6.569722', 'longitude': '146.706667', 'name':'Nadzab' },
'LAF': { 'latitude':'40.416667', 'longitude': '-86.933333', 'name':'Purdue University' },
'LAG': { 'latitude':'10.533333', 'longitude': '-67.033333', 'name':'La Guaira' },
'LAA': { 'latitude':'38.066667', 'longitude': '-102.683333', 'name':'Lamar Field' },
'LAB': { 'latitude':'-5.633333', 'longitude': '148.066667', 'name':'Lablab' },
'ROU': { 'latitude':'43.833333', 'longitude': '25.983333', 'name':'Rousse' },
'FFO': { 'latitude':'39.826111', 'longitude': '-84.048333', 'name':'Patterson Afb' },
'SBZ': { 'latitude':'45.783333', 'longitude': '24.1', 'name':'Sibiu' },
'FFM': { 'latitude':'46.283333', 'longitude': '-96.166667', 'name':'Fergus Falls' },
'FFL': { 'latitude':'40.933333', 'longitude': '-91.95', 'name':'Municipal' },
'LAX': { 'latitude':'33.9425', 'longitude': '-118.407222', 'name':'Los Angeles International' },
'LAY': { 'latitude':'-28.583333', 'longitude': '29.75', 'name':'Ladysmith' },
'LAZ': { 'latitude':'-13.266667', 'longitude': '-43.416667', 'name':'Bom Jesus Da Lapa' },
'LAT': { 'latitude':'4.75', 'longitude': '-74.05', 'name':'La Uribe' },
'LAU': { 'latitude':'-2.233333', 'longitude': '40.85', 'name':'Lamu' },
'LAV': { 'latitude':'-13.916667', 'longitude': '-172.0', 'name':'Lalomalava' },
'LAW': { 'latitude':'34.566667', 'longitude': '-98.416667', 'name':'Municipal' },
'LAP': { 'latitude':'24.116667', 'longitude': '-110.316667', 'name':'General Manuel Márquez De León International Airport' },
'LAQ': { 'latitude':'32.78861', 'longitude': '21.96417', 'name':'Beida' },
'LAR': { 'latitude':'41.316667', 'longitude': '-105.666667', 'name':'General Brees Field' },
'LAS': { 'latitude':'36.083333', 'longitude': '-115.166667', 'name':'Mc Carran Intl' },
'DTH': { 'latitude':'36.452222', 'longitude': '-116.869167', 'name':'Death Valley' },
'DTN': { 'latitude':'32.540278', 'longitude': '-93.745', 'name':'Shreveport Downtown' },
'DTM': { 'latitude':'51.518333', 'longitude': '7.612222', 'name':'Dortmund' },
'DTL': { 'latitude':'46.833333', 'longitude': '-95.883333', 'name':'Municipal' },
'DTA': { 'latitude':'39.383333', 'longitude': '-112.5', 'name':'Delta' },
'DTE': { 'latitude':'14.129167', 'longitude': '122.980278', 'name':'Naga' },
'MMP': { 'latitude':'9.25', 'longitude': '-74.433333', 'name':'Mompos' },
'DTR': { 'latitude':'42.218611', 'longitude': '-83.348333', 'name':'Decatur Island' },
'DTW': { 'latitude':'42.2125', 'longitude': '-83.353333', 'name':'Detroit Metropolitan Wayne County' },
'SBB': { 'latitude':'7.803611', 'longitude': '-71.165833', 'name':'Santa Barbara Ba' },
'SBC': { 'latitude':'-5.316667', 'longitude': '141.75', 'name':'Selbang' },
'SBA': { 'latitude':'34.427778', 'longitude': '-119.839444', 'name':'Santa Barbara Municipal' },
'SBF': { 'latitude':'33.297778', 'longitude': '68.631667', 'name':'Sardeh Band' },
'MKT': { 'latitude':'44.15', 'longitude': '-93.983333', 'name':'Municipal' },
'IGU': { 'latitude':'-25.683333', 'longitude': '-54.45', 'name':'Cataratas' },
'IGS': { 'latitude':'49.662222', 'longitude': '9.9275', 'name':'Ingolstadt-manching' },
'IGR': { 'latitude':'-25.583333', 'longitude': '-54.333333', 'name':'Cataratas' },
'SBE': { 'latitude':'-6.083333', 'longitude': '142.3', 'name':'Suabi' },
'IGG': { 'latitude':'59.316667', 'longitude': '-155.9', 'name':'Igiugig' },
'SBJ': { 'latitude':'-18.720278', 'longitude': '-39.8325', 'name':'Sao Mateus' },
'IGE': { 'latitude':'-1.916667', 'longitude': '9.316667', 'name':'Iguela' },
'IGB': { 'latitude':'-41.3', 'longitude': '-69.583333', 'name':'Ingeniero Jacobacci' },
'IGA': { 'latitude':'20.983333', 'longitude': '-73.666667', 'name':'Inagua' },
'SBK': { 'latitude':'48.516667', 'longitude': '-2.8', 'name':'Saint Brieuc-Armor' },
'IGO': { 'latitude':'7.685', 'longitude': '-76.694722', 'name':'Chigorodo' },
'IGN': { 'latitude':'8.25', 'longitude': '124.25', 'name':'Maria Cristina' },
'IGM': { 'latitude':'35.25', 'longitude': '-113.933333', 'name':'Kingman' },
'IGL': { 'latitude':'38.516667', 'longitude': '27.016667', 'name':'Cigli Military Arpt' },
'SBH': { 'latitude':'17.866667', 'longitude': '-62.833333', 'name':'St Barthelemy' },
'IGH': { 'latitude':'-18.8', 'longitude': '146.1', 'name':'Ingham' },
'CBB': { 'latitude':'-17.4', 'longitude': '-66.15', 'name':'J Wilsterman' },
'CBC': { 'latitude':'-18.666667', 'longitude': '125.366667', 'name':'Cherrabun' },
'CBA': { 'latitude':'57.716667', 'longitude': '-135.2', 'name':'Corner Bay' },
'CBF': { 'latitude':'41.266667', 'longitude': '-95.866667', 'name':'Municipal' },
'CBG': { 'latitude':'52.2', 'longitude': '0.183333', 'name':'Cambridge' },
'CBD': { 'latitude':'9.166667', 'longitude': '92.783333', 'name':'Car Nicobar' },
'CBE': { 'latitude':'39.6', 'longitude': '-78.766667', 'name':'Wiley Ford' },
'CBJ': { 'latitude':'17.933333', 'longitude': '-71.65', 'name':'Cabo Rojo' },
'CBK': { 'latitude':'39.416667', 'longitude': '-101.05', 'name':'Municipal' },
'CBH': { 'latitude':'31.65', 'longitude': '-2.25', 'name':'Leger' },
'CBI': { 'latitude':'-40.333333', 'longitude': '148.166667', 'name':'Cape Barren Island' },
'CBN': { 'latitude':'-6.75', 'longitude': '108.533333', 'name':'Penggung' },
'CBO': { 'latitude':'7.2', 'longitude': '124.166667', 'name':'Awang' },
'CBL': { 'latitude':'8.133333', 'longitude': '-63.533333', 'name':'Ciudad Bolivar' },
'CBM': { 'latitude':'33.643889', 'longitude': '-88.443889', 'name':'Columbus AFB' },
'CBR': { 'latitude':'-35.306944', 'longitude': '149.195', 'name':'Canberra' },
'CBS': { 'latitude':'10.383333', 'longitude': '-71.466667', 'name':'Oro Negro' },
'CBP': { 'latitude':'40.161389', 'longitude': '-8.472222', 'name':'Coimbra' },
'CBQ': { 'latitude':'4.983333', 'longitude': '8.333333', 'name':'Calabar' },
'CBV': { 'latitude':'15.583333', 'longitude': '-90.25', 'name':'Coban' },
'CBW': { 'latitude':'-24.05', 'longitude': '-52.366667', 'name':'Campo Mourao' },
'CBT': { 'latitude':'-12.483333', 'longitude': '13.483333', 'name':'Catumbela' },
'PJZ': { 'latitude':'21.133333', 'longitude': '-86.866667', 'name':'Puerto Vallarta' },
'CBZ': { 'latitude':'55.383333', 'longitude': '-132.416667', 'name':'Cabin Creek' },
'CBX': { 'latitude':'-33.066667', 'longitude': '147.2', 'name':'Condobolin' },
'CBY': { 'latitude':'-19.633333', 'longitude': '140.916667', 'name':'Canobie' },
'PJS': { 'latitude':'60.05', 'longitude': '-148.066667', 'name':'Port San Juan' },
'BZV': { 'latitude':'-4.25', 'longitude': '15.25', 'name':'Maya Maya' },
'BZU': { 'latitude':'2.8', 'longitude': '24.733333', 'name':'Buta' },
'BZT': { 'latitude':'29.05', 'longitude': '-95.566667', 'name':'Hinkles Ferry' },
'BZS': { 'latitude':'49.0', 'longitude': '-72.5', 'name':'Buzzards Pt S' },
'BZR': { 'latitude':'43.323333', 'longitude': '3.353333', 'name':'Beziers Vias' },
'KOH': { 'latitude':'-15.966667', 'longitude': '142.416667', 'name':'Koolatah' },
'BZZ': { 'latitude':'51.75', 'longitude': '-1.583889', 'name':'Raf Brize Norton' },
'BZY': { 'latitude':'47.838056', 'longitude': '27.781389', 'name':'Beltsy' },
'BZG': { 'latitude':'53.096667', 'longitude': '17.977778', 'name':'Bydgoszcz I. J. Paderewski Airport' },
'BZE': { 'latitude':'17.533333', 'longitude': '-88.3', 'name':'Philip S.W.Goldson Int' },
'BZD': { 'latitude':'-34.633333', 'longitude': '143.55', 'name':'Balranald' },
'BZC': { 'latitude':'-22.769444', 'longitude': '-41.964444', 'name':'Buzios' },
'BZB': { 'latitude':'-18.716667', 'longitude': '36.333333', 'name':'Bazaruto Island' },
'BZA': { 'latitude':'13.95', 'longitude': '-84.6', 'name':'San Pedro' },
'BZO': { 'latitude':'46.45', 'longitude': '11.316667', 'name':'Bolzano' },
'BZN': { 'latitude':'45.7775', 'longitude': '-111.153056', 'name':'Gallatin Field' },
'BZM': { 'latitude':'51.5', 'longitude': '4.283333', 'name':'Woensdrecht' },
'BZL': { 'latitude':'22.666667', 'longitude': '90.341667', 'name':'Barisal' },
'BZK': { 'latitude':'53.266667', 'longitude': '34.333333', 'name':'Briansk' },
'BZI': { 'latitude':'39.616667', 'longitude': '27.933333', 'name':'Balikesir' },
'BZH': { 'latitude':'-17.483333', 'longitude': '28.516667', 'name':'Bumi Hills' },
'ERR': { 'latitude':'44.7925', 'longitude': '-71.164722', 'name':'Errol' },
'PZL': { 'latitude':'-27.866667', 'longitude': '32.3', 'name':'Zulu Inyala' },
'ERS': { 'latitude':'-22.619444', 'longitude': '17.083333', 'name':'Eros' },
'BDZ': { 'latitude':'-6.333333', 'longitude': '146.95', 'name':'Baindoung' },
'MVP': { 'latitude':'1.133333', 'longitude': '-70.05', 'name':'Mitu' },
'MVQ': { 'latitude':'53.95', 'longitude': '30.133333', 'name':'Mogilev' },
'MVR': { 'latitude':'10.45', 'longitude': '14.25', 'name':'Salam' },
'MVS': { 'latitude':'-18.048889', 'longitude': '-39.864167', 'name':'Aeroporto Max Feffer' },
'MVT': { 'latitude':'-14.883333', 'longitude': '-148.666667', 'name':'Mataiva' },
'MVU': { 'latitude':'-14.166667', 'longitude': '143.683333', 'name':'Musgrave' },
'MVV': { 'latitude':'45.866667', 'longitude': '6.616667', 'name':'Megeve' },
'MVW': { 'latitude':'48.416667', 'longitude': '-122.333333', 'name':'Skagit Regional' },
'MVX': { 'latitude':'2.15', 'longitude': '12.133333', 'name':'Minvoul' },
'MVY': { 'latitude':'41.392778', 'longitude': '-70.616667', 'name':'Martha\'s Vineyard' },
'MVZ': { 'latitude':'-20.066667', 'longitude': '30.833333', 'name':'Masvingo' },
'MVA': { 'latitude':'65.616667', 'longitude': '-16.966667', 'name':'Reykiahlid' },
'MVB': { 'latitude':'-1.65', 'longitude': '13.433333', 'name':'Franceville/Mvengue' },
'MVC': { 'latitude':'10.1', 'longitude': '18.75', 'name':'Monroe - Walton County' },
'MVD': { 'latitude':'-34.838333', 'longitude': '-56.030833', 'name':'Carrasco International' },
'MVE': { 'latitude':'44.969167', 'longitude': '-95.710278', 'name':'Montevideo-Chippewa' },
'MVF': { 'latitude':'-5.183333', 'longitude': '-37.333333', 'name':'Dixsept Rosado' },
'MVG': { 'latitude':'0.083333', 'longitude': '11.083333', 'name':'Mevang' },
'MVH': { 'latitude':'-30.716667', 'longitude': '152.916667', 'name':'Macksville' },
'MVI': { 'latitude':'-6.0', 'longitude': '155.333333', 'name':'Manetai' },
'MVJ': { 'latitude':'18.016667', 'longitude': '-77.5', 'name':'Marlboro' },
'MVK': { 'latitude':'-28.35', 'longitude': '138.65', 'name':'Mulka' },
'MVL': { 'latitude':'44.583333', 'longitude': '-72.625', 'name':'Morrisville-Stowe' },
'MVM': { 'latitude':'36.709722', 'longitude': '-110.236667', 'name':'Monument Valley' },
'MVN': { 'latitude':'38.316667', 'longitude': '-88.866667', 'name':'Mt Vernon-Outland' },
'MVO': { 'latitude':'12.2', 'longitude': '18.783333', 'name':'Mongo' },
'ALN': { 'latitude':'38.891667', 'longitude': '-90.172222', 'name':'Alton' },
'KOY': { 'latitude':'57.15', 'longitude': '-154.233333', 'name':'Olga Bay SPB' },
'ALL': { 'latitude':'44.033333', 'longitude': '8.116667', 'name':'Albenga' },
'ALM': { 'latitude':'32.833333', 'longitude': '-106.0', 'name':'Municipal' },
'ALJ': { 'latitude':'-28.616667', 'longitude': '16.533333', 'name':'Kortdoorn' },
'ALK': { 'latitude':'7.966667', 'longitude': '39.116667', 'name':'Asela' },
'ALH': { 'latitude':'-34.95', 'longitude': '117.8', 'name':'Albany' },
'KOX': { 'latitude':'-4.533333', 'longitude': '136.55', 'name':'Kokonao' },
'ALF': { 'latitude':'69.983333', 'longitude': '23.366667', 'name':'Alta' },
'ALG': { 'latitude':'36.783333', 'longitude': '3.05', 'name':'Houari Boumediene' },
'ALD': { 'latitude':'-11.7', 'longitude': '-69.35', 'name':'Alerta' },
'ALE': { 'latitude':'30.386111', 'longitude': '-103.683333', 'name':'Alpine' },
'ALB': { 'latitude':'42.733333', 'longitude': '-73.8', 'name':'Albany International' },
'ALC': { 'latitude':'38.282222', 'longitude': '-0.558056', 'name':'Alicante El Altet' },
'ALA': { 'latitude':'43.351944', 'longitude': '77.040278', 'name':'Almaty' },
'NTI': { 'latitude':'-2.1', 'longitude': '133.516667', 'name':'Bintuni' },
'NTJ': { 'latitude':'39.266667', 'longitude': '-111.633333', 'name':'Manti-Ephraim' },
'ALZ': { 'latitude':'56.895833', 'longitude': '-154.245833', 'name':'Alitak SPB' },
'NTL': { 'latitude':'-32.795', 'longitude': '151.834444', 'name':'Williamtown' },
'ALX': { 'latitude':'32.933333', 'longitude': '-85.95', 'name':'Thomas C Russell Fld' },
'ALY': { 'latitude':'31.183333', 'longitude': '29.95', 'name':'El Nohza' },
'NTA': { 'latitude':'-18.083333', 'longitude': '177.316667', 'name':'Natadola' },
'ALW': { 'latitude':'46.1', 'longitude': '-118.3', 'name':'Walla Walla' },
'NTC': { 'latitude':'21.618333', 'longitude': '35.341667', 'name':'Santa Carolina' },
'ALU': { 'latitude':'11.883333', 'longitude': '50.666667', 'name':'Alula' },
'ALR': { 'latitude':'-45.216667', 'longitude': '169.366667', 'name':'Alexandra' },
'NTD': { 'latitude':'34.120278', 'longitude': '-119.121111', 'name':'Point Mugu NAS' },
'ALP': { 'latitude':'36.183333', 'longitude': '37.233333', 'name':'Nejrab' },
'ALQ': { 'latitude':'-29.8', 'longitude': '-55.733333', 'name':'Federal' },
'ERM': { 'latitude':'-27.659444', 'longitude': '-52.275556', 'name':'Comandante Kraemer' },
'ERN': { 'latitude':'-6.583333', 'longitude': '-69.883333', 'name':'Eirunepe' },
'ERO': { 'latitude':'61.0', 'longitude': '8.15', 'name':'Coast Guard' },
'SOT': { 'latitude':'67.383333', 'longitude': '26.616667', 'name':'Sodankyla' },
'KOU': { 'latitude':'-1.116667', 'longitude': '12.508333', 'name':'Koulamoutou' },
'KOT': { 'latitude':'63.033333', 'longitude': '-163.533333', 'name':'Kotlik' },
'KTX': { 'latitude':'12.383333', 'longitude': '-5.466667', 'name':'Koutiala' },
'KTY': { 'latitude':'6.0', 'longitude': '80.3', 'name':'Katukurunda Slaf Base' },
'KTZ': { 'latitude':'22.322778', 'longitude': '114.216667', 'name':'Kwun Tong' },
'KTT': { 'latitude':'67.701111', 'longitude': '24.846944', 'name':'Kittila' },
'KTU': { 'latitude':'25.0', 'longitude': '76.5', 'name':'Kota' },
'KTV': { 'latitude':'5.75', 'longitude': '-62.416667', 'name':'Kamarata' },
'KTW': { 'latitude':'50.474167', 'longitude': '19.08', 'name':'Pyrzowice' },
'KTP': { 'latitude':'18.016667', 'longitude': '-76.816667', 'name':'Tinson' },
'KTR': { 'latitude':'-14.516667', 'longitude': '132.366667', 'name':'Tindal' },
'KTS': { 'latitude':'65.333333', 'longitude': '-166.483333', 'name':'Brevig Mission' },
'KTL': { 'latitude':'0.966667', 'longitude': '34.95', 'name':'Kitale' },
'KTM': { 'latitude':'27.696667', 'longitude': '85.359167', 'name':'Tribhuvan' },
'KTN': { 'latitude':'55.333333', 'longitude': '-131.65', 'name':'International' },
'KTO': { 'latitude':'4.65', 'longitude': '-59.816667', 'name':'Kato' },
'KTH': { 'latitude':'27.666667', 'longitude': '88.516667', 'name':'SPB' },
'KTI': { 'latitude':'12.483333', 'longitude': '106.05', 'name':'Kratie' },
'KTK': { 'latitude':'-5.338889', 'longitude': '154.75', 'name':'Kanua' },
'KTD': { 'latitude':'25.95', 'longitude': '131.3', 'name':'Kitadaito' },
'KTE': { 'latitude':'4.483333', 'longitude': '103.433333', 'name':'Kerteh' },
'KTF': { 'latitude':'-40.85', 'longitude': '172.8', 'name':'Takaka' },
'KTG': { 'latitude':'-1.833333', 'longitude': '109.983333', 'name':'Ketapang' },
'KTA': { 'latitude':'-20.716667', 'longitude': '116.766667', 'name':'Karratha' },
'KTB': { 'latitude':'55.688333', 'longitude': '-132.535', 'name':'Thorne Bay' },
'KTC': { 'latitude':'8.133333', 'longitude': '-5.1', 'name':'Katiola' },
'YMP': { 'latitude':'50.583333', 'longitude': '-127.1', 'name':'Port McNeil' },
'YMS': { 'latitude':'-5.9', 'longitude': '-76.1', 'name':'Yurimaguas' },
'YMR': { 'latitude':'47.85', 'longitude': '3.683333', 'name':'Merry Island' },
'YMT': { 'latitude':'49.916667', 'longitude': '-74.366667', 'name':'Chibougamau' },
'YMW': { 'latitude':'46.272778', 'longitude': '-75.990556', 'name':'Maniwaki' },
'YMX': { 'latitude':'45.666667', 'longitude': '-74.033333', 'name':'Mirabel' },
'YMA': { 'latitude':'63.616667', 'longitude': '-135.866667', 'name':'Mayo' },
'YMC': { 'latitude':'56.516667', 'longitude': '-71.066667', 'name':'Maricourt Airstrip' },
'YMB': { 'latitude':'50.116667', 'longitude': '-120.783333', 'name':'Merritt' },
'YME': { 'latitude':'48.85', 'longitude': '-67.55', 'name':'Matane' },
'YMG': { 'latitude':'49.133333', 'longitude': '-85.733333', 'name':'Manitouwadge' },
'YMF': { 'latitude':'48.816667', 'longitude': '-123.2', 'name':'Montagne Harbor' },
'YMI': { 'latitude':'49.983333', 'longitude': '-94.733333', 'name':'Minaki' },
'YMH': { 'latitude':'52.3', 'longitude': '-55.833333', 'name':'Mary\'s Harbour' },
'YMJ': { 'latitude':'50.330278', 'longitude': '-105.559167', 'name':'Moose Jaw / Air Vice Marshal C. M. Mcewen Airport' },
'YMM': { 'latitude':'56.65', 'longitude': '-111.216667', 'name':'Fort Mcmurray' },
'YML': { 'latitude':'47.5975', 'longitude': '-70.223889', 'name':'Charlevoix' },
'YMO': { 'latitude':'51.291111', 'longitude': '-80.607778', 'name':'Moosonee' },
'YMN': { 'latitude':'55.083333', 'longitude': '-59.166667', 'name':'Makkovik' },
'MZY': { 'latitude':'-34.183333', 'longitude': '22.15', 'name':'Mossel Bay' },
'YPQ': { 'latitude':'44.23', 'longitude': '-78.363333', 'name':'Peterborough' },
'PMT': { 'latitude':'4.833333', 'longitude': '-59.55', 'name':'Paramakotoi' },
'PMU': { 'latitude':'61.966667', 'longitude': '-160.233333', 'name':'SPB' },
'WOT': { 'latitude':'23.416667', 'longitude': '119.5', 'name':'Wonan' },
'WOW': { 'latitude':'61.75', 'longitude': '-150.05', 'name':'Willow' },
'PMV': { 'latitude':'10.913056', 'longitude': '-63.9675', 'name':'Del Caribe International' },
'WOR': { 'latitude':'-12.433333', 'longitude': '49.1', 'name':'Moramba' },
'WOL': { 'latitude':'-34.5625', 'longitude': '150.788056', 'name':'Wollongong' },
'WOO': { 'latitude':'65.3', 'longitude': '-143.483333', 'name':'Woodchopper' },
'PMW': { 'latitude':'-10.29', 'longitude': '-48.357778', 'name':'Palmas' },
'WOI': { 'latitude':'8.266667', 'longitude': '-9.75', 'name':'Wologissi' },
'WOK': { 'latitude':'5.25', 'longitude': '-61.733333', 'name':'Wonken' },
'WOE': { 'latitude':'51.449167', 'longitude': '4.341944', 'name':'Woensdrecht' },
'PMP': { 'latitude':'-6.366667', 'longitude': '143.55', 'name':'Pimaga' },
'WOG': { 'latitude':'-22.5', 'longitude': '134.25', 'name':'Woodgreen' },
'WOA': { 'latitude':'-6.8', 'longitude': '145.883333', 'name':'Wonenara' },
'WOB': { 'latitude':'51.55', 'longitude': '-0.716667', 'name':'Woodbridge RAF' },
'PMR': { 'latitude':'-40.320556', 'longitude': '175.616944', 'name':'Palmerston North' },
'PMS': { 'latitude':'34.566667', 'longitude': '38.3', 'name':'Palmyra' },
'YPG': { 'latitude':'49.983333', 'longitude': '-98.3', 'name':'Portage La Prairie' },
'PMX': { 'latitude':'42.15', 'longitude': '-72.316667', 'name':'Metropolitan' },
'PMY': { 'latitude':'-42.733333', 'longitude': '-65.066667', 'name':'El Tehuelche' },
'SKP': { 'latitude':'41.961667', 'longitude': '21.621389', 'name':'Petrovec' },
'PMD': { 'latitude':'34.629444', 'longitude': '-118.084444', 'name':'La Palmdale Regional Airport' },
'PME': { 'latitude':'50.833333', 'longitude': '-1.05', 'name':'Portsmouth' },
'PMG': { 'latitude':'-22.533333', 'longitude': '-55.733333', 'name':'International' },
'YPM': { 'latitude':'51.816667', 'longitude': '-94.0', 'name':'Pikangikum' },
'PML': { 'latitude':'55.983333', 'longitude': '-160.533333', 'name':'AFS' },
'PMM': { 'latitude':'13.75', 'longitude': '101.4', 'name':'Phanom Sarakham' },
'PMN': { 'latitude':'-9.816667', 'longitude': '149.466667', 'name':'Pumani' },
'PMO': { 'latitude':'38.175833', 'longitude': '13.091111', 'name':'Punta Raisi' },
'PMH': { 'latitude':'38.840556', 'longitude': '-82.847222', 'name':'Greater Portsmouth Regional' },
'PMI': { 'latitude':'39.55', 'longitude': '2.733333', 'name':'Son Sant Joan Airport' },
'PMK': { 'latitude':'-18.083333', 'longitude': '146.683333', 'name':'Palm Island' },
'SKB': { 'latitude':'17.311111', 'longitude': '-62.718611', 'name':'Robert L Bradshaw International' },
'PQC': { 'latitude':'10.25', 'longitude': '104.0', 'name':'Duong Dong' },
'SKH': { 'latitude':'28.333333', 'longitude': '82.508333', 'name':'Surkhet' },
'SOD': { 'latitude':'-23.478056', 'longitude': '-47.49', 'name':'Sorocaba' },
'MFA': { 'latitude':'-7.9', 'longitude': '39.666667', 'name':'Mafia' },
'MFB': { 'latitude':'0.633333', 'longitude': '-69.75', 'name':'Monfort' },
'SNR': { 'latitude':'47.316667', 'longitude': '-2.15', 'name':'Montoir' },
'IZO': { 'latitude':'35.416667', 'longitude': '132.666667', 'name':'Izumo' },
'MFC': { 'latitude':'-29.8', 'longitude': '27.25', 'name':'Mafeteng' },
'IZT': { 'latitude':'16.449444', 'longitude': '-95.093611', 'name':'Ixtepec' },
'MFD': { 'latitude':'40.816667', 'longitude': '-82.516667', 'name':'Lahm Municipal' },
'MFE': { 'latitude':'26.175833', 'longitude': '-98.238611', 'name':'Mc Allen Miller International' },
'JPN': { 'latitude':'49.0', 'longitude': '-72.5', 'name':'Pentagon Army' },
'JPA': { 'latitude':'-7.15', 'longitude': '-34.966667', 'name':'Castro Pinto' },
'GET': { 'latitude':'-28.783333', 'longitude': '114.7', 'name':'Geraldton' },
'JPD': { 'latitude':'34.133333', 'longitude': '-118.133333', 'name':'Heliport' },
'TCW': { 'latitude':'-35.816667', 'longitude': '145.566667', 'name':'Tocumwal' },
'JPR': { 'latitude':'-8.05', 'longitude': '-62.866667', 'name':'Ji-Parana' },
'JPU': { 'latitude':'48.733333', 'longitude': '2.55', 'name':'La Defense Heliport' },
'MFJ': { 'latitude':'-18.6', 'longitude': '179.883333', 'name':'Moala' },
'BGA': { 'latitude':'7.1', 'longitude': '-73.15', 'name':'Palo Negro' },
'BGB': { 'latitude':'-0.1', 'longitude': '11.933333', 'name':'Booue' },
'GEX': { 'latitude':'-38.133333', 'longitude': '144.35', 'name':'Geelong' },
'BGD': { 'latitude':'35.65', 'longitude': '-101.4', 'name':'Borger' },
'BGE': { 'latitude':'30.9', 'longitude': '-84.6', 'name':'Decatur County' },
'BGF': { 'latitude':'4.383333', 'longitude': '18.566667', 'name':'Bangui' },
'BGG': { 'latitude':'6.65', 'longitude': '-4.2', 'name':'Bongouanou' },
'BGH': { 'latitude':'16.633333', 'longitude': '-14.2', 'name':'Abbaye' },
'BGI': { 'latitude':'13.074722', 'longitude': '-59.4925', 'name':'Grantley Adams International' },
'BGJ': { 'latitude':'64.466667', 'longitude': '-21.983333', 'name':'Borgarfjordur Eystri' },
'BGK': { 'latitude':'16.516667', 'longitude': '-88.416667', 'name':'Big Creek' },
'BGL': { 'latitude':'28.216667', 'longitude': '83.666667', 'name':'Baglung' },
'BGM': { 'latitude':'42.208611', 'longitude': '-75.979722', 'name':'Greater Binghamton' },
'BGN': { 'latitude':'51.2', 'longitude': '6.133333', 'name':'R.A.F.' },
'BGO': { 'latitude':'60.3', 'longitude': '5.216667', 'name':'Bergen Airport, Flesland' },
'BGP': { 'latitude':'-2.166667', 'longitude': '10.216667', 'name':'Bongo' },
'BGQ': { 'latitude':'61.533333', 'longitude': '-149.816667', 'name':'Big Lake' },
'BGR': { 'latitude':'44.8', 'longitude': '-68.816667', 'name':'Bangor International Airport' },
'BGS': { 'latitude':'-18.516667', 'longitude': '124.266667', 'name':'Webb AFB' },
'BGT': { 'latitude':'34.593056', 'longitude': '-113.170278', 'name':'Bagdad' },
'BGU': { 'latitude':'4.783333', 'longitude': '22.8', 'name':'Bangassou' },
'BGV': { 'latitude':'-29.166667', 'longitude': '-51.516667', 'name':'Bento Goncalves' },
'BGW': { 'latitude':'33.283333', 'longitude': '44.5', 'name':'Al Rasheed' },
'BGX': { 'latitude':'-31.390833', 'longitude': '-54.109722', 'name':'Airport Cmdt. Gustavo Kraemer' },
'BGY': { 'latitude':'45.673889', 'longitude': '9.704167', 'name':'Orio al Serio' },
'BGZ': { 'latitude':'41.583333', 'longitude': '-8.45', 'name':'Braga' },
'TCQ': { 'latitude':'-18.053333', 'longitude': '-70.275833', 'name':'Tacna' },
'MFP': { 'latitude':'-22.1', 'longitude': '137.983333', 'name':'Manners Creek' },
'MFQ': { 'latitude':'13.5', 'longitude': '7.133333', 'name':'Maradi' },
'MFR': { 'latitude':'42.366667', 'longitude': '-122.866667', 'name':'Rogue Valley International - Medford Airport' },
'TCM': { 'latitude':'47.137778', 'longitude': '-122.476389', 'name':'McChord AFB' },
'GEG': { 'latitude':'47.619722', 'longitude': '-117.533889', 'name':'Spokane International' },
'MFU': { 'latitude':'-13.066667', 'longitude': '31.766667', 'name':'Mfuwe' },
'GPL': { 'latitude':'10.216667', 'longitude': '-83.766667', 'name':'Guapiles' },
'GPN': { 'latitude':'-11.4', 'longitude': '130.433333', 'name':'Garden Point' },
'GPO': { 'latitude':'-35.7', 'longitude': '-63.75', 'name':'General Pico' },
'GEE': { 'latitude':'-41.079167', 'longitude': '146.838889', 'name':'George Town' },
'THY': { 'latitude':'22.95', 'longitude': '30.483333', 'name':'Thohoyandou' },
'VXE': { 'latitude':'16.85', 'longitude': '-24.966667', 'name':'San Pedro' },
'THV': { 'latitude':'48.75', 'longitude': '-64.583333', 'name':'York Airport' },
'THU': { 'latitude':'76.547778', 'longitude': '-68.842778', 'name':'Pituffik' },
'MFW': { 'latitude':'-10.883333', 'longitude': '40.566667', 'name':'Magaruque' },
'THS': { 'latitude':'17.216667', 'longitude': '99.816667', 'name':'Sukhothai' },
'GPA': { 'latitude':'38.25', 'longitude': '21.733333', 'name':'Araxos Airport' },
'GPB': { 'latitude':'-25.383333', 'longitude': '-51.45', 'name':'Tancredo Thomaz Faria' },
'THP': { 'latitude':'40.9', 'longitude': '23.55', 'name':'Hot Springs' },
'THO': { 'latitude':'66.2', 'longitude': '-15.333333', 'name':'Thorshofn' },
'TCF': { 'latitude':'15.583333', 'longitude': '-86.0', 'name':'Tocoa' },
'THM': { 'latitude':'50.233333', 'longitude': '-1.566667', 'name':'Thompsonfield' },
'THL': { 'latitude':'20.4475', 'longitude': '99.880833', 'name':'Tachilek' },
'THK': { 'latitude':'17.4', 'longitude': '104.8', 'name':'Thakhek' },
'GPZ': { 'latitude':'47.216667', 'longitude': '-93.516667', 'name':'Grand Rapids' },
'THH': { 'latitude':'-35.816667', 'longitude': '173.65', 'name':'Taharoa' },
'GPT': { 'latitude':'30.4', 'longitude': '-89.066667', 'name':'Gulfport-Biloxi International' },
'THF': { 'latitude':'52.489722', 'longitude': '13.416667', 'name':'Tempelhof' },
'THE': { 'latitude':'-5.06', 'longitude': '-42.823611', 'name':'Senador Petrônio Portella' },
'THC': { 'latitude':'5.999167', 'longitude': '-8.083889', 'name':'Tchien' },
'TCD': { 'latitude':'-2.933333', 'longitude': '-69.766667', 'name':'Tarapaca' },
'THA': { 'latitude':'35.38', 'longitude': '-86.246389', 'name':'Tullahoma/William Northern Field' },
'GPS': { 'latitude':'-0.433333', 'longitude': '-90.266667', 'name':'Baltra' },
'HJT': { 'latitude':'46.9', 'longitude': '102.766667', 'name':'Khujirt' },
'TCE': { 'latitude':'45.166667', 'longitude': '28.8', 'name':'Tulcea' },
'NIN': { 'latitude':'60.05', 'longitude': '-151.666667', 'name':'Ninilchik' },
'NIO': { 'latitude':'-2.75', 'longitude': '17.7', 'name':'Nioki' },
'NIM': { 'latitude':'13.483333', 'longitude': '2.166667', 'name':'Niamey' },
'NIB': { 'latitude':'63.016667', 'longitude': '-154.383333', 'name':'Nikolai' },
'NIC': { 'latitude':'35.15', 'longitude': '33.266667', 'name':'Nicosia International' },
'NIA': { 'latitude':'7.5', 'longitude': '-8.583333', 'name':'Nimba' },
'NIG': { 'latitude':'-1.383333', 'longitude': '176.433333', 'name':'Nikunau' },
'NIE': { 'latitude':'55.066667', 'longitude': '-132.15', 'name':'Niblack' },
'NIX': { 'latitude':'15.236111', 'longitude': '-9.583333', 'name':'Nioro' },
'NIS': { 'latitude':'-6.433333', 'longitude': '147.333333', 'name':'Simberi' },
'TCA': { 'latitude':'-19.533333', 'longitude': '134.4', 'name':'Tennant Creek' },
'NIT': { 'latitude':'46.316667', 'longitude': '-0.45', 'name':'Niort' },
'NIU': { 'latitude':'-16.13422', 'longitude': '-146.36673', 'name':'Niau' },
'FDE': { 'latitude':'61.391111', 'longitude': '5.756944', 'name':'Bringeland' },
'FDF': { 'latitude':'14.583333', 'longitude': '-61.0', 'name':'Lamentin' },
'FDH': { 'latitude':'47.666667', 'longitude': '9.516667', 'name':'Friedrichshafen' },
'FDK': { 'latitude':'39.4175', 'longitude': '-77.374444', 'name':'Frederick Municipal' },
'FDR': { 'latitude':'34.35', 'longitude': '-98.983333', 'name':'Municipal' },
'FDU': { 'latitude':'-3.311389', 'longitude': '17.381667', 'name':'Bandundu' },
'FDY': { 'latitude':'41.016667', 'longitude': '-83.666667', 'name':'Findlay' },
'JGC': { 'latitude':'35.975', 'longitude': '-112.140278', 'name':'Heliport' },
'EFW': { 'latitude':'42.016667', 'longitude': '-94.383333', 'name':'Municipal' },
'EFK': { 'latitude':'44.883333', 'longitude': '-72.233333', 'name':'Newport' },
'EFL': { 'latitude':'38.1175', 'longitude': '20.500278', 'name':'Kefalonia Istland International Airport' },
'EFB': { 'latitude':'58.0', 'longitude': '-135.733333', 'name':'Eight Fathom Bight' },
'EFD': { 'latitude':'29.602778', 'longitude': '-95.152778', 'name':'Ellington Field' },
'EFG': { 'latitude':'-9.15', 'longitude': '147.666667', 'name':'Efogi' },
'LCV': { 'latitude':'43.833333', 'longitude': '10.583333', 'name':'Lucca' },
'RNJ': { 'latitude':'27.033333', 'longitude': '128.433333', 'name':'Yoronjima' },
'RNI': { 'latitude':'12.083333', 'longitude': '-83.066667', 'name':'Corn Island' },
'RNH': { 'latitude':'45.116667', 'longitude': '-92.533333', 'name':'Municipal' },
'LCR': { 'latitude':'-0.733333', 'longitude': '-73.016667', 'name':'La Chorrera' },
'LCS': { 'latitude':'10.416667', 'longitude': '-85.133333', 'name':'Las Canas' },
'RNL': { 'latitude':'-11.666667', 'longitude': '160.3', 'name':'Rennell' },
'RNC': { 'latitude':'35.69861111', 'longitude': '-85.84388888', 'name':'Warren County' },
'RNB': { 'latitude':'56.266667', 'longitude': '15.266667', 'name':'Kallinge' },
'RNA': { 'latitude':'-9.864444', 'longitude': '161.983056', 'name':'Arona' },
'RNG': { 'latitude':'40.094722', 'longitude': '-108.760556', 'name':'Rangely' },
'LCX': { 'latitude':'25.675556', 'longitude': '116.745556', 'name':'Longyan' },
'LCY': { 'latitude':'51.505278', 'longitude': '0.055278', 'name':'London City Airport' },
'LCF': { 'latitude':'15.816667', 'longitude': '-88.75', 'name':'Las Vegas' },
'LCG': { 'latitude':'43.366667', 'longitude': '-8.383333', 'name':'La Coruna' },
'LCD': { 'latitude':'-23.016667', 'longitude': '29.716667', 'name':'Louis Trichardt' },
'LCE': { 'latitude':'15.75', 'longitude': '-86.833333', 'name':'Goloson International' },
'LCB': { 'latitude':'-1.55', 'longitude': '-47.883333', 'name':'Pontes e Lacerda' },
'LCC': { 'latitude':'40.25', 'longitude': '18.133333', 'name':'Galatina' },
'LCA': { 'latitude':'34.875', 'longitude': '33.624722', 'name':'Larnaca' },
'LCN': { 'latitude':'-30.533333', 'longitude': '139.316667', 'name':'Balcanoona' },
'LCO': { 'latitude':'-1.8', 'longitude': '14.866667', 'name':'Lague' },
'LCL': { 'latitude':'22.283333', 'longitude': '-83.616667', 'name':'La Coloma' },
'LCM': { 'latitude':'-31.0', 'longitude': '-64.533333', 'name':'La Cumbre' },
'LCJ': { 'latitude':'51.721944', 'longitude': '19.398056', 'name':'Lodz Lublinek' },
'LCK': { 'latitude':'40.002778', 'longitude': '-82.883333', 'name':'Rickenbacker' },
'LCH': { 'latitude':'30.116667', 'longitude': '-93.216667', 'name':'Municipal' },
'LCI': { 'latitude':'43.566667', 'longitude': '-71.416667', 'name':'Municipal' },
'DVL': { 'latitude':'48.116667', 'longitude': '-98.9', 'name':'Devils Lake' },
'DVO': { 'latitude':'7.125556', 'longitude': '125.645833', 'name':'Francisco Bangoy International' },
'DVN': { 'latitude':'-24.233333', 'longitude': '141.066667', 'name':'Davenport' },
'DVK': { 'latitude':'64.511389', 'longitude': '-110.289444', 'name':'Diavik' },
'DVA': { 'latitude':'45.883333', 'longitude': '22.916667', 'name':'Deva' },
'DVT': { 'latitude':'33.688333', 'longitude': '-112.0825', 'name':'Phoenix Deer Valley Airport' },
'DVP': { 'latitude':'-24.166667', 'longitude': '141.083333', 'name':'Davenport Downs' },
'DVR': { 'latitude':'-13.75', 'longitude': '130.683333', 'name':'Daly River' },
'OBN': { 'latitude':'56.583333', 'longitude': '-5.5', 'name':'Oban Airport' },
'OBO': { 'latitude':'42.883333', 'longitude': '143.166667', 'name':'Obihiro' },
'OBM': { 'latitude':'-7.75', 'longitude': '147.583333', 'name':'Morobe' },
'OBI': { 'latitude':'-1.866667', 'longitude': '-55.533333', 'name':'Obidos' },
'OBF': { 'latitude':'48.083333', 'longitude': '11.283333', 'name':'Oberpfaffenhofen' },
'OBD': { 'latitude':'-3.9', 'longitude': '136.2', 'name':'Obano' },
'OBE': { 'latitude':'27.25', 'longitude': '-80.833333', 'name':'County' },
'OBC': { 'latitude':'11.916667', 'longitude': '43.25', 'name':'Obock' },
'IEV': { 'latitude':'50.4', 'longitude': '30.466667', 'name':'Zhulhany' },
'IEJ': { 'latitude':'26.733333', 'longitude': '127.783333', 'name':'Iejima' },
'OBX': { 'latitude':'-7.583333', 'longitude': '141.333333', 'name':'Obo' },
'OBY': { 'latitude':'70.483333', 'longitude': '-22.016667', 'name':'Ittoqqortoormiit' },
'OBT': { 'latitude':'17.916667', 'longitude': '-142.05', 'name':'Oakland/Coliseum Stat' },
'OBU': { 'latitude':'66.933333', 'longitude': '-156.866667', 'name':'Kobuk/Wien' },
'OBS': { 'latitude':'44.616667', 'longitude': '4.383333', 'name':'Vals-Lanas' },
'IEG': { 'latitude':'52.138611', 'longitude': '15.798611', 'name':'Babimost' },
'CDD': { 'latitude':'15.316667', 'longitude': '-83.583333', 'name':'Cauquira' },
'CDE': { 'latitude':'8.233333', 'longitude': '-77.333333', 'name':'Caledonia' },
'PLU': { 'latitude':'-19.755556', 'longitude': '-43.75', 'name':'Pampulha Domestic' },
'CDG': { 'latitude':'49.016667', 'longitude': '2.55', 'name':'Charles De Gaulle' },
'PLS': { 'latitude':'21.766667', 'longitude': '-72.266667', 'name':'International' },
'CDA': { 'latitude':'-12.9', 'longitude': '132.516667', 'name':'Cooinda' },
'CDB': { 'latitude':'55.2', 'longitude': '-162.716667', 'name':'Cold Bay' },
'CDC': { 'latitude':'37.7', 'longitude': '-113.1', 'name':'Cedar City' },
'CDL': { 'latitude':'65.9', 'longitude': '-161.916667', 'name':'Candle' },
'CDN': { 'latitude':'34.266667', 'longitude': '-80.6', 'name':'Woodward Fld' },
'CDO': { 'latitude':'-32.155556', 'longitude': '25.645833', 'name':'Cradock' },
'CDH': { 'latitude':'33.616667', 'longitude': '-92.766667', 'name':'Harrell Fld' },
'CDI': { 'latitude':'-12.416667', 'longitude': '-41.633333', 'name':'Cachoeiro Itapemirim' },
'CDJ': { 'latitude':'-8.283333', 'longitude': '-49.283333', 'name':'Conceicao Do Araguaia' },
'CDK': { 'latitude':'29.133333', 'longitude': '-83.033333', 'name':'Lewis' },
'PLG': { 'latitude':'44.633333', 'longitude': '2.566667', 'name':'La Plagne' },
'CDU': { 'latitude':'-34.040278', 'longitude': '150.687222', 'name':'Camden' },
'CDV': { 'latitude':'60.483333', 'longitude': '-145.483333', 'name':'Mudhole Smith' },
'CDW': { 'latitude':'40.875278', 'longitude': '-74.281389', 'name':'Caldwell Wright' },
'CDP': { 'latitude':'14.516667', 'longitude': '78.783333', 'name':'Cuddapah' },
'CDQ': { 'latitude':'-18.3', 'longitude': '142.25', 'name':'Croydon' },
'CDR': { 'latitude':'42.833333', 'longitude': '-103.083333', 'name':'Chadron' },
'CDS': { 'latitude':'34.416667', 'longitude': '-100.216667', 'name':'Childress' },
'PLO': { 'latitude':'-34.6', 'longitude': '135.883333', 'name':'Port Lincoln' },
'PLN': { 'latitude':'45.566667', 'longitude': '-84.8', 'name':'Emmet County' },
'PLM': { 'latitude':'-2.9', 'longitude': '104.7', 'name':'Mahmud Badaruddin Ii' },
'PLL': { 'latitude':'-3.146111', 'longitude': '-59.986389', 'name':'Ponta Pelada' },
'PLK': { 'latitude':'36.616667', 'longitude': '-93.216667', 'name':'M Graham Clark' },
'CDY': { 'latitude':'7.016667', 'longitude': '118.5', 'name':'Cagayan De Sulu' },
'CDZ': { 'latitude':'36.533611', 'longitude': '-6.299444', 'name':'Cadiz' },
'PLH': { 'latitude':'50.416667', 'longitude': '-4.116667', 'name':'Plymouth' },
'BXX': { 'latitude':'9.933333', 'longitude': '43.15', 'name':'Borama International' },
'BXS': { 'latitude':'33.25', 'longitude': '-116.316667', 'name':'Borrego Springs' },
'BXR': { 'latitude':'29.0', 'longitude': '58.5', 'name':'Bam' },
'BXU': { 'latitude':'8.966667', 'longitude': '125.416667', 'name':'Butuan' },
'BXT': { 'latitude':'0.119444', 'longitude': '117.474722', 'name':'Bontang' },
'BXV': { 'latitude':'64.8', 'longitude': '-13.833333', 'name':'Breiddalsvik' },
'BXI': { 'latitude':'9.516667', 'longitude': '-6.483333', 'name':'Boundiali' },
'BXH': { 'latitude':'46.883333', 'longitude': '75.016667', 'name':'Balhash' },
'BXK': { 'latitude':'33.366667', 'longitude': '-112.583333', 'name':'Buckeye Municipal' },
'BXJ': { 'latitude':'45.083333', 'longitude': '74.016667', 'name':'Burundai' },
'BXM': { 'latitude':'-2.283333', 'longitude': '139.6', 'name':'Batom' },
'BXL': { 'latitude':'-16.936111', 'longitude': '177.363889', 'name':'Blue Lagoon' },
'BXO': { 'latitude':'11.883333', 'longitude': '-15.65', 'name':'Buochs' },
'BXN': { 'latitude':'37.134722', 'longitude': '27.667222', 'name':'Imsik Airport' },
'BXA': { 'latitude':'30.783333', 'longitude': '-89.866667', 'name':'George R Carr' },
'BXC': { 'latitude':'42.483611', 'longitude': '-71.535278', 'name':'Boxborough' },
'BXB': { 'latitude':'-2.55', 'longitude': '133.416667', 'name':'Babo' },
'BXE': { 'latitude':'14.916667', 'longitude': '-12.908333', 'name':'Bakel' },
'BXD': { 'latitude':'-7.166667', 'longitude': '139.583333', 'name':'Bade' },
'BXG': { 'latitude':'-36.739444', 'longitude': '144.329722', 'name':'Bendigo' },
'BXF': { 'latitude':'64.233333', 'longitude': '12.5', 'name':'Belburn' },
'WZY': { 'latitude':'25.087222', 'longitude': '-77.323889', 'name':'Paradise Island Seaplane Base' },
'TPN': { 'latitude':'-0.7', 'longitude': '-76.35', 'name':'Tiputini' },
'MTZ': { 'latitude':'31.333333', 'longitude': '35.383333', 'name':'Masada' },
'MTX': { 'latitude':'64.8', 'longitude': '-147.75', 'name':'Metro Field' },
'MTY': { 'latitude':'25.778333', 'longitude': '-100.106389', 'name':'Gen Mariano Escobedo' },
'MTR': { 'latitude':'8.766667', 'longitude': '-75.866667', 'name':'S. Jeronimo' },
'MTS': { 'latitude':'-26.523611', 'longitude': '31.3125', 'name':'Matsapha Intl' },
'MTP': { 'latitude':'41.083333', 'longitude': '-71.916667', 'name':'Montauk Airport' },
'MTQ': { 'latitude':'-26.583333', 'longitude': '147.966667', 'name':'Mitchell' },
'MTV': { 'latitude':'-13.816667', 'longitude': '167.7', 'name':'Mota Lava' },
'MTW': { 'latitude':'44.116667', 'longitude': '-87.666667', 'name':'Municipal' },
'MTT': { 'latitude':'18.0', 'longitude': '-94.533333', 'name':'Minatitlan' },
'MTU': { 'latitude':'-13.127778', 'longitude': '39.002778', 'name':'Montepuez' },
'MTJ': { 'latitude':'38.509722', 'longitude': '-107.894167', 'name':'Montrose Regional Airport' },
'MTK': { 'latitude':'3.116667', 'longitude': '172.8', 'name':'Makin Island' },
'MTH': { 'latitude':'24.716667', 'longitude': '-81.05', 'name':'Marathon Flight Strip' },
'MTI': { 'latitude':'15.0', 'longitude': '-24.433333', 'name':'Mosteiros' },
'MTN': { 'latitude':'39.183333', 'longitude': '-76.683333', 'name':'Glenn L Martin' },
'MTO': { 'latitude':'39.483333', 'longitude': '-88.283333', 'name':'Coles County Memorial' },
'MTL': { 'latitude':'-32.733333', 'longitude': '151.55', 'name':'Maitland' },
'MTM': { 'latitude':'55.133333', 'longitude': '-131.583333', 'name':'SPB' },
'MTB': { 'latitude':'8.083333', 'longitude': '-75.341667', 'name':'Monte Libano' },
'MTA': { 'latitude':'-37.733333', 'longitude': '175.75', 'name':'Matamata' },
'MTF': { 'latitude':'6.966667', 'longitude': '35.533333', 'name':'Mizan Teferi' },
'MTG': { 'latitude':'-15.016667', 'longitude': '-60.016667', 'name':'Mato Grosso' },
'MTD': { 'latitude':'-16.983333', 'longitude': '130.55', 'name':'Mt Sandford' },
'MTE': { 'latitude':'-2.016667', 'longitude': '-54.066667', 'name':'Monte Alegre' },
'ARP': { 'latitude':'-9.9', 'longitude': '149.466667', 'name':'Aragip' },
'ARQ': { 'latitude':'7.036111', 'longitude': '-71.440278', 'name':'Arauquita' },
'ARR': { 'latitude':'-45.166667', 'longitude': '-71.0', 'name':'Alto Rio Senguerr' },
'ARS': { 'latitude':'-15.896667', 'longitude': '-52.095556', 'name':'Aragarcas' },
'ART': { 'latitude':'43.983333', 'longitude': '-76.016667', 'name':'Watertown' },
'ARU': { 'latitude':'-21.183333', 'longitude': '-50.416667', 'name':'Aracatuba' },
'ARV': { 'latitude':'45.916667', 'longitude': '-89.733333', 'name':'Noble F. Lee' },
'ARW': { 'latitude':'46.166667', 'longitude': '21.25', 'name':'Arad' },
'ARX': { 'latitude':'40.219444', 'longitude': '-74.09', 'name':'Asbury Park' },
'ARY': { 'latitude':'-37.309444', 'longitude': '142.988611', 'name':'Ararat' },
'TPU': { 'latitude':'28.5', 'longitude': '81.133333', 'name':'Tikapur' },
'ARA': { 'latitude':'80.133333', 'longitude': '32.583333', 'name':'Acadiana Regional' },
'ARB': { 'latitude':'42.223056', 'longitude': '-83.745556', 'name':'Municipal' },
'ARC': { 'latitude':'68.116667', 'longitude': '-145.583333', 'name':'Arctic Village' },
'ARD': { 'latitude':'-8.25', 'longitude': '124.75', 'name':'Alor Island' },
'ARE': { 'latitude':'18.45', 'longitude': '-66.666667', 'name':'Arecibo' },
'ARF': { 'latitude':'0.533333', 'longitude': '-70.133333', 'name':'Acaricuara' },
'ARG': { 'latitude':'36.116667', 'longitude': '-90.916667', 'name':'Walnut Ridge' },
'ARH': { 'latitude':'64.566667', 'longitude': '40.533333', 'name':'Arkhangelsk' },
'ARI': { 'latitude':'-18.5', 'longitude': '-70.316667', 'name':'Chacalluta' },
'ARJ': { 'latitude':'-2.933333', 'longitude': '140.783333', 'name':'Arso' },
'ARK': { 'latitude':'-3.367778', 'longitude': '36.633333', 'name':'Arusha' },
'ARL': { 'latitude':'11.583333', 'longitude': '1.25', 'name':'Arly' },
'ARM': { 'latitude':'-30.533333', 'longitude': '151.616667', 'name':'Armidale' },
'ARN': { 'latitude':'59.651944', 'longitude': '17.918611', 'name':'Arlanda' },
'ARO': { 'latitude':'8.866667', 'longitude': '-76.433333', 'name':'Arboletas' },
'TPQ': { 'latitude':'21.419444', 'longitude': '-104.8425', 'name':'Tepic' },
'TPP': { 'latitude':'-6.511111', 'longitude': '-76.398611', 'name':'Tarapoto' },
'TPX': { 'latitude':'-16.283333', 'longitude': '-1.833333', 'name':'Tupai' },
'KVG': { 'latitude':'-2.566667', 'longitude': '150.816667', 'name':'Kavieng' },
'KVD': { 'latitude':'40.733333', 'longitude': '46.316667', 'name':'Gyandzha' },
'KVE': { 'latitude':'44.780833', 'longitude': '15.038333', 'name':'Kitava' },
'KVB': { 'latitude':'58.45', 'longitude': '13.966667', 'name':'Skovde' },
'KVC': { 'latitude':'55.066667', 'longitude': '-162.316667', 'name':'King Cove' },
'KVA': { 'latitude':'40.913333', 'longitude': '24.619167', 'name':'Megas Alexandros International' },
'KVL': { 'latitude':'67.733333', 'longitude': '-164.666667', 'name':'Kivalina' },
'KVK': { 'latitude':'67.583333', 'longitude': '33.583333', 'name':'Kirovsk' },
'KVU': { 'latitude':'-18.216667', 'longitude': '177.733333', 'name':'Korolevu' },
'KVR': { 'latitude':'44.2725', 'longitude': '135.0289', 'name':'Kavalerovo' },
'KVX': { 'latitude':'58.5', 'longitude': '49.35', 'name':'Kirov' },
'SOG': { 'latitude':'61.166667', 'longitude': '7.133333', 'name':'Haukasen' },
'YCZ': { 'latitude':'50.330278', 'longitude': '-115.873333', 'name':'Fairmont Hot Springs' },
'YCY': { 'latitude':'70.483333', 'longitude': '-68.516667', 'name':'Clyde River' },
'YCX': { 'latitude':'45.783333', 'longitude': '-66.15', 'name':'Gagetown' },
'YCS': { 'latitude':'63.333333', 'longitude': '-90.7', 'name':'Chesterfield Inlet' },
'YCR': { 'latitude':'54.6', 'longitude': '-97.766667', 'name':'Cross Lake' },
'YCQ': { 'latitude':'55.7', 'longitude': '-121.666667', 'name':'Chetwynd' },
'YCP': { 'latitude':'57.083333', 'longitude': '-103.0', 'name':'Co-op Point' },
'YCW': { 'latitude':'49.152778', 'longitude': '-121.938889', 'name':'Chilliwack Municipal Airport' },
'YCV': { 'latitude':'45.516667', 'longitude': '-73.716667', 'name':'Cartierville' },
'YCU': { 'latitude':'35.183333', 'longitude': '111.05', 'name':'Yun Cheng' },
'YCT': { 'latitude':'52.075', 'longitude': '-111.445278', 'name':'Coronation' },
'YCK': { 'latitude':'67.316667', 'longitude': '-125.666667', 'name':'Colville Lake' },
'YCJ': { 'latitude':'51.933333', 'longitude': '-131.016667', 'name':'Cape St James' },
'YCI': { 'latitude':'47.366667', 'longitude': '-85.816667', 'name':'Caribou Island' },
'YCH': { 'latitude':'47.166667', 'longitude': '-65.0', 'name':'Miramichi' },
'YCO': { 'latitude':'67.833333', 'longitude': '-115.083333', 'name':'Kugluktuk' },
'YCN': { 'latitude':'49.066667', 'longitude': '-81.016667', 'name':'Cochrane' },
'XIY': { 'latitude':'34.447222', 'longitude': '108.751667', 'name':'Xianyang' },
'YCL': { 'latitude':'47.990833', 'longitude': '-66.330278', 'name':'Charlo' },
'YCC': { 'latitude':'45.1', 'longitude': '-74.566667', 'name':'Regional' },
'YCB': { 'latitude':'69.116667', 'longitude': '-105.133333', 'name':'Cambridge Bay' },
'YCA': { 'latitude':'49.683333', 'longitude': '-125.0', 'name':'Courtenay' },
'YCG': { 'latitude':'49.3', 'longitude': '-117.633333', 'name':'Castlegar' },
'YCF': { 'latitude':'50.066667', 'longitude': '-124.933333', 'name':'Cortes Bay' },
'YCD': { 'latitude':'49.166667', 'longitude': '-123.933333', 'name':'Nanaimo Arpt' },
'ZZV': { 'latitude':'39.95', 'longitude': '-81.883333', 'name':'Zanesville' },
'ZZU': { 'latitude':'-11.45', 'longitude': '34.016667', 'name':'Mzuzu' },
'WIE': { 'latitude':'50.040833', 'longitude': '8.256111', 'name':'Air Base' },
'WID': { 'latitude':'51.1025', 'longitude': '6.216667', 'name':'Wildenrath' },
'WIC': { 'latitude':'58.45', 'longitude': '-3.083333', 'name':'Wick' },
'WIO': { 'latitude':'-31.566667', 'longitude': '143.383333', 'name':'Wilcannia' },
'WIN': { 'latitude':'-22.35', 'longitude': '143.066667', 'name':'Winton' },
'XVL': { 'latitude':'10.25', 'longitude': '105.95', 'name':'Vinh Long' },
'WIL': { 'latitude':'-1.316667', 'longitude': '36.816667', 'name':'Wilson' },
'WIK': { 'latitude':'-36.833333', 'longitude': '175.083333', 'name':'Surfdale' },
'WIU': { 'latitude':'-5.566667', 'longitude': '149.183333', 'name':'Witu' },
'WIT': { 'latitude':'-22.266667', 'longitude': '118.333333', 'name':'Wittenoom' },
'VTU': { 'latitude':'20.983333', 'longitude': '-76.933333', 'name':'Las Tunas' },
'HET': { 'latitude':'40.833333', 'longitude': '111.616667', 'name':'Hohhot' },
'TXL': { 'latitude':'52.561111', 'longitude': '13.289444', 'name':'Berlin-tegel / Otto Lilienthal' },
'HEV': { 'latitude':'37.258333', 'longitude': '-6.950833', 'name':'Huelva' },
'NDJ': { 'latitude':'12.133333', 'longitude': '15.033333', 'name':'Ndjamena' },
'XMI': { 'latitude':'-10.733333', 'longitude': '38.766667', 'name':'Masasi' },
'UZH': { 'latitude':'26.1', 'longitude': '43.933333', 'name':'Unayzah' },
'HER': { 'latitude':'35.339722', 'longitude': '25.180278', 'name':'Nikos Kazantzakis Airport' },
'HES': { 'latitude':'45.85', 'longitude': '-119.283333', 'name':'State' },
'UZC': { 'latitude':'43.898889', 'longitude': '19.697778', 'name':'Ponikve' },
'UZU': { 'latitude':'-29.783333', 'longitude': '-58.016667', 'name':'Curuzu Cuatia' },
'HEX': { 'latitude':'19.500556', 'longitude': '-70.235278', 'name':'Santo Domingo Herrera' },
'HEY': { 'latitude':'53.116667', 'longitude': '22.45', 'name':'Hanchey Army Heliport' },
'HEZ': { 'latitude':'31.616667', 'longitude': '-91.3', 'name':'Hardy-Anders' },
'NDY': { 'latitude':'59.466667', 'longitude': '-2.65', 'name':'Sanday' },
}
|
sudhakargmail/botkitwebhooks
|
tools/airports.py
|
Python
|
mit
| 920,906
|
[
"ADF",
"ASE",
"BWA",
"CDK",
"COLUMBUS",
"CRYSTAL",
"Elk",
"MOE",
"MOOSE",
"TINKER"
] |
15c542b20e6fd47131dc137c270aa4813246bea91c80ca6d3336e29b5d7e56af
|
import ocl
import camvtk
import time
import vtk
import datetime
import math
if __name__ == "__main__":
print ocl.version()
myscreen = camvtk.VTKScreen()
a = ocl.Point(0,1,0.3)
myscreen.addActor(camvtk.Point(center=(a.x,a.y,a.z), color=(1,0,1)))
b = ocl.Point(1,0.5,0.3)
myscreen.addActor(camvtk.Point(center=(b.x,b.y,b.z), color=(1,0,1)))
c = ocl.Point(0,0,0)
myscreen.addActor(camvtk.Point(center=(c.x,c.y,c.z), color=(1,0,1)))
myscreen.addActor( camvtk.Line(p1=(a.x,a.y,a.z),p2=(c.x,c.y,c.z)) )
myscreen.addActor( camvtk.Line(p1=(c.x,c.y,c.z),p2=(b.x,b.y,b.z)) )
myscreen.addActor( camvtk.Line(p1=(a.x,a.y,a.z),p2=(b.x,b.y,b.z)) )
t = ocl.Triangle(b,c,a)
s = ocl.STLSurf()
s.addTriangle(t) # a one-triangle STLSurf
zheights=[-0.3, -0.2, -0.1, -0.05, 0.0, 0.05, 0.1, 0.15, 0.2, 0.25, 0.26, 0.27, 0.28, 0.29 ] # the z-coordinates for the waterlines
zheights=[-0.8, -0.7, -0.6, -0.5, -0.4, -0.3, -0.2, -0.1, -0.05, 0.0, 0.05, 0.1, 0.15, 0.2, 0.28 ]
zheights=[ -0.35, -0.3, -0.25, -0.2, -0.15, -0.1, -0.05, 0.0, 0.05, 0.1, 0.15, 0.2, 0.25, 0.28]
cutter_diams = [0.6] # run the thing for all these cutter diameters
length = 5
loops = []
cutter = ocl.CylCutter( 1 , 1 )
t_total = time.time()
for zh in zheights:
for diam in cutter_diams:
cutter = ocl.CylCutter( diam , length )
cutter = ocl.BallCutter( diam , length )
#cutter = ocl.BullCutter( diam , diam/5, length )
#cutter = ocl.ConeCutter( diam , math.pi/5, length )
wl = ocl.Waterline()
#wl.setThreads(1)
wl.setSTL(s)
wl.setCutter(cutter)
wl.setZ(zh)
wl.setSampling(0.02)
wl.setThreads(1)
t_before = time.time()
wl.run()
t_after = time.time()
calctime = t_after-t_before
print " Waterline done in ", calctime," s"
cutter_loops = wl.getLoops()
for l in cutter_loops:
loops.append(l)
print " ALL Waterlines done in ", time.time()-t_total," s"
#print loops
print "All waterlines done. Got", len(loops)," loops in total."
# draw the loops
nloop=0
for lop in loops:
n = 0
N = len(lop)
first_point=ocl.Point(-1,-1,5)
previous=ocl.Point(-1,-1,5)
for p in lop:
if n==0: # don't draw anything on the first iteration
previous=p
first_point = p
elif n== (N-1): # the last point
myscreen.addActor( camvtk.Line(p1=(previous.x,previous.y,previous.z),p2=(p.x,p.y,p.z),color=camvtk.yellow) ) # the normal line
# and a line from p to the first point
myscreen.addActor( camvtk.Line(p1=(p.x,p.y,p.z),p2=(first_point.x,first_point.y,first_point.z),color=camvtk.yellow) )
else:
myscreen.addActor( camvtk.Line(p1=(previous.x,previous.y,previous.z),p2=(p.x,p.y,p.z),color=camvtk.yellow) )
previous=p
n=n+1
print "rendered loop ",nloop, " with ", len(lop), " points"
nloop = nloop+1
print "done."
myscreen.camera.SetPosition(2, 2, 2)
myscreen.camera.SetFocalPoint(0.5, 0.5, 0)
camvtk.drawArrows(myscreen,center=(-0.5,-0.5,-0.5))
camvtk.drawOCLtext(myscreen)
myscreen.render()
myscreen.iren.Start()
#raw_input("Press Enter to terminate")
|
JohnyEngine/CNC
|
opencamlib/scripts/waterline/waterline_0_onetriangle.py
|
Python
|
apache-2.0
| 3,500
|
[
"VTK"
] |
782acb3774d12fb2d974d21cba06fce770f993434b471f9e50016528d9790a70
|
#!/usr/bin/env python
##################################################
## DEPENDENCIES
import sys
import os
import os.path
try:
import builtins as builtin
except ImportError:
import __builtin__ as builtin
from os.path import getmtime, exists
import time
import types
from Cheetah.Version import MinCompatibleVersion as RequiredCheetahVersion
from Cheetah.Version import MinCompatibleVersionTuple as RequiredCheetahVersionTuple
from Cheetah.Template import Template
from Cheetah.DummyTransaction import *
from Cheetah.NameMapper import NotFound, valueForName, valueFromSearchList, valueFromFrameOrSearchList
from Cheetah.CacheRegion import CacheRegion
import Cheetah.Filters as Filters
import Cheetah.ErrorCatchers as ErrorCatchers
##################################################
## MODULE CONSTANTS
VFFSL=valueFromFrameOrSearchList
VFSL=valueFromSearchList
VFN=valueForName
currentTime=time.time
__CHEETAH_version__ = '2.4.4'
__CHEETAH_versionTuple__ = (2, 4, 4, 'development', 0)
__CHEETAH_genTime__ = 1447321436.180396
__CHEETAH_genTimestamp__ = 'Thu Nov 12 18:43:56 2015'
__CHEETAH_src__ = '/home/knuth/openpli-oe-core/build/tmp/work/fusionhd-oe-linux/enigma2-plugin-extensions-openwebif/1+gitAUTOINC+5837c87afc-r0/git/plugin/controllers/views/web/bouquets.tmpl'
__CHEETAH_srcLastModified__ = 'Thu Nov 12 18:43:41 2015'
__CHEETAH_docstring__ = 'Autogenerated by Cheetah: The Python-Powered Template Engine'
if __CHEETAH_versionTuple__ < RequiredCheetahVersionTuple:
raise AssertionError(
'This template was compiled with Cheetah version'
' %s. Templates compiled before version %s must be recompiled.'%(
__CHEETAH_version__, RequiredCheetahVersion))
##################################################
## CLASSES
class bouquets(Template):
##################################################
## CHEETAH GENERATED METHODS
def __init__(self, *args, **KWs):
super(bouquets, self).__init__(*args, **KWs)
if not self._CHEETAH__instanceInitialized:
cheetahKWArgs = {}
allowedKWs = 'searchList namespaces filter filtersLib errorCatcher'.split()
for k,v in KWs.items():
if k in allowedKWs: cheetahKWArgs[k] = v
self._initCheetahInstance(**cheetahKWArgs)
def respond(self, trans=None):
## CHEETAH: main method generated for this template
if (not trans and not self._CHEETAH__isBuffering and not callable(self.transaction)):
trans = self.transaction # is None unless self.awake() was called
if not trans:
trans = DummyTransaction()
_dummyTrans = True
else: _dummyTrans = False
write = trans.response().write
SL = self._CHEETAH__searchList
_filter = self._CHEETAH__currentFilter
########################################
## START - generated method body
_orig_filter_89368407 = _filter
filterName = u'WebSafe'
if self._CHEETAH__filters.has_key("WebSafe"):
_filter = self._CHEETAH__currentFilter = self._CHEETAH__filters[filterName]
else:
_filter = self._CHEETAH__currentFilter = \
self._CHEETAH__filters[filterName] = getattr(self._CHEETAH__filtersLib, filterName)(self).filter
write(u'''<?xml version="1.0" encoding="UTF-8"?>
<e2servicelist>
''')
for bouquet in VFFSL(SL,"bouquets",True): # generated from line 4, col 2
write(u'''\t<e2service>
\t\t<e2servicereference>''')
_v = VFFSL(SL,"bouquet",True)[0] # u'$bouquet[0]' on line 6, col 23
if _v is not None: write(_filter(_v, rawExpr=u'$bouquet[0]')) # from line 6, col 23.
write(u'''</e2servicereference>
\t\t<e2servicename>''')
_v = VFFSL(SL,"bouquet",True)[1] # u'$bouquet[1]' on line 7, col 18
if _v is not None: write(_filter(_v, rawExpr=u'$bouquet[1]')) # from line 7, col 18.
write(u'''</e2servicename>
\t</e2service>
''')
write(u'''</e2servicelist>
''')
_filter = self._CHEETAH__currentFilter = _orig_filter_89368407
########################################
## END - generated method body
return _dummyTrans and trans.response().getvalue() or ""
##################################################
## CHEETAH GENERATED ATTRIBUTES
_CHEETAH__instanceInitialized = False
_CHEETAH_version = __CHEETAH_version__
_CHEETAH_versionTuple = __CHEETAH_versionTuple__
_CHEETAH_genTime = __CHEETAH_genTime__
_CHEETAH_genTimestamp = __CHEETAH_genTimestamp__
_CHEETAH_src = __CHEETAH_src__
_CHEETAH_srcLastModified = __CHEETAH_srcLastModified__
_mainCheetahMethod_for_bouquets= 'respond'
## END CLASS DEFINITION
if not hasattr(bouquets, '_initCheetahAttributes'):
templateAPIClass = getattr(bouquets, '_CHEETAH_templateClass', Template)
templateAPIClass._addCheetahPlumbingCodeToClass(bouquets)
# CHEETAH was developed by Tavis Rudd and Mike Orr
# with code, advice and input from many other volunteers.
# For more information visit http://www.CheetahTemplate.org/
##################################################
## if run from command line:
if __name__ == '__main__':
from Cheetah.TemplateCmdLineIface import CmdLineIface
CmdLineIface(templateObj=bouquets()).run()
|
pli3/e2-openwbif
|
plugin/controllers/views/web/bouquets.py
|
Python
|
gpl-2.0
| 5,385
|
[
"VisIt"
] |
4eabd12190831a683170e02666c6b694fa4b0bc9458c1e8e39f52a35ff26f07c
|
import param
import numpy as np
import pandas as pd
from ..core import Operation, Element
from ..core.data import PandasInterface
from ..core.util import pandas_version
from ..element import Scatter
class RollingBase(param.Parameterized):
"""
Parameters shared between `rolling` and `rolling_outlier_std`.
"""
center = param.Boolean(default=True, doc="""
Whether to set the x-coordinate at the center or right edge
of the window.""")
min_periods = param.Integer(default=None, doc="""
Minimum number of observations in window required to have a
value (otherwise result is NaN).""")
rolling_window = param.Integer(default=10, doc="""
The window size over which to operate.""")
def _roll_kwargs(self):
return {'window': self.p.rolling_window,
'center': self.p.center,
'min_periods': self.p.min_periods}
class rolling(Operation,RollingBase):
"""
Applies a function over a rolling window.
"""
window_type = param.ObjectSelector(default=None,
objects=['boxcar', 'triang', 'blackman', 'hamming', 'bartlett',
'parzen', 'bohman', 'blackmanharris', 'nuttall',
'barthann', 'kaiser', 'gaussian', 'general_gaussian',
'slepian'], doc="The shape of the window to apply")
function = param.Callable(default=np.mean, doc="""
The function to apply over the rolling window.""")
def _process_layer(self, element, key=None):
xdim = element.kdims[0].name
df = PandasInterface.as_dframe(element)
df = df.set_index(xdim).rolling(win_type=self.p.window_type,
**self._roll_kwargs())
if self.p.window_type is None:
kwargs = {'raw': True} if pandas_version >= '0.23.0' else {}
rolled = df.apply(self.p.function, **kwargs)
else:
if self.p.function is np.mean:
rolled = df.mean()
elif self.p.function is np.sum:
rolled = df.sum()
else:
raise ValueError("Rolling window function only supports "
"mean and sum when custom window_type is supplied")
return element.clone(rolled.reset_index())
def _process(self, element, key=None):
return element.map(self._process_layer, Element)
class resample(Operation):
"""
Resamples a timeseries of dates with a frequency and function.
"""
closed = param.ObjectSelector(default=None, objects=['left', 'right'],
doc="Which side of bin interval is closed")
function = param.Callable(default=np.mean, doc="""
Function for computing new values out of existing ones.""")
label = param.ObjectSelector(default='right', doc="""
The bin edge to label the bin with.""")
rule = param.String(default='D', doc="""
A string representing the time interval over which to apply the resampling""")
def _process_layer(self, element, key=None):
df = PandasInterface.as_dframe(element)
xdim = element.kdims[0].name
resample_kwargs = {'rule': self.p.rule, 'label': self.p.label,
'closed': self.p.closed}
df = df.set_index(xdim).resample(**resample_kwargs)
return element.clone(df.apply(self.p.function).reset_index())
def _process(self, element, key=None):
return element.map(self._process_layer, Element)
class rolling_outlier_std(Operation, RollingBase):
"""
Detect outliers using the standard deviation within a rolling window.
Outliers are the array elements outside `sigma` standard deviations from
the smoothed trend line, as calculated from the trend line residuals.
The rolling window is controlled by parameters shared with the
`rolling` operation via the base class RollingBase, to make it
simpler to use the same settings for both.
"""
sigma = param.Number(default=2.0, doc="""
Minimum sigma before a value is considered an outlier.""")
def _process_layer(self, element, key=None):
ys = element.dimension_values(1)
# Calculate the variation in the distribution of the residual
avg = pd.Series(ys).rolling(**self._roll_kwargs()).mean()
residual = ys - avg
std = pd.Series(residual).rolling(**self._roll_kwargs()).std()
# Get indices of outliers
with np.errstate(invalid='ignore'):
outliers = (np.abs(residual) > std * self.p.sigma).values
return element[outliers].clone(new_type=Scatter)
def _process(self, element, key=None):
return element.map(self._process_layer, Element)
|
basnijholt/holoviews
|
holoviews/operation/timeseries.py
|
Python
|
bsd-3-clause
| 4,715
|
[
"Gaussian"
] |
8f9eb738a600ab4628cf095576b41b3eef396aac05425c1b9fcab5b0c0df855d
|
#!/usr/bin/python
"""
The MIT License (MIT)
Copyright (c) 2011 Poznan Supercomputing and Networking Center (PSNC)
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
Autor: Damian Parniewicz (damian.parniewicz at gmail.com)
"""
import sys, copy, json, traceback, os, copy, pickle
import os.path
from cmd import Cmd
import logging
import socket
import pprint
from functools import wraps
from xmlserializer import xml2obj, obj2xml
logger = logging.getLogger('cmd.default')
def configureLogger(_logger, logFile=None):
_logger.setLevel(logging.DEBUG)
if logFile is not None:
logs = logging.FileHandler(logFile)
logs.setLevel(logging.DEBUG)
logs_formatter = logging.Formatter("%(levelname)s - %(asctime)s - %(name)s - %(message)s")
logs.setFormatter(logs_formatter)
_logger.addHandler(logs)
_logger = logging.getLogger('cmd')
console = logging.StreamHandler(sys.stdout)
console.setLevel(logging.INFO)
console_formatter = logging.Formatter('%(message)s')
console.setFormatter(console_formatter)
_logger.addHandler(console)
def unicodeConverter(obj):
" Convert unicode string to standart Python string"
def parseValue(value):
if isinstance(value, dict):
return unicodeConverter(value)
elif isinstance(value, list):
return [unicodeConverter(i) for i in value]
elif isinstance(value, unicode):
return str(value)
elif value is None:
return value
if type(obj) is dict:
newobj = {}
for key, value in obj.iteritems():
newobj[str(key)] = parseValue(value)
elif type(obj) is list:
newobj = [parseValue(value) for value in obj]
elif isinstance(obj, unicode):
return str(obj)
elif obj is None:
return obj
else:
logger.debug(" ERROR: Type %s has no implemented unicode converter")
return newobj
def objectStdout(obj, indent=0):
prefix = ' '*indent
if isinstance(obj, dict):
for item in obj.items():
sys.stdout.write(prefix + " %s : %s\n" % item)
elif isinstance(obj, list):
text = ' '.join(obj)
sys.stdout.write(prefix + " %s\n" % text)
else:
sys.stdout.write(prefix + " %s\n" % str(obj))
def compareDict(dict1, dict2):
" Compare two dictionaries"
if len(dict1) != len(dict2):
return False
for v1, k1 in dict1.items():
if dict2.get(v1) != k1:
return False
return True
def clearedDictValues(dictionary):
d = {}
for key, value in dictionary.items():
if type(value) is dict:
#d[key] = clearedDictValues(value)
d[key] = {}
elif type(value) is list:
d[key] = []
else:
d[key] = None
return d
def exception_handler(f):
'intercepting all calls and checking for exceptions'
wraps(f)
def wrapper(*args, **kwargs):
logger.debug("Calling %s with arguments: %s" % (f.__name__, str(args)))
try:
return f(*args, **kwargs)
except:
logger.debug("Exception" + traceback.format_exc())
return wrapper
USING_READLINE = True
try:
# For platforms without readline support go visit ...
# http://pypi.python.org/pypi/readline/
import readline
delimiters = readline.get_completer_delims()
delimiters.replace('/', '').replace(':', '')
readline.set_completer_delims(delimiters)
except:
try:
# For Windows readline support go visit ...
# https://launchpad.net/pyreadline
import pyreadline
except:
USING_READLINE = False
class DefaultCmd(Cmd):
def __init__(self, database=None, dataSchema=None):
Cmd.__init__(self)
if not USING_READLINE:
self.completekey = None
self.prompt = "> "
self.intro = "Default Command-line."
self.dataFile = 'data.json'
self.defaultDatabase = {}
if dataSchema:
self.databaseSchema = dataSchema
else:
self.databaseSchema = {}
if database:
self.database = database
else:
self.database = self.loadData()
@exception_handler
def loadData(self):
"""
Loads data model information to run-time
Creates data model json file if missing
"""
if os.path.isfile(self.dataFile) is False:
os.system('touch %s' % self.dataFile) # creates the file if missing
data = ''
try:
data = file(self.dataFile, 'r').read()
except:
logger.error("Exception" + traceback.format_exc())
if len(data) == 0:
database = self.defaultDatabase
else:
database = json.loads(data)
database = unicodeConverter(database)
return database
@exception_handler
def saveData(self, database):
" Dumping data model to the json file "
file(self.dataFile, 'w').write(json.dumps(database, indent=4))
@exception_handler
def localizeObj(self, args, stopCondition=2):
" Go through data model nodes to a parent of the object refered by args"
args = args.split()
arg = None
_args = []
obj = self.database
schema = self.databaseSchema
while len(args) > stopCondition and type(obj) is dict:
arg = args.pop(0)
_args.append(arg)
if arg in obj:
obj = obj[arg]
if arg not in schema:
paramType = schema.keys()[0]
schema = schema[paramType]
else:
schema = schema[arg]
else:
break
arg = args.pop(0)
_args.append(arg)
logger.debug('arg=%s, args=%s', arg, args)
return arg, args, _args, obj, schema
@exception_handler
def do_show(self, args):
"""
Show object or parameter value
"""
try:
arg, args, _args, obj, schema = self.localizeObj(args)
if arg == 'list':
if type(obj) is dict:
# listing object parameters or indexes
objectStdout(obj.keys())
else:
raise Exception()
elif type(obj[arg]) is dict and len(args) == 0:
logger.debug('obj %s', obj[arg])
# listing object parameters or indexes
objectStdout(obj[arg].keys())
elif type(obj[arg]) is dict and len(args) > 0:
if args[0] == 'list':
# listing object parameters or indexes
objectStdout(obj[arg].keys())
return
obj = obj[arg][args[0]]
logger.debug('obj %s', obj)
if type(obj) is dict:
# listing dict object parameters and values
objectStdout(obj)
elif type(obj) in (list, tuple):
# listing list object values
for index, item in enumerate(obj):
sys.stdout.write(" %s.%s item #%i:\n" % ('.'.join(_args), args[0], index))
objectStdout(item, indent = 2)
else:
# listing simple object within dict
objectStdout(obj)
else:
# listing any other kind of object
objectStdout(obj[arg])
except:
logger.info(" Error: Command parameters not recognized!")
logger.debug(traceback.format_exc())
def complete_show(self, text, line, begidx, endidx):
" Completing show command"
ret = self._completedefault(text, line, begidx, endidx)
line = line.split()
if (len(line) == 2 and len(text) == 0) or (len(line) == 3 and ('list'.startswith(text) and len(text) > 0)):
obj = self.database[line[1]]
if isinstance(obj, dict):
ret.append('list')
return ret
@exception_handler
def do_set(self, args):
"""
Create object or set parameter value
"""
try:
arg, args, _args, obj, schema = self.localizeObj(args)
if type(obj) is dict:
# setting/adding value to dict
if arg not in schema:
logger.info(" Error: Parameter %s not recognized", '.'.join(_args))
return
logger.debug('obj keys %s', obj.keys())
logger.debug('schema keys %s', schema.keys())
if type(obj[arg]) in (str, type(None)):
# setting simple parameter value within dict
obj[arg] = args[0]
logger.info(" OK: Setting parameter %s to %s", '.'.join(_args), args[0])
elif type(obj[arg]) is dict:
# creating a new dict object within dict
obj = obj[arg]
schema = schema[arg]
arg = args.pop(0)
_args.append(arg)
logger.debug('arg %s %s', arg, args)
logger.debug('obj keys %s', obj.keys())
logger.debug('schema keys %s', schema.keys())
paramType = schema.keys()[0]
if paramType not in self.knownTypes():
raise Exception()
if self.validateValue(arg, paramType) is False:
return
if len(args) == 0 and (arg not in obj or len(obj[arg]) == 0):
# creating a new object (a dict)
obj[arg] = clearedDictValues(schema[paramType])
logger.info(" OK: Setting default value of %s", '.'.join(_args))
else:
logger.info(" Error: Object %s already exist", '.'.join(_args))
elif type(obj[arg]) is list:
# adding simple value to the list within dict
obj = obj[arg]
schema = schema[arg]
arg = args.pop(0)
_args.append(arg)
logger.debug('arg %s %s', arg, args)
logger.debug('obj %s', obj)
logger.debug('schema %s', schema)
if self.validateValue(arg, schema[0]) is False:
return
obj.append(arg)
logger.info(' OK: Adding %s to %s', arg, '.'.join(_args))
elif type(obj) is list:
# adding a dict value within list
logger.debug('obj list %s', obj)
logger.debug('schema list %s', schema)
if arg in schema[0]:
item = clearedDictValues(schema[0])
args.insert(0, arg)
_args.pop()
# create dict object to be inserted in list
while len(args) > 0:
paramName, paramValue = args[:2]
args = args[2:]
if paramName not in schema[0]:
logger.info(" Error: Unknown parameter %s.%s", '.'.join(_args), paramName)
return
if self.validateValue(paramValue, schema[0][paramName]) is False:
return
item[paramName] = paramValue
obj.append(item)
#new
swhere = '.'.join(_args)
if swhere.count('Policed') > 0:
#do it only for flows
f1 = open('/tmp/flow_connection', 'w')
pickle.dump("policedFlow", f1)
pickle.dump(_args[1], f1)
pickle.dump(item, f1)
f1.close()
elif swhere.count('Shaped') > 0 :
#do it only for flows
f1 = open('/tmp/flow_connection', 'w')
pickle.dump("shapedFlow", f1)
pickle.dump(_args[1], f1)
pickle.dump(item, f1)
f1.close()
else:
# check if item already on list
found = False
for i in obj:
if compareDict(i, item):
found = True
if found is False:
logger.info(" OK: Adding %s to %s", item, '.'.join(_args))
else:
logger.info(" Error: %s is already in %s", item, '.'.join(_args))
else:
logger.info(" Error: Other type of object %s %s", type(obj), obj)
except:
logger.info(" Error: Command parameters not recognized!")
logger.debug(traceback.format_exc())
@exception_handler
def do_delete(self, args):
"""
Delete object
"""
try:
arg, args, _args, obj, schema = self.localizeObj(args)
if type(obj) is str:
logger.debug('obj %s', obj)
logger.info(" Error: %s deletion not is allowed", '.'.join(_args))
return
elif type(obj) is dict:
logger.debug('obj keys %s', obj.keys())
logger.debug('schema keys %s', schema.keys())
if arg not in obj:
logger.info(" Error: Object %s is not present", '.'.join(_args))
elif arg in schema and len(args) == 0 and type(obj[arg]) is not list:
logger.info(" Error: %s deletion not is allowed", '.'.join(_args))
elif type(obj[arg]) is dict:
# removing an object
if len(args) == 1:
obj = obj[arg]
arg = args.pop()
_args.append(arg)
del obj[arg]
logger.info(" OK: %s was deleted", '.'.join(_args))
elif type(obj[arg]) is list:
# removing simple value from the list
if args[0].isdigit() and obj.count(args[0]) == 0: # deletion using position in list diseabled when an integer value in list
# removing by index
del obj[int(args[0])]
else:
# removing by value
obj[arg].remove(args[0])
logger.info(" OK: %s was deleted from %s", args[0], '.'.join(_args))
else:
logger.info(" Error: Missing deletion handling for %s", '.'.join(_args))
elif type(obj) is list:
logger.debug('obj list %s', obj)
logger.debug('schema list %s', schema)
if arg.isdigit():
# removing by index
del obj[int(arg)]
logger.info(" OK: %s was deleted", '.'.join(_args))
elif arg in schema[0]:
# removing by value (a dict)
item = {}
args.insert(0, arg)
_args.pop()
# create dict object for search
while len(args) > 0:
paramName, paramValue = args[:2]
if paramName not in schema[0]:
logger.info(" Error: Parameter %s not recognized", paramName)
return
args = args[2:]
item[paramName] = paramValue
# search value on list
removed = False
for i in obj:
if compareDict(i, item):
obj.remove(i)
removed = True
break
if removed:
logger.info(" OK: %s was removed from %s", item, '.'.join(_args))
else:
logger.info(" Error: %s was not found in %s", item, '.'.join(_args))
#new
swhere = '.'.join(_args)
if swhere.count('Policed') > 0:
#do it only for flows
f1 = open('/tmp/flow_connection', 'w')
pickle.dump("policedFlow", f1)
pickle.dump(_args[1], f1)
pickle.dump(item, f1)
f1.close()
elif swhere.count('Shaped') > 0 :
#do it only for flows
f1 = open('/tmp/flow_connection', 'w')
pickle.dump("shapedFlow", f1)
pickle.dump(_args[1], f1)
pickle.dump(item, f1)
f1.close()
else:
logger.info(" Error: Parameter %s not recognized", arg)
else:
logger.info(" Error: Other type of object %s %s", type(obj), obj)
except:
logger.info(" Error: Command parameters not recognized!")
logger.debug(traceback.format_exc())
def completenames(self, text, *ignored):
" Small modification to base method in order to add space after method token completition"
dotext = 'do_'+text
return [a[3:]+' ' for a in self.get_names() if a.startswith(dotext)]
def completedefault(self, text, line, begidx, endidx):
" Completing any command with non-already defined completion"
return self._completedefault(text, line, begidx, endidx)
@exception_handler
def _completedefault(self, text, line, begidx, endidx):
" Default completing command"
line_orginal = copy.copy(line)
def getSubItem(obj):
if type(obj) is dict:
return obj.keys()
else:
return obj[0]
def completeAttributes(schema, arg, line):
'''complete attributes of object, defined by schema, stored in list'''
if line_orginal.startswith("show"):
return []
schema = getSubItem(schema)
logger.debug("Schema for attributes is %s", schema)
attributes = []
#if len(arg) > 0:
# line.insert(0, arg)
while len(line) > 0:
logger.debug("Line is %s", line)
arg = line.pop(0)
logger.debug('Arg is %s', arg)
if arg in schema:
attributes.append(arg)
if len(line) == 0:
break
line.pop(0) # skip value of attribute
else:
break
logger.debug("Completed attributes are %s", attributes)
ret = [attribute for attribute in schema if attribute.startswith(text) and attribute not in attributes]
logger.debug(" Ret is %s", ret)
if len([attr for attr in schema if attr not in attributes]) == 0:
return 'Finalized'
if len(ret) == 1:
ret = [ret[0] + ' '] # adding space after a single parameter to help typing a value
return ret
ret = []
line = line.split()
line.pop(0)
obj = self.database
schema = self.databaseSchema
try:
while len(line) > 1:
arg = line[0]
if arg in obj:
arg = line[0]
line.pop(0)
obj = obj[arg]
if arg not in schema:
paramType = schema.keys()[0]
schema = schema[paramType]
else:
schema = schema[arg]
else:
schema = getSubItem(schema)
ret = completeAttributes(schema, "", line)
if ret == 'Finalized':
return []
if len(ret) > 0:
return ret
logger.debug("Unknown %s", line)
break
logger.debug("Line is %s", ' '.join(line))
logger.debug("Schema is %s", schema)
if (len(line) == 0 and len(text) == 0) or (len(line) == 1 and len(text) > 0):
try:
logger.debug('line=0, obj %s', obj)
obj = getSubItem(obj)
if type(obj) is dict:
obj = getSubItem(obj)
except IndexError:
schema = getSubItem(schema)
ret = completeAttributes(schema, "", line)
if ret == 'Finalized':
return []
if len(ret) > 0:
return ret
elif (len(line) == 1 and len(text) == 0) or (len(line) == 2 and len(text) > 0):
try:
logger.debug('line=1, obj %s', obj)
obj = getSubItem(obj[line[0]])
if type(obj) is dict:
obj = getSubItem(obj)
except IndexError:
schema = getSubItem(schema[line[0]])
line.pop(0)
ret = completeAttributes(schema, "", line)
if ret == 'Finalized':
return []
if len(ret) > 0:
return ret
except:
logger.debug(traceback.format_exc())
logger.debug("Obj %s", obj)
if type(obj) is not list or type(obj) is str:
return []
else:
ret = [param for param in obj if param.startswith(text)]
if len(ret) == 1:
ret = [ret[0] + ' '] # adding space after a single parameter to help typing a value
return ret
@exception_handler
def do_data(self, args):
"""
Show or overwrite loaded database in declared formats:
data format - showing database in format
data format text - overwriting database with database expressed as formated text
Example:
data python-types {'param1':'p1', param2:['value1', 'value2']}
data xml <section><param1>p1</param1><param2>value1<param2><param2>value2</param2></section>
"""
args = args.split()
if len(args) == 1:
if args[0] == 'python-types':
text = pprint.pformat(self.database, indent=4)
elif args[0] == 'json':
text = json.dumps(self.database, indent=4)
elif args[0] == 'xml':
text = obj2xml(self.database, indent=None)
else:
logger.info(" Error: Command parameters %s not recognized!", args)
sys.stdout.write(text+'\n')
elif len(args) > 1:
data = ' '.join(args[1:])
if args[0] == 'python-types':
data = eval(data)
elif args[0] == 'json':
data = json.loads(data)
elif args[0] == 'xml':
data = xml2obj(data)
else:
logger.info(" Error: Command parameters not recognized!")
return
if self.validateData(data, self.databaseSchema):
self.database = data
else:
sys.stdout.write(pprint.pformat(self.database, indent=4)+'\n')
def complete_data(self, text, line, begidx, endidx):
return [param for param in ['json', 'xml', 'python-types'] if param.startswith(text)]
@exception_handler
def do_open(self, args):
" Open subcommand for a database node specified by arguments"
arg, args, _args, obj, schema = self.localizeObj(args, stopCondition=1)
if arg not in obj:
logger.info(" Error: Command parameters not recognized!")
return
paramType = schema.keys()[0]
if paramType in self.knownTypes():
schema = schema[paramType]
else:
schema = schema[arg]
subCmd = DefaultCmd(database = obj[arg],
dataSchema = schema)
subCmd.prompt = '%s-%s> ' % (self.prompt[:-2], '.'.join(_args))
subCmd.cmdloop()
def do_schema(self, args):
" Show loaded data schema"
sys.stdout.write(pprint.pformat(self.databaseSchema, indent=4)+'\n')
def complete_schema(self, text, line, begidx, endidx):
pass # No data completition for 'data' command
def do_exit(self, args):
" Terminates the command-line"
return True
def complete_exit(self, text, line, begidx, endidx):
pass # No data completition for 'exit' command
def emptyline(self):
pass
def knownTypes(self):
return ['IPv6', 'uint', 'ushort', 'uchar', 'read-only', 'text']
@exception_handler
def validateValue(self, value, schema, checkReadOnly=True):
if schema is None:
logger.info(' Unknown parameter %s', value)
return False
try:
if schema == 'IPv6':
addr = value.split('/')
if len(addr) == 2:
prefix = addr[1]
else:
prefix = '128'
addr = addr[0]
if socket.inet_pton(socket.AF_INET6, addr) and 4 <= int(prefix) <= 128:
return True
if schema == 'IPv4':
if socket.inet_pton(socket.AF_INET, value):
return True
elif schema == 'uint':
if 0 <= int(value):
return True
elif schema == 'ushort':
if 0 <= int(value) <= 65535:
return True
elif schema == 'uchar':
if 0 <= int(value) <= 255:
return True
elif '|' in schema:
for desc in schema.split('|'):
if desc == value:
return True
elif schema == 'read-only':
if checkReadOnly:
logger.info(" Error: Cannot set parameter - it is read-only!")
return False
return True
elif schema == 'text':
_value = copy.copy(value)
_value = _value.replace('-', '').replace('_', '').replace('.', '')
if _value.isalnum():
return True
else:
logger.info(' Error: Unknown type %s', schema)
return False
except:
logger.debug(traceback.format_exc())
logger.info(' Error: Validation failed - parameter %s is not type of %s', value, schema)
return False
@exception_handler
def validateData(self, database, dataschema):
" Validates data agains data schema"
validated = True
if type(dataschema) is dict:
for name, schema in dataschema.items():
obj = database.get(name)
if obj is None:
logger.info(" Error: Lack of %s object/parameter in object %s", name, database)
validated = False
continue
if type(obj) != type(schema):
logger.info(" Error: Unproper %s parameter value type %s", name, obj)
validated = False
continue
if type(schema) is str:
if self.validateValue(obj, schema, checkReadOnly=False) is False:
validated = False
continue
elif type(schema) is dict:
indexType, valueSchema = schema.items()[0]
for index, value in obj.items():
if indexType in self.knownTypes():
if self.validateValue(index, indexType) is False:
logger.info(" Error: Unproper index %s of %s", index, name)
validated = False
continue
if self.validateData(value, valueSchema) is False:
validated = False
continue
else:
if self.validateData(value, schema[index]) is False:
validated = False
continue
elif type(schema) in (list, tuple):
valueSchema = schema[0]
for value in obj:
if self.validateData(value, valueSchema) is False:
validated = False
continue
else:
logger.info(' Error: Validation is not implemented for %s', type(schema))
elif type(dataschema) is list:
for value in database:
if self.validateData(value, dataschema[0]) is False:
validated = False
continue
return validated
|
damomeen/cli-from-datamodel
|
defaultCmd.py
|
Python
|
mit
| 31,233
|
[
"VisIt"
] |
547b3dc279e2daf6a6fcb08b84da9c163f756d5be95321517dcf2f1d05d218ad
|
# Copyright (c) 2019, NVIDIA CORPORATION. All rights reserved.
#
# This work is licensed under the Creative Commons Attribution-NonCommercial
# 4.0 International License. To view a copy of this license, visit
# http://creativecommons.org/licenses/by-nc/4.0/ or send a letter to
# Creative Commons, PO Box 1866, Mountain View, CA 94042, USA.
from . import run_context
from . import submit
|
microsoft/DiscoFaceGAN
|
dnnlib/submission/__init__.py
|
Python
|
mit
| 392
|
[
"VisIt"
] |
110815c02054f96c6e55ac84f12ca62088fdff60610a52100ec43997d9b482fe
|
# coding: utf-8
# Copyright (c) Pymatgen Development Team.
# Distributed under the terms of the MIT License.
from __future__ import division, unicode_literals
"""
This module implements a EnergyModel abstract class and some basic
implementations. Basically, an EnergyModel is any model that returns an
"energy" for any given structure.
"""
__author__ = "Shyue Ping Ong"
__copyright__ = "Copyright 2012, The Materials Project"
__version__ = "0.1"
__maintainer__ = "Shyue Ping Ong"
__email__ = "shyuep@gmail.com"
__date__ = "11/19/13"
import abc
import six
from monty.json import MSONable
from pymatgen.analysis.ewald import EwaldSummation
from pymatgen.symmetry.analyzer import SpacegroupAnalyzer
class EnergyModel(six.with_metaclass(abc.ABCMeta, MSONable)):
"""
Abstract structure filter class.
"""
@abc.abstractmethod
def get_energy(self, structure):
"""
Returns a boolean for any structure. Structures that return true are
kept in the Transmuter object during filtering.
"""
return
@classmethod
def from_dict(cls, d):
return cls(**d['init_args'])
class EwaldElectrostaticModel(EnergyModel):
"""
Wrapper around EwaldSum to calculate the electrostatic energy.
"""
def __init__(self, real_space_cut=None, recip_space_cut=None,
eta=None, acc_factor=8.0):
"""
Initializes the model. Args have the same definitions as in
:class:`pymatgen.analysis.ewald.EwaldSummation`.
Args:
real_space_cut (float): Real space cutoff radius dictating how
many terms are used in the real space sum. Defaults to None,
which means determine automagically using the formula given
in gulp 3.1 documentation.
recip_space_cut (float): Reciprocal space cutoff radius.
Defaults to None, which means determine automagically using
the formula given in gulp 3.1 documentation.
eta (float): Screening parameter. Defaults to None, which means
determine automatically.
acc_factor (float): No. of significant figures each sum is
converged to.
"""
self.real_space_cut = real_space_cut
self.recip_space_cut = recip_space_cut
self.eta = eta
self.acc_factor = acc_factor
def get_energy(self, structure):
e = EwaldSummation(structure, real_space_cut=self.real_space_cut,
recip_space_cut=self.recip_space_cut,
eta=self.eta,
acc_factor=self.acc_factor)
return e.total_energy
def as_dict(self):
return {"version": __version__,
"@module": self.__class__.__module__,
"@class": self.__class__.__name__,
"init_args": {"real_space_cut": self.real_space_cut,
"recip_space_cut": self.recip_space_cut,
"eta": self.eta,
"acc_factor": self.acc_factor}}
class SymmetryModel(EnergyModel):
"""
Sets the energy to the -ve of the spacegroup number. Higher symmetry =>
lower "energy".
Args have same meaning as in
:class:`pymatgen.symmetry.finder.SpacegroupAnalyzer`.
Args:
symprec (float): Symmetry tolerance. Defaults to 0.1.
angle_tolerance (float): Tolerance for angles. Defaults to 5 degrees.
"""
def __init__(self, symprec=0.1, angle_tolerance=5):
self.symprec = symprec
self.angle_tolerance = angle_tolerance
def get_energy(self, structure):
f = SpacegroupAnalyzer(structure, symprec=self.symprec,
angle_tolerance=self.angle_tolerance)
return -f.get_spacegroup_number()
def as_dict(self):
return {"version": __version__,
"@module": self.__class__.__module__,
"@class": self.__class__.__name__,
"init_args": {"symprec": self.symprec,
"angle_tolerance": self.angle_tolerance}}
class IsingModel(EnergyModel):
"""
A very simple Ising model, with r^2 decay.
Args:
j (float): The interaction parameter. E = J * spin1 * spin2.
radius (float): max_radius for the interaction.
"""
def __init__(self, j, max_radius):
self.j = j
self.max_radius = max_radius
def get_energy(self, structure):
all_nn = structure.get_all_neighbors(r=self.max_radius)
energy = 0
for i, nn in enumerate(all_nn):
s1 = getattr(structure[i].specie, "spin", 0)
for site, dist in nn:
energy += self.j * s1 * getattr(site.specie, "spin",
0) / (dist ** 2)
return energy
def as_dict(self):
return {"version": __version__,
"@module": self.__class__.__module__,
"@class": self.__class__.__name__,
"init_args": {"j": self.j, "max_radius": self.max_radius}}
class NsitesModel(EnergyModel):
"""
Sets the energy to the number of sites. More sites => higher "energy".
Used to rank structures from smallest number of sites to largest number
of sites after enumeration.
"""
def get_energy(self, structure):
return len(structure)
def as_dict(self):
return {"version": __version__,
"@module": self.__class__.__module__,
"@class": self.__class__.__name__,
"init_args": {}}
|
migueldiascosta/pymatgen
|
pymatgen/analysis/energy_models.py
|
Python
|
mit
| 5,623
|
[
"GULP",
"pymatgen"
] |
9161883fd69a403853fb77d90c202ace4d68d17980a81b92be59ca4add134f43
|
import vtk
###############################################################################
# read obj file
#
obj_filename = '/mnt/data1/StandardBrain/SB/SB256.obj'
object = vtk.vtkOBJReader()
object.SetFileName(obj_filename)
objectSmoother = vtk.vtkSmoothPolyDataFilter()
objectSmoother.SetInputConnection(object.GetOutputPort())
objectSmoother.SetNumberOfIterations(100)
objectMapper = vtk.vtkPolyDataMapper()
#objectMapper.SetInputConnection(object.GetOutputPort())
objectMapper.SetInputConnection(objectSmoother.GetOutputPort())
objectActor = vtk.vtkActor()
objectActor.SetMapper(objectMapper)
#objectActor.GetProperty().SetRepresentationToWireframe();
objectActor.GetProperty().SetColor(0.5, 0.5, 0.5)
objectActor.GetProperty().SetOpacity(0.5)
outline = vtk.vtkOutlineFilter()
outline.SetInputConnection(object.GetOutputPort())
outlineMapper = vtk.vtkPolyDataMapper()
outlineMapper.SetInputConnection(outline.GetOutputPort())
outlineActor = vtk.vtkActor()
outlineActor.SetMapper(outlineMapper)
outlineActor.GetProperty().SetColor(1.0, 0.0, 0.0)
outlineActor.GetProperty().SetOpacity(0.2)
###############################################################################
# read second obj file
#
filepos = '/mnt/data1/StandardBrain/SB/LALobj/'
obj_list = ['LAL1.obj','LAL2.obj','LAL3.obj','LAL4.obj','LAL5.obj', 'LAL1_flip.obj', 'LAL2_flip.obj', 'LAL3_flip.obj', 'LAL4_flip.obj', 'LAL5_flip.obj']
lut = vtk.vtkLookupTable()
lut.Build()
scalar_bar = vtk.vtkScalarBarActor()
scalar_bar.SetLookupTable(lut)
objs = []
objs_mapper = []
objs_actor = []
objs_smoother = []
for i, obj_name in enumerate(obj_list):
objs.append(vtk.vtkOBJReader())
objs[-1].SetFileName(filepos+obj_name)
objs_smoother.append(vtk.vtkSmoothPolyDataFilter())
objs_smoother[-1].SetInputConnection(objs[-1].GetOutputPort())
objs_smoother[-1].SetNumberOfIterations(50)
objs_mapper.append(vtk.vtkPolyDataMapper())
objs_mapper[-1].SetInputConnection(objs_smoother[-1].GetOutputPort())
objs_mapper[-1].SetLookupTable(lut)
objs_actor.append(vtk.vtkActor())
objs_actor[-1].SetMapper(objs_mapper[-1])
rgb = [0.0, 0.0, 0.0]
lut.GetColor((i / float(len(obj_list))), rgb)
objs_actor[-1].GetProperty().SetColor(rgb)
objs_actor[-1].GetProperty().SetOpacity(0.4)
neuronpos = '/mnt/data1/StandardBrain/highres/'
neuron_list = ['0004.obj', '0004flip.obj', '0005.obj', '0005flip.obj', '0008.obj', '0008flip.obj', '0009.obj', '0009flip.obj', '0012.obj', '0012flip.obj', '0017.obj', '0017flip.obj', '0019.obj', '0019flip.obj', '0021.obj', '0021flip.obj', '0655.obj', '0655flip.obj', '0661.obj', '0661flip.obj']
neurons = []
neurons_mapper = []
neurons_actor = []
neurons_smoother = []
for i, neuron_name in enumerate(neuron_list):
neurons.append(vtk.vtkOBJReader())
neurons[-1].SetFileName(neuronpos+neuron_name)
neurons_smoother.append(vtk.vtkSmoothPolyDataFilter())
neurons_smoother[-1].SetInputConnection(neurons[-1].GetOutputPort())
neurons_smoother[-1].SetNumberOfIterations(50)
neurons_mapper.append(vtk.vtkPolyDataMapper())
neurons_mapper[-1].SetInputConnection(neurons_smoother[-1].GetOutputPort())
neurons_mapper[-1].SetLookupTable(lut)
neurons_actor.append(vtk.vtkActor())
neurons_actor[-1].SetMapper(neurons_mapper[-1])
rgb = [0.0, 0.0, 0.0]
lut.GetColor((i / float(len(neuron_list))), rgb)
#neurons_actor[-1].GetProperty().SetColor(1.0, 1.0, 0.5)
neurons_actor[-1].GetProperty().SetColor(rgb)
neurons_actor[-1].GetProperty().SetOpacity(0.9)
###############################################################################
# draw axis
#
axesActor = vtk.vtkAxesActor()
###############################################################################
# prepare rendering
#
ren = vtk.vtkRenderer()
ren.AddActor(objectActor)
#ren.AddActor(object2Actor)
ren.AddActor(outlineActor)
ren.AddActor(scalar_bar)
#for actor in objs_actor:
# ren.AddActor(actor)
for actor in neurons_actor:
ren.AddActor(actor)
ren.AddActor(axesActor)
ren.SetBackground(.0, .0, .1)
renWin = vtk.vtkRenderWindow()
renWin.AddRenderer(ren)
renWin.SetWindowName('Silkmoth Brain Viewer')
renWin.SetSize(1400, 1200)
iren = vtk.vtkRenderWindowInteractor()
iren.SetRenderWindow(renWin)
iren.Initialize()
iren.Start()
|
neuroinformatics/bah2015_registration
|
vtk_test/draw_mothbrain.py
|
Python
|
mit
| 4,285
|
[
"VTK"
] |
08e00dc5e8d88f85cc2327b07cd5d16a96cc734b95db3bf1d049d95f43aa1b38
|
#
# Author: Adam Pridgen <adam@praetoriangrp.com>
# (C) 2010 praetorian group
# droid_gps.py - gps bridge for the android phone and GPSd or Kismet
from optparse import OptionParser
from socket import *
import android, sys, threading, traceback, time
from subprocess import *
from time import sleep
from math import *
from datetime import date,timedelta,datetime
from threading import Timer
EARTH_R = 10^6 # really does not matter since the factor is multiplied before its used
POLL_THREAD = None
def set_parse_options():
parser = OptionParser()
parser.add_option("-l", "--adb_lport", dest="adb_lport", type="int",
help="local port that adb will forward too")
parser.add_option("-r", "--adb_rport", dest="adb_rport", type="int",
help="remote port that adb will forward too")
parser.add_option("-t", "--timing", dest="timing", type="int",
help="how many seconds between polling the phones gps")
parser.add_option("-p", "--socat_port", dest="stcp_port", type="int",
help="port socat will recieve and forward the data to the serial port")
parser.add_option("-s", "--serial_name", dest="serialp_name", type="string",
help="port socat will recieve and forward the data to the serial port")
parser.set_defaults(adb_lport = None,
adb_rport = None,
stcp_port = None,
serialp_name = None,
timing = 3)
return parser
def get_checksum(sentence):
Checksum = 0
for char in sentence:
if char == '$': continue
elif char == '*': break
else:
if Checksum == 0:
Checksum = ord(char)
else:
Checksum = Checksum ^ ord(char)
return "%x"%Checksum
def convert_DMlongitude_to_NMEA(longitude):
hemi = "E"
if longitude < 0:
hemi = "W"
return "%.4f"%(convert_value(abs(longitude)))+","+hemi
def convert_value(DMS):
D = int(DMS)
M = (DMS - D) * 60
#S = ((DMS - D )*3600 - M * 60) * 3600
val = float(D * 100) + M
return val
def convert_DMlatitude_to_NMEA(latitude):
hemi = "N"
if latitude < 0:
hemi = "S"
return "%.4f"%(convert_value(abs(latitude)))+","+hemi
def create_gpgll_sentence(lat, long, time_):
gll = "$GPGLL,"
gll+= convert_DMlatitude_to_NMEA(lat)
gll+= convert_DMlongitude_to_NMEA(long)
d = datetime.fromtimestamp(time_/1000)
gll+= ","+d.strftime('%H%M%S')
gll+= ",A,*"
gll+= get_checksum(gll)
return gll+"\r\n"
def create_gprmc_sentence(lat, lon, time_,speed_=0.0,course_=0.00):
rmc = "$GPRMC"
d = datetime.fromtimestamp(time_/1000)
rmc+= ","+d.strftime('%H%M%S')+".999"
rmc+= ","+"A"
rmc+= ","+convert_DMlatitude_to_NMEA(lat)
rmc+= ","+convert_DMlongitude_to_NMEA(lon)
rmc+= ",%.2f"%(speed_*1.943844)
rmc+= ",%.2f"%(course_)
rmc+= ","+d.strftime('%D').replace("/","")
rmc+= ",,*"+get_checksum(rmc)
return rmc+"\r\n"
def init_android_instance(port, minUpdateTimeMs=1,minUpdateDistance=1):
port = int(port)
d = android.Android(("localhost", port))
print ("Android Scripting Environment initialized..time to start locating")
d.startLocating(minUpdateTimeMs,minUpdateDistance)
ev = d.getLastKnownLocation()
while not ev.result:
sleep(4)
print ev.result
return d
def test_gps(d):
ev_p = ev = d.readLocation()
print str(ev_p.result)
while True:
ev = d.readLocation()
if str(ev.result) == str(ev_p.result):
continue
ev_p = ev
print str(ev_p.result)
def same_events(ev, ev_p):
return str(ev.result) == str(ev_p.result)
def deinit_android_instance(d):
d.stopLocating()
return d
def pollForLocationEv(droid):
ev = get_location_values(droid)
#ev = droid.receiveEvent()
#print ev
#while not ev is None or\
# not ev.result is None or\
# not 'name' in ev.result or\
# ev.result['name'] != u"location":
# ev = droid.receiveEvent()
return ev
def run_cmd(cmd_str):
#global PROCESS_STARTED
#PROCESS_STARTED = False
x = Popen(cmd_str.split(), stdout=PIPE)
#print (x.stdout.read())
#PROCESS_STARTED = True
#print "Process started"
return x
KeepRunning = True
POLL_THREAD_LOCK = threading.RLock()
extract_stuff = lambda result:(float(result['latitude']),float(result['longitude']),int(result['time']),float(result['speed']))
def get_location_values(droid):
location = None
location_result = droid.getLastKnownLocation()
#print location
default = (0,0.0,0.0,0)
if location_result is None or\
location_result.result is None:
return default
ida = location_result.id
if "gps" in location_result.result and\
not location_result.result["gps"] is None:
location = location_result.result["gps"]
elif "network" in location_result.result:
location = location_result.result["network"]
if location:
return ida, float(location[u'latitude']),float(location['longitude']),int(location['time'])
return ida,0.0,0.0,0
def read_location_xmit_socat(droid, socat_socket, ev_p):
id,lat_,long_,t_ = get_location_values(droid)
tnow = date.fromtimestamp(time.time())
if (id,lat_,long_,t_) != (0,0.0,0.0,0):
nmea_sentence = ""
ev_p = (id,lat_,long_,t_)
nmea_sentence = create_gprmc_sentence(lat_,long_,t_)
print("Event: %u Posting the following NMEA Sentence: %s"%(id, nmea_sentence))
socat_socket.send(nmea_sentence)
else:
print "Read invalid location information"
schedule_callback(droid, socat_socket, ev_p)
def schedule_callback(droid, socat_socket, ev_p):
global POLL_THREAD_LOCK, POLL_THREAD
POLL_THREAD_LOCK.acquire()
POLL_THREAD = Timer(TIME, read_location_xmit_socat, args=(droid, socat_socket, ev_p))
POLL_THREAD.start()
POLL_THREAD_LOCK.release()
def construct_sent(string):
return string+get_checksum(string)+"\r\n"
def test_gpsd(sock):
s = sock.recv(100000)
print repr(s)
socat_cmd_str = "socat -d TCP4-LISTEN:%u,bind=localhost,reuseaddr pty,link=/dev/%s,raw,echo=0"
if __name__ == "__main__":
parser = set_parse_options()
(options, args) = parser.parse_args()
if options.adb_lport is None or\
options.adb_rport is None or\
options.stcp_port is None or\
options.serialp_name is None:
parser.print_help()
sys.exit(-1)
TIME = options.timing
adb_cmd = "adb forward tcp:%u tcp:%u"%(options.adb_lport, options.adb_rport)
#init adb
print ("Setting up adb for Python and ASE interation: %s"%adb_cmd)
run_cmd(adb_cmd)
# bind our command socket for the socat serial port forwarding
# start socat in a separate thread
socat_cmd = socat_cmd_str%(options.stcp_port,options.serialp_name)
print("Starting socat with the following command: %s"%socat_cmd)
socat_thread = threading.Thread(target=run_cmd, args=(socat_cmd,))
# ugh, always need to remember to start
# the thread!!! 3 hours lost )-:
socat_thread.start()
sleep(2)
# connect to the thread
print ("Connecting to: localhost %u"%options.stcp_port)
socat_socket = socket()
socat_socket.connect(("localhost",options.stcp_port))
pash = "$PASHR,RID*"
pgrm = "$PGRMC,2,0,,,,,,,,5,,,,*"
#socat_sock.send(construct_sent(pash))
# testing out gpsd
#test_gpsd(socat_socket)
f = raw_input("Press Enter After you have started gpsd or kismet")
socat_socket.send(construct_sent(pgrm))
#print repr(socat_socket.recv(8096))
# init the android ASE interface, and
# init location facade manager
droid = init_android_instance(options.adb_lport)
# Now lets rock and roll
long_p = lat_p = 0.0
t_p = 0
last_update = date.fromtimestamp(time.time())
tdelta = timedelta(milliseconds=(1000))
# poll for the first Location event
ev_p = pollForLocationEv(droid)
ev = ev_p
schedule_callback(droid, socat_socket, ev_p)
while 1:
try:
POLL_THREAD_LOCK.acquire()
if not POLL_THREAD.isAlive():
print "Uh-oh polling thread failed )-:"
POLL_THREAD_LOCK.release()
break
POLL_THREAD_LOCK.release()
sleep(3)
except KeyboardInterrupt:
print("Exitting the loop.")
KeepRunning = False
POLL_THREAD_LOCK.acquire()
POLL_THREAD.cancel()
POLL_THREAD_LOCK.release()
POLL_THREAD.join()
break
except:
print ("The following Exception Occurred:")
traceback.print_exc(file=sys.stdout)
sys.exc_clear()
pass
#run_cmd("pkill socat")
# dont bother stopping socat
# when the script dies the thread will terminate
|
deeso/python_scrirpts
|
droid_gps.py
|
Python
|
apache-2.0
| 8,327
|
[
"ASE"
] |
a12e2aad5bb539f2c519fb4106ff14e887a2be9bdff7c1f0bb48bcbbf6d9e389
|
# This code is part of the Biopython distribution and governed by its
# license. Please see the LICENSE file that should have been included
# as part of this package.
#
"""Extract information from alignment objects.
In order to try and avoid huge alignment objects with tons of functions,
functions which return summary type information about alignments should
be put into classes in this module.
"""
from __future__ import print_function
import math
import sys
from Bio import Alphabet
from Bio.Alphabet import IUPAC
from Bio.Seq import Seq
from Bio.SubsMat import FreqTable
__docformat__ = "restructuredtext en"
# Expected random distributions for 20-letter protein, and
# for 4-letter nucleotide alphabets
Protein20Random = 0.05
Nucleotide4Random = 0.25
class SummaryInfo(object):
"""Calculate summary info about the alignment.
This class should be used to caclculate information summarizing the
results of an alignment. This may either be straight consensus info
or more complicated things.
"""
def __init__(self, alignment):
"""Initialize with the alignment to calculate information on.
ic_vector attribute. A dictionary. Keys: column numbers. Values:
"""
self.alignment = alignment
self.ic_vector = {}
def dumb_consensus(self, threshold=.7, ambiguous="X",
consensus_alpha=None, require_multiple=0):
"""Output a fast consensus sequence of the alignment.
This doesn't do anything fancy at all. It will just go through the
sequence residue by residue and count up the number of each type
of residue (ie. A or G or T or C for DNA) in all sequences in the
alignment. If the percentage of the most common residue type is
greater then the passed threshold, then we will add that residue type,
otherwise an ambiguous character will be added.
This could be made a lot fancier (ie. to take a substitution matrix
into account), but it just meant for a quick and dirty consensus.
Arguments:
- threshold - The threshold value that is required to add a particular
atom.
- ambiguous - The ambiguous character to be added when the threshold is
not reached.
- consensus_alpha - The alphabet to return for the consensus sequence.
If this is None, then we will try to guess the alphabet.
- require_multiple - If set as 1, this will require that more than
1 sequence be part of an alignment to put it in the consensus (ie.
not just 1 sequence and gaps).
"""
# Iddo Friedberg, 1-JUL-2004: changed ambiguous default to "X"
consensus = ''
# find the length of the consensus we are creating
con_len = self.alignment.get_alignment_length()
# go through each seq item
for n in range(con_len):
# keep track of the counts of the different atoms we get
atom_dict = {}
num_atoms = 0
for record in self.alignment._records:
# make sure we haven't run past the end of any sequences
# if they are of different lengths
if n < len(record.seq):
if record.seq[n] != '-' and record.seq[n] != '.':
if record.seq[n] not in atom_dict:
atom_dict[record.seq[n]] = 1
else:
atom_dict[record.seq[n]] += 1
num_atoms = num_atoms + 1
max_atoms = []
max_size = 0
for atom in atom_dict:
if atom_dict[atom] > max_size:
max_atoms = [atom]
max_size = atom_dict[atom]
elif atom_dict[atom] == max_size:
max_atoms.append(atom)
if require_multiple and num_atoms == 1:
consensus += ambiguous
elif (len(max_atoms) == 1) and ((float(max_size) / float(num_atoms))
>= threshold):
consensus += max_atoms[0]
else:
consensus += ambiguous
# we need to guess a consensus alphabet if one isn't specified
if consensus_alpha is None:
consensus_alpha = self._guess_consensus_alphabet(ambiguous)
return Seq(consensus, consensus_alpha)
def gap_consensus(self, threshold=.7, ambiguous="X",
consensus_alpha=None, require_multiple=0):
"""Same as dumb_consensus(), but allows gap on the output.
Things to do:
- Let the user define that with only one gap, the result
character in consensus is gap.
- Let the user select gap character, now
it takes the same as input.
"""
# Iddo Friedberg, 1-JUL-2004: changed ambiguous default to "X"
consensus = ''
# find the length of the consensus we are creating
con_len = self.alignment.get_alignment_length()
# go through each seq item
for n in range(con_len):
# keep track of the counts of the different atoms we get
atom_dict = {}
num_atoms = 0
for record in self.alignment._records:
# make sure we haven't run past the end of any sequences
# if they are of different lengths
if n < len(record.seq):
if record.seq[n] not in atom_dict:
atom_dict[record.seq[n]] = 1
else:
atom_dict[record.seq[n]] += 1
num_atoms += 1
max_atoms = []
max_size = 0
for atom in atom_dict:
if atom_dict[atom] > max_size:
max_atoms = [atom]
max_size = atom_dict[atom]
elif atom_dict[atom] == max_size:
max_atoms.append(atom)
if require_multiple and num_atoms == 1:
consensus += ambiguous
elif (len(max_atoms) == 1) and ((float(max_size) / float(num_atoms))
>= threshold):
consensus += max_atoms[0]
else:
consensus += ambiguous
# we need to guess a consensus alphabet if one isn't specified
if consensus_alpha is None:
# TODO - Should we make this into a Gapped alphabet?
consensus_alpha = self._guess_consensus_alphabet(ambiguous)
return Seq(consensus, consensus_alpha)
def _guess_consensus_alphabet(self, ambiguous):
"""Pick an (ungapped) alphabet for an alignment consesus sequence.
This just looks at the sequences we have, checks their type, and
returns as appropriate type which seems to make sense with the
sequences we've got.
"""
# Start with the (un-gapped version of) the alignment alphabet
a = Alphabet._get_base_alphabet(self.alignment._alphabet)
# Now check its compatible with all the rest of the sequences
for record in self.alignment:
# Get the (un-gapped version of) the sequence's alphabet
alt = Alphabet._get_base_alphabet(record.seq.alphabet)
if not isinstance(alt, a.__class__):
raise ValueError("Alignment contains a sequence with \
an incompatible alphabet.")
# Check the ambiguous character we are going to use in the consensus
# is in the alphabet's list of valid letters (if defined).
if hasattr(a, "letters") and a.letters is not None \
and ambiguous not in a.letters:
# We'll need to pick a more generic alphabet...
if isinstance(a, IUPAC.IUPACUnambiguousDNA):
if ambiguous in IUPAC.IUPACUnambiguousDNA().letters:
a = IUPAC.IUPACUnambiguousDNA()
else:
a = Alphabet.generic_dna
elif isinstance(a, IUPAC.IUPACUnambiguousRNA):
if ambiguous in IUPAC.IUPACUnambiguousRNA().letters:
a = IUPAC.IUPACUnambiguousRNA()
else:
a = Alphabet.generic_rna
elif isinstance(a, IUPAC.IUPACProtein):
if ambiguous in IUPAC.ExtendedIUPACProtein().letters:
a = IUPAC.ExtendedIUPACProtein()
else:
a = Alphabet.generic_protein
else:
a = Alphabet.single_letter_alphabet
return a
def replacement_dictionary(self, skip_chars=[]):
"""Generate a replacement dictionary to plug into a substitution matrix
This should look at an alignment, and be able to generate the number
of substitutions of different residues for each other in the
aligned object.
Will then return a dictionary with this information::
{('A', 'C') : 10, ('C', 'A') : 12, ('G', 'C') : 15 ....}
This also treats weighted sequences. The following example shows how
we calculate the replacement dictionary. Given the following
multiple sequence alignment::
GTATC 0.5
AT--C 0.8
CTGTC 1.0
For the first column we have::
('A', 'G') : 0.5 * 0.8 = 0.4
('C', 'G') : 0.5 * 1.0 = 0.5
('A', 'C') : 0.8 * 1.0 = 0.8
We then continue this for all of the columns in the alignment, summing
the information for each substitution in each column, until we end
up with the replacement dictionary.
Arguments:
- skip_chars - A list of characters to skip when creating the dictionary.
For instance, you might have Xs (screened stuff) or Ns, and not want
to include the ambiguity characters in the dictionary.
"""
# get a starting dictionary based on the alphabet of the alignment
rep_dict, skip_items = self._get_base_replacements(skip_chars)
# iterate through each record
for rec_num1 in range(len(self.alignment._records)):
# iterate through each record from one beyond the current record
# to the end of the list of records
for rec_num2 in range(rec_num1 + 1, len(self.alignment._records)):
# for each pair of records, compare the sequences and add
# the pertinent info to the dictionary
rep_dict = self._pair_replacement(
self.alignment._records[rec_num1].seq,
self.alignment._records[rec_num2].seq,
self.alignment._records[rec_num1].annotations.get('weight', 1.0),
self.alignment._records[rec_num2].annotations.get('weight', 1.0),
rep_dict, skip_items)
return rep_dict
def _pair_replacement(self, seq1, seq2, weight1, weight2,
start_dict, ignore_chars):
"""Compare two sequences and generate info on the replacements seen.
Arguments:
- seq1, seq2 - The two sequences to compare.
- weight1, weight2 - The relative weights of seq1 and seq2.
- start_dict - The dictionary containing the starting replacement
info that we will modify.
- ignore_chars - A list of characters to ignore when calculating
replacements (ie. '-').
Returns:
- A replacment dictionary which is modified from initial_dict with
the information from the sequence comparison.
"""
# loop through each residue in the sequences
for residue_num in range(len(seq1)):
residue1 = seq1[residue_num]
try:
residue2 = seq2[residue_num]
# if seq2 is shorter, then we just stop looking at replacements
# and return the information
except IndexError:
return start_dict
# if the two residues are characters we want to count
if (residue1 not in ignore_chars) and (residue2 not in ignore_chars):
try:
# add info about the replacement to the dictionary,
# modified by the sequence weights
start_dict[(residue1, residue2)] += weight1 * weight2
# if we get a key error, then we've got a problem with alphabets
except KeyError:
raise ValueError("Residues %s, %s not found in alphabet %s"
% (residue1, residue2,
self.alignment._alphabet))
return start_dict
def _get_all_letters(self):
"""Returns a string containing the expected letters in the alignment."""
all_letters = self.alignment._alphabet.letters
if all_letters is None \
or (isinstance(self.alignment._alphabet, Alphabet.Gapped)
and all_letters == self.alignment._alphabet.gap_char):
# We are dealing with a generic alphabet class where the
# letters are not defined! We must build a list of the
# letters used...
set_letters = set()
for record in self.alignment:
# Note the built in set does not have a union_update
# which was provided by the sets module's Set
set_letters = set_letters.union(record.seq)
list_letters = sorted(set_letters)
all_letters = "".join(list_letters)
return all_letters
def _get_base_replacements(self, skip_items=[]):
"""Get a zeroed dictionary of all possible letter combinations.
This looks at the type of alphabet and gets the letters for it.
It then creates a dictionary with all possible combinations of these
letters as keys (ie. ('A', 'G')) and sets the values as zero.
Returns:
- The base dictionary created
- A list of alphabet items to skip when filling the dictionary.
(Right now the only thing I can imagine in this list is gap
characters, but maybe X's or something else might be useful later.
This will also include any characters that are specified to be
skipped.)
"""
base_dictionary = {}
all_letters = self._get_all_letters()
# if we have a gapped alphabet we need to find the gap character
# and drop it out
if isinstance(self.alignment._alphabet, Alphabet.Gapped):
skip_items.append(self.alignment._alphabet.gap_char)
all_letters = all_letters.replace(self.alignment._alphabet.gap_char, '')
# now create the dictionary
for first_letter in all_letters:
for second_letter in all_letters:
if first_letter not in skip_items and \
second_letter not in skip_items:
base_dictionary[(first_letter, second_letter)] = 0
return base_dictionary, skip_items
def pos_specific_score_matrix(self, axis_seq=None,
chars_to_ignore=[]):
"""Create a position specific score matrix object for the alignment.
This creates a position specific score matrix (pssm) which is an
alternative method to look at a consensus sequence.
Arguments:
- chars_to_ignore - A listing of all characters not to include in
the pssm. If the alignment alphabet declares a gap character,
then it will be excluded automatically.
- axis_seq - An optional argument specifying the sequence to
put on the axis of the PSSM. This should be a Seq object. If nothing
is specified, the consensus sequence, calculated with default
parameters, will be used.
Returns:
- A PSSM (position specific score matrix) object.
"""
# determine all of the letters we have to deal with
all_letters = self._get_all_letters()
assert all_letters
if not isinstance(chars_to_ignore, list):
raise TypeError("chars_to_ignore should be a list.")
# if we have a gap char, add it to stuff to ignore
if isinstance(self.alignment._alphabet, Alphabet.Gapped):
chars_to_ignore.append(self.alignment._alphabet.gap_char)
for char in chars_to_ignore:
all_letters = all_letters.replace(char, '')
if axis_seq:
left_seq = axis_seq
assert len(axis_seq) == self.alignment.get_alignment_length()
else:
left_seq = self.dumb_consensus()
pssm_info = []
# now start looping through all of the sequences and getting info
for residue_num in range(len(left_seq)):
score_dict = self._get_base_letters(all_letters)
for record in self.alignment._records:
try:
this_residue = record.seq[residue_num]
# if we hit an index error we've run out of sequence and
# should not add new residues
except IndexError:
this_residue = None
if this_residue and this_residue not in chars_to_ignore:
weight = record.annotations.get('weight', 1.0)
try:
score_dict[this_residue] += weight
# if we get a KeyError then we have an alphabet problem
except KeyError:
raise ValueError("Residue %s not found in alphabet %s"
% (this_residue,
self.alignment._alphabet))
pssm_info.append((left_seq[residue_num],
score_dict))
return PSSM(pssm_info)
def _get_base_letters(self, letters):
"""Create a zeroed dictionary with all of the specified letters.
"""
base_info = {}
for letter in letters:
base_info[letter] = 0
return base_info
def information_content(self, start=0,
end=None,
e_freq_table=None, log_base=2,
chars_to_ignore=[]):
"""Calculate the information content for each residue along an alignment.
Arguments:
- start, end - The starting an ending points to calculate the
information content. These points should be relative to the first
sequence in the alignment, starting at zero (ie. even if the 'real'
first position in the seq is 203 in the initial sequence, for
the info content, we need to use zero). This defaults to the entire
length of the first sequence.
- e_freq_table - A FreqTable object specifying the expected frequencies
for each letter in the alphabet we are using (e.g. {'G' : 0.4,
'C' : 0.4, 'T' : 0.1, 'A' : 0.1}). Gap characters should not be
included, since these should not have expected frequencies.
- log_base - The base of the logathrim to use in calculating the
information content. This defaults to 2 so the info is in bits.
- chars_to_ignore - A listing of characterw which should be ignored
in calculating the info content.
Returns:
- A number representing the info content for the specified region.
Please see the Biopython manual for more information on how information
content is calculated.
"""
# if no end was specified, then we default to the end of the sequence
if end is None:
end = len(self.alignment._records[0].seq)
if start < 0 or end > len(self.alignment._records[0].seq):
raise ValueError("Start (%s) and end (%s) are not in the \
range %s to %s"
% (start, end, 0, len(self.alignment._records[0].seq)))
# determine random expected frequencies, if necessary
random_expected = None
if not e_freq_table:
# TODO - What about ambiguous alphabets?
base_alpha = Alphabet._get_base_alphabet(self.alignment._alphabet)
if isinstance(base_alpha, Alphabet.ProteinAlphabet):
random_expected = Protein20Random
elif isinstance(base_alpha, Alphabet.NucleotideAlphabet):
random_expected = Nucleotide4Random
else:
errstr = "Error in alphabet: not Nucleotide or Protein, "
errstr += "supply expected frequencies"
raise ValueError(errstr)
del base_alpha
elif not isinstance(e_freq_table, FreqTable.FreqTable):
raise ValueError("e_freq_table should be a FreqTable object")
# determine all of the letters we have to deal with
all_letters = self._get_all_letters()
for char in chars_to_ignore:
all_letters = all_letters.replace(char, '')
info_content = {}
for residue_num in range(start, end):
freq_dict = self._get_letter_freqs(residue_num,
self.alignment._records,
all_letters, chars_to_ignore)
# print freq_dict,
column_score = self._get_column_info_content(freq_dict,
e_freq_table,
log_base,
random_expected)
info_content[residue_num] = column_score
# sum up the score
total_info = sum(info_content.values())
# fill in the ic_vector member: holds IC for each column
for i in info_content:
self.ic_vector[i] = info_content[i]
return total_info
def _get_letter_freqs(self, residue_num, all_records, letters, to_ignore):
"""Determine the frequency of specific letters in the alignment.
Arguments:
- residue_num - The number of the column we are getting frequencies
from.
- all_records - All of the SeqRecords in the alignment.
- letters - The letters we are interested in getting the frequency
for.
- to_ignore - Letters we are specifically supposed to ignore.
This will calculate the frequencies of each of the specified letters
in the alignment at the given frequency, and return this as a
dictionary where the keys are the letters and the values are the
frequencies.
"""
freq_info = self._get_base_letters(letters)
total_count = 0
# collect the count info into the dictionary for all the records
for record in all_records:
try:
if record.seq[residue_num] not in to_ignore:
weight = record.annotations.get('weight', 1.0)
freq_info[record.seq[residue_num]] += weight
total_count += weight
# getting a key error means we've got a problem with the alphabet
except KeyError:
raise ValueError("Residue %s not found in alphabet %s"
% (record.seq[residue_num],
self.alignment._alphabet))
if total_count == 0:
# This column must be entirely ignored characters
for letter in freq_info:
assert freq_info[letter] == 0
# TODO - Map this to NA or NaN?
else:
# now convert the counts into frequencies
for letter in freq_info:
freq_info[letter] = freq_info[letter] / total_count
return freq_info
def _get_column_info_content(self, obs_freq, e_freq_table, log_base,
random_expected):
"""Calculate the information content for a column.
Arguments:
- obs_freq - The frequencies observed for each letter in the column.
- e_freq_table - An optional argument specifying the expected
frequencies for each letter. This is a SubsMat.FreqTable instance.
- log_base - The base of the logathrim to use in calculating the
info content.
"""
try:
gap_char = self.alignment._alphabet.gap_char
except AttributeError:
# The alphabet doesn't declare a gap - there could be none
# in the sequence... or just a vague alphabet.
gap_char = "-" # Safe?
if e_freq_table:
if not isinstance(e_freq_table, FreqTable.FreqTable):
raise ValueError("e_freq_table should be a FreqTable object")
# check the expected freq information to make sure it is good
for key in obs_freq:
if (key != gap_char and key not in e_freq_table):
raise ValueError("Expected frequency letters %s "
"do not match observed %s"
% (list(e_freq_table),
list(obs_freq) - [gap_char]))
total_info = 0.0
for letter in obs_freq:
inner_log = 0.0
# if we have expected frequencies, modify the log value by them
# gap characters do not have expected frequencies, so they
# should just be the observed frequency.
if letter != gap_char:
if e_freq_table:
inner_log = obs_freq[letter] / e_freq_table[letter]
else:
inner_log = obs_freq[letter] / random_expected
# if the observed frequency is zero, we don't add any info to the
# total information content
if inner_log > 0:
letter_info = (obs_freq[letter] *
math.log(inner_log) / math.log(log_base))
total_info += letter_info
return total_info
def get_column(self, col):
# TODO - Deprecate this and implement slicing?
return self.alignment[:, col]
class PSSM(object):
"""Represent a position specific score matrix.
This class is meant to make it easy to access the info within a PSSM
and also make it easy to print out the information in a nice table.
Let's say you had an alignment like this::
GTATC
AT--C
CTGTC
The position specific score matrix (when printed) looks like::
G A T C
G 1 1 0 1
T 0 0 3 0
A 1 1 0 0
T 0 0 2 0
C 0 0 0 3
You can access a single element of the PSSM using the following::
your_pssm[sequence_number][residue_count_name]
For instance, to get the 'T' residue for the second element in the
above alignment you would need to do:
your_pssm[1]['T']
"""
def __init__(self, pssm):
"""Initialize with pssm data to represent.
The pssm passed should be a list with the following structure:
list[0] - The letter of the residue being represented (for instance,
from the example above, the first few list[0]s would be GTAT...
list[1] - A dictionary with the letter substitutions and counts.
"""
self.pssm = pssm
def __getitem__(self, pos):
return self.pssm[pos][1]
def __str__(self):
out = " "
all_residues = sorted(self.pssm[0][1])
# first print out the top header
for res in all_residues:
out += " %s" % res
out += "\n"
# for each item, write out the substitutions
for item in self.pssm:
out += "%s " % item[0]
for res in all_residues:
out += " %.1f" % item[1][res]
out += "\n"
return out
def get_residue(self, pos):
"""Return the residue letter at the specified position.
"""
return self.pssm[pos][0]
def print_info_content(summary_info, fout=None, rep_record=0):
""" Three column output: position, aa in representative sequence,
ic_vector value"""
fout = fout or sys.stdout
if not summary_info.ic_vector:
summary_info.information_content()
rep_sequence = summary_info.alignment._records[rep_record].seq
for pos in sorted(summary_info.ic_vector):
fout.write("%d %s %.3f\n" % (pos, rep_sequence[pos],
summary_info.ic_vector[pos]))
if __name__ == "__main__":
print("Quick test")
from Bio import AlignIO
from Bio.Align.Generic import Alignment
filename = "../../Tests/GFF/multi.fna"
format = "fasta"
expected = FreqTable.FreqTable({"A": 0.25, "G": 0.25, "T": 0.25, "C": 0.25},
FreqTable.FREQ,
IUPAC.unambiguous_dna)
alignment = AlignIO.read(open(filename), format)
for record in alignment:
print(record.seq)
print("=" * alignment.get_alignment_length())
summary = SummaryInfo(alignment)
consensus = summary.dumb_consensus(ambiguous="N")
print(consensus)
consensus = summary.gap_consensus(ambiguous="N")
print(consensus)
print("")
print(summary.pos_specific_score_matrix(chars_to_ignore=['-'],
axis_seq=consensus))
print("")
# Have a generic alphabet, without a declared gap char, so must tell
# provide the frequencies and chars to ignore explicitly.
print(summary.information_content(e_freq_table=expected,
chars_to_ignore=['-']))
print("")
print("Trying a protein sequence with gaps and stops")
alpha = Alphabet.HasStopCodon(Alphabet.Gapped(Alphabet.generic_protein, "-"), "*")
a = Alignment(alpha)
a.add_sequence("ID001", "MHQAIFIYQIGYP*LKSGYIQSIRSPEYDNW-")
a.add_sequence("ID002", "MH--IFIYQIGYAYLKSGYIQSIRSPEY-NW*")
a.add_sequence("ID003", "MHQAIFIYQIGYPYLKSGYIQSIRSPEYDNW*")
print(a)
print("=" * a.get_alignment_length())
s = SummaryInfo(a)
c = s.dumb_consensus(ambiguous="X")
print(c)
c = s.gap_consensus(ambiguous="X")
print(c)
print("")
print(s.pos_specific_score_matrix(chars_to_ignore=['-', '*'], axis_seq=c))
print(s.information_content(chars_to_ignore=['-', '*']))
print("Done")
|
updownlife/multipleK
|
dependencies/biopython-1.65/build/lib.linux-x86_64-2.7/Bio/Align/AlignInfo.py
|
Python
|
gpl-2.0
| 30,746
|
[
"Biopython"
] |
f7de6a1e64c44fd8d3fdfe10337274dbb3b3e49d2b538425976ed3da154252a2
|
'''
Multi-layer arc-cosine: Vectorized version
Note: The dot product of matrices in the kernel computation will eat up so much RAM
reducing the precision of float data is a nice option. A decomposed version
of the same is coming soon.
Author: Akhil P M
'''
from sklearn import svm, datasets
from sklearn.metrics import roc_curve, auc
import gc
from settings import *
import encoderRGB
def compute_J(N, theta):
if N == 0:
return np.pi - theta
elif N == 1:
return np.sin(theta) + (np.pi - theta) * np.cos(theta)
elif N == 2:
return 3*np.sin(theta)*np.cos(theta) + (np.pi - theta)*(1 + 2*pow(np.cos(theta), 2))
elif N == 3:
return 4*pow(np.sin(theta), 3) + 15*np.sin(theta)*pow(np.cos(theta), 2) + \
(np.pi- theta)*(9*pow(np.sin(theta),2)*np.cos(theta) + 15*pow(np.cos(theta),3))
else:
return np.zeros(theta.shape)
def arc_cosine_vector(X, Y):
"""param = a vector of n(degree) values at each layer """
param = np.array([1,1,1,1,1,1,1])
no_of_layers = len(param)
M = np.dot(X, Y.T)
temp1 = np.diag(np.dot(X, X.T))
temp2 = np.diag(np.dot(Y, Y.T))
for i in xrange(no_of_layers):
norm_matrix = np.outer(temp1,temp2) #the matix of k_xx, and K_yy's
theta = np.arccos( np.maximum( np.minimum(M/np.sqrt(norm_matrix), 1.0), -1.0))
n_l = param[i]
M = np.multiply(np.power(norm_matrix, n_l/2.0), compute_J(n_l, theta)) / np.pi
if i < no_of_layers-1:
zero1 = np.zeros(len(temp1))
zero2 = np.zeros(len(temp2))
temp1 = np.multiply(np.power(temp1, n_l), compute_J(n_l, zero1)) / np.pi
temp2 = np.multiply(np.power(temp2, n_l), compute_J(n_l, zero2)) / np.pi
return M
def arc_cosine(X, Y):
lenX = X.shape[0]
incr = 2000
M = np.zeros((lenX, Y.shape[0]))
for i in range(0,lenX,incr):
M[i:i+incr] = arc_cosine_vector(X[i:i+incr], Y)
return M
def main():
start = time.time()
#'''
W, b = encoderRGB.execute_sparse_autoencoder()
trainX = np.zeros((30000, 3072))
trainY = np.zeros(30000)
testX = np.zeros((10000, 3072))
testY = np.zeros(10000)
fo = open('data_batch_1', 'rb')
dict = cPickle.load(fo)
fo.close()
data = dict['data']
label = dict['labels']
label = np.asarray(label)
trainX[0:10000] = data
trainY[0:10000] = label
fo = open('data_batch_2', 'rb')
dict = cPickle.load(fo)
fo.close()
data = dict['data']
label = dict['labels']
label = np.asarray(label)
trainX[10000:20000] = data
trainY[10000:20000] = label
fo = open('data_batch_3', 'rb')
dict = cPickle.load(fo)
fo.close()
data = dict['data']
label = dict['labels']
label = np.asarray(label)
trainX[20000:] = data
trainY[20000:] = label
fo = open('test_batch', 'rb')
dict = cPickle.load(fo)
fo.close()
data = dict['data']
label = dict['labels']
label = np.asarray(label)
testX[0:] = data
testY[0:] = label
trainX = trainX/255.0
testX = testX/255.0
trainX = np.transpose(trainX)
testX = np.transpose(testX)
trainX = encoderRGB.extract_feature(W,b, trainX)
testX = encoderRGB.extract_feature(W,b, testX)
trainX = np.transpose(trainX)
testX = np.transpose(testX)
trainX = trainX.astype(np.float32)
testX = testX.astype(np.float32)
'''
trainX = np.load('trainX.npy')
testX = np.load('testX.npy')
trainY = np.load('trainY.npy')
testY = np.load('testY.npy')
'''
np.save('trainX', trainX)
np.save('testX', testX)
np.save('trainY', trainY)
np.save('testY', testY)
#'''
#sss = StratifiedShuffleSplit(mnist.target, 1, test_size=0.1, train_size=0.1, random_state=0)
#for train_index, test_index in sss:
# trainX, testX = mnist.data[train_index], mnist.data[test_index]
# trainY, testY = mnist.target[train_index], mnist.target[test_index]
clf = svm.SVC(kernel=arc_cosine, cache_size=4096)
#clf = svm.SVC(kernel = 'poly') #gaussian kernel is used
clf.fit(trainX, trainY)
pred = clf.predict(testX)
print accuracy_score(testY, pred)
print('total : %d, correct : %d, incorrect : %d\n' %(len(pred), np.sum(pred == testY), np.sum(pred != testY)))
print('Test Time : %f Minutes\n' %((time.time()-start)/60))
#pred = clf.predict(trainX)
#print accuracy_score(trainY, pred)
#print('total : %d, correct : %d, incorrect : %d\n' %(len(pred), np.sum(pred == trainY), np.sum(pred != trainY)))
print('Execution Time : %f Minutes\n' %((time.time()-start)/60))
if __name__ == '__main__':
main()
|
akhilpm/Masters-Project
|
autoencoderDLKM/cifar10/arc_cosine.py
|
Python
|
mit
| 4,293
|
[
"Gaussian"
] |
cc128b7a0cd7e22ef8eaf742dea99dcfcab10fbd2b377c78ad78a8fc1962dc56
|
import tensorflow as tf
import matplotlib
import numpy as np
import matplotlib.pyplot as plt
import random
import math
import scipy.stats as stats
np.random.seed(1234)
random.seed(1234)
def init_network(inputs, layers):
network = []
current_in = inputs
for l in layers:
layer = tf.Variable(-0.5 + np.random.rand(l, current_in + 1), dtype='float64')
current_in = l
network.append(layer)
return network
def apply_network(network, inputs):
current_out = inputs
for layer in network:
current_out = tf.concat([tf.expand_dims(np.repeat([1.0], current_out.shape[0]), 1), current_out], axis=1)
current_out = sigmoid(tf.matmul(current_out, tf.transpose(layer)))
return current_out
def sigmoid(tensor):
return 1.0/(1.0 + tf.exp(-tensor))
def split_data(n, K):
partitions = []
idx = list(range(n))
np.random.shuffle(idx)
sub_size = int(len(idx)/K)
for i in range(0, len(idx), sub_size):
Tr = []
Ts = []
for j in range(0, len(idx)):
if j >= i and j < (i+sub_size):
Ts.append(idx[j])
else:
Tr.append(idx[j])
partitions.append((Tr,Ts))
return partitions
def generateChevronData():
xBounds = [-50, 50]
yBounds = [-50, 50]
totalPoints = 100
points = []
targets = []
for i in range(0, totalPoints):
x = random.randint(xBounds[0], xBounds[1])
y = random.randint(yBounds[0], yBounds[1])
if x >= y and x <= -y:
points.append([x/50.0,y/50.0])
targets.append(0.0)
else:
points.append([x/50.0,y/50.0])
targets.append(1.0)
return np.array(points), np.array(targets)
def train_perceptron_network(Tr, Ts, points, targets):
inputs = tf.placeholder('float64', [in_size])
targets = tf.placeholder('float64', [out_size])
in_prime = tf.transpose(tf.expand_dims(inputs, 1))
network = init_network(2, [2,1])
output = apply_network(network, in_prime)
errors = tf.pow(tf.subtract(tf.expand_dims(targets, 1), output), 2.0)
error = tf.reduce_sum(errors)
train_op = tf.train.GradientDescentOptimizer(0.01).minimize(error)
model = tf.global_variables_initializer()
with tf.Session() as session:
session.run(model)
for e in range(6000):
for d in range(len(Tr)):
session.run(train_op, feed_dict={inputs: points[Tr[d]], targets: [out[Tr[d]]]})
train_err = 0
for d in range(len(Tr)):
train_err += session.run(error, feed_dict={inputs: points[Tr[d]], targets: [out[Tr[d]]]})
test_err = 0
for d in range(len(Ts)):
test_err += session.run(error, feed_dict={inputs: points[Ts[d]], targets: [out[Ts[d]]]})
return (train_err/len(Tr)), (test_err/len(Ts))
def conf_interval(pop):
z = z_critical = stats.norm.ppf(q = 0.95)
moe = z * (pop.std()/math.sqrt(len(pop)))
return (pop.mean() - moe, pop.mean() + moe)
K = 10
points, out = generateChevronData()
in_size = 2
out_size = 1
split = split_data(len(points), K)
train_errs = []
test_errs = []
for s in split:
train_err, test_err = train_perceptron_network(s[0], s[1], points, out)
train_errs.append(train_err)
test_errs.append(test_err)
print("Train Error: ", train_err)
print("Test Error", test_err)
print()
mean_train_err = np.array(train_errs).mean()
mean_test_err = np.array(test_errs).mean()
print("AVG Train Error: ", mean_train_err)
print("AVG Test Error: ", mean_test_err)
print("Train Conf: ", conf_interval(np.array(train_errs)))
print("Test Conf: ", conf_interval(np.array(test_errs)))
|
garibaldu/boundary-seekers
|
Boundary Hunter Ideas/TensorFlow/PerceptronNetwork.py
|
Python
|
mit
| 3,754
|
[
"MOE"
] |
60d4273676b1ca62676a44256dfb8b41b5186ecb53d4f6652be8dd0ae91a6901
|
##############################################################################
# Copyright (c) 2013-2017, Lawrence Livermore National Security, LLC.
# Produced at the Lawrence Livermore National Laboratory.
#
# This file is part of Spack.
# Created by Todd Gamblin, tgamblin@llnl.gov, All rights reserved.
# LLNL-CODE-647188
#
# For details, see https://github.com/llnl/spack
# Please also see the NOTICE and LICENSE files for our notice and the LGPL.
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU Lesser General Public License (as
# published by the Free Software Foundation) version 2.1, February 1999.
#
# This program is distributed in the hope that it will be useful, but
# WITHOUT ANY WARRANTY; without even the IMPLIED WARRANTY OF
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the terms and
# conditions of the GNU Lesser General Public License for more details.
#
# You should have received a copy of the GNU Lesser General Public
# License along with this program; if not, write to the Free Software
# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
##############################################################################
from spack import *
class Espressopp(CMakePackage):
"""ESPResSo++ is an extensible, flexible, fast and parallel simulation
software for soft matter research. It is a highly versatile software
package for the scientific simulation and analysis of coarse-grained
atomistic or bead-spring models as they are used in soft matter research
"""
homepage = "https://espressopp.github.io"
url = "https://github.com/espressopp/espressopp/tarball/v1.9.4.1"
version('develop', git='https://github.com/espressopp/espressopp.git', branch='master')
version('1.9.4.1', '0da74a6d4e1bfa6a2a24fca354245a4f')
version('1.9.4', 'f2a27993a83547ad014335006eea74ea')
variant('ug', default=False, description='Build user guide')
variant('pdf', default=False, description='Build user guide in pdf format')
variant('dg', default=False, description='Build developer guide')
depends_on("cmake@2.8:", type='build')
depends_on("mpi")
depends_on("boost+serialization+filesystem+system+python+mpi", when='@1.9.4:')
extends("python")
depends_on("python@2:2.8")
depends_on("py-mpi4py@2.0.0:", when='@1.9.4', type=('build', 'run'))
depends_on("py-mpi4py@1.3.1:", when='@1.9.4.1:', type=('build', 'run'))
depends_on("fftw")
depends_on("py-sphinx", when="+ug", type='build')
depends_on("py-sphinx", when="+pdf", type='build')
depends_on('py-numpy', type=('build', 'run'))
depends_on('py-matplotlib', when="+ug", type='build')
depends_on('py-matplotlib', when="+pdf", type='build')
depends_on("texlive", when="+pdf", type='build')
depends_on("doxygen", when="+dg", type='build')
def cmake_args(self):
return ['-DEXTERNAL_MPI4PY=ON', '-DEXTERNAL_BOOST=ON']
def build(self, spec, prefix):
with working_dir(self.build_directory):
make()
if '+ug' in spec:
make("ug", parallel=False)
if '+pdf' in spec:
make("ug-pdf", parallel=False)
if '+dg' in spec:
make("doc", parallel=False)
|
wscullin/spack
|
var/spack/repos/builtin/packages/espressopp/package.py
|
Python
|
lgpl-2.1
| 3,323
|
[
"ESPResSo"
] |
6a1cc0be2bf12335f25ac04f8bd2dc538d2b3ffb18ece903e60535c902a6f566
|
"""
Container page in Studio
"""
from bok_choy.page_object import PageObject
from bok_choy.promise import Promise, EmptyPromise
from . import BASE_URL
from utils import click_css, confirm_prompt
class ContainerPage(PageObject):
"""
Container page in Studio
"""
NAME_SELECTOR = '.page-header-title'
NAME_INPUT_SELECTOR = '.page-header .xblock-field-input'
NAME_FIELD_WRAPPER_SELECTOR = '.page-header .wrapper-xblock-field'
ADD_MISSING_GROUPS_SELECTOR = '.notification-action-button[data-notification-action="add-missing-groups"]'
def __init__(self, browser, locator):
super(ContainerPage, self).__init__(browser)
self.locator = locator
@property
def url(self):
"""URL to the container page for an xblock."""
return "{}/container/{}".format(BASE_URL, self.locator)
@property
def name(self):
titles = self.q(css=self.NAME_SELECTOR).text
if titles:
return titles[0]
else:
return None
def is_browser_on_page(self):
def _xblock_count(class_name, request_token):
return len(self.q(css='{body_selector} .xblock.{class_name}[data-request-token="{request_token}"]'.format(
body_selector=XBlockWrapper.BODY_SELECTOR, class_name=class_name, request_token=request_token
)).results)
def _is_finished_loading():
is_done = False
# Get the request token of the first xblock rendered on the page and assume it is correct.
data_request_elements = self.q(css='[data-request-token]')
if len(data_request_elements) > 0:
request_token = data_request_elements.first.attrs('data-request-token')[0]
# Then find the number of Studio xblock wrappers on the page with that request token.
num_wrappers = len(self.q(css='{} [data-request-token="{}"]'.format(XBlockWrapper.BODY_SELECTOR, request_token)).results)
# Wait until all components have been loaded and marked as either initialized or failed.
# See:
# - common/static/js/xblock/core.js which adds the class "xblock-initialized"
# at the end of initializeBlock.
# - common/static/js/views/xblock.js which adds the class "xblock-initialization-failed"
# if the xblock threw an error while initializing.
num_initialized_xblocks = _xblock_count('xblock-initialized', request_token)
num_failed_xblocks = _xblock_count('xblock-initialization-failed', request_token)
is_done = num_wrappers == (num_initialized_xblocks + num_failed_xblocks)
return (is_done, is_done)
# First make sure that an element with the view-container class is present on the page,
# and then wait for the loading spinner to go away and all the xblocks to be initialized.
return (
self.q(css='body.view-container').present and
self.q(css='div.ui-loading.is-hidden').present and
Promise(_is_finished_loading, 'Finished rendering the xblock wrappers.').fulfill()
)
def wait_for_component_menu(self):
"""
Waits until the menu bar of components is present on the page.
"""
EmptyPromise(
lambda: self.q(css='div.add-xblock-component').present,
'Wait for the menu of components to be present'
).fulfill()
@property
def xblocks(self):
"""
Return a list of xblocks loaded on the container page.
"""
return self._get_xblocks()
@property
def inactive_xblocks(self):
"""
Return a list of inactive xblocks loaded on the container page.
"""
return self._get_xblocks(".is-inactive ")
@property
def active_xblocks(self):
"""
Return a list of active xblocks loaded on the container page.
"""
return self._get_xblocks(".is-active ")
@property
def publish_title(self):
"""
Returns the title as displayed on the publishing sidebar component.
"""
return self.q(css='.pub-status').first.text[0]
@property
def release_title(self):
"""
Returns the title before the release date in the publishing sidebar component.
"""
return self.q(css='.wrapper-release .title').first.text[0]
@property
def release_date(self):
"""
Returns the release date of the unit (with ancestor inherited from), as displayed
in the publishing sidebar component.
"""
return self.q(css='.wrapper-release .copy').first.text[0]
@property
def last_saved_text(self):
"""
Returns the last saved message as displayed in the publishing sidebar component.
"""
return self.q(css='.wrapper-last-draft').first.text[0]
@property
def last_published_text(self):
"""
Returns the last published message as displayed in the sidebar.
"""
return self.q(css='.wrapper-last-publish').first.text[0]
@property
def currently_visible_to_students(self):
"""
Returns True if the unit is marked as currently visible to students
(meaning that a warning is being displayed).
"""
warnings = self.q(css='.container-message .warning')
if not warnings.is_present():
return False
warning_text = warnings.first.text[0]
return warning_text == "Caution: The last published version of this unit is live. By publishing changes you will change the student experience."
def shows_inherited_staff_lock(self, parent_type=None, parent_name=None):
"""
Returns True if the unit inherits staff lock from a section or subsection.
"""
return self.q(css='.bit-publishing .wrapper-visibility .copy .inherited-from').visible
@property
def publish_action(self):
"""
Returns the link for publishing a unit.
"""
return self.q(css='.action-publish').first
def discard_changes(self):
"""
Discards draft changes (which will then re-render the page).
"""
click_css(self, 'a.action-discard', 0, require_notification=False)
confirm_prompt(self)
self.wait_for_ajax()
@property
def is_staff_locked(self):
""" Returns True if staff lock is currently enabled, False otherwise """
for attr in self.q(css='a.action-staff-lock>i').attrs('class'):
if 'fa-check-square-o' in attr:
return True
return False
def toggle_staff_lock(self, inherits_staff_lock=False):
"""
Toggles "hide from students" which enables or disables a staff-only lock.
Returns True if the lock is now enabled, else False.
"""
was_locked_initially = self.is_staff_locked
if not was_locked_initially:
self.q(css='a.action-staff-lock').first.click()
else:
click_css(self, 'a.action-staff-lock', 0, require_notification=False)
if not inherits_staff_lock:
confirm_prompt(self)
self.wait_for_ajax()
return not was_locked_initially
def view_published_version(self):
"""
Clicks "View Live Version", which will open the published version of the unit page in the LMS.
Switches the browser to the newly opened LMS window.
"""
self.q(css='.button-view').first.click()
self._switch_to_lms()
def preview(self):
"""
Clicks "Preview Changes", which will open the draft version of the unit page in the LMS.
Switches the browser to the newly opened LMS window.
"""
self.q(css='.button-preview').first.click()
self._switch_to_lms()
def _switch_to_lms(self):
"""
Assumes LMS has opened-- switches to that window.
"""
browser_window_handles = self.browser.window_handles
# Switch to browser window that shows HTML Unit in LMS
# The last handle represents the latest windows opened
self.browser.switch_to_window(browser_window_handles[-1])
def _get_xblocks(self, prefix=""):
return self.q(css=prefix + XBlockWrapper.BODY_SELECTOR).map(
lambda el: XBlockWrapper(self.browser, el.get_attribute('data-locator'))).results
def duplicate(self, source_index):
"""
Duplicate the item with index source_index (based on vertical placement in page).
"""
click_css(self, 'a.duplicate-button', source_index)
def delete(self, source_index):
"""
Delete the item with index source_index (based on vertical placement in page).
Only visible items are counted in the source_index.
The index of the first item is 0.
"""
# Click the delete button
click_css(self, 'a.delete-button', source_index, require_notification=False)
# Click the confirmation dialog button
confirm_prompt(self)
def edit(self):
"""
Clicks the "edit" button for the first component on the page.
"""
return _click_edit(self)
def add_missing_groups(self):
"""
Click the "add missing groups" link.
Note that this does an ajax call.
"""
self.q(css=self.ADD_MISSING_GROUPS_SELECTOR).first.click()
self.wait_for_ajax()
# Wait until all xblocks rendered.
self.wait_for_page()
def missing_groups_button_present(self):
"""
Returns True if the "add missing groups" button is present.
"""
return self.q(css=self.ADD_MISSING_GROUPS_SELECTOR).present
def get_xblock_information_message(self):
"""
Returns an information message for the container page.
"""
return self.q(css=".xblock-message.information").first.text[0]
def is_inline_editing_display_name(self):
"""
Return whether this container's display name is in its editable form.
"""
return "is-editing" in self.q(css=self.NAME_FIELD_WRAPPER_SELECTOR).first.attrs("class")[0]
class XBlockWrapper(PageObject):
"""
A PageObject representing a wrapper around an XBlock child shown on the Studio container page.
"""
url = None
BODY_SELECTOR = '.studio-xblock-wrapper'
NAME_SELECTOR = '.xblock-display-name'
COMPONENT_BUTTONS = {
'basic_tab': '.editor-tabs li.inner_tab_wrap:nth-child(1) > a',
'advanced_tab': '.editor-tabs li.inner_tab_wrap:nth-child(2) > a',
'save_settings': '.action-save',
}
def __init__(self, browser, locator):
super(XBlockWrapper, self).__init__(browser)
self.locator = locator
def is_browser_on_page(self):
return self.q(css='{}[data-locator="{}"]'.format(self.BODY_SELECTOR, self.locator)).present
def _bounded_selector(self, selector):
"""
Return `selector`, but limited to this particular `CourseOutlineChild` context
"""
return '{}[data-locator="{}"] {}'.format(
self.BODY_SELECTOR,
self.locator,
selector
)
@property
def student_content(self):
"""
Returns the text content of the xblock as displayed on the container page.
"""
return self.q(css=self._bounded_selector('.xblock-student_view'))[0].text
@property
def name(self):
titles = self.q(css=self._bounded_selector(self.NAME_SELECTOR)).text
if titles:
return titles[0]
else:
return None
@property
def children(self):
"""
Will return any first-generation descendant xblocks of this xblock.
"""
descendants = self.q(css=self._bounded_selector(self.BODY_SELECTOR)).map(
lambda el: XBlockWrapper(self.browser, el.get_attribute('data-locator'))).results
# Now remove any non-direct descendants.
grandkids = []
for descendant in descendants:
grandkids.extend(descendant.children)
grand_locators = [grandkid.locator for grandkid in grandkids]
return [descendant for descendant in descendants if descendant.locator not in grand_locators]
@property
def preview_selector(self):
return self._bounded_selector('.xblock-student_view,.xblock-author_view')
def go_to_container(self):
"""
Open the container page linked to by this xblock, and return
an initialized :class:`.ContainerPage` for that xblock.
"""
return ContainerPage(self.browser, self.locator).visit()
def edit(self):
"""
Clicks the "edit" button for this xblock.
"""
return _click_edit(self, self._bounded_selector)
def open_advanced_tab(self):
"""
Click on Advanced Tab.
"""
self._click_button('advanced_tab')
def open_basic_tab(self):
"""
Click on Basic Tab.
"""
self._click_button('basic_tab')
def save_settings(self):
"""
Click on settings Save button.
"""
self._click_button('save_settings')
@property
def editor_selector(self):
return '.xblock-studio_view'
def _click_button(self, button_name):
"""
Click on a button as specified by `button_name`
Arguments:
button_name (str): button name
"""
self.q(css=self.COMPONENT_BUTTONS[button_name]).first.click()
self.wait_for_ajax()
def go_to_group_configuration_page(self):
"""
Go to the Group Configuration used by the component.
"""
self.q(css=self._bounded_selector('span.message-text a')).first.click()
@property
def group_configuration_link_name(self):
"""
Get Group Configuration name from link.
"""
return self.q(css=self._bounded_selector('span.message-text a')).first.text[0]
def _click_edit(page_object, bounded_selector=lambda(x): x):
"""
Click on the first edit button found and wait for the Studio editor to be present.
"""
page_object.q(css=bounded_selector('.edit-button')).first.click()
EmptyPromise(
lambda: page_object.q(css='.xblock-studio_view').present,
'Wait for the Studio editor to be present'
).fulfill()
return page_object
|
UQ-UQx/edx-platform_lti
|
common/test/acceptance/pages/studio/container.py
|
Python
|
agpl-3.0
| 14,504
|
[
"VisIt"
] |
78df7722c01b23282cfaea2cac76c21f3c0710309ba8869f98e894dfb5c8a795
|
'''
#
# This file is a part of Siesta Help Scripts GUI
#
# (c) Andrey Sobolev, 2013
#
Created on 03.04.2013
@author: andrey
'''
import os, paramiko
def getMount(path):
path = os.path.realpath(os.path.abspath(path))
while path != os.path.sep:
if os.path.ismount(path):
return path
path = os.path.abspath(os.path.join(path, os.pardir))
return path
def getDevice(path):
"Get the device mounted at path"
# uses "/proc/mounts"
pathname = os.path.normcase(path) # might be unnecessary here
try:
with open("/proc/mounts", "r") as ifp:
for line in ifp:
fields= line.rstrip('\n').split()
# note that line above assumes that
# no mount points contain whitespace
if fields[1] == pathname:
return fields[0], fields[2]
except EnvironmentError:
pass
return None # explicit
def getSSHClient(host, user):
'Returns paramiko ssh client'
ssh = paramiko.SSHClient()
ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
ssh.connect(host, username=user)
return ssh
def runCommand(ssh, cmd):
_, stdout, stderr = ssh.exec_command(cmd)
return stdout, stderr
def findExecutable(ssh, filename):
stdout, _ = runCommand(ssh, 'which ' + filename)
return len(stdout.readlines()) != 0
def getQueue(ssh):
'Returns queue system implemented on a remote cluster'
if findExecutable(ssh, 'qstat'):
return 'pbs'
elif findExecutable(ssh, 'sinfo'):
return 'slurm'
else:
return None
def copyFile(ssh, filename, localdir, remotedir):
'Copies a file filename from localdir to remotedir'
sftp = ssh.open_sftp()
localpath = os.path.join(localdir, filename)
remotepath = os.path.join(remotedir, filename)
sftp.put(localpath, remotepath)
return sftp
def removeFile(sftp, remotefile):
'Removes a file at given remotepath'
sftp.remove(remotefile)
def getRemoteDir(localdir, localmpath, remotempath):
''' Gets remote path of a directory mounted on local machine
Input:
-> localdir : a directory mounted on local machine
-> localmpath : a mountpoint of a directory on a local machine
-> remotempath : a directory on a remote machine which is mounted at localmpath
'''
return localdir.replace(localmpath, remotempath)
if __name__ == '__main__':
host = 'tornado.susu.ac.ru'
user = 'physics'
ssh = getSSHClient(host, user)
|
ansobolev/shs
|
shs/gui/sshutils.py
|
Python
|
mit
| 2,520
|
[
"SIESTA"
] |
ab91ec297b0ee60ea7b8b6a250473fca3419572a690d8a47a644131583390115
|
# -*- coding: utf-8 -*-
"""
Classes
-------
:class:`SGrid`
Simple grid class
:class:`Section`
Class for vertical sections
"""
# -----------------------------------
# Bjørn Ådlandsvik, <bjorn@imr.no>
# Institute of Marine Research
# Bergen, Norway
# 2010-09-30
# -----------------------------------
import numpy as np
from depth import sdepth, zslice, s_stretch
from sample import sample2D, bilin_inv
# ------------------------------------------------------
# Classes
# ------------------------------------------------------
class SGrid(object):
"""Simple ROMS grid object
Simple, minimal ROMS 3D grid object, for keeping important
information together. Meant to be compatible with
roms2soda's grdClass.
Note: Can not (yet) be initialized from a standard grd-file,
use initial, history or average file
Typical usage::
>>> fid = Dataset(roms_file)
>>> grd = SGrid(fid)
More arguments::
>>> fid = Dataset(roms_file)
>>> Vinfo = {'N' : 32, 'hc' : 10, 'theta_s' : 0.8, 'theta_b' : 0.4}
>>> grd = SGrid(fid, subgrid=(100, 121, 60, 161), Vinfo=Vinfo)
"""
def __init__(self, ncid, subgrid=None, Vinfo=None):
# ----------------------------------
# Handle the vertical discretization
# ----------------------------------
if Vinfo:
self.N = Vinfo['N']
self.hc = Vinfo['hc']
# Trengs ikke utenfor her
if Vinfo.has_key('Vstretching'):
self.Vstretching = Vinfo['Vstretching']
else:
self.Vstretching = 1
if Vinfo.has_key('Vtransform'): # Denne trenger self
self.Vtransform = Vinfo['Vtransform']
else:
self.Vtransform = 1
self.Cs_r = s_stretch(self.N, Vinfo['theta_s'], Vinfo['theta_b'],
stagger='rho', Vstretching=self.Vstretching)
self.Cs_w = s_stretch(self.N, Vinfo['theta_s'], Vinfo['theta_b'],
stagger='w', Vstretching=self.Vstretching)
else: # Read vertical info from the file
self.hc = ncid.variables['hc'].getValue()
self.Cs_r = ncid.variables['Cs_r'][:]
self.Cs_w = ncid.variables['Cs_w'][:]
# Vertical grid size
self.N = len(self.Cs_r)
# Vertical transform
self.Vtransform = 1 # Default
try: # Look for standard_name attribute of variable s_rho
v = ncid.variables['s_rho']
if v.standard_name[-1] == '2':
self.Vtransform = 2
# No variable s_rho or no standard_name attribute
except (KeyError, RuntimeError):
pass # keep default Vtransform = 1
# ---------------------
# Subgrid specification
# ---------------------
Mp, Lp = ncid.variables['h'].shape
if subgrid:
i0 = subgrid[0]
i1 = subgrid[1]
j0 = subgrid[2]
j1 = subgrid[3]
if i0 < 0: i0 += Lp
if i1 < 0: i1 += Lp
if j0 < 0: j0 += Mp
if j1 < 0: j1 += Mp
# should have test 0 <= i0 < i1 = Lp
# should have test 0 <= j0 < j1 = Mp
#self.Lp = self.i1 - self.i0
#elf.Mp = self.j1 - self.j0
self.i0, self.i1 = i0, i1
self.j0, self.j1 = j0, j1
else:
self.i0, self.i1 = 0, Lp
self.j0, self.j1 = 0, Mp
# Shape
self.shape = (self.j1-self.j0, self.i1-self.i0)
# Slices
self.I = slice(self.i0, self.i1)
self.J = slice(self.j0, self.j1)
# U and V-points
i0_u = max(0, self.i0-1)
i1_u = min(self.i1, Lp-1)
j0_v = max(0, self.j0-1)
j1_v = min(self.j1, Mp-1)
self.i0_u = i0_u
self.j0_v = j0_v
self.Iu = slice(i0_u, i1_u)
self.Ju = self.J
self.Iv = self.I
self.Jv = slice(j0_v, j1_v)
# ---------------
# Coordinates
# ---------------
# Limits
self.xmin = float(self.i0)
self.xmax = float(self.i1 - 1)
self.ymin = float(self.j0)
self.ymax = float(self.j1 - 1)
# Grid cell centers
self.X = np.arange(self.i0, self.i1)
self.Y = np.arange(self.j0, self.j1)
# U points
#self.Xu = np.arange(self.i0_u, self.i1_u)
#self.Yu = self.Y
# V points
#self.Xv = self.X
#self.Yv = np.arange(self.j0_v, self.j1_v)
# Grid cell boundaries = psi-points
self.Xb = np.arange(self.i0-0.5, self.i1)
self.Yb = np.arange(self.j0-0.5, self.j1)
# Read variables from the NetCDF file
self.h = ncid.variables['h'][self.J, self.I]
# mask_rho should not be masked
self.mask_rho = np.array(ncid.variables['mask_rho'][self.J, self.I])
try:
self.pm = ncid.variables['pm'][self.J, self.I]
self.pn = ncid.variables['pn'][self.J, self.I]
except KeyError:
pass
try:
self.lon_rho = ncid.variables['lon_rho'][self.J, self.I]
self.lat_rho = ncid.variables['lat_rho'][self.J, self.I]
except KeyError:
pass
try:
self.angle = ncid.variables['angle'][self.J, self.I]
self.f = ncid.variables['f'][self.J, self.I]
except KeyError:
pass
# ---------------------
# 3D depth structure
# ---------------------
self.z_r = sdepth(self.h, self.hc, self.Cs_r,
stagger='rho', Vtransform=self.Vtransform)
self.z_w = sdepth(self.h, self.hc, self.Cs_w,
stagger='w', Vtransform=self.Vtransform)
# Wrappers for romsutil functions
# Unødvendig?
def sample2D(self, F, X, Y, mask=True, undef=np.nan):
if mask:
return sample2D(F, X, Y, mask=self.mask_rho,
undef_value=undef)
else:
return sample2D(F, X, Y)
def zslice(self, F, z):
return zslice(F, self.z_r, -abs(z))
def xy2ll(self, x, y):
return sample2D(self.lon_rho, x, y), \
sample2D(self.lat_rho, x, y)
def ll2xy(self, lon, lat):
y, x = bilin_inv(lon, lat, self.lon_rho, self.lat_rho)
return x, y
|
chiluf/roppy
|
roppy/sgrid.py
|
Python
|
mit
| 6,540
|
[
"NetCDF"
] |
1549524101ddb012889d57fd3f4add1911794bbfd4d79352c7197a9a9a379b7d
|
#!/usr/bin/env python
################################################################################
# DATE: 2016/May/06, rev: 2016/July/11
#
# SCRIPT: magnitude_difference_flags.py
#
# VERSION: 2.0
#
# AUTHOR: Miguel A Ibarra (miguelib@ufl.edu)
#
# DESCRIPTION: This script takes a a wide format file and counts digits in
# decimal numbers.The output is an html file containing graphs and data
#
################################################################################
# Import built-in libraries
import os
import logging
import zipfile
import argparse
from io import StringIO
# Import add-on libraries
import matplotlib
import numpy as np
matplotlib.use('Agg')
from lxml import etree
import matplotlib.pyplot as plt
import xml.etree.ElementTree as ET
from matplotlib.backends.backend_pdf import PdfPages
# Import local data libraries
from secimtools.dataManager import logger as sl
from secimtools.dataManager.flags import Flags
from secimtools.dataManager.interface import wideToDesign
# Import local plotting libraries
from secimtools.visualManager import module_hist as hist
from secimtools.visualManager.manager_color import colorHandler
from secimtools.visualManager.manager_figure import figureHandler
def getOptions(myopts=None):
""" Function to pull in arguments """
description = """ Count the digits in data to determine possible outliers
or discrepancies"""
parser = argparse.ArgumentParser(description=description)
# Standard input
standard = parser.add_argument_group(description="Standar input")
standard.add_argument('-i',"--input", dest="input", action='store',
required=True, help="Input dataset in wide format.")
standard.add_argument('-d',"--design", dest="design", action='store',
required=True, help="Design file.")
standard.add_argument('-id',"--ID", dest="uniqID", action='store',
required=True, help="Name of the column with uniq IDs.")
standard.add_argument('-g',"--group", dest="group", action='store',
required=False, default=False, help="Add the option to "\
"separate sample IDs by treatement name. ")
# Tool input
tool = parser.add_argument_group(description="Optional input")
tool.add_argument('-nz',"--noZero", dest="zero", action='store_true',
required=False, help="Flag to ignore zeros.")
tool.add_argument('-bug',"--debug", dest="debug", action='store_true',
required=False, help="Add debugging log output.")
tool.add_argument('-ht',"--html", dest="html", action='store',
required=False, default=None, help="Path for html"\
" output file (this option is just for galaxy")
tool.add_argument('-htp',"--htmlPath", dest="htmlPath", action='store',
required=False, default=None, help="Path for html "\
"output file (this option is just for galaxy")
# Tool output
output = parser.add_argument_group(description="Output options")
output.add_argument("-f","--figure",dest="figure",action="store",
required=True,help="Output path for plot file")
output.add_argument("-fl","--flags",dest="flags",action="store",
required=True,help="Output path for flag file")
output.add_argument("-c","--counts",dest="counts",action="store",
required=True,help="Output name for counts files"\
"The extension is not requiered its going to be added"\
"automatically for each file.")
if myopts:
args = parser.parse_args(myopts)
else:
args = parser.parse_args()
return(args)
def splitDigits(x):
"""
Function to split digits by decimal
:Arguments:
:type x: int
:param x: Number to count digits form.
:Returns:
:rtype x: int
:returns x: count of the given number.
"""
if x == 0:
return np.nan
else:
# Bug fixer of scientific notation (Very large and very small numbers)
x = str('%f' % x)
# Split x at the decimal point and then take the length of the string
# Before the decimal point then return
return len(x.split('.')[0])
def countDigits(wide):
"""
This function counts digits on a given file.
:Arguments:
:type wide: pandas.DataFrame.
:param wide: Input data to count digits.
:Returns:
:rtype count: pandas.DataFrame
:returns count: DataFrama with the counted digits and min, max and
diff among rows.
"""
# Count the number of digits before decimal and get basic distribution info
count = wide.applymap(lambda x: splitDigits(x))
# Calculate min, max number of digits on the row and the difference
count["min"] = count.apply(np.min, axis=1)
count["max"] = count.apply(np.max, axis=1)
count["diff"] = count["max"] - count["min"]
# Return counts
return count
def plotCDhistogram(count,pdf,group):
"""
This function counts digits on a given file.
:Arguments:
:type count: pandas.DataFrame.
:param count: DataFrama with the counted digits and min, max and
diff among rows.
:type pdf: matplotlib.backends.backend_pdf.PdfPages.
:param pdf: PDF object to plot figures in.
:type group: str.
:param group: Name of the group to plot.
"""
#Creating title
title="Distribution of difference between \n(min and max) for {0} compounds".\
format(group)
if count['diff'].any():
#Opening figure handler
fh = figureHandler(proj='2d')
#Plot histogram
hist.quickHist(ax=fh.ax[0],dat=count['diff'])
#Giving format to the axis
fh.formatAxis(xTitle='Difference in Number of Digits (max - min)',
yTitle='Number of Features',figTitle=title, ylim="ignore")
# Explort figure
fh.addToPdf(pdf,dpi=600)
else:
logger.warn("There were no differences in digit counts for {0}, no plot will be generated".format(group))
def createHTML():
#Create html object
html = etree.Element("html")
head = etree.SubElement(html, "head")
title = etree.SubElement(head, "title")
title.text = "Count Digits Results List"
body = etree.SubElement(html, "body")
div = etree.SubElement(body, "div",style="background-color:black; "\
"color:white; text-align:center; margin-bottom:5% padding:4px;")
h1 = etree.SubElement(div,"h1")
ul = etree.SubElement(body,"ul",style="text-align:left; margin-left:5%;")
h1.text="Output"
#Return htmml
return html
def save2html(data, filename, filePath, html=None):
#Add data to html
if html is not None:
li = etree.SubElement(html[1][1],"li", style="margin-bottom:1.5%;")
a= etree.SubElement(li,"a",href=filename)
a.text=os.path.split(filename)[1]
#Save data
data.to_csv(filePath,sep="\t",na_rep=0)
#Return html
return html
def countDigitsByGroup(dat, args, folderDir, pdf, html=None):
"""
If the group option is selected this function is called to split by groups.
The function calls the countDigits function in a loop that iterates through
the groups
:Arguments:
:type dat: wideToDesign
:param dat: input data
:type args: argparse.ArgumentParser.
:param args: Command line arguments.
:type pdf: matplotlib.backends.backend_pdf.PdfPages.
:param pdf: PDF object to plot figures in.
:type countzip: zipfile.ZipFile.
:param countzip: Zip container.
"""
# Split Design file by group
if dat.group:
for name, group in dat.design.groupby(dat.group):
# Setting count path
countPath = folderDir+"_{0}.tsv".format(name)
# Setting count name
countName = args.counts+"_{0}.tsv".format(name)
# Filter the wide file into a new dataframe
currentFrame = dat.wide[group.index]
# Counting digits per group
count = countDigits(currentFrame)
# Plotting CD histograms
plotCDhistogram(count,pdf,name)
# Save countName, save it to html if exist
save2html(html=html, data=count, filename=countName, filePath=countPath)
def saveFlags(count):
"""
Function to create and export flags for the counts.
:Arguments:
:type count: pandas.DataFrame.
:param count: DataFrama with the counted digits and min, max and
diff among rows.
"""
# Create flag object
flag = Flags(index=count.index)
# If the difference is greater than 1 a flag is set for dat row/met.
flag.addColumn(column="flag_feature_count_digits",mask=count["diff"] >= 2)
#Save flags
flag.df_flags.to_csv(os.path.abspath(args.flags),sep="\t")
def main(args):
#parsing data with interface
dat = wideToDesign(wide=args.input, design=args.design, uniqID=args.uniqID,
group=args.group, logger=logger)
# Removing groups with just one elemen from dat
dat.removeSingle()
# Create folder for counts if html found
if args.html is not None:
logger.info(u"Using html output file")
folderDir = args.htmlPath
try:
os.makedirs(folderDir)
#KAS: changing raising exception error. Gives syntax error
# except Exception, e:
# raise Exception (e)
except Exception as e:
logger.error("Error. {}".format(e))
# Initiation zip files
html = createHTML()
folderDir =folderDir+"/"+args.counts
else:
folderDir=args.counts
html =args.html
# Use group separation or not depending on user input
with PdfPages(os.path.abspath(args.figure)) as pdf:
if args.group:
# Count Digits per group
logger.info(u"Counting digits per group")
countDigitsByGroup(dat, args, folderDir, pdf, html=html)
# Count digits for all elements
count = countDigits(wide=dat.wide)
# Plotting for all elements
plotCDhistogram(count=count, pdf=pdf, group="all")
# Calculate and save flags for all elements
logger.info(u"Calculating flags")
saveFlags(count)
# Add count of all elements to html if not html save directly
html = save2html(html=html,data=count,filename=args.counts+"_all.tsv",filePath=folderDir+"_all.tsv")
#Save to html
if args.html:
with open(args.html,"w") as htmlOut:
print(etree.tostring(html,pretty_print=True), file=htmlOut)
# print >> htmlOut,etree.tostring(html,pretty_print=True)
# Finishing script
logger.info(u"Count Digits Complete!")
if __name__ == '__main__':
# Command line options
args = getOptions()
# Setting logger
logger = logging.getLogger()
if args.debug:
sl.setLogger(logger, logLevel='debug')
else:
sl.setLogger(logger)
# Starting script with the following parameters
logger.info(u"Importing data with following parameters: "\
"\n\tWide: {0}"\
"\n\tDesign: {1}"\
"\n\tUnique ID: {2}"\
"\n\tGroup: {3}"\
"\n\tHtml: {4}".\
format(args.input,args.design, args.uniqID, args.group, args.html))
# Main
main(args)
|
secimTools/SECIMTools
|
src/scripts/magnitude_difference_flags.py
|
Python
|
mit
| 11,801
|
[
"Galaxy"
] |
2abc656d4216ebb38f2a38239cab81d3b9899f76e612eab623f0adb5fc9efa3d
|
"""
Author: Keith Schwarz (htiek@cs.stanford.edu)
Ported to Python by Dan Stromberg (strombrg@gmail.com)
An implementation of a priority queue backed by a Fibonacci heap, as described
by Fredman and Tarjan. Fibonacci heaps are interesting theoretically because
they have asymptotically good runtime guarantees for many operations. In
particular, insert, peek, and decrease-key all run in amortized O(1) time.
dequeue_min and delete each run in amortized O(lg n) time. This allows
algorithms that rely heavily on decrease-key to gain significant performance
boosts. For example, Dijkstra's algorithm for single-source shortest paths can
be shown to run in O(m + n lg n) using a Fibonacci heap, compared to O(m lg n)
using a standard binary or binomial heap.
Internally, a Fibonacci heap is represented as a circular, doubly-linked list
of trees obeying the min-heap property. Each node stores pointers to its
parent (if any) and some arbitrary child. Additionally, every node stores its
degree (the number of children it has) and whether it is a "marked" node.
Finally, each Fibonacci heap stores a pointer to the tree with the minimum
value.
To insert a node into a Fibonacci heap, a singleton tree is created and merged
into the rest of the trees. The merge operation works by simply splicing
together the doubly-linked lists of the two trees, then updating the min
pointer to be the smaller of the minima of the two heaps. Peeking at the
smallest element can therefore be accomplished by just looking at the min
element. All of these operations complete in O(1) time.
The tricky operations are dequeue_min and decrease_key. dequeue_min works by
removing the root of the tree containing the smallest element, then merging its
children with the topmost roots. Then, the roots are scanned and merged so
that there is only one tree of each degree in the root list. This works by
maintaining a dynamic array of trees, each initially null, pointing to the
roots of trees of each dimension. The list is then scanned and this array is
populated. Whenever a conflict is discovered, the appropriate trees are merged
together until no more conflicts exist. The resulting trees are then put into
the root list. A clever analysis using the potential method can be used to
show that the amortized cost of this operation is O(lg n), see "Introduction to
Algorithms, Second Edition" by Cormen, Rivest, Leiserson, and Stein for more
details.
The other hard operation is decrease_key, which works as follows. First, we
update the key of the node to be the new value. If this leaves the node
smaller than its parent, we're done. Otherwise, we cut the node from its
parent, add it as a root, and then mark its parent. If the parent was already
marked, we cut that node as well, recursively mark its parent, and continue
this process. This can be shown to run in O(1) amortized time using yet
another clever potential function. Finally, given this function, we can
implement delete by decreasing a key to -infinity, then calling dequeue_min to
extract it.
"""
import math
import collections
def merge_lists(one, two):
"""
Utility function which, given two pointers into disjoint circularly-
linked lists, merges the two lists together into one circularly-linked
list in O(1) time. Because the lists may be empty, the return value
is the only pointer that's guaranteed to be to an element of the
resulting list.
This function assumes that one and two are the minimum elements of the
lists they are in, and returns a pointer to whichever is smaller. If
this condition does not hold, the return value is some arbitrary pointer
into the doubly-linked list.
@param one A reference to one of the two deques.
@param two A reference to the other of the two deques.
@return A reference to the smallest element of the resulting list.
"""
# There are four cases depending on whether the lists are None or not.
# We consider each separately.
if one is None and two is None:
# Both None, resulting list is None.
return None
elif one is not None and two is None:
# Two is None, result is one.
return one
elif one is None and two is not None:
# One is None, result is two.
return two
else:
# Both non-None; actually do the splice.
# This is actually not as easy as it seems. The idea is that we'll
# have two lists that look like this:
#
# +----+ +----+ +----+
# | |--N->|one |--N->| |
# | |<-P--| |<-P--| |
# +----+ +----+ +----+
#
#
# +----+ +----+ +----+
# | |--N->|two |--N->| |
# | |<-P--| |<-P--| |
# +----+ +----+ +----+
#
# And we want to relink everything to get
#
# +----+ +----+ +----+---+
# | |--N->|one | | | |
# | |<-P--| | | |<+ |
# +----+ +----+<-\ +----+ | |
# \ P | |
# N \ N |
# +----+ +----+ \->+----+ | |
# | |--N->|two | | | | |
# | |<-P--| | | | | P
# +----+ +----+ +----+ | |
# ^ | | |
# | +-------------+ |
# +-----------------+
# Cache this since we're about to overwrite it.
one_next = one.m_next
one.m_next = two.m_next
one.m_next.m_prev = one
two.m_next = one_next
two.m_next.m_prev = two
# Return a pointer to whichever's smaller.
if one.m_priority < two.m_priority:
return one
else:
return two
def merge(one, two):
"""
Given two Fibonacci heaps, returns a new Fibonacci heap that contains
all of the elements of the two heaps. Each of the input heaps is
destructively modified by having all its elements removed. You can
continue to use those heaps, but be aware that they will be empty
after this call completes.
@param one The first Fibonacci heap to merge.
@param two The second Fibonacci heap to merge.
@return A new Fibonacci_heap containing all of the elements of both
heaps.
"""
# Create a new Fibonacci_heap to hold the result.
result = Fibonacci_heap()
# Merge the two Fibonacci heap root lists together. This helper function
# also computes the min of the two lists, so we can store the result in
# the m_min field of the new heap.
result.m_min = merge_lists(one.m_min, two.m_min)
# The size of the new heap is the sum of the sizes of the input heaps.
result.m_size = one.m_size + two.m_size
# Clear the old heaps.
one.m_size = two.m_size = 0
one.m_min = None
two.m_min = None
# Return the newly-merged heap.
return result
# In order for all of the Fibonacci heap operations to complete in O(1),
# clients need to have O(1) access to any element in the heap. We make
# this work by having each insertion operation produce a handle to the
# node in the tree. In actuality, this handle is the node itself.
class Entry(object):
# pylint: disable=too-many-instance-attributes
"""Hold an entry in the heap"""
__slots__ = ['m_degree', 'm_is_marked', 'm_parent', 'm_child', 'm_next', 'm_prev', 'm_elem', 'm_priority']
def __init__(self, elem, priority):
# Number of children
self.m_degree = 0
# Whether this node is marked
self.m_is_marked = False
# Parent in the tree, if any.
self.m_parent = None
# Child node, if any.
self.m_child = None
self.m_next = self.m_prev = self
self.m_elem = elem
self.m_priority = priority
def __lt__(self, other):
if self.m_priority < other.m_priority:
return True
else:
if self.m_elem < other.m_elem:
return True
else:
return False
def __eq__(self, other):
if self.m_priority == other.m_priority:
return True
else:
if self.m_elem == other.m_elem:
return True
else:
return False
def __gt__(self, other):
if self.m_priority > other.m_priority:
return True
else:
if self.m_elem > other.m_elem:
return True
else:
return False
def __cmp__(self, other):
if self.__lt__(other):
return -1
elif self.__gt__(other):
return 1
else:
return 0
def get_value(self):
"""
Returns the element represented by this heap entry.
@return The element represented by this heap entry.
"""
return self.m_elem
def set_value(self, value):
"""
Sets the element associated with this heap entry.
@param value The element to associate with this heap entry.
"""
self.m_elem = value
def get_priority(self):
"""
Returns the priority of this element.
@return The priority of this element.
"""
return self.m_priority
def _entry(self, elem, priority):
"""
Constructs a new Entry that holds the given element with the indicated
priority.
@param elem The element stored in this node.
@param priority The priority of this element.
"""
self.m_next = self.m_prev = self
self.m_elem = elem
self.m_priority = priority
class Fibonacci_heap(object):
"""
A class representing a Fibonacci heap.
@author Keith Schwarz (htiek@cs.stanford.edu)
"""
def __init__(self):
# Pointer to the minimum element in the heap.
self.m_min = None
# Cached size of the heap, so we don't have to recompute this explicitly.
self.m_size = 0
def enqueue(self, value, priority):
"""
Inserts the specified element into the Fibonacci heap with the specified
priority. Its priority must be a valid double, so you cannot set the
priority to NaN.
@param value The value to insert.
@param priority Its priority, which must be valid.
@return An Entry representing that element in the tree.
"""
self._check_priority(priority)
# Create the entry object, which is a circularly-linked list of length
# one.
result = Entry(value, priority)
# Merge this singleton list with the tree list.
self.m_min = merge_lists(self.m_min, result)
# Increase the size of the heap; we just added something.
self.m_size += 1
# Return the reference to the new element.
return result
def min(self):
"""
Returns an Entry object corresponding to the minimum element of the
Fibonacci heap, raising an IndexError if the heap is
empty.
@return The smallest element of the heap.
@raises IndexError If the heap is empty.
"""
if not bool(self):
raise IndexError("Heap is empty.")
return self.m_min
def __bool__(self):
"""
Returns whether the heap is nonempty.
@return Whether the heap is nonempty.
"""
if self.m_min is None:
return False
else:
return True
__nonzero__ = __bool__
def __len__(self):
"""
Returns the number of elements in the heap.
@return The number of elements in the heap.
"""
return self.m_size
def dequeue_min(self):
# pylint: disable=too-many-branches
"""
Dequeues and returns the minimum element of the Fibonacci heap. If the
heap is empty, this throws an IndexError.
@return The smallest element of the Fibonacci heap.
@raises IndexError if the heap is empty.
"""
# Check for whether we're empty.
if not bool(self):
raise IndexError("Heap is empty.")
# Otherwise, we're about to lose an element, so decrement the number of
# entries in this heap.
self.m_size -= 1
# Grab the minimum element so we know what to return.
min_elem = self.m_min
# Now, we need to get rid of this element from the list of roots. There
# are two cases to consider. First, if this is the only element in the
# list of roots, we set the list of roots to be None by clearing m_min.
# Otherwise, if it's not None, then we write the elements next to the
# min element around the min element to remove it, then arbitrarily
# reassign the min.
if self.m_min.m_next is self.m_min:
# Case one
self.m_min = None
else:
# Case two
self.m_min.m_prev.m_next = self.m_min.m_next
self.m_min.m_next.m_prev = self.m_min.m_prev
# Arbitrary element of the root list.
self.m_min = self.m_min.m_next
# Next, clear the parent fields of all of the min element's children,
# since they're about to become roots. Because the elements are
# stored in a circular list, the traversal is a bit complex.
if min_elem.m_child is not None:
# Keep track of the first visited node.
curr = min_elem.m_child
while True:
curr.m_parent = None
# Walk to the next node, then stop if this is the node we
# started at.
curr = curr.m_next
if curr is min_elem.m_child:
# This was a do-while (curr != minElem.mChild);
break
# Next, splice the children of the root node into the topmost list,
# then set self.m_min to point somewhere in that list.
self.m_min = merge_lists(self.m_min, min_elem.m_child)
# If there are no entries left, we're done.
if self.m_min is None:
return min_elem
# Next, we need to coalesce all of the roots so that there is only one
# tree of each degree. To track trees of each size, we allocate an
# ArrayList where the entry at position i is either None or the
# unique tree of degree i.
tree_table = collections.deque()
# We need to traverse the entire list, but since we're going to be
# messing around with it we have to be careful not to break our
# traversal order mid-stream. One major challenge is how to detect
# whether we're visiting the same node twice. To do this, we'll
# spent a bit of overhead adding all of the nodes to a list, and
# then will visit each element of this list in order.
to_visit = collections.deque()
# To add everything, we'll iterate across the elements until we
# find the first element twice. We check this by looping while the
# list is empty or while the current element isn't the first element
# of that list.
# for (Entry<T> curr = self.m_min; toVisit.isEmpty() || toVisit.get(0) != curr; curr = curr.m_next)
curr = self.m_min
while not to_visit or to_visit[0] is not curr:
to_visit.append(curr)
curr = curr.m_next
# Traverse this list and perform the appropriate unioning steps.
for curr in to_visit:
# Keep merging until a match arises.
while True:
# Ensure that the list is long enough to hold an element of this
# degree.
while curr.m_degree >= len(tree_table):
tree_table.append(None)
# If nothing's here, we can record that this tree has this size
# and are done processing.
if tree_table[curr.m_degree] is None:
tree_table[curr.m_degree] = curr
break
# Otherwise, merge with what's there.
other = tree_table[curr.m_degree]
# Clear the slot
tree_table[curr.m_degree] = None
# Determine which of the two trees has the smaller root, storing
# the two trees accordingly.
# minimum = (other.m_priority < curr.m_priority)? other : curr
if other.m_priority < curr.m_priority:
minimum = other
else:
minimum = curr
# maximum = (other.m_priority < curr.m_priority)? curr : other
if other.m_priority < curr.m_priority:
maximum = curr
else:
maximum = other
# Break max out of the root list, then merge it into min's child
# list.
maximum.m_next.m_prev = maximum.m_prev
maximum.m_prev.m_next = maximum.m_next
# Make it a singleton so that we can merge it.
maximum.m_next = maximum.m_prev = maximum
minimum.m_child = merge_lists(minimum.m_child, maximum)
# Reparent maximum appropriately.
maximum.m_parent = minimum
# Clear maximum's mark, since it can now lose another child.
maximum.m_is_marked = False
# Increase minimum's degree; it now has another child.
minimum.m_degree += 1
# Continue merging this tree.
curr = minimum
# Update the global min based on this node. Note that we compare
# for <= instead of < here. That's because if we just did a
# reparent operation that merged two different trees of equal
# priority, we need to make sure that the min pointer points to
# the root-level one.
if curr.m_priority <= self.m_min.m_priority:
self.m_min = curr
return min_elem
def decrease_key(self, entry, new_priority):
"""
Decreases the key of the specified element to the new priority. If the
new priority is greater than the old priority, this function raises an
ValueError. The new priority must be a finite double,
so you cannot set the priority to be NaN, or +/- infinity. Doing
so also raises an ValueError.
It is assumed that the entry belongs in this heap. For efficiency
reasons, this is not checked at runtime.
@param entry The element whose priority should be decreased.
@param new_priority The new priority to associate with this entry.
@raises ValueError If the new priority exceeds the old
priority, or if the argument is not a finite double.
"""
self._check_priority(new_priority)
if new_priority > entry.m_priority:
raise ValueError("New priority exceeds old.")
# Forward this to a helper function.
self.decrease_key_unchecked(entry, new_priority)
def delete(self, entry):
"""
Deletes this Entry from the Fibonacci heap that contains it.
It is assumed that the entry belongs in this heap. For efficiency
reasons, this is not checked at runtime.
@param entry The entry to delete.
"""
#Use decreaseKey to drop the entry's key to -infinity. This will
#guarantee that the node is cut and set to the global minimum.
self.decrease_key_unchecked(entry, float("-inf"))
# Call dequeue_min to remove it.
self.dequeue_min()
@staticmethod
def _check_priority(priority):
"""
Utility function which, given a user-specified priority, checks whether
it's a valid double and throws an ValueError otherwise.
@param priority The user's specified priority.
@raises ValueError if it is not valid.
"""
if math.isnan(priority) or math.isinf(priority):
raise ValueError("Priority {} is invalid.".format(priority))
def decrease_key_unchecked(self, entry, priority):
"""
Decreases the key of a node in the tree without doing any checking to ensure
that the new priority is valid.
@param entry The node whose key should be decreased.
@param priority The node's new priority.
"""
# First, change the node's priority.
entry.m_priority = priority
# If the node no longer has a higher priority than its parent, cut it.
# Note that this also means that if we try to run a delete operation
# that decreases the key to -infinity, it's guaranteed to cut the node
# from its parent.
if entry.m_parent is not None and entry.m_priority <= entry.m_parent.m_priority:
self.cut_node(entry)
# If our new value is the new min, mark it as such. Note that if we
# ended up decreasing the key in a way that ties the current minimum
# priority, this will change the min accordingly.
if entry.m_priority <= self.m_min.m_priority:
self.m_min = entry
def cut_node(self, entry):
"""
Cuts a node from its parent. If the parent was already marked, recursively
cuts that node from its parent as well.
@param entry The node to cut from its parent.
"""
# Begin by clearing the node's mark, since we just cut it.
entry.m_is_marked = False
# Base case: If the node has no parent, we're done.
if entry.m_parent is None:
return
# Rewire the node's siblings around it, if it has any siblings.
if entry.m_next is not entry:
# Has siblings
entry.m_next.m_prev = entry.m_prev
entry.m_prev.m_next = entry.m_next
# If the node is the one identified by its parent as its child,
# we need to rewrite that pointer to point to some arbitrary other
# child.
if entry.m_parent.m_child is entry:
if entry.m_next is not entry:
# If there are any other children, pick one of them arbitrarily.
entry.m_parent.m_child = entry.m_next
else:
# Otherwise, there aren't any children left and we should clear the
# pointer and drop the node's degree.
entry.m_parent.m_child = None
# Decrease the degree of the parent, since it just lost a child.
entry.m_parent.m_degree -= 1
# Splice this tree into the root list by converting it to a singleton
# and invoking the merge subroutine.
entry.m_prev = entry.m_next = entry
self.m_min = merge_lists(self.m_min, entry)
# Mark the parent and recursively cut it if it's already been
# marked.
if entry.m_parent.m_is_marked:
self.cut_node(entry.m_parent)
else:
entry.m_parent.m_is_marked = True
# Clear the relocated node's parent; it's now a root.
entry.m_parent = None
|
dokren/SSSP
|
fheap.py
|
Python
|
mit
| 23,278
|
[
"VisIt"
] |
d6fe4e0f2755943ab88422475d609a6790e41ce11e5fb112ac691341038e248a
|
# Copyright 2022 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# https://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
import abc
import contextlib
import dataclasses
import logging
import shutil
import tempfile
import typing as t
import apache_beam as beam
import xarray as xr
from apache_beam.io.filesystems import FileSystems
from apache_beam.io.gcp.gcsio import DEFAULT_READ_BUFFER_SIZE
logger = logging.getLogger(__name__)
logger.setLevel(logging.INFO)
@dataclasses.dataclass
class ToDataSink(abc.ABC, beam.PTransform):
variables: t.List[str]
area: t.Tuple[int, int, int, int]
xarray_open_dataset_kwargs: t.Dict
@classmethod
def from_kwargs(cls, **kwargs):
fields = [f.name for f in dataclasses.fields(cls)]
return cls(**{k: v for k, v, in kwargs.items() if k in fields})
def _make_grib_dataset_inmem(grib_ds: xr.Dataset) -> xr.Dataset:
# Copies all the vars to in-memory to reduce disk seeks everytime a single row is processed.
# This also removes the need to keep the backing temp source file around.
data_ds = grib_ds.copy(deep=True)
for v in grib_ds.variables:
if v not in data_ds.coords:
data_ds[v].variable.values = grib_ds[v].variable.values
return data_ds
def __open_dataset_file(filename: str, open_dataset_kwargs: t.Optional[t.Dict] = None) -> xr.Dataset:
if open_dataset_kwargs:
return _make_grib_dataset_inmem(xr.open_dataset(filename, **open_dataset_kwargs))
# If no open kwargs are available, make educated guesses about the dataset.
try:
return xr.open_dataset(filename)
except ValueError as e:
e_str = str(e)
if not ("Consider explicitly selecting one of the installed engines" in e_str and "cfgrib" in e_str):
raise
# Trying with explicit engine for cfgrib.
try:
return _make_grib_dataset_inmem(
xr.open_dataset(filename, engine='cfgrib', backend_kwargs={'indexpath': ''}))
except ValueError as e:
if "multiple values for key 'edition'" not in str(e):
raise
logger.warning("Assuming grib edition 1.")
# Try with edition 1
# Note: picking edition 1 for now as it seems to get the most data/variables for ECMWF realtime data.
return _make_grib_dataset_inmem(xr.open_dataset(filename, engine='cfgrib',
backend_kwargs={'filter_by_keys': {'edition': 1}, 'indexpath': ''}))
@contextlib.contextmanager
def open_dataset(uri: str, open_dataset_kwargs: t.Optional[t.Dict] = None) -> t.Iterator[xr.Dataset]:
"""Open the dataset at 'uri' and return a xarray.Dataset."""
try:
# Copy netcdf or grib object from cloud storage, like GCS, to local file
# so xarray can open it with mmap instead of copying the entire thing
# into memory.
with FileSystems().open(uri) as source_file:
with tempfile.NamedTemporaryFile() as dest_file:
shutil.copyfileobj(source_file, dest_file, DEFAULT_READ_BUFFER_SIZE)
dest_file.flush()
dest_file.seek(0)
xr_dataset: xr.Dataset = __open_dataset_file(dest_file.name, open_dataset_kwargs)
logger.info(f'opened dataset size: {xr_dataset.nbytes}')
beam.metrics.Metrics.counter('Success', 'ReadNetcdfData').inc()
yield xr_dataset
except Exception as e:
beam.metrics.Metrics.counter('Failure', 'ReadNetcdfData').inc()
logger.error(f'Unable to open file {uri!r}: {e}')
raise
|
google/weather-tools
|
weather_mv/loader_pipeline/sinks.py
|
Python
|
apache-2.0
| 4,026
|
[
"NetCDF"
] |
a7ee66384ab95f655e4a579c668aab488c466bd5c83da82cdf18d6cc97775b77
|
"""The suite of window functions."""
import operator
import warnings
import numpy as np
from scipy import linalg, special, fft as sp_fft
__all__ = ['boxcar', 'triang', 'parzen', 'bohman', 'blackman', 'nuttall',
'blackmanharris', 'flattop', 'bartlett', 'hanning', 'barthann',
'hamming', 'kaiser', 'kaiser_bessel_derived', 'gaussian',
'general_cosine', 'general_gaussian', 'general_hamming',
'chebwin', 'cosine', 'hann', 'exponential', 'tukey', 'taylor',
'dpss', 'get_window']
def _len_guards(M):
"""Handle small or incorrect window lengths"""
if int(M) != M or M < 0:
raise ValueError('Window length M must be a non-negative integer')
return M <= 1
def _extend(M, sym):
"""Extend window by 1 sample if needed for DFT-even symmetry"""
if not sym:
return M + 1, True
else:
return M, False
def _truncate(w, needed):
"""Truncate window by 1 sample if needed for DFT-even symmetry"""
if needed:
return w[:-1]
else:
return w
def general_cosine(M, a, sym=True):
r"""
Generic weighted sum of cosine terms window
Parameters
----------
M : int
Number of points in the output window
a : array_like
Sequence of weighting coefficients. This uses the convention of being
centered on the origin, so these will typically all be positive
numbers, not alternating sign.
sym : bool, optional
When True (default), generates a symmetric window, for use in filter
design.
When False, generates a periodic window, for use in spectral analysis.
References
----------
.. [1] A. Nuttall, "Some windows with very good sidelobe behavior," IEEE
Transactions on Acoustics, Speech, and Signal Processing, vol. 29,
no. 1, pp. 84-91, Feb 1981. :doi:`10.1109/TASSP.1981.1163506`.
.. [2] Heinzel G. et al., "Spectrum and spectral density estimation by the
Discrete Fourier transform (DFT), including a comprehensive list of
window functions and some new flat-top windows", February 15, 2002
https://holometer.fnal.gov/GH_FFT.pdf
Examples
--------
Heinzel describes a flat-top window named "HFT90D" with formula: [2]_
.. math:: w_j = 1 - 1.942604 \cos(z) + 1.340318 \cos(2z)
- 0.440811 \cos(3z) + 0.043097 \cos(4z)
where
.. math:: z = \frac{2 \pi j}{N}, j = 0...N - 1
Since this uses the convention of starting at the origin, to reproduce the
window, we need to convert every other coefficient to a positive number:
>>> HFT90D = [1, 1.942604, 1.340318, 0.440811, 0.043097]
The paper states that the highest sidelobe is at -90.2 dB. Reproduce
Figure 42 by plotting the window and its frequency response, and confirm
the sidelobe level in red:
>>> from scipy.signal.windows import general_cosine
>>> from scipy.fft import fft, fftshift
>>> import matplotlib.pyplot as plt
>>> window = general_cosine(1000, HFT90D, sym=False)
>>> plt.plot(window)
>>> plt.title("HFT90D window")
>>> plt.ylabel("Amplitude")
>>> plt.xlabel("Sample")
>>> plt.figure()
>>> A = fft(window, 10000) / (len(window)/2.0)
>>> freq = np.linspace(-0.5, 0.5, len(A))
>>> response = np.abs(fftshift(A / abs(A).max()))
>>> response = 20 * np.log10(np.maximum(response, 1e-10))
>>> plt.plot(freq, response)
>>> plt.axis([-50/1000, 50/1000, -140, 0])
>>> plt.title("Frequency response of the HFT90D window")
>>> plt.ylabel("Normalized magnitude [dB]")
>>> plt.xlabel("Normalized frequency [cycles per sample]")
>>> plt.axhline(-90.2, color='red')
>>> plt.show()
"""
if _len_guards(M):
return np.ones(M)
M, needs_trunc = _extend(M, sym)
fac = np.linspace(-np.pi, np.pi, M)
w = np.zeros(M)
for k in range(len(a)):
w += a[k] * np.cos(k * fac)
return _truncate(w, needs_trunc)
def boxcar(M, sym=True):
"""Return a boxcar or rectangular window.
Also known as a rectangular window or Dirichlet window, this is equivalent
to no window at all.
Parameters
----------
M : int
Number of points in the output window. If zero or less, an empty
array is returned.
sym : bool, optional
Whether the window is symmetric. (Has no effect for boxcar.)
Returns
-------
w : ndarray
The window, with the maximum value normalized to 1.
Examples
--------
Plot the window and its frequency response:
>>> from scipy import signal
>>> from scipy.fft import fft, fftshift
>>> import matplotlib.pyplot as plt
>>> window = signal.windows.boxcar(51)
>>> plt.plot(window)
>>> plt.title("Boxcar window")
>>> plt.ylabel("Amplitude")
>>> plt.xlabel("Sample")
>>> plt.figure()
>>> A = fft(window, 2048) / (len(window)/2.0)
>>> freq = np.linspace(-0.5, 0.5, len(A))
>>> response = 20 * np.log10(np.abs(fftshift(A / abs(A).max())))
>>> plt.plot(freq, response)
>>> plt.axis([-0.5, 0.5, -120, 0])
>>> plt.title("Frequency response of the boxcar window")
>>> plt.ylabel("Normalized magnitude [dB]")
>>> plt.xlabel("Normalized frequency [cycles per sample]")
"""
if _len_guards(M):
return np.ones(M)
M, needs_trunc = _extend(M, sym)
w = np.ones(M, float)
return _truncate(w, needs_trunc)
def triang(M, sym=True):
"""Return a triangular window.
Parameters
----------
M : int
Number of points in the output window. If zero or less, an empty
array is returned.
sym : bool, optional
When True (default), generates a symmetric window, for use in filter
design.
When False, generates a periodic window, for use in spectral analysis.
Returns
-------
w : ndarray
The window, with the maximum value normalized to 1 (though the value 1
does not appear if `M` is even and `sym` is True).
See Also
--------
bartlett : A triangular window that touches zero
Examples
--------
Plot the window and its frequency response:
>>> from scipy import signal
>>> from scipy.fft import fft, fftshift
>>> import matplotlib.pyplot as plt
>>> window = signal.windows.triang(51)
>>> plt.plot(window)
>>> plt.title("Triangular window")
>>> plt.ylabel("Amplitude")
>>> plt.xlabel("Sample")
>>> plt.figure()
>>> A = fft(window, 2048) / (len(window)/2.0)
>>> freq = np.linspace(-0.5, 0.5, len(A))
>>> response = np.abs(fftshift(A / abs(A).max()))
>>> response = 20 * np.log10(np.maximum(response, 1e-10))
>>> plt.plot(freq, response)
>>> plt.axis([-0.5, 0.5, -120, 0])
>>> plt.title("Frequency response of the triangular window")
>>> plt.ylabel("Normalized magnitude [dB]")
>>> plt.xlabel("Normalized frequency [cycles per sample]")
"""
if _len_guards(M):
return np.ones(M)
M, needs_trunc = _extend(M, sym)
n = np.arange(1, (M + 1) // 2 + 1)
if M % 2 == 0:
w = (2 * n - 1.0) / M
w = np.r_[w, w[::-1]]
else:
w = 2 * n / (M + 1.0)
w = np.r_[w, w[-2::-1]]
return _truncate(w, needs_trunc)
def parzen(M, sym=True):
"""Return a Parzen window.
Parameters
----------
M : int
Number of points in the output window. If zero or less, an empty
array is returned.
sym : bool, optional
When True (default), generates a symmetric window, for use in filter
design.
When False, generates a periodic window, for use in spectral analysis.
Returns
-------
w : ndarray
The window, with the maximum value normalized to 1 (though the value 1
does not appear if `M` is even and `sym` is True).
References
----------
.. [1] E. Parzen, "Mathematical Considerations in the Estimation of
Spectra", Technometrics, Vol. 3, No. 2 (May, 1961), pp. 167-190
Examples
--------
Plot the window and its frequency response:
>>> from scipy import signal
>>> from scipy.fft import fft, fftshift
>>> import matplotlib.pyplot as plt
>>> window = signal.windows.parzen(51)
>>> plt.plot(window)
>>> plt.title("Parzen window")
>>> plt.ylabel("Amplitude")
>>> plt.xlabel("Sample")
>>> plt.figure()
>>> A = fft(window, 2048) / (len(window)/2.0)
>>> freq = np.linspace(-0.5, 0.5, len(A))
>>> response = 20 * np.log10(np.abs(fftshift(A / abs(A).max())))
>>> plt.plot(freq, response)
>>> plt.axis([-0.5, 0.5, -120, 0])
>>> plt.title("Frequency response of the Parzen window")
>>> plt.ylabel("Normalized magnitude [dB]")
>>> plt.xlabel("Normalized frequency [cycles per sample]")
"""
if _len_guards(M):
return np.ones(M)
M, needs_trunc = _extend(M, sym)
n = np.arange(-(M - 1) / 2.0, (M - 1) / 2.0 + 0.5, 1.0)
na = np.extract(n < -(M - 1) / 4.0, n)
nb = np.extract(abs(n) <= (M - 1) / 4.0, n)
wa = 2 * (1 - np.abs(na) / (M / 2.0)) ** 3.0
wb = (1 - 6 * (np.abs(nb) / (M / 2.0)) ** 2.0 +
6 * (np.abs(nb) / (M / 2.0)) ** 3.0)
w = np.r_[wa, wb, wa[::-1]]
return _truncate(w, needs_trunc)
def bohman(M, sym=True):
"""Return a Bohman window.
Parameters
----------
M : int
Number of points in the output window. If zero or less, an empty
array is returned.
sym : bool, optional
When True (default), generates a symmetric window, for use in filter
design.
When False, generates a periodic window, for use in spectral analysis.
Returns
-------
w : ndarray
The window, with the maximum value normalized to 1 (though the value 1
does not appear if `M` is even and `sym` is True).
Examples
--------
Plot the window and its frequency response:
>>> from scipy import signal
>>> from scipy.fft import fft, fftshift
>>> import matplotlib.pyplot as plt
>>> window = signal.windows.bohman(51)
>>> plt.plot(window)
>>> plt.title("Bohman window")
>>> plt.ylabel("Amplitude")
>>> plt.xlabel("Sample")
>>> plt.figure()
>>> A = fft(window, 2048) / (len(window)/2.0)
>>> freq = np.linspace(-0.5, 0.5, len(A))
>>> np.seterr(divide='ignore')
>>> response = 20 * np.log10(np.abs(fftshift(A / abs(A).max())))
>>> plt.plot(freq, response)
>>> plt.axis([-0.5, 0.5, -120, 0])
>>> plt.title("Frequency response of the Bohman window")
>>> plt.ylabel("Normalized magnitude [dB]")
>>> plt.xlabel("Normalized frequency [cycles per sample]")
"""
if _len_guards(M):
return np.ones(M)
M, needs_trunc = _extend(M, sym)
fac = np.abs(np.linspace(-1, 1, M)[1:-1])
w = (1 - fac) * np.cos(np.pi * fac) + 1.0 / np.pi * np.sin(np.pi * fac)
w = np.r_[0, w, 0]
return _truncate(w, needs_trunc)
def blackman(M, sym=True):
r"""
Return a Blackman window.
The Blackman window is a taper formed by using the first three terms of
a summation of cosines. It was designed to have close to the minimal
leakage possible. It is close to optimal, only slightly worse than a
Kaiser window.
Parameters
----------
M : int
Number of points in the output window. If zero or less, an empty
array is returned.
sym : bool, optional
When True (default), generates a symmetric window, for use in filter
design.
When False, generates a periodic window, for use in spectral analysis.
Returns
-------
w : ndarray
The window, with the maximum value normalized to 1 (though the value 1
does not appear if `M` is even and `sym` is True).
Notes
-----
The Blackman window is defined as
.. math:: w(n) = 0.42 - 0.5 \cos(2\pi n/M) + 0.08 \cos(4\pi n/M)
The "exact Blackman" window was designed to null out the third and fourth
sidelobes, but has discontinuities at the boundaries, resulting in a
6 dB/oct fall-off. This window is an approximation of the "exact" window,
which does not null the sidelobes as well, but is smooth at the edges,
improving the fall-off rate to 18 dB/oct. [3]_
Most references to the Blackman window come from the signal processing
literature, where it is used as one of many windowing functions for
smoothing values. It is also known as an apodization (which means
"removing the foot", i.e. smoothing discontinuities at the beginning
and end of the sampled signal) or tapering function. It is known as a
"near optimal" tapering function, almost as good (by some measures)
as the Kaiser window.
References
----------
.. [1] Blackman, R.B. and Tukey, J.W., (1958) The measurement of power
spectra, Dover Publications, New York.
.. [2] Oppenheim, A.V., and R.W. Schafer. Discrete-Time Signal Processing.
Upper Saddle River, NJ: Prentice-Hall, 1999, pp. 468-471.
.. [3] Harris, Fredric J. (Jan 1978). "On the use of Windows for Harmonic
Analysis with the Discrete Fourier Transform". Proceedings of the
IEEE 66 (1): 51-83. :doi:`10.1109/PROC.1978.10837`.
Examples
--------
Plot the window and its frequency response:
>>> from scipy import signal
>>> from scipy.fft import fft, fftshift
>>> import matplotlib.pyplot as plt
>>> window = signal.windows.blackman(51)
>>> plt.plot(window)
>>> plt.title("Blackman window")
>>> plt.ylabel("Amplitude")
>>> plt.xlabel("Sample")
>>> plt.figure()
>>> A = fft(window, 2048) / (len(window)/2.0)
>>> freq = np.linspace(-0.5, 0.5, len(A))
>>> response = np.abs(fftshift(A / abs(A).max()))
>>> response = 20 * np.log10(np.maximum(response, 1e-10))
>>> plt.plot(freq, response)
>>> plt.axis([-0.5, 0.5, -120, 0])
>>> plt.title("Frequency response of the Blackman window")
>>> plt.ylabel("Normalized magnitude [dB]")
>>> plt.xlabel("Normalized frequency [cycles per sample]")
"""
# Docstring adapted from NumPy's blackman function
return general_cosine(M, [0.42, 0.50, 0.08], sym)
def nuttall(M, sym=True):
"""Return a minimum 4-term Blackman-Harris window according to Nuttall.
This variation is called "Nuttall4c" by Heinzel. [2]_
Parameters
----------
M : int
Number of points in the output window. If zero or less, an empty
array is returned.
sym : bool, optional
When True (default), generates a symmetric window, for use in filter
design.
When False, generates a periodic window, for use in spectral analysis.
Returns
-------
w : ndarray
The window, with the maximum value normalized to 1 (though the value 1
does not appear if `M` is even and `sym` is True).
References
----------
.. [1] A. Nuttall, "Some windows with very good sidelobe behavior," IEEE
Transactions on Acoustics, Speech, and Signal Processing, vol. 29,
no. 1, pp. 84-91, Feb 1981. :doi:`10.1109/TASSP.1981.1163506`.
.. [2] Heinzel G. et al., "Spectrum and spectral density estimation by the
Discrete Fourier transform (DFT), including a comprehensive list of
window functions and some new flat-top windows", February 15, 2002
https://holometer.fnal.gov/GH_FFT.pdf
Examples
--------
Plot the window and its frequency response:
>>> from scipy import signal
>>> from scipy.fft import fft, fftshift
>>> import matplotlib.pyplot as plt
>>> window = signal.windows.nuttall(51)
>>> plt.plot(window)
>>> plt.title("Nuttall window")
>>> plt.ylabel("Amplitude")
>>> plt.xlabel("Sample")
>>> plt.figure()
>>> A = fft(window, 2048) / (len(window)/2.0)
>>> freq = np.linspace(-0.5, 0.5, len(A))
>>> response = 20 * np.log10(np.abs(fftshift(A / abs(A).max())))
>>> plt.plot(freq, response)
>>> plt.axis([-0.5, 0.5, -120, 0])
>>> plt.title("Frequency response of the Nuttall window")
>>> plt.ylabel("Normalized magnitude [dB]")
>>> plt.xlabel("Normalized frequency [cycles per sample]")
"""
return general_cosine(M, [0.3635819, 0.4891775, 0.1365995, 0.0106411], sym)
def blackmanharris(M, sym=True):
"""Return a minimum 4-term Blackman-Harris window.
Parameters
----------
M : int
Number of points in the output window. If zero or less, an empty
array is returned.
sym : bool, optional
When True (default), generates a symmetric window, for use in filter
design.
When False, generates a periodic window, for use in spectral analysis.
Returns
-------
w : ndarray
The window, with the maximum value normalized to 1 (though the value 1
does not appear if `M` is even and `sym` is True).
Examples
--------
Plot the window and its frequency response:
>>> from scipy import signal
>>> from scipy.fft import fft, fftshift
>>> import matplotlib.pyplot as plt
>>> window = signal.windows.blackmanharris(51)
>>> plt.plot(window)
>>> plt.title("Blackman-Harris window")
>>> plt.ylabel("Amplitude")
>>> plt.xlabel("Sample")
>>> plt.figure()
>>> A = fft(window, 2048) / (len(window)/2.0)
>>> freq = np.linspace(-0.5, 0.5, len(A))
>>> response = 20 * np.log10(np.abs(fftshift(A / abs(A).max())))
>>> plt.plot(freq, response)
>>> plt.axis([-0.5, 0.5, -120, 0])
>>> plt.title("Frequency response of the Blackman-Harris window")
>>> plt.ylabel("Normalized magnitude [dB]")
>>> plt.xlabel("Normalized frequency [cycles per sample]")
"""
return general_cosine(M, [0.35875, 0.48829, 0.14128, 0.01168], sym)
def flattop(M, sym=True):
"""Return a flat top window.
Parameters
----------
M : int
Number of points in the output window. If zero or less, an empty
array is returned.
sym : bool, optional
When True (default), generates a symmetric window, for use in filter
design.
When False, generates a periodic window, for use in spectral analysis.
Returns
-------
w : ndarray
The window, with the maximum value normalized to 1 (though the value 1
does not appear if `M` is even and `sym` is True).
Notes
-----
Flat top windows are used for taking accurate measurements of signal
amplitude in the frequency domain, with minimal scalloping error from the
center of a frequency bin to its edges, compared to others. This is a
5th-order cosine window, with the 5 terms optimized to make the main lobe
maximally flat. [1]_
References
----------
.. [1] D'Antona, Gabriele, and A. Ferrero, "Digital Signal Processing for
Measurement Systems", Springer Media, 2006, p. 70
:doi:`10.1007/0-387-28666-7`.
Examples
--------
Plot the window and its frequency response:
>>> from scipy import signal
>>> from scipy.fft import fft, fftshift
>>> import matplotlib.pyplot as plt
>>> window = signal.windows.flattop(51)
>>> plt.plot(window)
>>> plt.title("Flat top window")
>>> plt.ylabel("Amplitude")
>>> plt.xlabel("Sample")
>>> plt.figure()
>>> A = fft(window, 2048) / (len(window)/2.0)
>>> freq = np.linspace(-0.5, 0.5, len(A))
>>> response = 20 * np.log10(np.abs(fftshift(A / abs(A).max())))
>>> plt.plot(freq, response)
>>> plt.axis([-0.5, 0.5, -120, 0])
>>> plt.title("Frequency response of the flat top window")
>>> plt.ylabel("Normalized magnitude [dB]")
>>> plt.xlabel("Normalized frequency [cycles per sample]")
"""
a = [0.21557895, 0.41663158, 0.277263158, 0.083578947, 0.006947368]
return general_cosine(M, a, sym)
def bartlett(M, sym=True):
r"""
Return a Bartlett window.
The Bartlett window is very similar to a triangular window, except
that the end points are at zero. It is often used in signal
processing for tapering a signal, without generating too much
ripple in the frequency domain.
Parameters
----------
M : int
Number of points in the output window. If zero or less, an empty
array is returned.
sym : bool, optional
When True (default), generates a symmetric window, for use in filter
design.
When False, generates a periodic window, for use in spectral analysis.
Returns
-------
w : ndarray
The triangular window, with the first and last samples equal to zero
and the maximum value normalized to 1 (though the value 1 does not
appear if `M` is even and `sym` is True).
See Also
--------
triang : A triangular window that does not touch zero at the ends
Notes
-----
The Bartlett window is defined as
.. math:: w(n) = \frac{2}{M-1} \left(
\frac{M-1}{2} - \left|n - \frac{M-1}{2}\right|
\right)
Most references to the Bartlett window come from the signal
processing literature, where it is used as one of many windowing
functions for smoothing values. Note that convolution with this
window produces linear interpolation. It is also known as an
apodization (which means"removing the foot", i.e. smoothing
discontinuities at the beginning and end of the sampled signal) or
tapering function. The Fourier transform of the Bartlett is the product
of two sinc functions.
Note the excellent discussion in Kanasewich. [2]_
References
----------
.. [1] M.S. Bartlett, "Periodogram Analysis and Continuous Spectra",
Biometrika 37, 1-16, 1950.
.. [2] E.R. Kanasewich, "Time Sequence Analysis in Geophysics",
The University of Alberta Press, 1975, pp. 109-110.
.. [3] A.V. Oppenheim and R.W. Schafer, "Discrete-Time Signal
Processing", Prentice-Hall, 1999, pp. 468-471.
.. [4] Wikipedia, "Window function",
https://en.wikipedia.org/wiki/Window_function
.. [5] W.H. Press, B.P. Flannery, S.A. Teukolsky, and W.T. Vetterling,
"Numerical Recipes", Cambridge University Press, 1986, page 429.
Examples
--------
Plot the window and its frequency response:
>>> from scipy import signal
>>> from scipy.fft import fft, fftshift
>>> import matplotlib.pyplot as plt
>>> window = signal.windows.bartlett(51)
>>> plt.plot(window)
>>> plt.title("Bartlett window")
>>> plt.ylabel("Amplitude")
>>> plt.xlabel("Sample")
>>> plt.figure()
>>> A = fft(window, 2048) / (len(window)/2.0)
>>> freq = np.linspace(-0.5, 0.5, len(A))
>>> response = 20 * np.log10(np.abs(fftshift(A / abs(A).max())))
>>> plt.plot(freq, response)
>>> plt.axis([-0.5, 0.5, -120, 0])
>>> plt.title("Frequency response of the Bartlett window")
>>> plt.ylabel("Normalized magnitude [dB]")
>>> plt.xlabel("Normalized frequency [cycles per sample]")
"""
# Docstring adapted from NumPy's bartlett function
if _len_guards(M):
return np.ones(M)
M, needs_trunc = _extend(M, sym)
n = np.arange(0, M)
w = np.where(np.less_equal(n, (M - 1) / 2.0),
2.0 * n / (M - 1), 2.0 - 2.0 * n / (M - 1))
return _truncate(w, needs_trunc)
def hann(M, sym=True):
r"""
Return a Hann window.
The Hann window is a taper formed by using a raised cosine or sine-squared
with ends that touch zero.
Parameters
----------
M : int
Number of points in the output window. If zero or less, an empty
array is returned.
sym : bool, optional
When True (default), generates a symmetric window, for use in filter
design.
When False, generates a periodic window, for use in spectral analysis.
Returns
-------
w : ndarray
The window, with the maximum value normalized to 1 (though the value 1
does not appear if `M` is even and `sym` is True).
Notes
-----
The Hann window is defined as
.. math:: w(n) = 0.5 - 0.5 \cos\left(\frac{2\pi{n}}{M-1}\right)
\qquad 0 \leq n \leq M-1
The window was named for Julius von Hann, an Austrian meteorologist. It is
also known as the Cosine Bell. It is sometimes erroneously referred to as
the "Hanning" window, from the use of "hann" as a verb in the original
paper and confusion with the very similar Hamming window.
Most references to the Hann window come from the signal processing
literature, where it is used as one of many windowing functions for
smoothing values. It is also known as an apodization (which means
"removing the foot", i.e. smoothing discontinuities at the beginning
and end of the sampled signal) or tapering function.
References
----------
.. [1] Blackman, R.B. and Tukey, J.W., (1958) The measurement of power
spectra, Dover Publications, New York.
.. [2] E.R. Kanasewich, "Time Sequence Analysis in Geophysics",
The University of Alberta Press, 1975, pp. 106-108.
.. [3] Wikipedia, "Window function",
https://en.wikipedia.org/wiki/Window_function
.. [4] W.H. Press, B.P. Flannery, S.A. Teukolsky, and W.T. Vetterling,
"Numerical Recipes", Cambridge University Press, 1986, page 425.
Examples
--------
Plot the window and its frequency response:
>>> from scipy import signal
>>> from scipy.fft import fft, fftshift
>>> import matplotlib.pyplot as plt
>>> window = signal.windows.hann(51)
>>> plt.plot(window)
>>> plt.title("Hann window")
>>> plt.ylabel("Amplitude")
>>> plt.xlabel("Sample")
>>> plt.figure()
>>> A = fft(window, 2048) / (len(window)/2.0)
>>> freq = np.linspace(-0.5, 0.5, len(A))
>>> response = np.abs(fftshift(A / abs(A).max()))
>>> response = 20 * np.log10(np.maximum(response, 1e-10))
>>> plt.plot(freq, response)
>>> plt.axis([-0.5, 0.5, -120, 0])
>>> plt.title("Frequency response of the Hann window")
>>> plt.ylabel("Normalized magnitude [dB]")
>>> plt.xlabel("Normalized frequency [cycles per sample]")
"""
# Docstring adapted from NumPy's hanning function
return general_hamming(M, 0.5, sym)
@np.deprecate(new_name='scipy.signal.windows.hann')
def hanning(*args, **kwargs):
return hann(*args, **kwargs)
def tukey(M, alpha=0.5, sym=True):
r"""Return a Tukey window, also known as a tapered cosine window.
Parameters
----------
M : int
Number of points in the output window. If zero or less, an empty
array is returned.
alpha : float, optional
Shape parameter of the Tukey window, representing the fraction of the
window inside the cosine tapered region.
If zero, the Tukey window is equivalent to a rectangular window.
If one, the Tukey window is equivalent to a Hann window.
sym : bool, optional
When True (default), generates a symmetric window, for use in filter
design.
When False, generates a periodic window, for use in spectral analysis.
Returns
-------
w : ndarray
The window, with the maximum value normalized to 1 (though the value 1
does not appear if `M` is even and `sym` is True).
References
----------
.. [1] Harris, Fredric J. (Jan 1978). "On the use of Windows for Harmonic
Analysis with the Discrete Fourier Transform". Proceedings of the
IEEE 66 (1): 51-83. :doi:`10.1109/PROC.1978.10837`
.. [2] Wikipedia, "Window function",
https://en.wikipedia.org/wiki/Window_function#Tukey_window
Examples
--------
Plot the window and its frequency response:
>>> from scipy import signal
>>> from scipy.fft import fft, fftshift
>>> import matplotlib.pyplot as plt
>>> window = signal.windows.tukey(51)
>>> plt.plot(window)
>>> plt.title("Tukey window")
>>> plt.ylabel("Amplitude")
>>> plt.xlabel("Sample")
>>> plt.ylim([0, 1.1])
>>> plt.figure()
>>> A = fft(window, 2048) / (len(window)/2.0)
>>> freq = np.linspace(-0.5, 0.5, len(A))
>>> response = 20 * np.log10(np.abs(fftshift(A / abs(A).max())))
>>> plt.plot(freq, response)
>>> plt.axis([-0.5, 0.5, -120, 0])
>>> plt.title("Frequency response of the Tukey window")
>>> plt.ylabel("Normalized magnitude [dB]")
>>> plt.xlabel("Normalized frequency [cycles per sample]")
"""
if _len_guards(M):
return np.ones(M)
if alpha <= 0:
return np.ones(M, 'd')
elif alpha >= 1.0:
return hann(M, sym=sym)
M, needs_trunc = _extend(M, sym)
n = np.arange(0, M)
width = int(np.floor(alpha*(M-1)/2.0))
n1 = n[0:width+1]
n2 = n[width+1:M-width-1]
n3 = n[M-width-1:]
w1 = 0.5 * (1 + np.cos(np.pi * (-1 + 2.0*n1/alpha/(M-1))))
w2 = np.ones(n2.shape)
w3 = 0.5 * (1 + np.cos(np.pi * (-2.0/alpha + 1 + 2.0*n3/alpha/(M-1))))
w = np.concatenate((w1, w2, w3))
return _truncate(w, needs_trunc)
def barthann(M, sym=True):
"""Return a modified Bartlett-Hann window.
Parameters
----------
M : int
Number of points in the output window. If zero or less, an empty
array is returned.
sym : bool, optional
When True (default), generates a symmetric window, for use in filter
design.
When False, generates a periodic window, for use in spectral analysis.
Returns
-------
w : ndarray
The window, with the maximum value normalized to 1 (though the value 1
does not appear if `M` is even and `sym` is True).
Examples
--------
Plot the window and its frequency response:
>>> from scipy import signal
>>> from scipy.fft import fft, fftshift
>>> import matplotlib.pyplot as plt
>>> window = signal.windows.barthann(51)
>>> plt.plot(window)
>>> plt.title("Bartlett-Hann window")
>>> plt.ylabel("Amplitude")
>>> plt.xlabel("Sample")
>>> plt.figure()
>>> A = fft(window, 2048) / (len(window)/2.0)
>>> freq = np.linspace(-0.5, 0.5, len(A))
>>> response = 20 * np.log10(np.abs(fftshift(A / abs(A).max())))
>>> plt.plot(freq, response)
>>> plt.axis([-0.5, 0.5, -120, 0])
>>> plt.title("Frequency response of the Bartlett-Hann window")
>>> plt.ylabel("Normalized magnitude [dB]")
>>> plt.xlabel("Normalized frequency [cycles per sample]")
"""
if _len_guards(M):
return np.ones(M)
M, needs_trunc = _extend(M, sym)
n = np.arange(0, M)
fac = np.abs(n / (M - 1.0) - 0.5)
w = 0.62 - 0.48 * fac + 0.38 * np.cos(2 * np.pi * fac)
return _truncate(w, needs_trunc)
def general_hamming(M, alpha, sym=True):
r"""Return a generalized Hamming window.
The generalized Hamming window is constructed by multiplying a rectangular
window by one period of a cosine function [1]_.
Parameters
----------
M : int
Number of points in the output window. If zero or less, an empty
array is returned.
alpha : float
The window coefficient, :math:`\alpha`
sym : bool, optional
When True (default), generates a symmetric window, for use in filter
design.
When False, generates a periodic window, for use in spectral analysis.
Returns
-------
w : ndarray
The window, with the maximum value normalized to 1 (though the value 1
does not appear if `M` is even and `sym` is True).
Notes
-----
The generalized Hamming window is defined as
.. math:: w(n) = \alpha - \left(1 - \alpha\right) \cos\left(\frac{2\pi{n}}{M-1}\right)
\qquad 0 \leq n \leq M-1
Both the common Hamming window and Hann window are special cases of the
generalized Hamming window with :math:`\alpha` = 0.54 and :math:`\alpha` =
0.5, respectively [2]_.
See Also
--------
hamming, hann
Examples
--------
The Sentinel-1A/B Instrument Processing Facility uses generalized Hamming
windows in the processing of spaceborne Synthetic Aperture Radar (SAR)
data [3]_. The facility uses various values for the :math:`\alpha`
parameter based on operating mode of the SAR instrument. Some common
:math:`\alpha` values include 0.75, 0.7 and 0.52 [4]_. As an example, we
plot these different windows.
>>> from scipy.signal.windows import general_hamming
>>> from scipy.fft import fft, fftshift
>>> import matplotlib.pyplot as plt
>>> fig1, spatial_plot = plt.subplots()
>>> spatial_plot.set_title("Generalized Hamming Windows")
>>> spatial_plot.set_ylabel("Amplitude")
>>> spatial_plot.set_xlabel("Sample")
>>> fig2, freq_plot = plt.subplots()
>>> freq_plot.set_title("Frequency Responses")
>>> freq_plot.set_ylabel("Normalized magnitude [dB]")
>>> freq_plot.set_xlabel("Normalized frequency [cycles per sample]")
>>> for alpha in [0.75, 0.7, 0.52]:
... window = general_hamming(41, alpha)
... spatial_plot.plot(window, label="{:.2f}".format(alpha))
... A = fft(window, 2048) / (len(window)/2.0)
... freq = np.linspace(-0.5, 0.5, len(A))
... response = 20 * np.log10(np.abs(fftshift(A / abs(A).max())))
... freq_plot.plot(freq, response, label="{:.2f}".format(alpha))
>>> freq_plot.legend(loc="upper right")
>>> spatial_plot.legend(loc="upper right")
References
----------
.. [1] DSPRelated, "Generalized Hamming Window Family",
https://www.dsprelated.com/freebooks/sasp/Generalized_Hamming_Window_Family.html
.. [2] Wikipedia, "Window function",
https://en.wikipedia.org/wiki/Window_function
.. [3] Riccardo Piantanida ESA, "Sentinel-1 Level 1 Detailed Algorithm
Definition",
https://sentinel.esa.int/documents/247904/1877131/Sentinel-1-Level-1-Detailed-Algorithm-Definition
.. [4] Matthieu Bourbigot ESA, "Sentinel-1 Product Definition",
https://sentinel.esa.int/documents/247904/1877131/Sentinel-1-Product-Definition
"""
return general_cosine(M, [alpha, 1. - alpha], sym)
def hamming(M, sym=True):
r"""Return a Hamming window.
The Hamming window is a taper formed by using a raised cosine with
non-zero endpoints, optimized to minimize the nearest side lobe.
Parameters
----------
M : int
Number of points in the output window. If zero or less, an empty
array is returned.
sym : bool, optional
When True (default), generates a symmetric window, for use in filter
design.
When False, generates a periodic window, for use in spectral analysis.
Returns
-------
w : ndarray
The window, with the maximum value normalized to 1 (though the value 1
does not appear if `M` is even and `sym` is True).
Notes
-----
The Hamming window is defined as
.. math:: w(n) = 0.54 - 0.46 \cos\left(\frac{2\pi{n}}{M-1}\right)
\qquad 0 \leq n \leq M-1
The Hamming was named for R. W. Hamming, an associate of J. W. Tukey and
is described in Blackman and Tukey. It was recommended for smoothing the
truncated autocovariance function in the time domain.
Most references to the Hamming window come from the signal processing
literature, where it is used as one of many windowing functions for
smoothing values. It is also known as an apodization (which means
"removing the foot", i.e. smoothing discontinuities at the beginning
and end of the sampled signal) or tapering function.
References
----------
.. [1] Blackman, R.B. and Tukey, J.W., (1958) The measurement of power
spectra, Dover Publications, New York.
.. [2] E.R. Kanasewich, "Time Sequence Analysis in Geophysics", The
University of Alberta Press, 1975, pp. 109-110.
.. [3] Wikipedia, "Window function",
https://en.wikipedia.org/wiki/Window_function
.. [4] W.H. Press, B.P. Flannery, S.A. Teukolsky, and W.T. Vetterling,
"Numerical Recipes", Cambridge University Press, 1986, page 425.
Examples
--------
Plot the window and its frequency response:
>>> from scipy import signal
>>> from scipy.fft import fft, fftshift
>>> import matplotlib.pyplot as plt
>>> window = signal.windows.hamming(51)
>>> plt.plot(window)
>>> plt.title("Hamming window")
>>> plt.ylabel("Amplitude")
>>> plt.xlabel("Sample")
>>> plt.figure()
>>> A = fft(window, 2048) / (len(window)/2.0)
>>> freq = np.linspace(-0.5, 0.5, len(A))
>>> response = 20 * np.log10(np.abs(fftshift(A / abs(A).max())))
>>> plt.plot(freq, response)
>>> plt.axis([-0.5, 0.5, -120, 0])
>>> plt.title("Frequency response of the Hamming window")
>>> plt.ylabel("Normalized magnitude [dB]")
>>> plt.xlabel("Normalized frequency [cycles per sample]")
"""
# Docstring adapted from NumPy's hamming function
return general_hamming(M, 0.54, sym)
def kaiser(M, beta, sym=True):
r"""Return a Kaiser window.
The Kaiser window is a taper formed by using a Bessel function.
Parameters
----------
M : int
Number of points in the output window. If zero or less, an empty
array is returned.
beta : float
Shape parameter, determines trade-off between main-lobe width and
side lobe level. As beta gets large, the window narrows.
sym : bool, optional
When True (default), generates a symmetric window, for use in filter
design.
When False, generates a periodic window, for use in spectral analysis.
Returns
-------
w : ndarray
The window, with the maximum value normalized to 1 (though the value 1
does not appear if `M` is even and `sym` is True).
Notes
-----
The Kaiser window is defined as
.. math:: w(n) = I_0\left( \beta \sqrt{1-\frac{4n^2}{(M-1)^2}}
\right)/I_0(\beta)
with
.. math:: \quad -\frac{M-1}{2} \leq n \leq \frac{M-1}{2},
where :math:`I_0` is the modified zeroth-order Bessel function.
The Kaiser was named for Jim Kaiser, who discovered a simple approximation
to the DPSS window based on Bessel functions.
The Kaiser window is a very good approximation to the Digital Prolate
Spheroidal Sequence, or Slepian window, which is the transform which
maximizes the energy in the main lobe of the window relative to total
energy.
The Kaiser can approximate other windows by varying the beta parameter.
(Some literature uses alpha = beta/pi.) [4]_
==== =======================
beta Window shape
==== =======================
0 Rectangular
5 Similar to a Hamming
6 Similar to a Hann
8.6 Similar to a Blackman
==== =======================
A beta value of 14 is probably a good starting point. Note that as beta
gets large, the window narrows, and so the number of samples needs to be
large enough to sample the increasingly narrow spike, otherwise NaNs will
be returned.
Most references to the Kaiser window come from the signal processing
literature, where it is used as one of many windowing functions for
smoothing values. It is also known as an apodization (which means
"removing the foot", i.e. smoothing discontinuities at the beginning
and end of the sampled signal) or tapering function.
References
----------
.. [1] J. F. Kaiser, "Digital Filters" - Ch 7 in "Systems analysis by
digital computer", Editors: F.F. Kuo and J.F. Kaiser, p 218-285.
John Wiley and Sons, New York, (1966).
.. [2] E.R. Kanasewich, "Time Sequence Analysis in Geophysics", The
University of Alberta Press, 1975, pp. 177-178.
.. [3] Wikipedia, "Window function",
https://en.wikipedia.org/wiki/Window_function
.. [4] F. J. Harris, "On the use of windows for harmonic analysis with the
discrete Fourier transform," Proceedings of the IEEE, vol. 66,
no. 1, pp. 51-83, Jan. 1978. :doi:`10.1109/PROC.1978.10837`.
Examples
--------
Plot the window and its frequency response:
>>> from scipy import signal
>>> from scipy.fft import fft, fftshift
>>> import matplotlib.pyplot as plt
>>> window = signal.windows.kaiser(51, beta=14)
>>> plt.plot(window)
>>> plt.title(r"Kaiser window ($\beta$=14)")
>>> plt.ylabel("Amplitude")
>>> plt.xlabel("Sample")
>>> plt.figure()
>>> A = fft(window, 2048) / (len(window)/2.0)
>>> freq = np.linspace(-0.5, 0.5, len(A))
>>> response = 20 * np.log10(np.abs(fftshift(A / abs(A).max())))
>>> plt.plot(freq, response)
>>> plt.axis([-0.5, 0.5, -120, 0])
>>> plt.title(r"Frequency response of the Kaiser window ($\beta$=14)")
>>> plt.ylabel("Normalized magnitude [dB]")
>>> plt.xlabel("Normalized frequency [cycles per sample]")
"""
# Docstring adapted from NumPy's kaiser function
if _len_guards(M):
return np.ones(M)
M, needs_trunc = _extend(M, sym)
n = np.arange(0, M)
alpha = (M - 1) / 2.0
w = (special.i0(beta * np.sqrt(1 - ((n - alpha) / alpha) ** 2.0)) /
special.i0(beta))
return _truncate(w, needs_trunc)
def kaiser_bessel_derived(M, beta, *, sym=True):
"""Return a Kaiser-Bessel derived window.
Parameters
----------
M : int
Number of points in the output window. If zero or less, an empty
array is returned. Note that this window is only defined for an even
number of points.
beta : float
Kaiser window shape parameter.
sym : bool, optional
This parameter only exists to comply with the interface offered by
the other window functions and to be callable by `get_window`.
When True (default), generates a symmetric window, for use in filter
design.
Returns
-------
w : ndarray
The window, normalized to fulfil the Princen-Bradley condition.
See Also
--------
kaiser
Notes
-----
It is designed to be suitable for use with the modified discrete cosine
transform (MDCT) and is mainly used in audio signal processing and
audio coding.
.. versionadded:: 1.9.0
References
----------
.. [1] Bosi, Marina, and Richard E. Goldberg. Introduction to Digital
Audio Coding and Standards. Dordrecht: Kluwer, 2003.
.. [2] Wikipedia, "Kaiser window",
https://en.wikipedia.org/wiki/Kaiser_window
Examples
--------
Plot the Kaiser-Bessel derived window based on the wikipedia
reference [2]_:
>>> from scipy import signal
>>> import matplotlib.pyplot as plt
>>> fig, ax = plt.subplots()
>>> N = 50
>>> for alpha in [0.64, 2.55, 7.64, 31.83]:
... ax.plot(signal.windows.kaiser_bessel_derived(2*N, np.pi*alpha),
... label=f"{alpha=}")
>>> ax.grid(True)
>>> ax.set_title("Kaiser-Bessel derived window")
>>> ax.set_ylabel("Amplitude")
>>> ax.set_xlabel("Sample")
>>> ax.set_xticks([0, N, 2*N-1])
>>> ax.set_xticklabels(["0", "N", "2N+1"]) # doctest: +SKIP
>>> ax.set_yticks([0.0, 0.2, 0.4, 0.6, 0.707, 0.8, 1.0])
>>> fig.legend(loc="center")
>>> fig.tight_layout()
>>> fig.show()
"""
if not sym:
raise ValueError(
"Kaiser-Bessel Derived windows are only defined for symmetric "
"shapes"
)
elif M < 1:
return np.array([])
elif M % 2:
raise ValueError(
"Kaiser-Bessel Derived windows are only defined for even number "
"of points"
)
kaiser_window = kaiser(M // 2 + 1, beta)
csum = np.cumsum(kaiser_window)
half_window = np.sqrt(csum[:-1] / csum[-1])
w = np.concatenate((half_window, half_window[::-1]), axis=0)
return w
def gaussian(M, std, sym=True):
r"""Return a Gaussian window.
Parameters
----------
M : int
Number of points in the output window. If zero or less, an empty
array is returned.
std : float
The standard deviation, sigma.
sym : bool, optional
When True (default), generates a symmetric window, for use in filter
design.
When False, generates a periodic window, for use in spectral analysis.
Returns
-------
w : ndarray
The window, with the maximum value normalized to 1 (though the value 1
does not appear if `M` is even and `sym` is True).
Notes
-----
The Gaussian window is defined as
.. math:: w(n) = e^{ -\frac{1}{2}\left(\frac{n}{\sigma}\right)^2 }
Examples
--------
Plot the window and its frequency response:
>>> from scipy import signal
>>> from scipy.fft import fft, fftshift
>>> import matplotlib.pyplot as plt
>>> window = signal.windows.gaussian(51, std=7)
>>> plt.plot(window)
>>> plt.title(r"Gaussian window ($\sigma$=7)")
>>> plt.ylabel("Amplitude")
>>> plt.xlabel("Sample")
>>> plt.figure()
>>> A = fft(window, 2048) / (len(window)/2.0)
>>> freq = np.linspace(-0.5, 0.5, len(A))
>>> response = 20 * np.log10(np.abs(fftshift(A / abs(A).max())))
>>> plt.plot(freq, response)
>>> plt.axis([-0.5, 0.5, -120, 0])
>>> plt.title(r"Frequency response of the Gaussian window ($\sigma$=7)")
>>> plt.ylabel("Normalized magnitude [dB]")
>>> plt.xlabel("Normalized frequency [cycles per sample]")
"""
if _len_guards(M):
return np.ones(M)
M, needs_trunc = _extend(M, sym)
n = np.arange(0, M) - (M - 1.0) / 2.0
sig2 = 2 * std * std
w = np.exp(-n ** 2 / sig2)
return _truncate(w, needs_trunc)
def general_gaussian(M, p, sig, sym=True):
r"""Return a window with a generalized Gaussian shape.
Parameters
----------
M : int
Number of points in the output window. If zero or less, an empty
array is returned.
p : float
Shape parameter. p = 1 is identical to `gaussian`, p = 0.5 is
the same shape as the Laplace distribution.
sig : float
The standard deviation, sigma.
sym : bool, optional
When True (default), generates a symmetric window, for use in filter
design.
When False, generates a periodic window, for use in spectral analysis.
Returns
-------
w : ndarray
The window, with the maximum value normalized to 1 (though the value 1
does not appear if `M` is even and `sym` is True).
Notes
-----
The generalized Gaussian window is defined as
.. math:: w(n) = e^{ -\frac{1}{2}\left|\frac{n}{\sigma}\right|^{2p} }
the half-power point is at
.. math:: (2 \log(2))^{1/(2 p)} \sigma
Examples
--------
Plot the window and its frequency response:
>>> from scipy import signal
>>> from scipy.fft import fft, fftshift
>>> import matplotlib.pyplot as plt
>>> window = signal.windows.general_gaussian(51, p=1.5, sig=7)
>>> plt.plot(window)
>>> plt.title(r"Generalized Gaussian window (p=1.5, $\sigma$=7)")
>>> plt.ylabel("Amplitude")
>>> plt.xlabel("Sample")
>>> plt.figure()
>>> A = fft(window, 2048) / (len(window)/2.0)
>>> freq = np.linspace(-0.5, 0.5, len(A))
>>> response = 20 * np.log10(np.abs(fftshift(A / abs(A).max())))
>>> plt.plot(freq, response)
>>> plt.axis([-0.5, 0.5, -120, 0])
>>> plt.title(r"Freq. resp. of the gen. Gaussian "
... r"window (p=1.5, $\sigma$=7)")
>>> plt.ylabel("Normalized magnitude [dB]")
>>> plt.xlabel("Normalized frequency [cycles per sample]")
"""
if _len_guards(M):
return np.ones(M)
M, needs_trunc = _extend(M, sym)
n = np.arange(0, M) - (M - 1.0) / 2.0
w = np.exp(-0.5 * np.abs(n / sig) ** (2 * p))
return _truncate(w, needs_trunc)
# `chebwin` contributed by Kumar Appaiah.
def chebwin(M, at, sym=True):
r"""Return a Dolph-Chebyshev window.
Parameters
----------
M : int
Number of points in the output window. If zero or less, an empty
array is returned.
at : float
Attenuation (in dB).
sym : bool, optional
When True (default), generates a symmetric window, for use in filter
design.
When False, generates a periodic window, for use in spectral analysis.
Returns
-------
w : ndarray
The window, with the maximum value always normalized to 1
Notes
-----
This window optimizes for the narrowest main lobe width for a given order
`M` and sidelobe equiripple attenuation `at`, using Chebyshev
polynomials. It was originally developed by Dolph to optimize the
directionality of radio antenna arrays.
Unlike most windows, the Dolph-Chebyshev is defined in terms of its
frequency response:
.. math:: W(k) = \frac
{\cos\{M \cos^{-1}[\beta \cos(\frac{\pi k}{M})]\}}
{\cosh[M \cosh^{-1}(\beta)]}
where
.. math:: \beta = \cosh \left [\frac{1}{M}
\cosh^{-1}(10^\frac{A}{20}) \right ]
and 0 <= abs(k) <= M-1. A is the attenuation in decibels (`at`).
The time domain window is then generated using the IFFT, so
power-of-two `M` are the fastest to generate, and prime number `M` are
the slowest.
The equiripple condition in the frequency domain creates impulses in the
time domain, which appear at the ends of the window.
References
----------
.. [1] C. Dolph, "A current distribution for broadside arrays which
optimizes the relationship between beam width and side-lobe level",
Proceedings of the IEEE, Vol. 34, Issue 6
.. [2] Peter Lynch, "The Dolph-Chebyshev Window: A Simple Optimal Filter",
American Meteorological Society (April 1997)
http://mathsci.ucd.ie/~plynch/Publications/Dolph.pdf
.. [3] F. J. Harris, "On the use of windows for harmonic analysis with the
discrete Fourier transforms", Proceedings of the IEEE, Vol. 66,
No. 1, January 1978
Examples
--------
Plot the window and its frequency response:
>>> from scipy import signal
>>> from scipy.fft import fft, fftshift
>>> import matplotlib.pyplot as plt
>>> window = signal.windows.chebwin(51, at=100)
>>> plt.plot(window)
>>> plt.title("Dolph-Chebyshev window (100 dB)")
>>> plt.ylabel("Amplitude")
>>> plt.xlabel("Sample")
>>> plt.figure()
>>> A = fft(window, 2048) / (len(window)/2.0)
>>> freq = np.linspace(-0.5, 0.5, len(A))
>>> response = 20 * np.log10(np.abs(fftshift(A / abs(A).max())))
>>> plt.plot(freq, response)
>>> plt.axis([-0.5, 0.5, -120, 0])
>>> plt.title("Frequency response of the Dolph-Chebyshev window (100 dB)")
>>> plt.ylabel("Normalized magnitude [dB]")
>>> plt.xlabel("Normalized frequency [cycles per sample]")
"""
if np.abs(at) < 45:
warnings.warn("This window is not suitable for spectral analysis "
"for attenuation values lower than about 45dB because "
"the equivalent noise bandwidth of a Chebyshev window "
"does not grow monotonically with increasing sidelobe "
"attenuation when the attenuation is smaller than "
"about 45 dB.")
if _len_guards(M):
return np.ones(M)
M, needs_trunc = _extend(M, sym)
# compute the parameter beta
order = M - 1.0
beta = np.cosh(1.0 / order * np.arccosh(10 ** (np.abs(at) / 20.)))
k = np.r_[0:M] * 1.0
x = beta * np.cos(np.pi * k / M)
# Find the window's DFT coefficients
# Use analytic definition of Chebyshev polynomial instead of expansion
# from scipy.special. Using the expansion in scipy.special leads to errors.
p = np.zeros(x.shape)
p[x > 1] = np.cosh(order * np.arccosh(x[x > 1]))
p[x < -1] = (2 * (M % 2) - 1) * np.cosh(order * np.arccosh(-x[x < -1]))
p[np.abs(x) <= 1] = np.cos(order * np.arccos(x[np.abs(x) <= 1]))
# Appropriate IDFT and filling up
# depending on even/odd M
if M % 2:
w = np.real(sp_fft.fft(p))
n = (M + 1) // 2
w = w[:n]
w = np.concatenate((w[n - 1:0:-1], w))
else:
p = p * np.exp(1.j * np.pi / M * np.r_[0:M])
w = np.real(sp_fft.fft(p))
n = M // 2 + 1
w = np.concatenate((w[n - 1:0:-1], w[1:n]))
w = w / max(w)
return _truncate(w, needs_trunc)
def cosine(M, sym=True):
"""Return a window with a simple cosine shape.
Parameters
----------
M : int
Number of points in the output window. If zero or less, an empty
array is returned.
sym : bool, optional
When True (default), generates a symmetric window, for use in filter
design.
When False, generates a periodic window, for use in spectral analysis.
Returns
-------
w : ndarray
The window, with the maximum value normalized to 1 (though the value 1
does not appear if `M` is even and `sym` is True).
Notes
-----
.. versionadded:: 0.13.0
Examples
--------
Plot the window and its frequency response:
>>> from scipy import signal
>>> from scipy.fft import fft, fftshift
>>> import matplotlib.pyplot as plt
>>> window = signal.windows.cosine(51)
>>> plt.plot(window)
>>> plt.title("Cosine window")
>>> plt.ylabel("Amplitude")
>>> plt.xlabel("Sample")
>>> plt.figure()
>>> A = fft(window, 2048) / (len(window)/2.0)
>>> freq = np.linspace(-0.5, 0.5, len(A))
>>> np.seterr(divide='ignore')
>>> response = 20 * np.log10(np.abs(fftshift(A / abs(A).max())))
>>> plt.plot(freq, response)
>>> plt.axis([-0.5, 0.5, -120, 0])
>>> plt.title("Frequency response of the cosine window")
>>> plt.ylabel("Normalized magnitude [dB]")
>>> plt.xlabel("Normalized frequency [cycles per sample]")
>>> plt.show()
"""
if _len_guards(M):
return np.ones(M)
M, needs_trunc = _extend(M, sym)
w = np.sin(np.pi / M * (np.arange(0, M) + .5))
return _truncate(w, needs_trunc)
def exponential(M, center=None, tau=1., sym=True):
r"""Return an exponential (or Poisson) window.
Parameters
----------
M : int
Number of points in the output window. If zero or less, an empty
array is returned.
center : float, optional
Parameter defining the center location of the window function.
The default value if not given is ``center = (M-1) / 2``. This
parameter must take its default value for symmetric windows.
tau : float, optional
Parameter defining the decay. For ``center = 0`` use
``tau = -(M-1) / ln(x)`` if ``x`` is the fraction of the window
remaining at the end.
sym : bool, optional
When True (default), generates a symmetric window, for use in filter
design.
When False, generates a periodic window, for use in spectral analysis.
Returns
-------
w : ndarray
The window, with the maximum value normalized to 1 (though the value 1
does not appear if `M` is even and `sym` is True).
Notes
-----
The Exponential window is defined as
.. math:: w(n) = e^{-|n-center| / \tau}
References
----------
.. [1] S. Gade and H. Herlufsen, "Windows to FFT analysis (Part I)",
Technical Review 3, Bruel & Kjaer, 1987.
Examples
--------
Plot the symmetric window and its frequency response:
>>> from scipy import signal
>>> from scipy.fft import fft, fftshift
>>> import matplotlib.pyplot as plt
>>> M = 51
>>> tau = 3.0
>>> window = signal.windows.exponential(M, tau=tau)
>>> plt.plot(window)
>>> plt.title("Exponential Window (tau=3.0)")
>>> plt.ylabel("Amplitude")
>>> plt.xlabel("Sample")
>>> plt.figure()
>>> A = fft(window, 2048) / (len(window)/2.0)
>>> freq = np.linspace(-0.5, 0.5, len(A))
>>> response = 20 * np.log10(np.abs(fftshift(A / abs(A).max())))
>>> plt.plot(freq, response)
>>> plt.axis([-0.5, 0.5, -35, 0])
>>> plt.title("Frequency response of the Exponential window (tau=3.0)")
>>> plt.ylabel("Normalized magnitude [dB]")
>>> plt.xlabel("Normalized frequency [cycles per sample]")
This function can also generate non-symmetric windows:
>>> tau2 = -(M-1) / np.log(0.01)
>>> window2 = signal.windows.exponential(M, 0, tau2, False)
>>> plt.figure()
>>> plt.plot(window2)
>>> plt.ylabel("Amplitude")
>>> plt.xlabel("Sample")
"""
if sym and center is not None:
raise ValueError("If sym==True, center must be None.")
if _len_guards(M):
return np.ones(M)
M, needs_trunc = _extend(M, sym)
if center is None:
center = (M-1) / 2
n = np.arange(0, M)
w = np.exp(-np.abs(n-center) / tau)
return _truncate(w, needs_trunc)
def taylor(M, nbar=4, sll=30, norm=True, sym=True):
"""
Return a Taylor window.
The Taylor window taper function approximates the Dolph-Chebyshev window's
constant sidelobe level for a parameterized number of near-in sidelobes,
but then allows a taper beyond [2]_.
The SAR (synthetic aperature radar) community commonly uses Taylor
weighting for image formation processing because it provides strong,
selectable sidelobe suppression with minimum broadening of the
mainlobe [1]_.
Parameters
----------
M : int
Number of points in the output window. If zero or less, an
empty array is returned.
nbar : int, optional
Number of nearly constant level sidelobes adjacent to the mainlobe.
sll : float, optional
Desired suppression of sidelobe level in decibels (dB) relative to the
DC gain of the mainlobe. This should be a positive number.
norm : bool, optional
When True (default), divides the window by the largest (middle) value
for odd-length windows or the value that would occur between the two
repeated middle values for even-length windows such that all values
are less than or equal to 1. When False the DC gain will remain at 1
(0 dB) and the sidelobes will be `sll` dB down.
sym : bool, optional
When True (default), generates a symmetric window, for use in filter
design.
When False, generates a periodic window, for use in spectral analysis.
Returns
-------
out : array
The window. When `norm` is True (default), the maximum value is
normalized to 1 (though the value 1 does not appear if `M` is
even and `sym` is True).
See Also
--------
chebwin, kaiser, bartlett, blackman, hamming, hanning
References
----------
.. [1] W. Carrara, R. Goodman, and R. Majewski, "Spotlight Synthetic
Aperture Radar: Signal Processing Algorithms" Pages 512-513,
July 1995.
.. [2] Armin Doerry, "Catalog of Window Taper Functions for
Sidelobe Control", 2017.
https://www.researchgate.net/profile/Armin_Doerry/publication/316281181_Catalog_of_Window_Taper_Functions_for_Sidelobe_Control/links/58f92cb2a6fdccb121c9d54d/Catalog-of-Window-Taper-Functions-for-Sidelobe-Control.pdf
Examples
--------
Plot the window and its frequency response:
>>> from scipy import signal
>>> from scipy.fft import fft, fftshift
>>> import matplotlib.pyplot as plt
>>> window = signal.windows.taylor(51, nbar=20, sll=100, norm=False)
>>> plt.plot(window)
>>> plt.title("Taylor window (100 dB)")
>>> plt.ylabel("Amplitude")
>>> plt.xlabel("Sample")
>>> plt.figure()
>>> A = fft(window, 2048) / (len(window)/2.0)
>>> freq = np.linspace(-0.5, 0.5, len(A))
>>> response = 20 * np.log10(np.abs(fftshift(A / abs(A).max())))
>>> plt.plot(freq, response)
>>> plt.axis([-0.5, 0.5, -120, 0])
>>> plt.title("Frequency response of the Taylor window (100 dB)")
>>> plt.ylabel("Normalized magnitude [dB]")
>>> plt.xlabel("Normalized frequency [cycles per sample]")
""" # noqa: E501
if _len_guards(M):
return np.ones(M)
M, needs_trunc = _extend(M, sym)
# Original text uses a negative sidelobe level parameter and then negates
# it in the calculation of B. To keep consistent with other methods we
# assume the sidelobe level parameter to be positive.
B = 10**(sll / 20)
A = np.arccosh(B) / np.pi
s2 = nbar**2 / (A**2 + (nbar - 0.5)**2)
ma = np.arange(1, nbar)
Fm = np.empty(nbar-1)
signs = np.empty_like(ma)
signs[::2] = 1
signs[1::2] = -1
m2 = ma*ma
for mi, m in enumerate(ma):
numer = signs[mi] * np.prod(1 - m2[mi]/s2/(A**2 + (ma - 0.5)**2))
denom = 2 * np.prod(1 - m2[mi]/m2[:mi]) * np.prod(1 - m2[mi]/m2[mi+1:])
Fm[mi] = numer / denom
def W(n):
return 1 + 2*np.dot(Fm, np.cos(
2*np.pi*ma[:, np.newaxis]*(n-M/2.+0.5)/M))
w = W(np.arange(M))
# normalize (Note that this is not described in the original text [1])
if norm:
scale = 1.0 / W((M - 1) / 2)
w *= scale
return _truncate(w, needs_trunc)
def dpss(M, NW, Kmax=None, sym=True, norm=None, return_ratios=False):
"""
Compute the Discrete Prolate Spheroidal Sequences (DPSS).
DPSS (or Slepian sequences) are often used in multitaper power spectral
density estimation (see [1]_). The first window in the sequence can be
used to maximize the energy concentration in the main lobe, and is also
called the Slepian window.
Parameters
----------
M : int
Window length.
NW : float
Standardized half bandwidth corresponding to ``2*NW = BW/f0 = BW*M*dt``
where ``dt`` is taken as 1.
Kmax : int | None, optional
Number of DPSS windows to return (orders ``0`` through ``Kmax-1``).
If None (default), return only a single window of shape ``(M,)``
instead of an array of windows of shape ``(Kmax, M)``.
sym : bool, optional
When True (default), generates a symmetric window, for use in filter
design.
When False, generates a periodic window, for use in spectral analysis.
norm : {2, 'approximate', 'subsample'} | None, optional
If 'approximate' or 'subsample', then the windows are normalized by the
maximum, and a correction scale-factor for even-length windows
is applied either using ``M**2/(M**2+NW)`` ("approximate") or
a FFT-based subsample shift ("subsample"), see Notes for details.
If None, then "approximate" is used when ``Kmax=None`` and 2 otherwise
(which uses the l2 norm).
return_ratios : bool, optional
If True, also return the concentration ratios in addition to the
windows.
Returns
-------
v : ndarray, shape (Kmax, M) or (M,)
The DPSS windows. Will be 1D if `Kmax` is None.
r : ndarray, shape (Kmax,) or float, optional
The concentration ratios for the windows. Only returned if
`return_ratios` evaluates to True. Will be 0D if `Kmax` is None.
Notes
-----
This computation uses the tridiagonal eigenvector formulation given
in [2]_.
The default normalization for ``Kmax=None``, i.e. window-generation mode,
simply using the l-infinity norm would create a window with two unity
values, which creates slight normalization differences between even and odd
orders. The approximate correction of ``M**2/float(M**2+NW)`` for even
sample numbers is used to counteract this effect (see Examples below).
For very long signals (e.g., 1e6 elements), it can be useful to compute
windows orders of magnitude shorter and use interpolation (e.g.,
`scipy.interpolate.interp1d`) to obtain tapers of length `M`,
but this in general will not preserve orthogonality between the tapers.
.. versionadded:: 1.1
References
----------
.. [1] Percival DB, Walden WT. Spectral Analysis for Physical Applications:
Multitaper and Conventional Univariate Techniques.
Cambridge University Press; 1993.
.. [2] Slepian, D. Prolate spheroidal wave functions, Fourier analysis, and
uncertainty V: The discrete case. Bell System Technical Journal,
Volume 57 (1978), 1371430.
.. [3] Kaiser, JF, Schafer RW. On the Use of the I0-Sinh Window for
Spectrum Analysis. IEEE Transactions on Acoustics, Speech and
Signal Processing. ASSP-28 (1): 105-107; 1980.
Examples
--------
We can compare the window to `kaiser`, which was invented as an alternative
that was easier to calculate [3]_ (example adapted from
`here <https://ccrma.stanford.edu/~jos/sasp/Kaiser_DPSS_Windows_Compared.html>`_):
>>> import numpy as np
>>> import matplotlib.pyplot as plt
>>> from scipy.signal import windows, freqz
>>> M = 51
>>> fig, axes = plt.subplots(3, 2, figsize=(5, 7))
>>> for ai, alpha in enumerate((1, 3, 5)):
... win_dpss = windows.dpss(M, alpha)
... beta = alpha*np.pi
... win_kaiser = windows.kaiser(M, beta)
... for win, c in ((win_dpss, 'k'), (win_kaiser, 'r')):
... win /= win.sum()
... axes[ai, 0].plot(win, color=c, lw=1.)
... axes[ai, 0].set(xlim=[0, M-1], title=r'$\\alpha$ = %s' % alpha,
... ylabel='Amplitude')
... w, h = freqz(win)
... axes[ai, 1].plot(w, 20 * np.log10(np.abs(h)), color=c, lw=1.)
... axes[ai, 1].set(xlim=[0, np.pi],
... title=r'$\\beta$ = %0.2f' % beta,
... ylabel='Magnitude (dB)')
>>> for ax in axes.ravel():
... ax.grid(True)
>>> axes[2, 1].legend(['DPSS', 'Kaiser'])
>>> fig.tight_layout()
>>> plt.show()
And here are examples of the first four windows, along with their
concentration ratios:
>>> M = 512
>>> NW = 2.5
>>> win, eigvals = windows.dpss(M, NW, 4, return_ratios=True)
>>> fig, ax = plt.subplots(1)
>>> ax.plot(win.T, linewidth=1.)
>>> ax.set(xlim=[0, M-1], ylim=[-0.1, 0.1], xlabel='Samples',
... title='DPSS, M=%d, NW=%0.1f' % (M, NW))
>>> ax.legend(['win[%d] (%0.4f)' % (ii, ratio)
... for ii, ratio in enumerate(eigvals)])
>>> fig.tight_layout()
>>> plt.show()
Using a standard :math:`l_{\\infty}` norm would produce two unity values
for even `M`, but only one unity value for odd `M`. This produces uneven
window power that can be counteracted by the approximate correction
``M**2/float(M**2+NW)``, which can be selected by using
``norm='approximate'`` (which is the same as ``norm=None`` when
``Kmax=None``, as is the case here). Alternatively, the slower
``norm='subsample'`` can be used, which uses subsample shifting in the
frequency domain (FFT) to compute the correction:
>>> Ms = np.arange(1, 41)
>>> factors = (50, 20, 10, 5, 2.0001)
>>> energy = np.empty((3, len(Ms), len(factors)))
>>> for mi, M in enumerate(Ms):
... for fi, factor in enumerate(factors):
... NW = M / float(factor)
... # Corrected using empirical approximation (default)
... win = windows.dpss(M, NW)
... energy[0, mi, fi] = np.sum(win ** 2) / np.sqrt(M)
... # Corrected using subsample shifting
... win = windows.dpss(M, NW, norm='subsample')
... energy[1, mi, fi] = np.sum(win ** 2) / np.sqrt(M)
... # Uncorrected (using l-infinity norm)
... win /= win.max()
... energy[2, mi, fi] = np.sum(win ** 2) / np.sqrt(M)
>>> fig, ax = plt.subplots(1)
>>> hs = ax.plot(Ms, energy[2], '-o', markersize=4,
... markeredgecolor='none')
>>> leg = [hs[-1]]
>>> for hi, hh in enumerate(hs):
... h1 = ax.plot(Ms, energy[0, :, hi], '-o', markersize=4,
... color=hh.get_color(), markeredgecolor='none',
... alpha=0.66)
... h2 = ax.plot(Ms, energy[1, :, hi], '-o', markersize=4,
... color=hh.get_color(), markeredgecolor='none',
... alpha=0.33)
... if hi == len(hs) - 1:
... leg.insert(0, h1[0])
... leg.insert(0, h2[0])
>>> ax.set(xlabel='M (samples)', ylabel=r'Power / $\\sqrt{M}$')
>>> ax.legend(leg, ['Uncorrected', r'Corrected: $\\frac{M^2}{M^2+NW}$',
... 'Corrected (subsample)'])
>>> fig.tight_layout()
""" # noqa: E501
if _len_guards(M):
return np.ones(M)
if norm is None:
norm = 'approximate' if Kmax is None else 2
known_norms = (2, 'approximate', 'subsample')
if norm not in known_norms:
raise ValueError('norm must be one of %s, got %s'
% (known_norms, norm))
if Kmax is None:
singleton = True
Kmax = 1
else:
singleton = False
Kmax = operator.index(Kmax)
if not 0 < Kmax <= M:
raise ValueError('Kmax must be greater than 0 and less than M')
if NW >= M/2.:
raise ValueError('NW must be less than M/2.')
if NW <= 0:
raise ValueError('NW must be positive')
M, needs_trunc = _extend(M, sym)
W = float(NW) / M
nidx = np.arange(M)
# Here we want to set up an optimization problem to find a sequence
# whose energy is maximally concentrated within band [-W,W].
# Thus, the measure lambda(T,W) is the ratio between the energy within
# that band, and the total energy. This leads to the eigen-system
# (A - (l1)I)v = 0, where the eigenvector corresponding to the largest
# eigenvalue is the sequence with maximally concentrated energy. The
# collection of eigenvectors of this system are called Slepian
# sequences, or discrete prolate spheroidal sequences (DPSS). Only the
# first K, K = 2NW/dt orders of DPSS will exhibit good spectral
# concentration
# [see https://en.wikipedia.org/wiki/Spectral_concentration_problem]
# Here we set up an alternative symmetric tri-diagonal eigenvalue
# problem such that
# (B - (l2)I)v = 0, and v are our DPSS (but eigenvalues l2 != l1)
# the main diagonal = ([M-1-2*t]/2)**2 cos(2PIW), t=[0,1,2,...,M-1]
# and the first off-diagonal = t(M-t)/2, t=[1,2,...,M-1]
# [see Percival and Walden, 1993]
d = ((M - 1 - 2 * nidx) / 2.) ** 2 * np.cos(2 * np.pi * W)
e = nidx[1:] * (M - nidx[1:]) / 2.
# only calculate the highest Kmax eigenvalues
w, windows = linalg.eigh_tridiagonal(
d, e, select='i', select_range=(M - Kmax, M - 1))
w = w[::-1]
windows = windows[:, ::-1].T
# By convention (Percival and Walden, 1993 pg 379)
# * symmetric tapers (k=0,2,4,...) should have a positive average.
fix_even = (windows[::2].sum(axis=1) < 0)
for i, f in enumerate(fix_even):
if f:
windows[2 * i] *= -1
# * antisymmetric tapers should begin with a positive lobe
# (this depends on the definition of "lobe", here we'll take the first
# point above the numerical noise, which should be good enough for
# sufficiently smooth functions, and more robust than relying on an
# algorithm that uses max(abs(w)), which is susceptible to numerical
# noise problems)
thresh = max(1e-7, 1. / M)
for i, w in enumerate(windows[1::2]):
if w[w * w > thresh][0] < 0:
windows[2 * i + 1] *= -1
# Now find the eigenvalues of the original spectral concentration problem
# Use the autocorr sequence technique from Percival and Walden, 1993 pg 390
if return_ratios:
dpss_rxx = _fftautocorr(windows)
r = 4 * W * np.sinc(2 * W * nidx)
r[0] = 2 * W
ratios = np.dot(dpss_rxx, r)
if singleton:
ratios = ratios[0]
# Deal with sym and Kmax=None
if norm != 2:
windows /= windows.max()
if M % 2 == 0:
if norm == 'approximate':
correction = M**2 / float(M**2 + NW)
else:
s = sp_fft.rfft(windows[0])
shift = -(1 - 1./M) * np.arange(1, M//2 + 1)
s[1:] *= 2 * np.exp(-1j * np.pi * shift)
correction = M / s.real.sum()
windows *= correction
# else we're already l2 normed, so do nothing
if needs_trunc:
windows = windows[:, :-1]
if singleton:
windows = windows[0]
return (windows, ratios) if return_ratios else windows
def _fftautocorr(x):
"""Compute the autocorrelation of a real array and crop the result."""
N = x.shape[-1]
use_N = sp_fft.next_fast_len(2*N-1)
x_fft = sp_fft.rfft(x, use_N, axis=-1)
cxy = sp_fft.irfft(x_fft * x_fft.conj(), n=use_N)[:, :N]
# Or equivalently (but in most cases slower):
# cxy = np.array([np.convolve(xx, yy[::-1], mode='full')
# for xx, yy in zip(x, x)])[:, N-1:2*N-1]
return cxy
_win_equiv_raw = {
('barthann', 'brthan', 'bth'): (barthann, False),
('bartlett', 'bart', 'brt'): (bartlett, False),
('blackman', 'black', 'blk'): (blackman, False),
('blackmanharris', 'blackharr', 'bkh'): (blackmanharris, False),
('bohman', 'bman', 'bmn'): (bohman, False),
('boxcar', 'box', 'ones',
'rect', 'rectangular'): (boxcar, False),
('chebwin', 'cheb'): (chebwin, True),
('cosine', 'halfcosine'): (cosine, False),
('dpss',): (dpss, True),
('exponential', 'poisson'): (exponential, False),
('flattop', 'flat', 'flt'): (flattop, False),
('gaussian', 'gauss', 'gss'): (gaussian, True),
('general cosine', 'general_cosine'): (general_cosine, True),
('general gaussian', 'general_gaussian',
'general gauss', 'general_gauss', 'ggs'): (general_gaussian, True),
('general hamming', 'general_hamming'): (general_hamming, True),
('hamming', 'hamm', 'ham'): (hamming, False),
('hanning', 'hann', 'han'): (hann, False),
('kaiser', 'ksr'): (kaiser, True),
('kaiser bessel derived', 'kbd'): (kaiser_bessel_derived, True),
('nuttall', 'nutl', 'nut'): (nuttall, False),
('parzen', 'parz', 'par'): (parzen, False),
('taylor', 'taylorwin'): (taylor, False),
('triangle', 'triang', 'tri'): (triang, False),
('tukey', 'tuk'): (tukey, False),
}
# Fill dict with all valid window name strings
_win_equiv = {}
for k, v in _win_equiv_raw.items():
for key in k:
_win_equiv[key] = v[0]
# Keep track of which windows need additional parameters
_needs_param = set()
for k, v in _win_equiv_raw.items():
if v[1]:
_needs_param.update(k)
def get_window(window, Nx, fftbins=True):
"""
Return a window of a given length and type.
Parameters
----------
window : string, float, or tuple
The type of window to create. See below for more details.
Nx : int
The number of samples in the window.
fftbins : bool, optional
If True (default), create a "periodic" window, ready to use with
`ifftshift` and be multiplied by the result of an FFT (see also
:func:`~scipy.fft.fftfreq`).
If False, create a "symmetric" window, for use in filter design.
Returns
-------
get_window : ndarray
Returns a window of length `Nx` and type `window`
Notes
-----
Window types:
- `~scipy.signal.windows.boxcar`
- `~scipy.signal.windows.triang`
- `~scipy.signal.windows.blackman`
- `~scipy.signal.windows.hamming`
- `~scipy.signal.windows.hann`
- `~scipy.signal.windows.bartlett`
- `~scipy.signal.windows.flattop`
- `~scipy.signal.windows.parzen`
- `~scipy.signal.windows.bohman`
- `~scipy.signal.windows.blackmanharris`
- `~scipy.signal.windows.nuttall`
- `~scipy.signal.windows.barthann`
- `~scipy.signal.windows.cosine`
- `~scipy.signal.windows.exponential`
- `~scipy.signal.windows.tukey`
- `~scipy.signal.windows.taylor`
- `~scipy.signal.windows.kaiser` (needs beta)
- `~scipy.signal.windows.kaiser_bessel_derived` (needs beta)
- `~scipy.signal.windows.gaussian` (needs standard deviation)
- `~scipy.signal.windows.general_cosine` (needs weighting coefficients)
- `~scipy.signal.windows.general_gaussian` (needs power, width)
- `~scipy.signal.windows.general_hamming` (needs window coefficient)
- `~scipy.signal.windows.dpss` (needs normalized half-bandwidth)
- `~scipy.signal.windows.chebwin` (needs attenuation)
If the window requires no parameters, then `window` can be a string.
If the window requires parameters, then `window` must be a tuple
with the first argument the string name of the window, and the next
arguments the needed parameters.
If `window` is a floating point number, it is interpreted as the beta
parameter of the `~scipy.signal.windows.kaiser` window.
Each of the window types listed above is also the name of
a function that can be called directly to create a window of
that type.
Examples
--------
>>> from scipy import signal
>>> signal.get_window('triang', 7)
array([ 0.125, 0.375, 0.625, 0.875, 0.875, 0.625, 0.375])
>>> signal.get_window(('kaiser', 4.0), 9)
array([ 0.08848053, 0.29425961, 0.56437221, 0.82160913, 0.97885093,
0.97885093, 0.82160913, 0.56437221, 0.29425961])
>>> signal.get_window(('exponential', None, 1.), 9)
array([ 0.011109 , 0.03019738, 0.082085 , 0.22313016, 0.60653066,
0.60653066, 0.22313016, 0.082085 , 0.03019738])
>>> signal.get_window(4.0, 9)
array([ 0.08848053, 0.29425961, 0.56437221, 0.82160913, 0.97885093,
0.97885093, 0.82160913, 0.56437221, 0.29425961])
"""
sym = not fftbins
try:
beta = float(window)
except (TypeError, ValueError) as e:
args = ()
if isinstance(window, tuple):
winstr = window[0]
if len(window) > 1:
args = window[1:]
elif isinstance(window, str):
if window in _needs_param:
raise ValueError("The '" + window + "' window needs one or "
"more parameters -- pass a tuple.") from e
else:
winstr = window
else:
raise ValueError("%s as window type is not supported." %
str(type(window))) from e
try:
winfunc = _win_equiv[winstr]
except KeyError as e:
raise ValueError("Unknown window type.") from e
if winfunc is dpss:
params = (Nx,) + args + (None,)
else:
params = (Nx,) + args
else:
winfunc = kaiser
params = (Nx, beta)
return winfunc(*params, sym=sym)
|
mdhaber/scipy
|
scipy/signal/windows/_windows.py
|
Python
|
bsd-3-clause
| 79,078
|
[
"Gaussian"
] |
a32a795c7cde0cb13304145bdb01bffa5d3e8cd6d64d3d4e84ed2b060986c61e
|
# $HeadURL$
__RCSID__ = "$Id$"
""" This backend just print the log messages through the standar output
"""
from DIRAC.FrameworkSystem.private.logging.backends.BaseBackend import BaseBackend
from DIRAC.Core.Utilities import LogColoring
class PrintBackend( BaseBackend ):
def doMessage( self, messageObject ):
msg = self.composeString( messageObject )
if not self._optionsDictionary[ 'Color' ]:
print( msg )
else:
print LogColoring.colorMessage( messageObject.getLevel(), msg )
|
Sbalbp/DIRAC
|
FrameworkSystem/private/logging/backends/PrintBackend.py
|
Python
|
gpl-3.0
| 507
|
[
"DIRAC"
] |
b0801934a65f53a33ccb99c7ae2885bf49aa217a52b12cf1bd6eb591d06fe257
|
# Copyright (c), Michael DeHaan <michael.dehaan@gmail.com>, 2012-2013
# Copyright (c), Toshio Kuratomi <tkuratomi@ansible.com> 2016
# Simplified BSD License (see licenses/simplified_bsd.txt or https://opensource.org/licenses/BSD-2-Clause)
from __future__ import absolute_import, division, print_function
SIZE_RANGES = {
'Y': 1 << 80,
'Z': 1 << 70,
'E': 1 << 60,
'P': 1 << 50,
'T': 1 << 40,
'G': 1 << 30,
'M': 1 << 20,
'K': 1 << 10,
'B': 1,
}
FILE_ATTRIBUTES = {
'A': 'noatime',
'a': 'append',
'c': 'compressed',
'C': 'nocow',
'd': 'nodump',
'D': 'dirsync',
'e': 'extents',
'E': 'encrypted',
'h': 'blocksize',
'i': 'immutable',
'I': 'indexed',
'j': 'journalled',
'N': 'inline',
's': 'zero',
'S': 'synchronous',
't': 'notail',
'T': 'blockroot',
'u': 'undelete',
'X': 'compressedraw',
'Z': 'compresseddirty',
}
PASS_VARS = {
'check_mode': 'check_mode',
'debug': '_debug',
'diff': '_diff',
'keep_remote_files': '_keep_remote_files',
'module_name': '_name',
'no_log': 'no_log',
'remote_tmp': '_remote_tmp',
'selinux_special_fs': '_selinux_special_fs',
'shell_executable': '_shell',
'socket': '_socket_path',
'syslog_facility': '_syslog_facility',
'tmpdir': '_tmpdir',
'verbosity': '_verbosity',
'version': 'ansible_version',
}
PASS_BOOLS = ('no_log', 'debug', 'diff')
# Ansible modules can be written in any language.
# The functions available here can be used to do many common tasks,
# to simplify development of Python modules.
import __main__
import atexit
import locale
import os
import re
import shlex
import subprocess
import sys
import types
import time
import select
import shutil
import stat
import tempfile
import traceback
import grp
import pwd
import platform
import errno
import datetime
from collections import deque
from itertools import chain, repeat
try:
import syslog
HAS_SYSLOG = True
except ImportError:
HAS_SYSLOG = False
try:
from systemd import journal
has_journal = True
except ImportError:
has_journal = False
HAVE_SELINUX = False
try:
import selinux
HAVE_SELINUX = True
except ImportError:
pass
# Python2 & 3 way to get NoneType
NoneType = type(None)
try:
import json
# Detect the python-json library which is incompatible
try:
if not isinstance(json.loads, types.FunctionType) or not isinstance(json.dumps, types.FunctionType):
raise ImportError
except AttributeError:
raise ImportError
except ImportError:
print('\n{"msg": "Error: ansible requires the stdlib json and was not found!", "failed": true}')
sys.exit(1)
AVAILABLE_HASH_ALGORITHMS = dict()
try:
import hashlib
# python 2.7.9+ and 2.7.0+
for attribute in ('available_algorithms', 'algorithms'):
algorithms = getattr(hashlib, attribute, None)
if algorithms:
break
if algorithms is None:
# python 2.5+
algorithms = ('md5', 'sha1', 'sha224', 'sha256', 'sha384', 'sha512')
for algorithm in algorithms:
AVAILABLE_HASH_ALGORITHMS[algorithm] = getattr(hashlib, algorithm)
# we may have been able to import md5 but it could still not be available
try:
hashlib.md5()
except ValueError:
algorithms.pop('md5', None)
except Exception:
import sha
AVAILABLE_HASH_ALGORITHMS = {'sha1': sha.sha}
try:
import md5
AVAILABLE_HASH_ALGORITHMS['md5'] = md5.md5
except Exception:
pass
from ansible.module_utils.common._collections_compat import (
KeysView,
Mapping, MutableMapping,
Sequence, MutableSequence,
Set, MutableSet,
)
from ansible.module_utils.common.process import get_bin_path
from ansible.module_utils.common.file import is_executable
from ansible.module_utils.pycompat24 import get_exception, literal_eval
from ansible.module_utils.six import (
PY2,
PY3,
b,
binary_type,
integer_types,
iteritems,
string_types,
text_type,
)
from ansible.module_utils.six.moves import map, reduce, shlex_quote
from ansible.module_utils._text import to_native, to_bytes, to_text
from ansible.module_utils.parsing.convert_bool import BOOLEANS, BOOLEANS_FALSE, BOOLEANS_TRUE, boolean
# Note: When getting Sequence from collections, it matches with strings. If
# this matters, make sure to check for strings before checking for sequencetype
SEQUENCETYPE = frozenset, KeysView, Sequence
PASSWORD_MATCH = re.compile(r'^(?:.+[-_\s])?pass(?:[-_\s]?(?:word|phrase|wrd|wd)?)(?:[-_\s].+)?$', re.I)
_NUMBERTYPES = tuple(list(integer_types) + [float])
# Deprecated compat. Only kept in case another module used these names Using
# ansible.module_utils.six is preferred
NUMBERTYPES = _NUMBERTYPES
imap = map
try:
# Python 2
unicode
except NameError:
# Python 3
unicode = text_type
try:
# Python 2
basestring
except NameError:
# Python 3
basestring = string_types
_literal_eval = literal_eval
# End of deprecated names
# Internal global holding passed in params. This is consulted in case
# multiple AnsibleModules are created. Otherwise each AnsibleModule would
# attempt to read from stdin. Other code should not use this directly as it
# is an internal implementation detail
_ANSIBLE_ARGS = None
FILE_COMMON_ARGUMENTS = dict(
# These are things we want. About setting metadata (mode, ownership, permissions in general) on
# created files (these are used by set_fs_attributes_if_different and included in
# load_file_common_arguments)
mode=dict(type='raw'),
owner=dict(),
group=dict(),
seuser=dict(),
serole=dict(),
selevel=dict(),
setype=dict(),
attributes=dict(aliases=['attr']),
# The following are not about perms and should not be in a rewritten file_common_args
src=dict(), # Maybe dest or path would be appropriate but src is not
follow=dict(type='bool', default=False), # Maybe follow is appropriate because it determines whether to follow symlinks for permission purposes too
force=dict(type='bool'),
# not taken by the file module, but other action plugins call the file module so this ignores
# them for now. In the future, the caller should take care of removing these from the module
# arguments before calling the file module.
content=dict(no_log=True), # used by copy
backup=dict(), # Used by a few modules to create a remote backup before updating the file
remote_src=dict(), # used by assemble
regexp=dict(), # used by assemble
delimiter=dict(), # used by assemble
directory_mode=dict(), # used by copy
unsafe_writes=dict(type='bool'), # should be available to any module using atomic_move
)
PASSWD_ARG_RE = re.compile(r'^[-]{0,2}pass[-]?(word|wd)?')
# Used for parsing symbolic file perms
MODE_OPERATOR_RE = re.compile(r'[+=-]')
USERS_RE = re.compile(r'[^ugo]')
PERMS_RE = re.compile(r'[^rwxXstugo]')
PERM_BITS = 0o7777 # file mode permission bits
EXEC_PERM_BITS = 0o0111 # execute permission bits
DEFAULT_PERM = 0o0666 # default file permission bits
# Used for determining if the system is running a new enough python version
# and should only restrict on our documented minimum versions
_PY3_MIN = sys.version_info[:2] >= (3, 5)
_PY2_MIN = (2, 6) <= sys.version_info[:2] < (3,)
_PY_MIN = _PY3_MIN or _PY2_MIN
if not _PY_MIN:
print(
'\n{"failed": true, '
'"msg": "Ansible requires a minimum of Python2 version 2.6 or Python3 version 3.5. Current version: %s"}' % ''.join(sys.version.splitlines())
)
sys.exit(1)
def get_platform():
''' what's the platform? example: Linux is a platform. '''
return platform.system()
def get_distribution():
''' return the distribution name '''
if platform.system() == 'Linux':
try:
supported_dists = platform._supported_dists + ('arch', 'alpine', 'devuan')
distribution = platform.linux_distribution(supported_dists=supported_dists)[0].capitalize()
if not distribution and os.path.isfile('/etc/system-release'):
distribution = platform.linux_distribution(supported_dists=['system'])[0].capitalize()
if 'Amazon' in distribution:
distribution = 'Amazon'
else:
distribution = 'OtherLinux'
except:
# FIXME: MethodMissing, I assume?
distribution = platform.dist()[0].capitalize()
else:
distribution = None
return distribution
def get_distribution_version():
''' return the distribution version '''
if platform.system() == 'Linux':
try:
distribution_version = platform.linux_distribution()[1]
if not distribution_version and os.path.isfile('/etc/system-release'):
distribution_version = platform.linux_distribution(supported_dists=['system'])[1]
except:
# FIXME: MethodMissing, I assume?
distribution_version = platform.dist()[1]
else:
distribution_version = None
return distribution_version
def get_all_subclasses(cls):
'''
used by modules like Hardware or Network fact classes to retrieve all subclasses of a given class.
__subclasses__ return only direct sub classes. This one go down into the class tree.
'''
# Retrieve direct subclasses
subclasses = cls.__subclasses__()
to_visit = list(subclasses)
# Then visit all subclasses
while to_visit:
for sc in to_visit:
# The current class is now visited, so remove it from list
to_visit.remove(sc)
# Appending all subclasses to visit and keep a reference of available class
for ssc in sc.__subclasses__():
subclasses.append(ssc)
to_visit.append(ssc)
return subclasses
def load_platform_subclass(cls, *args, **kwargs):
'''
used by modules like User to have different implementations based on detected platform. See User
module for an example.
'''
this_platform = get_platform()
distribution = get_distribution()
subclass = None
# get the most specific superclass for this platform
if distribution is not None:
for sc in get_all_subclasses(cls):
if sc.distribution is not None and sc.distribution == distribution and sc.platform == this_platform:
subclass = sc
if subclass is None:
for sc in get_all_subclasses(cls):
if sc.platform == this_platform and sc.distribution is None:
subclass = sc
if subclass is None:
subclass = cls
return super(cls, subclass).__new__(subclass)
def json_dict_unicode_to_bytes(d, encoding='utf-8', errors='surrogate_or_strict'):
''' Recursively convert dict keys and values to byte str
Specialized for json return because this only handles, lists, tuples,
and dict container types (the containers that the json module returns)
'''
if isinstance(d, text_type):
return to_bytes(d, encoding=encoding, errors=errors)
elif isinstance(d, dict):
return dict(map(json_dict_unicode_to_bytes, iteritems(d), repeat(encoding), repeat(errors)))
elif isinstance(d, list):
return list(map(json_dict_unicode_to_bytes, d, repeat(encoding), repeat(errors)))
elif isinstance(d, tuple):
return tuple(map(json_dict_unicode_to_bytes, d, repeat(encoding), repeat(errors)))
else:
return d
def json_dict_bytes_to_unicode(d, encoding='utf-8', errors='surrogate_or_strict'):
''' Recursively convert dict keys and values to byte str
Specialized for json return because this only handles, lists, tuples,
and dict container types (the containers that the json module returns)
'''
if isinstance(d, binary_type):
# Warning, can traceback
return to_text(d, encoding=encoding, errors=errors)
elif isinstance(d, dict):
return dict(map(json_dict_bytes_to_unicode, iteritems(d), repeat(encoding), repeat(errors)))
elif isinstance(d, list):
return list(map(json_dict_bytes_to_unicode, d, repeat(encoding), repeat(errors)))
elif isinstance(d, tuple):
return tuple(map(json_dict_bytes_to_unicode, d, repeat(encoding), repeat(errors)))
else:
return d
def return_values(obj):
""" Return native stringified values from datastructures.
For use with removing sensitive values pre-jsonification."""
if isinstance(obj, (text_type, binary_type)):
if obj:
yield to_native(obj, errors='surrogate_or_strict')
return
elif isinstance(obj, SEQUENCETYPE):
for element in obj:
for subelement in return_values(element):
yield subelement
elif isinstance(obj, Mapping):
for element in obj.items():
for subelement in return_values(element[1]):
yield subelement
elif isinstance(obj, (bool, NoneType)):
# This must come before int because bools are also ints
return
elif isinstance(obj, NUMBERTYPES):
yield to_native(obj, nonstring='simplerepr')
else:
raise TypeError('Unknown parameter type: %s, %s' % (type(obj), obj))
def _remove_values_conditions(value, no_log_strings, deferred_removals):
"""
Helper function for :meth:`remove_values`.
:arg value: The value to check for strings that need to be stripped
:arg no_log_strings: set of strings which must be stripped out of any values
:arg deferred_removals: List which holds information about nested
containers that have to be iterated for removals. It is passed into
this function so that more entries can be added to it if value is
a container type. The format of each entry is a 2-tuple where the first
element is the ``value`` parameter and the second value is a new
container to copy the elements of ``value`` into once iterated.
:returns: if ``value`` is a scalar, returns ``value`` with two exceptions:
1. :class:`~datetime.datetime` objects which are changed into a string representation.
2. objects which are in no_log_strings are replaced with a placeholder
so that no sensitive data is leaked.
If ``value`` is a container type, returns a new empty container.
``deferred_removals`` is added to as a side-effect of this function.
.. warning:: It is up to the caller to make sure the order in which value
is passed in is correct. For instance, higher level containers need
to be passed in before lower level containers. For example, given
``{'level1': {'level2': 'level3': [True]} }`` first pass in the
dictionary for ``level1``, then the dict for ``level2``, and finally
the list for ``level3``.
"""
if isinstance(value, (text_type, binary_type)):
# Need native str type
native_str_value = value
if isinstance(value, text_type):
value_is_text = True
if PY2:
native_str_value = to_bytes(value, errors='surrogate_or_strict')
elif isinstance(value, binary_type):
value_is_text = False
if PY3:
native_str_value = to_text(value, errors='surrogate_or_strict')
if native_str_value in no_log_strings:
return 'VALUE_SPECIFIED_IN_NO_LOG_PARAMETER'
for omit_me in no_log_strings:
native_str_value = native_str_value.replace(omit_me, '*' * 8)
if value_is_text and isinstance(native_str_value, binary_type):
value = to_text(native_str_value, encoding='utf-8', errors='surrogate_then_replace')
elif not value_is_text and isinstance(native_str_value, text_type):
value = to_bytes(native_str_value, encoding='utf-8', errors='surrogate_then_replace')
else:
value = native_str_value
elif isinstance(value, Sequence):
if isinstance(value, MutableSequence):
new_value = type(value)()
else:
new_value = [] # Need a mutable value
deferred_removals.append((value, new_value))
value = new_value
elif isinstance(value, Set):
if isinstance(value, MutableSet):
new_value = type(value)()
else:
new_value = set() # Need a mutable value
deferred_removals.append((value, new_value))
value = new_value
elif isinstance(value, Mapping):
if isinstance(value, MutableMapping):
new_value = type(value)()
else:
new_value = {} # Need a mutable value
deferred_removals.append((value, new_value))
value = new_value
elif isinstance(value, tuple(chain(NUMBERTYPES, (bool, NoneType)))):
stringy_value = to_native(value, encoding='utf-8', errors='surrogate_or_strict')
if stringy_value in no_log_strings:
return 'VALUE_SPECIFIED_IN_NO_LOG_PARAMETER'
for omit_me in no_log_strings:
if omit_me in stringy_value:
return 'VALUE_SPECIFIED_IN_NO_LOG_PARAMETER'
elif isinstance(value, datetime.datetime):
value = value.isoformat()
else:
raise TypeError('Value of unknown type: %s, %s' % (type(value), value))
return value
def remove_values(value, no_log_strings):
""" Remove strings in no_log_strings from value. If value is a container
type, then remove a lot more"""
deferred_removals = deque()
no_log_strings = [to_native(s, errors='surrogate_or_strict') for s in no_log_strings]
new_value = _remove_values_conditions(value, no_log_strings, deferred_removals)
while deferred_removals:
old_data, new_data = deferred_removals.popleft()
if isinstance(new_data, Mapping):
for old_key, old_elem in old_data.items():
new_elem = _remove_values_conditions(old_elem, no_log_strings, deferred_removals)
new_data[old_key] = new_elem
else:
for elem in old_data:
new_elem = _remove_values_conditions(elem, no_log_strings, deferred_removals)
if isinstance(new_data, MutableSequence):
new_data.append(new_elem)
elif isinstance(new_data, MutableSet):
new_data.add(new_elem)
else:
raise TypeError('Unknown container type encountered when removing private values from output')
return new_value
def heuristic_log_sanitize(data, no_log_values=None):
''' Remove strings that look like passwords from log messages '''
# Currently filters:
# user:pass@foo/whatever and http://username:pass@wherever/foo
# This code has false positives and consumes parts of logs that are
# not passwds
# begin: start of a passwd containing string
# end: end of a passwd containing string
# sep: char between user and passwd
# prev_begin: where in the overall string to start a search for
# a passwd
# sep_search_end: where in the string to end a search for the sep
data = to_native(data)
output = []
begin = len(data)
prev_begin = begin
sep = 1
while sep:
# Find the potential end of a passwd
try:
end = data.rindex('@', 0, begin)
except ValueError:
# No passwd in the rest of the data
output.insert(0, data[0:begin])
break
# Search for the beginning of a passwd
sep = None
sep_search_end = end
while not sep:
# URL-style username+password
try:
begin = data.rindex('://', 0, sep_search_end)
except ValueError:
# No url style in the data, check for ssh style in the
# rest of the string
begin = 0
# Search for separator
try:
sep = data.index(':', begin + 3, end)
except ValueError:
# No separator; choices:
if begin == 0:
# Searched the whole string so there's no password
# here. Return the remaining data
output.insert(0, data[0:begin])
break
# Search for a different beginning of the password field.
sep_search_end = begin
continue
if sep:
# Password was found; remove it.
output.insert(0, data[end:prev_begin])
output.insert(0, '********')
output.insert(0, data[begin:sep + 1])
prev_begin = begin
output = ''.join(output)
if no_log_values:
output = remove_values(output, no_log_values)
return output
def bytes_to_human(size, isbits=False, unit=None):
base = 'Bytes'
if isbits:
base = 'bits'
suffix = ''
for suffix, limit in sorted(iteritems(SIZE_RANGES), key=lambda item: -item[1]):
if (unit is None and size >= limit) or unit is not None and unit.upper() == suffix[0]:
break
if limit != 1:
suffix += base[0]
else:
suffix = base
return '%.2f %s' % (size / limit, suffix)
def human_to_bytes(number, default_unit=None, isbits=False):
'''
Convert number in string format into bytes (ex: '2K' => 2048) or using unit argument
ex:
human_to_bytes('10M') <=> human_to_bytes(10, 'M')
'''
m = re.search(r'^\s*(\d*\.?\d*)\s*([A-Za-z]+)?', str(number), flags=re.IGNORECASE)
if m is None:
raise ValueError("human_to_bytes() can't interpret following string: %s" % str(number))
try:
num = float(m.group(1))
except:
raise ValueError("human_to_bytes() can't interpret following number: %s (original input string: %s)" % (m.group(1), number))
unit = m.group(2)
if unit is None:
unit = default_unit
if unit is None:
''' No unit given, returning raw number '''
return int(round(num))
range_key = unit[0].upper()
try:
limit = SIZE_RANGES[range_key]
except:
raise ValueError("human_to_bytes() failed to convert %s (unit = %s). The suffix must be one of %s" % (number, unit, ", ".join(SIZE_RANGES.keys())))
# default value
unit_class = 'B'
unit_class_name = 'byte'
# handling bits case
if isbits:
unit_class = 'b'
unit_class_name = 'bit'
# check unit value if more than one character (KB, MB)
if len(unit) > 1:
expect_message = 'expect %s%s or %s' % (range_key, unit_class, range_key)
if range_key == 'B':
expect_message = 'expect %s or %s' % (unit_class, unit_class_name)
if unit_class_name in unit.lower():
pass
elif unit[1] != unit_class:
raise ValueError("human_to_bytes() failed to convert %s. Value is not a valid string (%s)" % (number, expect_message))
return int(round(num * limit))
def _load_params():
''' read the modules parameters and store them globally.
This function may be needed for certain very dynamic custom modules which
want to process the parameters that are being handed the module. Since
this is so closely tied to the implementation of modules we cannot
guarantee API stability for it (it may change between versions) however we
will try not to break it gratuitously. It is certainly more future-proof
to call this function and consume its outputs than to implement the logic
inside it as a copy in your own code.
'''
global _ANSIBLE_ARGS
if _ANSIBLE_ARGS is not None:
buffer = _ANSIBLE_ARGS
else:
# debug overrides to read args from file or cmdline
# Avoid tracebacks when locale is non-utf8
# We control the args and we pass them as utf8
if len(sys.argv) > 1:
if os.path.isfile(sys.argv[1]):
fd = open(sys.argv[1], 'rb')
buffer = fd.read()
fd.close()
else:
buffer = sys.argv[1]
if PY3:
buffer = buffer.encode('utf-8', errors='surrogateescape')
# default case, read from stdin
else:
if PY2:
buffer = sys.stdin.read()
else:
buffer = sys.stdin.buffer.read()
_ANSIBLE_ARGS = buffer
try:
params = json.loads(buffer.decode('utf-8'))
except ValueError:
# This helper used too early for fail_json to work.
print('\n{"msg": "Error: Module unable to decode valid JSON on stdin. Unable to figure out what parameters were passed", "failed": true}')
sys.exit(1)
if PY2:
params = json_dict_unicode_to_bytes(params)
try:
return params['ANSIBLE_MODULE_ARGS']
except KeyError:
# This helper does not have access to fail_json so we have to print
# json output on our own.
print('\n{"msg": "Error: Module unable to locate ANSIBLE_MODULE_ARGS in json data from stdin. Unable to figure out what parameters were passed", '
'"failed": true}')
sys.exit(1)
def env_fallback(*args, **kwargs):
''' Load value from environment '''
for arg in args:
if arg in os.environ:
return os.environ[arg]
raise AnsibleFallbackNotFound
def _lenient_lowercase(lst):
"""Lowercase elements of a list.
If an element is not a string, pass it through untouched.
"""
lowered = []
for value in lst:
try:
lowered.append(value.lower())
except AttributeError:
lowered.append(value)
return lowered
def format_attributes(attributes):
attribute_list = []
for attr in attributes:
if attr in FILE_ATTRIBUTES:
attribute_list.append(FILE_ATTRIBUTES[attr])
return attribute_list
def get_flags_from_attributes(attributes):
flags = []
for key, attr in FILE_ATTRIBUTES.items():
if attr in attributes:
flags.append(key)
return ''.join(flags)
def _json_encode_fallback(obj):
if isinstance(obj, Set):
return list(obj)
elif isinstance(obj, datetime.datetime):
return obj.isoformat()
raise TypeError("Cannot json serialize %s" % to_native(obj))
def jsonify(data, **kwargs):
for encoding in ("utf-8", "latin-1"):
try:
return json.dumps(data, encoding=encoding, default=_json_encode_fallback, **kwargs)
# Old systems using old simplejson module does not support encoding keyword.
except TypeError:
try:
new_data = json_dict_bytes_to_unicode(data, encoding=encoding)
except UnicodeDecodeError:
continue
return json.dumps(new_data, default=_json_encode_fallback, **kwargs)
except UnicodeDecodeError:
continue
raise UnicodeError('Invalid unicode encoding encountered')
class AnsibleFallbackNotFound(Exception):
pass
class AnsibleModule(object):
def __init__(self, argument_spec, bypass_checks=False, no_log=False,
check_invalid_arguments=None, mutually_exclusive=None, required_together=None,
required_one_of=None, add_file_common_args=False, supports_check_mode=False,
required_if=None):
'''
common code for quickly building an ansible module in Python
(although you can write modules in anything that can return JSON)
see library/* for examples
'''
self._name = os.path.basename(__file__) # initialize name until we can parse from options
self.argument_spec = argument_spec
self.supports_check_mode = supports_check_mode
self.check_mode = False
self.bypass_checks = bypass_checks
self.no_log = no_log
# Check whether code set this explicitly for deprecation purposes
if check_invalid_arguments is None:
check_invalid_arguments = True
module_set_check_invalid_arguments = False
else:
module_set_check_invalid_arguments = True
self.check_invalid_arguments = check_invalid_arguments
self.mutually_exclusive = mutually_exclusive
self.required_together = required_together
self.required_one_of = required_one_of
self.required_if = required_if
self.cleanup_files = []
self._debug = False
self._diff = False
self._socket_path = None
self._shell = None
self._verbosity = 0
# May be used to set modifications to the environment for any
# run_command invocation
self.run_command_environ_update = {}
self._warnings = []
self._deprecations = []
self._clean = {}
self.aliases = {}
self._legal_inputs = ['_ansible_%s' % k for k in PASS_VARS]
self._options_context = list()
self._tmpdir = None
if add_file_common_args:
for k, v in FILE_COMMON_ARGUMENTS.items():
if k not in self.argument_spec:
self.argument_spec[k] = v
self._load_params()
self._set_fallbacks()
# append to legal_inputs and then possibly check against them
try:
self.aliases = self._handle_aliases()
except Exception as e:
# Use exceptions here because it isn't safe to call fail_json until no_log is processed
print('\n{"failed": true, "msg": "Module alias error: %s"}' % to_native(e))
sys.exit(1)
# Save parameter values that should never be logged
self.no_log_values = set()
self._handle_no_log_values()
# check the locale as set by the current environment, and reset to
# a known valid (LANG=C) if it's an invalid/unavailable locale
self._check_locale()
self._check_arguments(check_invalid_arguments)
# check exclusive early
if not bypass_checks:
self._check_mutually_exclusive(mutually_exclusive)
self._set_defaults(pre=True)
self._CHECK_ARGUMENT_TYPES_DISPATCHER = {
'str': self._check_type_str,
'list': self._check_type_list,
'dict': self._check_type_dict,
'bool': self._check_type_bool,
'int': self._check_type_int,
'float': self._check_type_float,
'path': self._check_type_path,
'raw': self._check_type_raw,
'jsonarg': self._check_type_jsonarg,
'json': self._check_type_jsonarg,
'bytes': self._check_type_bytes,
'bits': self._check_type_bits,
}
if not bypass_checks:
self._check_required_arguments()
self._check_argument_types()
self._check_argument_values()
self._check_required_together(required_together)
self._check_required_one_of(required_one_of)
self._check_required_if(required_if)
self._set_defaults(pre=False)
# deal with options sub-spec
self._handle_options()
if not self.no_log:
self._log_invocation()
# finally, make sure we're in a sane working dir
self._set_cwd()
# Do this at the end so that logging parameters have been set up
# This is to warn third party module authors that the functionatlity is going away.
# We exclude uri and zfs as they have their own deprecation warnings for users and we'll
# make sure to update their code to stop using check_invalid_arguments when 2.9 rolls around
if module_set_check_invalid_arguments and self._name not in ('uri', 'zfs'):
self.deprecate('Setting check_invalid_arguments is deprecated and will be removed.'
' Update the code for this module In the future, AnsibleModule will'
' always check for invalid arguments.', version='2.9')
@property
def tmpdir(self):
# if _ansible_tmpdir was not set and we have a remote_tmp,
# the module needs to create it and clean it up once finished.
# otherwise we create our own module tmp dir from the system defaults
if self._tmpdir is None:
basedir = None
basedir = os.path.expanduser(os.path.expandvars(self._remote_tmp))
if not os.path.exists(basedir):
try:
os.makedirs(basedir, mode=0o700)
except (OSError, IOError) as e:
self.warn("Unable to use %s as temporary directory, "
"failing back to system: %s" % (basedir, to_native(e)))
basedir = None
else:
self.warn("Module remote_tmp %s did not exist and was "
"created with a mode of 0700, this may cause"
" issues when running as another user. To "
"avoid this, create the remote_tmp dir with "
"the correct permissions manually" % basedir)
basefile = "ansible-moduletmp-%s-" % time.time()
try:
tmpdir = tempfile.mkdtemp(prefix=basefile, dir=basedir)
except (OSError, IOError) as e:
self.fail_json(
msg="Failed to create remote module tmp path at dir %s "
"with prefix %s: %s" % (basedir, basefile, to_native(e))
)
if not self._keep_remote_files:
atexit.register(shutil.rmtree, tmpdir)
self._tmpdir = tmpdir
return self._tmpdir
def warn(self, warning):
if isinstance(warning, string_types):
self._warnings.append(warning)
self.log('[WARNING] %s' % warning)
else:
raise TypeError("warn requires a string not a %s" % type(warning))
def deprecate(self, msg, version=None):
if isinstance(msg, string_types):
self._deprecations.append({
'msg': msg,
'version': version
})
self.log('[DEPRECATION WARNING] %s %s' % (msg, version))
else:
raise TypeError("deprecate requires a string not a %s" % type(msg))
def load_file_common_arguments(self, params):
'''
many modules deal with files, this encapsulates common
options that the file module accepts such that it is directly
available to all modules and they can share code.
'''
path = params.get('path', params.get('dest', None))
if path is None:
return {}
else:
path = os.path.expanduser(os.path.expandvars(path))
b_path = to_bytes(path, errors='surrogate_or_strict')
# if the path is a symlink, and we're following links, get
# the target of the link instead for testing
if params.get('follow', False) and os.path.islink(b_path):
b_path = os.path.realpath(b_path)
path = to_native(b_path)
mode = params.get('mode', None)
owner = params.get('owner', None)
group = params.get('group', None)
# selinux related options
seuser = params.get('seuser', None)
serole = params.get('serole', None)
setype = params.get('setype', None)
selevel = params.get('selevel', None)
secontext = [seuser, serole, setype]
if self.selinux_mls_enabled():
secontext.append(selevel)
default_secontext = self.selinux_default_context(path)
for i in range(len(default_secontext)):
if i is not None and secontext[i] == '_default':
secontext[i] = default_secontext[i]
attributes = params.get('attributes', None)
return dict(
path=path, mode=mode, owner=owner, group=group,
seuser=seuser, serole=serole, setype=setype,
selevel=selevel, secontext=secontext, attributes=attributes,
)
# Detect whether using selinux that is MLS-aware.
# While this means you can set the level/range with
# selinux.lsetfilecon(), it may or may not mean that you
# will get the selevel as part of the context returned
# by selinux.lgetfilecon().
def selinux_mls_enabled(self):
if not HAVE_SELINUX:
return False
if selinux.is_selinux_mls_enabled() == 1:
return True
else:
return False
def selinux_enabled(self):
if not HAVE_SELINUX:
seenabled = self.get_bin_path('selinuxenabled')
if seenabled is not None:
(rc, out, err) = self.run_command(seenabled)
if rc == 0:
self.fail_json(msg="Aborting, target uses selinux but python bindings (libselinux-python) aren't installed!")
return False
if selinux.is_selinux_enabled() == 1:
return True
else:
return False
# Determine whether we need a placeholder for selevel/mls
def selinux_initial_context(self):
context = [None, None, None]
if self.selinux_mls_enabled():
context.append(None)
return context
# If selinux fails to find a default, return an array of None
def selinux_default_context(self, path, mode=0):
context = self.selinux_initial_context()
if not HAVE_SELINUX or not self.selinux_enabled():
return context
try:
ret = selinux.matchpathcon(to_native(path, errors='surrogate_or_strict'), mode)
except OSError:
return context
if ret[0] == -1:
return context
# Limit split to 4 because the selevel, the last in the list,
# may contain ':' characters
context = ret[1].split(':', 3)
return context
def selinux_context(self, path):
context = self.selinux_initial_context()
if not HAVE_SELINUX or not self.selinux_enabled():
return context
try:
ret = selinux.lgetfilecon_raw(to_native(path, errors='surrogate_or_strict'))
except OSError as e:
if e.errno == errno.ENOENT:
self.fail_json(path=path, msg='path %s does not exist' % path)
else:
self.fail_json(path=path, msg='failed to retrieve selinux context')
if ret[0] == -1:
return context
# Limit split to 4 because the selevel, the last in the list,
# may contain ':' characters
context = ret[1].split(':', 3)
return context
def user_and_group(self, path, expand=True):
b_path = to_bytes(path, errors='surrogate_or_strict')
if expand:
b_path = os.path.expanduser(os.path.expandvars(b_path))
st = os.lstat(b_path)
uid = st.st_uid
gid = st.st_gid
return (uid, gid)
def find_mount_point(self, path):
path_is_bytes = False
if isinstance(path, binary_type):
path_is_bytes = True
b_path = os.path.realpath(to_bytes(os.path.expanduser(os.path.expandvars(path)), errors='surrogate_or_strict'))
while not os.path.ismount(b_path):
b_path = os.path.dirname(b_path)
if path_is_bytes:
return b_path
return to_text(b_path, errors='surrogate_or_strict')
def is_special_selinux_path(self, path):
"""
Returns a tuple containing (True, selinux_context) if the given path is on a
NFS or other 'special' fs mount point, otherwise the return will be (False, None).
"""
try:
f = open('/proc/mounts', 'r')
mount_data = f.readlines()
f.close()
except:
return (False, None)
path_mount_point = self.find_mount_point(path)
for line in mount_data:
(device, mount_point, fstype, options, rest) = line.split(' ', 4)
if path_mount_point == mount_point:
for fs in self._selinux_special_fs:
if fs in fstype:
special_context = self.selinux_context(path_mount_point)
return (True, special_context)
return (False, None)
def set_default_selinux_context(self, path, changed):
if not HAVE_SELINUX or not self.selinux_enabled():
return changed
context = self.selinux_default_context(path)
return self.set_context_if_different(path, context, False)
def set_context_if_different(self, path, context, changed, diff=None):
if not HAVE_SELINUX or not self.selinux_enabled():
return changed
if self.check_file_absent_if_check_mode(path):
return True
cur_context = self.selinux_context(path)
new_context = list(cur_context)
# Iterate over the current context instead of the
# argument context, which may have selevel.
(is_special_se, sp_context) = self.is_special_selinux_path(path)
if is_special_se:
new_context = sp_context
else:
for i in range(len(cur_context)):
if len(context) > i:
if context[i] is not None and context[i] != cur_context[i]:
new_context[i] = context[i]
elif context[i] is None:
new_context[i] = cur_context[i]
if cur_context != new_context:
if diff is not None:
if 'before' not in diff:
diff['before'] = {}
diff['before']['secontext'] = cur_context
if 'after' not in diff:
diff['after'] = {}
diff['after']['secontext'] = new_context
try:
if self.check_mode:
return True
rc = selinux.lsetfilecon(to_native(path), ':'.join(new_context))
except OSError as e:
self.fail_json(path=path, msg='invalid selinux context: %s' % to_native(e),
new_context=new_context, cur_context=cur_context, input_was=context)
if rc != 0:
self.fail_json(path=path, msg='set selinux context failed')
changed = True
return changed
def set_owner_if_different(self, path, owner, changed, diff=None, expand=True):
if owner is None:
return changed
b_path = to_bytes(path, errors='surrogate_or_strict')
if expand:
b_path = os.path.expanduser(os.path.expandvars(b_path))
if self.check_file_absent_if_check_mode(b_path):
return True
orig_uid, orig_gid = self.user_and_group(b_path, expand)
try:
uid = int(owner)
except ValueError:
try:
uid = pwd.getpwnam(owner).pw_uid
except KeyError:
path = to_text(b_path)
self.fail_json(path=path, msg='chown failed: failed to look up user %s' % owner)
if orig_uid != uid:
if diff is not None:
if 'before' not in diff:
diff['before'] = {}
diff['before']['owner'] = orig_uid
if 'after' not in diff:
diff['after'] = {}
diff['after']['owner'] = uid
if self.check_mode:
return True
try:
os.lchown(b_path, uid, -1)
except (IOError, OSError) as e:
path = to_text(b_path)
self.fail_json(path=path, msg='chown failed: %s' % (to_text(e)))
changed = True
return changed
def set_group_if_different(self, path, group, changed, diff=None, expand=True):
if group is None:
return changed
b_path = to_bytes(path, errors='surrogate_or_strict')
if expand:
b_path = os.path.expanduser(os.path.expandvars(b_path))
if self.check_file_absent_if_check_mode(b_path):
return True
orig_uid, orig_gid = self.user_and_group(b_path, expand)
try:
gid = int(group)
except ValueError:
try:
gid = grp.getgrnam(group).gr_gid
except KeyError:
path = to_text(b_path)
self.fail_json(path=path, msg='chgrp failed: failed to look up group %s' % group)
if orig_gid != gid:
if diff is not None:
if 'before' not in diff:
diff['before'] = {}
diff['before']['group'] = orig_gid
if 'after' not in diff:
diff['after'] = {}
diff['after']['group'] = gid
if self.check_mode:
return True
try:
os.lchown(b_path, -1, gid)
except OSError:
path = to_text(b_path)
self.fail_json(path=path, msg='chgrp failed')
changed = True
return changed
def set_mode_if_different(self, path, mode, changed, diff=None, expand=True):
if mode is None:
return changed
b_path = to_bytes(path, errors='surrogate_or_strict')
if expand:
b_path = os.path.expanduser(os.path.expandvars(b_path))
path_stat = os.lstat(b_path)
if self.check_file_absent_if_check_mode(b_path):
return True
if not isinstance(mode, int):
try:
mode = int(mode, 8)
except Exception:
try:
mode = self._symbolic_mode_to_octal(path_stat, mode)
except Exception as e:
path = to_text(b_path)
self.fail_json(path=path,
msg="mode must be in octal or symbolic form",
details=to_native(e))
if mode != stat.S_IMODE(mode):
# prevent mode from having extra info orbeing invalid long number
path = to_text(b_path)
self.fail_json(path=path, msg="Invalid mode supplied, only permission info is allowed", details=mode)
prev_mode = stat.S_IMODE(path_stat.st_mode)
if prev_mode != mode:
if diff is not None:
if 'before' not in diff:
diff['before'] = {}
diff['before']['mode'] = '0%03o' % prev_mode
if 'after' not in diff:
diff['after'] = {}
diff['after']['mode'] = '0%03o' % mode
if self.check_mode:
return True
# FIXME: comparison against string above will cause this to be executed
# every time
try:
if hasattr(os, 'lchmod'):
os.lchmod(b_path, mode)
else:
if not os.path.islink(b_path):
os.chmod(b_path, mode)
else:
# Attempt to set the perms of the symlink but be
# careful not to change the perms of the underlying
# file while trying
underlying_stat = os.stat(b_path)
os.chmod(b_path, mode)
new_underlying_stat = os.stat(b_path)
if underlying_stat.st_mode != new_underlying_stat.st_mode:
os.chmod(b_path, stat.S_IMODE(underlying_stat.st_mode))
except OSError as e:
if os.path.islink(b_path) and e.errno == errno.EPERM: # Can't set mode on symbolic links
pass
elif e.errno in (errno.ENOENT, errno.ELOOP): # Can't set mode on broken symbolic links
pass
else:
raise
except Exception as e:
path = to_text(b_path)
self.fail_json(path=path, msg='chmod failed', details=to_native(e),
exception=traceback.format_exc())
path_stat = os.lstat(b_path)
new_mode = stat.S_IMODE(path_stat.st_mode)
if new_mode != prev_mode:
changed = True
return changed
def set_attributes_if_different(self, path, attributes, changed, diff=None, expand=True):
if attributes is None:
return changed
b_path = to_bytes(path, errors='surrogate_or_strict')
if expand:
b_path = os.path.expanduser(os.path.expandvars(b_path))
if self.check_file_absent_if_check_mode(b_path):
return True
existing = self.get_file_attributes(b_path)
attr_mod = '='
if attributes.startswith(('-', '+')):
attr_mod = attributes[0]
attributes = attributes[1:]
if existing.get('attr_flags', '') != attributes or attr_mod == '-':
attrcmd = self.get_bin_path('chattr')
if attrcmd:
attrcmd = [attrcmd, '%s%s' % (attr_mod, attributes), b_path]
changed = True
if diff is not None:
if 'before' not in diff:
diff['before'] = {}
diff['before']['attributes'] = existing.get('attr_flags')
if 'after' not in diff:
diff['after'] = {}
diff['after']['attributes'] = '%s%s' % (attr_mod, attributes)
if not self.check_mode:
try:
rc, out, err = self.run_command(attrcmd)
if rc != 0 or err:
raise Exception("Error while setting attributes: %s" % (out + err))
except Exception as e:
self.fail_json(path=to_text(b_path), msg='chattr failed',
details=to_native(e), exception=traceback.format_exc())
return changed
def get_file_attributes(self, path):
output = {}
attrcmd = self.get_bin_path('lsattr', False)
if attrcmd:
attrcmd = [attrcmd, '-vd', path]
try:
rc, out, err = self.run_command(attrcmd)
if rc == 0:
res = out.split()
output['attr_flags'] = res[1].replace('-', '').strip()
output['version'] = res[0].strip()
output['attributes'] = format_attributes(output['attr_flags'])
except:
pass
return output
@classmethod
def _symbolic_mode_to_octal(cls, path_stat, symbolic_mode):
"""
This enables symbolic chmod string parsing as stated in the chmod man-page
This includes things like: "u=rw-x+X,g=r-x+X,o=r-x+X"
"""
new_mode = stat.S_IMODE(path_stat.st_mode)
# Now parse all symbolic modes
for mode in symbolic_mode.split(','):
# Per single mode. This always contains a '+', '-' or '='
# Split it on that
permlist = MODE_OPERATOR_RE.split(mode)
# And find all the operators
opers = MODE_OPERATOR_RE.findall(mode)
# The user(s) where it's all about is the first element in the
# 'permlist' list. Take that and remove it from the list.
# An empty user or 'a' means 'all'.
users = permlist.pop(0)
use_umask = (users == '')
if users == 'a' or users == '':
users = 'ugo'
# Check if there are illegal characters in the user list
# They can end up in 'users' because they are not split
if USERS_RE.match(users):
raise ValueError("bad symbolic permission for mode: %s" % mode)
# Now we have two list of equal length, one contains the requested
# permissions and one with the corresponding operators.
for idx, perms in enumerate(permlist):
# Check if there are illegal characters in the permissions
if PERMS_RE.match(perms):
raise ValueError("bad symbolic permission for mode: %s" % mode)
for user in users:
mode_to_apply = cls._get_octal_mode_from_symbolic_perms(path_stat, user, perms, use_umask)
new_mode = cls._apply_operation_to_mode(user, opers[idx], mode_to_apply, new_mode)
return new_mode
@staticmethod
def _apply_operation_to_mode(user, operator, mode_to_apply, current_mode):
if operator == '=':
if user == 'u':
mask = stat.S_IRWXU | stat.S_ISUID
elif user == 'g':
mask = stat.S_IRWXG | stat.S_ISGID
elif user == 'o':
mask = stat.S_IRWXO | stat.S_ISVTX
# mask out u, g, or o permissions from current_mode and apply new permissions
inverse_mask = mask ^ PERM_BITS
new_mode = (current_mode & inverse_mask) | mode_to_apply
elif operator == '+':
new_mode = current_mode | mode_to_apply
elif operator == '-':
new_mode = current_mode - (current_mode & mode_to_apply)
return new_mode
@staticmethod
def _get_octal_mode_from_symbolic_perms(path_stat, user, perms, use_umask):
prev_mode = stat.S_IMODE(path_stat.st_mode)
is_directory = stat.S_ISDIR(path_stat.st_mode)
has_x_permissions = (prev_mode & EXEC_PERM_BITS) > 0
apply_X_permission = is_directory or has_x_permissions
# Get the umask, if the 'user' part is empty, the effect is as if (a) were
# given, but bits that are set in the umask are not affected.
# We also need the "reversed umask" for masking
umask = os.umask(0)
os.umask(umask)
rev_umask = umask ^ PERM_BITS
# Permission bits constants documented at:
# http://docs.python.org/2/library/stat.html#stat.S_ISUID
if apply_X_permission:
X_perms = {
'u': {'X': stat.S_IXUSR},
'g': {'X': stat.S_IXGRP},
'o': {'X': stat.S_IXOTH},
}
else:
X_perms = {
'u': {'X': 0},
'g': {'X': 0},
'o': {'X': 0},
}
user_perms_to_modes = {
'u': {
'r': rev_umask & stat.S_IRUSR if use_umask else stat.S_IRUSR,
'w': rev_umask & stat.S_IWUSR if use_umask else stat.S_IWUSR,
'x': rev_umask & stat.S_IXUSR if use_umask else stat.S_IXUSR,
's': stat.S_ISUID,
't': 0,
'u': prev_mode & stat.S_IRWXU,
'g': (prev_mode & stat.S_IRWXG) << 3,
'o': (prev_mode & stat.S_IRWXO) << 6},
'g': {
'r': rev_umask & stat.S_IRGRP if use_umask else stat.S_IRGRP,
'w': rev_umask & stat.S_IWGRP if use_umask else stat.S_IWGRP,
'x': rev_umask & stat.S_IXGRP if use_umask else stat.S_IXGRP,
's': stat.S_ISGID,
't': 0,
'u': (prev_mode & stat.S_IRWXU) >> 3,
'g': prev_mode & stat.S_IRWXG,
'o': (prev_mode & stat.S_IRWXO) << 3},
'o': {
'r': rev_umask & stat.S_IROTH if use_umask else stat.S_IROTH,
'w': rev_umask & stat.S_IWOTH if use_umask else stat.S_IWOTH,
'x': rev_umask & stat.S_IXOTH if use_umask else stat.S_IXOTH,
's': 0,
't': stat.S_ISVTX,
'u': (prev_mode & stat.S_IRWXU) >> 6,
'g': (prev_mode & stat.S_IRWXG) >> 3,
'o': prev_mode & stat.S_IRWXO},
}
# Insert X_perms into user_perms_to_modes
for key, value in X_perms.items():
user_perms_to_modes[key].update(value)
def or_reduce(mode, perm):
return mode | user_perms_to_modes[user][perm]
return reduce(or_reduce, perms, 0)
def set_fs_attributes_if_different(self, file_args, changed, diff=None, expand=True):
# set modes owners and context as needed
changed = self.set_context_if_different(
file_args['path'], file_args['secontext'], changed, diff
)
changed = self.set_owner_if_different(
file_args['path'], file_args['owner'], changed, diff, expand
)
changed = self.set_group_if_different(
file_args['path'], file_args['group'], changed, diff, expand
)
changed = self.set_mode_if_different(
file_args['path'], file_args['mode'], changed, diff, expand
)
changed = self.set_attributes_if_different(
file_args['path'], file_args['attributes'], changed, diff, expand
)
return changed
def check_file_absent_if_check_mode(self, file_path):
return self.check_mode and not os.path.exists(file_path)
def set_directory_attributes_if_different(self, file_args, changed, diff=None, expand=True):
return self.set_fs_attributes_if_different(file_args, changed, diff, expand)
def set_file_attributes_if_different(self, file_args, changed, diff=None, expand=True):
return self.set_fs_attributes_if_different(file_args, changed, diff, expand)
def add_path_info(self, kwargs):
'''
for results that are files, supplement the info about the file
in the return path with stats about the file path.
'''
path = kwargs.get('path', kwargs.get('dest', None))
if path is None:
return kwargs
b_path = to_bytes(path, errors='surrogate_or_strict')
if os.path.exists(b_path):
(uid, gid) = self.user_and_group(path)
kwargs['uid'] = uid
kwargs['gid'] = gid
try:
user = pwd.getpwuid(uid)[0]
except KeyError:
user = str(uid)
try:
group = grp.getgrgid(gid)[0]
except KeyError:
group = str(gid)
kwargs['owner'] = user
kwargs['group'] = group
st = os.lstat(b_path)
kwargs['mode'] = '0%03o' % stat.S_IMODE(st[stat.ST_MODE])
# secontext not yet supported
if os.path.islink(b_path):
kwargs['state'] = 'link'
elif os.path.isdir(b_path):
kwargs['state'] = 'directory'
elif os.stat(b_path).st_nlink > 1:
kwargs['state'] = 'hard'
else:
kwargs['state'] = 'file'
if HAVE_SELINUX and self.selinux_enabled():
kwargs['secontext'] = ':'.join(self.selinux_context(path))
kwargs['size'] = st[stat.ST_SIZE]
else:
kwargs['state'] = 'absent'
return kwargs
def _check_locale(self):
'''
Uses the locale module to test the currently set locale
(per the LANG and LC_CTYPE environment settings)
'''
try:
# setting the locale to '' uses the default locale
# as it would be returned by locale.getdefaultlocale()
locale.setlocale(locale.LC_ALL, '')
except locale.Error:
# fallback to the 'C' locale, which may cause unicode
# issues but is preferable to simply failing because
# of an unknown locale
locale.setlocale(locale.LC_ALL, 'C')
os.environ['LANG'] = 'C'
os.environ['LC_ALL'] = 'C'
os.environ['LC_MESSAGES'] = 'C'
except Exception as e:
self.fail_json(msg="An unknown error was encountered while attempting to validate the locale: %s" %
to_native(e), exception=traceback.format_exc())
def _handle_aliases(self, spec=None, param=None):
# this uses exceptions as it happens before we can safely call fail_json
aliases_results = {} # alias:canon
if param is None:
param = self.params
if spec is None:
spec = self.argument_spec
for (k, v) in spec.items():
self._legal_inputs.append(k)
aliases = v.get('aliases', None)
default = v.get('default', None)
required = v.get('required', False)
if default is not None and required:
# not alias specific but this is a good place to check this
raise Exception("internal error: required and default are mutually exclusive for %s" % k)
if aliases is None:
continue
if not isinstance(aliases, SEQUENCETYPE) or isinstance(aliases, (binary_type, text_type)):
raise Exception('internal error: aliases must be a list or tuple')
for alias in aliases:
self._legal_inputs.append(alias)
aliases_results[alias] = k
if alias in param:
param[k] = param[alias]
return aliases_results
def _handle_no_log_values(self, spec=None, param=None):
if spec is None:
spec = self.argument_spec
if param is None:
param = self.params
# Use the argspec to determine which args are no_log
for arg_name, arg_opts in spec.items():
if arg_opts.get('no_log', False):
# Find the value for the no_log'd param
no_log_object = param.get(arg_name, None)
if no_log_object:
self.no_log_values.update(return_values(no_log_object))
if arg_opts.get('removed_in_version') is not None and arg_name in param:
self._deprecations.append({
'msg': "Param '%s' is deprecated. See the module docs for more information" % arg_name,
'version': arg_opts.get('removed_in_version')
})
def _check_arguments(self, check_invalid_arguments, spec=None, param=None, legal_inputs=None):
self._syslog_facility = 'LOG_USER'
unsupported_parameters = set()
if spec is None:
spec = self.argument_spec
if param is None:
param = self.params
if legal_inputs is None:
legal_inputs = self._legal_inputs
for (k, v) in list(param.items()):
if check_invalid_arguments and k not in legal_inputs:
unsupported_parameters.add(k)
elif k.startswith('_ansible_'):
# handle setting internal properties from internal ansible vars
key = k.replace('_ansible_', '')
if key in PASS_BOOLS:
setattr(self, PASS_VARS[key], self.boolean(v))
else:
setattr(self, PASS_VARS[key], v)
# clean up internal params:
del self.params[k]
if unsupported_parameters:
msg = "Unsupported parameters for (%s) module: %s" % (self._name, ', '.join(sorted(list(unsupported_parameters))))
if self._options_context:
msg += " found in %s." % " -> ".join(self._options_context)
msg += " Supported parameters include: %s" % (', '.join(sorted(spec.keys())))
self.fail_json(msg=msg)
if self.check_mode and not self.supports_check_mode:
self.exit_json(skipped=True, msg="remote module (%s) does not support check mode" % self._name)
def _count_terms(self, check, param=None):
count = 0
if param is None:
param = self.params
for term in check:
if term in param:
count += 1
return count
def _check_mutually_exclusive(self, spec, param=None):
if spec is None:
return
for check in spec:
count = self._count_terms(check, param)
if count > 1:
msg = "parameters are mutually exclusive: %s" % ', '.join(check)
if self._options_context:
msg += " found in %s" % " -> ".join(self._options_context)
self.fail_json(msg=msg)
def _check_required_one_of(self, spec, param=None):
if spec is None:
return
for check in spec:
count = self._count_terms(check, param)
if count == 0:
msg = "one of the following is required: %s" % ', '.join(check)
if self._options_context:
msg += " found in %s" % " -> ".join(self._options_context)
self.fail_json(msg=msg)
def _check_required_together(self, spec, param=None):
if spec is None:
return
for check in spec:
counts = [self._count_terms([field], param) for field in check]
non_zero = [c for c in counts if c > 0]
if len(non_zero) > 0:
if 0 in counts:
msg = "parameters are required together: %s" % ', '.join(check)
if self._options_context:
msg += " found in %s" % " -> ".join(self._options_context)
self.fail_json(msg=msg)
def _check_required_arguments(self, spec=None, param=None):
''' ensure all required arguments are present '''
missing = []
if spec is None:
spec = self.argument_spec
if param is None:
param = self.params
for (k, v) in spec.items():
required = v.get('required', False)
if required and k not in param:
missing.append(k)
if len(missing) > 0:
msg = "missing required arguments: %s" % ", ".join(missing)
if self._options_context:
msg += " found in %s" % " -> ".join(self._options_context)
self.fail_json(msg=msg)
def _check_required_if(self, spec, param=None):
''' ensure that parameters which conditionally required are present '''
if spec is None:
return
if param is None:
param = self.params
for sp in spec:
missing = []
max_missing_count = 0
is_one_of = False
if len(sp) == 4:
key, val, requirements, is_one_of = sp
else:
key, val, requirements = sp
# is_one_of is True at least one requirement should be
# present, else all requirements should be present.
if is_one_of:
max_missing_count = len(requirements)
term = 'any'
else:
term = 'all'
if key in param and param[key] == val:
for check in requirements:
count = self._count_terms((check,), param)
if count == 0:
missing.append(check)
if len(missing) and len(missing) >= max_missing_count:
msg = "%s is %s but %s of the following are missing: %s" % (key, val, term, ', '.join(missing))
if self._options_context:
msg += " found in %s" % " -> ".join(self._options_context)
self.fail_json(msg=msg)
def _check_argument_values(self, spec=None, param=None):
''' ensure all arguments have the requested values, and there are no stray arguments '''
if spec is None:
spec = self.argument_spec
if param is None:
param = self.params
for (k, v) in spec.items():
choices = v.get('choices', None)
if choices is None:
continue
if isinstance(choices, SEQUENCETYPE) and not isinstance(choices, (binary_type, text_type)):
if k in param:
# Allow one or more when type='list' param with choices
if isinstance(param[k], list):
diff_list = ", ".join([item for item in param[k] if item not in choices])
if diff_list:
choices_str = ", ".join([to_native(c) for c in choices])
msg = "value of %s must be one or more of: %s. Got no match for: %s" % (k, choices_str, diff_list)
if self._options_context:
msg += " found in %s" % " -> ".join(self._options_context)
self.fail_json(msg=msg)
elif param[k] not in choices:
# PyYaml converts certain strings to bools. If we can unambiguously convert back, do so before checking
# the value. If we can't figure this out, module author is responsible.
lowered_choices = None
if param[k] == 'False':
lowered_choices = _lenient_lowercase(choices)
overlap = BOOLEANS_FALSE.intersection(choices)
if len(overlap) == 1:
# Extract from a set
(param[k],) = overlap
if param[k] == 'True':
if lowered_choices is None:
lowered_choices = _lenient_lowercase(choices)
overlap = BOOLEANS_TRUE.intersection(choices)
if len(overlap) == 1:
(param[k],) = overlap
if param[k] not in choices:
choices_str = ", ".join([to_native(c) for c in choices])
msg = "value of %s must be one of: %s, got: %s" % (k, choices_str, param[k])
if self._options_context:
msg += " found in %s" % " -> ".join(self._options_context)
self.fail_json(msg=msg)
else:
msg = "internal error: choices for argument %s are not iterable: %s" % (k, choices)
if self._options_context:
msg += " found in %s" % " -> ".join(self._options_context)
self.fail_json(msg=msg)
def safe_eval(self, value, locals=None, include_exceptions=False):
# do not allow method calls to modules
if not isinstance(value, string_types):
# already templated to a datavaluestructure, perhaps?
if include_exceptions:
return (value, None)
return value
if re.search(r'\w\.\w+\(', value):
if include_exceptions:
return (value, None)
return value
# do not allow imports
if re.search(r'import \w+', value):
if include_exceptions:
return (value, None)
return value
try:
result = literal_eval(value)
if include_exceptions:
return (result, None)
else:
return result
except Exception as e:
if include_exceptions:
return (value, e)
return value
def _check_type_str(self, value):
if isinstance(value, string_types):
return value
# Note: This could throw a unicode error if value's __str__() method
# returns non-ascii. Have to port utils.to_bytes() if that happens
return str(value)
def _check_type_list(self, value):
if isinstance(value, list):
return value
if isinstance(value, string_types):
return value.split(",")
elif isinstance(value, int) or isinstance(value, float):
return [str(value)]
raise TypeError('%s cannot be converted to a list' % type(value))
def _check_type_dict(self, value):
if isinstance(value, dict):
return value
if isinstance(value, string_types):
if value.startswith("{"):
try:
return json.loads(value)
except:
(result, exc) = self.safe_eval(value, dict(), include_exceptions=True)
if exc is not None:
raise TypeError('unable to evaluate string as dictionary')
return result
elif '=' in value:
fields = []
field_buffer = []
in_quote = False
in_escape = False
for c in value.strip():
if in_escape:
field_buffer.append(c)
in_escape = False
elif c == '\\':
in_escape = True
elif not in_quote and c in ('\'', '"'):
in_quote = c
elif in_quote and in_quote == c:
in_quote = False
elif not in_quote and c in (',', ' '):
field = ''.join(field_buffer)
if field:
fields.append(field)
field_buffer = []
else:
field_buffer.append(c)
field = ''.join(field_buffer)
if field:
fields.append(field)
return dict(x.split("=", 1) for x in fields)
else:
raise TypeError("dictionary requested, could not parse JSON or key=value")
raise TypeError('%s cannot be converted to a dict' % type(value))
def _check_type_bool(self, value):
if isinstance(value, bool):
return value
if isinstance(value, string_types) or isinstance(value, int):
return self.boolean(value)
raise TypeError('%s cannot be converted to a bool' % type(value))
def _check_type_int(self, value):
if isinstance(value, int):
return value
if isinstance(value, string_types):
return int(value)
raise TypeError('%s cannot be converted to an int' % type(value))
def _check_type_float(self, value):
if isinstance(value, float):
return value
if isinstance(value, (binary_type, text_type, int)):
return float(value)
raise TypeError('%s cannot be converted to a float' % type(value))
def _check_type_path(self, value):
value = self._check_type_str(value)
return os.path.expanduser(os.path.expandvars(value))
def _check_type_jsonarg(self, value):
# Return a jsonified string. Sometimes the controller turns a json
# string into a dict/list so transform it back into json here
if isinstance(value, (text_type, binary_type)):
return value.strip()
else:
if isinstance(value, (list, tuple, dict)):
return self.jsonify(value)
raise TypeError('%s cannot be converted to a json string' % type(value))
def _check_type_raw(self, value):
return value
def _check_type_bytes(self, value):
try:
self.human_to_bytes(value)
except ValueError:
raise TypeError('%s cannot be converted to a Byte value' % type(value))
def _check_type_bits(self, value):
try:
self.human_to_bytes(value, isbits=True)
except ValueError:
raise TypeError('%s cannot be converted to a Bit value' % type(value))
def _handle_options(self, argument_spec=None, params=None):
''' deal with options to create sub spec '''
if argument_spec is None:
argument_spec = self.argument_spec
if params is None:
params = self.params
for (k, v) in argument_spec.items():
wanted = v.get('type', None)
if wanted == 'dict' or (wanted == 'list' and v.get('elements', '') == 'dict'):
spec = v.get('options', None)
if v.get('apply_defaults', False):
if spec is not None:
if params.get(k) is None:
params[k] = {}
else:
continue
elif spec is None or k not in params or params[k] is None:
continue
self._options_context.append(k)
if isinstance(params[k], dict):
elements = [params[k]]
else:
elements = params[k]
for param in elements:
if not isinstance(param, dict):
self.fail_json(msg="value of %s must be of type dict or list of dict" % k)
self._set_fallbacks(spec, param)
options_aliases = self._handle_aliases(spec, param)
self._handle_no_log_values(spec, param)
options_legal_inputs = list(spec.keys()) + list(options_aliases.keys())
self._check_arguments(self.check_invalid_arguments, spec, param, options_legal_inputs)
# check exclusive early
if not self.bypass_checks:
self._check_mutually_exclusive(v.get('mutually_exclusive', None), param)
self._set_defaults(pre=True, spec=spec, param=param)
if not self.bypass_checks:
self._check_required_arguments(spec, param)
self._check_argument_types(spec, param)
self._check_argument_values(spec, param)
self._check_required_together(v.get('required_together', None), param)
self._check_required_one_of(v.get('required_one_of', None), param)
self._check_required_if(v.get('required_if', None), param)
self._set_defaults(pre=False, spec=spec, param=param)
# handle multi level options (sub argspec)
self._handle_options(spec, param)
self._options_context.pop()
def _check_argument_types(self, spec=None, param=None):
''' ensure all arguments have the requested type '''
if spec is None:
spec = self.argument_spec
if param is None:
param = self.params
for (k, v) in spec.items():
wanted = v.get('type', None)
if k not in param:
continue
value = param[k]
if value is None:
continue
if not callable(wanted):
if wanted is None:
# Mostly we want to default to str.
# For values set to None explicitly, return None instead as
# that allows a user to unset a parameter
if param[k] is None:
continue
wanted = 'str'
try:
type_checker = self._CHECK_ARGUMENT_TYPES_DISPATCHER[wanted]
except KeyError:
self.fail_json(msg="implementation error: unknown type %s requested for %s" % (wanted, k))
else:
# set the type_checker to the callable, and reset wanted to the callable's name (or type if it doesn't have one, ala MagicMock)
type_checker = wanted
wanted = getattr(wanted, '__name__', to_native(type(wanted)))
try:
param[k] = type_checker(value)
except (TypeError, ValueError) as e:
self.fail_json(msg="argument %s is of type %s and we were unable to convert to %s: %s" %
(k, type(value), wanted, to_native(e)))
def _set_defaults(self, pre=True, spec=None, param=None):
if spec is None:
spec = self.argument_spec
if param is None:
param = self.params
for (k, v) in spec.items():
default = v.get('default', None)
if pre is True:
# this prevents setting defaults on required items
if default is not None and k not in param:
param[k] = default
else:
# make sure things without a default still get set None
if k not in param:
param[k] = default
def _set_fallbacks(self, spec=None, param=None):
if spec is None:
spec = self.argument_spec
if param is None:
param = self.params
for (k, v) in spec.items():
fallback = v.get('fallback', (None,))
fallback_strategy = fallback[0]
fallback_args = []
fallback_kwargs = {}
if k not in param and fallback_strategy is not None:
for item in fallback[1:]:
if isinstance(item, dict):
fallback_kwargs = item
else:
fallback_args = item
try:
param[k] = fallback_strategy(*fallback_args, **fallback_kwargs)
except AnsibleFallbackNotFound:
continue
def _load_params(self):
''' read the input and set the params attribute.
This method is for backwards compatibility. The guts of the function
were moved out in 2.1 so that custom modules could read the parameters.
'''
# debug overrides to read args from file or cmdline
self.params = _load_params()
def _log_to_syslog(self, msg):
if HAS_SYSLOG:
module = 'ansible-%s' % self._name
facility = getattr(syslog, self._syslog_facility, syslog.LOG_USER)
syslog.openlog(str(module), 0, facility)
syslog.syslog(syslog.LOG_INFO, msg)
def debug(self, msg):
if self._debug:
self.log('[debug] %s' % msg)
def log(self, msg, log_args=None):
if not self.no_log:
if log_args is None:
log_args = dict()
module = 'ansible-%s' % self._name
if isinstance(module, binary_type):
module = module.decode('utf-8', 'replace')
# 6655 - allow for accented characters
if not isinstance(msg, (binary_type, text_type)):
raise TypeError("msg should be a string (got %s)" % type(msg))
# We want journal to always take text type
# syslog takes bytes on py2, text type on py3
if isinstance(msg, binary_type):
journal_msg = remove_values(msg.decode('utf-8', 'replace'), self.no_log_values)
else:
# TODO: surrogateescape is a danger here on Py3
journal_msg = remove_values(msg, self.no_log_values)
if PY3:
syslog_msg = journal_msg
else:
syslog_msg = journal_msg.encode('utf-8', 'replace')
if has_journal:
journal_args = [("MODULE", os.path.basename(__file__))]
for arg in log_args:
journal_args.append((arg.upper(), str(log_args[arg])))
try:
if HAS_SYSLOG:
# If syslog_facility specified, it needs to convert
# from the facility name to the facility code, and
# set it as SYSLOG_FACILITY argument of journal.send()
facility = getattr(syslog,
self._syslog_facility,
syslog.LOG_USER) >> 3
journal.send(MESSAGE=u"%s %s" % (module, journal_msg),
SYSLOG_FACILITY=facility,
**dict(journal_args))
else:
journal.send(MESSAGE=u"%s %s" % (module, journal_msg),
**dict(journal_args))
except IOError:
# fall back to syslog since logging to journal failed
self._log_to_syslog(syslog_msg)
else:
self._log_to_syslog(syslog_msg)
def _log_invocation(self):
''' log that ansible ran the module '''
# TODO: generalize a separate log function and make log_invocation use it
# Sanitize possible password argument when logging.
log_args = dict()
for param in self.params:
canon = self.aliases.get(param, param)
arg_opts = self.argument_spec.get(canon, {})
no_log = arg_opts.get('no_log', False)
if self.boolean(no_log):
log_args[param] = 'NOT_LOGGING_PARAMETER'
# try to capture all passwords/passphrase named fields missed by no_log
elif PASSWORD_MATCH.search(param) and arg_opts.get('type', 'str') != 'bool' and not arg_opts.get('choices', False):
# skip boolean and enums as they are about 'password' state
log_args[param] = 'NOT_LOGGING_PASSWORD'
self.warn('Module did not set no_log for %s' % param)
else:
param_val = self.params[param]
if not isinstance(param_val, (text_type, binary_type)):
param_val = str(param_val)
elif isinstance(param_val, text_type):
param_val = param_val.encode('utf-8')
log_args[param] = heuristic_log_sanitize(param_val, self.no_log_values)
msg = ['%s=%s' % (to_native(arg), to_native(val)) for arg, val in log_args.items()]
if msg:
msg = 'Invoked with %s' % ' '.join(msg)
else:
msg = 'Invoked'
self.log(msg, log_args=log_args)
def _set_cwd(self):
try:
cwd = os.getcwd()
if not os.access(cwd, os.F_OK | os.R_OK):
raise Exception()
return cwd
except:
# we don't have access to the cwd, probably because of sudo.
# Try and move to a neutral location to prevent errors
for cwd in [self.tmpdir, os.path.expandvars('$HOME'), tempfile.gettempdir()]:
try:
if os.access(cwd, os.F_OK | os.R_OK):
os.chdir(cwd)
return cwd
except:
pass
# we won't error here, as it may *not* be a problem,
# and we don't want to break modules unnecessarily
return None
def get_bin_path(self, arg, required=False, opt_dirs=None):
'''
find system executable in PATH.
Optional arguments:
- required: if executable is not found and required is true, fail_json
- opt_dirs: optional list of directories to search in addition to PATH
if found return full path; otherwise return None
'''
bin_path = None
try:
bin_path = get_bin_path(arg, required, opt_dirs)
except ValueError as e:
self.fail_json(msg=to_text(e))
return bin_path
def boolean(self, arg):
''' return a bool for the arg '''
if arg is None:
return arg
try:
return boolean(arg)
except TypeError as e:
self.fail_json(msg=to_native(e))
def jsonify(self, data):
try:
return jsonify(data)
except UnicodeError as e:
self.fail_json(msg=to_text(e))
def from_json(self, data):
return json.loads(data)
def add_cleanup_file(self, path):
if path not in self.cleanup_files:
self.cleanup_files.append(path)
def do_cleanup_files(self):
for path in self.cleanup_files:
self.cleanup(path)
def _return_formatted(self, kwargs):
self.add_path_info(kwargs)
if 'invocation' not in kwargs:
kwargs['invocation'] = {'module_args': self.params}
if 'warnings' in kwargs:
if isinstance(kwargs['warnings'], list):
for w in kwargs['warnings']:
self.warn(w)
else:
self.warn(kwargs['warnings'])
if self._warnings:
kwargs['warnings'] = self._warnings
if 'deprecations' in kwargs:
if isinstance(kwargs['deprecations'], list):
for d in kwargs['deprecations']:
if isinstance(d, SEQUENCETYPE) and len(d) == 2:
self.deprecate(d[0], version=d[1])
elif isinstance(d, Mapping):
self.deprecate(d['msg'], version=d.get('version', None))
else:
self.deprecate(d)
else:
self.deprecate(kwargs['deprecations'])
if self._deprecations:
kwargs['deprecations'] = self._deprecations
kwargs = remove_values(kwargs, self.no_log_values)
print('\n%s' % self.jsonify(kwargs))
def exit_json(self, **kwargs):
''' return from the module, without error '''
self.do_cleanup_files()
self._return_formatted(kwargs)
sys.exit(0)
def fail_json(self, **kwargs):
''' return from the module, with an error message '''
if 'msg' not in kwargs:
raise AssertionError("implementation error -- msg to explain the error is required")
kwargs['failed'] = True
# Add traceback if debug or high verbosity and it is missing
# NOTE: Badly named as exception, it really always has been a traceback
if 'exception' not in kwargs and sys.exc_info()[2] and (self._debug or self._verbosity >= 3):
if PY2:
# On Python 2 this is the last (stack frame) exception and as such may be unrelated to the failure
kwargs['exception'] = 'WARNING: The below traceback may *not* be related to the actual failure.\n' +\
''.join(traceback.format_tb(sys.exc_info()[2]))
else:
kwargs['exception'] = ''.join(traceback.format_tb(sys.exc_info()[2]))
self.do_cleanup_files()
self._return_formatted(kwargs)
sys.exit(1)
def fail_on_missing_params(self, required_params=None):
''' This is for checking for required params when we can not check via argspec because we
need more information than is simply given in the argspec.
'''
if not required_params:
return
missing_params = []
for required_param in required_params:
if not self.params.get(required_param):
missing_params.append(required_param)
if missing_params:
self.fail_json(msg="missing required arguments: %s" % ', '.join(missing_params))
def digest_from_file(self, filename, algorithm):
''' Return hex digest of local file for a digest_method specified by name, or None if file is not present. '''
if not os.path.exists(filename):
return None
if os.path.isdir(filename):
self.fail_json(msg="attempted to take checksum of directory: %s" % filename)
# preserve old behaviour where the third parameter was a hash algorithm object
if hasattr(algorithm, 'hexdigest'):
digest_method = algorithm
else:
try:
digest_method = AVAILABLE_HASH_ALGORITHMS[algorithm]()
except KeyError:
self.fail_json(msg="Could not hash file '%s' with algorithm '%s'. Available algorithms: %s" %
(filename, algorithm, ', '.join(AVAILABLE_HASH_ALGORITHMS)))
blocksize = 64 * 1024
infile = open(os.path.realpath(filename), 'rb')
block = infile.read(blocksize)
while block:
digest_method.update(block)
block = infile.read(blocksize)
infile.close()
return digest_method.hexdigest()
def md5(self, filename):
''' Return MD5 hex digest of local file using digest_from_file().
Do not use this function unless you have no other choice for:
1) Optional backwards compatibility
2) Compatibility with a third party protocol
This function will not work on systems complying with FIPS-140-2.
Most uses of this function can use the module.sha1 function instead.
'''
if 'md5' not in AVAILABLE_HASH_ALGORITHMS:
raise ValueError('MD5 not available. Possibly running in FIPS mode')
return self.digest_from_file(filename, 'md5')
def sha1(self, filename):
''' Return SHA1 hex digest of local file using digest_from_file(). '''
return self.digest_from_file(filename, 'sha1')
def sha256(self, filename):
''' Return SHA-256 hex digest of local file using digest_from_file(). '''
return self.digest_from_file(filename, 'sha256')
def backup_local(self, fn):
'''make a date-marked backup of the specified file, return True or False on success or failure'''
backupdest = ''
if os.path.exists(fn):
# backups named basename.PID.YYYY-MM-DD@HH:MM:SS~
ext = time.strftime("%Y-%m-%d@%H:%M:%S~", time.localtime(time.time()))
backupdest = '%s.%s.%s' % (fn, os.getpid(), ext)
try:
self.preserved_copy(fn, backupdest)
except (shutil.Error, IOError) as e:
self.fail_json(msg='Could not make backup of %s to %s: %s' % (fn, backupdest, to_native(e)))
return backupdest
def cleanup(self, tmpfile):
if os.path.exists(tmpfile):
try:
os.unlink(tmpfile)
except OSError as e:
sys.stderr.write("could not cleanup %s: %s" % (tmpfile, to_native(e)))
def preserved_copy(self, src, dest):
"""Copy a file with preserved ownership, permissions and context"""
# shutil.copy2(src, dst)
# Similar to shutil.copy(), but metadata is copied as well - in fact,
# this is just shutil.copy() followed by copystat(). This is similar
# to the Unix command cp -p.
#
# shutil.copystat(src, dst)
# Copy the permission bits, last access time, last modification time,
# and flags from src to dst. The file contents, owner, and group are
# unaffected. src and dst are path names given as strings.
shutil.copy2(src, dest)
# Set the context
if self.selinux_enabled():
context = self.selinux_context(src)
self.set_context_if_different(dest, context, False)
# chown it
try:
dest_stat = os.stat(src)
tmp_stat = os.stat(dest)
if dest_stat and (tmp_stat.st_uid != dest_stat.st_uid or tmp_stat.st_gid != dest_stat.st_gid):
os.chown(dest, dest_stat.st_uid, dest_stat.st_gid)
except OSError as e:
if e.errno != errno.EPERM:
raise
# Set the attributes
current_attribs = self.get_file_attributes(src)
current_attribs = current_attribs.get('attr_flags', '')
self.set_attributes_if_different(dest, current_attribs, True)
def atomic_move(self, src, dest, unsafe_writes=False):
'''atomically move src to dest, copying attributes from dest, returns true on success
it uses os.rename to ensure this as it is an atomic operation, rest of the function is
to work around limitations, corner cases and ensure selinux context is saved if possible'''
context = None
dest_stat = None
b_src = to_bytes(src, errors='surrogate_or_strict')
b_dest = to_bytes(dest, errors='surrogate_or_strict')
if os.path.exists(b_dest):
try:
dest_stat = os.stat(b_dest)
# copy mode and ownership
os.chmod(b_src, dest_stat.st_mode & PERM_BITS)
os.chown(b_src, dest_stat.st_uid, dest_stat.st_gid)
# try to copy flags if possible
if hasattr(os, 'chflags') and hasattr(dest_stat, 'st_flags'):
try:
os.chflags(b_src, dest_stat.st_flags)
except OSError as e:
for err in 'EOPNOTSUPP', 'ENOTSUP':
if hasattr(errno, err) and e.errno == getattr(errno, err):
break
else:
raise
except OSError as e:
if e.errno != errno.EPERM:
raise
if self.selinux_enabled():
context = self.selinux_context(dest)
else:
if self.selinux_enabled():
context = self.selinux_default_context(dest)
creating = not os.path.exists(b_dest)
try:
# Optimistically try a rename, solves some corner cases and can avoid useless work, throws exception if not atomic.
os.rename(b_src, b_dest)
except (IOError, OSError) as e:
if e.errno not in [errno.EPERM, errno.EXDEV, errno.EACCES, errno.ETXTBSY, errno.EBUSY]:
# only try workarounds for errno 18 (cross device), 1 (not permitted), 13 (permission denied)
# and 26 (text file busy) which happens on vagrant synced folders and other 'exotic' non posix file systems
self.fail_json(msg='Could not replace file: %s to %s: %s' % (src, dest, to_native(e)),
exception=traceback.format_exc())
else:
# Use bytes here. In the shippable CI, this fails with
# a UnicodeError with surrogateescape'd strings for an unknown
# reason (doesn't happen in a local Ubuntu16.04 VM)
b_dest_dir = os.path.dirname(b_dest)
b_suffix = os.path.basename(b_dest)
error_msg = None
tmp_dest_name = None
try:
tmp_dest_fd, tmp_dest_name = tempfile.mkstemp(prefix=b'.ansible_tmp',
dir=b_dest_dir, suffix=b_suffix)
except (OSError, IOError) as e:
error_msg = 'The destination directory (%s) is not writable by the current user. Error was: %s' % (os.path.dirname(dest), to_native(e))
except TypeError:
# We expect that this is happening because python3.4.x and
# below can't handle byte strings in mkstemp(). Traceback
# would end in something like:
# file = _os.path.join(dir, pre + name + suf)
# TypeError: can't concat bytes to str
error_msg = ('Failed creating tmp file for atomic move. This usually happens when using Python3 less than Python3.5. '
'Please use Python2.x or Python3.5 or greater.')
finally:
if error_msg:
if unsafe_writes:
self._unsafe_writes(b_src, b_dest)
else:
self.fail_json(msg=error_msg, exception=traceback.format_exc())
if tmp_dest_name:
b_tmp_dest_name = to_bytes(tmp_dest_name, errors='surrogate_or_strict')
try:
try:
# close tmp file handle before file operations to prevent text file busy errors on vboxfs synced folders (windows host)
os.close(tmp_dest_fd)
# leaves tmp file behind when sudo and not root
try:
shutil.move(b_src, b_tmp_dest_name)
except OSError:
# cleanup will happen by 'rm' of tmpdir
# copy2 will preserve some metadata
shutil.copy2(b_src, b_tmp_dest_name)
if self.selinux_enabled():
self.set_context_if_different(
b_tmp_dest_name, context, False)
try:
tmp_stat = os.stat(b_tmp_dest_name)
if dest_stat and (tmp_stat.st_uid != dest_stat.st_uid or tmp_stat.st_gid != dest_stat.st_gid):
os.chown(b_tmp_dest_name, dest_stat.st_uid, dest_stat.st_gid)
except OSError as e:
if e.errno != errno.EPERM:
raise
try:
os.rename(b_tmp_dest_name, b_dest)
except (shutil.Error, OSError, IOError) as e:
if unsafe_writes and e.errno == errno.EBUSY:
self._unsafe_writes(b_tmp_dest_name, b_dest)
else:
self.fail_json(msg='Unable to make %s into to %s, failed final rename from %s: %s' %
(src, dest, b_tmp_dest_name, to_native(e)),
exception=traceback.format_exc())
except (shutil.Error, OSError, IOError) as e:
self.fail_json(msg='Failed to replace file: %s to %s: %s' % (src, dest, to_native(e)),
exception=traceback.format_exc())
finally:
self.cleanup(b_tmp_dest_name)
if creating:
# make sure the file has the correct permissions
# based on the current value of umask
umask = os.umask(0)
os.umask(umask)
os.chmod(b_dest, DEFAULT_PERM & ~umask)
try:
os.chown(b_dest, os.geteuid(), os.getegid())
except OSError:
# We're okay with trying our best here. If the user is not
# root (or old Unices) they won't be able to chown.
pass
if self.selinux_enabled():
# rename might not preserve context
self.set_context_if_different(dest, context, False)
def _unsafe_writes(self, src, dest):
# sadly there are some situations where we cannot ensure atomicity, but only if
# the user insists and we get the appropriate error we update the file unsafely
try:
out_dest = in_src = None
try:
out_dest = open(dest, 'wb')
in_src = open(src, 'rb')
shutil.copyfileobj(in_src, out_dest)
finally: # assuring closed files in 2.4 compatible way
if out_dest:
out_dest.close()
if in_src:
in_src.close()
except (shutil.Error, OSError, IOError) as e:
self.fail_json(msg='Could not write data to file (%s) from (%s): %s' % (dest, src, to_native(e)),
exception=traceback.format_exc())
def _read_from_pipes(self, rpipes, rfds, file_descriptor):
data = b('')
if file_descriptor in rfds:
data = os.read(file_descriptor.fileno(), 9000)
if data == b(''):
rpipes.remove(file_descriptor)
return data
def _clean_args(self, args):
if not self._clean:
# create a printable version of the command for use in reporting later,
# which strips out things like passwords from the args list
to_clean_args = args
if PY2:
if isinstance(args, text_type):
to_clean_args = to_bytes(args)
else:
if isinstance(args, binary_type):
to_clean_args = to_text(args)
if isinstance(args, (text_type, binary_type)):
to_clean_args = shlex.split(to_clean_args)
clean_args = []
is_passwd = False
for arg in (to_native(a) for a in to_clean_args):
if is_passwd:
is_passwd = False
clean_args.append('********')
continue
if PASSWD_ARG_RE.match(arg):
sep_idx = arg.find('=')
if sep_idx > -1:
clean_args.append('%s=********' % arg[:sep_idx])
continue
else:
is_passwd = True
arg = heuristic_log_sanitize(arg, self.no_log_values)
clean_args.append(arg)
self._clean = ' '.join(shlex_quote(arg) for arg in clean_args)
return self._clean
def run_command(self, args, check_rc=False, close_fds=True, executable=None, data=None, binary_data=False, path_prefix=None, cwd=None,
use_unsafe_shell=False, prompt_regex=None, environ_update=None, umask=None, encoding='utf-8', errors='surrogate_or_strict',
expand_user_and_vars=True):
'''
Execute a command, returns rc, stdout, and stderr.
:arg args: is the command to run
* If args is a list, the command will be run with shell=False.
* If args is a string and use_unsafe_shell=False it will split args to a list and run with shell=False
* If args is a string and use_unsafe_shell=True it runs with shell=True.
:kw check_rc: Whether to call fail_json in case of non zero RC.
Default False
:kw close_fds: See documentation for subprocess.Popen(). Default True
:kw executable: See documentation for subprocess.Popen(). Default None
:kw data: If given, information to write to the stdin of the command
:kw binary_data: If False, append a newline to the data. Default False
:kw path_prefix: If given, additional path to find the command in.
This adds to the PATH environment vairable so helper commands in
the same directory can also be found
:kw cwd: If given, working directory to run the command inside
:kw use_unsafe_shell: See `args` parameter. Default False
:kw prompt_regex: Regex string (not a compiled regex) which can be
used to detect prompts in the stdout which would otherwise cause
the execution to hang (especially if no input data is specified)
:kw environ_update: dictionary to *update* os.environ with
:kw umask: Umask to be used when running the command. Default None
:kw encoding: Since we return native strings, on python3 we need to
know the encoding to use to transform from bytes to text. If you
want to always get bytes back, use encoding=None. The default is
"utf-8". This does not affect transformation of strings given as
args.
:kw errors: Since we return native strings, on python3 we need to
transform stdout and stderr from bytes to text. If the bytes are
undecodable in the ``encoding`` specified, then use this error
handler to deal with them. The default is ``surrogate_or_strict``
which means that the bytes will be decoded using the
surrogateescape error handler if available (available on all
python3 versions we support) otherwise a UnicodeError traceback
will be raised. This does not affect transformations of strings
given as args.
:kw expand_user_and_vars: When ``use_unsafe_shell=False`` this argument
dictates whether ``~`` is expanded in paths and environment variables
are expanded before running the command. When ``True`` a string such as
``$SHELL`` will be expanded regardless of escaping. When ``False`` and
``use_unsafe_shell=False`` no path or variable expansion will be done.
:returns: A 3-tuple of return code (integer), stdout (native string),
and stderr (native string). On python2, stdout and stderr are both
byte strings. On python3, stdout and stderr are text strings converted
according to the encoding and errors parameters. If you want byte
strings on python3, use encoding=None to turn decoding to text off.
'''
# used by clean args later on
self._clean = None
if not isinstance(args, (list, binary_type, text_type)):
msg = "Argument 'args' to run_command must be list or string"
self.fail_json(rc=257, cmd=args, msg=msg)
shell = False
if use_unsafe_shell:
# stringify args for unsafe/direct shell usage
if isinstance(args, list):
args = " ".join([shlex_quote(x) for x in args])
# not set explicitly, check if set by controller
if executable:
args = [executable, '-c', args]
elif self._shell not in (None, '/bin/sh'):
args = [self._shell, '-c', args]
else:
shell = True
else:
# ensure args are a list
if isinstance(args, (binary_type, text_type)):
# On python2.6 and below, shlex has problems with text type
# On python3, shlex needs a text type.
if PY2:
args = to_bytes(args, errors='surrogate_or_strict')
elif PY3:
args = to_text(args, errors='surrogateescape')
args = shlex.split(args)
# expand ``~`` in paths, and all environment vars
if expand_user_and_vars:
args = [os.path.expanduser(os.path.expandvars(x)) for x in args if x is not None]
else:
args = [x for x in args if x is not None]
prompt_re = None
if prompt_regex:
if isinstance(prompt_regex, text_type):
if PY3:
prompt_regex = to_bytes(prompt_regex, errors='surrogateescape')
elif PY2:
prompt_regex = to_bytes(prompt_regex, errors='surrogate_or_strict')
try:
prompt_re = re.compile(prompt_regex, re.MULTILINE)
except re.error:
self.fail_json(msg="invalid prompt regular expression given to run_command")
rc = 0
msg = None
st_in = None
# Manipulate the environ we'll send to the new process
old_env_vals = {}
# We can set this from both an attribute and per call
for key, val in self.run_command_environ_update.items():
old_env_vals[key] = os.environ.get(key, None)
os.environ[key] = val
if environ_update:
for key, val in environ_update.items():
old_env_vals[key] = os.environ.get(key, None)
os.environ[key] = val
if path_prefix:
old_env_vals['PATH'] = os.environ['PATH']
os.environ['PATH'] = "%s:%s" % (path_prefix, os.environ['PATH'])
# If using test-module and explode, the remote lib path will resemble ...
# /tmp/test_module_scratch/debug_dir/ansible/module_utils/basic.py
# If using ansible or ansible-playbook with a remote system ...
# /tmp/ansible_vmweLQ/ansible_modlib.zip/ansible/module_utils/basic.py
# Clean out python paths set by ansiballz
if 'PYTHONPATH' in os.environ:
pypaths = os.environ['PYTHONPATH'].split(':')
pypaths = [x for x in pypaths
if not x.endswith('/ansible_modlib.zip') and
not x.endswith('/debug_dir')]
os.environ['PYTHONPATH'] = ':'.join(pypaths)
if not os.environ['PYTHONPATH']:
del os.environ['PYTHONPATH']
if data:
st_in = subprocess.PIPE
kwargs = dict(
executable=executable,
shell=shell,
close_fds=close_fds,
stdin=st_in,
stdout=subprocess.PIPE,
stderr=subprocess.PIPE,
)
# store the pwd
prev_dir = os.getcwd()
# make sure we're in the right working directory
if cwd and os.path.isdir(cwd):
cwd = os.path.abspath(os.path.expanduser(cwd))
kwargs['cwd'] = cwd
try:
os.chdir(cwd)
except (OSError, IOError) as e:
self.fail_json(rc=e.errno, msg="Could not open %s, %s" % (cwd, to_native(e)),
exception=traceback.format_exc())
old_umask = None
if umask:
old_umask = os.umask(umask)
try:
if self._debug:
self.log('Executing: ' + self._clean_args(args))
cmd = subprocess.Popen(args, **kwargs)
# the communication logic here is essentially taken from that
# of the _communicate() function in ssh.py
stdout = b('')
stderr = b('')
rpipes = [cmd.stdout, cmd.stderr]
if data:
if not binary_data:
data += '\n'
if isinstance(data, text_type):
data = to_bytes(data)
cmd.stdin.write(data)
cmd.stdin.close()
while True:
rfds, wfds, efds = select.select(rpipes, [], rpipes, 1)
stdout += self._read_from_pipes(rpipes, rfds, cmd.stdout)
stderr += self._read_from_pipes(rpipes, rfds, cmd.stderr)
# if we're checking for prompts, do it now
if prompt_re:
if prompt_re.search(stdout) and not data:
if encoding:
stdout = to_native(stdout, encoding=encoding, errors=errors)
else:
stdout = stdout
return (257, stdout, "A prompt was encountered while running a command, but no input data was specified")
# only break out if no pipes are left to read or
# the pipes are completely read and
# the process is terminated
if (not rpipes or not rfds) and cmd.poll() is not None:
break
# No pipes are left to read but process is not yet terminated
# Only then it is safe to wait for the process to be finished
# NOTE: Actually cmd.poll() is always None here if rpipes is empty
elif not rpipes and cmd.poll() is None:
cmd.wait()
# The process is terminated. Since no pipes to read from are
# left, there is no need to call select() again.
break
cmd.stdout.close()
cmd.stderr.close()
rc = cmd.returncode
except (OSError, IOError) as e:
self.log("Error Executing CMD:%s Exception:%s" % (self._clean_args(args), to_native(e)))
self.fail_json(rc=e.errno, msg=to_native(e), cmd=self._clean_args(args))
except Exception as e:
self.log("Error Executing CMD:%s Exception:%s" % (self._clean_args(args), to_native(traceback.format_exc())))
self.fail_json(rc=257, msg=to_native(e), exception=traceback.format_exc(), cmd=self._clean_args(args))
# Restore env settings
for key, val in old_env_vals.items():
if val is None:
del os.environ[key]
else:
os.environ[key] = val
if old_umask:
os.umask(old_umask)
if rc != 0 and check_rc:
msg = heuristic_log_sanitize(stderr.rstrip(), self.no_log_values)
self.fail_json(cmd=self._clean_args(args), rc=rc, stdout=stdout, stderr=stderr, msg=msg)
# reset the pwd
os.chdir(prev_dir)
if encoding is not None:
return (rc, to_native(stdout, encoding=encoding, errors=errors),
to_native(stderr, encoding=encoding, errors=errors))
return (rc, stdout, stderr)
def append_to_file(self, filename, str):
filename = os.path.expandvars(os.path.expanduser(filename))
fh = open(filename, 'a')
fh.write(str)
fh.close()
def bytes_to_human(self, size):
return bytes_to_human(size)
# for backwards compatibility
pretty_bytes = bytes_to_human
def human_to_bytes(self, number, isbits=False):
return human_to_bytes(number, isbits)
#
# Backwards compat
#
# In 2.0, moved from inside the module to the toplevel
is_executable = is_executable
def get_module_path():
return os.path.dirname(os.path.realpath(__file__))
|
direvus/ansible
|
lib/ansible/module_utils/basic.py
|
Python
|
gpl-3.0
| 117,473
|
[
"VisIt"
] |
ccf0c6e5fc920ca900985a2595ea5bf43da9ecf1142767b53171b89c2bd73ff2
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.