web.py 19.1 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
13
14
15
16
import ftplib
from ftplib import FTP
import gzip
from operator import itemgetter
import shutil
17
import urllib
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
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'),
                   )
124
125
126
127
128
129
130
131
132
133
134
135
136
137


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.
138
139
140
141
142
        **kwargs:
            original_colnames (bool): Use the original column names from the
                                      spdf specification. The alternative is
                                      nicer and shorter names. Defaults to
                                      False.
143
144
145
            resolution (str): (default: 'high') Here you can choose 'high' or
                              'low' resolution omni data. Some columns appear
                              in one but not the other.
146
147
148
149
150
151
152
153

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

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

156
157
158
159
        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)
160
161
        ```
    """
162
163
164
    # Author: Qusai Al Shidi
    # Email: qusai@umich.edu

165
    # Initialize
166
    return_data = {}
167
    return_data['times'] = []
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
    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):
197
198

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

            time = omni['parsetime'](cols)
            if time_from <= time <= time_to:
204
                return_data['times'] += [time]
205
206
207
                # Assign the data from after the time columns
                for col_name, value in zip(omni['cols'],
                                           cols[omni['ntimecols']:]):
208
                    if _check_bad_omni_num(value):
209
                        return_data[col_name] += [None]
210
                    else:
211
                        return_data[col_name] += [float(value)]
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
    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
245
246


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


257
def download_magnetogram_hmi(mag_time, hmi_map='hmi.B_720s', **kwargs):
258
259
260
    """Downloads HMI vector magnetogram fits files.

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

263
    This unfortunately depends on sunpy and drms, if you don't have it try,
264
265

    ```bash
266
    pip install -U --user sunpy drms
267
268
269
    ```

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

    **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
280
        str: list of filenames downloaded.
281
282
283

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

    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
296
        filenames = download_magnetogram_hmi(mag_time=time_mag,
297
                                             hmi_map='B_720s',
298
299
300
301
302
303
                                             download_dir='mydir/')

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

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

310
311
312
313
    get_urls = {
        'hmi.B_720s': _get_urls_hmi_b720,
        'hmi.b_synoptic_small': _get_urls_hmi_b_synoptic_small,
        }
314
315
    client = drms.Client()

316
    urls = get_urls[hmi_map](client, mag_time)
317

318
319
320
    # Download data
    if kwargs.get('verbose', False):
        print('Starting download of magnetograms:\n')
321
    return_name = ''
322
323
324
    download_dir = kwargs.get('download_dir', '')
    if not download_dir.endswith('/') and download_dir != '':
        download_dir += '/'
325
    for data_time, mag_url in urls:
326
327
        if mag_url == 'BadSegLink':  # JSOC will return this if not found
            raise FileNotFoundError('Could not find those HMI magnetograms.')
328
        filename = 'hmi_' + str(data_time).replace(' ', '_')  # Add timestamp
329
330
331
332
333
334
335
336
337
        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')
338
        return_name = download_dir+filename
339
340
341
342

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

343
    return return_name
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
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)}'
384
    query_string += '/1h]'
385
386
387
388
389
390
391
392
    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

393

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

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

    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.
406
407
408
409

    **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
410

411
412
413
    Returns:
        str: First unzipped filename found.

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

    Examples:
        ```python
        import datetime as dt

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

    if map_type == 'fixed':
        map_id = '0'
    elif map_type == 'central':
        map_id = '1'
    else:
440
        raise ValueError('Not recognized type of ADAPT map')
Qusai Al Shidi's avatar
Qusai Al Shidi committed
441
442
443
444
445
446
447
448
449
450
451
452
453

    # Go to the the ADAPT ftp server
    ftp = FTP('gong2.nso.edu')
    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()
454
        raise NotADirectoryError('Cannot go to the specific year directory')
Qusai Al Shidi's avatar
Qusai Al Shidi committed
455

456
457
458
459
    # 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
460
              time.hour//2*2)
Qusai Al Shidi's avatar
Qusai Al Shidi committed
461
462
463
464
465
    # 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
466
        + str(time.hour//2*2).zfill(2) + '*'
467
    # adapt4[0,1]3*yyyymmddhh
Qusai Al Shidi's avatar
Qusai Al Shidi committed
468
469
470
471

    filenames = ftp.nlst(file_pattern)

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

    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()
486
                raise FileNotFoundError('Cannot download ', filename)
Qusai Al Shidi's avatar
Qusai Al Shidi committed
487
488
489
490
491
492
493
494
495
496

        # 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()
497
498

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