serverWsgi.michel.py 25.8 KB
Newer Older
Caillat Michel's avatar
Caillat Michel committed
1
2
#!/usr/bin/env python

3
from bottle import route, run, get, request, view, default_app, response, error
Caillat Michel's avatar
Caillat Michel committed
4
5
6
7
8
9
10
11
12
13
14
15
16
17

import astropy

import sys
import socket
import getopt
import os
import traceback
import collections
import numpy as np

import json
import errno
import logging
18
from autologging import logged, TRACE, traced
Caillat Michel's avatar
Caillat Michel committed
19
20
21
22
23
24
25
26
27

ARTEMIXDataDir = None
FITSRootDir = None
SAMPDataDir = None
baseUrl = "/artemix"

logger = None
dm = None

28
import dataManager_michel as dataManager
Caillat Michel's avatar
Caillat Michel committed
29
30
31
32
33
34
35

#####################################################################
#                                                                   #
#                            Utilities                              #
#                                                                   #
#####################################################################

36
37
"""
enable cross domain ajax requests
Caillat Michel's avatar
Caillat Michel committed
38
39
"""
def enable_cors(fn):
40
    def _enable_cors(*args, **kwargs):
Caillat Michel's avatar
Caillat Michel committed
41
    # set CORS headers
42
43
44
        response.headers['Access-Control-Allow-Origin'] = '*'
        response.headers['Access-Control-Allow-Methods'] = 'GET, POST, PUT, OPTIONS'
        response.headers['Access-Control-Allow-Headers'] = 'Origin, Accept, Content-Type, X-Requested-With, X-CSRF-Token'
Caillat Michel's avatar
Caillat Michel committed
45

46
47
48
        if request.method != 'OPTIONS':
            # actual request; reply with the actual response
            return fn(*args, **kwargs)
Caillat Michel's avatar
Caillat Michel committed
49

50
    return _enable_cors
Caillat Michel's avatar
Caillat Michel committed
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
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
109
110
111
112
113
114
115
116
117
118

def getFloatValue(value):
    if value is not None and str(value) != "null":
        return float(value)
    return None

def getIntValue(value):
    if value is not None and str(value) != "null":
        return int(value)
    return None

def getBoolValue(value):
    if value is not None and str(value) != "null":
        return value == "true"
    return None

"""
	Replaces NaN values by None in array
"""
def cleanNanInList(arr):
    result = arr
    result[np.isnan(result)] = None
    return result

"""
    Given filename ( string )
    returns a string where each space character present in filename is replaced by '+' character.
"""
def rebuildFilename(filename):
    result = byteify(filename.replace(" ", "+"))
    if ((result[0] == '"' and result[len(result) - 1] == '"') or ( result[0] == "'" and result[len(result) - 1] == "'" )):
        result = result[1:-1]
    return result

"""
    A function to transform the content of a dictionary a unicode value into its ascii's
    see https://stackoverflow.com/questions/956867/how-to-get-string-objects-instead-of-unicode-from-json
"""

def byteify(input):
    result = None
    if isinstance(input, dict):
        result = {byteify(key): byteify(value)
                for key, value in input.items()}
    elif isinstance(input, list):
        result = [byteify(element) for element in input]
    elif isinstance(input, str):
        result =  input.encode('utf-8').decode('utf-8')
    elif isinstance(input, bytes):
        result = input.encode('utf-8').decode('utf-8')
    else:
        result = input
    #logging.debug("result = %r" % result)
    return result


#####################################################################
#                                                                   #
#                   Routes definitions                              #
#                                                                   #
#####################################################################

"""
  Check that the server is alive and waiting.
"""
@route(baseUrl+"/ping", name='upAnWaiting', method='GET')
@enable_cors
def upAnWaiting():
119
120
  logger.debug("upAndWaiting - wrapper : entering")
  logger.debug("upAndWaiting - wrapper : exiting")
Caillat Michel's avatar
Caillat Michel committed
121
122
123
124
125
126
127
128
129
  return "{status: %r, message : 'Up and waiting', 'result': %r}" % (True, request)

"""
    Given two values expressed in degrees one for a Right Ascension (ra) and one for a Declination
    returns their respectives conversion in Hour Minute Second and Degree Minute Second
"""
@route( baseUrl+'/degToHMSDMS', name='degToHMSDMS', method='GET')
@enable_cors
def degToHMSDMS():
130
131
132
133
134
135
136
137
138
    logger.debug("degToHMSDMS - wrapper : entering")
    try:
        relFITSFilePath = rebuildFilename(request.GET['relFITSFilePath'])
        RAinDD = getFloatValue(request.GET['RAinDD'])
        DECinDD = getFloatValue(request.GET['DECinDD'])
    except Exception as e:
        logger.debug(f'{e}')
        raise

Caillat Michel's avatar
Caillat Michel committed
139
    response.content_type = "application/json; charset=utf-8"
140
141
142
    logger.debug("degToHMSDMS - wrapper : exiting")

    return json.dumps(dm.degToHMSDMS(relFITSFilePath, RAinDD, DECinDD))
Caillat Michel's avatar
Caillat Michel committed
143
144
145
146
147
148
149
150
151
152


"""
    Given a FITS filename and an interval of positive integers values and
    an integer step returns an array of Hour:Minute:Second right ascension values
    located on the grid defined by (start, end, step)
"""
@route( baseUrl+'/rangeToHMS', name='rangeToHMS', method='GET')
@enable_cors
def rangeToHMS():
153
154
155
156
157
158
159
160
161
    logger.debug("rangeToHMS - wrapper : entering")
    try:
        relFITSFilePath = rebuildFilename(request.GET['relFITSFilePath'])
        iRA0 = getIntValue(request.GET['iRA0'])
        iRA1 = getIntValue(request.GET['iRA1'])
        iRAstep = getIntValue(request.GET['iRAstep'])
    except Exception as e:
        logger.debug(f'{e}')
        raise
Caillat Michel's avatar
Caillat Michel committed
162
163

    response.content_type = "application/json; charset=utf-8"
164
    logger.debug("rangeToHMS - wrapper : exiting")
Caillat Michel's avatar
Caillat Michel committed
165

166
    return json.dumps(dm.rangeToHMS(relFITSFilePath, iRA0, iRA1, iRAstep))
Caillat Michel's avatar
Caillat Michel committed
167
168
169
170
171
172
173
174
175

"""
    Given a FITS filename and an interval of positive integers values and
    an integer step returns an array of Degree:Minute:Second declination values
    located on the grid defined by (start, end, step)
"""
@route( baseUrl+'/rangeToDMS', name='rangeToDMS', method='GET')
@enable_cors
def rangeToDMS():
176
177
178
179
180
181
182
183
    logger.debug("rangeToDMS - wrapper : entering")
    try:
        relFITSFilePath = rebuildFilename(request.GET['relFITSFilePath'])
        iDEC0 = getIntValue(request.GET['iDEC0'])
        iDEC1 = getIntValue(request.GET['iDEC1'])
        iDECstep = getIntValue(request.GET['iDECstep'])
    except Exception as e:
        logger.debug(f'{e}')
Caillat Michel's avatar
Caillat Michel committed
184
    response.content_type = "application/json; charset=utf-8"
185
    logger.debug("rangeToDMS - wrapper : exiting")
Caillat Michel's avatar
Caillat Michel committed
186

187
    return json.dumps(dm.rangeToDMS(relFITSFilePath, iDEC0, iDEC1, iDECstep))
Caillat Michel's avatar
Caillat Michel committed
188
189

"""
190
    Given relFITSFilePath read corresponding the FITS file in memory
Caillat Michel's avatar
Caillat Michel committed
191
192
193
194
195
    returns the FITS header of that file.
"""
@route( baseUrl+'/setData', name='setData', method='GET')
@enable_cors
def setData():
196
197
198
199
200
201
    logger.debug("setData - wrapper : entering")
    try:
        relFITSFilePath = rebuildFilename(request.GET['relFITSFilePath'])
    except Exception as e:
        logger.debug(f'{e}')
        raise
Caillat Michel's avatar
Caillat Michel committed
202
    response.content_type = "application/json; charset=utf-8"
203
    result = dm.setData(relFITSFilePath)
204
    logger.debug("setData - wrapper : exiting")
205
    return json.dumps(result)
Caillat Michel's avatar
Caillat Michel committed
206
207
208

"""
    Given filename return the shape of the data cube contained
209
    in relFITSFilePath
Caillat Michel's avatar
Caillat Michel committed
210
211
212
213
"""
@route( baseUrl+'/getDimensions', name='getDimensions', method='GET')
@enable_cors
def getDimensions():
214
215
216
217
218
219
    logger.debug("getDimensions - wrapper : entering")
    try:
        relFITSFilePath = rebuildFilename(request.GET['relFITSFilePath'])
    except Exception as e:
        logger.debug(f'{e}')
        raise
Caillat Michel's avatar
Caillat Michel committed
220
    response.content_type = "application/json; charset=utf-8"
221
    logger.debug("getDimensions - wrapper : exiting")
Caillat Michel's avatar
Caillat Michel committed
222

223
    return json.dumps(dm.getDimensions(relFITSFilePath))
Caillat Michel's avatar
Caillat Michel committed
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245

"""
    Given a multidimensional array l
    return a flattened representation of l
"""
@route( baseUrl+'/flatten', name='flatten', method='GET')
@enable_cors
def flatten():

    l = request.GET['l']

    return json.dumps(dm.flatten(l))

"""
    Given relFITSFilePath and a triple of integer values iFreq, iRA, iDEC
    returns the pixel value with coordinates (iFreq, iRA, iDEC) in the data cube
    associated to relFITSFilePath.
"""
@route( baseUrl+'/getPixelValueAtiFreqiRAiDEC', name="getPixelValueAtiFreqiRAiDEC", method='GET')
@enable_cors
def getPixelValueAtiFreqiRAiDEC():
    logger.debug("getPixelValueAtiFreqiRAiDEC - wrapper : entering" )
Caillat Michel's avatar
Caillat Michel committed
246
247
    try:
        relFITSFilePath = rebuildFilename(request.GET['relFITSFilePath'])
248
        iFREQ = getIntValue(request.GET['iFREQ'])
Caillat Michel's avatar
Caillat Michel committed
249
250
        iRA = getIntValue(request.GET['iRA'])
        iDEC = getIntValue(request.GET['iDEC'])
251
        result = json.dumps(dm.getPixelValueAtiFreqiRAiDEC(relFITSFilePath, iFREQ, iRA, iDEC))
Caillat Michel's avatar
Caillat Michel committed
252
    except Exception as e:
253
254
255
256
        exc_type, exc_value, exc_traceback = sys.exc_info()
        traceback.print_exc()
        message = "%s ! %s" %  (repr(e), "".join(traceback.format_list(traceback.extract_tb(exc_traceback))))
        result = {"status": False, "message": message}
Caillat Michel's avatar
Caillat Michel committed
257
258
259
260
261
262
263

    response.content_type = "application/json; charset=utf-8"
    logger.debug("getPixelValueAtiFreqiRAiDEC - wrapper : exiting" )
    return result

"""
    Given an integer sliceNumb and an integer step
264
    and a string relFITSFilePath
Caillat Michel's avatar
Caillat Michel committed
265
    returns a 2D array made of one pixel every (step, step)
266
    of the slice sliceNumb in the datacube contained in relFITSFilePath
Caillat Michel's avatar
Caillat Michel committed
267
268
269
270
"""
@route( baseUrl+'/getSlice', name='getSlice', method='GET')
@enable_cors
def getSlice():
271
    logger.debug("getSlice - wrapper : entering" )
Caillat Michel's avatar
Caillat Michel committed
272

Caillat Michel's avatar
Caillat Michel committed
273
274
275
276
277
278
279
280
    try:
        relFITSFilePath = rebuildFilename(request.GET['relFITSFilePath'])
        iFREQ = int(request.GET['iFREQ'])
    except Exception as e:
        logger.debug(f'{e}')
        raise

    result = dm.getSlice(relFITSFilePath, iFREQ)
Caillat Michel's avatar
Caillat Michel committed
281
    response.content_type = "application/json; charset=utf-8"
282
283
    logger.debug("getSlice - wrapper : exiting" )

Caillat Michel's avatar
Caillat Michel committed
284
285
286
287
    return json.dumps(result)

"""
    Given one pair, x and y, of integer coordinates in the RAxDEC plane and
Caillat Michel's avatar
Caillat Michel committed
288
289
    a frequency range defined by a pair of integers iFREQ0 and iFRE1
    returns the values contained in the data cube at [iFREQ0:iFRE1, x, y]
Caillat Michel's avatar
Caillat Michel committed
290
291
292
293
"""
@route( baseUrl+'/getFreq', name='getFreq', method='GET')
@enable_cors
def getFreq():
294
    logger.debug("getFreq - wrapper : entering" )
Caillat Michel's avatar
Caillat Michel committed
295

Caillat Michel's avatar
Caillat Michel committed
296
297
298
299
300
301
302
303
304
    try:
        relFITSFilePath = rebuildFilename(request.GET['relFITSFilePath'])
        iRA = getIntValue(request.GET['iRA'])
        iDEC = getIntValue(request.GET['iDEC'])
        iFREQ0 = getIntValue(request.GET['iFREQ0'])
        iFREQ1 = getIntValue(request.GET['iFREQ1'])
    except Exception as e:
        logger.debug(f'{e}')
        raise
Caillat Michel's avatar
Caillat Michel committed
305
    response.content_type = "application/json; charset=utf-8"
Caillat Michel's avatar
Caillat Michel committed
306
307
    result = json.dumps(dm.getFreq(relFITSFilePath, iRA, iDEC, iFREQ0, iFREQ1))
    logger.debug("getFreq - wrapper : exiting")
Caillat Michel's avatar
Caillat Michel committed
308

309
    return result
Caillat Michel's avatar
Caillat Michel committed
310
311

"""
Caillat Michel's avatar
Caillat Michel committed
312
313
314
    Given two pairs -- iRA0,iRA1 and iDEC0,iDEC1 -- defining a rectangular area the RAxDEC plane
    and a frequency range defined by a pair of integers iFREQ0 and iFRE1
    returns the result of numpy.nansum(datacube[iFREQ0:iFRE1, iDEC0:iDEC1, iRA0:iRA1], (1,2))
Caillat Michel's avatar
Caillat Michel committed
315
316
317
318
319
320
321
322
323
324
325
326
327
    multiplied by cdelt and divided by convert where

    * cdelt == 4 * math.log(2) * abs(CDELT1) * pi180 * abs(CDELT2) * pi180
    * convert == pi * bmaj * bmin
    * bmaj == BMAJ * pi180
    * bmin == BMIN * pi180
    * pi180 == pi / 180 / 4.86e-6

    That is a weighted sum the defined area of the data cube along the frequency axis.
"""
@route( baseUrl+'/getAverageSpectrum', name='getAverageSpectrum', method='GET')
@enable_cors
def getAverageSpectrum():
328
    logger.debug("getAverageSpectrum - wrapper : entering" )
Caillat Michel's avatar
Caillat Michel committed
329
330
331

    relFITSFilePath = rebuildFilename(request.GET['relFITSFilePath'])

Caillat Michel's avatar
Caillat Michel committed
332
333
334
335
336
337
338
339
340
341
    try:
        iDEC0 = getIntValue(request.GET['iDEC0'])
        iDEC1 = getIntValue(request.GET['iDEC1'])
        iRA0 = getIntValue(request.GET['iRA0'])
        iRA1 = getIntValue(request.GET['iRA1'])
        retFITS = getBoolValue(request.GET['retFITS'])
    except Exception as e:
        logger.debug(f'{e}')
        raise

Caillat Michel's avatar
Caillat Michel committed
342
    response.content_type = "application/json; charset=utf-8"
Caillat Michel's avatar
Caillat Michel committed
343
    result = json.dumps(dm.getAverageSpectrum(relFITSFilePath, iDEC0, iDEC1, iRA0, iRA1, retFITS))
344
    logger.debug("getAverageSpectrum - wrapper : exiting" )
Caillat Michel's avatar
Caillat Michel committed
345
346
347
348
349

    return result

"""
    Given two pairs -- RAPix0,RAPix1 and DECPix0,DECPix1 -- defining a rectangular area the RAxDEC plane
Caillat Michel's avatar
Caillat Michel committed
350
351
    and a frequency defined by an integer iFREQ
    returns the result of numpy.nansum(datacube[iFREQ, iDEC0:iDEC1, iRA0:iRA1], (1,2))
Caillat Michel's avatar
Caillat Michel committed
352
353
354
355
356
    multiplied by 4 * log(2) * cdelt1 * pi / 180 / 4.86e-6 * cdelt2 * pi / 180 / 4.86e-6
"""
@route( baseUrl+'/getSumOverSliceRectArea', name='getSumOverSliceRectArea', method='GET')
@enable_cors
def getSumOverSliceRectArea():
Caillat Michel's avatar
Caillat Michel committed
357
358
359
360
361
362
363
364
365
366
367
    logger.debug("getSumOverSliceRectArea - wrapper : entering" )
    try:
        relFITSFilePath = rebuildFilename(request.GET['relFITSFilePath'])
        DECPix0 = getIntValue(request.GET['DECPix0'])
        DECPix1 = getIntValue(request.GET['DECPix1'])
        RAPix0 = getIntValue(request.GET['RAPix0'])
        RAPix1 = getIntValue(request.GET['RAPix1'])
        iFREQ = getIntValue(request.GET['iFREQ'])
    except Exception as e:
        logger.debug(f'{e}')
        raise
Caillat Michel's avatar
Caillat Michel committed
368
369

    response.content_type = "application/json; charset=utf-8"
Caillat Michel's avatar
Caillat Michel committed
370
371
372
    result = json.dumps(dm.getSumOverSliceRectArea(relFITSFilePath,  iFREQ, RAPix0, RAPix1, DECPix0, DECPix1))
    logger.debug("getSumOverSliceRectArea - wrapper : exiting" )

Caillat Michel's avatar
Caillat Michel committed
373
374
375
    return result

"""
Caillat Michel's avatar
Caillat Michel committed
376
377
378
    Given two pairs -- iRA0,iRA1 and iDEC0,iDEC1 -- defining a rectangular area the RAxDEC plane
    and a frequency range defined by a pair of integers iFREQ0 and iFRE1
    returns the result of numpy.nansum(datacube[iFREQ0:iFRE1, iDEC0:iDEC1, iRA0:iRA1], 0)
Caillat Michel's avatar
Caillat Michel committed
379
380
381
382
383
    multiplied by 4 * log(2) * cdelt1 * pi / 180 / 4.86e-6 * cdelt2 * pi / 180 / 4.86e-6
"""
@route( baseUrl+'/getAverage', name='getAverage', method='GET')
@enable_cors
def getAverage():
Caillat Michel's avatar
Caillat Michel committed
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
    logger.debug("getAverage - wrapper : entering" )
    try:
        logger.debug(request)
        relFITSFilePath = rebuildFilename(request.GET['relFITSFilePath'])
        iDEC0 = getIntValue(request.GET['iDEC0'])
        iDEC1 = getIntValue(request.GET['iDEC1'])
        iRA1 = getIntValue(request.GET['iRA1'])
        iRA0 = getIntValue(request.GET['iRA0'])
        iFREQ0 = getIntValue(request.GET['iFREQ0'])
        iFREQ1 = getIntValue(request.GET['iFREQ1'])
        retFITS = getBoolValue(request.GET['retFITS'])
        result = dm.getAverage(relFITSFilePath, iFREQ0, iFREQ1, iDEC0, iDEC1, iRA0, iRA1, retFITS)
    except Exception as e:
        logger.debug(f'{e}')
        exc_type, exc_value, exc_traceback = sys.exc_info()
        message = "%s ! %s" %  (type(e), "".join(traceback.format_list(traceback.extract_tb(exc_traceback))))
        traceback.print_exc()
        result = {"status": False, "message": message}
Caillat Michel's avatar
Caillat Michel committed
402
    response.content_type = "application/json; charset=utf-8"
Caillat Michel's avatar
Caillat Michel committed
403
    logger.debug("getAverage - wrapper : exiting" )
Caillat Michel's avatar
Caillat Michel committed
404
405
406
407
408
409
410
411
    return json.dumps(result)

"""
Create a FITS file whose type is TABLE and content is the spectrum at position (iRA, iDEC)
along with the frequencies/velocities.

Returns the content of the file.
"""
Caillat Michel's avatar
Caillat Michel committed
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
# @route( baseUrl+'/createFits', name='createFits', method='POST')
# @enable_cors
# def createFits():
#     logger.debug("createFits - wrapper : entering" )
#     try:
#         header = request.json['header']
#         relFITSFilePath = request.json['relFITSFilePath']
#         iRA = request.json['iRA']
#         iDEC = request.json['iDEC']
#     except Exception as e:
#         logger.debug(f'{e}')
#         raise
#     response.content_type = "application/json; charset=utf-8"
#     logger.debug("createFits - wrapper : exiting" )
#     return json.dumps(dm.createFits(relFITSFilePath, iRA, iDEC))
Caillat Michel's avatar
Caillat Michel committed
427
428

"""
429
    Given relFITSFilePath
Caillat Michel's avatar
Caillat Michel committed
430
431
432
433
434
    returns the FITS header
"""
@route( baseUrl+'/getHeader', name='getHeader', method='GET')
@enable_cors
def getHeader():
435
436
437
438
439
440
    logger.debug("getHeader - wrapper : entering")
    try:
        relFITSFilePath = rebuildFilename(request.GET['relFITSFilePath'])
    except Exception as e:
        logger.debug(f'{e}')
        raise
Caillat Michel's avatar
Caillat Michel committed
441
    response.content_type = "application/json; charset=utf-8"
442
    result = json.dumps(dm.getHeader(relFITSFilePath))
443
    logger.debug("getHeader - wrapper : exiting")
444
    return result
Caillat Michel's avatar
Caillat Michel committed
445
446

"""
447
    Given relFITSFilePath
Caillat Michel's avatar
Caillat Michel committed
448
449
450
451
452
453
    returns the area in the RA x DEC plane of the data contained in the data cube
    as a pair of pairs ((ramin, ramax), ( decmin, decmax))
"""
@route( baseUrl+'/RADECRangeInDegrees', name='RADECRangeInDegrees', method='GET')
@enable_cors
def RADECRangeInDegrees():
454
455
456
457
458
459
    logger.debug("RADECRangeInDegrees - wrapper : entering")
    try :
        relFITSFilePath = rebuildFilename(request.GET['relFITSFilePath'])
    except Exception as e:
        logger.debug(f'{e}')
        raise
Caillat Michel's avatar
Caillat Michel committed
460
    response.content_type = "application/json; charset=utf-8"
461
462
    logger.debug("RADECRangeInDegrees - wrapper : exiting")

463
    return json.dumps(dm.RADECRangeInDegrees(relFITSFilePath))
Caillat Michel's avatar
Caillat Michel committed
464
465

"""
Caillat Michel's avatar
Caillat Michel committed
466
    Given relFITSFilePath and iFREQ
Caillat Michel's avatar
Caillat Michel committed
467

Caillat Michel's avatar
Caillat Michel committed
468
    produces a PNG file representing the slice number int(iFREQ_s) of the datacube along the frequency axis
Caillat Michel's avatar
Caillat Michel committed
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484

    returns a dictionary {"data_steps" : data_steps, "path_to_png": relPNGFilePath} where :

    * data_steps is a dictionary color -> physical quantity for a flux density
    * relPNGFilePath a path to the PNG file relative to the root directory of PNG files.
"""
@route( baseUrl+'/getOneSliceAsPNG', name='getOneSliceAsPNG', method='POST')
@enable_cors
def getOneSliceAsPNG():
    request_body = (request.body.read())
    body = None
    response.content_type = "application/json; charset=utf-8"

    try:
        body = byteify(json.loads(request_body))
        relFITSFilePath = rebuildFilename(body['relFITSFilePath'])
Caillat Michel's avatar
Caillat Michel committed
485
        iFREQ = getIntValue(body['iFREQ'])
Caillat Michel's avatar
Caillat Michel committed
486

487
488
489
490
        kwargs = {}
        for x in ['ittName', 'lutName', 'vmName']:
            if x in body :
                kwargs[x]=body[x]
Caillat Michel's avatar
Caillat Michel committed
491
        ret = dm.getOneSliceAsPNG(iFREQ, relFITSFilePath, **kwargs)
Caillat Michel's avatar
Caillat Michel committed
492
493
494
495
496
497
498
499
    except Exception as e:
        exc_type, exc_value, exc_traceback = sys.exc_info()
        traceback.print_exc()
        message = "%s ! %s" %  (repr(e), "".join(traceback.format_list(traceback.extract_tb(exc_traceback))))
        ret = {"status": False, "message": message}
    return json.dumps(ret)

"""
Caillat Michel's avatar
Caillat Michel committed
500
501
    Given relFITSFilePath and a pair iFREQ0, iFREQ1
    performs a weighted sum slices with indices in [iFREQ0, iFREQ1] along the frequency axis
Caillat Michel's avatar
Caillat Michel committed
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
    and saves it as a PNG file.

    returns a dictionary {"data_steps" : data_steps, "path_to_png": relPNGFilePath} where :

    * data_steps is a dictionary color -> physical quantity for a flux density
    * relPNGFilePath a path to the PNG file relative to the root directory of PNG files.
"""
@route( baseUrl+'/getSummedSliceRangeAsPNG', name='getSummedSliceRangeAsPNG', method='POST')
@enable_cors
def getSummedSliceRangeAsPNG():
    response.content_type = "application/json; charset=utf-8"

    try:
        body = byteify(json.loads(request.body.read()))
        logger.debug("getSummedSliceRangeAsPNG(): body = %r" % json.loads(request.body.read()) )
        relFITSFilePath = rebuildFilename(body['relFITSFilePath'])
Caillat Michel's avatar
Caillat Michel committed
518
519
        iFREQ0 = getIntValue(body['iFREQ0'])
        iFREQ1 = getIntValue(body['iFREQ1'])
520
521
522
523
524

        kwargs = {}
        for x in ['ittName', 'lutName', 'vmName']:
            if x in body :
                kwargs[x]=body[x]
525
        ret =  dm.getSummedSliceRangeAsPNG(relFITSFilePath, iFREQ0, iFREQ1,  **kwargs);
Caillat Michel's avatar
Caillat Michel committed
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
    except Exception as e:
        exc_type, exc_value, exc_traceback = sys.exc_info()
        message = "%s ! %s" %  (type(e), "".join(traceback.format_list(traceback.extract_tb(exc_traceback))))
        traceback.print_exc()
        ret = {"status": False, "message": message}
    return json.dumps(ret)

"""
    Given the values of a spectrum 'ydata' passed with the corresponding frequency values 'xdata'
    at an (x,y) given position ( integer indexes ) in the RAxDEC plan of a cube, generate a FITS file containing that
    spectrum. Supposedly be used for interoperability based on SAMP. A typical interlocutor is CASSIS

    @header the FITS Header of the file contaning the input data cube.
    @relFITSFilePath the path to the input data cube on disk.
    @iRA a single integer value containing the index along the RA axis
    @iDEC a single integer value containing the index along the DEC axis
"""
@route( baseUrl+'/createFits', name='createFits', method='POST')
@enable_cors
def createFits():
    response.content_type = "application/json; charset=utf-8"
Caillat Michel's avatar
Caillat Michel committed
547
548
549
550
551
552
553
554
555
556
557
    try:
        body = byteify(json.loads(request.body.read()))
        relFITSFilePath = body['relFITSFilePath']
        iRA = getIntValue(body['iRA'])
        iDEC = getIntValue(body['iDEC'])
        result =  dm.createFits(relFITSFilePath, iRA, iDEC)
    except Exception as e:
        exc_type, exc_value, exc_traceback = sys.exc_info()
        message = "%s ! %s" %  (type(e), "".join(traceback.format_list(traceback.extract_tb(exc_traceback))))
        traceback.print_exc()
        result = {"status": False, "message": message}
Caillat Michel's avatar
Caillat Michel committed
558
559

    response.content_type = "application/json; charset=utf-8"
Caillat Michel's avatar
Caillat Michel committed
560
    return json.dumps(result)
Caillat Michel's avatar
Caillat Michel committed
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576


"""
    Returns all the entries directly located under a given subdirectory.
    The subdirectory must be passed as a full path implicitely
    rooted at FITSFilePrefix.
    i.e. :
    "/" will be interpreted as FITSFilePrefix+"/"
    "/2018" will be interpreted as FITSFilePrefix+"/2018"
    etc...
    The result is a JSON array of dictionaries , on the basis of one dictionary per inode:
    [{'title': filename of the entry, 'key': the FITSFilePrefix rooted path of the entry, 'folder' : true (resp. false) if the inode is (resp. is not) a subdir, 'lazy': true}]
"""
@route( baseUrl+'/getEntries', name='getEntries', method='POST')
@enable_cors
def getEntries() :
Caillat Michel's avatar
Caillat Michel committed
577
    logger.debug("getEntries : entering...")
Caillat Michel's avatar
Caillat Michel committed
578
    response.content_type = "application/json; charset=utf-8"
Caillat Michel's avatar
Caillat Michel committed
579
580
581
582
583
584
585
586
587
588
589
590
    try:
        body = byteify(json.loads(request.body.read()))
        logger.debug(request.body)
        relKey = body['relKey']
        result = dm.getEntries(relKey)
    except Exception as e:
        exc_type, exc_value, exc_traceback = sys.exc_info()
        message = "%s ! %s" %  (type(e), "".join(traceback.format_list(traceback.extract_tb(exc_traceback))))
        traceback.print_exc()
        result = {"status": False, "message": message}
    logger.debug("getEntries : exiting")
    return json.dumps(result)
Caillat Michel's avatar
Caillat Michel committed
591
592
593
594
595
596
597
598
599
600

"""
   Returns the rendering capabilities of the server in terms of ITTs, LUTs and video modes ( direct [, reverse ).
   These capabilities are defined in lists of names so that a client knows which names to use e.g. 1) to build
   menus in a GUI  , 2) query the server to apply the ITT and/or LUT and/or video mode of its choice for the
   construction of the images.
"""
@route( baseUrl+'/renderingCapabilities', name='renderingCapabilities', method='GET')
@enable_cors
def renderingCapabilities():
Caillat Michel's avatar
Caillat Michel committed
601
602
603
604
605
606
607
608
609
610
611
    logger.debug("renderingCapabilities wrapper : entering")
    response.content_type = "application/json; charset=utf-8"
    try:
        result = dm.renderingCapabilities()
    except Exception as e:
        exc_type, exc_value, exc_traceback = sys.exc_info()
        message = "%s ! %s" %  (type(e), "".join(traceback.format_list(traceback.extract_tb(exc_traceback))))
        traceback.print_exc()
        result = {"status": False, "message": message}
    logger.debug("renderingCapabilities wrapper : exiting")
    return json.dumps(result)
612
613
614
615
616
617
618
619
620

"""
  Returns a collection of informations about the DatBlocks present
  in memory at the time of the call.
"""
@route( baseUrl+'/getDataBlockInfos', name='getDataBlockInfos', method='POST')
@enable_cors
def getDataBlockInfos():
    logger.debug("getDataBlockInfos wrapper : entering")
Caillat Michel's avatar
Caillat Michel committed
621
622
623
624
625
626
627
    try:
        result = dm.getDataBlockInfos()
    except Exception as e:
        exc_type, exc_value, exc_traceback = sys.exc_info()
        message = "%s ! %s" %  (type(e), "".join(traceback.format_list(traceback.extract_tb(exc_traceback))))
        traceback.print_exc()
        result = {"status": False, "message": message}
628
629
630
631
632
633
634
635
636
637
638
    logger.debug("getDataBlockInfos wrapper : exiting")
    return json.dumps(result)

"""
  Erase the DataBlocks idle for a duration greater than DataBlock.getMaxIdle
  (env var YAFITSS_MAXIDLE)
"""
@route( baseUrl+'/purgeDataBlocks', name='purgeDataBlocks', method='POST')
@enable_cors
def purgeDataBlocks():
    logger.debug("purgeDataBlocks wrapper : entering")
Caillat Michel's avatar
Caillat Michel committed
639
640
641
642
643
644
645
    try:
        result = dm.purgeDataBlocks()
    except Exception as e:
        exc_type, exc_value, exc_traceback = sys.exc_info()
        message = "%s ! %s" %  (type(e), "".join(traceback.format_list(traceback.extract_tb(exc_traceback))))
        traceback.print_exc()
        result = {"status": False, "message": message}
646
647
    logger.debug("purgeDataBlocks wrapper : exiting")
    return json.dumps(result)
Caillat Michel's avatar
Caillat Michel committed
648
649
650
651
652
653

#
#    End of the class
#
#

654
655
656
#
# HTTP server error handling
#
657
# @error(500)
658
659
660
661
662
663
def error500(error):
    stack_str=''.join(traceback.format_stack())
    global logger
    logger.debug(f"{stack_str}")
    return f"{error} : {stack_str}"

Caillat Michel's avatar
Caillat Michel committed
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
"""
    start local bottle server
    @port port number
    @debug True if debug enabled
"""
def main(argv):

    global logger
    global dm

    try :
        print (argv)
        opts, args = getopt.getopt(argv[1:], "p:", ["port="])
        print (opts)
    except getopt.GetoptError:
        print ("Bad command")
        sys.exit(2)

682
    port = 4251
Caillat Michel's avatar
Caillat Michel committed
683
684
685
686
    for opt, arg in opts:
        if opt in ('-p', '--port'):
            port = int(arg)

Caillat Michel's avatar
Caillat Michel committed
687
    logger = logging.getLogger(argv[0])
Caillat Michel's avatar
Caillat Michel committed
688
689
690
691
    logger.setLevel(logging.DEBUG)

    # create console handler and set level to debug
    #ch = logging.StreamHandler()
Caillat Michel's avatar
Caillat Michel committed
692
693

    #create file handler and set level to debug
Caillat Michel's avatar
Caillat Michel committed
694
695
696
697
698
    theRootDir = "/home/partemix"
    theLogDir = theRootDir + '/log/'
    theLogFile = theLogDir + os.path.splitext(os.path.basename(argv[0]))[0] + '-'+str(port)+'.log'
    print (theLogFile)
    ch = logging.FileHandler(theLogFile)
Caillat Michel's avatar
Caillat Michel committed
699

Caillat Michel's avatar
Caillat Michel committed
700
701
702
703
    ch.setLevel(logging.DEBUG)

    # create formatter
    formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s')
Caillat Michel's avatar
Caillat Michel committed
704

Caillat Michel's avatar
Caillat Michel committed
705
706
    # add formatter to ch
    ch.setFormatter(formatter)
Caillat Michel's avatar
Caillat Michel committed
707

Caillat Michel's avatar
Caillat Michel committed
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
    # add ch to logger
    logger.addHandler(ch)

    hostname = socket.gethostname()
    logger.debug("%s just starting server on %s:%d" % (argv[0], hostname, port))
    logger.debug("Using astropy version %s" % (astropy.version.version))

    # Obtain a data manager implementation
    dm = dataManager.DataManagerImpl(logger)

    app = default_app()
    run(host=hostname, port=port, debug=True, quiet=False)
    return

if __name__ == '__main__':
    main(sys.argv)