Skip to content
Snippets Groups Projects
manage_GSNdata.py 34.4 KiB
Newer Older
perma's avatar
perma committed
'''
perma's avatar
perma committed
Data manager for PermaSense data. Initially created for the paper "A decade of detailed observations (2008--2018) in steep 
perma's avatar
perma committed
3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 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 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 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 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 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475
bedrock permafrost at Matterhorn Hoernligrat (Zermatt, CH)"

Script to perform the experiments

Copyright (c) 201, Swiss Federal Institute of Technology (ETH Zurich)
All rights reserved.

Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:

* Redistributions of source code must retain the above copyright notice, this
  list of conditions and the following disclaimer.

* Redistributions in binary form must reproduce the above copyright notice,
  this list of conditions and the following disclaimer in the documentation
  and/or other materials provided with the distribution.

* Neither the name of the copyright holder nor the names of its
  contributors may be used to endorse or promote products derived from
  this software without specific prior written permission.

THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.

@date: March 19, 2020
@author: Samuel Weber, Jan Beutel and Matthias Meyer

usage: manage_GSNdata.py [-h] [--gsn2raw] [--load] [--filter] [--clean]
                         [--aggregationInterval AGGREGATIONINTERVAL]
                         [--export2csv] [--sanityPlot] [--gsn2img]
                         [--nImg NIMG] [-p PATH] [-y1 YEARBEGIN]
                         [-m1 MONTHBEGIN] [-d1 DAYBEGIN] [-y2 YEAREND]
                         [-m2 MONTHEND] [-d2 DAYEND]

optional arguments:
  -h, --help            show this help message and exit
  --gsn2raw             Get raw data from GSN and store locally (step1)
  --load                Load locally stored data (step2)
  --filter              Filter data (according reference values, step3)
  --clean               Clean data manually (step4)
  --aggregationInterval AGGREGATIONINTERVAL
                        Aggregate data over timewindows of X minutes (step5)
  --export2csv          Export data in yearly csv files (step6)
  --sanityPlot          Plot for sanity check (step7)
  --gsn2img             Downlod images from GSN and convert NEF to JPEG
  --nImg NIMG           Number of images to download and convert
  -p PATH, --path PATH  Relative path for the data output
  -y1 YEARBEGIN, --yearBegin YEARBEGIN
                        Year begin
  -m1 MONTHBEGIN, --monthBegin MONTHBEGIN
                        Month begin
  -d1 DAYBEGIN, --dayBegin DAYBEGIN
                        Day begin
  -y2 YEAREND, --yearEnd YEAREND
                        Year end
  -m2 MONTHEND, --monthEnd MONTHEND
                        Month end
  -d2 DAYEND, --dayEnd DAYEND
                        Day end
'''
def main():
    ## ## ## ## ## ## ## ## ## ## ## ## ## ## ## ## ## ## ## ## ## ## ## ## ## 
    ## SETUP PYTHON ENVIRONMENT
    ## ## ## ## ## ## ## ## ## ## ## ## ## ## ## ## ## ## ## ## ## ## ## ## ## 
    
    # Load functions
    import sys
    import socket
    import argparse
    import os as os
    import numpy as np
    import pandas as pd
    import datetime as dt
    import matplotlib as mpl

    # For proper plotting on server
    if socket.gethostname() == 'tik43x':
        mpl.use('Agg')
    import matplotlib.pyplot as plt

    # faster plotting
    import matplotlib.style as mplstyle
    mplstyle.use('fast')
    # remove matplotlib warning 
    from pandas.plotting import register_matplotlib_converters
    register_matplotlib_converters()
    
    
    # Load functions in relative path
    sys.path.append('~/permasense/')
    from permasense.GSNdata import get_GSNdata, save_data, load_data, filter_data, clean_data, get_GSNimg
    
    ## ## ## ## ## ## ## ## ## ## ## ## ## ## ## ## ## ## ## ## ## ## ## ## ## 
    ## ASSIGN ARGUMENTS TO VARIABLES
    ## ## ## ## ## ## ## ## ## ## ## ## ## ## ## ## ## ## ## ## ## ## ## ## ## 
    args = parseArguments()
    
    # Define path to data
    PATH_DATA = args.path
    
    # Define time range
    TBEG = dt.datetime(args.yearBegin,args.monthBegin,args.dayBegin)
    TEND = dt.datetime(args.yearEnd,args.monthEnd,args.dayEnd)
    
    # Get raw data from GSN (step1) and produce derived data product (step2 - step7)
    GSN2RAW = args.gsn2raw
    
    LOAD = args.load
    FILTER = args.filter
    CLEAN = args.clean
    AGGREGATION_INTERVAL = args.aggregationInterval
    EXPORT2CSV = args.export2csv
    SANITY_PLOT = args.sanityPlot
    if FILTER | CLEAN | EXPORT2CSV | SANITY_PLOT:
        LOAD = True
    
    # Get high-resolution images (.NEF) and convert to .JPG
    GSN2IMG = args.gsn2img
    N_IMG = args.nImg
    KEEP_NEF = False
    # max number of images to download
    DOWNLOAD_LIMIT = 30000
    #DOWNLOAD_MAX_SIZE =  20000
    DOWNLOAD_MAX_SIZE = 1000000
    RESIZE = False
    #resize_w, resize_h = 356, 536
    RESIZE_WIDTH = 712
    RESIZE_HEIGHT = 1072  
    
    ## ## ## ## ## ## ## ## ## ## ## ## ## ## ## ## ## ## ## ## ## ## ## ## ## 
    ## DICTIONARIES ASSIGNING 'VIRTUAL_SENSOR' TO 'POSITION'
    ## ## ## ## ## ## ## ## ## ## ## 'resistivity_fracture', ## ## ## ## ## ## ## ## ## ## ## ## ## ## 
    DEPO_VS = {
            #'AD01': {'displacement', 'temperature_rock'},      #OK
            #'AD02': {'displacement'},                          #OK
            #'AD03': {'displacement'},                          #OK
            #'AD04': {'displacement', 'temperature_rock'},      #OK
            #'AD05': {'displacement'},                          #OK
            #'AD06': {'displacement', 'temperature_rock'},      #OK
            #'AD07': {'temperature_rock'},                      #OK
            #'AD08': {'temperature_rock'},                      #OK
            #'AD09': {'temperature_rock'},                      #OK
            
            # 'DH00': {'RD01': {'gps_differential__batch__daily','gps_differential__rtklib__daily'}},                    #                    OK
            # 'DH05': {'DI55': {'gps_differential__batch__daily','gps_differential__rtklib__daily'}},                    #                    OK
            # 'DH06': {'RA01': {'gps_differential__batch__daily','gps_differential__rtklib__daily','gps_inclinometer'}}, #000deg,             OK
            # 'DH07': {'DI57': {'gps_differential__batch__daily','gps_differential__rtklib__daily'}},                    #                    OK
            # 'DH09': {'RA02': {'gps_differential__batch__daily','gps_differential__rtklib__daily','gps_inclinometer'}}, #000deg,             OK
            # 'DH12': {'BH03': {'gps_differential__batch__daily','gps_differential__rtklib__daily'}},                    #                    OK
            # 'DH15': {'DI02': {'gps_differential__batch__daily','gps_differential__rtklib__daily','gps_inclinometer'}}, #225/131/281/246deg, OK
            # 'DH17': {'DI07': {'gps_differential__batch__daily','gps_differential__rtklib__daily','gps_inclinometer'}}, #105/277/321/334deg, OK
            # 'DH21': {'LS01': {'gps_differential__batch__daily','gps_differential__rtklib__daily','gps_inclinometer'}}, #110deg,             OK
            # 'DH23': {'LS04': {'gps_differential__batch__daily','gps_differential__rtklib__daily','gps_inclinometer'}}, #225deg,             OK
            # 'DH25': {'BH07': {'gps_differential__batch__daily','gps_differential__rtklib__daily','gps_inclinometer'}}, #240deg,             OK
            # 'DH27': {'BH09': {'gps_differential__batch__daily','gps_differential__rtklib__daily','gps_inclinometer'}}, #130deg,             OK
            # 'DH29': {'ST02': {'gps_differential__batch__daily','gps_differential__rtklib__daily','gps_inclinometer'}}, #004deg,             OK
            # 'DH31': {'ST05': {'gps_differential__batch__daily','gps_differential__rtklib__daily','gps_inclinometer'}}, #124deg,             OK 
            # 'DH33': {'GU02': {'gps_differential__batch__daily','gps_differential__rtklib__daily','gps_inclinometer'}}, #335deg,             OK
            # 'DH35': {'GU03': {'gps_differential__batch__daily','gps_differential__rtklib__daily','gps_inclinometer'}}, #010deg,             OK
            # 'DH39': {'RG01': {'gps_differential__batch__daily','gps_differential__rtklib__daily'}},                    #                    OK
            # 'DH41': {'GG52': {'gps_differential__batch__daily','gps_differential__rtklib__daily'}},                    #                    OK
            # 'DH43': {'GG01': {'gps_differential__batch__daily','gps_differential__rtklib__daily','gps_inclinometer'}}, #325deg,             OK
            # 'DH44': {'GG02': {'gps_differential__batch__daily','gps_differential__rtklib__daily','gps_inclinometer'}}, #205/041deg          OK
            # 'DH55': {'BH10': {'gps_differential__batch__daily','gps_differential__rtklib__daily','gps_inclinometer'}}, #280/270/294/312deg  OK
            # 'DH56': {'RL01': {'gps_differential__batch__daily','gps_differential__rtklib__daily','gps_inclinometer'}}, #309deg              OK
            # 'DH57': {'GU04': {'gps_differential__batch__daily','gps_differential__rtklib__daily','gps_inclinometer'}}, #014deg,             OK
            # 'DH62': {'BH12': {'gps_differential__batch__daily','gps_differential__rtklib__daily','gps_inclinometer'}}, #140deg,             OK
            # 'DH63': {'BH13': {'gps_differential__batch__daily','gps_differential__rtklib__daily','gps_inclinometer'}}, #090/000deg,         OK
            # 'DH64': {'LS05': {'gps_differential__batch__daily','gps_differential__rtklib__daily','gps_inclinometer'}}, #318/330deg,         OK
            # 'DH66': {'GG66': {'gps_differential__batch__daily','gps_differential__rtklib__daily'}}, #,                                      OK
            # 'DH67': {'GG67': {'gps_differential__batch__daily','gps_differential__rtklib__daily'}}, #,                                      OK
            # 'DH70': {'RA03': {'gps_differential__batch__daily','gps_differential__rtklib__daily','gps_inclinometer'}}, #000deg,             OK
            # 'DH81': {'RAND': {'gps_differential__batch__daily','gps_differential__rtklib__daily'}},                    #,                   OK
            # 'DH82': {'WYS1': {'gps_differential__batch__daily','gps_differential__rtklib__daily','gps_inclinometer'}}, #170deg,             OK
            # 'DH83': {'LS11': {'gps_differential__batch__daily','gps_differential__rtklib__daily','gps_inclinometer'}}, #262deg,             OK
            # 'DH84': {'LS12': {'gps_differential__batch__daily','gps_differential__rtklib__daily','gps_inclinometer'}}, #006deg,             OK
            # 'DH86': {'DI03': {'gps_differential__batch__daily','gps_differential__rtklib__daily','gps_inclinometer'}}, #000deg,             OK
            # 'DH87': {'DI04': {'gps_differential__batch__daily','gps_differential__rtklib__daily','gps_inclinometer'}}, #000deg,             OK
            # 'DH88': {'LS06': {'gps_differential__batch__daily','gps_differential__rtklib__daily','gps_inclinometer'}}, #000deg,             OK
            #       #'DH89': {'SA01': {'gps_differential__batch__daily','gps_differential__rtklib__daily','gps_inclinometer'}}, #000deg
            #       #'DH91': {'SATT': {'gps_differential__batch__daily','gps_differential__rtklib__daily'}},                    #
            
            # 'DH13': {'DH13': {'vaisalawxt520prec', 'vaisalawxt520windpth'}},                                           #
            # 'DH42': {'DH42': {'vaisalawxt520prec', 'vaisalawxt520windpth'}},                                           #
            # 'DH68': {'DH68': {'vaisalawxt520prec', 'vaisalawxt520windpth'}},                                           #
            # 'DH69': {'DH69': {'vaisalawxt520prec', 'vaisalawxt520windpth'}},                                           #
            # 'DH73': {'DH73': {'radiometer__conv'}},                                                                    #

            # 'PE01': {'DIS1': {'gps_differential__batch__daily','gps_differential__rtklib__daily','gps_inclinometer'}}, #,                   OK
            # 'PE02': {'DIS2': {'gps_differential__batch__daily','gps_differential__rtklib__daily','gps_inclinometer'}}, #,                   OK
            # 'PE03': {'RIT1': {'gps_differential__batch__daily','gps_differential__rtklib__daily','gps_inclinometer'}}, #,                   OK
            # 'PE04': {'GRU1': {'gps_differential__batch__daily','gps_differential__rtklib__daily','gps_inclinometer'}}, #,                   OK
            # 'PE05': {'JAE1': {'gps_differential__batch__daily','gps_differential__rtklib__daily','gps_inclinometer'}}, #,                   OK
            # 'PE06': {'SCH1': {'gps_differential__batch__daily','gps_differential__rtklib__daily','gps_inclinometer'}}, #,                   OK
            # 'PE07': {'MUA1': {'gps_differential__batch__daily','gps_differential__rtklib__daily','gps_inclinometer'}}, #,                   OK
            # 'PE08': {'LAR1': {'gps_differential__batch__daily','gps_differential__rtklib__daily','gps_inclinometer'}}, #,                   OK
            # 'PE09': {'LAR2': {'gps_differential__batch__daily','gps_differential__rtklib__daily','gps_inclinometer'}}, #,                   OK
            # 'PE10': {'COR1': {'gps_differential__batch__daily','gps_differential__rtklib__daily','gps_inclinometer'}}, #,                   OK

            #'JJ01': {'resistivity_rock', 'temperature_rock'},      #OK
            #'JJ02': {'resistivity_rock', 'temperature_rock'},      #OK
            #'JJ03': {'resistivity_rock', 'temperature_rock'},      #OK
            #'JJ04': {'resistivity_rock', 'temperature_rock'},      #OK
            #'JJ05': {'resistivity_rock', 'temperature_rock'},      #OK
            #'JJ06': {'resistivity_rock', 'temperature_rock'},      #OK
            #'JJ07': {'resistivity_rock', 'temperature_rock'},      #OK
            #'JJ08': {'temperature_fracture'},                      #OK
            #'JJ09': {'resistivity_rock', 'temperature_rock'},      #OK
            #'JJ10': {'temperature_fracture'},                      #OK
            #'JJ13': {'temperature_rock'},                          #
            #'JJ14': {'temperature_rock'},                          #
            #'JJ18': {'temperature_rock'},                          #
            #'JJ22': {'temperature_rock'},                          #
            #'JJ25': {'temperature_rock'},                          #


            'MH01': {'MH01': {'displacement', 'temperature_fracture', 'temperature_rock'}},                                    #ok
            'MH02': {'MH02': {'displacement', 'temperature_fracture', 'temperature_rock'}},                                    #ok
            'MH03': {'MH03': {'displacement', 'temperature_fracture', 'temperature_rock'}},                                    #ok
            'MH04': {'MH04': {'displacement', 'temperature_fracture', 'temperature_rock'}},                                    #ok
            'MH05': {'MH05': {'resistivity_fracture', 'temperature_fracture'}},                                                #ok but resistivity
            'MH06': {'MH06': {'displacement', 'temperature_rock'}},                                                            #ok
            'MH07': {'MH07': {'resistivity_fracture', 'temperature_fracture'}},                                                #ok but resistivity
            'MH08': {'MH08': {'displacement', 'temperature_rock'}},                                                            #ok
            'MH09': {'MH09': {'displacement', 'temperature_fracture'}},                                                        #ok
            'MH10': {'MH10': {'resistivity_rock', 'temperature_rock'}},                                                        #ok but resistivity
            'MH11': {'MH11': {'resistivity_rock', 'temperature_rock'}},                                                        #ok but resistivity_rock
            'MH12': {'MH12': {'resistivity_rock', 'temperature_rock'}},                                                        #ok but resistivity
            'MH18': {'MH18': {'displacement'}},                                                                                #ok
            'MH20': {'MH20': {'displacement'}},                                                                                #ok
            'MH21': {'MH21': {'displacement'}},                                                                                #ok
            'MH22': {'MH22': {'displacement'}},                                                                                #ok
            'MH27': {'MH27': {'temperature_rock'}},                                                                            #ok
            'MH30': {'MH30': {'temperature_rock'}},                                                                            #ok
            'MH46': {'MH46': {'temperature_rock'}},                                                                            #ok
            'MH47': {'MH47': {'temperature_rock'}},                                                                            #ok
    
            'MH15': {'MH15': {'radiometer__conv'}},                                                                            #ok
            'MH25': {'MH25': {'vaisalawxt520prec', 'vaisalawxt520windpth'}},                                                   #ok
    
            'MH33': {'MH33': {'gps_differential__batch__daily','gps_differential__rtklib__daily','gps_inclinometer'}},         #ok
            'MH34': {'MH34': {'gps_differential__batch__daily','gps_differential__rtklib__daily','gps_inclinometer'}},         #ok
            'MH35': {'MH35': {'gps_differential__batch__daily','gps_differential__rtklib__daily','gps_inclinometer'}},         #ok
            'MH40': {'MH40': {'gps_differential__batch__daily','gps_differential__rtklib__daily'}},                            #ok
            'MH42': {'MH42': {'gps_differential__batch__daily','gps_differential__rtklib__daily'}},                            #ok
            'MH43': {'MH43': {'gps_differential__batch__daily','gps_differential__rtklib__daily'}},
            }

    DEPO_GPS = ['MH33', 'MH34', 'MH35', 'MH40', 'MH42', 'MH43']

    DEPO_IMG = {
            #'MH19': {'camera_pos19__scaled'}
            #'MH19': {'binary__mapped'}
            }
        
    
    ## ## ## ## ## ## ## ## ## ## ## ## ## ## ## ## ## ## ## ## ## ## ## ## ## 
    ## Create PATH_DATA if it does not exist yet
    ## ## ## ## ## ## ## ## ## ## ## ## ## ## ## ## ## ## ## ## ## ## ## ## ## 
    
    os.makedirs(PATH_DATA, exist_ok=True)
    os.makedirs(PATH_DATA + '/gnss_data_raw', exist_ok=True)
    os.makedirs(PATH_DATA + '/gnss_derived_data_products', exist_ok=True)
    os.makedirs(PATH_DATA + '/timelapse_images', exist_ok=True)
    os.makedirs(PATH_DATA + '/timeseries_data_raw', exist_ok=True)
    os.makedirs(PATH_DATA + '/timeseries_derived_data_products', exist_ok=True)
    os.makedirs(PATH_DATA + '/timeseries_sanity_plots', exist_ok=True)
    os.makedirs(PATH_DATA + '/timeseries_sanity_plots/' + 'channelwise', exist_ok=True)
        
    
    ## ## ## ## ## ## ## ## ## ## ## ## ## ## ## ## ## ## ## ## ## ## ## ## ## 
    ## GSN timeseries data
    ## ## ## ## ## ## ## ## ## ## ## ## ## ## ## ## ## ## ## ## ## ## ## ## ## 
    
    # Loop through keys (depo) in dictionary DEPO_VS
    #print(DEPO_VS)
    #print(DEPO_VS.items())

    for depo, depo_line in DEPO_VS.items():
        print(depo)
        print(depo_line)
        for label in depo_line:
            print('Working on data of label {:s} and depo {:s}.'.format(label, depo))
#            print('Working on data for: ',label, depo, deployment, vsensor, position)
            #print(list(depo_line[label]))

        if depo[0:2] == 'JJ':
            deployment = 'jungfraujoch'
        elif depo[0:2] == 'AD':
            deployment = 'adm'
        elif depo[0:2] == 'MH':
            deployment = 'matterhorn'
        elif depo[0:2] == 'DH':
            deployment = 'dirruhorn'
        elif depo[0:2] == 'PE':
            deployment = 'permos'
        position = int(depo[2:4])
        #print(depo)
        #print(deployment)
        #print(label)
        #print("\n")
        
        # Loop through values for a given key of dictionary DEPO_VS
        #print(sorted(list(DEPO_VS[depo])))
        #for vsensor in sorted(list(DEPO_VS[depo])):
        for vsensor in sorted(list(depo_line[label])):
            print(label, depo, deployment, vsensor, position)
            # Step 1: Query data from GSN server and save it locally
            if GSN2RAW:
                print('Data from position {:s} and virtual sensor {:s} is imported (gsn query) as pd.DataFrame and stored as csv-file.'.format(depo,vsensor))
                print('Time interval: ',TBEG, ' to ', TEND)
                df = get_GSNdata(deployment, position, vsensor, TBEG, TEND, download_max_size = DOWNLOAD_MAX_SIZE)
                if len(df) > 1:
                    print('Saving raw data')
                    #debug dtypes
                    #df.info(verbose=True)
                    #print(df)
                    if vsensor == 'gps_differential__batch__daily':
                        save_data(df, PATH_DATA + '/gnss_data_raw/', label, vsensor, deployment, file_type='csv')
                        save_data(df, PATH_DATA + '/gnss_data_raw/', label, vsensor, deployment, yearly=True, iso=True, file_type='csv')
                    elif vsensor == 'gps_differential__rtklib__daily':
                        save_data(df, PATH_DATA + '/gnss_data_raw/', label, vsensor, deployment, file_type='csv')
                        save_data(df, PATH_DATA + '/gnss_data_raw/', label, vsensor, deployment, yearly=True, iso=True, file_type='csv')
                    else:
                        save_data(df, PATH_DATA + '/timeseries_data_raw/', label, vsensor, deployment, file_type='csv')
                        save_data(df, PATH_DATA + '/timeseries_data_raw/', label, vsensor, deployment, yearly=True, iso=True, file_type='csv')
                #debug dtypes
                #df.info(verbose=True)
                #print(df.describe())
                #print(df)
                print()
                
        # Loop through values for a given key of dictionary DEPO_VS but without GPS
        DEPO_VS_but_DEPO_GPS = list(vs for vs in sorted(list(depo_line[label])) if vs != 'gps_differential__batch__daily')
        #print(DEPO_VS_but_DEPO_GPS)
        #DEPO_VS_but_DEPO_GPS = list(vs for vs in sorted(list(DEPO_VS_but_DEPO_GPS)) if vs != 'gps_differential__rtklib__daily')
        #print(DEPO_VS_but_DEPO_GPS)

        #print(sorted(list(DEPO_VS[depo])))
        #for vsensor in sorted(list(DEPO_VS[depo])):
        for vsensor in DEPO_VS_but_DEPO_GPS:
            #print(vsensor)
            df={}
            #print(df)
            # Step 2: Load data
            if LOAD:
                print('Loading data', label, depo, deployment, vsensor)
                #debug dtypes
                #df.info(verbose=True)
                if vsensor == 'gps_differential__batch__daily':
                    df = load_data(PATH_DATA + '/gnss_data_raw/', label, vsensor, file_type='csv')
                    df_raw = df.copy()
                elif vsensor == 'gps_differential__rtklib__daily':
                    df = load_data(PATH_DATA + '/gnss_data_raw/', label, vsensor, file_type='csv')
                    df_raw = df.copy()
                else:
                    df = load_data(PATH_DATA + '/timeseries_data_raw/', label, vsensor, file_type='csv')
                    df_raw = df.copy()
            
            # Step 3 (optional): Filter data (according to reference values)
            if FILTER:
                print('Filtering data', label, depo, deployment, vsensor)
                #debug dtypes
                #df.info(verbose=True)
                df = filter_data(df, depo)
            df_filt = df.copy()
            
            # Step 4 (optional): Clean data manually
            if CLEAN:
                print('Cleaning data', label, depo, deployment, vsensor)
                try:
                    df = clean_data(df, depo, vsensor)
                except Exception as i:
                    print('An issue with data cleaning raised - please check the data', i)
                    pass
            df_filt_clean = df.copy()
    
            # Step 5 (optional): Aggregate data
            if AGGREGATION_INTERVAL > 0:
                print('Aggregating data', label, depo, deployment, vsensor)
                try:
                    if vsensor == 'vaisalawxt520prec':
                        f = {'position':'mean', 'device_id':'mean', 'rain_accumulation':'sum', 'rain_duration':'sum', 'rain_intensity':'mean', 'rain_peak_intensity':'max', 'hail_accumulation':'sum', 'hail_duration':'sum', 'hail_intensity':'mean', 'hail_peak_intensity':'mean'}
                        df = df.groupby(pd.Grouper(freq=str(AGGREGATION_INTERVAL) + 'Min')).agg(f)
                    elif vsensor == 'vaisalawxt520windpth':
                        f = {'position':'mean', 'device_id':'mean', 'wind_direction_minimum':'min', 'wind_direction_average':'mean', 'wind_direction_maximum':'max', 'wind_speed_minimum':'min', 'wind_speed_average':'mean', 'wind_speed_maximum':'max', 'temp_air':'mean', 'temp_internal':'mean', 'relative_humidity':'mean', 'air_pressure':'mean'}
                        df = df.groupby(pd.Grouper(freq=str(AGGREGATION_INTERVAL) + 'Min')).agg(f)
                    elif vsensor == 'gps_differential__batch__daily':
                        print('Copying GPS data, no aggregation.')
                    #    df = df
                    elif vsensor == 'gps_differential__rtklib__daily':
                        print('Copying GPS data, no aggregation.')
                    #    df = df
                    else:
                        df = df.groupby(pd.Grouper(freq=str(AGGREGATION_INTERVAL) + 'Min')).aggregate(np.mean)
                        #df = df.groupby(pd.TimeGrouper(freq=str(AGGREGATION_INTERVAL) + 'Min')).aggregate(np.median)
                        
                except:
                    print('There was an issue with time aggregation')
                    pass
            df_agg = df.copy()
            #df_agg.info(verbose=True)
            #print(df_agg)
            #df.info(verbose=True)
            #print(df)
                                
            # Step 6: Export to csv
            if EXPORT2CSV:
                print('Exporting data', label, depo, deployment, vsensor)
                for col in ['position', 'device_id',  'ref1',  'ref2',  'ref3',  'ref4',  'ref5',  'ref6']:
                    try:
                        df_csv = df.drop([col], axis=1, inplace=False)
                    except:
                        pass
    
                try:
                    if vsensor == 'gps_differential__batch__daily':
                        save_data(df_csv, PATH_DATA + '/gnss_derived_data_products/', label, vsensor, deployment, yearly=True, iso=True, file_type='csv', float_format=4)
                    elif vsensor == 'gps_differential__rtklib__daily':
                        save_data(df_csv, PATH_DATA + '/gnss_derived_data_products/', label, vsensor, deployment, yearly=True, iso=True, file_type='csv', float_format=4)
                    else:
                        save_data(df_csv, PATH_DATA + '/timeseries_derived_data_products/', label, vsensor, deployment, yearly=True, iso=True, file_type='csv', float_format=4)
                except:
                    pass
                
            # Step 7: Plot for sanity check

            if SANITY_PLOT:
                print('Plotting data', label, depo, deployment, vsensor)
                for i, col in enumerate(df_agg):
                    if col not in ['device_id', 'device_type', 'position', 'label', 'ref1', 'ref2', 'ref3', 'ref4', 'ref5', 'ref6', 'sd_e', 'sd_n', 'sd_h', 'version', 'reference_label', 'processing_time', 'ratio_of_fixed_ambiguities']:
                        #print(col)
                        #plt.figure(figsize=(24/2.54, 18/2.54), facecolor='w', edgecolor='k')
                        plt.figure(figsize=(40/2.54, 18/2.54), facecolor='w', edgecolor='k')
                        plt.plot(df_raw[col][~df_raw[col].isnull()] , color='C0')
                        plt.plot(df_filt[col], color='C1')
                        plt.plot(df_filt_clean[col], color='C2')
                        plt.plot(df_agg[col], color='C3')
                        plt.title(' Label: {:s} \n Deployment: {:s} \n Position: {:s} \n VSENSOR: {:s}\n VARIABLE: {:s}'.format(label, deployment,depo,vsensor,col), loc='left')
                        
                        diff = df_agg[col].max() - df_agg[col].min()
                        try:
                            plt.ylim([df_agg[col].min() - diff/10, df_agg[col].max() + diff/10])
                        except:
                            pass
                        plt.legend(['raw','+ filtered', '+ cleaned', '+ aggregated'], loc="upper left")
                        ##print(mpl.rcParams['agg.path.chunksize'])
                        mpl.rcParams['agg.path.chunksize'] = 10000
                        plt.savefig('{:s}/timeseries_sanity_plots/channelwise/{:s}_{:s}_{:s}.png'.format(PATH_DATA , label, vsensor, col), dpi=200)
#                        plt.close('all')
                        mpl.rcParams['agg.path.chunksize'] = 0
                
                #plt.figure(figsize=(24/2.54, 18/2.54), facecolor='w', edgecolor='k')
                fig = plt.figure(figsize=(40/2.54, 18/2.54), facecolor='w', edgecolor='k')
                for i, col in enumerate(df_agg):
                    if col not in ['device_id', 'device_type', 'position', 'label', 'ref1', 'ref2', 'ref3', 'ref4', 'ref5', 'ref6', 'sd_e', 'sd_n', 'sd_h', 'version', 'reference_label', 'processing_time', 'ratio_of_fixed_ambiguities']:
                        #print(df_agg[col])
                        if ~df_agg[col].isnull().all():
                            plt.plot(df_agg[col], label=col)
                            #print(p1)
                            #print(col)	
                plt.title(' Label: {:s} \n Deployment: {:s} \n Position: {:s} \n VSENSOR: {:s}\n All channels'.format(label,deployment,depo,vsensor), loc='left')
                # any legend location is too slow
                # #plt.legend()
                plt.legend(loc="upper left")
perma's avatar
perma committed
                plt.xlim([TBEG, TEND])
perma's avatar
perma committed
                plt.tight_layout()
perma's avatar
perma committed
                if fig.get_axes(): # Do stuff when the figure isn't empty.
                    plt.savefig('{:s}/timeseries_sanity_plots/{:s}_{:s}_all.png'.format(PATH_DATA , label, vsensor), dpi=300)
#                plt.close('all')
                print()

    ## ## ## ## ## ## ## ## ## ## ## ## ## ## ## ## ## ## ## ## ## ## ## ## ## 
    ## GSN images
    ## ## ## ## ## ## ## ## ## ## ## ## ## ## ## ## ## ## ## ## ## ## ## ## ##
    print(GSN2IMG)
    if GSN2IMG:
        # Loop through keys (depo) in dictionary DEPO_IMG
        for depo in DEPO_IMG:
            if depo[0:2] == 'MH':
                deployment = 'matterhorn'
            position = int(depo[2:4])
            
            # Loop through values for a given key of dictionary DEPO_IMG
            for vsensor in list(DEPO_IMG[depo]):
                print(deployment, position, vsensor, TBEG, TEND)
                df = get_GSNimg(PATH_DATA + '/timelapse_images/', deployment, position, vsensor, TBEG, TEND, n_img = N_IMG, keep_nef = KEEP_NEF, download_limit = DOWNLOAD_LIMIT, download_max_size = DOWNLOAD_MAX_SIZE, resize = RESIZE, resize_w = RESIZE_WIDTH, resize_h = RESIZE_HEIGHT)



def parseArguments():
    import argparse
    import datetime as dt
    
    # Create argument parser
    parser = argparse.ArgumentParser()

    # Positional (mandatory) arguments
    #parser.add_argument("positionalArgument1", help="Positional argument 1", type=float)

    # Optional arguments
    parser.add_argument("--gsn2raw", help="Get raw data from GSN and store locally (step1)", action='store_false')
    parser.add_argument("--load", help="Load locally stored data (step2)", action='store_false')
    parser.add_argument("--filter", help="Filter data (according reference values, step3)", action='store_false')
    parser.add_argument("--clean", help="Clean data manually (step4)", action='store_false')
    parser.add_argument("--aggregationInterval", help="Aggregate data over timewindows of X minutes (step5)", type=int, default=60)
    parser.add_argument("--export2csv", help="Export data in yearly csv files (step6)", action='store_false')
    parser.add_argument("--sanityPlot", help="Plot for sanity check (step7)", action='store_false')
    parser.add_argument("--gsn2img", help="Downlod images from GSN and convert NEF to JPEG", action='store_false')
    parser.add_argument("--nImg", help="Number of images to download and convert", type=int, default=10)
    parser.add_argument("-p", "--path", help="Relative path for the data output", type=str, default='./data')
    parser.add_argument("-y1", "--yearBegin", help="Year begin", type=int, default=2008)
    #parser.add_argument("-y1", "--yearBegin", help="Year begin", type=int, default=2018)
    parser.add_argument("-m1", "--monthBegin", help="Month begin", type=int, default=1)
    parser.add_argument("-d1", "--dayBegin", help="Day begin", type=int, default=1)
    parser.add_argument("-y2", "--yearEnd", help="Year end", type=int, default=dt.datetime.now().year)
    parser.add_argument("-m2", "--monthEnd", help="Month end", type=int, default=dt.datetime.now().month)
    parser.add_argument("-d2", "--dayEnd", help="Day end", type=int, default=dt.datetime.now().day)

    # Print version
    #parser.add_argument("--version", action="version", version='%(prog)s - Version 1.0')

    # Parse argument
    return parser.parse_args()

if __name__ == "__main__":
    main()