Legacy API Reference#

Warning

This API interface is deprecated and will be removed on or after December 2023. See the Imager API Reference for the current (and equivalent) asilib implementation.

asilib saves all of the ASI image files, skymap calibration files, and movies to

asilib.config['ASI_DATA_DIR']

By default this directory is set to ~/asilib-data/, but you can configure the paths using the prompt opened by

python3 -m asilib config

The below functions can be imported and called using either of the following ways:

  • import asilib
    asilib.load_image(...)
    
  • from asilib.io.load import load_image
    load_image(...)
    

The former option is possible because these functions are all imported by default. However, this may change in a future release, so absolute import (shown in the latter example) is preferred.

Note

The longitude units are converted from [0, 360] to [-180, 180] degrees in the skymap calibration files.

Function Summary#

asilib.io.download.download_image

Download a CDF image file when time is given, or multiple files when time_range is given.

asilib.io.download.download_skymap

Download all of the THEMIS or REGO skymap IDL .sav files.

asilib.io.load.load_skymap

Loads the appropriate THEMIS or REGO skymap file (closest and before time) into memory.

asilib.io.load.load_image

Load into memory an ASI image and time stamp when time is given, or images with time stamps when time_range is given.

asilib.io.load.load_image_generator

Yields multiple ASI image files one by one and crops the time stamps by time_range.

asilib.plot.plot_keogram.plot_keogram

Makes a keogram along the central meridian.

asilib.plot.plot_fisheye.plot_fisheye

Plots one fisheye image, oriented with North on the top, and East on the right of the image.

asilib.plot.plot_map.plot_map

Projects the ASI images to a map at an altitude defined in the skymap calibration file.

asilib.plot.animate_fisheye.animate_fisheye

Animate a series of THEMIS or REGO fisheye images.

asilib.plot.animate_fisheye.animate_fisheye_generator

A generator function that loads the ASI data and then yields individual ASI images, image by image.

asilib.plot.animate_map.animate_map

Projects a series of THEMIS or REGO images on a map at map_alt altitude in kilometers and animates them.

asilib.plot.animate_map.animate_map_generator

Projects a series of THEMIS or REGO images on a map at map_alt altitude in kilometers and animates them.

asilib.analysis.keogram.keogram

Makes a keogram pd.DataFrame along the central meridian.

asilib.analysis.map.lla2azel

Maps, a satellite's latitude, longitude, and altitude (LLA) coordinates to the ASI's azimuth and elevation (azel) coordinates and image pixel index.

asilib.analysis.map.lla2footprint

Map the spacecraft's position to map_alt along the magnetic field line.

asilib.analysis.equal_area.equal_area

Calculate a box_km area at the aurora emission altitude.

Download#

asilib.io.download.download_image(asi_array_code, location_code, time=None, time_range=None, redownload=False, ignore_missing_data=True)[source]#

Download a CDF image file when time is given, or multiple files when time_range is given.

Parameters:
  • asi_array_code (str) – The imager array name, i.e. THEMIS or REGO.

  • location_code (str) – The ASI station code, i.e. ATHA

  • time (datetime.datetime or str) – The date and time to download of the data. If str, time must be in the ISO 8601 standard.

  • time_range (list of datetime.datetimes or stings) – Defined the duration of data to download. Must be of length 2.

  • redownload (bool) – If True, download the file even if it already exists. Useful if a prior data download was incomplete.

  • ignore_missing_data (bool) – Flag to ignore the FileNotFoundError that is raised when ASI data is unavailable for that date-hour. Only useful when time_range is passed.

Returns:

download_paths – A list of pathlib.Path objects that contain the downloaded file path(s).

Return type:

list

Example

from datetime import datetime

import asilib

asi_array_code = ‘THEMIS’
location_code = ‘LUCK’
time = datetime(2017, 4, 13, 5)
download_path = asilib.download_image(asi_array_code, location_code, time)
asilib.io.download.download_skymap(asi_array_code, location_code, redownload=False)[source]#

Download all of the THEMIS or REGO skymap IDL .sav files.

Parameters:
  • asi_array_code (str) – The imager array name, i.e. THEMIS or REGO.

  • location_code (str) – The ASI station code, i.e. ATHA

  • redownload (bool) – If True, download the file even if it already exists. Useful if a prior data download was incomplete.

Returns:

download_paths – A list of pathlib.Path objects that contain the skymap file path(s).

Return type:

list

Example

import asilib

asi_array_code = ‘THEMIS’
location_code = ‘LUCK’
asilib.download_skymap(asi_array_code, location_code)

Load#

The following functions are very useful if you want to work with the raw image and skymap data without dealing without explicitly downloading them.

asilib.io.load.load_image(asi_array_code, location_code, time=None, time_range=None, redownload=False, time_thresh_s=3, ignore_missing_data=True)[source]#

Load into memory an ASI image and time stamp when time is given, or images with time stamps when time_range is given.

Parameters:
  • asi_array_code (str) – The imager array name, i.e. THEMIS or REGO.

  • location_code (str) – The ASI station code, i.e. ATHA

  • time (datetime.datetime or str) – The date and time to download of the data. If str, time must be in the ISO 8601 standard.

  • time_range (list of datetime.datetimes or stings) – Defined the duration of data to download. Must be of length 2.

  • redownload (bool) – If True, download the file even if it already exists. Useful if a prior data download was incomplete.

  • time_thresh_s (float) – The maximum allowable time difference between time and an ASI time stamp. This is relevant only when time is specified.

  • ignore_missing_data (bool) – Flag to ignore the FileNotFoundError that is raised when ASI data is unavailable for that date-hour. Only useful when time_range is passed.

Returns:

  • times (datetime, or List[datetime]) – The image timestamp if time is passed, or a list of timestamps if time_range is passed. When time_range is passed, the timestamps can include start time if a timestamp exactly matches, but will exclude the timestamp that exactly matches the end time.

  • images (np.ndarray) – Either an (nPixelRows x nPixelCols) or (nTime x nPixelRows x nPixelCols) array containing the ASI images.

Example

# Load a single image
asi_array_code = ‘THEMIS’
location_code = ‘ATHA’
time = datetime(2008, 3, 9, 9, 18, 0)
image_time, image = asilib.load_image(asi_array_code, location_code, time=time, redownload=False)

# Load multiple images
asi_array_code = ‘REGO’
location_code = ‘LUCK’
time_range = [datetime(2017, 9, 27, 7, 15), datetime(2017, 9, 27, 8, 15)]
image_times, images = asilib.load_image(asi_array_code, location_code, time_range=time_range, redownload=False)
asilib.io.load.load_image_generator(asi_array_code, location_code, time_range, redownload=False, ignore_missing_data=True)[source]#

Yields multiple ASI image files one by one and crops the time stamps by time_range.

This generator is useful for loading lots of data—useful for keograms. The returned time stamps span a range from time_range[0], up to, but excluding a time stamp exactly matching time_range[1].

See asilib._load_images() for an example on how to use this function.

Parameters:
  • asi_array_code (str) – The imager array name, i.e. THEMIS or REGO.

  • location_code (str) – The ASI station code, i.e. ATHA

  • time_range (list of datetime.datetimes or stings) – Defined the duration of data to download. Must be of length 2.

  • redownload (bool) – If True, download the file even if it already exists. Useful if a prior data download was incomplete.

  • ignore_missing_data (bool) – Flag to ignore the FileNotFoundError that is raised when ASI data is unavailable for that date-hour. Only useful when time_range is passed.

Yields:
  • times (datetime) – The image timestamps contained in time_range, including the start time and excluding the end time (if time_range[1] exactly matches a ASI time stamp).

  • images (np.ndarray) – An (nTime x nPixelRows x nPixelCols) array containing the ASI images for times contained in time_range.

asilib.io.load.load_skymap(asi_array_code, location_code, time, redownload=False)[source]#

Loads the appropriate THEMIS or REGO skymap file (closest and before time) into memory.

Parameters:
  • asi_array_code (str) – The imager array name, i.e. THEMIS or REGO.

  • location_code (str) – The ASI station code, i.e. ATHA

  • time (datetime.datetime or str) – The date and time to download of the data. If str, time must be in the ISO 8601 standard.

  • redownload (bool) – If True, download the file even if it already exists. Useful if a prior data download was incomplete.

Returns:

The skymap data with longitudes mapped from 0->360 to to -180->180 degrees.

Return type:

dict

Example

import asilib

rego_skymap = asilib.load_skymap(‘REGO’, ‘GILL’, ‘2018-10-01’)

Plot#

asilib.plot.plot_keogram.plot_keogram(asi_array_code, location_code, time_range, map_alt=None, path=None, aacgm=False, ax=None, color_bounds=None, color_norm='lin', title=True, pcolormesh_kwargs={})[source]#

Makes a keogram along the central meridian.

Warning

Use plot_keogram() instead. This function will be removed in or after December 2023.

Parameters:
  • asi_array_code (str) – The imager array name, i.e. THEMIS or REGO.

  • location_code (str) – The ASI station code, i.e. ATHA

  • time_range (list of datetime.datetimes or stings) – Defined the duration of data to download. Must be of length 2.

  • map_alt (int) – The mapping altitude, in kilometers, used to index the mapped latitude in the skymap calibration data. If None, will plot pixel index for the y-axis.

  • path (array) – Make a keogram along a custom path. Path shape must be (n, 2) and contain the lat/lon coordinates that are mapped to map_alt. If the map_alt kwarg is unspecified, this function will raise a ValueError.

  • aacgm (bool) – Map the keogram latitudes to Altitude Adjusted Corrected Geogmagnetic Coordinates (aacgmv2) derived by Shepherd, S. G. (2014), Altitude-adjusted corrected geomagnetic coordinates: Definition and functional approximations, Journal of Geophysical Research: Space Physics, 119, 7501-7521, doi:10.1002/2014JA020264.

  • ax (plt.Axes) – The subplot to plot the image on. If None, this function will create one.

  • color_bounds (List[float]) – The lower and upper values of the color scale. If None, will automatically set it to low=1st_quartile and high=min(3rd_quartile, 10*1st_quartile)

  • color_norm (str) – Sets the linear (‘lin’) or logarithmic (‘log’) color normalization.

  • title (bool) – Toggles a default plot title with the format “date ASI_array_code-location_code keogram”.

  • pcolormesh_kwargs (dict) – A dictionary of keyword arguments (kwargs) to pass directly into plt.pcolormesh. One use of this parameter is to change the colormap. For example, pcolormesh_kwargs = {‘cmap’:’tu’}

Returns:

  • ax (plt.Axes) – The subplot object to modify the axis, labels, etc.

  • im (plt.AxesImage) – The plt.pcolormesh image object. Common use for im is to add a colorbar.

Raises:

AssertionError – If len(time_range) != 2. Also if map_alt does not equal the mapped altitudes in the skymap mapped values.

Example

import matplotlib.pyplot as plt

import asilib

asi_array_code=’REGO’
location_code=’LUCK’
time_range=[‘2017-09-27T07’, ‘2017-09-27T09’]

fig, ax = plt.subplots(figsize=(8, 6))
ax, im = asilib.plot_keogram(asi_array_code, location_code, time_range,
ax=ax, map_alt=230, color_bounds=(300, 800), pcolormesh_kwargs={‘cmap’:’turbo’})

plt.colorbar(im)
plt.tight_layout()
plt.show()
asilib.plot.plot_fisheye.plot_fisheye(asi_array_code, location_code, time, redownload=False, time_thresh_s=3, ax=None, label=True, color_map='auto', color_bounds=None, color_norm='log', azel_contours=False)[source]#

Plots one fisheye image, oriented with North on the top, and East on the right of the image.

Warning

Use plot_fisheye() instead. This function will be removed in or after December 2023.

Parameters:
  • asi_array_code (str) – The imager array name, i.e. THEMIS or REGO.

  • location_code (str) – The ASI station code, i.e. ATHA

  • time (datetime.datetime or str) – The date and time to download of the data. If str, time must be in the ISO 8601 standard.

  • time_range (list of datetime.datetimes or stings) – Defined the duration of data to download. Must be of length 2.

  • redownload (bool) – If True, download the file even if it already exists. Useful if a prior data download was incomplete and corrupted.

  • time_thresh_s (float) – The maximum allowable time difference between time and an ASI time stamp.

  • ax (plt.Axes) – The subplot to plot the image on. If None, this function will create one.

  • label (bool) – Flag to add the “asi_array_code/location_code/image_time” text to the plot.

  • color_map (str) – The matplotlib colormap to use. If ‘auto’, will default to a black-red colormap for REGO and black-white colormap for THEMIS. For more information See https://matplotlib.org/3.3.3/tutorials/colors/colormaps.html

  • color_bounds (List[float]) – The lower and upper values of the color scale. If None, will automatically set it to low=1st_quartile and high=min(3rd_quartile, 10*1st_quartile). This range works well for most cases.

  • color_norm (str) – Sets the ‘lin’ linear or ‘log’ logarithmic color normalization.

  • azel_contours (bool) – Switch azimuth and elevation contours on or off.

Returns:

  • image_time (datetime.datetime) – The time of the current image.

  • image (np.array) – The 2d ASI image corresponding to image_time.

  • ax (plt.Axes) – The subplot object to modify the axis, labels, etc.

  • im (plt.AxesImage) – The plt.imshow image object. Common use for im is to add a colorbar. The image is oriented in the map orientation (north is up, south is down, west is right, and east is left), contrary to the camera orientation where the east/west directions are flipped. Set azel_contours=True to confirm.

Raises:
  • NotImplementedError – If the colormap is unspecified (‘auto’ by default) and the auto colormap is undefined for an ASI array.

  • ValueError – If the color_norm kwarg is not “log” or “lin”.

Example

from datetime import datetime

import matplotlib.pyplot as plt

import asilib

# A bright auroral arc that was analyzed by Imajo et al., 2021 “Active
# auroral arc powered by accelerated electrons from very high altitudes”
time = datetime(2017, 9, 15, 2, 34, 0)
image_time, ax, im = asilib.plot_fisheye(‘THEMIS’, ‘RANK’, time,
color_norm=’log’, redownload=False)

plt.colorbar(im)
ax.axis(‘off’)
plt.show()

This module contains functions to project the ASI images to a map.

asilib.plot.plot_map.plot_map(asi_array_code, location_code, time, map_alt, time_thresh_s=3, ax=None, color_map='auto', min_elevation=10, norm=True, asi_label=True, color_bounds=None, color_norm='log', pcolormesh_kwargs={}, map_shapefile='ne_10m_land', coast_color='k', land_color='g', ocean_color='w', lon_bounds=(-140, -60), lat_bounds=(40, 82))[source]#

Projects the ASI images to a map at an altitude defined in the skymap calibration file.

Warning

Use plot_map() instead. This function will be removed in or after December 2023.

Parameters:
  • asi_array_code (str) – The imager array name, i.e. THEMIS or REGO.

  • location_code (str) – The ASI station code, i.e. ATHA

  • time (datetime.datetime or str) – The date and time to download of the data. If str, time must be in the ISO 8601 standard.

  • map_alt (float) – The altitude in kilometers to project to. Must be an altitude value in the skymap calibration.

  • time_thresh_s (float) – The maximum allowable time difference between time and an ASI time stamp. This is relevant only when time is specified.

  • ax (plt.Axes) – The subplot to plot the image on. If None, this function will create one.

  • color_map (str) – The matplotlib colormap to use. If ‘auto’, will default to a black-red colormap for REGO and black-white colormap for THEMIS. For more information See https://matplotlib.org/3.3.3/tutorials/colors/colormaps.html

  • min_elevation (float) – Masks the pixels below min_elevation degrees.

  • norm (bool) – If True, normalizes the image array to 0-1. This is useful when mapping images from multiple imagers.

  • asi_label (bool) – Annotates the map with the ASI code in the center of the image.

  • color_bounds (List[float] or None) – The lower and upper values of the color scale. If None, will automatically set it to low=1st_quartile and high=min(3rd_quartile, 10*1st_quartile)

  • color_norm (str) – Sets the ‘lin’ linear or ‘log’ logarithmic color normalization.

  • pcolormesh_kwargs (dict) – A dictionary of keyword arguments (kwargs) to pass directly into plt.pcolormesh. One use of this parameter is to change the colormap. For example, pcolormesh_kwargs = {‘cmap’:’tu}

  • map_shapefile (str or pathlib.Path) – The path to the shapefile zip archive. If str, it will try to load the shapefile in asilib/data/{file}.

  • coast_color (str) – The coast color. If None will not draw it.

  • land_color (str) – The land color. If None will not draw it.

  • ocean_color (str) – The ocean color. If None will not draw it.

  • ax – The subplot to put the map on.

  • lon_bounds (tuple) – The map’s longitude bounds.

  • lat_bounds (tuple) – The map’s latitude bounds.

Returns:

  • image_time (datetime.datetime) – The time of the current image.

  • image (np.array) – The 2d ASI image corresponding to image_time.

  • skyamp (dict) – The skymap calibration for that ASI.

  • ax (plt.Axes) – The subplot object to modify the axis, labels, etc.

  • p (plt.AxesImage) – The plt.pcolormesh image object. Common use for p is to add a colorbar.

Example

from datetime import datetime

import matplotlib.pyplot as plt

import asilib

asi_array_code = ‘THEMIS’
location_code = ‘ATHA’
time = datetime(2008, 3, 9, 9, 18, 0)
map_alt_km = 110
asilib.plot_map(asi_array_code, location_code, time, map_alt_km);
plt.show()
asilib.plot.plot_map.make_map(file='ne_10m_land', coast_color='k', land_color='g', ocean_color='w', ax=None, lon_bounds=(-140, -60), lat_bounds=(40, 82))[source]#

Makes a map using the mercator projection with a shapefile read in by the pyshp package.

A good place to download shapefiles is https://www.naturalearthdata.com/downloads/10m-physical-vectors/.

Warning

Use create_map() instead. This function will be removed in or after December 2023.

Parameters:
  • file (str or pathlib.Path) – The path to the shapefile zip archive. If str, it will try to load the shapefile in asilib/data/{file}.

  • coast_color (str) – The coast color. If None will not draw it.

  • land_color (str) – The land color. If None will not draw it.

  • ocean_color (str) – The ocean color. If None will not draw it.

  • ax (plt.Axes) – The subplot to put the map on.

  • lon_bounds (tuple) – The map’s longitude bounds.

  • lat_bounds (tuple) – The map’s latitude bounds.

Returns:

The subplot object containing the map.

Return type:

plt.Axes

Example

import asilib

ax = asilib.make_map(lon_bounds=(-127, -100), lat_bounds=(45, 65))
asilib.plot.animate_fisheye.animate_fisheye(asi_array_code, location_code, time_range, **kwargs)[source]#

Animate a series of THEMIS or REGO fisheye images.

This function basically runs animate_fisheye_generator() in a for loop. The two function’s arguments and keyword arguments are identical, so see animate_fisheye_generator() docs for the full argument list.

Note: To make movies, you’ll need to install ffmpeg in your operating system.

Warning

Use animate_fisheye() instead. This function will be removed in or after December 2023.

Parameters:
  • asi_array_code (str) – The imager array name, i.e. THEMIS or REGO.

  • location_code (str) – The ASI station code, i.e. ATHA

  • time_range (list of datetime.datetimes or stings) – Defined the duration of data to download. Must be of length 2.

Return type:

None

Raises:
  • NotImplementedError – If the colormap is unspecified (‘auto’ by default) and the auto colormap is undefined for an ASI array.

  • ValueError – If the color_norm kwarg is not “log” or “lin”.

Example

from datetime import datetime

import asilib

time_range = (datetime(2015, 3, 26, 6, 7), datetime(2015, 3, 26, 6, 12))
asilib.animate_fisheye(‘THEMIS’, ‘FSMI’, time_range)
print(f’Movie saved in {asilib.config[“ASI_DATA_DIR”] / “movies”}’)
asilib.plot.animate_fisheye.animate_fisheye_generator(asi_array_code, location_code, time_range, overwrite=False, label=True, color_map='auto', color_bounds=None, color_norm='log', azel_contours=False, ax=None, movie_container='mp4', ffmpeg_output_params={})[source]#

A generator function that loads the ASI data and then yields individual ASI images, image by image. This allows the user to add content to each image, such as the spacecraft position, and that will convert it to a movie. If you just want to make an ASI fisheye movie, use the wrapper for this function, called animate_fisheye().

Once this generator is initiated with the name gen, for example, but before the for loop, you can get the ASI images and times by calling gen.send(‘data’). This will yield a collections.namedtuple with time and images attributes.

Warning

Use animate_fisheye_gen() instead. This function will be removed in or after December 2023.

Parameters:
  • asi_array_code (str) – The imager array name, i.e. THEMIS or REGO.

  • location_code (str) – The ASI station code, i.e. ATHA

  • time_range (list of datetime.datetimes or stings) – Defined the duration of data to download. Must be of length 2.

  • overwrite (bool) – If true, the output animation will be overwritten, otherwise it will prompt the user to answer y/n.

  • label (bool) – Flag to add the “asi_array_code/location_code/image_time” text to the plot.

  • color_map (str) – The matplotlib colormap to use. If ‘auto’, will default to a black-red colormap for REGO and black-white colormap for THEMIS. For more information See https://matplotlib.org/3.3.3/tutorials/colors/colormaps.html

  • color_bounds (List[float] or None) – The lower and upper values of the color scale. If None, will automatically set it to low=1st_quartile and high=min(3rd_quartile, 10*1st_quartile)

  • ax (plt.Axes) – The optional subplot that will be drawn on.

  • movie_container (str) – The movie container: mp4 has better compression but avi was determined to be the official container for preserving digital video by the National Archives and Records Administration.

  • ffmpeg_output_params (dict) – The additional/overwitten ffmpeg output parameters. The default parameters are: framerate=10, crf=25, vcodec=libx264, pix_fmt=yuv420p, preset=slower.

  • color_norm (str) – Sets the ‘lin’ linear or ‘log’ logarithmic color normalization.

  • azel_contours (bool) – Switch azimuth and elevation contours on or off.

Yields:
  • image_time (datetime.datetime) – The time of the current image.

  • image (np.ndarray) – A 2d image array of the image corresponding to image_time

  • ax (plt.Axes) – The subplot object to modify the axis, labels, etc.

  • im (plt.AxesImage) – The plt.imshow image object. Common use for im is to add a colorbar. The image is oriented in the map orientation (north is up, south is down, west is right, and east is left). Set azel_contours=True to confirm.

Raises:
  • NotImplementedError – If the colormap is unspecified (‘auto’ by default) and the auto colormap is undefined for an ASI array.

  • ValueError – If the color_norm kwarg is not “log” or “lin”.

Example

from datetime import datetime

import asilib

time_range = (datetime(2015, 3, 26, 6, 7), datetime(2015, 3, 26, 6, 12))
movie_generator = asilib.animate_fisheye_generator(‘THEMIS’, ‘FSMI’, time_range)

for image_time, image, im, ax in movie_generator:
# The code that modifies each image here.
pass

print(f’Movie saved in {asilib.config[“ASI_DATA_DIR”] / “movies”}’)
asilib.plot.animate_map.animate_map(asi_array_code, location_code, time_range, map_alt, **kwargs)[source]#

Projects a series of THEMIS or REGO images on a map at map_alt altitude in kilometers and animates them.

This function basically runs animate_map_generator() in a for loop. The two function’s arguments and keyword arguments are identical, so see animate_map_generator() docs for the full argument list.

Note: To make animations, you’ll need to install ffmpeg in your operating system.

Warning

Use animate_map() instead. This function will be removed in or after December 2023.

Parameters:
  • asi_array_code (str) – The imager array name, i.e. THEMIS or REGO.

  • location_code (str) – The ASI station code, i.e. ATHA

  • time_range (list of datetime.datetimes or stings) – Defined the duration of data to download. Must be of length 2.

Return type:

None

Raises:
  • NotImplementedError – If the colormap is unspecified (‘auto’ by default) and the auto colormap is undefined for an ASI array.

  • ValueError – If the color_norm kwarg is not “log” or “lin”.

  • AssertionError – If the ASI data exists for that time period, but without time stamps inside time_range.

Example

from datetime import datetime

import asilib

map_alt=110 # km
time_range = (datetime(2015, 3, 26, 6, 7), datetime(2015, 3, 26, 6, 12))
asilib.animate_map(‘THEMIS’, ‘FSMI’, time_range, map_alt=map_alt)
print(f’Movie saved in {asilib.config[“ASI_DATA_DIR”] / “animations”}’)
asilib.plot.animate_map.animate_map_generator(asi_array_code, location_code, time_range, map_alt, min_elevation=10, overwrite=False, color_map='auto', color_bounds=None, color_norm='log', ax=None, map_shapefile='ne_10m_land', coast_color='k', land_color='g', ocean_color='w', lon_bounds=(-140, -60), lat_bounds=(40, 82), label=True, movie_container='mp4', ffmpeg_output_params={}, pcolormesh_kwargs={})[source]#

Projects a series of THEMIS or REGO images on a map at map_alt altitude in kilometers and animates them. This generator function is useful if you need to superpose other data onto a map in the movie.

Once this generator is initiated with the name gen, for example, but before the for loop, you can get the ASI images and times by calling gen.send(‘data’). This will yield a collections.namedtuple with time and images attributes.

Warning

Use animate_map_gen() instead. This function will be removed in or after December 2023.

Parameters:
  • asi_array_code (str) – The imager array name, i.e. THEMIS or REGO.

  • location_code (str) – The ASI station code, i.e. ATHA

  • time_range (list of datetime.datetimes or stings) – Defined the duration of data to download. Must be of length 2.

  • map_alt (float) – The altitude in kilometers to project to. Must be an altitude value in the skymap calibration.

  • min_elevation (float) – Masks the pixels below min_elevation degrees.

  • overwrite (bool) – If True, the animation will be overwritten. Otherwise it will prompt the user to answer y/n.

  • color_map (str) – The matplotlib colormap to use. If ‘auto’, will default to a black-red colormap for REGO and black-white colormap for THEMIS. For more information See https://matplotlib.org/3.3.3/tutorials/colors/colormaps.html

  • color_bounds (List[float] or None) – The lower and upper values of the color scale. If None, will automatically set it to low=1st_quartile and high=min(3rd_quartile, 10*1st_quartile)

  • ax (plt.Axes) – The optional subplot that will be drawn on.

  • map_shapefile (str or pathlib.Path) – The path to the shapefile zip archive. If str, it will try to load the shapefile in asilib/data/{file}.

  • coast_color (str) – The coast color. If None will not draw it.

  • land_color (str) – The land color. If None will not draw it.

  • ocean_color (str) – The ocean color. If None will not draw it.

  • lon_bounds (tuple) – The map’s longitude bounds.

  • lat_bounds (tuple) – The map’s latitude bounds.

  • label (bool) – Annotates the map with the ASI code in the center of the image.

  • movie_container (str) – The movie container: mp4 has better compression but avi was determined to be the official container for preserving digital video by the National Archives and Records Administration.

  • ffmpeg_output_params (dict) – The additional/overwitten ffmpeg output parameters. The default parameters are: framerate=10, crf=25, vcodec=libx264, pix_fmt=yuv420p, preset=slower.

  • color_norm (str) – Sets the ‘lin’ linear or ‘log’ logarithmic color normalization.

  • pcolormesh_kwargs (dict) – A dictionary of keyword arguments (kwargs) to pass directly into plt.pcolormesh. One use of this parameter is to change the colormap. For example, pcolormesh_kwargs = {‘cmap’:’tu}

Yields:
  • image_time (datetime.datetime) – The time of the current image.

  • image (np.ndarray) – A 2d image array of the image corresponding to image_time

  • ax (plt.Axes) – The subplot object to modify the axis, labels, etc.

  • im (plt.AxesImage) – The plt.pcolormesh object.

Raises:
  • NotImplementedError – If the colormap is unspecified (‘auto’ by default) and the auto colormap is undefined for an ASI array.

  • ValueError – If the color_norm kwarg is not “log” or “lin”.

  • AssertionError – If the ASI data exists for that time period, but without time stamps inside time_range.

Example

from datetime import datetime

import asilib

map_alt=110
time_range = (datetime(2015, 3, 26, 6, 7), datetime(2015, 3, 26, 6, 12))
map_generator = asilib.animate_map_generator(‘THEMIS’, ‘FSMI’, time_range, map_alt=map_alt,
lon_bounds=(-125, -100), lat_bounds=(55, 70))

for (image_time1, image, ax, p) in map_generator:
# The code that modifies each image here.
pass

print(f’Movie saved in {asilib.config[“ASI_DATA_DIR”] / “animations”}’)

Analysis#

asilib.analysis.keogram.keogram(asi_array_code, location_code, time_range, map_alt=None, path=None, aacgm=False)[source]#

Makes a keogram pd.DataFrame along the central meridian.

Parameters:
  • asi_array_code (str) – The imager array name, i.e. THEMIS or REGO.

  • location_code (str) – The ASI station code, i.e. ATHA

  • time_range (list of datetime.datetimes or stings) – Defined the duration of data to download. Must be of length 2.

  • map_alt (int) – The mapping altitude, in kilometers, used to index the mapped latitude in the skymap data. If None, will plot pixel index for the y-axis.

  • path (array) – Make a keogram along a custom path. Path shape must be (n, 2) and contain the lat/lon coordinates that are mapped to map_alt. If the map_alt kwarg is unspecified, this function will raise a ValueError.

  • aacgm (bool) – Map the keogram latitudes to Altitude Adjusted Corrected Geogmagnetic Coordinates (aacgmv2) derived by Shepherd, S. G. (2014), Altitude-adjusted corrected geomagnetic coordinates: Definition and functional approximations, Journal of Geophysical Research: Space Physics, 119, 7501-7521, doi:10.1002/2014JA020264.

Returns:

keo – The 2d keogram with the time index. The columns are the geographic latitude if map_alt != None, otherwise it is the image pixel values (0-265) or (0-512).

Return type:

pd.DataFrame

Raises:
  • AssertionError – If map_alt does not equal the mapped altitudes in the skymap mapped values.

  • ValueError – If no images are in time_range.

  • ValueError – If a custom path is provided but not map_alt.

asilib.analysis.map.lla2azel(asi_array_code, location_code, time, sat_lla)[source]#

Maps, a satellite’s latitude, longitude, and altitude (LLA) coordinates to the ASI’s azimuth and elevation (azel) coordinates and image pixel index.

This function is useful to plot a satellite’s location in the ASI image using the pixel indices.

Parameters:
  • asi_array_code (str) – The imager array name, i.e. THEMIS or REGO.

  • location_code (str) – The ASI station code, i.e. ATHA

  • time (datetime.datetime or str) – The date and time to find the relevant skymap file. If str, time must be in the ISO 8601 standard.

  • sat_lla (np.ndarray or pd.DataFrame) – The satellite’s latitude, longitude, and altitude coordinates in a 2d array with shape (nPosition, 3) where each row is the number of satellite positions to map, and the columns correspond to latitude, longitude, and altitude, respectively. The altitude is in kilometer units.

Returns:

  • sat_azel (np.ndarray) – An array with shape (nPosition, 2) of the satellite’s azimuth and elevation coordinates.

  • asi_pixels (np.ndarray) – An array with shape (nPosition, 2) of the x- and y-axis pixel indices for the ASI image.

Raises:

AssertionError – If the sat_lla argument does not have exactly 3 columns (1st dimension).

Example

from datetime import datetime

import numpy as np
from asilib import lla2azel

# THEMIS/ATHA’s LLA coordinates are (54.72, -113.301, 676 (meters)).
# The LLA is a North-South pass right above ATHA..
n = 50
lats = np.linspace(60, 50, n)
lons = -113.64*np.ones(n)
alts = 500**np.ones(n)
lla = np.array([lats, lons, alts]).T

time = datetime(2015, 10, 1) # To load the proper skymap file.

azel, pixels = lla2azel(‘REGO’, ‘ATHA’, time, lla)
asilib.analysis.map.lla2footprint(space_time, map_alt, b_model='OPQ77', maginput=None, hemisphere=0)[source]#

Map the spacecraft’s position to map_alt along the magnetic field line. The mapping is implemeneted in IRBEM and by default it maps to the same hemisphere.

Parameters:
  • space_time (np.ndarray) – A 2d array with shape (n_times, 4) with the columns containing the time, latitude, longitude, and altitude coordinates in that order.

  • map_alt (float) – The altitude to map to, in km, in the same hemisphere.

  • b_model (str) – The magnetic field model to use, by default the model is Olson-Pfitzer 1974. This parameter is passed directly into IRBEM.MagFields as the ‘kext’ parameter.

  • maginput (dict) – If you use a differnet b_model that requires time-dependent parameters, supply the appropriate values to the maginput dictionary. It is directly passed into IRBEM.MagFields so refer to IRBEM on the proper format.

  • hemisphere (int) – The hemisphere to map to. This kwarg is passed to IRBEM and can be one of these four values: 0 = same magnetic hemisphere as starting point +1 = northern magnetic hemisphere -1 = southern magnetic hemisphere +2 = opposite magnetic hemisphere as starting point

Returns:

magnetic_footprint – A numpy.array with size (n_times, 3) with lat, lon, alt columns representing the magnetic footprint coordinates.

Return type:

np.ndarray

Raises:

ImportError – If IRBEM can’t be imported.

asilib.analysis.equal_area.equal_area(asi_array_code, location_code, time, lla, box_km=(5, 5), alt_thresh_km=3)[source]#

Calculate a box_km area at the aurora emission altitude.

Parameters:
  • asi_array_code (str) – The imager array name, i.e. THEMIS or REGO.

  • location_code (str) – The ASI station code, i.e. ATHA

  • time (datetime.datetime or str) – The date and time to download of the data. If str, time must be in the ISO 8601 standard.

  • lla (np.ndarray) – An array with (n_time, 3) dimensions with the columns representing the latitude, longitude, and altitude (LLA) coordinates.

  • box_size_km (iterable) – Bounds the emission box dimensions in longitude and latitude. Units are kilometers.

Returns:

pixel_mask – An array with (n_time, n_x_pixels, n_y_pixels) dimensions with dimensions n_x_pixels and n_y_pixels dimensions the size of each image. Values inside the area are 1 and outside are np.nan.

Return type:

np.ndarray