Note: The default ITS GitLab runner is a shared resource and is subject to slowdowns during heavy usage.
You can run your own GitLab runner that is dedicated just to your group if you need to avoid processing delays.

web.py 19.3 KB
Newer Older
1
"""### Tools to download/upload data on the web
2

3
Here are a collection of tools to work with data on the internet. Thus,
4
5
6
this module mostly requires an internet connection. Which on some
supercomputers would be turned off during a job run. In scripts, make sure to
use these to preprocess before submitting jobs.
7
8
9
10
11
"""
__author__ = 'Qusai Al Shidi'
__email__ = 'qusai@umich.edu'

import datetime as dt
12
from ftplib import FTP, all_errors
13
14
15
import gzip
from operator import itemgetter
import shutil
16
import urllib
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
from dateutil import rrule
import drms
import numpy as np
from sunpy.coordinates.sun import carrington_rotation_number
from .tools import _nearest

# Global defines
# This is straight from the format guide on spdf with nicer names as second col
# spdf_name nice_name type
OMNI_HIRES_COLS = (('ID for IMF spacecraft', 'id_imf'),
                   ('ID for SW Plasma spacecraft', 'id_sw'),
                   ('# of points in IMF averages', 'num_avg_imf'),
                   ('# of points in Plasma averages', 'num_avg_sw'),
                   ('Percent interp', 'interp'),
                   ('Timeshift, sec', 'timeshift'),
                   ('RMS, Timeshift', 'rms_timeshift'),
                   ('RMS, Phase front normal', 'rms_phase'),
                   ('Time btwn observations, sec', 'dt'),
                   ('Field magnitude average, nT', 'b'),
                   ('Bx, nT (GSE, GSM)', 'bx'),
                   ('By, nT (GSE)', 'by_gse'),
                   ('Bz, nT (GSE)', 'bz_gse'),
                   ('By, nT (GSM)', 'by'),
                   ('Bz, nT (GSM)', 'bz'),
                   ('RMS SD B scalar, nT', 'rms_sd_b'),
                   ('RMS SD field vector, nT', 'rms_sd_field'),
                   ('Flow speed, km/s', 'v'),
                   ('Vx Velocity, km/s, GSE', 'vx_gse'),
                   ('Vy Velocity, km/s, GSE', 'vy_gse'),
                   ('Vz Velocity, km/s, GSE', 'vz_gse'),
                   ('Proton Density, n/cc', 'density'),
                   ('Temperature, K', 'temperature'),
                   ('Flow pressure, nPa', 'pressure'),
                   ('Electric field, mV/m', 'e'),
                   ('Plasma beta', 'beta'),
                   ('Alfven mach number', 'alfven_mach'),
                   ('X(s/c), GSE, Re', 'x_gse'),
                   ('Y(s/c), GSE, Re', 'y_gse'),
                   ('Z(s/c), GSE, Re', 'z_gse'),
                   ('BSN location, Xgse, Re', 'bsn_x_gse'),
                   ('BSN location, Ygse, Re', 'bsn_y_gse'),
                   ('BSN location, Zgse, Re', 'bsn_z_gse'),
                   ('AE-index, nT', 'ae'),
                   ('AL-index, nT', 'al'),
                   ('AU-index, nT', 'au'),
                   ('SYM/D index, nT', 'sym_d'),
                   ('SYM/H index, nT', 'sym_h'),
                   ('ASY/D index, nT', 'asy_d'),
                   ('ASY/H index, nT', 'asy_h'),
                   ('PC(N) index', 'pc_n'),
                   ('Magnetosonic mach number', 'mach'),
                   )

OMNI_LORES_COLS = (('Bartels rotation number', 'bartels'),
                   ('ID for IMF spacecraft', 'id_imf'),
                   ('ID for SW plasma spacecraft', 'id_sw'),
                   ('# of points in the IMF averages', 'num_avg_imf'),
                   ('# of points in the plasma averages', 'num_avg_sw'),
                   ('Field Magnitude Average |B|', 'b_avg'),
                   ('Magnitude of Average Field Vector', 'b'),
                   ('Lat.Angle of Aver. Field Vector', 'b_angle_lat'),
                   ('Long.Angle of Aver.Field Vector', 'b_angle_lon'),
                   ('Bx GSE, GSM', 'bx'),
                   ('By GSE', 'by_gse'),
                   ('Bz GSE', 'bz_gse'),
                   ('By GSM', 'by'),
                   ('Bz GSM', 'bz'),
                   ('sigma|B|', 'sigma_b_avg'),
                   ('sigma B', 'sigma_b'),
                   ('sigma Bx', 'sigma_bx'),
                   ('sigma By', 'sigma_by'),
                   ('sigma Bz', 'sigma_bz'),
                   ('Proton temperature', 'temperature'),
                   ('Proton Density', 'density'),
                   ('Plasma (Flow) speed', 'v'),
                   ('Plasma Flow Long. Angle', 'v_angle_lat'),
                   ('Plasma  Flow Lat. Angle', 'v_angle_lon'),
                   ('Na/Np', 'na_np'),
                   ('Flow Pressure', 'dyn_p'),
                   ('sigma T', 'sigma_t'),
                   ('sigma N', 'sigma_n'),
                   ('sigma V', 'sigma_v'),
                   ('sigma phi V', 'sigma_phi_v'),
                   ('sigma theta V', 'sigma_theta_v'),
                   ('sigma-Na/Np', 'sigma_na_np'),
                   ('Electric field', 'e'),
                   ('Plasma beta', 'beta'),
                   ('Alfven mach number', 'alfven_mach'),
                   ('Kp', 'kp'),
                   ('R', 'sunspot'),
                   ('DST Index', 'dst'),
                   ('AE-index', 'ae'),
                   ('Proton flux number/cmsq sec sr >1 Mev', 'p_flux_1'),
                   ('Proton flux number/cmsq sec sr >2 Mev', 'p_flux_2'),
                   ('Proton flux number/cmsq sec sr >4 Mev', 'p_flux_4'),
                   ('Proton flux number/cmsq sec sr >10 Mev', 'p_flux_10'),
                   ('Proton flux number/cmsq sec sr >30 Mev', 'p_flux_30'),
                   ('Proton flux number/cmsq sec sr >60 Mev', 'p_flux_60'),
                   ('Flag(***)', 'flag'),
                   ('ap-index', 'ap'),
                   ('f10.7_index', 'f10_7'),
                   ('PC(N) index', 'pc_n'),
                   ('AL-index', 'al'),
                   ('AU-index', 'au'),
                   ('Magnetosonic mach number', 'mach'),
                   )
123
124
125
126
127
128
129
130
131
132
133
134
135
136


def get_omni_data(time_from, time_to, **kwargs):
    """Retrieve omni solar wind data over http.

    This will download omni data from https://spdf.gsfc.nasa.gov/pub/data/omni
    and put it into a dictionary. If your data is large, then make a csv and
    use swmfpy.io.read_omni_data().

    Args:
        time_from (datetime.datetime): The start time of the solar wind
                                       data that you want to receive.
        time_to (datetime.datetime): The end time of the solar wind data
                                     you want to receive.
137
138
139
140
141
        **kwargs:
            original_colnames (bool): Use the original column names from the
                                      spdf specification. The alternative is
                                      nicer and shorter names. Defaults to
                                      False.
142
143
144
            resolution (str): (default: 'high') Here you can choose 'high' or
                              'low' resolution omni data. Some columns appear
                              in one but not the other.
145
146
147
148
149
150
151
152

    Returns:
        dict: This will be a list of *all* columns
              available in the omni data set.

    Examples:
        ```python
        import datetime
153
        import swmfpy.web
154

155
156
157
158
        storm_start = datetime.datetime(year=2000, month=1, day=1)
        storm_end = datetime.datetime(year=2000, month=2, day=15)
        data = swmfpy.web.get_omni_data(time_from=storm_start,
                                        time_to=storm_end)
159
160
161
162
        # or for low res
        data = swmfpy.web.get_omni_data(time_from=storm_start,
                                        time_to=storm_end,
                                        resolution='low')
163
164
        ```
    """
165
166
167
    # Author: Qusai Al Shidi
    # Email: qusai@umich.edu

168
    # Initialize
169
    return_data = {}
170
    return_data['times'] = []
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
    name_type = int(not kwargs.get('original_colnames', False))
    name_type = itemgetter(name_type)
    resolution = kwargs.get('resolution', 'high')
    # omni cols do not include time cols
    omni = {
        'high': {
            'urls': _urls_omni_hires,
            'cols': list(map(name_type, OMNI_HIRES_COLS)),
            'parsetime': lambda cols: (dt.datetime(int(cols[0]), 1, 1,
                                                   int(cols[2]),
                                                   int(cols[3]))
                                       + dt.timedelta(int(cols[1])-1)),
            'ntimecols': 4,  # Minute
            },
        'low': {
            'urls': _urls_omni_lores,
            'cols': list(map(name_type, OMNI_LORES_COLS)),
            'parsetime': lambda cols: (dt.datetime(int(cols[0]), 1, 1,
                                                   int(cols[2]))
                                       + dt.timedelta(int(cols[1])-1)),
            'ntimecols': 3,  # Hourly
            },
        }
    omni = omni[resolution]  # To save line space
    for col_name in omni['cols']:
        return_data[col_name] = []

    # Iterate by url to save RAM
    for url in omni['urls'](time_from, time_to):
200
201

        # Parse omni data
202
        for line in list(urllib.request.urlopen(url)):
203
            cols = line.decode('ascii').split()
204
205
206

            time = omni['parsetime'](cols)
            if time_from <= time <= time_to:
207
                return_data['times'] += [time]
208
209
210
                # Assign the data from after the time columns
                for col_name, value in zip(omni['cols'],
                                           cols[omni['ntimecols']:]):
211
                    if _check_bad_omni_num(value):
212
                        return_data[col_name] += [None]
213
                    else:
214
                        return_data[col_name] += [float(value)]
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
    for col_name in omni['cols']:
        return_data[col_name] = np.array(return_data[col_name],
                                         dtype=float)
    return return_data


def _urls_omni_hires(time_from, time_to):
    """Returns hires omni urls from time_from to time_to
    """
    prefix = 'https://spdf.gsfc.nasa.gov/pub/data/omni/'
    prefix += 'high_res_omni/monthly_1min/'
    for date in rrule.rrule(rrule.MONTHLY,
                            dtstart=time_from,
                            until=dt.datetime(time_to.year,
                                              time_to.month+1,
                                              1)):
        suffix = 'omni_min'
        suffix += str(date.year) + str(date.month).zfill(2)
        suffix += '.asc'
        yield prefix+suffix


def _urls_omni_lores(time_from, time_to):
    """Returns lores omni urls from time_from to time_to
    """
    prefix = 'https://spdf.gsfc.nasa.gov/pub/data/omni/'
    prefix += 'low_res_omni/'
    for year in range(time_from.year, time_to.year+1):
        suffix = 'omni2_'
        suffix += str(year)
        suffix += '.dat'
        yield prefix+suffix
Qusai Al Shidi's avatar
Qusai Al Shidi committed
248
249


250
def _check_bad_omni_num(value_string):
251
252
253
    """Returns true if bad or false if not. Bad numbers usually just have 9s
       in omni.
    """
254
    for char in value_string:
255
        if char not in ('9', '.'):
256
257
258
259
            return False
    return True


260
def download_magnetogram_hmi(mag_time, hmi_map='hmi.B_720s', **kwargs):
261
262
263
    """Downloads HMI vector magnetogram fits files.

    This will download vector magnetogram FITS files from
264
    Joint Science Operations Center (JSOC) near a certain hour.
265

266
    This unfortunately depends on sunpy and drms, if you don't have it try,
267
268

    ```bash
269
    pip install -U --user sunpy drms
270
271
272
    ```

    Args:
273
274
        mag_time (datetime.datetime): Time after which to find
                                      vector magnetograms.
275
276
        hmi_map (str): JSOC prefix for hmi maps. Currently can only do
                       'hmi.B_720s' and 'hmi.b_synoptic.small'.
277
278
279
280
281
282

    **kwargs:
        download_dir (str): Relative directory to download to.
        verbose (bool): (default False) print out the files it's downloading.

    Returns:
Qusai Al Shidi's avatar
Qusai Al Shidi committed
283
        str: list of filenames downloaded.
284
285
286

    Raises:
        ImportError: If module `drms` is not found.
287
288
        FileNotFoundError: If the JSOC doesn't have the magnetograms for that
                           time.
289
290
291
292
293
294
295
296
297
298

    Examples:
        ```python
        from swmfpy.web import download_magnetogram_hmi
        import datetime as dt

        # I am interested in the hmi vector magnetogram from 2014, 2, 18
        time_mag = dt.datetime(2014, 2, 18, 10)  # Around hour 10

        # Calling it will download
299
        filenames = download_magnetogram_hmi(mag_time=time_mag,
300
                                             hmi_map='B_720s',
301
302
303
304
305
306
                                             download_dir='mydir/')

        # To see my list
        print('The magnetograms I downloaded are:', filenames)

        # You may call and ignore the file list
307
308
309
        download_magnetogram_hmi(mag_time=time_mag,
                                 hmi_map='b_synoptic_small',
                                 download_dir='mydir')
310
311
312
        ```
    """

313
314
315
316
    get_urls = {
        'hmi.B_720s': _get_urls_hmi_b720,
        'hmi.b_synoptic_small': _get_urls_hmi_b_synoptic_small,
        }
317
318
    client = drms.Client()

319
    urls = get_urls[hmi_map](client, mag_time)
320

321
322
323
    # Download data
    if kwargs.get('verbose', False):
        print('Starting download of magnetograms:\n')
324
    return_name = ''
325
326
327
    download_dir = kwargs.get('download_dir', '')
    if not download_dir.endswith('/') and download_dir != '':
        download_dir += '/'
328
    for data_time, mag_url in urls:
329
330
        if mag_url == 'BadSegLink':  # JSOC will return this if not found
            raise FileNotFoundError('Could not find those HMI magnetograms.')
331
        filename = 'hmi_' + str(data_time).replace(' ', '_')  # Add timestamp
332
333
334
335
336
337
338
339
340
        filename += '_' + mag_url.split('/')[-1]  # Last is filename
        url = 'http://jsoc.stanford.edu' + mag_url
        if kwargs.get('verbose', False):
            print(f'Downloading from {url} to {download_dir+filename}.')
        with urllib.request.urlopen(url) as fits_file:
            with open(download_dir+filename, 'wb') as local_file:
                local_file.write(fits_file.read())
        if kwargs.get('verbose', False):
            print(f'Done writing {download_dir+filename}.\n')
341
        return_name = download_dir+filename
342
343
344
345

    if kwargs.get('verbose', False):
        print('Completed downloads.\n')

346
    return return_name
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
def _get_urls_hmi_b_synoptic_small(client, mag_time):
    """Returns for #download_magnetogram_hmi needed urls

    Args:
        client (drms.Client): To query and return urls.
        mag_time (datetime.datetime): To find nearest magnetogram.

    Returns:
        generator that yields (datetime.datetime, str): Time of magnetogram,
            suffix url of magnetogram
    """

    cr_number = int(round(carrington_rotation_number(mag_time)))
    query_string = f'hmi.b_synoptic_small[{int(round(cr_number))}]'
    components = ['Bp', 'Bt', 'Br']
    data = client.query(query_string, seg=components)
    # Generator to find the nearest time
    prefix_str = 'CR' + str(cr_number) + '_' + str(mag_time)
    urls = ((prefix_str, data[component][0]) for component in components)
    return urls


def _get_urls_hmi_b720(client, mag_time):
    """Returns for #download_magnetogram_hmi needed urls for hmi.B_720s

    Args:
        client (drms.Client): To query and return urls.
        mag_time (datetime.datetime): To find nearest magnetogram.

    Returns:
        generator that yields (datetime.datetime, str): Time of magnetogram,
            suffix url of magnetogram
    """
    query_string = 'hmi.B_720s'
    query_string += f'[{mag_time.year}.'
    query_string += f'{str(mag_time.month).zfill(2)}.'
    query_string += f'{str(mag_time.day).zfill(2)}_'
    query_string += f'{str(mag_time.hour).zfill(2)}'
387
    query_string += '/1h]'
388
389
390
391
392
393
394
395
    data = client.query(query_string, key='T_REC', seg='field')
    times = drms.to_datetime(data[0].T_REC)
    nearest_time = _nearest(mag_time, times)
    # Generator to find the nearest time
    urls = ((data_time, mag_url) for (data_time, mag_url)
            in zip(times, data[1].field) if data_time == nearest_time)
    return urls

396

Qusai Al Shidi's avatar
Qusai Al Shidi committed
397
def download_magnetogram_adapt(time, map_type='fixed', **kwargs):
Qusai Al Shidi's avatar
Qusai Al Shidi committed
398
    """This routine downloads GONG ADAPT magnetograms.
Qusai Al Shidi's avatar
Qusai Al Shidi committed
399
400

    Downloads ADAPT magnetograms from ftp://gong2.nso.edu/adapt/maps/gong/
401
    to a local directory. It will download all maps with the regex file
402
    pattern: adapt4[0,1]3*yyyymmddhh
Qusai Al Shidi's avatar
Qusai Al Shidi committed
403
404
405
406
407
408

    Args:
        time (datetime.datetime): Time in which you want the magnetogram.
        map_type (str): (default: 'fixed')
                        Choose either 'fixed' or 'central' for
                        the map type you want.
409
410
411
412

    **kwargs:
        download_dir (str): (default is current dir) Relative directory
                            where you want the maps to be downloaded.
Qusai Al Shidi's avatar
Qusai Al Shidi committed
413

414
415
416
    Returns:
        str: First unzipped filename found.

Qusai Al Shidi's avatar
Qusai Al Shidi committed
417
    Raises:
418
419
        NotADirectoryError: If the adapt maps directory
                            is not found on the server.
Qusai Al Shidi's avatar
Qusai Al Shidi committed
420
421
        ValueError: If map_type is not recognized.
                    (i.e. not 'fixed' or 'central')
422
        FileNotFoundError: If maps were not found.
Qusai Al Shidi's avatar
Qusai Al Shidi committed
423
424
425
426
427
428

    Examples:
        ```python
        import datetime as dt

        # Use datetime objects for the time
429
        time_flare = dt.datetime(2018, 2, 12, hour=10)
Qusai Al Shidi's avatar
Qusai Al Shidi committed
430
431
432
433
        swmfpy.web.download_magnetogram_adapt(time=time_flare,
                                              map_type='central',
                                              download_dir='./mymaps/')
        ```
Qusai Al Shidi's avatar
Qusai Al Shidi committed
434
    """
Qusai Al Shidi's avatar
Qusai Al Shidi committed
435
436
437
438
439
440
441
442
    # Author: Zhenguang Huang
    # Email: zghuang@umich.edu

    if map_type == 'fixed':
        map_id = '0'
    elif map_type == 'central':
        map_id = '1'
    else:
443
        raise ValueError('Not recognized type of ADAPT map')
Qusai Al Shidi's avatar
Qusai Al Shidi committed
444
445

    # Go to the the ADAPT ftp server
446
    ftp = ftplib.FTP('gong2.nso.edu')
Qusai Al Shidi's avatar
Qusai Al Shidi committed
447
448
449
450
451
452
453
454
455
456
    ftp.login()

    # Only ADAPT GONG is considered
    ftp.cwd('adapt/maps/gong')

    # Go to the specific year
    try:
        ftp.cwd(str(time.year))
    except ftplib.all_errors:
        ftp.quit()
457
        raise NotADirectoryError('Cannot go to the specific year directory')
Qusai Al Shidi's avatar
Qusai Al Shidi committed
458

459
460
461
462
    # ADAPT maps only contains the hours for even numbers
    if time.hour % 2 != 0:
        print('Warning: Hour must be an even number.',
              'The entered hour value is changed to',
Qusai Al Shidi's avatar
Qusai Al Shidi committed
463
              time.hour//2*2)
Qusai Al Shidi's avatar
Qusai Al Shidi committed
464
465
466
467
468
    # Only consider the public (4) Carrington Fixed (0) GONG (3) ADAPT maps
    file_pattern = 'adapt4' + map_id + '3*' \
        + str(time.year).zfill(4) \
        + str(time.month).zfill(2) \
        + str(time.day).zfill(2) \
Qusai Al Shidi's avatar
Qusai Al Shidi committed
469
        + str(time.hour//2*2).zfill(2) + '*'
470
    # adapt4[0,1]3*yyyymmddhh
Qusai Al Shidi's avatar
Qusai Al Shidi committed
471
472
473
474

    filenames = ftp.nlst(file_pattern)

    if len(filenames) < 1:
475
476
        raise FileNotFoundError('Could not find a file that matches'
                                + 'the pattern.')
Qusai Al Shidi's avatar
Qusai Al Shidi committed
477
478
479
480
481
482
483
484
485
486
487
488

    for filename in filenames:
        # open the file locally
        directory = kwargs.get('download_dir', './')
        if directory[-1] != '/':
            directory += '/'
        with open(directory + filename, 'wb') as fhandle:
            # try to download the magnetogram
            try:
                ftp.retrbinary('RETR ' + filename, fhandle.write)
            except ftplib.all_errors:
                ftp.quit()
489
                raise FileNotFoundError('Cannot download ', filename)
Qusai Al Shidi's avatar
Qusai Al Shidi committed
490
491
492
493
494
495
496
497
498
499

        # unzip the file
        if '.gz' in filename:
            filename_unzip = filename.replace('.gz', '')
            with gzip.open(directory + filename, 'rb') as s_file:
                with open(directory + filename_unzip, 'wb') as d_file:
                    shutil.copyfileobj(s_file, d_file, 65536)

    # close the connection
    ftp.quit()
500
501

    # return first file name if all goes well
502
503
504
505
506
    return_names = filenames
    for index, filename in enumerate(return_names):
        if '.gz' in filename:
            return_names[index] = filename.replace('.gz', '')
    return return_names