downloadversionIRdata.py 73.2 KB
Newer Older
Holger Niemann's avatar
Holger Niemann committed
1
2
3
4
5
6
7
8
# -*- coding: utf-8 -*-
"""
Created on Wed Oct 25 15:51:46 2017

@author: holn
"""

import numpy as np
9
import IR_image_tools as IR_tools
10
from IR_config_constants import archivepath,portcamdict,camlimdict,valid_FOV_circle,valid_background_rectangle,TC_port,TC_channel,IRCamColdframes_fittingpath
11
12
13
14
try:
    import W7Xrest.read_restdb as AKF_1
except:
    import read_restdb as AKF_1
Holger Niemann's avatar
Holger Niemann committed
15
16
17
import datetime
import urllib
import json
18
19
from PIL import Image
from io import BytesIO
20
from os.path import join
21
22
23
import matplotlib.pyplot as plt
try:        
    import multiprocessing    
24
    import archivedb as AKF_2
25
26
27
28
    fastDL=True
except Exception as E:
    print(E)
    fastDL=False
Holger Niemann's avatar
Holger Niemann committed
29

30

31
32
33
34
35
36
37
try:
    config_path="\\\\sv-e4-fs-1\\E4-Mitarbeiter\\E4 Diagnostics\\QIR\\Software\\QI-RealTime\\v1.0.0\\release\\QIR-IrAnalysis\\Config\\Thermal calibration\\"
    FOV=plt.imread(config_path+portcamdict['OP1.2a']['AEF'+str(10)]+"\\"+"AEF"+str(10)+"_FOV.png")[:,:,0]   
    del FOV
except:
    config_path=""

38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
def get_OP_by_program(program):
    try:    
        bla=int(program.split(".")[0])
        time_ns=int(TimeToNs([bla // 10000,bla % 10000 // 100,bla % 10000 % 100],[10,0,0,0]))
        return get_OP_by_time(time_ns)
    except Exception as E:
        print(E)
        return None
    
def get_OP_by_time(time_ns):
    dateOP=datetime.datetime.utcfromtimestamp(time_ns/1e9)
    if dateOP.year==2017:
        if dateOP.month>8 and dateOP.month<12:
            return "OP1.2a"
        elif dateOP.month==8 and dateOP.day>28:
            return "OP1.2a"
        elif dateOP.month==12 and dateOP.day<8:
            return "OP1.2a"
        else:
            return None        
    elif dateOP.year==2018:
        return "OP1.2b"
    elif dateOP.year<=2016 and dateOP.year>=2015:
        if (dateOP.year==2016 and dateOP.month<=3) or (dateOP.year==2015 and dateOP.month==12):
            return "OP1.1"
        else:
            return None

66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
def get_latest_version(stream):
     """Find out latest version of given stream
     :param stream   url stream of interest
     :return int of version number of None if non-versioned or non-existing stream
     author: G. Schlisio, edit by holn
     """
     request =urllib.request.Request(archivepath + stream + "/_versions.json", headers={"Accept": "application/json"})
     try:
         response = urllib.request.urlopen(request)
         d = json.loads(response.read().decode('utf-8'))
     except urllib.error.HTTPError as ex:
         msg = ex.read()
         raise RuntimeError(msg)
     # detect unversioned or non-existing stream
     if d["versionInfo"] == []:
         return None
     versions = []
     for i in d['versionInfo']:
         versions.append(i['number'])

     return max(versions)

Holger Niemann's avatar
Holger Niemann committed
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
119
120
121
122
123
124
125
126
127
128
def TimeToNs(date,time):
    """
    TimeToNs(date,time)
    (list)  date    [year,month,day]
    (list)  time    [hours,minutes,seconds,microseconds]
    """ 
    date_time=datetime.datetime(date[0],date[1],date[2],time[0],time[1],time[2],time[3])
    div=date_time-datetime.datetime(1970,1,1,0,0,0)
    nsdate=div.total_seconds()*1e9
    return nsdate

def read_program(timestampstart,timestamp_end=0,tol=60):
    """
    read_program()
    """
    program_url = 'http://archive-webapi.ipp-hgw.mpg.de/programs.json?from'
    if timestamp_end!=0:
        jsonurl=program_url+"="+str(int(timestampstart-tol*1e9))+"&upto="+str(int(timestamp_end+tol*1e9))
    else:
        jsonurl=program_url+"="+str(int(timestampstart-tol*1e9))+"&upto="+str(int(timestampstart+tol*1e9))
    try:
        res = urllib.request.urlopen(jsonurl)
        prog_raw=res.read()
        res.close()
    except urllib.error.URLError as e:
        print('!get_program: Error opening URL')
        print(e)
        return False,0
    else:
        prog_string=prog_raw.decode(encoding='UTF-8')
        prog_list = json.loads(prog_string)
        pl=prog_list['programs'][0]
        return True, pl

def read_restdb_old(request_url):
    """
    Reads JSON data from W7-X REST API
    Returns: 
        valid: access ok
        t: numpy-array of time
        signal: numpy-array of requested signals
129
    by H. Thomsen
Holger Niemann's avatar
Holger Niemann committed
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
    """
    try:
        res = urllib.request.urlopen(request_url)
    except urllib.error.URLError as e:
        print(e)
        return False, 0, -1
    else:
        signal_raw=res.read()
        res.close()
        signal_string=signal_raw.decode(encoding='UTF-8')
        signal_list = json.loads(signal_string)
        signal0=np.array(signal_list['values'])
        t=np.array(signal_list['dimensions'])
        return True, t, signal0

145
def download_LUT(port,time,exposure=0,emissivity=0,camera_filter=0,version=0, verbose=0):
Holger Niemann's avatar
Holger Niemann committed
146
147
148
    """
    download_LUT(camera,port,time,exposure=0,emissivity=0,camera_filter=0,version=1):
        time in ns
149
    Have to swap 11, 21 until correction in the database
Holger Niemann's avatar
Holger Niemann committed
150
    """    
151
152
153
154
    if port == 21:
        port = 11
    elif port == 11:
        port = 21
155
    if port==50:# camera=="INFRATEC" or camera=="infratec" or camera=="Infratec":
156
157
        stream="QRT_INFRATEC/"+"AEF"+str(port)+"_LUT_"
        larchivepath=archivepath+stream#"QRT_INFRATEC/"+"AEF"+str(port)+"_LUT_"
Holger Niemann's avatar
Holger Niemann committed
158
        query="Filter_"+str(camera_filter)+"_Texp_"+str(int(exposure))+"us_e_"+str(float(emissivity))
159
    elif port in [10,11,20,21,30,31,40,41,51]:#camera=="IRCAM" or camera=="IRcam" or camera=="ircam":
160
161
        stream="QRT_IRCAM/"+"AEF"+str(port)+"_LUT_"
        larchivepath=archivepath+stream
Holger Niemann's avatar
Holger Niemann committed
162
163
164
165
        query="Texp_"+str(int(exposure))+"us_e_"+str(float(emissivity))
    else:
        print("camera unknown, stopping here")
        raise Exception
166
167
    if version==0:
        version=get_latest_version(stream+"DATASTREAM")
168
169
        if verbose>0:
            print("LUT V"+str(version)+" is used")
Holger Niemann's avatar
Holger Niemann committed
170
    #time=int(fu.TimeToNs([2017,9,26],[8,0,0,0]))
171
    LUTpar=read_restdb_old(larchivepath+"PARLOG/V"+str(version)+"/_signal.json?from="+str(time-10)+"&upto="+str(time+20))
Holger Niemann's avatar
Holger Niemann committed
172
173
    if LUTpar[0]:
        LUTid=LUTpar[2][0]['structure'][query]
174
        LUTs=read_restdb_old(larchivepath+"DATASTREAM/V"+str(version)+"/0/LUT/_signal.json?from="+str(time-10)+"&upto="+str(time+20))
Holger Niemann's avatar
Holger Niemann committed
175
        if LUTs[0]:
176
            LUTs=LUTs[2].swapaxes(1,2)[0]
Holger Niemann's avatar
Holger Niemann committed
177
178
179
180
            LUT=[LUTs[0],LUTs[LUTid],LUTs[LUTid+1]]
            del LUTpar, LUTs
            return True,LUT
        else:
181
            print("Warning: unable to download the LUTs")
Holger Niemann's avatar
Holger Niemann committed
182
183
184
185
            del LUTpar, LUTs
            return False,0
    else:
        del LUTpar
186
        print("Warning: unable to find LUTs, check your request")
Holger Niemann's avatar
Holger Niemann committed
187
188
        return False,0

189
def download_NUC_by_program(port,program,exposure,version=0):
Holger Niemann's avatar
Holger Niemann committed
190
    prog=AKF_1.get_program_from_PID(program)
191
192
193
#    try:
#        t_program = AKF_2.get_program_from_to(program)
#        prog =AKF_2.get_program_list(t_program[0], t_program[1])
Holger Niemann's avatar
Holger Niemann committed
194
195
196
197
198
    if prog[0]:
        starttime=prog[1]['trigger']['0'][0]
        stoptime=prog[1]['trigger']['1'][0]
        return download_NUC_by_times(port,starttime,stoptime,exposure,version)
    else:
199
#    except:
Holger Niemann's avatar
Holger Niemann committed
200
201
202
        print("cannot find the program")
        return False,0,0

203
def download_NUC_by_times(port,starttime,stoptime,exposure,version=0):
Holger Niemann's avatar
Holger Niemann committed
204
205
    larchivepath=archivepath+"QRT_IRCAM/AEF"+str(port)+"_NUC_"
#    NUC_parlog=AKF_1.read_restdb_old(archivepath+"PARLOG/V"+str(version)+"/_signal.json?from="+str(starttime)+"&upto="+str(stoptime))
206
207
    if version==0:
        version=get_latest_version("QRT_IRCAM/AEF"+str(port)+"_NUC_DATASTREAM")
Holger Niemann's avatar
Holger Niemann committed
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
    try:
        res = urllib.request.urlopen(larchivepath+"PARLOG/V"+str(version)+"/_signal.json?from="+str(starttime)+"&upto="+str(stoptime))
        signal_list = json.loads(res.read().decode('utf-8'))
        res.close()
        goon=True
    except urllib.error.URLError as e:
        print(e)
        goon=False
    if goon:        
        n=0
        nuctimes=[0]
        for NUCpar in signal_list['values']:
            if NUCpar['structure']['Texp']==exposure:
                nuctimes=[signal_list['dimensions'][2*n],signal_list['dimensions'][2*n+1]]
#                gain_i=NUCpar['structure']['gain_index']
                offset_i=NUCpar['structure']['offset_index']                
            n+=1 
        if nuctimes[0]!=0:
            NUC=AKF_1.read_restdb(larchivepath+"DATASTREAM/V"+str(version)+"/_signal.json?from="+str(nuctimes[0]-10)+"&upto="+str(nuctimes[1]+10))
            if NUC[0]:
                images=np.vsplit(NUC[2],np.shape(NUC[2])[0]/offset_i)                    
                return True,images,['gain','offset','cold','badpixels','gain_error','offset_error']
            else:
                print("NUC image for requested exposure time not found")
                return False, 0, 0
        else:
            print("NUC image for requested exposure time not found")
            return False,0,0
    else:
        return False,0,0
    
239
def download_background_by_program(port,program,exposure,version=0):
240
241
242
    '''
    returned exist,time,frame
    '''
243
244
245
246
247
248
249
#    prog=AKF_1.get_program_from_PID(program)
    try:
        t_program = AKF_2.get_program_from_to(program)
        prog =AKF_2.get_program_list(t_program[0], t_program[1])
#    if prog[0]:
        starttime=prog[0]['trigger']['0'][0]
        stoptime=prog[0]['trigger']['1'][0]
250
        return download_background_by_times(port,starttime,stoptime,exposure,version)
251
    except:
Holger Niemann's avatar
Holger Niemann committed
252
253
254
        print("cannot find the program")
        return False,0,0
    
255
def download_background_by_times(port,starttime,stoptime,exposure,camera_filter=0,version=0):
256
    if port==50:#camera=="INFRATEC" or camera=="infratec" or camera=="Infratec":
257
        stream="QRT_INFRATEC/"+"AEF"+str(port)+"_background_" 
Holger Niemann's avatar
Holger Niemann committed
258
        larchivepath=archivepath+"QRT_INFRATEC/"+"AEF"+str(port)+"_background_"      
259
    elif port in [10,11,20,21,30,31,40,41,51]:#camera=="IRCAM" or camera=="IRcam" or camera=="ircam":
260
        stream="QRT_IRCAM/"+"AEF"+str(port)+"_background_"   
Holger Niemann's avatar
Holger Niemann committed
261
262
263
264
        larchivepath=archivepath+"QRT_IRCAM/"+"AEF"+str(port)+"_background_"   
    else:
        print("camera unknown, stopping here")
        raise Exception
265
266
    if version==0:
        version=get_latest_version(stream+"DATASTREAM")
Holger Niemann's avatar
Holger Niemann committed
267
268
269
270
271
272
273
274
275
276
277
278
279
    try:
        res = urllib.request.urlopen(larchivepath+"PARLOG/V"+str(version)+"/_signal.json?from="+str(starttime)+"&upto="+str(stoptime))
        signal_list = json.loads(res.read().decode('utf-8'))
        res.close()
        goon=True
    except urllib.error.URLError as e:
        print(e)
        goon=False
    if goon: 
        n=0
        backtimes=[0]
        for backpar in signal_list['values']:
            if backpar['structure']['Texp']==exposure:
280
                if port==50:# camera=="INFRATEC" or camera=="infratec" or camera=="Infratec":
Holger Niemann's avatar
Holger Niemann committed
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
                    if backpar['structure']['filter']==camera_filter:
                        backtimes=[signal_list['dimensions'][2*n],signal_list['dimensions'][2*n+1]]                             
                else:
                    backtimes=[signal_list['dimensions'][2*n],signal_list['dimensions'][2*n+1]]                             
            n+=1
        if backtimes[0]!=0:
            backdat=AKF_1.read_restdb(larchivepath+"DATASTREAM/V"+str(version)+"/_signal.json?from="+str(backtimes[0]-10)+"&upto="+str(backtimes[1]+10))
            if backdat[0]:                                    
                return backdat#[True,backdat[2]]
            else:
                print("background image for requested exposure time(, filter) not found")
                return False,0,0
        else:
            print("background image for requested exposure time(, filter) not found")
            return False,0,0
    else:
        return False,0,0

299
def download_raw_images_by_program(port,program,time_s=0,version=0):
300
301
302
303
304
305
306
#    prog=AKF_1.get_program_from_PID(program)
    try:
        t_program = AKF_2.get_program_from_to(program)
        prog =AKF_2.get_program_list(t_program[0], t_program[1])
#    if prog[0]:
        starttime=prog[0]['trigger']['1'][0]
        stoptime=prog[0]['trigger']['6'][0]
Holger Niemann's avatar
Holger Niemann committed
307
308
309
310
311
312
        if type(time_s)==list:
            tstart=time_s[0]
            tstop=time_s[1]
            if tstop<tstart:
                raise Exception("endtime before starttime")
            return download_raw_images_by_times(port,int(starttime+tstart*1e9),int(starttime+tstop*1e9),version)
Holger Niemann's avatar
Holger Niemann committed
313
        else:
Holger Niemann's avatar
Holger Niemann committed
314
315
316
317
            if time_s==0:
                return download_raw_images_by_times(port,starttime,stoptime,version)
            else:
                return download_raw_images_by_times(port,starttime,int(starttime+time_s*1e9),version)
318
    except:
Holger Niemann's avatar
Holger Niemann committed
319
320
321
        print("cannot find the program")
        return False,0,0

322
323
def download_raw_images_by_times(port,starttime,stoptime,version=0,intervalSize=1E9):
    
324
    if port==50:#camera=="INFRATEC" or camera=="infratec" or camera=="Infratec":
325
326
        if version==0:
            version=get_latest_version("QRT_INFRATEC/"+"AEF"+str(port)+"_raw_DATASTREAM")
Holger Niemann's avatar
Holger Niemann committed
327
        larchivepath=archivepath+"QRT_INFRATEC/"+"AEF"+str(port)+"_raw_DATASTREAM/V"+str(version)+"/0/raw"
328
    elif port in [10,11,20,21,30,31,40,41,51]:#camera=="IRCAM" or camera=="IRcam" or camera=="ircam":
329
330
        if version==0:
            version=get_latest_version("QRT_IRCAM/"+"AEF"+str(port)+"_raw_DATASTREAM")
Holger Niemann's avatar
Holger Niemann committed
331
332
333
334
        larchivepath=archivepath+"QRT_IRCAM/"+"AEF"+str(port)+"_raw_DATASTREAM/V"+str(version)+"/0/raw"
    else:
        print("camera unknown, stopping here")
        raise Exception
335
336
    if (stoptime-starttime)/intervalSize>1:        
        nrinterv=int(np.ceil((stoptime-starttime)/intervalSize))
337
        print("timewindow to large, splitting into smaller fractions ("+str(nrinterv)+")")
Holger Niemann's avatar
Holger Niemann committed
338
        intervalls=[]
339
        for i in range(nrinterv):
340
            intervalls.append(int(starttime-10+i*intervalSize))
Holger Niemann's avatar
Holger Niemann committed
341
        intervalls.append(stoptime)
342
        for i in range(nrinterv):
Holger Niemann's avatar
Holger Niemann committed
343
            try:
Holger Niemann's avatar
Holger Niemann committed
344
                res = urllib.request.urlopen(larchivepath+"/_signal.json?from="+str(intervalls[i])+"&upto="+str(intervalls[i+1]))
Holger Niemann's avatar
Holger Niemann committed
345
346
                signal_list = json.loads(res.read().decode('utf-8'))
                res.close()
347
348
349
                
                images=[np.array(ele, dtype=np.uint16) for ele in signal_list['values']]
#                signal=np.array(signal_list['values'],dtype=np.uint16)
Holger Niemann's avatar
Holger Niemann committed
350
351
352
                t=np.array(signal_list['dimensions'])
                del signal_list
                if i==0:
353
                    allimages=images.copy()
Holger Niemann's avatar
Holger Niemann committed
354
355
                    time=t
                else:
356
                    allimages=allimages+images#np.append(ressignal,signal,axis=0)
Holger Niemann's avatar
Holger Niemann committed
357
                    time=np.append(time,t)
358
                del images,t
Holger Niemann's avatar
Holger Niemann committed
359
            except urllib.error.URLError as e:
Holger Niemann's avatar
Holger Niemann committed
360
                print(e)                
361
        return True,time,allimages
Holger Niemann's avatar
Holger Niemann committed
362
363
364
365
366
    else:
        try:
            res = urllib.request.urlopen(larchivepath+"/_signal.json?from="+str(starttime-10)+"&upto="+str(stoptime))
            signal_list = json.loads(res.read().decode('utf-8'))
            res.close()
367
368
            images=[np.array(ele, dtype=np.uint16) for ele in signal_list['values']]
#            signal=np.array(signal_list['values'],dtype=np.uint16)
Holger Niemann's avatar
Holger Niemann committed
369
370
            t=np.array(signal_list['dimensions'])
            del signal_list
371
            return True, t, images
Holger Niemann's avatar
Holger Niemann committed
372
373
374
        except urllib.error.URLError as e:
            print(e)
            return False, 0,-1
375

376
if fastDL:
377
    def download_raw_images_by_program_via_png(port,program,time_s=0,version=0,threads=1, verbose=0):
378
379
380
381
382
383
384
        prog=AKF_1.get_program_from_PID(program)
#        try:
#            t_program = AKF_2.get_program_from_to(program)
#            prog =AKF_2.get_program_list(t_program[0], t_program[1])
        if prog[0]:
            starttime=prog[1]['trigger']['1'][0]
            stoptime=prog[1]['trigger']['6'][0]
385
386
387
388
            success=True
            OP=get_OP_by_time(starttime)
            Cam=portcamdict[OP]['AEF'+str(port)]
            if Cam.split("_")[0]=="Infratec":#camera=="INFRATEC" or camera=="infratec" or camera=="Infratec":
389
390
                if version==0:
                    version=get_latest_version("QRT_INFRATEC/"+"AEF"+str(port)+"_raw_DATASTREAM")
391
392
                larchivepath="Test/raw/W7X/"+"QRT_INFRATEC/"+"AEF"+str(port)+"_raw_DATASTREAM/V"+str(version)+"/0/raw"
            elif Cam.split("_")[0]=="IRCam":#camera=="IRCAM" or camera=="IRcam" or camera=="ircam":
393
394
                if version==0:
                    version=get_latest_version("QRT_IRCAM/"+"AEF"+str(port)+"_raw_DATASTREAM")
395
396
397
                larchivepath="Test/raw/W7X/"+"QRT_IRCAM/"+"AEF"+str(port)+"_raw_DATASTREAM/V"+str(version)+"/0/raw"
            else:
                raise Exception("Port number does not fit the known cameras")
Holger Niemann's avatar
Holger Niemann committed
398
399
400
401
402
403
404
405
            if type(time_s)==list:
                tstart=time_s[0]
                tstop=time_s[1]
                if tstop<tstart:
                    raise Exception("endtime before starttime")
                stdate=datetime.datetime.utcfromtimestamp((starttime-100)/1e9+tstart)
                stdate=stdate.isoformat()
                enddate=datetime.datetime.utcfromtimestamp((starttime)/1e9+tstop)  
406
407
                enddate=enddate.isoformat()
            else:
Holger Niemann's avatar
Holger Niemann committed
408
409
410
411
412
413
414
415
                stdate=datetime.datetime.utcfromtimestamp((starttime-100)/1e9)
                stdate=stdate.isoformat()
                if time_s==0:
                    enddate=datetime.datetime.utcfromtimestamp(stoptime/1e9)        
                    enddate=enddate.isoformat()
                else:
                    enddate=datetime.datetime.utcfromtimestamp((starttime)/1e9+time_s)  
                    enddate=enddate.isoformat()
416
                #"2017-11-15 08:00:00"
417
            times=AKF_2.get_time_intervals(larchivepath,stdate.replace("T"," "),enddate.replace("T"," "))#
418
419
420
421
422
423
424
425
426
            time=[]
            images=[]
            lnt=len(times)
            if threads==1:
                for i in range(lnt):
                    ele=times[lnt-1-i]
                    imag=download_last_raw_image_by_time(port,ele[0]-10,ele[0]+10)
                    if imag[0]:
                        time.append(ele[0])
427
                        images.append(np.array(imag[1],dtype=np.uint16))
428
429
                    else:
                        success=False
430
                return success,np.array(time),images
431
432
433
434
435
436
437
438
439
440
441
442
            else:
                tim=[]
                for i in range(lnt):
                    tim.append(times[lnt-1-i][0])
                intervalls=[]
                intervalSize=int(lnt/threads)
                for i in range(threads):
                    intervalls.append(int(i*intervalSize))
                intervalls.append(lnt)
                jobs = []
                out_q=multiprocessing.Queue()
                for i in range(threads):
443
444
                    if verbose>0:
                        print("Start Thread ",i+1)                
445
446
447
448
449
450
451
452
                    p = multiprocessing.Process(target=download_raw_images_png_by_times_thread, args=(port,tim[intervalls[i]:intervalls[i+1]],out_q,i,version,))
                    jobs.append(p)
                    p.start()
                resultdict = []
                for i in range(threads):
                    resultdict.append(out_q.get())
                for p in jobs:
                    p.join()
453
454
                if verbose>0:
                    print("all threads are done")
455
456
457
458
459
460
                order=[]
                for ele in resultdict:
                    order.append(ele[0])
                    if len(np.where(np.asarray(ele[1])==False)[0])>0:
                        success=False
                
461
462
463
464
465
                times=[]#np.array(resultdict[order.index(0)][2])
                images=[]#np.array(resultdict[order.index(0)][3])
                for i in range(threads):
                    images=images+resultdict[order.index(i)][3]
                    times=times+resultdict[order.index(i)][2]
466
                del resultdict
467
                return success,np.array(times),images
468
469
#        except Exception as E:
#            raise Exception(E)
470
            
471
    
472
    def download_raw_images_png_by_times_thread(port,times,out_q,threadnumber,version=0):
473
474
475
476
        images=[]
        time=[]
        successes=[]
        for i in times:
477
            imag=download_last_raw_image_by_time(port,i-10,i+10,version=version)
478
            if imag[0]:
479
                images.append(np.array(imag[1],dtype=np.uint16))
480
#                print(np.min(imag[1]),np.max(imag[1]))
481
482
483
484
485
486
                time.append(i)
                successes.append(True)
            else:
                successes.append(False)
        out_q.put([threadnumber,successes,time,images])        
    #    return success,np.array(time),np.array(images,dtype=np.uint16)
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
        
    def convert_raw_to_temp_thread(port,times,out_q,threadnumber,version=0,background=0,LUT=[[],[],[]],refT=28.5,gain=0,offset=0,gain_error=0,offset_error=0,give_ERROR=False,FOV=0,badpixels=[]):
        images=[]
        time=[]
        successes=[]
        for i in times:
            imag=download_last_raw_image_by_time(port,i-10,i+10,version=version)
            if imag[0]:
                images.append(np.array(imag[1],dtype=np.uint16))
                time.append(i)
                successes.append(True)
            else:
                successes.append(False)
        if give_ERROR:
            images,error_images=apply_calib_on_raw(images,background,LUT,refT,gain,offset,gain_error,offset_error,False,give_ERROR)
        else:
            images=apply_calib_on_raw(images,background,LUT,refT,gain,offset,gain_error,offset_error,False,give_ERROR)
        
        for i in range(len(images)):
            images[i]=(images[i]*FOV).astype(np.float32)
        print(datetime.datetime.now(),"correcting bad pixels")
508
        images=IR_tools.correct_images(images,badpixels)
509
        out_q.put([threadnumber,successes,time,images]) 
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
    
    def NUC_raw_thread(port,times,out_q,threadnumber,version=0,background=0,LUT=[[],[],[]],refT=28.5,gain=0,offset=0,gain_error=0,offset_error=0,give_ERROR=False,FOV=0,badpixels=[]):
        images=[]
        time=[]
        successes=[]
        for i in times:
            imag=download_last_raw_image_by_time(port,i-10,i+10,version=version)
            if imag[0]:
                images.append(np.array(imag[1],dtype=np.uint16))
                time.append(i)
                successes.append(True)
            else:
                successes.append(False)
        if give_ERROR:
            images,error_images=apply_NUC(images,gain,offset,gain_error,offset_error,give_ERROR)
        else:
            images=apply_NUC(images,gain,offset,gain_error,offset_error,give_ERROR)
        
        for i in range(len(images)):
            images[i]=(images[i]*FOV).astype(np.float32)
        print(datetime.datetime.now(),"correcting bad pixels")
        images=IR_tools.correct_images(images,badpixels)
        out_q.put([threadnumber,successes,time,images]) 
533
        
534
def download_last_raw_image_by_time(port,starttime,stoptime,version=0):
535
536
537
    OP=get_OP_by_time(starttime)
    Cam=portcamdict[OP]['AEF'+str(port)]
    if Cam.split("_")[0]=="Infratec":#camera=="INFRATEC" or camera=="infratec" or camera=="Infratec":
538
539
        if version==0:
            version=get_latest_version("QRT_INFRATEC/"+"AEF"+str(port)+"_raw_DATASTREAM")
540
541
        larchivepath=archivepath+"QRT_INFRATEC/"+"AEF"+str(port)+"_raw_DATASTREAM/V"+str(version)+"/0/raw"
    elif Cam.split("_")[0]=="IRCam":#camera=="IRCAM" or camera=="IRcam" or camera=="ircam":
542
543
        if version==0:
            version=get_latest_version("QRT_IRCAM/"+"AEF"+str(port)+"_raw_DATASTREAM")
544
545
546
547
548
549
550
551
552
553
554
555
556
        larchivepath=archivepath+"QRT_IRCAM/"+"AEF"+str(port)+"_raw_DATASTREAM/V"+str(version)+"/0/raw"
    else:
        raise Exception("camera unknown, stopping here")
    try:
        res = urllib.request.urlopen(larchivepath+"/_signal.png?from="+str(starttime-10)+"&upto="+str(stoptime))
        img = Image.open(BytesIO(res.read()))
        res.close()
#        pixelarray = np.array(img.getdata()).reshape(img.size[1], img.size[0])
        pixelarray = np.array(img,dtype=np.uint16)#.swapaxes(0,1)
        return True, pixelarray
    except urllib.error.URLError as e:
        print(e)
        return False, -1
Holger Niemann's avatar
Holger Niemann committed
557
    
558
def download_raw_parlog_by_program(port,program,version=0):
559
560
561
562
563
564
565
#    prog=AKF_1.get_program_from_PID(program)
    try:
        t_program = AKF_2.get_program_from_to(program)
        prog =AKF_2.get_program_list(t_program[0], t_program[1])
#    if prog[0]:
        starttime=prog[0]['trigger']['1'][0]
        stoptime=prog[0]['trigger']['6'][0]
566
        return download_raw_parlog_by_times(port,starttime,stoptime,version)    
567
    except:
Holger Niemann's avatar
Holger Niemann committed
568
569
570
        print("cannot find the program")
        return False,0,0
    
571
def download_raw_parlog_by_times(port,starttime,stoptime,version=0):
572
    if port==50:#camera=="INFRATEC" or camera=="infratec" or camera=="Infratec":
573
574
        if version==0:
            version=get_latest_version("QRT_INFRATEC/"+"AEF"+str(port)+"_raw_PARLOG")
Holger Niemann's avatar
Holger Niemann committed
575
        larchivepath=archivepath+"QRT_INFRATEC/"+"AEF"+str(port)+"_raw_PARLOG/V"+str(version)
576
    elif port in [10,11,20,21,30,31,40,41,51]:#elif camera=="IRCAM" or camera=="IRcam" or camera=="ircam":
577
578
        if version==0:
            version=get_latest_version("QRT_IRCAM/"+"AEF"+str(port)+"_raw_PARLOG")
Holger Niemann's avatar
Holger Niemann committed
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
        larchivepath=archivepath+"QRT_IRCAM/"+"AEF"+str(port)+"_raw_PARLOG/V"+str(version)   
    else:
        print("camera unknown, stopping here")
        raise Exception
    try:
        res = urllib.request.urlopen(larchivepath+"/_signal.json?from="+str(starttime)+"&upto="+str(stoptime))
        signal_list = json.loads(res.read().decode('utf-8'))
        res.close()
        goon=True
    except urllib.error.URLError as e:
        print(e)
        goon=False
    if goon: 
        return True, signal_list['dimensions'],signal_list['values'][0]['meta-data']
    

595
def get_INFRATEC_filter_by_program(program,version=0):
596
597
598
599
600
601
602
    prog=AKF_1.get_program_from_PID(program)
#    try:
#        t_program = AKF_2.get_program_from_to(program)
#        prog =AKF_2.get_program_list(t_program[0], t_program[1])
    if prog[0]:
        starttime=prog[1]['trigger']['1'][0]
        stoptime=prog[1]['trigger']['6'][0]
Holger Niemann's avatar
Holger Niemann committed
603
        return  get_INFRATEC_filter_by_times(starttime,stoptime,50,version)
604
    else:#except:
Holger Niemann's avatar
Holger Niemann committed
605
606
607
        print("cannot find the program")
        return False,0,0

608
609
610
def get_INFRATEC_filter_by_times(starttime,stoptime,port=50,version=0):
    if version==0:
        version=get_latest_version("QRT_INFRATEC/"+"AEF"+str(port)+"_raw_PARLOG")
Holger Niemann's avatar
Holger Niemann committed
611
612
613
614
615
616
617
618
619
620
    larchivepath=archivepath+"QRT_INFRATEC/AEF"+str(port)+"_raw_PARLOG/V"+str(version)
    try:
        res = urllib.request.urlopen(larchivepath+"/_signal.json?from="+str(starttime)+"&upto="+str(stoptime))
        signal_list = json.loads(res.read().decode('utf-8'))
        res.close()
        goon=True
    except urllib.error.URLError as e:
        print(e)
        goon=False
    if goon: 
Holger Niemann's avatar
Holger Niemann committed
621
622
623
        return True, signal_list['dimensions'],signal_list['values'][0]['meta-data']['filter']  
    else:
        return False, 0,-1
Holger Niemann's avatar
Holger Niemann committed
624
    
625
def get_exposure_by_program(port,program,version=0):
Holger Niemann's avatar
Holger Niemann committed
626
    prog=AKF_1.get_program_from_PID(program)
627
628
629
#    try:
#        t_program = AKF_2.get_program_from_to(program)
#        prog =AKF_2.get_program_list(t_program[0], t_program[1])
Holger Niemann's avatar
Holger Niemann committed
630
631
632
    if prog[0]:
        starttime=prog[1]['trigger']['1'][0]
        stoptime=prog[1]['trigger']['6'][0]
633
        return get_exposure_by_times(port,starttime,stoptime,version)
Holger Niemann's avatar
Holger Niemann committed
634
    else:
635
636
#    except Exception as E:
        print("cannot find the program, no exposure time available;")#, E)
Holger Niemann's avatar
Holger Niemann committed
637
638
        return False,0,0
        
639
def get_exposure_by_times(port,starttime,stoptime,version=0):
640
    if port==50:#camera=="INFRATEC" or camera=="infratec" or camera=="Infratec":
641
642
        larchivepath=archivepath+"QRT_INFRATEC/"+"AEF"+str(port)+"_meta_"   
        stream="QRT_INFRATEC/"+"AEF"+str(port)+"_meta_" 
643
    elif port in [10,11,20,21,30,31,40,41,51]:#camera=="IRCAM" or camera=="IRcam" or camera=="ircam":
644
        larchivepath=archivepath+"QRT_IRCAM/"+"AEF"+str(port)+"_meta_" 
645
        stream="QRT_IRCAM/"+"AEF"+str(port)+"_meta_"
646
    if version==0:
647
        version=get_latest_version(stream+"DATASTREAM")
Holger Niemann's avatar
Holger Niemann committed
648
649
    return AKF_1.read_restdb(larchivepath+"DATASTREAM/V"+str(version)+"/3/exposuretime"+"/_signal.json?from="+str(starttime)+"&upto="+str(stoptime))
      
650
def get_camera_temp_by_program(port,program,version=0):
651
652
653
654
655
656
657
#    prog=AKF_1.get_program_from_PID(program)
    try:
        t_program = AKF_2.get_program_from_to(program)
        prog =AKF_2.get_program_list(t_program[0], t_program[1])
#    if prog[0]:
        starttime=prog[0]['trigger']['1'][0]
        stoptime=prog[0]['trigger']['6'][0]
658
        return get_camera_temp_by_times(port,starttime,stoptime,version)
659
    except:
Holger Niemann's avatar
Holger Niemann committed
660
661
662
        print("cannot find the program")
        return False,0,0
        
663
def get_camera_temp_by_times(port,starttime,stoptime,version=0):
664
    if port==50:#camera=="INFRATEC" or camera=="infratec" or camera=="Infratec":
665
        stream="QRT_INFRATEC/"+"AEF"+str(port)+"_meta_"  
Holger Niemann's avatar
Holger Niemann committed
666
        larchivepath=archivepath+"QRT_INFRATEC/"+"AEF"+str(port)+"_meta_"      
667
    elif port in [10,11,20,21,30,31,40,41,51]:#camera=="IRCAM" or camera=="IRcam" or camera=="ircam":
668
        stream="QRT_IRCAM/"+"AEF"+str(port)+"_meta_"
Holger Niemann's avatar
Holger Niemann committed
669
        larchivepath=archivepath+"QRT_IRCAM/"+"AEF"+str(port)+"_meta_"
670
671
672
    else:
        print("Port unknown")
        raise Exception
673
674
    if version==0:
        version=get_latest_version(stream+"DATASTREAM")
675
676
677
678
679
    dummy=AKF_1.read_restdb(larchivepath+"DATASTREAM/V"+str(version)+"/1/cameratemperature/_signal.json?from="+str(starttime)+"&upto="+str(stoptime))
    if dummy[0]:
        return dummy
    else:
        return AKF_1.read_restdb(larchivepath+"DATASTREAM/V"+str(version)+"/1/cameratempetarure/_signal.json?from="+str(starttime)+"&upto="+str(stoptime))
Holger Niemann's avatar
Holger Niemann committed
680
    
681
def get_sensor_temp_by_program(port,program,version=0):
682
683
684
685
686
687
688
    prog=AKF_1.get_program_from_PID(program)
#    try:
#        t_program = AKF_2.get_program_from_to(program)
#        prog =AKF_2.get_program_list(t_program[0], t_program[1])
    if prog[0]:
        starttime=prog[1]['trigger']['1'][0]
        stoptime=prog[1]['trigger']['6'][0]
689
        return get_sensor_temp_by_times(port,starttime,stoptime,version)
690
    else:#except:
Holger Niemann's avatar
Holger Niemann committed
691
692
693
        print("cannot find the program")
        return False,0,0
        
694
def get_sensor_temp_by_times(port,starttime,stoptime,version=0):
695
    if port==50:#camera=="INFRATEC" or camera=="infratec" or camera=="Infratec":
696
        stream="QRT_INFRATEC/"+"AEF"+str(port)+"_meta_"
Holger Niemann's avatar
Holger Niemann committed
697
        larchivepath=archivepath+"QRT_INFRATEC/"+"AEF"+str(port)+"_meta_"      
698
    elif port in [10,11,20,21,30,31,40,41,51]:#camera=="IRCAM" or camera=="IRcam" or camera=="ircam":
699
        stream="QRT_IRCAM/"+"AEF"+str(port)+"_meta_"
Holger Niemann's avatar
Holger Niemann committed
700
        larchivepath=archivepath+"QRT_IRCAM/"+"AEF"+str(port)+"_meta_"
701
702
    if version==0:
        version=get_latest_version(stream+"DATASTREAM")
Holger Niemann's avatar
Holger Niemann committed
703
704
    return AKF_1.read_restdb(larchivepath+"DATASTREAM/V"+str(version)+"/0/sensortemperature/_signal.json?from="+str(starttime)+"&upto="+str(stoptime))

705
def get_camera_framerate_by_program(port,program,version=0):
706
707
708
709
710
711
712
#    prog=AKF_1.get_program_from_PID(program)
    try:
        t_program = AKF_2.get_program_from_to(program)
        prog =AKF_2.get_program_list(t_program[0], t_program[1])
#    if prog[0]:
        starttime=prog[0]['trigger']['1'][0]
        stoptime=prog[0]['trigger']['6'][0]
713
        return get_camera_framerate_by_times(port,starttime,stoptime,version)
714
    except:
Holger Niemann's avatar
Holger Niemann committed
715
716
717
        print("cannot find the program")
        return False,0,0
        
718
def get_camera_framerate_by_times(port,starttime,stoptime,version=0):
719
    if port==50:#camera=="INFRATEC" or camera=="infratec" or camera=="Infratec":
720
        stream="QRT_INFRATEC/"+"AEF"+str(port)+"_meta_"      
Holger Niemann's avatar
Holger Niemann committed
721
        larchivepath=archivepath+"QRT_INFRATEC/"+"AEF"+str(port)+"_meta_"      
722
    elif port in [10,11,20,21,30,31,40,41,51]:#camera=="IRCAM" or camera=="IRcam" or camera=="ircam":
723
        stream="QRT_IRCAM/"+"AEF"+str(port)+"_meta_"
Holger Niemann's avatar
Holger Niemann committed
724
        larchivepath=archivepath+"QRT_IRCAM/"+"AEF"+str(port)+"_meta_"
725
726
    if version==0:
        version=get_latest_version(stream+"DATASTREAM")    
Holger Niemann's avatar
Holger Niemann committed
727
728
729
    return AKF_1.read_restdb(larchivepath+"DATASTREAM/V"+str(version)+"/2/framerate/_signal.json?from="+str(starttime)+"&upto="+str(stoptime))
    

730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
def get_average_divertor_TC_for_camtemp(port,starttime,endtime,part="all",TC=0):
    urlstart="http://archive-webapi.ipp-hgw.mpg.de/ArchiveDB/raw/W7X/CoDaStationDesc.115/"
    if port==50 or port==51:
        urlstart=urlstart+"DataModuleDesc.19471_DATASTREAM/"
    else:
        urlstart=urlstart+"DataModuleDesc.262_DATASTREAM/"
    if port %10==1:##uneven cameraport, even TC port
        portnr=port-1
        offset=(port//10-1)*32
    elif port%10==0:##even cameraport, uneven TC port
        portnr=port+1
        offset=(port//10-1)*32+16
    else:
        print("unknown port!")
        raise Exception
    if portnr==50:
        offset=0
    elif portnr==51:
        offset=16
    ext="/ActV1QRD"+str(portnr)+"CT1"
    n=0
    signal=0
    success=True
    if portnr==21:
        skip=True
        skipnr=1
    else:
        skip=False
        skipnr=0
    if part=="all":
        rs=0
        re=10
    elif part in ["h","horizontal","full h","full horizontal"]:
        rs=0
        re=7
    elif part in ["v","vertical","vertikal"]: 
        rs=7
        re=10
    elif part in ["hli","horizontal low iota"]:
769
770
        rs=0#4
        re=4#7
771
    elif part in ["hhi","horizontal high iota","high iota","hi"]:
772
773
        rs=4#0
        re=7#4
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
    elif part in [0,1,2,3,4,5,6,7,8,9,10]:
        rs=part
        re=part+1
    elif part in ["Single","s","single"]:
        rs=TC
        re=TC+1
    else:
        rs=0
        re=0
    if rs!=re:
        for i in range(rs,re,1):
            if skip and i==skipnr:
                i+=1
            url=urlstart+str(offset+i)+ext+"0"+str(i)+"_TC"+str(i%8+1)
            try:
                result=AKF_1.read_restdb(url+"/_signal.json?from="+str(starttime)+"&upto="+str(endtime))
    #                res.append(result)
                if result[0]:
                    n+=1            
                    time=result[1]
                    signal=signal+np.array(result[2])
                else:
                    time=0
                    success=False
            except Exception as E:
                print(E)        
                success=False
Holger Niemann's avatar
Holger Niemann committed
801
802
        try:
            return success,time,signal/n
803
804
        except Exception as E:
            print(E)
Holger Niemann's avatar
Holger Niemann committed
805
            return False,0,-1
806
    else:
807
        print("same numbers!")
808
        return False,0,-1
809

810
def get_divertor_TC_coordinate(cameraport,TC=0):
811
    from IR_config_constants import TC_database
812
813
814
815
816
    if cameraport %10==1:##uneven cameraport, even TC port
        portnr=cameraport-1
    elif cameraport%10==0:##even cameraport, uneven TC port
        portnr=cameraport+1
    else:        
817
        raise Exception("unknown port!")    
818
819
    return TC_database[portnr][TC]

820
def get_TC_data_for_port_by_program(port,program,part=0,version=0):
821
822
823
824
825
826
827
#    prog=AKF_1.get_program_from_PID(program)
    try:
        t_program = AKF_2.get_program_from_to(program)
        prog =AKF_2.get_program_list(t_program[0], t_program[1])
#    if prog[0]:
        starttime=prog[0]['trigger']['1'][0]
        stoptime=prog[0]['trigger']['6'][0]
828
        return get_TC_data_for_port(port,starttime,stoptime,part,version)
829
    except:
830
831
832
833
834
835
        print("cannot find the program")
        return False,0,0
        
def get_TC_data_for_port(port,starttime,endtime,part=0,version=0):
    urlstart="http://archive-webapi.ipp-hgw.mpg.de/ArchiveDB/raw/W7X/CoDaStationDesc.115/DataModuleDesc.19471_DATASTREAM/"
    #66,67(10),72,73(20),78,79(30),84,85(40/50_2),90,91(50_1)
836
    
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
    n=0
    success=True
    signal=0
    time=0
    try:
        for thisport in TC_port[port]:
            thisTCchannel=TC_channel[thisport]
            if part==0:
                for chi in range(len(thisTCchannel[0])):            
                    url=urlstart+str(thisTCchannel[0][chi])+"/"+thisTCchannel[1][chi]
                    try:
                        result=AKF_1.read_restdb(url+"/_signal.json?from="+str(starttime)+"&upto="+str(endtime))
                        if result[0]:
                            n+=1            
                            time=result[1]
                            signal=signal+np.array(result[2])
                        else:                     
                            success=False
                    except Exception as E:
                        print(E)
                        success=False
                        n=1
            else:
                try:
                    url=urlstart+str(thisTCchannel[0][part-1])+"/"+thisTCchannel[1][part-1]
                    try:
                        result=AKF_1.read_restdb(url+"/_signal.json?from="+str(starttime)+"&upto="+str(endtime))
                        if result[0]:
                            n+=1            
                            time=result[1]
                            signal=signal+np.array(result[2])
                        else:                     
                            success=False
                            n=1
                    except Exception as E:
                        print(E)
                        success=False
                        n=1
                except Exception as E:
                    print(E)
                    success=False
                    n=1                    
    except:
        success=False
        n=1
    return success,time,signal/n
Holger Niemann's avatar
Holger Niemann committed
883
"""
884
end of download functions, below combination to get temperature
Holger Niemann's avatar
Holger Niemann committed
885
"""
886

887
888
889
890
891
892
893
894
895
#def apply_LUT_to_images(LUT,images):
#    LUTd={LUT[0][i]: LUT[1][i] for i in range(0, len(LUT[0]))}
#    return np.vectorize(LUTd.get)(images)

def temp_from_LUT(LUT,images):    
    return LUT[0,images]

def terror_from_LUT(LUT,images):
    return LUT[1,images]
896

897
898
899
def check_temperature_range(time,maxvalue_C,minvalue_C,port,exposure,cfilter=0):
    try:
        cam=portcamdict[get_OP_by_time(time)]['AEF'+str(port)]
900
901
902
903
        if port==50:
            ranges=camlimdict[cam][cfilter][exposure]
        else:
            ranges=camlimdict[cam][exposure]
904
905
906
907
908
#        if minvalue_C>=ranges[0] and maxvalue_C<=ranges[1]:
#            return True
        if minvalue_C<ranges[0] and maxvalue_C<=ranges[1]:
            raise Exception("min value ({0:.2f}°C) is out of the valid temperature range (T>{1:.2f}°C)".format(minvalue_C,ranges[0]))
#            return False
909
        elif minvalue_C>=ranges[0] and maxvalue_C>ranges[1]:
910
911
912
913
914
            raise Exception("max value ({0:.2f}°C) is out of the valid temperature range (T<{1:.2f}°C)".format(maxvalue_C,ranges[1]))
#            return False
        elif minvalue_C<ranges[0] and maxvalue_C>ranges[1]:
            raise Exception("max and min value ({0:.2f}°C,{1:.2f}°C) is out of the valid temperature range ({2:.2f}°C<T<{3:.2f}!C)".format(maxvalue_C,minvalue_C,ranges[0],ranges[1]))
#            return False
915
    except Exception as E:
916
917
        raise Exception(E)
        
918

919
def get_temp_from_raw_by_program_V1(portnr,program,time_s=0,emi=0.8,divertorpart="all",version=0,intervalSize=1E9,give_ERROR=False):
920
    background,LUT,refT,gain,offset,badpixels,t_exp,cfilter,gain_error,offset_error=get_calib_data(portnr,program,emi,1,version)    
921
922
923
#    prog=AKF_1.get_program_from_PID(program)
    try:
        t_program = AKF_2.get_program_from_to(program)
924
        prog = AKF_2.get_program_list(t_program[0], t_program[1])
925
#    if prog[0]:
926
#        t0=prog[1]['trigger']['0'][0]
927
928
        t1=prog[0]['trigger']['1'][0]
        t6=prog[0]['trigger']['6'][0]
Holger Niemann's avatar
Holger Niemann committed
929
        starttime=t1-10
Holger Niemann's avatar
Holger Niemann committed
930
931
932
933
934
        if type(time_s)==list:
            tstart=time_s[0]
            tstop=time_s[1]
            if tstop<tstart:
                raise Exception("endtime before starttime")
935
            stoptime=int(starttime+tstop*1e9)  
Holger Niemann's avatar
Holger Niemann committed
936
            starttime=int(starttime+tstart*1e9)        
Holger Niemann's avatar
Holger Niemann committed
937
        else:
Holger Niemann's avatar
Holger Niemann committed
938
939
940
941
            if time_s==0:                                
                stoptime=t6
            else:
                stoptime=int(starttime+time_s*1e9)
942
943
944
945
        success=True
        print(datetime.datetime.now(),"Start download of raw images")
        if (stoptime-starttime)/intervalSize>1:        
            nrinterv=int(np.ceil((stoptime-starttime)/intervalSize))
946
            print("timewindow to large, splitting into smaller fractions ("+str(nrinterv)+")")
947
948
949
950
            intervalls=[]
            for i in range(nrinterv):
                intervalls.append(int(starttime-10+i*intervalSize))
            intervalls.append(stoptime)
951
952
            temperatureimages=[]
            times=[]
953
954
955
956
957
958
959
            for i in range(nrinterv):                            
                raw_dl=download_raw_images_by_times(portnr,intervalls[i],intervalls[i+1],version,intervalSize)
                print(datetime.datetime.now(),"download of raw images part "+str(i+1)+" of "+str(nrinterv)+" finished")
                if raw_dl[0]:
                    time=raw_dl[1]
                    images=raw_dl[2]
                    del raw_dl
960
961
962
963
964
965
#                    images=images.swapaxes(1,2)
                    images=[im.swapaxes(0,1) for im in images]
                    images=apply_calib_on_raw(images,background,LUT,refT,gain,offset,True)                                        
                    temperatureimages=temperatureimages+images
                    times=times+time                                        
                    del time,images
966
                else:
967
                    raise Exception("cannot download the raw images")
968
        else:
969
970
971
972
973
            raw_dl=download_raw_images_by_times(portnr,starttime,stoptime,version,intervalSize)
            if raw_dl[0]:
                times=raw_dl[1]
                temperatureimages=raw_dl[2]
                del raw_dl
974
975
976
977
978
979
#                temperatureimages=temperatureimages.swapaxes(1,2)
                temperatureimages=[im.swapaxes(0,1) for im in temperatureimages]
                if give_ERROR:
                    temperatureimages,error_images=apply_calib_on_raw(temperatureimages,background,LUT,refT,gain,offset,gain_error,offset_error,True,give_ERROR)                                    
                else:
                    temperatureimages=apply_calib_on_raw(temperatureimages,background,LUT,refT,gain,offset,gain_error,offset_error,True,give_ERROR)                                    
980
            else:
981
982
983
984
985
986
987
988
989
990
991
992
993
                raise Exception("cannot download the raw images")
        valid=True
        for i in range(len(temperatureimages)):
            try:
                check_temperature_range(times[0],np.max(temperatureimages)-273.15,np.min(temperatureimages)-273.15,portnr,t_exp,cfilter)
            except Exception as E:
                print(E)
                valid=False
                i=len(temperatureimages)
        if give_ERROR:
            return success,times,temperatureimages,valid,error_images
        else:
            return success,times,temperatureimages,valid          
994
    except:
995
996
997
        print("cannot find program")
        return False,0,-1,False

998
999
def get_temp_from_raw_by_program_V2(portnr,program,time_s=0,emi=0.8,version=0,threads=1,give_ERROR=False,use_firstframe_as_background=False):
    return get_temp_from_raw_by_program(portnr,program,time_s=time_s,emi=emi,T_version=2,version=version,threads=threads,give_ERROR=give_ERROR,use_firstframe_as_background=use_firstframe_as_background)
1000
  
1001
1002
def get_temp_from_raw_by_program(portnr,program,time_s=0,emi=0.8,T_version=2,version=0,threads=1,give_ERROR=False,use_firstframe_as_background=False,back_emissivity=0.8):
    background,LUT,refT,gain,offset,badpixels,t_exp,cfilter,gain_error,offset_error=get_calib_data(portnr,program,emi,T_version,version,back_emissivity)
1003
    print(datetime.datetime.now(),"raw download start")
1004
1005
1006
1007
    if fastDL: 
        exist,time,frames=download_raw_images_by_program_via_png(portnr,program,time_s,version,threads)
    else:
        exist,time,frames=download_raw_images_by_program(portnr,program,time_s,version)
1008
1009
1010
1011
        if exist:
            frames=[im.swapaxes(0,1) for im in frames]
        else:
            raise Exception("no data found")
Holger Niemann's avatar
Holger Niemann committed
1012
    print(datetime.datetime.now(),"raw download finished")
Holger Niemann's avatar
Holger Niemann committed
1013
    FOV=get_FOV_mask(portnr)
1014
1015
    if use_firstframe_as_background:
        bim=apply_NUC([frames[0]],gain,offset)
Holger Niemann's avatar
bugfix    
Holger Niemann committed
1016
        background=get_average_background_recangle(portnr,bim[0])
1017
1018
1019
1020
1021
    if give_ERROR:
        frames,error_images=apply_calib_on_raw(frames,background,LUT,refT,gain,offset,gain_error,offset_error,False,give_ERROR)
    else:
        frames=apply_calib_on_raw(frames,background,LUT,refT,gain,offset,gain_error,offset_error,False,give_ERROR)
    
Holger Niemann's avatar
Holger Niemann committed
1022
    for i in range(len(frames)):
1023
        frames[i]=(frames[i]*FOV).astype(np.float32)
Holger Niemann's avatar
Holger Niemann committed
1024
    print(datetime.datetime.now(),"correcting bad pixels")
1025
    frames=IR_tools.correct_images(frames,badpixels)
1026
1027
    print(datetime.datetime.now(),"checking temperaturerange")
    valid=True
1028
1029
1030
1031
1032
1033
1034
#    for i in range(len(frames)):
    try:
        check_temperature_range(time[0],np.max(frames)-273.15,np.min(frames[:][np.nonzero(frames[i])])-273.15,portnr,t_exp,cfilter)
    except Exception as E:
        print(E)
        valid=False
#        i=len(frames)
1035
1036
1037
1038
    if give_ERROR:
        return exist,time,frames,valid,error_images
    else:
        return exist,time,frames,valid
1039

1040
1041
1042
1043
1044
def get_temp_from_raw_by_program_fullthreads(portnr,program,time_s=0,emi=0.8,T_version=2,version=0,threads=1,give_ERROR=False,check_range=True):
    if threads==1 or not fastDL:
        return get_temp_from_raw_by_program(portnr,program,time_s,emi,T_version,version,threads,give_ERROR)
    else:
        background,LUT,refT,gain,offset,badpixels,t_exp,cfilter,gain_error,offset_error=get_calib_data(portnr,program,emi,T_version,version)
1045
        FOV=get_FOV_mask(portnr)        
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
        prog=AKF_1.get_program_from_PID(program)
        if prog[0]:
            starttime=prog[1]['trigger']['1'][0]
            stoptime=prog[1]['trigger']['6'][0]
            success=True
            OP=get_OP_by_time(starttime)
            Cam=portcamdict[OP]['AEF'+str(portnr)]
            if Cam.split("_")[0]=="Infratec":#camera=="INFRATEC" or camera=="infratec" or camera=="Infratec":
                if version==0:
                    version=get_latest_version("QRT_INFRATEC/"+"AEF"+str(portnr)+"_raw_DATASTREAM")
                larchivepath="Test/raw/W7X/"+"QRT_INFRATEC/"+"AEF"+str(portnr)+"_raw_DATASTREAM/V"+str(version)+"/0/raw"
            elif Cam.split("_")[0]=="IRCam":#camera=="IRCAM" or camera=="IRcam" or camera=="ircam":
                if version==0:
                    version=get_latest_version("QRT_IRCAM/"+"AEF"+str(portnr)+"_raw_DATASTREAM")
                larchivepath="Test/raw/W7X/"+"QRT_IRCAM/"+"AEF"+str(portnr)+"_raw_DATASTREAM/V"+str(version)+"/0/raw"
            else:
                raise Exception("Port number does not fit the known cameras")
            if type(time_s)==list:
                tstart=time_s[0]
                tstop=time_s[1]
                if tstop<tstart:
                    raise Exception("endtime before starttime")
                stdate=datetime.datetime.utcfromtimestamp((starttime-100)/1e9+tstart)
                stdate=stdate.isoformat()
                enddate=datetime.datetime.utcfromtimestamp((starttime)/1e9+tstop)  
                enddate=enddate.isoformat()
            else:
                stdate=datetime.datetime.utcfromtimestamp((starttime-100)/1e9)
                stdate=stdate.isoformat()
                if time_s==0:
                    enddate=datetime.datetime.utcfromtimestamp(stoptime/1e9)        
                    enddate=enddate.isoformat()
                else:
                    enddate=datetime.datetime.utcfromtimestamp((starttime)/1e9+time_s)  
                    enddate=enddate.isoformat()        
        
1082
            times=AKF_2.get_time_intervals(larchivepath,stdate.replace("T"," "),enddate.replace("T"," "))#
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
            lnt=len(times)
            tim=[]
            for i in range(lnt):
                tim.append(times[lnt-1-i][0])
            intervalls=[]
            intervalSize=int(lnt/threads)
            for i in range(threads):
                intervalls.append(int(i*intervalSize))
            intervalls.append(lnt)
            jobs = []
            out_q=multiprocessing.Queue()
            for i in range(threads):
                print("Start Thread ",i+1)                
                p = multiprocessing.Process(target=convert_raw_to_temp_thread, args=(portnr,tim[intervalls[i]:intervalls[i+1]],out_q,i,version,background,LUT,refT,gain,offset,gain_error,offset_error,give_ERROR,FOV,badpixels,))
                jobs.append(p)
                p.start()
            resultdict = []
            for i in range(threads):
                resultdict.append(out_q.get())
            for p in jobs:
                p.join()
            print("all threads are done")
            order=[]
            for ele in resultdict:
                order.append(ele[0])
                if len(np.where(np.asarray(ele[1])==False)[0])>0:
                    success=False            
            times=[]#np.array(resultdict[order.index(0)][2])
            images=[]#np.array(resultdict[order.index(0)][3])
            for i in range(threads):
                images=images+resultdict[order.index(i)][3]
                times=times+resultdict[order.index(i)][2]
            del resultdict
            if check_range:
                print(datetime.datetime.now(),"checking temperaturerange")
                valid=True
                for i in range(len(images)):
                    try:
                        check_temperature_range(times[0],np.max(images[i])-273.15,np.min(images[i][np.nonzero(images[i])])-273.15,portnr,t_exp,cfilter)
                    except Exception as E:
                        print(E)
                        valid=False
                        i=len(images)
            else:
                valid=True
        else:
            success=False
            times=[0]
            images=[0]
            valid=False
            error_images=[0]
        
        if give_ERROR:
            return success,np.array(times),images,valid,error_images
        else:
            return success,np.array(times),images,valid
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210

def get_nuced_raw_by_program(portnr,program,time_s=0,version=0,threads=1,give_ERROR=False):
    background,LUT,refT,gain,offset,badpixels,t_exp,cfilter,gain_error,offset_error=get_calib_data(portnr,program,emi=1,T_version=2,version=version)
    print(datetime.datetime.now(),"raw download start")
    if fastDL: 
        exist,time,frames=download_raw_images_by_program_via_png(portnr,program,time_s,version,threads)
    else:
        exist,time,frames=