import random
import datetime
import StringIO
from math import sqrt
from os import listdir, environ
from os.path import isfile, join, abspath, dirname
import csv
import json
import gzip
import urllib
import logging
from pprint import pprint
from csv import writer as csv_writer
from yaml import load as yaml_load
from flask import Flask
from flask import redirect, url_for, send_from_directory, abort
from flask import request
from jinja2 import Environment, FileSystemLoader
from netCDF4 import Dataset
# PATH RELATIVITY #############################################################
THIS_DIRECTORY = dirname(abspath(__file__))
def get_path(relative_path):
return abspath(join(THIS_DIRECTORY, relative_path))
# COLLECT GLOBAL INFORMATION FROM SOURCES #####################################
# VERSION
with open(get_path('../VERSION'), 'r') as version_file:
version = version_file.read().strip()
# CONFIG
with open(get_path('../config.yml'), 'r') as config_file:
config = yaml_load(config_file.read())
# LOGGING #####################################################################
log = logging.getLogger("HelioPropa")
log.setLevel(logging.INFO)
log.addHandler(logging.FileHandler(get_path('run.log')))
# SETUP FLASK ENGINE ##########################################################
app = Flask(__name__, root_path=THIS_DIRECTORY)
app.debug = environ.get('DEBUG') == 'true'
# SETUP JINJA2 TEMPLATE ENGINE ################################################
def static_global(filename):
return url_for('static', filename=filename)
def shuffle_filter(seq):
"""
This shuffles the sequence it is applied to.
'tis a failure of jinja2 to not provide a shuffle filter by default.
"""
try:
result = list(seq)
random.shuffle(result)
return result
except:
return seq
def markdown_filter(value, nl2br=False, p=True):
"""
nl2br: set to True to replace line breaks with
tags
p: set to False to remove the enclosing
", "").replace(r"
", "") return markdowned tpl_engine = Environment(loader=FileSystemLoader([get_path('view')]), trim_blocks=True, lstrip_blocks=True) tpl_engine.globals.update( url_for=url_for, static=static_global, ) tpl_engine.filters['markdown'] = markdown_filter tpl_engine.filters['md'] = markdown_filter tpl_engine.filters['shuffle'] = shuffle_filter tpl_global_vars = { 'request': request, 'version': version, 'config': config, 'now': datetime.datetime.now(), } # HELPERS ##################################################################### def render_view(view, context=None): """ A simple helper to render [view] template with [context] vars. It automatically adds the global template vars defined above, too. It returns a string, usually the HTML contents to display. """ context = {} if context is None else context return tpl_engine.get_template(view).render( dict(tpl_global_vars.items() + context.items()) ) # def render_page(page, title="My Page", context=None): # """ # A simple helper to render the md_page.html template with [context] vars & # the additional contents of `page/[page].md` in the `md_page` variable. # It automagically adds the global template vars defined above, too. # It returns a string, usually the HTML contents to display. # """ # if context is None: # context = {} # context['title'] = title # context['md_page'] = '' # with file(get_path('page/%s.md' % page)) as f: # context['md_page'] = f.read() # return tpl_engine.get_template('md_page.html').render( # dict(tpl_global_vars.items() + context.items()) # ) def datetime_from_list(time_list): """ Datetimes in retrieved CDFs are stored in lists of numbers, with DayOfYear starting at 0. We want it starting at 1 for default parsers. """ # Day Of Year starts at 0, but for our datetime parser it starts at 1 doy = '{:03d}'.format(int(''.join(time_list[4:7])) + 1) return datetime.datetime.strptime( "%s%s%s" % (''.join(time_list[0:4]), doy, ''.join(time_list[7:])), "%Y%j%H%M%S%f" ) def get_source_config(slug): for s in config['targets']: if s['slug'] == slug: return s raise Exception("No source found for slug '%s'." % slug) def retrieve_data(orbiter, what, started_at, stopped_at): """ Handles remote querying Myriam's API, downloading, extracting and caching the netCDF files. :param orbiter: key of the source in the YAML config :param what: either 'model' or 'orbit', a key in the config of the source :param started_at: :param stopped_at: :return: a list of local file paths to netCDF (.nc) files """ url = config['amda'].format( dataSet=what, startTime=started_at.isoformat(), stopTime=stopped_at.isoformat() ) response = urllib.urlopen(url) remote_gzip_files = json.loads(response.read()) if not remote_gzip_files or remote_gzip_files == 'NODATASET': abort(400, "Failed to fetch data at '%s'." % url) # retriever = urllib.URLopener() # would we need to do this every time ? local_gzip_files = [] for remote_gzip_file in remote_gzip_files: # removeme @Myriam if remote_gzip_file.endswith('/.gz'): continue remote_gzip_file = remote_gzip_file.replace('cdpp1', 'cdpp', 1) ######################### filename = "%s_%s" % (orbiter, str(remote_gzip_file).split('/')[-1]) local_gzip_file = get_path("../cache/%s" % filename) local_gzip_files.append(local_gzip_file) if not isfile(local_gzip_file): urllib.urlretrieve(remote_gzip_file, local_gzip_file) local_netc_files = [] for local_gzip_file in local_gzip_files: local_netc_file = local_gzip_file[0:-3] local_netc_files.append(local_netc_file) with gzip.open(local_gzip_file, 'rb') as f: file_content = f.read() with open(local_netc_file, 'w+b') as g: g.write(file_content) return local_netc_files # ROUTING ##################################################################### @app.route('/favicon.ico') def favicon(): return send_from_directory( join(app.root_path, 'static', 'img'), 'favicon.ico', mimetype='image/vnd.microsoft.icon' ) @app.route("/") @app.route("/home.html") @app.route("/index.html") def home(): return render_view('home.html.jinja2', { 'targets': config['targets'], 'planets': [s for s in config['targets'] if s['type'] == 'planet'], 'probes': [s for s in config['targets'] if s['type'] == 'probe'], 'comets': [s for s in config['targets'] if s['type'] == 'comet'], }) @app.route("/inspect") def analyze_cdf(): cdf_to_inspect = get_path("../res/dummy.nc") cdf_to_inspect = get_path("../res/dummy_jupiter_coordinates.nc") si = StringIO.StringIO() cw = csv.DictWriter(si, fieldnames=['Name', 'Shape', 'Length']) cw.writeheader() # Time, StartTime, StopTime, V, B, N, T, Delta_angle, P_dyn, QualityFlag cdf_handle = Dataset(cdf_to_inspect, "r", format="NETCDF4") for variable in cdf_handle.variables: v = cdf_handle.variables[variable] cw.writerow({ 'Name': variable, 'Shape': v.shape, 'Length': v.size, }) cdf_handle.close() return si.getvalue() @app.route("/