Blame view

web/run.py 37.7 KB
bde97e4d   Goutte   Add more changes ...
1
2
# coding=utf-8

9390ec89   Goutte   Initial experimen...
3
import StringIO
bc18b96c   Goutte   Implement first (...
4
import datetime
8644387c   Goutte   Use real data.
5
import gzip
bc18b96c   Goutte   Implement first (...
6
7
8
import json
import logging
import random
2fedd73b   Goutte   Initial implement...
9
import tarfile
bde97e4d   Goutte   Add more changes ...
10
import time
8644387c   Goutte   Use real data.
11
import urllib
9390ec89   Goutte   Initial experimen...
12
from csv import writer as csv_writer
bc18b96c   Goutte   Implement first (...
13
14
15
16
from math import sqrt
from os import environ, remove as removefile
from os.path import isfile, join, abspath, dirname

9390ec89   Goutte   Initial experimen...
17
from flask import Flask
9390ec89   Goutte   Initial experimen...
18
from flask import request
bc18b96c   Goutte   Implement first (...
19
from flask import url_for, send_from_directory, abort as abort_flask
bde97e4d   Goutte   Add more changes ...
20
from jinja2 import Environment, FileSystemLoader, Markup
57493104   Goutte   Add the time to t...
21
from netCDF4 import Dataset, date2num
bc18b96c   Goutte   Implement first (...
22
from yaml import load as yaml_load
9390ec89   Goutte   Initial experimen...
23
24
25
26
27
28
29

# PATH RELATIVITY #############################################################

THIS_DIRECTORY = dirname(abspath(__file__))


def get_path(relative_path):
a4a9ef03   Goutte   Cache generated C...
30
    """Get an absolute path from the relative path to this script directory."""
9390ec89   Goutte   Initial experimen...
31
32
33
34
35
36
37
38
39
40
41
42
43
    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())

c0df94bc   Goutte   Adding more logs.
44
45
FILE_DATE_FMT = "%Y-%m-%dT%H:%M:%S"

9390ec89   Goutte   Initial experimen...
46

f75faf5f   Goutte   WIP
47
48
# LOGGING #####################################################################

1324cc91   Goutte   Make the footer i...
49
50
LOG_FILE = get_path('run.log')

f75faf5f   Goutte   WIP
51
log = logging.getLogger("HelioPropa")
9bfa6c42   Goutte   More bug hunting.
52
log.setLevel(logging.DEBUG)
077980eb   Goutte   Improve availabil...
53
# log.setLevel(logging.ERROR)                        # <-- set log level here !
1324cc91   Goutte   Make the footer i...
54
logHandler = logging.FileHandler(LOG_FILE)
b2837a08   Goutte   Add three retries...
55
56
57
58
logHandler.setFormatter(logging.Formatter(
    "%(asctime)s - %(levelname)s - %(message)s"
))
log.addHandler(logHandler)
f75faf5f   Goutte   WIP
59
60


e18701b6   Goutte   Cache clear (remo...
61
62
# HARDCODED CONFIGURATION #####################################################

952e3d8f   Goutte   Move to another s...
63
64
65
# Absolute path to the installed CDF library from https://cdf.gsfc.nasa.gov/
CDF_LIB = '/usr/local/lib/libcdf'

e18701b6   Goutte   Cache clear (remo...
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
# Absolute path to the data cache directory
CACHE_DIR = get_path('../cache')

# These two configs are not in the YAML config because adding a new parameter
# will not work as-is, you'll have to edit some netcdf-related code.

# The slugs of the available parameters in the generated CSV files.
# The order matters. If you change this you also need to change the
# innermost loop of `get_data_for_target`.
# The javascript knows the targets' properties under these names.
PROPERTIES = ('time', 'vrad', 'vtan', 'vtot', 'btan', 'temp', 'pdyn', 'dens',
              'angl', 'xhee', 'yhee')

# The parameters that the users can handle.
# The slug MUST be one of the properties above.
PARAMETERS = {
    'pdyn': {
        'slug': 'pdyn',
        'name': 'Dyn. Pressure',
        'title': 'The dynamic pressure.',
        'units': 'nPa',
        'active': True,
        'position': 10,
    },
    'vtot': {
        'slug': 'vtot',
        'name': 'Velocity',
        'title': 'The velocity of the particles.',
        'units': 'km/s',
        'active': False,
        'position': 20,
    },
    'btan': {
        'slug': 'btan',
        'name': 'B Tangential',
        'title': 'B Tangential.',
        'units': 'nT',
        'active': False,
        'position': 30,
    },
    'temp': {
        'slug': 'temp',
        'name': 'Temperature',
60b73eb1   Goutte   Change temperatur...
109
110
        'title': 'The temperature.',
        'units': 'eV',
e18701b6   Goutte   Cache clear (remo...
111
112
113
114
115
116
117
        'active': False,
        'position': 40,
    },
    'dens': {
        'slug': 'dens',
        'name': 'Density',
        'title': 'The density N.',
aa7247d6   Goutte   Generate a CDF fi...
118
        'units': 'cm^-3',
e18701b6   Goutte   Cache clear (remo...
119
120
121
122
123
124
125
126
127
128
129
130
131
132
        'active': False,
        'position': 50,
    },
    'angl': {
        'slug': 'angl',
        'name': 'Angle T-S-E',
        'title': 'Angle Target-Sun-Earth.',
        'units': 'deg',
        'active': False,
        'position': 60,
    },
}


9390ec89   Goutte   Initial experimen...
133
134
135
136
# SETUP FLASK ENGINE ##########################################################

app = Flask(__name__, root_path=THIS_DIRECTORY)
app.debug = environ.get('DEBUG') == 'true'
b2837a08   Goutte   Add three retries...
137
if app.debug:
2fedd73b   Goutte   Initial implement...
138
    log.info("Starting Flask app IN DEBUG MODE...")
b2837a08   Goutte   Add three retries...
139
140
else:
    log.info("Starting Flask app...")
9390ec89   Goutte   Initial experimen...
141
142
143
144
145
146
147
148
149
150
151


# 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.
2fedd73b   Goutte   Initial implement...
152
    Jinja2 _should_ provide this.
9390ec89   Goutte   Initial experimen...
153
154
155
156
157
158
159
160
161
162
163
    """
    try:
        result = list(seq)
        random.shuffle(result)
        return result
    except:
        return seq


def markdown_filter(value, nl2br=False, p=True):
    """
2fedd73b   Goutte   Initial implement...
164
    Converts markdown into html.
9390ec89   Goutte   Initial experimen...
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
    nl2br: set to True to replace line breaks with <br> tags
    p: set to False to remove the enclosing <p></p> tags
    """
    from markdown import markdown
    from markdown.extensions.nl2br import Nl2BrExtension
    from markdown.extensions.abbr import AbbrExtension
    extensions = [AbbrExtension()]
    if nl2br is True:
        extensions.append(Nl2BrExtension())
    markdowned = markdown(value, output_format='html5', extensions=extensions)
    if p is False:
        markdowned = markdowned.replace(r"<p>", "").replace(r"</p>", "")
    return markdowned


bde97e4d   Goutte   Add more changes ...
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
_js_escapes = {
        '\\': '\\u005C',
        '\'': '\\u0027',
        '"': '\\u0022',
        '>': '\\u003E',
        '<': '\\u003C',
        '&': '\\u0026',
        '=': '\\u003D',
        '-': '\\u002D',
        ';': '\\u003B',
        u'\u2028': '\\u2028',
        u'\u2029': '\\u2029'
}
# Escape every ASCII character with a value less than 32.
_js_escapes.update(('%c' % z, '\\u%04X' % z) for z in xrange(32))


def escapejs_filter(value):
    escaped = []
    for letter in value:
        if letter in _js_escapes:
            escaped.append(_js_escapes[letter])
        else:
            escaped.append(letter)

    return Markup("".join(escaped))

9390ec89   Goutte   Initial experimen...
207
208
209
210
211
212
213
214
215
216
217
218
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
bde97e4d   Goutte   Add more changes ...
219
tpl_engine.filters['escapejs'] = escapejs_filter
9390ec89   Goutte   Initial experimen...
220
221
222
223
224
225
226
227
228
229
230

tpl_global_vars = {
    'request': request,
    'version': version,
    'config': config,
    'now': datetime.datetime.now(),
}


# HELPERS #####################################################################

57f42bd7   Goutte   Log the abortions.
231
232
233
234
235
def abort(code, message):
    log.error(message)
    abort_flask(code, message)


9390ec89   Goutte   Initial experimen...
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
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())
#     )

077980eb   Goutte   Improve availabil...
265

bc18b96c   Goutte   Implement first (...
266
267
268
269
270
271
272
def is_list_in_list(needle, haystack):
    for n in needle:
        if n not in haystack:
            return False
    return True


1324cc91   Goutte   Make the footer i...
273
274
275
276
277
278
279
280
281
282
283
284
285
def round_time(dt=None, round_to=60):
    """
    Round a datetime object to any time laps in seconds
    dt : datetime.datetime object, default now.
    roundTo : Closest number of seconds to round to, default 1 minute.
    """
    if dt is None:
        dt = datetime.datetime.now()
    seconds = (dt.replace(tzinfo=None) - dt.min).seconds
    rounding = (seconds + round_to / 2) // round_to * round_to
    return dt + datetime.timedelta(0, rounding-seconds, -dt.microsecond)


2d2af24b   Goutte   Add a basic orbit...
286
def datetime_from_list(time_list):
0b9821dd   Goutte   Clean up.
287
    """
2fedd73b   Goutte   Initial implement...
288
    Datetimes in retrieved CDFs are stored as lists of numbers,
80352490   Goutte   Multi model suppo...
289
290
    with DayOfYear starting at 0. We want it starting at 1 because it's what
    vendor parsers use, both in python and javascript.
0b9821dd   Goutte   Clean up.
291
    """
2d2af24b   Goutte   Add a basic orbit...
292
293
294
295
296
297
    # 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"
    )
9390ec89   Goutte   Initial experimen...
298

ce8af118   Goutte   Fix the favicon.
299

927c69c3   Goutte   Make the local ca...
300
301
302
303
304
305
306
307
308
309
310
311
312
313
def get_local_filename(url):
    """
    Build the local cache filename for the distant file
    :param url: string
    :return: string
    """
    from slugify import slugify
    n = len('http://')
    if url.startswith('https'):
        n += 1
    s = url[n:]
    return slugify(s)


180d7d97   Goutte   Refactor heavily.
314
def get_target_config(slug):
2fedd73b   Goutte   Initial implement...
315
    for s in config['targets']:  # dumb
8644387c   Goutte   Use real data.
316
317
        if s['slug'] == slug:
            return s
180d7d97   Goutte   Refactor heavily.
318
    raise Exception("No target found in configuration for '%s'." % slug)
8644387c   Goutte   Use real data.
319
320


180d7d97   Goutte   Refactor heavily.
321
322
323
324
325
def check_target_config(slug):
    get_target_config(slug)


def retrieve_amda_netcdf(orbiter, what, started_at, stopped_at):
8644387c   Goutte   Use real data.
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
    """
    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()
    )
c50cc9d8   Goutte   Continue fixing.
341
    log.info("Fetching remote gzip files list at '%s'." % url)
b2837a08   Goutte   Add three retries...
342
343
    retries = 0
    success = False
92abc15b   Goutte   Mistrust the API ...
344
    errors = []
b2837a08   Goutte   Add three retries...
345
346
347
348
349
350
351
352
    remote_gzip_files = []
    while not success and retries < 3:
        try:
            response = urllib.urlopen(url)
            remote_gzip_files = json.loads(response.read())
            if not remote_gzip_files:
                raise Exception("Failed to fetch data at '%s'." % url)
            if remote_gzip_files == 'NODATASET':
92abc15b   Goutte   Mistrust the API ...
353
354
355
                raise Exception("API says there's no dataset at '%s'." % url)
            if remote_gzip_files == 'ERROR':
                raise Exception("API returned an error at '%s'." % url)
077980eb   Goutte   Improve availabil...
356
            if remote_gzip_files == ['OUTOFTIME']:  # it happens
80352490   Goutte   Multi model suppo...
357
358
                return []
                # raise Exception("API says it's out of time at '%s'." % url)
b2837a08   Goutte   Add three retries...
359
360
361
            success = True
        except Exception as e:
            log.warn("Failed (%d/3) '%s' : %s" % (retries+1, url, e.message))
92abc15b   Goutte   Mistrust the API ...
362
363
            remote_gzip_files = []
            errors.append(e)
b2837a08   Goutte   Add three retries...
364
365
366
        finally:
            retries += 1
    if not remote_gzip_files:
08abc2d4   Goutte   Remove duplicate ...
367
368
369
370
        abort(400, "Failed to fetch gzip files list for %s at '%s' : %s" %
                   (orbiter, url, errors))
    else:
        remote_gzip_files = list(set(remote_gzip_files))
9bfa6c42   Goutte   More bug hunting.
371
372

    log.debug("Fetched remote gzip files list : %s." % str(remote_gzip_files))
8644387c   Goutte   Use real data.
373

8644387c   Goutte   Use real data.
374
375
    local_gzip_files = []
    for remote_gzip_file in remote_gzip_files:
077980eb   Goutte   Improve availabil...
376
377
378
        # hotfixes to remove when fixed upstream @Myriam
        if remote_gzip_file in ['OUTOFTIME', 'ERROR']:
            continue  # sometimes half the response is okay, the other not
8644387c   Goutte   Use real data.
379
        if remote_gzip_file.endswith('/.gz'):
80352490   Goutte   Multi model suppo...
380
            continue  # this is just a plain bug
8644387c   Goutte   Use real data.
381
        remote_gzip_file = remote_gzip_file.replace('cdpp1', 'cdpp', 1)
077980eb   Goutte   Improve availabil...
382
        ################################################
e18701b6   Goutte   Cache clear (remo...
383
        local_gzip_file = join(CACHE_DIR, get_local_filename(remote_gzip_file))
8644387c   Goutte   Use real data.
384
385
        local_gzip_files.append(local_gzip_file)
        if not isfile(local_gzip_file):
9bfa6c42   Goutte   More bug hunting.
386
            log.debug("Retrieving '%s'..." % local_gzip_file)
8644387c   Goutte   Use real data.
387
            urllib.urlretrieve(remote_gzip_file, local_gzip_file)
9bfa6c42   Goutte   More bug hunting.
388
            log.debug("Retrieved '%s'." % local_gzip_file)
dc0be992   Goutte   Support having no...
389
390
        else:
            log.debug("Found '%s' in the cache." % local_gzip_file)
8644387c   Goutte   Use real data.
391
392
393
394

    local_netc_files = []
    for local_gzip_file in local_gzip_files:
        local_netc_file = local_gzip_file[0:-3]
9bfa6c42   Goutte   More bug hunting.
395
        log.debug("Unzipping '%s'..." % local_gzip_file)
3c064b17   Goutte   Ignore failures w...
396
397
398
399
400
401
402
403
        success = True
        try:
            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)
        except Exception as e:
            success = False
dc0be992   Goutte   Support having no...
404
405
406
407
408
            log.error("Cannot process gz file '%s' from '%s' : %s" %
                      (local_gzip_file, url, e))
            # Sometimes, the downloaded gz is corrupted, and CRC checks fail.
            # We want to delete the local gz file and try again next time.
            removefile(local_gzip_file)
3c064b17   Goutte   Ignore failures w...
409
        if success:
dc0be992   Goutte   Support having no...
410
            local_netc_files.append(local_netc_file)
3c064b17   Goutte   Ignore failures w...
411
            log.debug("Unzipped '%s'." % local_gzip_file)
8644387c   Goutte   Use real data.
412

ea6c8d5d   Goutte   Add interval cons...
413
    return list(set(local_netc_files))  # remove possible dupes
8644387c   Goutte   Use real data.
414
415


180d7d97   Goutte   Refactor heavily.
416
417
418
419
420
def get_data_for_target(target_config, started_at, stopped_at):
    """
    :return: dict whose keys are datetime as str, values tuples of data
    """
    log.debug("Grabbing data for '%s'..." % target_config['slug'])
80352490   Goutte   Multi model suppo...
421

8644387c   Goutte   Use real data.
422
    try:
80352490   Goutte   Multi model suppo...
423
        models = target_config['models']
077980eb   Goutte   Improve availabil...
424
425
    except Exception as e:
        abort(500, "Invalid model configuration for '%s' : %s"
180d7d97   Goutte   Refactor heavily.
426
427
              % (target_config['slug'], str(e)))
    try:
80352490   Goutte   Multi model suppo...
428
        orbits = target_config['orbit']['models']
180d7d97   Goutte   Refactor heavily.
429
430
431
    except Exception as e:
        abort(500, "Invalid orbit configuration for '%s' : %s"
              % (target_config['slug'], str(e)))
28ef3790   Goutte   Clean up.
432

58bfe281   Goutte   Handle start and ...
433
434
435
436
437
438
439
440
441
442
443
    def _sta_sto(_cnf, _sta, _sto):
        if 'started_at' in _cnf:
            _s0 = datetime.datetime.strptime(_cnf['started_at'], FILE_DATE_FMT)
            _s0 = max(_s0, _sta)
        else:
            _s0 = _sta
        if 'stopped_at' in _cnf:
            _s1 = datetime.datetime.strptime(_cnf['stopped_at'], FILE_DATE_FMT)
            _s1 = min(_s1, _sto)
        else:
            _s1 = _sto
aa7247d6   Goutte   Generate a CDF fi...
444
        return _s0, _s1
80352490   Goutte   Multi model suppo...
445
446

    precision = "%Y-%m-%dT%H"  # model and orbits times are only equal-ish
180d7d97   Goutte   Refactor heavily.
447
    orbit_data = {}  # keys are datetime as str, values arrays of XY
ea6c8d5d   Goutte   Add interval cons...
448
449

    for orbit in orbits:
58bfe281   Goutte   Handle start and ...
450
        s0, s1 = _sta_sto(orbit, started_at, stopped_at)
ea6c8d5d   Goutte   Add interval cons...
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467

        orbit_files = retrieve_amda_netcdf(
            target_config['slug'], orbit['slug'], s0, s1
        )
        for orbit_file in orbit_files:
            log.debug("%s: opening orbit NETCDF4 '%s'..." %
                      (target_config['name'], orbit_file))
            cdf_handle = Dataset(orbit_file, "r", format="NETCDF4")
            times = cdf_handle.variables['Time']  # YYYY DOY HH MM SS .ms
            try:
                data_hee = cdf_handle.variables['HEE']
            except KeyError:
                data_hee = cdf_handle.variables['XYZ_HEE']  # p67 uses this

            log.debug("%s: aggregating data from '%s'..." %
                      (target_config['name'], orbit_file))
            for time, datum_hee in zip(times, data_hee):
1324cc91   Goutte   Make the footer i...
468
469
470
471
472
                try:
                    dtime = datetime_from_list(time)
                except Exception as e:
                    log.error("Failed to parse time from %s." % time)
                    raise e
ea6c8d5d   Goutte   Add interval cons...
473
                if s0 <= dtime <= s1:
1324cc91   Goutte   Make the footer i...
474
                    dkey = round_time(dtime, 60*60).strftime(precision)
ea6c8d5d   Goutte   Add interval cons...
475
476
                    orbit_data[dkey] = datum_hee
            cdf_handle.close()
180d7d97   Goutte   Refactor heavily.
477

8644387c   Goutte   Use real data.
478
    all_data = {}  # keys are datetime as str, values tuples of data
58bfe281   Goutte   Handle start and ...
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
    for model in models:
        s0, s1 = _sta_sto(model, started_at, stopped_at)
        model_files = retrieve_amda_netcdf(
            target_config['slug'], model['slug'], s0, s1
        )
        for model_file in model_files:
            # Time, StartTime, StopTime, V, B, N, T, Delta_angle, P_dyn
            log.debug("%s: opening model NETCDF4 '%s'..." %
                      (target_config['name'], model_file))
            cdf_handle = Dataset(model_file, "r", format="NETCDF4")
            times = cdf_handle.variables['Time']  # YYYY DOY HH MM SS .ms
            data_v = cdf_handle.variables['V']
            data_b = cdf_handle.variables['B']
            data_t = cdf_handle.variables['T']
            data_n = cdf_handle.variables['N']
            data_p = cdf_handle.variables['P_dyn']
            data_d = cdf_handle.variables['Delta_angle']
            log.debug("%s: aggregating data from '%s'..." %
                      (target_config['name'], model_file))
            for time, datum_v, datum_b, datum_t, datum_n, datum_p, datum_d \
                    in zip(times, data_v, data_b, data_t, data_n, data_p, data_d):
                vrad = datum_v[0]
                vtan = datum_v[1]
                try:
                    dtime = datetime_from_list(time)
                except Exception as e:
                    log.error("Failed to parse time from %s." % time)
                    raise e
                if s0 <= dtime <= s1:
                    dkey = round_time(dtime, 60*60).strftime(precision)
                    x_hee = None
                    y_hee = None
                    if dkey in orbit_data:
                        x_hee = orbit_data[dkey][0]
                        y_hee = orbit_data[dkey][1]
                    all_data[dkey] = (
                        dtime.strftime("%Y-%m-%dT%H:%M:%S+00:00"),
                        vrad, vtan, sqrt(vrad * vrad + vtan * vtan),
                        datum_b, datum_t, datum_n, datum_p, datum_d,
                        x_hee, y_hee
                    )
            cdf_handle.close()
8644387c   Goutte   Use real data.
521

180d7d97   Goutte   Refactor heavily.
522
523
524
525
526
527
528
529
530
531
532
533
534
    return all_data


def generate_csv_contents(target_slug, started_at, stopped_at):
    target_config = get_target_config(target_slug)
    log.debug("Crunching CSV contents for '%s'..." % target_config['name'])
    si = StringIO.StringIO()
    cw = csv_writer(si)
    cw.writerow(PROPERTIES)

    all_data = get_data_for_target(target_config, started_at, stopped_at)

    log.debug("Writing and sorting CSV for '%s'..." % target_config['slug'])
8644387c   Goutte   Use real data.
535
536
    for dkey in sorted(all_data):
        cw.writerow(all_data[dkey])
2d2af24b   Goutte   Add a basic orbit...
537

180d7d97   Goutte   Refactor heavily.
538
    log.info("Generated CSV contents for '%s'." % target_config['slug'])
2d2af24b   Goutte   Add a basic orbit...
539
540
    return si.getvalue()

8644387c   Goutte   Use real data.
541

180d7d97   Goutte   Refactor heavily.
542
543
def generate_csv_file_if_needed(target_slug, started_at, stopped_at):
    filename = "%s_%s_%s.csv" % (target_slug,
c0df94bc   Goutte   Adding more logs.
544
545
                                 started_at.strftime(FILE_DATE_FMT),
                                 stopped_at.strftime(FILE_DATE_FMT))
e18701b6   Goutte   Cache clear (remo...
546
    local_csv_file = join(CACHE_DIR, filename)
80352490   Goutte   Multi model suppo...
547
548
549
550
551
552
553
554
555
556
557
558
559

    generate = True
    if isfile(local_csv_file):
        # It need to have more than one line to not be empty (headers)
        with open(local_csv_file) as f:
            cnt = 0
            for _ in f:
                cnt += 1
                if cnt > 1:
                    generate = False
                    break

    if generate:
c0df94bc   Goutte   Adding more logs.
560
561
562
        log.info("Generating CSV '%s'..." % local_csv_file)
        try:
            with open(local_csv_file, mode="w+") as f:
180d7d97   Goutte   Refactor heavily.
563
                f.write(generate_csv_contents(target_slug,
c0df94bc   Goutte   Adding more logs.
564
565
566
567
                                              started_at=started_at,
                                              stopped_at=stopped_at))
            log.info("Generation of '%s' done." % filename)
        except Exception as e:
dc0be992   Goutte   Support having no...
568
            log.error(e)
5ede388f   Goutte   Make sure failed ...
569
            if isfile(local_csv_file):
92abc15b   Goutte   Mistrust the API ...
570
                log.warn("Removing failed CSV '%s'..." % local_csv_file)
5ede388f   Goutte   Make sure failed ...
571
                removefile(local_csv_file)
9bfa6c42   Goutte   More bug hunting.
572
            abort(500, "Failed creating CSV '%s' : %s" % (filename, e))
c0df94bc   Goutte   Adding more logs.
573
574


e18701b6   Goutte   Cache clear (remo...
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
def remove_all_files(in_directory):
    """
    Will throw if something horrible happens.
    Does not remove recursively (could be done with os.walk if needed).
    Does not remove directories either.
    :param in_directory: absolute path to directory
    :return:
    """
    import os

    if not os.path.isdir(in_directory):
        raise ValueError("No directory to clean at '%s'.")

    removed_files = []
    for file_name in os.listdir(in_directory):
        file_path = os.path.join(in_directory, file_name)
        if os.path.isfile(file_path):
            os.remove(file_path)
            removed_files.append(file_path)

    return removed_files


28bb4b28   Goutte   API for the cache...
598
599
def remove_files_created_before(date, in_directory):
    """
077980eb   Goutte   Improve availabil...
600
601
602
    Will throw if something horrible happens.
    Does not remove recursively (could be done with os.walk if needed).
    Does not remove directories either.
28bb4b28   Goutte   API for the cache...
603
    :param date: datetime object
077980eb   Goutte   Improve availabil...
604
    :param in_directory: absolute path to directory
28bb4b28   Goutte   API for the cache...
605
606
607
608
609
610
611
    :return:
    """
    import os
    import time

    secs = time.mktime(date.timetuple())

077980eb   Goutte   Improve availabil...
612
613
    if not os.path.isdir(in_directory):
        raise ValueError("No directory to clean at '%s'.")
28bb4b28   Goutte   API for the cache...
614
615
616
617

    removed_files = []
    for file_name in os.listdir(in_directory):
        file_path = os.path.join(in_directory, file_name)
077980eb   Goutte   Improve availabil...
618
619
620
621
622
        if os.path.isfile(file_path):
            t = os.stat(file_path)
            if t.st_ctime < secs:
                os.remove(file_path)
                removed_files.append(file_path)
28bb4b28   Goutte   API for the cache...
623
624
625
626

    return removed_files


077980eb   Goutte   Improve availabil...
627
628
629
630
631
632
633
634
635
636
637
def get_hit_counter():
    hit_count_path = get_path("../VISITS")

    if isfile(hit_count_path):
        hit_count = int(open(hit_count_path).read())
    else:
        hit_count = 1

    return hit_count


a4a9ef03   Goutte   Cache generated C...
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
def increment_hit_counter():
    hit_count_path = get_path("../VISITS")

    if isfile(hit_count_path):
        hit_count = int(open(hit_count_path).read())
        hit_count += 1
    else:
        hit_count = 1

    hit_counter_file = open(hit_count_path, 'w')
    hit_counter_file.write(str(hit_count))
    hit_counter_file.close()

    return hit_count


077980eb   Goutte   Improve availabil...
654
655
656
tpl_global_vars['visits'] = get_hit_counter()


a4a9ef03   Goutte   Cache generated C...
657
658
659
# ROUTING #####################################################################

@app.route('/favicon.ico')
bde97e4d   Goutte   Add more changes ...
660
def favicon():  # we want it served from the root, not from static/
a4a9ef03   Goutte   Cache generated C...
661
662
663
664
665
666
667
668
669
670
    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():
077980eb   Goutte   Improve availabil...
671
    increment_hit_counter()
bde97e4d   Goutte   Add more changes ...
672
673
    parameters = PARAMETERS.values()
    parameters.sort(key=lambda x: x['position'])
a4a9ef03   Goutte   Cache generated C...
674
675
    return render_view('home.html.jinja2', {
        'targets': config['targets'],
bde97e4d   Goutte   Add more changes ...
676
        'parameters': parameters,
a4a9ef03   Goutte   Cache generated C...
677
678
679
        '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'],
077980eb   Goutte   Improve availabil...
680
        'visits':  get_hit_counter(),
a4a9ef03   Goutte   Cache generated C...
681
682
683
    })


180d7d97   Goutte   Refactor heavily.
684
685
@app.route("/<target>_<started_at>_<stopped_at>.csv")
def download_target_csv(target, started_at, stopped_at):
a4a9ef03   Goutte   Cache generated C...
686
687
688
689
690
    """
    Grab data and orbit data for the specified `target`,
    rearrange it and return it as a CSV file.
    `started_at` and `stopped_at` should be UTC.
    """
180d7d97   Goutte   Refactor heavily.
691
    check_target_config(target)
a4a9ef03   Goutte   Cache generated C...
692
    try:
c0df94bc   Goutte   Adding more logs.
693
        started_at = datetime.datetime.strptime(started_at, FILE_DATE_FMT)
a4a9ef03   Goutte   Cache generated C...
694
695
696
    except:
        abort(400, "Invalid started_at parameter : '%s'." % started_at)
    try:
c0df94bc   Goutte   Adding more logs.
697
        stopped_at = datetime.datetime.strptime(stopped_at, FILE_DATE_FMT)
a4a9ef03   Goutte   Cache generated C...
698
699
700
    except:
        abort(400, "Invalid stopped_at parameter : '%s'." % stopped_at)

180d7d97   Goutte   Refactor heavily.
701
    filename = "%s_%s_%s.csv" % (target,
c0df94bc   Goutte   Adding more logs.
702
703
                                 started_at.strftime(FILE_DATE_FMT),
                                 stopped_at.strftime(FILE_DATE_FMT))
e18701b6   Goutte   Cache clear (remo...
704
    local_csv_file = join(CACHE_DIR, filename)
180d7d97   Goutte   Refactor heavily.
705
    generate_csv_file_if_needed(target, started_at, stopped_at)
a4a9ef03   Goutte   Cache generated C...
706
707
708
    if not isfile(local_csv_file):
        abort(500, "Could not cache CSV file at '%s'." % local_csv_file)

e18701b6   Goutte   Cache clear (remo...
709
    return send_from_directory(CACHE_DIR, filename)
a4a9ef03   Goutte   Cache generated C...
710
711


0511eed7   Goutte   Tarball generatio...
712
713
@app.route("/<targets>_<started_at>_<stopped_at>.tar.gz")
def download_targets_tarball(targets, started_at, stopped_at):
b2837a08   Goutte   Add three retries...
714
    """
bc18b96c   Goutte   Implement first (...
715
716
717
    Grab data and orbit data for each of the specified `targets`,
    in their own CSV file, and make a tarball of them.
    `started_at` and `stopped_at` should be UTC strings.
b2837a08   Goutte   Add three retries...
718

ea6c8d5d   Goutte   Add interval cons...
719
720
    Note: we do not use this route anymore, but let's keep it shelved for now.

2fedd73b   Goutte   Initial implement...
721
    targets: string list of targets' slugs, separated by `-`.
b2837a08   Goutte   Add three retries...
722
    """
2fedd73b   Goutte   Initial implement...
723
    separator = '-'
0511eed7   Goutte   Tarball generatio...
724
725
    targets = targets.split(separator)
    targets.sort()
2fedd73b   Goutte   Initial implement...
726
727
    targets_configs = []
    for target in targets:
b2837a08   Goutte   Add three retries...
728
729
        if not target:
            abort(400, "Invalid targets format : `%s`." % targets)
180d7d97   Goutte   Refactor heavily.
730
        targets_configs.append(get_target_config(target))
2fedd73b   Goutte   Initial implement...
731
    if 0 == len(targets_configs):
b2837a08   Goutte   Add three retries...
732
733
        abort(400, "No valid targets specified. What are you doing?")

b2837a08   Goutte   Add three retries...
734
    try:
ea6c8d5d   Goutte   Add interval cons...
735
        started_at = datetime.datetime.strptime(started_at, FILE_DATE_FMT)
b2837a08   Goutte   Add three retries...
736
737
738
    except:
        abort(400, "Invalid started_at parameter : '%s'." % started_at)
    try:
ea6c8d5d   Goutte   Add interval cons...
739
        stopped_at = datetime.datetime.strptime(stopped_at, FILE_DATE_FMT)
b2837a08   Goutte   Add three retries...
740
741
    except:
        abort(400, "Invalid stopped_at parameter : '%s'." % stopped_at)
ea6c8d5d   Goutte   Add interval cons...
742
743
    sta = started_at.strftime(FILE_DATE_FMT)
    sto = stopped_at.strftime(FILE_DATE_FMT)
b2837a08   Goutte   Add three retries...
744

0511eed7   Goutte   Tarball generatio...
745
    gzip_filename = "%s_%s_%s.tar.gz" % (separator.join(targets), sta, sto)
e18701b6   Goutte   Cache clear (remo...
746
    local_gzip_file = join(CACHE_DIR, gzip_filename)
2fedd73b   Goutte   Initial implement...
747
748

    if not isfile(local_gzip_file):
0511eed7   Goutte   Tarball generatio...
749
        log.debug("Creating the CSV files for the tarball...")
2fedd73b   Goutte   Initial implement...
750
        for target_config in targets_configs:
0511eed7   Goutte   Tarball generatio...
751
            filename = "%s_%s_%s.csv" % (target_config['slug'], sta, sto)
e18701b6   Goutte   Cache clear (remo...
752
            local_csv_file = join(CACHE_DIR, filename)
2fedd73b   Goutte   Initial implement...
753
754
            if not isfile(local_csv_file):
                with open(local_csv_file, mode="w+") as f:
180d7d97   Goutte   Refactor heavily.
755
                    f.write(generate_csv_contents(target_config['slug'],
2fedd73b   Goutte   Initial implement...
756
757
758
                                                  started_at=started_at,
                                                  stopped_at=stopped_at))

0511eed7   Goutte   Tarball generatio...
759
        log.debug("Creating the tarball '%s'..." % local_gzip_file)
2fedd73b   Goutte   Initial implement...
760
761
        with tarfile.open(local_gzip_file, "w:gz") as tar:
            for target_config in targets_configs:
0511eed7   Goutte   Tarball generatio...
762
                filename = "%s_%s_%s.csv" % (target_config['slug'], sta, sto)
e18701b6   Goutte   Cache clear (remo...
763
                local_csv_file = join(CACHE_DIR, filename)
2fedd73b   Goutte   Initial implement...
764
765
766
                tar.add(local_csv_file, arcname=filename)

    if not isfile(local_gzip_file):
0511eed7   Goutte   Tarball generatio...
767
        abort(500, "No tarball to serve. Looked at '%s'." % local_gzip_file)
2fedd73b   Goutte   Initial implement...
768

e18701b6   Goutte   Cache clear (remo...
769
    return send_from_directory(CACHE_DIR, gzip_filename)
b2837a08   Goutte   Add three retries...
770

28bb4b28   Goutte   API for the cache...
771

bc18b96c   Goutte   Implement first (...
772
773
774
775
@app.route("/<targets>_<params>_<started_at>_<stopped_at>.nc")
def download_targets_netcdf(targets, params, started_at, stopped_at):
    """
    Grab data and orbit data for the specified `target`,
aa7247d6   Goutte   Generate a CDF fi...
776
    rearrange it and return it as a NetCDF file.
e18701b6   Goutte   Cache clear (remo...
777
    `started_at` and `stopped_at` are expected to be UTC.
bc18b96c   Goutte   Implement first (...
778
779
780
781

    targets: string list of targets' slugs, separated by `-`.
    params: string list of targets' parameters, separated by `-`.
    """
e18701b6   Goutte   Cache clear (remo...
782
    separator = '-'  # /!\ this char should never be in target's slugs
bc18b96c   Goutte   Implement first (...
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
    targets = targets.split(separator)
    targets.sort()
    targets_configs = []
    for target in targets:
        if not target:
            abort(400, "Invalid targets format : `%s`." % targets)
        targets_configs.append(get_target_config(target))
    if 0 == len(targets_configs):
        abort(400, "No valid targets specified. What are you doing?")
    params = params.split(separator)
    params.sort()
    if 0 == len(params):
        abort(400, "No valid parameters specified. What are you doing?")
    if not is_list_in_list(params, PARAMETERS.keys()):
        abort(400, "Some parameters are not recognized in '%s'." % str(params))

57493104   Goutte   Add the time to t...
799
    date_fmt = FILE_DATE_FMT
bc18b96c   Goutte   Implement first (...
800
801
802
803
804
805
806
807
808
809
810
811
812
    try:
        started_at = datetime.datetime.strptime(started_at, date_fmt)
    except:
        abort(400, "Invalid started_at parameter : '%s'." % started_at)
    try:
        stopped_at = datetime.datetime.strptime(stopped_at, date_fmt)
    except:
        abort(400, "Invalid stopped_at parameter : '%s'." % stopped_at)
    sta = started_at.strftime(date_fmt)
    sto = stopped_at.strftime(date_fmt)

    nc_filename = "%s_%s_%s_%s.nc" % \
                  (separator.join(targets), separator.join(params), sta, sto)
e18701b6   Goutte   Cache clear (remo...
813
    nc_path = join(CACHE_DIR, nc_filename)
bc18b96c   Goutte   Implement first (...
814
815
816
817
818

    if not isfile(nc_path):
        log.debug("Creating the NetCDF file '%s'..." % nc_filename)
        nc_handle = Dataset(nc_path, "w", format="NETCDF4")
        try:
ea6c8d5d   Goutte   Add interval cons...
819
            nc_handle.description = "Model and orbit data for targets"  # todo
bc18b96c   Goutte   Implement first (...
820
            nc_handle.history = "Created " + time.ctime(time.time())
ea6c8d5d   Goutte   Add interval cons...
821
            nc_handle.source = "Heliopropa (CDDP)"
bc18b96c   Goutte   Implement first (...
822
823
824
825
826
827
828
            available_params = list(PROPERTIES)
            for target in targets_configs:
                target_slug = target['slug']
                log.debug("Adding group '%s' to the NetCDF..." % target_slug)
                nc_group = nc_handle.createGroup(target_slug)
                data = get_data_for_target(target, started_at, stopped_at)
                dkeys = sorted(data)
ceeb2f4a   Goutte   Add the target co...
829
830
                dimension = 'dim_'+target_slug
                nc_handle.createDimension(dimension, len(dkeys))
57493104   Goutte   Add the time to t...
831
832

                # TIME #
ceeb2f4a   Goutte   Add the target co...
833
                nc_time = nc_group.createVariable('time', 'i8', (dimension,))
57493104   Goutte   Add the time to t...
834
835
836
837
838
839
840
841
842
843
844
845
                nc_time.units = "hours since 1970-01-01 00:00:00"
                nc_time.calendar = "standard"
                times = []
                for dkey in dkeys:
                    time_as_string = data[dkey][0][:-6]  # remove +00:00 tail
                    date = datetime.datetime.strptime(time_as_string, date_fmt)
                    times.append(date2num(
                        date, units=nc_time.units, calendar=nc_time.calendar
                    ))
                nc_time[:] = times

                # SELECTED PARAMETERS #
bc18b96c   Goutte   Implement first (...
846
847
848
849
                nc_vars = []
                indices = []
                for param in params:
                    indices.append(available_params.index(param))
ceeb2f4a   Goutte   Add the target co...
850
                    nc_var = nc_group.createVariable(param, 'f8', (dimension,))
5a6d4498   Goutte   Add a title to ea...
851
                    nc_var.units = PARAMETERS[param]['units']
bc18b96c   Goutte   Implement first (...
852
853
854
855
856
857
858
859
                    nc_vars.append(nc_var)
                for i, nc_var in enumerate(nc_vars):
                    index = indices[i]
                    values = []
                    for dkey in dkeys:
                        dval = data[dkey]
                        values.append(dval[index])
                    nc_var[:] = values
ceeb2f4a   Goutte   Add the target co...
860
861

                # ORBIT #
6491a1f1   Goutte   Fix up the bugs l...
862
                nc_x = nc_group.createVariable('xhee', 'f8', (dimension,))
ceeb2f4a   Goutte   Add the target co...
863
                nc_x.units = 'Au'
6491a1f1   Goutte   Fix up the bugs l...
864
                nc_y = nc_group.createVariable('yhee', 'f8', (dimension,))
ceeb2f4a   Goutte   Add the target co...
865
866
867
                nc_y.units = 'Au'
                values_x = []
                values_y = []
6491a1f1   Goutte   Fix up the bugs l...
868
869
                index_x = available_params.index('xhee')
                index_y = available_params.index('yhee')
ceeb2f4a   Goutte   Add the target co...
870
871
872
873
874
875
876
877
                for dkey in dkeys:
                    dval = data[dkey]
                    values_x.append(dval[index_x])
                    values_y.append(dval[index_y])
                nc_x[:] = values_x
                nc_y[:] = values_y
            log.debug("Writing NetCDF '%s'..." % nc_filename)

bc18b96c   Goutte   Implement first (...
878
        except Exception as e:
57493104   Goutte   Add the time to t...
879
            log.error("Failed to generate NetCDF '%s'." % nc_filename)
bc18b96c   Goutte   Implement first (...
880
881
882
883
884
885
886
            raise e
        finally:
            nc_handle.close()

    if not isfile(nc_path):
        abort(500, "No NetCDF to serve. Looked at '%s'." % nc_path)

e18701b6   Goutte   Cache clear (remo...
887
    return send_from_directory(CACHE_DIR, nc_filename)
bc18b96c   Goutte   Implement first (...
888
889


aa7247d6   Goutte   Generate a CDF fi...
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
@app.route("/<targets>_<started_at>_<stopped_at>.cdf")
def download_targets_cdf(targets, started_at, stopped_at):
    """
    Grab data and orbit data for the specified `target`,
    rearrange it and return it as a CDF file.
    `started_at` and `stopped_at` are expected to be UTC.

    targets: string list of targets' slugs, separated by `-`.
    params: string list of targets' parameters, separated by `-`.
    """
    separator = '-'  # /!\ this char should never be in target's slugs
    targets = targets.split(separator)
    targets.sort()
    targets_configs = []
    for target in targets:
        if not target:
            abort(400, "Invalid targets format : `%s`." % targets)
        targets_configs.append(get_target_config(target))
    if 0 == len(targets_configs):
        abort(400, "No valid targets specified. What are you doing?")

    params = PARAMETERS.keys()
    # params = params.split(separator)
    # params.sort()
    # if 0 == len(params):
    #     abort(400, "No valid parameters specified. What are you doing?")
    # if not is_list_in_list(params, PARAMETERS.keys()):
    #     abort(400, "Some parameters are not recognized in '%s'." % str(params))

    try:
        started_at = datetime.datetime.strptime(started_at, FILE_DATE_FMT)
    except:
        abort(400, "Invalid started_at parameter : '%s'." % started_at)
    try:
        stopped_at = datetime.datetime.strptime(stopped_at, FILE_DATE_FMT)
    except:
        abort(400, "Invalid stopped_at parameter : '%s'." % stopped_at)
    sta = started_at.strftime(FILE_DATE_FMT)
    sto = stopped_at.strftime(FILE_DATE_FMT)

    cdf_filename = "%s_%s_%s.cdf" % (separator.join(targets), sta, sto)
    cdf_path = join(CACHE_DIR, cdf_filename)

    if not isfile(cdf_path):
        log.debug("Creating the CDF file '%s'..." % cdf_filename)
952e3d8f   Goutte   Move to another s...
935
936
        environ['CDF_LIB'] = CDF_LIB
        from spacepy import pycdf
aa7247d6   Goutte   Generate a CDF fi...
937
        try:
952e3d8f   Goutte   Move to another s...
938
            cdf_handle = pycdf.CDF(cdf_path, masterpath='')
aa7247d6   Goutte   Generate a CDF fi...
939
940
            description = "Model and orbit data for %s." % \
                ', '.join([t['name'] for t in targets_configs])
952e3d8f   Goutte   Move to another s...
941
942
943
            cdf_handle.attrs['Description'] = description
            cdf_handle.attrs['Author'] = "Heliopropa.irap.omp.eu (CDPP)"
            cdf_handle.attrs['Created'] = str(time.ctime(time.time()))
aa7247d6   Goutte   Generate a CDF fi...
944
945
946
947
948
949
950
951

            available_params = list(PROPERTIES)
            for target in targets_configs:
                target_slug = target['slug']
                data = get_data_for_target(target, started_at, stopped_at)
                dkeys = sorted(data)

                values = []
aa7247d6   Goutte   Generate a CDF fi...
952
                for dkey in dkeys:
952e3d8f   Goutte   Move to another s...
953
954
955
956
957
958
                    time_str = data[dkey][0][:-6]  # remove +00:00 tail
                    date = datetime.datetime.strptime(time_str, FILE_DATE_FMT)
                    values.append(date)
                kt = "%s_time" % target_slug
                cdf_handle[kt] = values
                cdf_handle[kt].attrs['FIELDNAM'] = "Time since 0 A.D"
aa7247d6   Goutte   Generate a CDF fi...
959
960
961
962
963
964
965
966

                for param in params:
                    k = "%s_%s" % (target_slug, param)
                    values = []
                    i = available_params.index(param)
                    for dkey in dkeys:
                        values.append(data[dkey][i])
                    cdf_handle[k] = values
952e3d8f   Goutte   Move to another s...
967
968
969
970
971
972
973
974
975
976
                    attrs = cdf_handle[k].attrs
                    attrs['UNITS'] = PARAMETERS[param]['units']
                    attrs['LABLAXIS'] = PARAMETERS[param]['name']
                    attrs['FIELDNAM'] = PARAMETERS[param]['title']
                    if values:
                        attrs['VALIDMIN'] = min(values)
                        attrs['VALIDMAX'] = max(values)

                kx = "%s_xhee" % target_slug
                ky = "%s_yhee" % target_slug
aa7247d6   Goutte   Generate a CDF fi...
977
978
979
980
981
982
983
                values_xhee = []
                values_yhee = []
                index_x = available_params.index('xhee')
                index_y = available_params.index('yhee')
                for dkey in dkeys:
                    values_xhee.append(data[dkey][index_x])
                    values_yhee.append(data[dkey][index_y])
952e3d8f   Goutte   Move to another s...
984
985
986
987
                cdf_handle[kx] = values_xhee
                cdf_handle[ky] = values_yhee
                cdf_handle[kx].attrs['UNITS'] = 'Au'
                cdf_handle[ky].attrs['UNITS'] = 'Au'
aa7247d6   Goutte   Generate a CDF fi...
988
989

            log.debug("Writing CDF '%s'..." % cdf_filename)
952e3d8f   Goutte   Move to another s...
990
991
            cdf_handle.close()
            log.debug("Wrote CDF '%s'." % cdf_filename)
aa7247d6   Goutte   Generate a CDF fi...
992
993
994

        except Exception as e:
            log.error("Failed to generate CDF '%s'." % cdf_filename)
952e3d8f   Goutte   Move to another s...
995
996
            if isfile(cdf_path):
                removefile(cdf_path)
aa7247d6   Goutte   Generate a CDF fi...
997
998
            raise

aa7247d6   Goutte   Generate a CDF fi...
999
1000
1001
1002
1003
1004
    if not isfile(cdf_path):
        abort(500, "No CDF to serve. Looked at '%s'." % cdf_path)

    return send_from_directory(CACHE_DIR, cdf_filename)


28bb4b28   Goutte   API for the cache...
1005
1006
# API #########################################################################

e18701b6   Goutte   Cache clear (remo...
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
@app.route("/cache/clear")
def cache_clear():
    """
    Removes all files from the cache.
    Note: It also removes the .gitkeep file. Not a problem for prod.
    """
    removed_files = remove_all_files(CACHE_DIR)
    count = len(removed_files)
    return "Cache cleared! Removed %d file%s." \
           % (count, 's' if count != 1 else '')


d9710a98   Goutte   Rename the cleanu...
1019
1020
@app.route("/cache/cleanup")
def cache_cleanup():
28bb4b28   Goutte   API for the cache...
1021
1022
    """
    Removes all files from the cache that are older than roughly one month.
e18701b6   Goutte   Cache clear (remo...
1023
    Note: It also removes the .gitkeep file. Maybe it should not, but hey.
28bb4b28   Goutte   API for the cache...
1024
1025
    """
    a_month_ago = datetime.datetime.now() - datetime.timedelta(days=32)
e18701b6   Goutte   Cache clear (remo...
1026
    removed_files = remove_files_created_before(a_month_ago, CACHE_DIR)
d9710a98   Goutte   Rename the cleanu...
1027
1028
1029
    count = len(removed_files)
    return "Cache cleaned! Removed %d old file%s." \
           % (count, 's' if count != 1 else '')
28bb4b28   Goutte   API for the cache...
1030
1031


b500e561   Goutte   Invert the orbits...
1032
1033
1034
1035
@app.route("/cache/warmup")
def cache_warmup():
    """
    Warms up the cache for the current day.
927c69c3   Goutte   Make the local ca...
1036
    Linked to SpaceWeather#edit in swapp.ls to get the default time interval.
e18701b6   Goutte   Cache clear (remo...
1037
    If you edit this code you'll need to edit the other as well and vice versa.
b500e561   Goutte   Invert the orbits...
1038
    """
b500e561   Goutte   Invert the orbits...
1039
1040
1041
1042
1043
    # relativedelta(years=3)
    # startted_at = datetime.datetime.now() - relativedelta(years=3)
    return "To Do"


1324cc91   Goutte   Make the footer i...
1044
1045
1046
@app.route("/log")
def log_show():
    with open(LOG_FILE, 'r') as f:
bde97e4d   Goutte   Add more changes ...
1047
1048
1049
1050
        contents = f.read()
    return contents


1324cc91   Goutte   Make the footer i...
1051
1052
1053
1054
1055
1056
1057
@app.route("/log/clear")
def log_clear():
    with open(LOG_FILE, 'w') as f:
        f.truncate()
    return "Log cleared successfully."


1754789b   Goutte   Decorate and clea...
1058
1059
1060
1061
# DEV TOOLS ###################################################################

# @app.route("/inspect")
# def analyze_cdf():
a4a9ef03   Goutte   Cache generated C...
1062
#     """
1754789b   Goutte   Decorate and clea...
1063
#     For debug purposes.
a4a9ef03   Goutte   Cache generated C...
1064
#     """
1754789b   Goutte   Decorate and clea...
1065
1066
#     cdf_to_inspect = get_path("../res/dummy.nc")
#     cdf_to_inspect = get_path("../res/dummy_jupiter_coordinates.nc")
a4a9ef03   Goutte   Cache generated C...
1067
1068
#
#     si = StringIO.StringIO()
1754789b   Goutte   Decorate and clea...
1069
1070
#     cw = csv.DictWriter(si, fieldnames=['Name', 'Shape', 'Length'])
#     cw.writeheader()
a4a9ef03   Goutte   Cache generated C...
1071
#
1754789b   Goutte   Decorate and clea...
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
#     # 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()
a4a9ef03   Goutte   Cache generated C...
1082
1083
1084
1085
#
#     return si.getvalue()


9390ec89   Goutte   Initial experimen...
1086
1087
1088
# MAIN ########################################################################

if __name__ == "__main__":
952e3d8f   Goutte   Move to another s...
1089
    # Debug mode is on, as the production server does not use this but run.wsgi
9390ec89   Goutte   Initial experimen...
1090
1091
    extra_files = [get_path('../config.yml')]
    app.run(debug=True, extra_files=extra_files)