Imager API Reference#

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

Note

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

ASI arrays#

Time History of Events and Macroscale Interactions during Substorms (THEMIS)#

asilib.asi.themis(location_code, time=None, time_range=None, alt=110, custom_alt=False, redownload=False, missing_ok=True, load_images=True, imager=<class 'asilib.imager.Imager'>)[source]#

Create an Imager instance with the THEMIS ASI images and skymaps.

Parameters:
  • location_code (str) – The ASI’s location code (four letters).

  • time (str or datetime.datetime) – A time to look for the ASI data at. Either time or time_range must be specified (not both or neither).

  • time_range (list of str or datetime.datetime) – A length 2 list of string-formatted times or datetimes to bracket the ASI data time interval.

  • alt (int) – The reference skymap altitude, in kilometers.

  • redownload (bool) – If True, will download the data from the internet, regardless of wether or not the data exists locally (useful if the data becomes corrupted).

  • custom_alt (bool) –

    If True, asilib will calculate (lat, lon) skymaps assuming a spherical Earth. Otherwise, it will use the official skymaps (Courtesy of University of Calgary).

    Note

    The spherical model of Earth’s surface is less accurate than the oblate spheroid geometrical representation. Therefore, there will be a small difference between these and the official skymaps.

  • missing_ok (bool) – Wether to allow missing data files inside time_range (after searching for them locally and online).

  • load_images (bool) – Create an Imager object without images. This is useful if you need to calculate conjunctions and don’t need to download or load unnecessary data.

  • imager (asilib.Imager) – Controls what Imager instance to return, asilib.Imager by default. This parameter is useful if you need to subclass asilib.Imager.

Returns:

A THEMIS ASI instance with the time stamps, images, skymaps, and metadata.

Return type:

Imager()

asilib.asi.themis_info()[source]#

Returns a pd.DataFrame with the THEMIS ASI names and locations.

Returns:

A table of THEMIS imager names and locations.

Return type:

pd.DataFrame

asilib.asi.themis_skymap(location_code, time, redownload)[source]#

Load a THEMIS ASI skymap file.

Parameters:
  • location_code (str) – The four character location name.

  • time (str or datetime.datetime) – A ISO-fomatted time string or datetime object. Must be in UT time.

  • redownload (bool) – Redownload all skymaps.

Red-line Emission Geospace Observatory (REGO)#

asilib.asi.rego(location_code, time=None, time_range=None, alt=110, custom_alt=False, redownload=False, missing_ok=True, load_images=True, imager=<class 'asilib.imager.Imager'>)[source]#

Create an Imager instance with the REGO ASI images and skymaps.

Redline Emission Geospace Observatory (REGO) data is courtesy of Space Environment Canada (space-environment.ca). Use of the data must adhere to the rules of the road for that dataset. Please see below for the required data acknowledgement. Any questions about the REGO instrumentation or data should be directed to the University of Calgary, Emma Spanswick (elspansw@ucalgary.ca) and/or Eric Donovan (edonovan@ucalgary.ca).

“The Redline Emission Geospace Observatory (REGO) is a joint Canada Foundation for Innovation and Canadian Space Agency project developed by the University of Calgary. REGO is operated and maintained by Space Environment Canada with the support of the Canadian Space Agency (CSA) [23SUGOSEC].”

Parameters:
  • location_code (str) – The ASI’s location code (four letters).

  • time (str or datetime.datetime) – A time to look for the ASI data at. Either time or time_range must be specified (not both or neither).

  • time_range (list of str or datetime.datetime) – A length 2 list of string-formatted times or datetimes to bracket the ASI data time interval.

  • alt (int) – The reference skymap altitude, in kilometers.

  • custom_alt (bool) –

    If True, asilib will calculate (lat, lon) skymaps assuming a spherical Earth. Otherwise, it will use the official skymaps (Courtesy of University of Calgary).

    Note

    The spherical model of Earth’s surface is less accurate than the oblate spheroid geometrical representation. Therefore, there will be a small difference between these and the official skymaps.

  • redownload (bool) – If True, will download the data from the internet, regardless of wether or not the data exists locally (useful if the data becomes corrupted).

  • missing_ok (bool) – Wether to allow missing data files inside time_range (after searching for them locally and online).

  • load_images (bool) – Create an Imager object without images. This is useful if you need to calculate conjunctions and don’t need to download or load unnecessary data.

  • imager (asilib.Imager) – Controls what Imager instance to return, asilib.Imager by default. This parameter is useful if you need to subclass asilib.Imager.

Returns:

The THEMIS Imager instance.

Return type:

Imager()

Examples

>>> # Plot a single image.
>>> from datetime import datetime
>>> import matplotlib.pyplot as plt
>>> import asilib.asi
>>> import asilib.map
>>> location_code = 'RANK'
>>> time = datetime(2017, 9, 15, 2, 34, 0)
>>> alt_km = 110
>>> fig = plt.figure(figsize=(10, 6))
>>> ax = fig.add_subplot(121)
>>> bx = asilib.map.create_map(fig_ax=(fig, 122), lon_bounds = (-102, -82), lat_bounds = (58, 68))
>>> asi = asilib.asi.rego(location_code, time=time, alt=alt_km)
>>> asi.plot_fisheye(ax=ax)
>>> asi.plot_map(ax=bx)
>>> plt.tight_layout()
>>> plt.show()
Returns:

A REGO ASI instance with the time stamps, images, skymaps, and metadata.

Return type:

Imager()

asilib.asi.rego_info()[source]#

Returns a pd.DataFrame with the REGO ASI names and locations.

Returns:

A table of REGO imager names and locations.

Return type:

pd.DataFrame

asilib.asi.rego_skymap(location_code, time, redownload=False)[source]#

Load a REGO ASI skymap file.

Parameters:
  • location_code (str) – The four character location name.

  • time (str or datetime.datetime) – A ISO-fomatted time string or datetime object. Must be in UT time.

  • redownload (bool) – Redownload the file.

Returns:

The skymap.

Return type:

dict

Transition Region Explorer (TREx)#

asilib.asi.trex_rgb(location_code, time=None, time_range=None, alt=110, custom_alt=False, redownload=False, missing_ok=True, load_images=True, colors='rgb', burst=False, imager=<class 'asilib.imager.Imager'>)[source]#

Create an Imager instance using the TREX-RGB ASI images and skymaps.

Transition Region Explorer (TREx) RGB data is courtesy of Space Environment Canada (space-environment.ca). Use of the data must adhere to the rules of the road for that dataset. Please see below for the required data acknowledgement. Any questions about the TREx instrumentation or data should be directed to the University of Calgary, Emma Spanswick (elspansw@ucalgary.ca) and/or Eric Donovan (edonovan@ucalgary.ca).

“The Transition Region Explorer RGB (TREx RGB) is a joint Canada Foundation for Innovation and Canadian Space Agency project developed by the University of Calgary. TREx-RGB is operated and maintained by Space Environment Canada with the support of the Canadian Space Agency (CSA) [23SUGOSEC].”

For more information see: https://www.ucalgary.ca/aurora/projects/trex.

Parameters:
  • location_code (str) – The ASI’s location code (four letters).

  • time (str or datetime.datetime) – A time to look for the ASI data at. Either time or time_range must be specified (not both or neither).

  • time_range (list of str or datetime.datetime) – A length 2 list of string-formatted times or datetimes to bracket the ASI data time interval.

  • alt (int) – The reference skymap altitude, in kilometers.

  • custom_alt (bool) –

    If True, asilib will calculate (lat, lon) skymaps assuming a spherical Earth. Otherwise, it will use the official skymaps (Courtesy of University of Calgary).

    Note

    The spherical model of Earth’s surface is less accurate than the oblate spheroid geometrical representation. Therefore, there will be a small difference between these and the official skymaps.

  • redownload (bool) – If True, will download the data from the internet, regardless of wether or not the data exists locally (useful if the data becomes corrupted).

  • missing_ok (bool) – Wether to allow missing data files inside time_range (after searching for them locally and online).

  • load_images (bool) – Create an Imager object without images. This is useful if you need to calculate conjunctions and don’t need to download or load unnecessary data.

  • colors (str) – Load all three color channels if “rgb”, or individual color channels specified by “r”, “g”, “b” (or any combination of them).

  • burst (bool) – Sometimes Trex-rgb uses a burst mode with higher resolution.

  • imager (Imager()) – Controls what Imager instance to return, asilib.Imager by default. This parameter is useful if you need to subclass asilib.Imager.

Returns:

The trex Imager instance.

Return type:

Imager()

Examples

>>> from datetime import datetime
>>>
>>> import matplotlib.pyplot as plt
>>> import asilib.map
>>> import asilib
>>> from asilib.asi import trex_rgb
>>>
>>> time = datetime(2021, 11, 4, 7, 3, 51)
>>> location_codes = ['FSMI', 'LUCK', 'RABB', 'PINA', 'GILL']
>>> asi_list = []
>>> ax = asilib.map.create_simple_map()
>>> for location_code in location_codes:
>>>     asi_list.append(trex_rgb(location_code, time=time, colors='rgb'))
>>>
>>> asis = asilib.Imagers(asi_list)
>>> asis.plot_map(ax=ax)
>>> ax.set(title=time)
>>> plt.tight_layout()
>>> plt.show()
asilib.asi.trex_rgb_info()[source]#

Returns a pd.DataFrame with the TREx RGB ASI names and locations.

Returns:

A table of TREx-RGB imager names and locations.

Return type:

pd.DataFrame

asilib.asi.trex_rgb_skymap(location_code, time, redownload=False)[source]#

Load a TREx RGB skymap file.

Parameters:
  • location_code (str) – The four character location name.

  • time (str or datetime.datetime) – A ISO-formatted time string or datetime object. Must be in UT time.

  • redownload (bool) – Redownload the file.

Returns:

The skymap.

Return type:

dict

asilib.asi.trex_nir(location_code, time=None, time_range=None, alt=110, custom_alt=False, redownload=False, missing_ok=True, load_images=True, imager=<class 'asilib.imager.Imager'>)[source]#

Create an Imager instance using the TREX-NIR ASI images and skymaps.

Transition Region Explorer (TREx) NIR data is courtesy of Space Environment Canada (space-environment.ca). Use of the data must adhere to the rules of the road for that dataset. Please see below for the required data acknowledgement. Any questions about the TREx instrumentation or data should be directed to the University of Calgary, Emma Spanswick (elspansw@ucalgary.ca) and/or Eric Donovan (edonovan@ucalgary.ca).

“The Transition Region Explorer NIR (TREx NIR) is a joint Canada Foundation for Innovation and Canadian Space Agency project developed by the University of Calgary. TREx-NIR is operated and maintained by Space Environment Canada with the support of the Canadian Space Agency (CSA) [23SUGOSEC].”

For more information see: https://www.ucalgary.ca/aurora/projects/trex.

Parameters:
  • location_code (str) – The ASI’s location code (four letters).

  • time (str or datetime.datetime) – A time to look for the ASI data at. Either time or time_range must be specified (not both or neither).

  • time_range (list of str or datetime.datetime) – A length 2 list of string-formatted times or datetimes to bracket the ASI data time interval.

  • alt (int) – The reference skymap altitude, in kilometers.

  • custom_alt (bool) –

    If True, asilib will calculate (lat, lon) skymaps assuming a spherical Earth. Otherwise, it will use the official skymaps (Courtesy of University of Calgary).

    Note

    The spherical model of Earth’s surface is less accurate than the oblate spheroid geometrical representation. Therefore, there will be a small difference between these and the official skymaps.

  • redownload (bool) – If True, will download the data from the internet, regardless of wether or not the data exists locally (useful if the data becomes corrupted).

  • missing_ok (bool) – Wether to allow missing data files inside time_range (after searching for them locally and online).

  • load_images (bool) – Create an Imager object without images. This is useful if you need to calculate conjunctions and don’t need to download or load unnecessary data.

  • imager (asilib.Imager) – Controls what Imager instance to return, asilib.Imager by default. This parameter is useful if you need to subclass asilib.Imager.

Returns:

The THEMIS Imager instance.

Return type:

Imager()

Examples

>>> import asilib
>>> import asilib.map
>>> import asilib.asi
>>> import matplotlib.pyplot as plt
>>>
>>> fig = plt.figure(figsize=(10, 6))
>>> ax = fig.add_subplot(121)
>>> bx = asilib.map.create_map(fig_ax=(fig, 122), lon_bounds=(-102, -86), lat_bounds=(51, 61))
>>> asi = asilib.asi.trex_nir('gill', time='2020-03-21T06:00')
>>> asi.plot_fisheye(ax=ax)
>>> asi.plot_map(ax=bx)
>>> plt.tight_layout()
>>> plt.show()
>>> import asilib
>>> import asilib.map
>>> import asilib.asi
>>> import matplotlib.pyplot as plt
>>>
>>> time_range = ('2020-03-21T05:00', '2020-03-21T07:00')
>>> fig, ax = plt.subplots(2, sharex=True)
>>> asi = asilib.asi.trex_nir('gill', time_range=time_range)
>>> asi.plot_keogram(ax=ax[0])
>>> asi.plot_keogram(ax=ax[1], aacgm=True)
>>> ax[0].set_title(f'TREX_NIR GILL keogram | {time_range}')
>>> ax[0].set_ylabel('Geo Lat')
>>> ax[1].set_ylabel('Mag Lat')
>>> ax[1].set_xlabel('Time')
>>> plt.show()
asilib.asi.trex_nir_skymap(location_code, time, redownload=False)[source]#

Load a TREx NIR ASI skymap file.

Parameters:
  • location_code (str) – The four character location name.

  • time (str or datetime.datetime) – A ISO-formatted time string or datetime object. Must be in UT time.

  • redownload (bool) – Redownload the file.

Returns:

The skymap.

Return type:

dict

asilib.asi.trex_nir_info()[source]#

Returns a pd.DataFrame with the TREx NIR ASI names and locations.

Returns:

A table of TREx-RGB imager names and locations.

Return type:

pd.DataFrame

Class Interface#

class asilib.Imager(file_info, meta, skymap, plot_settings={})[source]#

Bases: object

The central asilib class to plot, animate, and analyze ASI data.

Normally asilib.Imager() should not be directly called by users, but by the ASI wrapper functions. This interface is thoroughly documented in the Adding A New ASI documentation page.

Parameters:
  • file_info (dict) – Specifies image file paths, start end end times for each file, the loader function, and if the user needs one or multiple images.

  • meta (dict) – Specifies ASI metadata that describes the ASI name, location, cadence, and pixel resolution.

  • skymap (dict) – Specifies what each pixel maps to in (azimuth, elevation) coordinates as well as (latitude, longitude) coordinates at a prescribed auroral mission altitude.

  • plot_settings (dict) – An optional dictionary customizing the plot colormap, color scale (logarithmic vs linear), and color bounds (vmin, vmax arguments in matplotlib.imshow()).

plot_fisheye(ax=None, label=True, color_map=None, color_bounds=None, color_norm=None, color_brighten=True, azel_contours=False, azel_contour_color='yellow', cardinal_directions='NE', origin=(0.8, 0.1))[source]#

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

Parameters:
  • ax (plt.Axes) – The subplot to plot the image on. If None this method 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. By default will use a black-white colormap. For more information See matplotlib colormaps.

  • color_bounds (List[float]) – The lower and upper values of the color scale. The default is: low=1st_quartile and high=min(3rd_quartile, 10*1st_quartile). This range works well for most cases.

  • color_norm (str) – Set the ‘lin’ (linear) or ‘log’ (logarithmic) color normalization. If color_norm=None, the color normalization will be taken from the ASI array (if specified), and if not specified it will default to logarithmic. The norm is not applied to RGB images (see matplotlib.pyplot.imshow)

  • color_brighten (bool) – If True, scales the RGB intensities from min(image)-max(image) to 0-1 range. This results in brighter colors. This is only applied to RGB images.

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

  • azel_contour_color (str) – The color of the azimuth and elevation contours.

  • cardinal_directions (str) – Plot one or more cardinal directions specified with a string containing the first letter of one or more cardinal directions. Case insensitive. For example, to plot the North and East directions, set cardinal_directions=’NE’.

  • origin (tuple) – The origin of the cardinal direction arrows.

Returns:

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

  • im (matplotlib.collections.QuadMesh) – 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

>>> # A bright auroral arc that was analyzed by Imajo et al., 2021 "Active
>>> # auroral arc powered by accelerated electrons from very high altitudes"
>>> from datetime import datetime
>>> import matplotlib.pyplot as plt
>>> import asilib.asi
>>>
>>> asi = asilib.asi.themis('RANK', time=datetime(2017, 9, 15, 2, 34, 0))
>>> ax, im = asi.plot_fisheye(cardinal_directions='NE', origin=(0.95, 0.05))
>>> plt.colorbar(im)
>>> ax.axis('off')
>>> plt.show()
animate_fisheye(**kwargs)[source]#

A wrapper for the `Imager.animate_fisheye_gen()` method that animates a series of fisheye images. Any kwargs are passed directly into `Imager.animate_fisheye_gen()`.

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

  • 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. By default will use a black-white colormap. For more information See matplotlib colormaps.

  • color_bounds (List[float]) – The lower and upper values of the color scale. The default is: low=1st_quartile and high=min(3rd_quartile, 10*1st_quartile). This range works well for most cases.

  • color_norm (str) –

    Set the ‘lin’ (linear) or ‘log’ (logarithmic) color normalization. If color_norm=None, the color normalization will be taken from the ASI array (if specified), and if not specified it will default to logarithmic. The norm is not applied to RGB images (see matplotlib.pyplot.imshow)

  • color_brighten (bool) – If True, scales the RGB intensities from min(image)-max(image) to 0-1 range. This results in brighter colors. This is only applied to RGB images.

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

  • azel_contour_color (str) – The color of the azimuth and elevation contours.

  • cardinal_directions (str) – Plot one or more cardinal directions specified with a string containing the first letter of one or more cardinal directions. Case insensitive. For example, to plot the North and East directions, set cardinal_directions=’NE’.

  • origin (tuple) – The origin of the cardinal direction arrows.

  • 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_params (dict) – The additional/overwitten ffmpeg output parameters. The default parameters are: framerate=10, crf=25, vcodec=libx264, pix_fmt=yuv420p, preset=slower.

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

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.asi
>>>
>>> time_range = (datetime(2015, 3, 26, 6, 7), datetime(2015, 3, 26, 6, 12))
>>> asi = asilib.asi.themis('FSMI', time_range=time_range)
>>> asi.animate_fisheye(cardinal_directions='NE', origin=(0.95, 0.05), overwrite=True)
>>> print(f'Animation saved in {asilib.config["ASI_DATA_DIR"] / "animations" / asi.animation_name}')
animate_fisheye_gen(ax=None, label=True, color_map=None, color_bounds=None, color_norm=None, color_brighten=True, azel_contours=False, azel_contour_color='yellow', cardinal_directions='NE', origin=(0.8, 0.1), movie_container='mp4', animation_save_dir=None, ffmpeg_params={}, overwrite=False)[source]#

Animate a series of fisheye images and superpose your data on each image.

A generator behaves like an iterator in that it plots one fisheye image at a time and yields (similar to returns) the image. You can modify, or add content to the image (such as a spacecraft position). Then, once the iteration is complete, this method stitches the images into an animation. See the examples below and in the examples page for use cases. The `animate_fisheye()` method takes care of the iteration.

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

  • 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. By default will use a black-white colormap. For more information See matplotlib colormaps.

  • color_bounds (List[float]) – The lower and upper values of the color scale. The default is: low=1st_quartile and high=min(3rd_quartile, 10*1st_quartile). This range works well for most cases.

  • color_norm (str) –

    Set the ‘lin’ (linear) or ‘log’ (logarithmic) color normalization. If color_norm=None, the color normalization will be taken from the ASI array (if specified), and if not specified it will default to logarithmic. The norm is not applied to RGB images (see matplotlib.pyplot.imshow)

  • color_brighten (bool) – If True, scales the RGB intensities from min(image)-max(image) to 0-1 range. This results in brighter colors. This is only applied to RGB images.

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

  • azel_contour_color (str) – The color of the azimuth and elevation contours.

  • cardinal_directions (str) – Plot one or more cardinal directions specified with a string containing the first letter of one or more cardinal directions. Case insensitive. For example, to plot the North and East directions, set cardinal_directions=’NE’.

  • origin (tuple) – The origin of the cardinal direction arrows.

  • 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_params (dict) – The additional/overwitten ffmpeg output parameters. The default parameters are: framerate=10, crf=25, vcodec=libx264, pix_fmt=yuv420p, preset=slower.

  • overwrite (bool) – Overwrite the animation. If False, ffmpeg will prompt you to answer y/n if the animation already exists.

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 (matplotlib.collections.QuadMesh) – 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.asi
>>> import asilib
>>>
>>> time_range = (datetime(2015, 3, 26, 6, 7), datetime(2015, 3, 26, 6, 12))
>>> asi = asilib.asi.themis('FSMI', time_range=time_range)
>>> gen = asi.animate_fisheye_gen(cardinal_directions='NE', origin=(0.95, 0.05), overwrite=True)
>>> for image_time, image, ax, im in gen:
...         # Add your code that modifies each image here.
...         pass
...
>>> print(f'Animation saved in {asilib.config["ASI_DATA_DIR"] / "animations" / asi.animation_name}')
plot_map(lon_bounds=(-160, -50), lat_bounds=(40, 82), ax=None, coast_color='k', land_color='g', ocean_color='w', color_map=None, color_bounds=None, color_norm=None, color_brighten=True, min_elevation=10, asi_label=True, pcolormesh_kwargs={})[source]#

Projects an ASI image onto a map at an altitude that is defined in the skymap calibration file.

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

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

  • ax (plt.Axes, tuple) – The subplot to put the map on. If cartopy is installed, `ax` must be a two element tuple specifying the plt.Figure object and subplot position passed directly as args into fig.add_subplot().

  • 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.

  • color_map (str) –

    The matplotlib colormap to use. See matplotlib colormaps.

  • color_norm (str) –

    Set the ‘lin’ (linear) or ‘log’ (logarithmic) color normalization. If color_norm=None, the color normalization will be taken from the ASI array (if specified), and if not specified it will default to logarithmic. The norm is not applied to RGB images (see matplotlib.pyplot.imshow)

  • color_brighten (bool) – If True, scales the RGB intensities from min(image)-max(image) to 0-1 range. This results in brighter colors. This is only applied to RGB images.

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

  • asi_label (bool) – Annotates the map with the ASI code in the center of the mapped 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 – Set the ‘lin’ (linear) or ‘log’ (logarithmic) color normalization. If color_norm=None, the color normalization will be taken from the ASI array (if specified), and if not specified it will default to logarithmic.

  • pcolormesh_kwargs (dict) – A dictionary of keyword arguments (kwargs) to pass directly into plt.pcolormesh.

Returns:

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

  • matplotlib.collections.QuadMesh – The plt.pcolormesh image object. Common use for p is to add a colorbar.

Examples

>>> # Project an image of STEVE onto a map.
>>> from datetime import datetime
>>> import matplotlib.pyplot as plt
>>> import asilib.asi
>>>
>>> asi = asilib.asi.themis('ATHA', time=datetime(2010, 4, 5, 6, 7, 0))
>>> asi.plot_map(lon_bounds=(-127, -100), lat_bounds=(45, 65))
>>> plt.tight_layout()
>>> plt.show()
animate_map(**kwargs)[source]#

A wrapper for the `animate_map_gen()` method that animates a series of mapped images. Any kwargs are passed directly into `animate_map_gen()`.

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

  • 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. By default will use a black-white colormap. For more information See matplotlib colormaps.

  • color_bounds (List[float]) – The lower and upper values of the color scale. The default is: low=1st_quartile and high=min(3rd_quartile, 10*1st_quartile). This range works well for most cases.

  • color_norm (str) –

    Set the ‘lin’ (linear) or ‘log’ (logarithmic) color normalization. If color_norm=None, the color normalization will be taken from the ASI array (if specified), and if not specified it will default to logarithmic. The norm is not applied to RGB images (see matplotlib.pyplot.imshow)

  • color_brighten (bool) – If True, scales the RGB intensities from min(image)-max(image) to 0-1 range. This results in brighter colors. This is only applied to RGB images.

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

  • azel_contour_color (str) – The color of the azimuth and elevation contours.

  • cardinal_directions (str) – Plot one or more cardinal directions specified with a string containing the first letter of one or more cardinal directions. Case insensitive. For example, to plot the North and East directions, set cardinal_directions=’NE’.

  • 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_params (dict) – The additional/overwitten ffmpeg output parameters. The default parameters are: framerate=10, crf=25, vcodec=libx264, pix_fmt=yuv420p, preset=slower.

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

Example

>>> from datetime import datetime
>>> import asilib.asi
>>> import asilib
>>>
>>> location = 'FSMI'
>>> time_range = (datetime(2015, 3, 26, 6, 7), datetime(2015, 3, 26, 6, 12))
>>> asi = asilib.asi.themis(location, time_range=time_range)
>>> asi.animate_map(overwrite=True)
>>> print(f'Animation saved in {asilib.config["ASI_DATA_DIR"] / "animations" / asi.animation_name}')
animate_map_gen(lon_bounds=(-160, -50), lat_bounds=(40, 82), ax=None, coast_color='k', land_color='g', ocean_color='w', color_map=None, color_bounds=None, color_norm=None, color_brighten=True, min_elevation=10, pcolormesh_kwargs={}, asi_label=True, movie_container='mp4', animation_save_dir=None, ffmpeg_params={}, overwrite=False)[source]#

Animate a series of mapped images and superpose your data on each image.

A generator behaves like an iterator in that it plots one fisheye image at a time and yields (similar to returns) the image. You can modify, or add content to the image (such as a spacecraft position). Then, once the iteration is complete, this method stitches the images into an animation. See the examples below and in the examples page for use cases. The `animate_fisheye()` method takes care of the iteration.

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

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

  • ax (plt.Axes, tuple) –

    The subplot to put the map on. If cartopy is installed, `ax` must be a two element tuple specifying the plt.Figure object and subplot position passed directly as args into fig.add_subplot().

  • 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.

  • color_map (str) –

    The matplotlib colormap to use. See matplotlib colormaps for supported colormaps.

  • color_bounds (List[float]) – The lower and upper values of the color scale. The default is: low=1st_quartile and high=min(3rd_quartile, 10*1st_quartile). This range works well for most cases.

  • color_norm (str) –

    Set the ‘lin’ (linear) or ‘log’ (logarithmic) color normalization. If color_norm=None, the color normalization will be taken from the ASI array (if specified), and if not specified it will default to logarithmic. The norm is not applied to RGB images (see matplotlib.pyplot.imshow)

  • color_brighten (bool) – If True, scales the RGB intensities from min(image)-max(image) to 0-1 range. This results in brighter colors. This is only applied to RGB images.

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

  • pcolormesh_kwargs (dict) – A dictionary of keyword arguments (kwargs) to pass directly into plt.pcolormesh.

  • asi_label (bool) – Annotates the map with the ASI code in the center of the mapped 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_params (dict) – The additional/overwitten ffmpeg output parameters. The default parameters are: framerate=10, crf=25, vcodec=libx264, pix_fmt=yuv420p, preset=slower.

  • overwrite (bool) – Overwrite the animation. If False, ffmpeg will prompt you to answer y/n if the animation already exists.

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 (matplotlib.collections.QuadMesh) – 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.

Example

>>> from datetime import datetime
>>> import matplotlib.pyplot as plt
>>> import asilib
>>> import asilib.asi
>>>
>>> location = 'FSMI'
>>> time_range = (datetime(2015, 3, 26, 6, 7), datetime(2015, 3, 26, 6, 12))
>>> asi = asilib.asi.themis(location, time_range=time_range)
>>> ax = asilib.map.create_map(lon_bounds=(-120, -100), lat_bounds=(55, 65))
>>> plt.tight_layout()
>>>
>>> gen = asi.animate_map_gen(overwrite=True, ax=ax)
>>>
>>> for image_time, image, ax, im in gen:
>>>     # Add your code that modifies each image here...
>>>     # To demonstrate, lets annotate each frame with the timestamp.
>>>     # We will need to delete the prior text object, otherwise the current one
>>>     # will overplot on the prior one---clean up after yourself!
>>>     if 'text_obj' in locals():
>>>             ax.texts.remove(text_obj)
>>>     text_obj = ax.text(0, 0.9, f'THEMIS-{location} at {image_time:%F %T}',
>>>             transform=ax.transAxes, color='white', fontsize=15)
>>>
>>> print(f'Animation saved in {asilib.config["ASI_DATA_DIR"] / "animations" / asi.animation_name}')
keogram(path=None, aacgm=False, minimum_elevation=0)[source]#

Create a keogram along the meridian or a custom path.

Parameters:
  • path (array) – Make a keogram along a custom path. The path is a lat/lon array of shape (n, 2). Longitude must be between [-180, 180].

  • 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.

  • minimum_elevation (float) – The minimum elevation of pixels to use in the keogram.

Returns:

  • np.array – Keogram timestamps

  • np.array – Keogram latitudes: geographic if the aacgm kwarg is False and magnetic is aacgm if True.

  • np.array – Keogram array with rows corresponding to times and columns with latitudes.

Example

>>> # A keogram in geographic and magnetic latitude coordinates. See
>>> # Imager.plot_keogram() on how to plot a keogram.
>>> # Event from https://doi.org/10.1029/2021GL094696
>>> import numpy as np
>>> import asilib.asi
>>>
>>> time_range=['2008-01-16T10', '2008-01-16T12']
>>>
>>> asi = asilib.asi.themis('GILL', time_range=time_range)
>>> time, geo_lat, geo_keogram = asi.keogram()  # geographic latitude
>>> time, mag_lat, mag_keogram = asi.keogram(aacgm=True)  # magnetic latitude
>>> time
array([datetime.datetime(2008, 1, 16, 10, 0, 0, 20162),
    datetime.datetime(2008, 1, 16, 10, 0, 3, 9658),
    datetime.datetime(2008, 1, 16, 10, 0, 6, 29345), ...,
    datetime.datetime(2008, 1, 16, 11, 59, 51, 50496),
    datetime.datetime(2008, 1, 16, 11, 59, 54, 10602),
    datetime.datetime(2008, 1, 16, 11, 59, 57, 60543)], dtype=object)
>>> geo_lat[:10]
array([47.900368, 48.506763, 49.057587, 49.556927, 50.009083, 50.418365,
    50.788963, 51.124836, 51.42965 , 51.706768], dtype=float32)
>>> mag_lat[:10]
array([57.97198543, 58.55886486, 59.09144098, 59.57379565, 60.01019679,
    60.40490277, 60.76203547, 61.0854798 , 61.37882613, 61.64536043])
>>> np.all(mag_keogram == geo_keogram)  # aacgm=True only changes the latitudes.
True
plot_keogram(ax=None, path=None, aacgm=False, title=True, minimum_elevation=0, color_map=None, color_bounds=None, color_norm=None, color_brighten=True, pcolormesh_kwargs={})[source]#

Plot a keogram along the meridian or a custom path.

Parameters:
  • ax (plt.Axes) – The subplot to plot the keogram on.

  • path (np.array) – Make a keogram along a custom path. The path is a lat/lon array of shape (n, 2). Longitude must be between [-180, 180].

  • 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.

  • title (bool) – Add a plot title with the date, ASI array, and ASI location.

  • minimum_elevation (float) – The minimum elevation of pixels to use in the keogram.

  • color_map (str) –

    The matplotlib colormap to use. See matplotlib colormaps for supported colormaps.

  • color_bounds (List[float]) – The lower and upper values of the color scale. The default is: low=1st_quartile and high=min(3rd_quartile, 10*1st_quartile). This range works well for most cases.

  • color_norm (str) –

    Set the ‘lin’ (linear) or ‘log’ (logarithmic) color normalization. If color_norm=None, the color normalization will be taken from the ASI array (if specified), and if not specified it will default to logarithmic. The norm is not applied to RGB images (see matplotlib.pyplot.imshow)

  • color_brighten (bool) – If True, scales the RGB intensities from min(image)-max(image) to 0-1 range. This results in brighter colors. This is only applied to RGB images.

  • pcolormesh_kwargs (dict) – A dictionary of keyword arguments (kwargs) to pass directly into plt.pcolormesh.

Returns:

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

  • matplotlib.collections.QuadMesh – The plt.pcolormesh image object, useful to add a colorbar, for example.

Example

>>> # Plot a keogram in geographic and magnetic latitude coordinates.
>>> # Event from https://doi.org/10.1029/2021GL094696
>>> import matplotlib.pyplot as plt
>>> import asilib.asi
>>>
>>> time_range=['2008-01-16T10', '2008-01-16T12']
>>> fig, ax = plt.subplots(2, sharex=True, figsize=(10, 6))
>>>
>>> asi = asilib.asi.themis('GILL', time_range=time_range)
>>> _, p = asi.plot_keogram(ax=ax[0], color_map='turbo')
>>> asi.plot_keogram(ax=ax[1], color_map='turbo', aacgm=True, title=False)
>>>
>>> ax[0].set_ylabel('Geographic Lat [deg]')
>>> ax[1].set_ylabel('Magnetic Lat [deg]')
>>> fig.subplots_adjust(right=0.8)
>>> cbar_ax = fig.add_axes([0.85, 0.15, 0.05, 0.7])
>>> fig.colorbar(p, cax=cbar_ax)
>>> plt.show()
iter_files()[source]#

Iterate one ASI file (or large chunks of a file) at a time. The output data is clipped by time_range.

Yields:
  • np.array – ASI timestamps in datetine.datetime() or numpy.datetime64() format.

  • np.array – ASI images.

Example

Loop over ~5 minutes of data, starting in the middle of one file.
>>> import asilib.asi
>>> time_range=['2008-01-16T10:00:30', '2008-01-16T10:05']
>>> asi = asilib.asi.themis('GILL', time_range=time_range)
>>> for file_times, file_images in asi.iter_files():
...     print(file_times[0], file_times[-1], file_images.shape)
...
2008-01-16 10:00:30.019526 2008-01-16 10:00:57.049007 (10, 256, 256)
2008-01-16 10:01:00.058996 2008-01-16 10:01:57.049620 (20, 256, 256)
2008-01-16 10:02:00.059597 2008-01-16 10:02:57.029981 (20, 256, 256)
2008-01-16 10:03:00.050822 2008-01-16 10:03:57.020254 (20, 256, 256)
2008-01-16 10:04:00.030448 2008-01-16 10:04:57.046170 (20, 256, 256)
property data[source]#

Load ASI data.

Returns:

A named tuple containing (times, images). Members can be accessed using either index notation, or dot notation.

Return type:

namedtuple

class asilib.Imagers(imagers, iter_tol=2)[source]#

Bases: object

Plot and animate multiple Imager() objects.

Warning

This class is in development and not all methods are implemented/matured.

Parameters:
  • imagers (Tuple) – The Imager objects to plot and animate.

  • iter_tol (float) – The allowable time tolerance, in units of time_tol*imager_cadence, for imagers to be considered synchronized. Adjusting this kwarg is useful if the imager has missing data and you need to animate a mosaic.

plot_fisheye(ax, **kwargs)[source]#

Plots one fisheye image in each subplot, oriented with North on the top, and East on the left of the image.

Parameters:
  • ax (Tuple[plt.Axes]) – Subplots corresponding to each fisheye lens image.

  • kwargs (dict) – Keyword arguments directly passed into each plot_fisheye() method.

Example

>>> from datetime import datetime
>>>
>>> import matplotlib.pyplot as plt
>>> import asilib
>>> import asilib.asi
>>>
>>> time = datetime(2007, 3, 13, 5, 8, 45)
>>> location_codes = ['FSIM', 'ATHA', 'TPAS', 'SNKQ']
>>>
>>> fig, ax = plt.subplots(1, len(location_codes), figsize=(12, 3.5))
>>>
>>> _imagers = []
>>>
>>> for location_code in location_codes:
>>>     _imagers.append(asilib.asi.themis(location_code, time=time))
>>>
>>> for ax_i in ax:
>>>     ax_i.axis('off')
>>>
>>> asis = asilib.Imagers(_imagers)
>>> asis.plot_fisheye(ax=ax)
>>>
>>> plt.suptitle('Donovan et al. 2008 | First breakup of an auroral arc')
>>> plt.tight_layout()
>>> plt.show()
plot_map(overlap=False, **kwargs)[source]#

Projects multiple ASI images onto a map at an altitude that is defined in the skymap calibration file.

Parameters:
  • overlap (bool) – If True, pixels that overlap between imager FOV’s are overplotted such that only the final imager’s pixels are shown.

  • kwargs (dict) – Keyword arguments directly passed into each plot_map() method.

Example

>>> from datetime import datetime
>>>
>>> import matplotlib.pyplot as plt
>>>
>>> import asilib
>>> import asilib.map
>>> import asilib.asi
>>>
>>> time = datetime(2007, 3, 13, 5, 8, 45)
>>> location_codes = ['FSIM', 'ATHA', 'TPAS', 'SNKQ']
>>> map_alt = 110
>>> min_elevation = 2
>>>
>>> ax = asilib.map.create_map(lon_bounds=(-140, -60), lat_bounds=(40, 82))
>>>
>>> _imagers = []
>>>
>>> for location_code in location_codes:
>>>     _imagers.append(asilib.asi.themis(location_code, time=time, alt=map_alt))
>>>
>>> asis = asilib.Imagers(_imagers)
>>> asis.plot_map(ax=ax, overlap=False, min_elevation=min_elevation)
>>>
>>> ax.set_title('Donovan et al. 2008 | First breakup of an auroral arc')
>>> plt.show()
animate_map(**kwargs)[source]#

Animate an ASI mosaic. It is a wrapper for the animate_map_gen() method.

See animate_map_gen() documentation for the complete list of kwargs.

Example

>>> import asilib
>>> import asilib.asi
>>>
>>> time_range = ('2021-11-04T06:55', '2021-11-04T07:05')
>>> asis = asilib.Imagers(
>>>     [asilib.asi.trex_rgb(location_code, time_range=time_range)
>>>     for location_code in ['LUCK', 'PINA', 'GILL', 'RABB']]
>>>     )
>>> asis.animate_map(lon_bounds=(-115, -85), lat_bounds=(43, 63), overwrite=True)
animate_map_gen(overlap=False, lon_bounds=(-160, -50), lat_bounds=(40, 82), ax=None, coast_color='k', land_color='g', ocean_color='w', color_map=None, color_bounds=None, color_norm=None, color_brighten=True, min_elevation=10, pcolormesh_kwargs={}, asi_label=True, movie_container='mp4', animation_save_dir=None, ffmpeg_params={}, overwrite=False)[source]#

Animate an ASI mosaic.

Parameters:
  • overlap (bool) – If True, pixels that overlap between imager FOV’s are overplotted such that only the final imager’s pixels are shown.

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

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

  • ax (plt.Axes, tuple) –

    The subplot to put the map on. If cartopy is installed, `ax` must be a two element tuple specifying the plt.Figure object and subplot position passed directly as args into fig.add_subplot().

  • 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.

  • color_map (str) –

    The matplotlib colormap to use. See matplotlib colormaps for supported colormaps.

  • color_bounds (List[float]) – The lower and upper values of the color scale. The default is: low=1st_quartile and high=min(3rd_quartile, 10*1st_quartile). This range works well for most cases.

  • color_norm (str) – Set the ‘lin’ (linear) or ‘log’ (logarithmic) color normalization. If color_norm=None, the color normalization will be taken from the ASI array (if specified), and if not specified it will default to logarithmic.

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

  • pcolormesh_kwargs (dict) – A dictionary of keyword arguments (kwargs) to pass directly into plt.pcolormesh.

  • asi_label (bool) – Annotates the map with the ASI code in the center of the mapped 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_params (dict) – The additional/overwitten ffmpeg output parameters. The default parameters are: framerate=10, crf=25, vcodec=libx264, pix_fmt=yuv420p, preset=slower.

  • overwrite (bool) – Overwrite the animation. If False, ffmpeg will prompt you to answer y/n if the animation already exists.

Yields:
  • datetime.datetime – The guide time used to keep the images synchronized.

  • List[datetime.datetime] – Nearest imager time stamps to the guide time. If the difference between the imager time and the guide time is greater than time_tol*imager_cadence, or the imager is off, the imager is considered unsynchronized and the returned time is datetime.min.

  • List[np.ndarray] – The images corresponding to the times returned above. If the that imager is unsynchronized, the corresponding image value is None.

  • plt.Axes – The subplot object.

Example

>>> # Animate a TREX-RGB mosaic and print the individual time stamps
>>> # to confirm that the imagers are synchronized.
>>> import asilib
>>> import asilib.asi
>>>
>>> time_range = ('2021-11-04T06:55', '2021-11-04T07:05')
>>> asis = asilib.Imagers(
>>>     [asilib.asi.trex_rgb(location_code, time_range=time_range)
>>>     for location_code in ['LUCK', 'PINA', 'GILL', 'RABB']]
>>>     )
>>> gen = asis.animate_map_gen(
>>>     lon_bounds=(-115, -85), lat_bounds=(43, 63), overwrite=True
>>>     )
>>> for guide_time, asi_times, asi_images, ax in gen:
>>>     if '_text_obj' in locals():
>>>         _text_obj.remove()
>>>     info_str = f'Guide: {guide_time: %Y:%m:%d %H:%M:%S}\n'
>>>     # The below for loop is possible because the imagers and
>>>     # asi_times can be indexed together.
>>>     for _imager, _imager_time in zip(asis.imagers, asi_times):
>>>         info_str += f'{_imager.meta["location"]}: {_imager_time: %Y:%m:%d %H:%M:%S}\n'
>>>     info_str = info_str[:-1]  # Remove the training newline
>>>
>>>     _text_obj = ax.text(
>>>         0.01, 0.99, info_str, va='top', transform=ax.transAxes,
>>>         bbox=dict(facecolor='grey', edgecolor='black'))
get_points(min_elevation=10)[source]#

Get pixel intensities in each (lat, lon) grid point.

Parameters:

min_elevation (float) – Only return pixel intensities above min_elevation.

Returns:

  • np.ndarray – An (n, 2) array with each row corresponding to a (lat, lon) point.

  • np.ndarray – Pixel intensities with shape (n) for white-light images, and (n, 3) for RGB images.

Examples

>>> from datetime import datetime
>>>
>>> import asilib
>>> import asilib.asi
>>>
>>> time = datetime(2007, 3, 13, 5, 8, 45)
>>> location_codes = ['FSIM', 'ATHA', 'TPAS', 'SNKQ']
>>> map_alt = 110
>>> min_elevation = 2
>>>
>>> _imagers = [asilib.asi.themis(location_code, time=time, alt=map_alt)
>>>             for location_code in location_codes]
>>> asis = asilib.Imagers(_imagers)
>>> lat_lon_points, intensities = asis.get_points(min_elevation=min_elevation)
>>> # A comprehensive example showing how Imagers.get_points() can closely reproduce
>>> # Imagers.plot_map()
>>> from datetime import datetime
>>>
>>> import matplotlib.pyplot as plt
>>> import matplotlib.colors
>>>
>>> import asilib
>>> import asilib.map
>>> import asilib.asi
>>>
>>> time = datetime(2007, 3, 13, 5, 8, 45)
>>> location_codes = ['FSIM', 'ATHA', 'TPAS', 'SNKQ']
>>> map_alt = 110
>>> min_elevation = 2
>>>
>>> _imagers = [asilib.asi.themis(location_code, time=time, alt=map_alt)
>>>             for location_code in location_codes]
>>> asis = asilib.Imagers(_imagers)
>>> lat_lon_points, intensities = asis.get_points(min_elevation=min_elevation)
>>>
>>> fig = plt.figure(figsize=(12,5))
>>> ax = asilib.map.create_simple_map(
>>>     lon_bounds=(-140, -60), lat_bounds=(40, 82), fig_ax=(fig, 121)
>>>     )
>>> bx = asilib.map.create_simple_map(
>>>     lon_bounds=(-140, -60), lat_bounds=(40, 82), fig_ax=(fig, 122)
>>>     )
>>> asis.plot_map(ax=ax, overlap=False, min_elevation=min_elevation)
>>> bx.scatter(lat_lon_points[:, 1], lat_lon_points[:, 0], c=intensities,
>>>         norm=matplotlib.colors.LogNorm())
>>> ax.text(0.01, 0.99, f'(A) Mosaic using Imagers.plot_map()', transform=ax.transAxes,
>>>         va='top', fontweight='bold', color='red')
>>> bx.text(0.01, 0.99, f'(B) Mosaic from Imagers.get_points() scatter', transform=bx.transAxes,
>>>         va='top', fontweight='bold', color='red')
>>> fig.suptitle('Donovan et al. 2008 | First breakup of an auroral arc')
>>> plt.tight_layout()
>>> plt.show()
class asilib.Conjunction(imager, satellite)[source]#

Bases: object

find(min_el=20, time_gap_s=60)[source]#

Finds the start and end times of conjunctions defined by a minimum elevation.

Parameters:

min_el (float) – The minimum elevation of the conjunction.

intensity(box=None, box_op=None)[source]#

Calculate the auroral intensity near the satellite’s footprint at the ASI time stamps.

Parameters:
  • box (Tuple[float, float]) – A tuple of two floats that specifies the rectangular area, at the auroral emission altitude, in which to calculate the auroral intensity. The intensities in the box are averaged by default, and can be changed using the box_op kwarg. If box_size=None, the auroral intensity will come from the pixel nearest to the footprint. In this case the box_op kwarg is irrelevant.

  • box_op (Callable) – The function to apply to the auroral intensity in the box surrounding the footprint. Since it must operate on the mask array that equal_area() produces, the box_op function must work with (i.e., ignore) np.nan values. If None, the function is np.nanmean() summed over the x-y pixels.

Returns:

  • np.ndarray – The auroral intensity near the footprint, calculated either from the nearest pixel (if box_size=None) or the mean intensity in a rectangular area defined by box_size.

  • .. note:: – If box_size=None the nearest pixel is calculated using map_azel(), otherwise if box_size=(10, 10) and box_op is the default, equal_area() is used to calculate the mean intensity in a 10x10 km box. The two different implementations should yield similar results, but discrepancies may arise if the skymap (az, el) and (lat, lon) mapping arrays are mismatched. This is the case for some of the THEMIS ASIs right after they were deployed.

interp_sat()[source]#

Interpolate the satellite timestamps and LLA to imager timestamps.

lla_footprint(alt, b_model='OPQ77', maginput=None, hemisphere=0)[source]#

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

Parameters:
  • 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 different 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.

map_azel(min_el=0)[source]#

Maps a satellite’s location to the ASI’s azimuth and elevation (azel) coordinates and image pixel index.

Parameters:

min_el (float) – The minimum elevation in degrees for which return valid values for. The satellite’s azel values and pixel indices are NaN below min_el.

Returns:

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

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

  • .. note:: – The azel pixel columns are ordered for plotting with an image: plt.plot(azel_pixels[:, 0], azel_pixels[:, 1]). However, the column order must be flipped for indexing. For example: image[azel_pixels[:, 1], azel_pixels[:, 0]]

equal_area(box=(5, 5))[source]#

Find all pixels around the footprint within a rectangular area defined by box.

Parameters:

box (Tuple[float, float]) – Bounds the emission area box dimensions in longitude and latitude. Units are kilometers.

Returns:

An array with dimensions (n_time, n_x_pixels, n_y_pixels) 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

See also

Conjunction.equal_area_gen

A memory-friendly way to calculate equal areas.

equal_area_gen(box=(5, 5))[source]#

Generator to find all pixels around the footprint within a rectangular area defined by box.

Parameters:

box (Tuple[float, float]) – Bounds the emission box dimensions in longitude and latitude. Units are kilometers.

Returns:

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

Geographic Maps#

Plot geographic maps using cartopy or the simple built-in function. Before you project an ASI image onto a map, you will need to create a map using the following functions.

The simplest way to create a map is via create_map() that by default creates a map above North America. create_map() is a wrapper that automatically chooses what library to plot the map: cartopy if it is installed, or asilib’s create_simple_map() function to create a simple map if cartopy is not installed. All of these functions output the subplot object with the map.

You can override this automatic behavior by calling the underlying functions directly: create_simple_map() or create_cartopy_map().

The two functions are called similarly with the exception of the ax kwarg if you need to specify what subplot to create the map on:

  • for create_simple_map() you must pass in a ax subplot object, and

  • for create_cartopy_map(), you need to pass in a ax tuple containing two elements. The first element is the `plt.Figure object, and the second element is a 3 digit number (or a tuple) specifying where to place that subplot. For example,

    >>> fig = plt.Figure()
    >>> ax = asilib.map.create_cartopy_map(ax=(fig, 111))
    
asilib.map.create_map(lon_bounds=(-160, -50), lat_bounds=(40, 82), fig_ax=None, coast_color='k', land_color='g', ocean_color='w')[source]#

Create a geographic map using cartopy (if installed) or asilib’s own map library.

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

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

  • fig_ax (Tuple[matplotlib.figure.Figure, int]) –

    A two element tuple. First element is a matplotlib.figure.Figure object and second element is the subplot index or matplotlib.gridspec.SubplotSpec object. The second element is passed directly as args fig.add_subplot().

    For example:

    fig = plt.Figure()
    ax = asilib.map.create_cartopy_map(fig_ax=(fig, 111))
    

  • 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.

Returns:

The subplot object containing the map.

Return type:

plt.Axes

Examples

These examples will differ if you have cartopy installed or not. To force a consistent map, replace asilib.map.create_map with asilib.map.create_simple_map or asilib.map.create_cartopy_map.

Examples

>>> # Create a map above Scandinavia in a single subplot
>>> import asilib.map
>>> import matplotlib.pyplot as plt
>>> ax = asilib.map.create_map(lon_bounds=[0, 38], lat_bounds=[50, 75])
>>> ax.set_title('Generated via asilib.map.create_map()')
>>> plt.show()
>>> # The above examples made a map on one subplot. But what if you have multiple subplots?
>>> import asilib.map
>>> import numpy as np
>>> import matplotlib.pyplot as plt
>>> fig = plt.figure(figsize=(6, 10))
>>> bx = asilib.map.create_map(lon_bounds=[0, 38], lat_bounds=[50, 75], fig_ax=(fig, 211))
>>> cx = fig.add_subplot(2, 1, 2)
>>> cx.plot(np.arange(10), np.arange(10))
>>> fig.suptitle('Two subplots with equal sizes')
>>> plt.show()
>>> # Another multi-subplot example with different height ratios. The syntax is the same as in plt.subplot() (See the args section in https://matplotlib.org/stable/api/_as_gen/matplotlib.pyplot.subplot.html).
>>> import asilib.map
>>> import numpy as np
>>> import matplotlib.pyplot as plt
>>> fig = plt.figure(figsize=(6, 10))
>>> dx = (3, 1, (1, 2))
>>> dx = asilib.map.create_map(lon_bounds=[0, 38], lat_bounds=[50, 75], fig_ax=(fig, dx))
>>> ex = fig.add_subplot(3, 1, 3)
>>> ex.plot(np.arange(10), np.arange(10))
>>> fig.suptitle('Two subplots with unequal sizes')
>>> plt.show()
>>> # And make a map using gridspec
>>> import asilib.map
>>> import matplotlib.pyplot as plt
>>> import matplotlib.gridspec
>>> fig = plt.figure()
>>> gs = matplotlib.gridspec.GridSpec(1, 1, fig)
>>> dx = asilib.map.create_map(lon_bounds=[0, 38], lat_bounds=[50, 75], fig_ax=(fig, gs))
>>> dx.set_title('Map made using gridspec')
>>> plt.show()

See also

create_simple_map()

Create a simple map using asilib’s own map library.

create_cartopy_map()

Create a map using the cartopy library.

asilib.map.create_simple_map(lon_bounds=(-140, -60), lat_bounds=(40, 82), fig_ax=None, coast_color='k', land_color='g', ocean_color='w', file='ne_10m_land')[source]#

Create a simple map without cartopy.

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

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

  • fig_ax (Tuple[matplotlib.figure.Figure, int]) –

    A two element tuple. First element is a matplotlib.figure.Figure object and second element is the subplot index or matplotlib.gridspec.SubplotSpec object. The second element is passed directly as args fig.add_subplot().

    For example:

    fig = plt.Figure()
    ax = asilib.map.create_simple_map(fig_ax=(fig, 111))
    

  • 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.

  • 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}. You can download other shapefiles from https://www.naturalearthdata.com/downloads/10m-physical-vectors/.

Examples

See create_map() and replace create_map with create_simple_map.

Returns:

The subplot object containing the map.

Return type:

plt.Axes

asilib.map.create_cartopy_map(lon_bounds=(-160, -50), lat_bounds=(40, 82), fig_ax=None, coast_color='k', land_color='g', ocean_color='w')[source]#

A helper function to create two map styles: a simple black and white map, and a more sophisticated map with green land.

Parameters:
  • lon_bounds (tuple or list) – A tuple of length 2 specifying the map’s longitude bounds.

  • lat_bounds (tuple or list) – A tuple of length 2 specifying the map’s latitude bounds.

  • fig_ax (Tuple[matplotlib.figure.Figure, int]) –

    A two element tuple. First element is a matplotlib.figure.Figure object and second element is the subplot index or matplotlib.gridspec.SubplotSpec object. The second element is passed directly as args fig.add_subplot().

    For example:

    fig = plt.Figure()
    ax = asilib.map.create_cartopy_map(fig_ax=(fig, 111))
    

  • 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.

Returns:

ax – The subplot object with a cartopy map.

Return type:

plt.Axes

Examples

See create_map() and replace create_map with create_simple_map.