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.
ASI 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:
A THEMIS ASI instance with the time stamps, images, skymaps, and metadata.
- 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.
REGO#
As part of the Canadian Space Agency’s Geospace Observatory (GO) Canada initiative, the Auroral Imaging Group operates an array of redline auroral all-sky imagers designed by the AIG for the RISR-C CFI project. These systems are specifically designed to capture image data from only the 630.0nm wavelength (red coloured aurora). The Redline Geospace Observatory (REGO) array consists of 9 systems and are co-located with other auroral instrumentation that we operate to maximize the scientific impact. These imaging systems were deployed in late 2014 and continue to operate.
- asilib.asi.rego.rego(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 REGO 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:
Examples
>>> # Plot a single image. >>> from datetime import datetime >>> import matplotlib.pyplot as plt >>> import asilib >>> 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.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:
- asilib.asi.rego.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.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
TREx#
Transition Region Explorer (TREx) is a CFI-funded project and aims to be the world’s foremost auroral imaging facility for remote sensing the near-Earth space environment. The project consists of the development and deployment of an extensive ground-based network of sophisticated optical and radio instrumentation across Alberta, Saskatchewan, Manitoba, and the Northwest Territories.
The TREx project will design and deploy the following instruments: - 6 blue-line all-sky imagers (3s-30Hz cadence) - 6 RGB colour all-sky imagers (3s cadence) - 6 Near-Infrared all-sky imagers (6s cadence) - 10 Imaging Riometers (1s-100Hz cadence - operations project is GO-IRIS) - 2 Proton Aurora Meridian Imaging Spectographs (15s cadence) - 13 Global Navigation Satellite System receiver systems (GNSS)
In partnership with IBM, TREx will include sensor web technology to autonomously control and coordinate sensor behaviour across the observational region. This architecture will allow TREx to produce the first high resolution data (estimated at 120 TB of data per year) over a region large enough to study multi-scale coupling of key physical processes in the space environment.
- asilib.asi.trex.trex_nir(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 using the TREX-NIR 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:
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.trex_nir_info()[source]#
Returns a pd.DataFrame with the TREx NIR ASI names and locations.
- Returns:
A table of REGO imager names and locations.
- Return type:
pd.DataFrame
- asilib.asi.trex.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-fomatted time string or datetime object. Must be in UT time.
redownload (bool) – Redownload the file.
- Returns:
The skymap.
- Return type:
dict
ASI Interface#
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:
objectThe 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
timeandimagefor a single image; orstart_time,end_time,path, andloaderkeys.meta (dict) – The ASI metadata that must have the following keys
array,location,lat,lon,alt, andcadence. Thecadenceunits are seconds andaltis 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,
timemust 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 >>> >>> 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
`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.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='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.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='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.Figureobject and subplot position passed directly asargsinto 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
>>> # 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.
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='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.Figureobject and subplot position passed directly asargsinto 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 >>> 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='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.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)
- 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
Conjunctions with Satellites#
- class asilib.conjunction.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=<function nanmean>)[source]#
Calculate the auroral intensity near the satellite’s footprint.
- 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_opkwarg. Ifbox_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, thebox_opfunction must work with (i.e., ignore)np.nanvalues.
- 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 bybox_size... note:: – If box_size=None the nearest pixel is calculated using
map_azel(), otherwise ifbox_size=(10, 10)andbox_opis 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.
- lla_footprint(alt, b_model='OPQ77', maginput=None, hemisphere=0)[source]#
Map the spacecraft’s position to
altalong the magnetic field line. The mapping is implemented inIRBEMand 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_genA 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 aaxsubplot object, andfor
create_cartopy_map(), you need to pass in aaxtuple containing two elements. The first element is the`plt.Figureobject, 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.Figureobject and second element is the subplot index or matplotlib.gridspec.SubplotSpec object. The second element is passed directly asargsfig.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_mapwithasilib.map.create_simple_maporasilib.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.Figureobject and second element is the subplot index or matplotlib.gridspec.SubplotSpec object. The second element is passed directly asargsfig.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_mapwithcreate_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.Figureobject and second element is the subplot index or matplotlib.gridspec.SubplotSpec object. The second element is passed directly asargsfig.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_mapwithcreate_simple_map.