Imager API Reference#
Warning
The Imager API is under active development.
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.
Summary#
The central asilib class to plot, animate, and analyze ASI data. |
|
Plot geographic maps using cartopy or the simple built-in function. |
|
Create an Imager instance with the THEMIS ASI images and skymaps. |
|
Create an Imager instance using the LAMP's ground-based EMCCD ASI. |
|
Create an Imager instance using the LAMP's ground-based Phantom ASI. |
Imager#
asilib.Imager provides methods to load ASI time stamps and images, as well as basic plotting methods.
Note
Most of the basic asilib operations are to download and load large amounts of images. Therefore, your performance is largely impacted by your internet speed and the type of hard drive/memory on your machine.
- class asilib.imager.Imager(data, meta, skymap, plot_settings={})[source]#
Bases:
object
The central asilib class to plot, animate, and analyze ASI data.
Note
Considering that some ASIs produce enough data to overwhelm your computer’s memory, for example the Phantom ASIs in support of the LAMP sounding rocket produced a whopping 190 GB/hour of data, by default asilib loads data as needed. This is the “lazy” mode that prioritizes memory at the expense of higher CPU usage. Alternatively, if memory is not a concern, asilib supports an “eager” mode that loads all of the data into memory.
- Parameters:
data (dict) – Dictionary containing image data in two main formats (sets of keys): the first is with two keys
time
andimage
for a single image; orstart_time
,end_time
,path
, andloader
keys.meta (dict) – The ASI metadata that must have the following keys
array
,location
,lat
,lon
,alt
, andcadence
. Thecadence
units are seconds andalt
is kilometers.skymap (dict) – The data to map each pixel to azimuth and elevation (
az
,el
) and latitude, longitude, altitude (lat
,lon
,alt
) coordinates.plot_settings (dict) – An optional dictionary containing
`color_bounds`
,`color_map`
, and`color_norm`
keys. The`color_bounds`
can be either a function takes in an image and returns the lower and upper bound numbers, or a len 2 tuple or list. The`color_map`
key must be a valid matplotlib colormap. And lastly,`color_norm`
must be either`lin`
for linear or`log`
for logarithmic color scale.
- plot_fisheye(time=None, ax=None, label=True, color_map=None, color_bounds=None, color_norm='log', 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:
time (datetime.datetime or str) – The date and time to download of the data. If str,
time
must be in the ISO 8601 standard.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.
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 = asilib.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
`animate_fisheye_gen()`
method that animates a series of fisheye images. Any kwargs are passed directly into`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.
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 >>> time_range = (datetime(2015, 3, 26, 6, 7), datetime(2015, 3, 26, 6, 12)) >>> imager = asilib.themis('FSMI', time_range=time_range) >>> imager.animate_fisheye(cardinal_directions='NE', origin:tuple=(0.95, 0.05), overwrite=True) >>> print(f'Animation saved in {asilib.config["ASI_DATA_DIR"] / "animations" / imager.animation_name}')
- animate_fisheye_gen(ax=None, label=True, color_map=None, color_bounds=None, color_norm='log', azel_contours=False, azel_contour_color='yellow', cardinal_directions='NE', origin=(0.8, 0.1), movie_container='mp4', 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.
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 >>> time_range = (datetime(2015, 3, 26, 6, 7), datetime(2015, 3, 26, 6, 12)) >>> imager = asilib.themis('FSMI', time_range=time_range) >>> gen = imager.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" / imager.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='log', min_elevation=10, asi_label=True, pcolormesh_kwargs={})[source]#
Projects the ASI images to a map at an altitude 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 theplt.Figure
object and subplot position passed directly asargs
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.
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 (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.
- 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
>>> from datetime import datetime >>> import numpy as np >>> import matplotlib.pyplot as plt >>> import asilib
# Project a single image onto a single-panel geographic map.
>>> imager = asilib.themis('ATHA', time=datetime(2010, 4, 5, 6, 7, 0)) >>> imager.plot_map(lon_bounds=(-127, -100), lat_bounds=(45, 65)) >>> plt.tight_layout() >>> plt.show()
# Project a single image onto a two-panel geographic map using the # simple asilib map.
>>> imager = asilib.themis('ATHA', time=datetime(2010, 4, 5, 6, 7, 0)) >>> fig, ax = plt.subplots(1, 2, figsize=(10, 6)) >>> ax[0] = asilib.map.create_simple_map(lon_bounds=(-127, -100), lat_bounds=(45, 65), ax=ax[0]) >>> # or let asilib choose for you by calling >>> # ax[0] = asilib.map.create_map(lon_bounds=(-127, -100), lat_bounds=(45, 65), ax=ax[0]) >>> imager.plot_map(lon_bounds=(-127, -100), lat_bounds=(45, 65), ax=ax[0]) >>> ax[1].plot(np.arange(10), np.random.rand(10)) >>> plt.tight_layout() >>> plt.show()
# If you have cartopy installed, here is how you can project a single image # onto a two-panel geographic map.
>>> imager = asilib.themis('ATHA', time=datetime(2010, 4, 5, 6, 7, 0)) >>> fig = plt.figure(figsize=(10, 6)) >>> ax = [None, None] >>> ax[0] = asilib.map.create_cartopy_map(lon_bounds=(-127, -100), lat_bounds=(45, 65), ax=(fig, 121)) >>> ax[1] = plt.subplot(122) >>> # or let asilib choose for you by calling >>> # ax[0] = asilib.map.create_map(lon_bounds=(-127, -100), lat_bounds=(45, 65), ax=(fig, 121)) >>> imager.plot_map(lon_bounds=(-127, -100), lat_bounds=(45, 65), ax=ax[0]) >>> ax[1].plot(np.arange(10), np.random.rand(10)) >>> 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.
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 matplotlib.pyplot as plt >>> import asilib >>> >>> location = 'FSMI' >>> time_range = (datetime(2015, 3, 26, 6, 7), datetime(2015, 3, 26, 6, 12)) >>> asi = asilib.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='log', min_elevation=10, pcolormesh_kwargs={}, asi_label=True, movie_container='mp4', 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 theplt.Figure
object and subplot position passed directly asargs
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.
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 >>> >>> location = 'FSMI' >>> time_range = (datetime(2015, 3, 26, 6, 7), datetime(2015, 3, 26, 6, 12)) >>> imager = asilib.themis(location, time_range=time_range) >>> ax = asilib.map.create_map(lon_bounds=(-120, -100), lat_bounds=(55, 65)) >>> plt.tight_layout() >>> >>> gen = imager.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" / imager.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 >>> >>> time_range=['2008-01-16T10', '2008-01-16T12'] >>> >>> asi = asilib.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='log', 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.
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 >>> >>> time_range=['2008-01-16T10', '2008-01-16T12'] >>> fig, ax = plt.subplots(2, sharex=True, figsize=(10, 6)) >>> >>> asi = asilib.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 >>> time_range=['2008-01-16T10:00:30', '2008-01-16T10:05'] >>> asi = asilib.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)
- iter_chunks(chunk_size)[source]#
Chunk and iterate over the ASI data. The output data is clipped by time_range.
- Parameters:
chunk_size (int) – The number of time stamps and images to return.
- Yields:
np.array – ASI timestamps in datetine.datetime() or numpy.datetime64() format.
np.array – ASI images.
Example
TODO: Add
- class asilib.conjunction.Conjunction(imager, sat_time, sat_loc)[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.
- resample()[source]#
Resample the sat_loc from the satellite to imager time stamps. Useful for one-to-one comparison between the images a satellite trajectory.
- map_lla_footprint(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 inIRBEM
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 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.
- map_lla_azel(min_el=0)[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:
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.
- Raises:
AssertionError – If the sat_lla argument does not have exactly 3 columns (1st dimension).
Example
from datetime import datetimeimport numpy as npfrom 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 = 50lats = np.linspace(60, 50, n)lons = -113.64*np.ones(n)alts = 500**np.ones(n)lla = np.array([lats, lons, alts]).Ttime = datetime(2015, 10, 1) # To load the proper skymap file.azel, pixels = lla2azel(‘REGO’, ‘ATHA’, time, lla)
- equal_area(box=(5, 5))[source]#
Calculate a
box_km
area mask at the aurora emission altitude.- Parameters:
box (tuple) – 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
- equal_area_gen(box=(5, 5))[source]#
A generator function to calculate a
box_km
area mask at the aurora emission altitude for a large number of footprints.- Parameters:
box (tuple) – 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
Supported ASI systems (arrays)#
THEMIS#
The THEMIS ground-based All-Sky Imager (ASI) array observes the white light aurora over the North American continent from Canada to Alaska. The ASI array consists of 20 cameras covering a large section of the auroral oval with one-kilometer resolution. The all-sky imagers are time synchronized and have an image repetition rate of three seconds. During northern winter, continuous coverage is available from about 00:00-15:00 UT covering approximately 17-07 MLT for each individual site. Geographic locations and more details are available using asilib.asi.themis.themis_info(). The full-resolution 256x256 pixel images are transferred via hard-disk swap and become available approximately 3-5 months after data collection.
- asilib.asi.themis.themis(location_code, time=None, time_range=None, alt=110, 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).
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:
- asilib.asi.themis.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.
LAMP#
- asilib.asi.lamp_emccd.lamp(location_code, time=None, time_range=None, redownload=False, missing_ok=True, alt=90)[source]#
Create an Imager instance using the LAMP’s ground-based EMCCD ASI.
- 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) – A length 2 list of string-formatted times or datetimes to bracket the ASI data time interval.
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).
alt (int) – The mapping altitude.
- asilib.asi.lamp_emccd.find_skymap(location_code, alt, redownload=True)[source]#
Find the path to the skymap file.
- asilib.asi.lamp_emccd.load_skymap(location_code, alt, redownload)[source]#
Load the skymap file and apply the transformations.
- asilib.asi.lamp_phantom.lamp(location_code, time=None, time_range=None, redownload=False, missing_ok=True, alt=100)[source]#
Create an Imager instance using the LAMP’s ground-based Phantom ASI.
- 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) – A length 2 list of string-formatted times or datetimes to bracket the ASI data time interval.
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).
alt (int) – The mapping altitude.
- asilib.asi.lamp_phantom.lamp_reader(path)[source]#
Loads in the Phantom images chunk_size at a time to avoid a memory overflow. The .mat format is version 7.3 which are technically in the hdf5 format.
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 aax
subplot object, andfor
create_cartopy_map()
, you need to pass in aax
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 asargs
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
withasilib.map.create_simple_map
orasilib.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 asargs
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 replacecreate_map
withcreate_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 asargs
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 replacecreate_map
withcreate_simple_map
.