class imfits.Imfits(infile, pv=False, frame=None, equinox='J2000', axesorder=(), velocity=True, flip_vaxis=True, generate_empty_object=False, beam_savetype='full', beam_index=0)

Bases: object

Read and store fits data and header information. Spatial coordinates, velocity and frequency are saved in units of degree, km/s, and Hz, respectively, by default. Beam FWHM and PA are saved in units of arcsec and degree, respectively.

Parameters:
  • infile (str) – Path to the fits file.

  • pv (bool) – If the input fits file is the position-velocity image or not.

  • frame (str or None, optional) – Coordinate frame, required if missing in the FITS header.

  • equinox (str, optional) – Equinox of the coordinate frame; used when the coordinate frame is Jxxxx and the equinox is missing in the header.

  • axesorder (tuple) – Order of axes if they need to be reordered. The new axis order is specified using original axis indices. E.g., to swich the 2nd and 4th axes, use (0, 3, 2, 1). Indices start at 0.

  • velocity (bool) – Convert frequency to velocity if True.

  • flip_vaxis (bool) – Flip the velocity axis if it decreases with increasing index.

  • beam_savetype ({'full', 'average', or 'single'}, optional) – How to treat CASA multi-beam. See the read_casa_multibeam method for more details.

  • beam_index (int) – Index of multi-beam used when beam_savetype = ‘single’. See the read_casa_multibeam method for more details.

  • generate_empty_object (bool) – Generate an empty Imfits object if True.

attach_vectors(infile, sep='\\s+', rotate=False, comment='=', pandas_args=None)

Read and attach polarization/B-field vectors.

Parameters:
  • infile (str) – Path to the table file contaiting vectors.

  • sep (str) – Seperation character to be used.

  • rotate (bool) – Rotate vectors by 90 degree if True.

  • comment ('str') – Comment-out character in the table file.

  • pandas_args (dict or None) – Args for pandas.read_csv, with which the table file is read. If given, sep and comment must be also provided in pandas_args instead of the method input parameters.

binning(nbin, axis='velocity')

Bin data.

Parameters:
  • nbin (int) – Binning factor. E.g., if nbin = 3, original three pixels will be binned into a single pixel.

  • axis ({'velocity' or 'xy'}) – Axis to be binned.

binning_v(nbin)

Bin data along the velocity or frequency axis.

Parameters:

nbin (int) – Binning factor. E.g., if nbin = 3, original three pixels will be binned into a single pixel.

binning_xy(nbin)

Bin data in the xy spatial plane.

nbinint

Binning factor. E.g., if nbin = 3, original three pixels will be binned into a single pixel.

convert_units(conversion='IvtoTb')

Convert unit of intensity.

Parameters:

coversion ({'IvtoTb', 'TbtoIv', 'IvtoTp', 'pas2topmb'}) – Conversion to be applied. ‘IvtoTb’ converts Iv in Jy/beam to Tb in K. ‘TbtoIv’ applys conversion the other way around. ‘IvtoTp’ converts Iv to T through the full Planck function without using the Rayleigh-Jeans approximation. ‘pas2topmb’ converts Jy/arcsec^2 to Jy/beam.

copy()

Make a copy.

Return type:

Copied Imfits object.

flip_vaxis()

Flip the velocity axis. The axis order of (s, v, y, x) is assumed.

get_1dresolution(pa)

Calculate FWHM beam size along a 1D cut in a particular position angle.

This method solves get the FWHM resolution in the 1D cut by solving the following equations.

An elliptical beam can be expressed as (x/bmaj)**2 + (y/bmin)**2 = 1 with FWHMs along the beam major (bmaj) and minor (bmin) axes, taking the beam major axis to align with x axis. A line toward a position angle theta measured from xaxis to yaxis is y = x*tan(theta)

The crossing point of the beam ellipse and line is the resolution along a cut in the position angle.

Parameters:

pa (float) – Position angle of the cut.

get_coordinates()

Get sky coordinates.

get_mapextent(unit='arcsec')

Get map extent.

get_momentzero_rms(rms_ch, vrange=None)

Calculate expected rms noise of the moment 0 map through the error propagation.

Parameters:
  • rms_ch (float) – rms noise per channel.

  • vrange (list or None) – Integrated velocity range, given as [vmin, vmax].

get_relative_coordinates(coord, frame=None)

Convert a given coordinate to a relative coordinate to the map center.

Parameters:

coord (str) – An absolute coordinate in the same coordinate frame as that of the the image. The format of the coordinate is ‘hh:mm:ss.ss dd:mm:ss.ss’ or ‘hms dms’ if RA-Dec.

getmoments(moments=[0], vrange=[], threshold=[], outfits=True, outname=None, overwrite=False, i_stokes=0)

Calculate moment maps. For moment 1 and 2, error maps are also calculated through the error propagation.

Parameters:
  • moments (list) – Integers of moments to calculate. E.g., [0,1] will calculate moment 0 and 1.

  • vrange (list) – Velocity range to be used for calculating moment maps.

  • threshold (list) – Threshold to clip data, given as [minimum intensity, maximum intensity]

  • outfits (bool) – Save results to a fits file if True

  • outname (str) – Output fits file name if outfits=True.

  • overwrite (bool) – Overwrite an existing fits file if True.

getrms_cube(vwindows=[[]], radius=None, saxis=0, mask=None)

Calculate rms using line free channels.

Parameters:
  • vwindows (list) – Velocity or frequency windows to be excluded. Multiple windows can be specified by nesting list. E.g., [[0, 5], [7, 10]] will exclude 0–5 km/s and 7–10 km/s.

  • radius (float) – Radial threshold in arcsec, within which rms noise will be calculated.

  • saxis (int) – Index of the Stokes axis.

  • mask (ndarray) – Flexible mask, defined with numpy.ndarray. The mask array is supposed to be a bool array in the same shape of data.

read_casa_multibeam(savetype='full', index=0)

Read CASA Multibeam.

Parameters:
  • savetype ({'full', 'average', 'single'}) – How to treat CASA multibeam. All beams as a function of frequency are stored if ‘full’. Beam averaged over frequency is stored if ‘average’. A single beam specified by the index parameter is stored if ‘single’.

  • index (int) – Channel index to specify beam to be stored when savetype = ‘single’.

read_coordinate_frame()
read_header(frame=None, velocity=True, axesorder=(), equinox='J2000', beam_savetype='full', beam_index=0)

Get axes of a FITS image from header.

Parameters:
  • frame (str or None, optional) – Coordinate frame, required if missing in the header.

  • velocity (bool) – Convert frequency to velocity if True.

  • axesorder (tuple, optional) – Order of axes if they need to be reordered. The new axis order is specified using original axis indices. E.g., to swich the 2nd and 4th axes, use (0, 3, 2, 1). Indices start at 0.

  • equinox (str, optional) – Equinox of the coordinate frame; used when the coordinate frame is Jxxxx and the equinox is missing in the header.

  • beam_savetype ({'full', 'average', or 'single'}, optional) – How to treat CASA multi-beam. See the read_casa_multibeam method for more details.

  • beam_index (int) – Index of multi-beam used when beam_savetype = ‘single’. See the read_casa_multibeam method for more details.

read_pvfits(axesorder=())

Read position-velocity FITS header.

Parameters:

axesorder (tuple) – Reorder axes if given. The new axis order is specified using original axis indices. E.g., to swich the 1st and 2nd axes, use (1, 0, 2). Indices start at 0.

reorder_axes(order)

Reorder fits axes.

Parameters:

(tuple) (order) – E.g., in order to swich the 2nd and 4th axes, the input will be (0, 3, 2, 1). The index starts with zero.

sampling(steps: list, units='resolution', keep_center=True)

Resampling data.

Parameters:
  • steps (list) – Sampling steps. E.g., steps = [2,2,4], data are resampled along x and y axes in steps of 2 x units, and along v axis in steps of 4 x units. Units are defined by the units parameter; see below. If you want to resample data only along a particular axis, give sampling steps that are finner than those of original data for other axes.

  • units ('resolution', 'pixel', or 'absolute') – Units of sampling step.

  • keep_center (bool) – Keep map center if True.

search_for_line_detection(threshold, cond_area=0.7, saxis=0, radius=None, output_mode='minmax')

Search for line-detected channels.

Parameters:
  • threshold (float) – Noise threshold, above which the line is defined as detected.

  • cond_area (float) – Area threshold in unit of mean beam size. If the line emission area detected above the noise threshold is smaller than the area threshold, the emission is regarded as noise.

  • saxis (int) – Stokes axis index.

  • radius (float or None) – A radius cutting off outer regions of the image.

  • output_mode ('minmax' or 'full') – Returns all channel indices of emission detected if ‘full’. Returns starting and ending channel indices of emission detected if ‘minmax’. Note that line-detected channels can be discontinuous.

shift_coord_center(coord_center, interpolate=False, zero_center=True)

Shift the coordinate center.

Parameters:
  • coord_center (str) – New map coordinate center, in format of ‘00h00m00.00s 00d00m00.00s’, or ‘hh:mm:ss.ss dd:mm:ss.ss’.

  • regrid (bool) – Interpolate data into an organized grid if True.

  • zero_center (bool) – Set the coordinate center at the central pixel rather the border of two central pixels.

trim_data(xlim: list = [], ylim: list = [], vlim: list = [], slim: list = [])

Trim a cube image. The extent of each axis should be given as [min, max].

Parameters:
  • xlim (list) – Range of x coordinates in arcsec.

  • ylim (list)) – Range of y coordinates in arcsec.

  • vlim (list) – Velocity range in km s^-1, or frequency range in Hz.

  • slim (list) – Stokes range.

update_hdinfo(vunit='freq')

Update header by reading data.

Parameters:

vunit ('velocity' or 'freq') – Dimension of the 3rd axis. Velocity or frequency.

writeout(outname, comment=None, hdkeys=None, overwrite=False, vunit='freq')

Export an image to a fits file. This method has not been tested enough yet. Please use it with causion.

Parameters:
  • outname (str) – Output fits file name.

  • comment (str) – Comment to put in the COMMENT column of the FITS header.

  • hdkeys (dict) – Additional header information to add or modify in the FITS header. It can be given as a dictonary with header keys and their values; e.g., {‘BUNIT’: ‘K’}.

Plotting

class imfits.drawmaps.AstroCanvas(nrow_ncol: tuple = (0, 0), axes_pad: tuple = (0.2, 0.2), fig=None, imagegrid: bool = False, cbar_mode: str = None, cbaroptions=['right', '3%', '0%'], label_mode='1', figsize: tuple = (11.69, 8.27), pltconfig: dict = {'font.size': '12', 'xtick.direction': 'in', 'ytick.direction': 'in'}, projection=None)

Bases: object

A Python class working with Imfits to manage astronomical plots.

Parameters:
  • nrow_ncol (tuple) – Number of rows and columns given as (n_rows, n_columns).

  • axes_pad (tuple) – Padding between each panel given as (horizontal padding, vertical padding), where padding takes from zero to one.

  • fig (matplotlib Figure object, optional) – Will use the given Figure object if given. Otherwise, AstroCanvas will generate a Figure object.

  • imagegrid (bool) – Use ImageGrid of mpl_toolkits if True. This option allows a better spacing between panels.

  • cbar_mode ({'each', 'signle', 'edge'} or None) – Used when imagegrid=True to specify a colorbar mode. ‘each’ puts a color bar aside on each panel, ‘single’ puts a single ecolor bar on the figure, and ‘edge’ puts color bars on panels at the edge of the figure. None will generate no color bar.

  • cbaroptions (list or tuple) – Used when imagegrid=True to setup a colorbar(s). Must be given in a format of [location, width, padding]. The location can be ‘right’, ‘top’, ‘left’, or ‘bottom’. The width and padding can be given as a percentage of the axis width in str; e.g., [‘right’, ‘3%’, ‘3%’].

  • label_mode ({'L', '1', or 'all'}) – Used when imagegrid=True to setup axis labels. ‘L’ puts axis labels on panels at the left and bottom edge of the figure. ‘1’ puts axis labels only on the bottom-left panel. ‘all’ puts axis labels on all panels.

  • figsize (tuple) – Figure size. Default is (11.69, 8.27), which corresponds to A4 landscape.

  • pltconfig (dict) – A dictionary object containting matplotlib rcParams to change the plotting style.

add_axes(nrow, ncol, wspace=None, hspace=None, projection=None)

Add axes to Figure.

Parameters:
  • nrow (int) – Number of rows.

  • ncol (int) – Number of columns.

  • wspace (float) – Horizontal spacing between panels.

  • hspace (float) – Vertical spacing between panels.

  • projection – Projection for plots. It is for future development and currently not used.

add_axis()

Add an axis to Figure.

add_colorbar(cim=None, iaxis=0, cbarlabel: str = '', cbaroptions: list = ['right', '3%', '0%'], ticks: list = None, tickcolor: str = 'k', axiscolor: str = 'k', labelcolor: str = 'k')

Add a color bar to an axis or a grid.

Parameters:
  • cim – Color image as an output of imshow, pcolor or relevant functions of matplotlib.

  • iaxis (int) – Axis index.

  • cbarlabel (str) – Color bar label.

  • cbaroptions (list) – Color bar properties given as [location, width, padding]. Location can be ‘right’, ‘left’, ‘top’, or ‘bottom’. Width and padding can be given as a parcentage of the axis extent. Default is [‘right’, ‘3%’, ‘0%’].

  • ticks (ndarray or None) – Color bar ticks.

  • tickcolor (str) – Tick color.

  • axiscolor (str) – Color bar axis color.

  • labelcolor (str) – Color of the color bar label.

add_grid(nrow, ncol, cbar_mode=None, axes_pad=(0.0, 0.0), share_all=True, cbaroptions=['right', '3%', '0%'], label_mode='1')

Generate grid (i.e., axes) using ImageGrid of matplotlib. For more detail of ImageGrid, check https://matplotlib.org/stable/api/_as_gen/mpl_toolkits.axes_grid1.axes_grid.ImageGrid.html.

Parameters:
  • nrow (int) – Number of rows

  • ncol (int) – Number of columns

  • axes_pad (tuple or float) – Padding between axes. If tuple is given, it will be treated as (vertical, horizontal) padding.

  • share_all (bool) – Whether all axes share their x- and y-axis or not.

  • cbar_mode ({'each', 'signle', 'edge'} or None) – Colorbar mode. ‘each’ puts a color bar aside on each panel, ‘single’ puts a single ecolor bar on the figure, and ‘edge’ puts color bars on panels at the edge of the figure. None will generate no color bar.

ax_corner(loc='lower left')

Return an axis at the figure corner.

Parameters:

loc ({'lower left', 'lower right', 'upper right', 'upper left'}) – The location of the corner to extract.

channelmaps(image, imscale=[], data=None, color=True, cmap='PuBuGn', vmin=None, vmax=None, contour=True, clevels=[], ccolor='k', clw=0.5, nrow=5, ncol=5, velmin=None, velmax=None, nskip=1, color_norm=None, xticks=[], yticks=[], vsys=None, scalebar=[], ccross=True, prop_cross=[None, 1.0, 'k'], plot_beam=True, bcolor='k', coord_center=None, vlabel_on=True, txtcolor='k', colorbar=True, cbarlabel='', cbarticks=None, alpha=1.0, plotall=False, outname=None, absolutecoords=False)

Draw channel maps.

Parameters:
  • image (Imfits object) – Input image in the Imfits object.

  • imscale (list) – Image extent to show. It must be given as [xmin, xmax, ymin, ymax] in unit of arcsec.

  • data (ndarray or None) – Plot given data instead of the input Imfits image if given. Other map information such as map extent is taken from the input Imfits image.

  • color (bool) – Show the image in color scale if True. Default is False.

  • cmap (str) – color of the colorscale.

  • vmin (float or None) – Minimum value of the color scale. Default is the minimum value of the data.

  • vmax (float or None) – Maximum value of the color scale. Default is the maximum value of the data.

  • contour (bool) – Show the image with contours if True. Default is True.

  • clevels (ndarray or None) – Contour levels. Default is 0.2, 0.4, 0.6, and 0.8 times the maximum value of the data.

  • ccolor (str) – Contour color.

  • clw (float) – Contour widths.

  • nrow (int) – Number of rows, required if no axes were added in AstroCanvas.

  • ncol (int) – Number of columns, required if no axes were added in AstroCanvas.

  • velmin (float) – Minimum velocity to show.

  • velmax (float) – Maximum velocity to show.

  • nskip (int) – Steps to skip and show channels.

  • color_norm (str or tuple) – Color-scale normalization. Default is linear. Supported formats are currently ‘log’, (‘asinhstretch’, a), or (func, func_inverse), where func and func_inverse are arbitoral functions which determine the colorscale. For the last option, refer mpl.colors.FuncNorm for more details. When using ‘asinhstretch’, a is a float value to specify the color strech.

  • xticks (list) – Ticks for x axis.

  • yticks (list) – Ticks for y axis.

  • vsys (float or None) – Systemic velicity in km/s. If given, velocities will be labeled in the relative velocity with respect to the systemic velocity rather than in LSRK.

  • scalebar (list) – Add scale bar if given. Can be given as either of two formats; [barlength, bartext, loc, barcolor, fontsize] or [barx, bary, barlength, textx, texty, bartext, barcolor, fontsize]. See drawmaps.add_scalebar for more details.

  • ccross (bool) – Plot a cross at the map center if True.

  • prop_cross (list) – Property of the central cross give as [length, width, color], where length and width are in the same units as those of the x- and y-axis. E.g., [2., 2., ‘k’].

  • plot_beam (bool) – Plot observing beam if True.

  • bcolor (str) – Color of the beam.

  • coord_center (str) – New map center given as’00h00m00.00s 00d00m00.00s’, or ‘hh:mm:ss.ss dd:mm:ss.ss’ assuming RA DEC.

  • vlabel_on (bool) – Show velocity of each channel if True.

  • txtcolor (str) – Velocity label color.

  • colorbar (bool) – Show color bar if True.

  • cbarlabel (str) – Color bar label.

  • cbarticks (ndarray) – Color bar ticks.

  • alpha (float) – Transparency alpha for color plot.

  • plotall (bool) – Plot all channels by seperating output files if True. Default is False.

  • outname (str) – An output file name used to save the figure. The figure will be saved with the name when plotall = True.

  • absolutecoords (bool) – Make plots with absolute coordinates if True. This option is not fully supported, and may result in weired plot axes.

intensitymap(image, imscale=[], color=True, cmap='PuBuGn', colorbar=True, cbarlabel=None, cbaroptions=array(['right', '3%', '0%'], dtype='<U5'), vmin=None, vmax=None, color_norm=None, contour=False, clevels=None, ccolor='k', clw=1, xticks=[], yticks=[], absolutecoords=False, scalebar=[], plot_beam=True, bcolor='k', ccross=True, prop_cross=[None, 1.0, 'k'], coord_center=None, aspect=1, interpolation=None, exact_coord=False, iaxis=0, saxis=0, vaxis=0, inmode=None, data=None, outname=None, transparent=True, color_alpha=1)

Draw the intensity map.

Parameters:
  • image (Imfits object) – Input image give as an Imfits object.

  • iaxis (int) – Index of the axis, on which the intensity map will be plotted.

  • imscale (list) – Extent of the map to show, given as [xmin, xmax, ymin, ymax].

  • color (bool) – If plot in color or not.

  • cmap (str, Matplotlib color map code) – Map color code.

  • colorbar (bool) – If plot the color bar or not.

  • cbaroptions (list) – Setting for the color bar, give as [location, width, pad]. The location can be ‘top’, ‘right’, ‘bottom’, or ‘left’. The width and padding can be specified by parcentage of the extent of the plot. E.g., [‘top’, ‘3%’, ‘3%’].

  • vmin (float) – Minimun value of the color scale.

  • vmax (float) – Maximun value of the color scale.

  • contour (bool) – If plot the image with contours or not.

  • clevels (ndarray) – Contour levels, give in absolute values.

  • ccolor (str) – Contour color.

  • clw (float) – Contour widths.

  • color_norm (str or tuple) – Color-scale normalization. Default is linear. Supported formats are currently ‘log’, (‘asinhstretch’, a), or (func, func_inverse), where func and func_inverse are arbitoral functions which determine the colorscale. For the last option, refer mpl.colors.FuncNorm for more details. When using ‘asinhstretch’, a is a float value to specify the color strech.

  • vaxis (int) – Index of the 3rd (typically velocity) axis, if the input image is in more than two dimensions.

  • saxis (int) – Index of the 4th (typically stokes) axis, if the input image is in more than three dimension.

  • xticks (list) – Ticks for x axis.

  • yticks (list) – Ticks for y axis.

  • absolutecoords (bool) – Make plots with absolute coordinates if True. This option is not fully supported, and may result in weired plot axes.

  • scalebar (list) – Add scale bar if given. Must be given as [] or [].

  • plot_beam (bool) – Plot observing beam if True.

  • bcolor (str) – Color of the beam.

  • ccross (bool) – Plot a cross at the map center if True.

  • prop_cross (list) – Property of the central cross give as [length, width, color], where length and width are in the same units as those of the x- and y-axis. E.g., [2., 2., ‘k’].

  • coord_center (str) – New coordinate center, given as ‘00h00m00.00s +00d00m00.00s’.

  • aspect (float) – Aspect ratio of the axis.

  • interpolation (str) – Interpolation style for the color plot.

  • exact_coord (bool) – pcolor is used rather than imshow if True. Better to use when grid spacing of the input image is not uniform.

  • inmode (str) – If ‘data’, then ndarray given by the data parameter will be used for plot while other info like the map extent is taken from the input image.

  • data (ndarray) – Data to plot instead of the input Imfits image.

  • outname (str) – An output file name used to save the figure. The figure will be saved with the name if given.

  • transparent (bool) – If make the figure background transparent or not.

plot_vectors(image, iaxis=0, norm=1.0, pivot='mid', headwidth=1.0, headlength=0.001, width=0.01, color='red')

Plot polarization (or B-field) vectors attached with the image.

pvdiagram(image, color=True, cmap='PuBuGn', color_norm=None, vmin=None, vmax=None, contour=True, clevels=None, ccolor='k', lw=1, pa=None, vsys=None, vrel=False, x_offset=False, ratio=1.2, clip=None, plot_res=True, xlim=[], ylim=[], ln_hor=True, ln_var=True, alpha=None, colorbar=False, cbaroptions=('right', '3%', '0%'), cbarlabel='(Jy beam$^{-1}$)', iaxis=0, inmode=None, data=None, outname=None, transparent=True)

Draw a PV diagram.

Parameters:
  • image (Imfits object) – Input image in the Imfits object.

  • color (bool) – Show the image in color scale if True. Default is False.

  • cmap (str) – color of the colorscale.

  • color_norm (str or tuple) – Color-scale normalization. Default is linear. Supported formats are currently ‘log’, (‘asinhstretch’, a), or (func, func_inverse), where func and func_inverse are arbitoral functions which determine the colorscale. For the last option, refer mpl.colors.FuncNorm for more details. When using ‘asinhstretch’, a is a float value to specify the color strech.

  • vmin (float or None) – Minimum value of the color scale. Default is the minimum value of the data.

  • vmax (float or None) – Maximum value of the color scale. Default is the maximum value of the data.

  • contour (bool) – Show the image with contours if True. Default is True.

  • clevels (ndarray or None) – Contour levels. Default is 0.2, 0.4, 0.6, and 0.8 times the maximum value of the data.

  • ccolor (str) – Contour color.

  • lw (float) – Contour widths.

  • pa (float) – Position angle of the PV cut, used to calculate 1D beam FWHM along the cut if given.

  • vrel (bool) – Show velocity in the relative velocity to the systemic velocity rather than LSR velocity if True.

  • vsys (float or None) – Systemic velicity in km/s. Used if vrel = True.

  • x_offset (bool) – Set offset to x axis, and velocity to y axis if True. Default is False, which sets offset to y axis.

  • ratio (float) – Aspect ratio of the axis.

  • clip (float or None) – Clip data having values below the ‘clip’ value.

  • plot_res (bool) – Plot spatial and velocity resolutions if True.

  • xlim (list) – x range for the plot.

  • ylim (list) – y range for the plot.

  • ln_hor (bool) – Plot horizontal line to show y=0 or vsys.

  • ln_var (bool) – Plot vertical line to show x=0 or vsys.

  • alpha (float) – Transparency alpha for color plot.

  • colorbar (bool) – Show color bar if True.

  • cbaroptions (list or tuple) – Color bar setting given as (location, width, padding).

  • cbarlabel (str) – Color bar label.

  • iaxis (int) – Axis index for plot.

  • inmode (str) – If ‘data’, then ndarray given by the data parameter will be used for plot while other info like the map extent is taken from the input image.

  • data (ndarray) – Data to plot instead of the input Imfits image.

  • outname (str) – An output file name used to save the figure. The figure will be saved with the name if given.

  • transparent (bool) – Make the figure background transparent if True.

reset_axes()

Remove all existing axes.

rgb_plot(image_r=None, image_g=None, image_b=None, reference='R', normalize=True, weight_rgb=(1.0, 1.0, 1), iaxis=0, stretch=0.5, scalebar=None)

Make RGB plot. It wraps astropy.visualization.make_lupton_rgb.

Parameters:
  • image_r (Imfits object or None) – Red image.

  • image_g (Imfits object or None) – Green image.

  • image_b (Imfits object or None) – Blue image.

  • reference ({'R', 'G', 'B'}) – Reference image to scale other images.

  • normalization (bool) – Normalize each image with the intensity peak if True.

  • weight_rgb (tuple) – Weight of each color. Must be given as (weight_for_red, weight_for_green, weight_for_blue), where each weight takes a float value from zero to one.

  • iaxis (int) – Axis index.

  • stretch (float) – The linear stretch of the image.

  • scalebar (list) – Scale bar options. See add_scalebar for more details.

savefig(outname: str, ext: str = 'pdf', transparent: bool = True, dpi=None)

Save figure.

Parameters:
  • outname (str) – Output file name.

  • ext (str) – Extension of the output file; png, pdf, etc.

  • transparent (bool) – If make background transparent or not.

  • dpi (float) – dpi resolution.

style(config)

Update plot style with matplotlib.pyplot.rcParams.

imfits.drawmaps

imfits.drawmaps.add_beam(ax, bmaj: float, bmin: float, bpa: float, bcolor: str = 'k', loc: str = 'bottom left', alpha: float = 1.0, zorder: float = 10.0, fill=True, ls='-')

Add a beam ellipse to a plot.

Parameters:
  • ax (Matploltlib Axis) – A matplotlib axis on which make a plot.

  • bmaj (float) – Beam major FWHM.

  • bmin (float) – Beam minor FWHM.

  • bpa (float) – Beam position angle in degree.

  • bcolor (str) – Beam color.

  • loc (str or tuple) – Location of the beam. Can be ‘bottom left’, ‘bottom right’, ‘top left’, ‘top right’, or (x, y). x and y take values between 0 and 1, where 0 corresponds to the most left or bottom, and 1 corresponds to the most right or top.

  • alpha (float) – Transparency.

  • zorder (float) – z order.

  • fill (bool) – If True, plot the beam with a filled ellipse; otherwise plot with an open ellipse. Default is True.

  • ls (str) – Line style.

imfits.drawmaps.add_box(ax, xc, yc, xl, yl, width=1.0, color='k', zorder=10.0, ls='--', angle=0.0)

Add a box in a plot.

Parameters:
  • ax (Matploltlib Axis) – A matplotlib axis on which make a plot.

  • xc (float) – x coordinate of the box center.

  • yc (float) – y coordinate of the box center.

  • xl (float) – x length of the box.

  • yl (float) – y length of the box.

  • width (float) – Line width.

  • color (str) – Line color.

  • ls (str) – Line style.

  • zorder (float) – zorder.

  • angle (float) – Rotation angle of the box in degree.

imfits.drawmaps.add_colorbar_toaxis(ax, cim=None, loc='right', pad='3%', width='3%', length='100%', cbaroptions: list = None, cbarlabel='', ticks: list = None, fontsize: float = None, tickcolor: str = 'k', labelcolor: str = 'k')

Add a colorbar to axis.

Parameters:
  • loc ({'right', 'left', 'top', 'bottom'}) – Location of the colorbar.

  • pad (str or float) – Pad between the axis and colorbar given as percentage (e.g., ‘3%’) or fraction (e.g, 0.03) of the full plot width.

  • width (str or float) – Width of the colorbar given as percentage or fraction of the full plot width.

  • length (str or float) – Length of the colorbar given as percentage or fraction of the full plot width.

  • cbaroptions (list) – Color bar options given as [loc, pad, width], which set location, pad, and width all at once. If given, the loc, pad and width parameters are ignored.

  • ticks (list or ndarray, optional) – Colorbar ticks.

  • fontsize (float, optional) – Font size of the colorbar and tick labels.

  • tickcolor (str) – Tick color.

  • labelcolor (str) – Label color.

imfits.drawmaps.add_colorbar_togrid(cim, grid, cbarlabel: str = '', tickcolor: str = 'k', axiscolor: str = 'k', labelcolor: str = 'k', cbar_loc='right')

Add color bar to ImageGrid.

imfits.drawmaps.add_cross(ax, loc=(0, 0), length=None, width=1.0, color='k', zorder=10.0)

Add a cross in a plot.

Parameters:
  • ax (Matploltlib Axis) – A matplotlib axis on which make a plot.

  • loc (tuple or list) – (x, y) coordinates of the cross position.

  • length (float) – Line length.

  • width (float) – Line width.

  • color (str) – Color of the cross.

  • zorder (float) – zorder.

imfits.drawmaps.add_line(ax, length=None, pa=0.0, cent=(0, 0), width=1.0, color='k', ls='-', alpha=1.0, zorder=10.0)

Add a line in a plot, sets by the central position, lenght and position angle.

Parameters:
  • ax (Matploltlib Axis) – A matplotlib axis on which make a plot.

  • length (float) – Line length.

  • pa (float) – Position angle of the line, measured from north toward east.

  • cent (tuple) – Central position of the line given as (x,y).

  • width (float) – Line width.

  • color (str) – Line color.

  • ls (str) – Line style.

  • alpha (float) – Line transparency.

  • zorder (float) – zorder.

imfits.drawmaps.add_scalebar(ax, scalebar: list, orientation='horizontal', loc: str = 'bottom right', barcolor: str = 'k', fontsize: float = 11.0, lw: float = 2.0, zorder: float = 10.0, alpha: float = 1.0)

Add a scale bar to an axis.

Parameters:
  • ax (matplotlib Axis object) – Matplotlib Axis object.

  • scalebar (list) – Properties of the scale bar. It can be given as either of two formats; [barlength, bartext, loc, barcolor, fontsize] or [barx, bary, barlength, textx, texty, bartext, barcolor, fontsize]. barlength is the length of the scaler bar, and bartext is the scaler bar label. loc is the location of the scale bar; it can be ‘bottom left’, ‘bottom right’, ‘top left’, ‘top right’, or a list of [(bar_xloc, bar_yloc), (text_xloc, text_yloc)]. xxx_xloc/xxx_yloc takes a value from zero to one, which corresponds to left/bottom and right/top of the axis, respectively. barcolor is the color of the scaler bar and text. fontsize is the font size for the label. For the second option, barx and bary are exact coordinates of the scaler bar, and textx and texty are exact coordiantes of the scale bar label.

  • orientation ({'horizontal', 'vertical'}) – Orientation of the scale bar.

  • lw (float) – Bar width.

  • zorder (float) – z order.

  • alpha (float) – Transparency.

imfits.drawmaps.add_sources(ax, image, coords, length=None, width=1.0, color='k', zorder=10.0, frame='icrs', unit=(Unit('h'), Unit('deg')), equinox='J2000')

Add crosses indicating source positions in a plot. The positions are supposed to be given in absolute coordinates.

Parameters:
  • ax (Matploltlib Axis) – A matplotlib axis on which make a plot.

  • image (Imfits object) – An Imfits image, from which the map center is read.

  • coords (str or list) – Coordinates to indicate with crosses, given as ‘x y’. E.g., ‘hh:mm:ss.ss dd:mm:ss.ss’ if RA-Dec.

  • length (float) – Line length of the crosses.

  • width (float) – Width of the crosses.

  • color (str) – Color of the crosses.

  • zorder (float) – zorder.

  • frame (str) – Coordinate frame.

  • unit (tuple) – Units of (x,y) coordinates given as astropy units.

  • equinox (str) – Equinox if required.

imfits.drawmaps.add_vectors(image, ax, norm=1.0, pivot='mid', headwidth=1.0, headlength=0.001, width=0.01, color='red')

Add vectors on a plot.

Parameters:
  • image (Imfits object) – An Imfits image with vectors attached.

  • ax (Matploltlib Axis) – A matplotlib axis on which make a plot.

imfits.drawmaps.change_aspect_ratio(ax, ratio, plottype='linear')

Change aspect ratio of an axis.

Parameters:
  • ax (matplotlib Axes object) – Matplotlib axis.

  • ratio (float or int) – Relative x width compared to y width.

  • plottype ({'linear', 'loglog', 'linearlog', 'loglinear'}) – Scale of x and y axes.

imfits.drawmaps.generate_grid(nrow, ncol, axes_pad=(0.2, 0.2), figsize=(11.69, 8.27), share_all=True, cbar_mode=None, cbaroptions=['right', '3%', '0%'], label_mode='1')

Generate grid using ImageGrid of matplotlib. For more detail of the function, check https://matplotlib.org/stable/api/_as_gen/mpl_toolkits.axes_grid1.axes_grid.ImageGrid.html.

Parameters:
  • nrow (int) – Number of rows.

  • ncol (int) – Number of columns.

  • axes_pad (tuple or float) – Padding between axes. If given as tuple, it will be treated as (vertical, horizontal) padding.

  • figsize (tuple) – Figure size. Default is (11.69, 8.27), corresponding to A4 landscape.

  • share_all (bool) – If all axes share their x- and y-axis or not.

  • cbar_mode ({'each', 'signle', 'edge'} or None) – Used when imagegrid=True to specify a colorbar mode. ‘each’ puts a color bar aside on each panel, ‘single’ puts a single ecolor bar on the figure, and ‘edge’ puts color bars on panels at the edge of the figure. None will generate no color bar.

  • cbaroptions (list or tuple) – Used when imagegrid=True to setup a colorbar(s). Must be given in a format of [location, width, padding]. The location can be ‘right’, ‘top’, ‘left’, or ‘bottom’. The width and padding can be given as a percentage of the axis width in str; e.g., [‘right’, ‘3%’, ‘3%’].

  • label_mode ({'L', '1', or 'all'}) – Used when imagegrid=True to setup axis labels. ‘L’ puts axis labels on panels at the left and bottom edge of the figure. ‘1’ puts axis labels only on the bottom-left panel. ‘all’ puts axis labels on all panels.

Returns:

grid

Return type:

ImageGrid

Utils

imfits.au

Analysis utilities for Imfits objects.

imfits.au.gaussian_cube_fit(image, rms, sampling='Nyquist', isaxis=0, save_as_fits=False, outname=None, overwrite=True, nthr=3)

Fit cube with a Gaussian line profile function pixel by pixel. The definision of the line width is the Doppler line width rather than sigma of Gaussian.

Parameters:
  • image (Imfits object) – Input cube image.

  • rms (float) – rms noise of the cube.

  • sampling (list) – Sampling steps in unit of beam.

  • isaxis (int, optional) – Index of the stokes axis.

  • save_as_fits (bool) – Save the fitting results as fits files.

  • outname (str) – Output file name that is used when save_as_fits = True. Should include ‘.fits’.

  • ovwerwrite (bool) – Overwrite fits files when fits files with outname exist.

  • nthr (int) – Minimum number of data above three sigma. Fitting will be skipped if n_data (>3sigma) <= nthr.

Returns:

pfit, e_pfit – The optimized parameters and their fitting errors as 3D array in a shape of (3, ny, nx), where nx and ny are lengths of x and y axes of the input cube. The first axis is amplitude, centroid velocity and line width from start to end.

Return type:

ndarray

imfits.au.get_1Dprofile(image, pa, average_side=False)

Get one dimensional profile in a orientation at a position angle.

Parameters:
  • image (Imfits object) – Input image

  • pa (float) – Position angle for the 1D cut.

  • average_sides (bool) – Take an average of profiles on positive and negative sides, or not.

Returns:

  • x (ndarray) – x coordinates.

  • y (ndarray) – Extracted 1D profile.

imfits.au.getflux(image, rms=None, aptype='circle', r=None, semimaj=None, semimin=None, pa=None, istokes=0, ivelocity=0, inmode_data=False, dx=None, dy=None, beam=None, xx=None, yy=None)

Get flux from an image.

Parameters:
  • image (Imfits object or ndarray) – Input image.

  • rms (float) – rms noise level of the image.

  • aptype ({'circle', 'ellipse', 'none'}) – Aperture type within which the flux is measured.

  • r (float) – Radius of the circuler aperture in arcsec.

  • semimaj (float) – Semi-major axis of the elliptical aperture in arcsec.

  • semimin (float) – Semi-minor axis of the elliptical aperture in arcsec.

  • pa (float) – Position angle of the elliptical aperture in degree, measured from north toward east.

  • inmode_data (bool) – If True, the input image is recognized as ndarray. Default False.

  • istokes (int, optional) – Index of the stokes axis.

  • ivelocity (int, optional) – Index of the velocity axis.

  • dx (float, optional) – Pixel x size, required if inmode_data = True

  • dy (float, optional) – Pixel y size, required if inmode_data = True

  • beam (list, optional) – [bmaj, bmin, bpa], required if inmode_data = True

  • xx (ndarray, optional) – x coordinates 2D array, required if inmode_data = True

  • yy (ndarray, optional) – y coordinates 2D array, required if inmode_data = True

Returns:

  • flux (float) – Flux.

  • e_flux (float, optional) – Error of the flux, computed through the error propagation if rms is given.

imfits.au.imrotate(image, angle=0)

Rotate the input image

Parameters:
  • image (Imfits object) – Input image.

  • angle (float) – Rotational Angle in deg. Anti-clockwise direction will be positive (same as the position angle).

Return type:

Rotated image as N dimensional ndarray, where N is the dimension of the input image.

imfits.au.match_images(image, ref_image)

Regrid an image so that it matches the reference image grid.

Parameters:
  • image (Imfits object) – Image to regrid.

  • ref_image (Imfits object) – Reference image.

Return type:

N dimensional data array, where N is the dimension of the input data.

imfits.au.radial_profile(image, rms=None, pa=None, inc=None, step='Nyquist', return_all=False, npa=361, pa_min=-180.0, pa_max=180.0, error_type='stat', istokes=None, ivelocity=None)

Calculate an azimuthally-averaged radial profile from an input image. Sky deprojection can be applied assuming a thin disk if position and inclination angles are given.

Parameters:
  • image (Imfits object) – Input image.

  • rms (float) – Image rms noise.

  • pa (float, optional) – Position angle of the object. Used to deproject image.

  • inc (float, optional) – Inclination angle of the object. Used to deproject image.

  • step (str or int) – Sampling step in unit of pixel. Default is Nyquist sampling.

  • return_all (bool) – Return full results if true.

  • npa (int) – Number of bins along the azimuthal direction. Default 361, meaning 1 deg steps.

  • pa_min (float, optional) – Minimum and maximum position angles, over which an azimuthal average is taken. Default is -180 deg to 180 deg, covering 360 deg.

  • pa_max (float, optional) – Minimum and maximum position angles, over which an azimuthal average is taken. Default is -180 deg to 180 deg, covering 360 deg.

  • error_type ({'stat', 'var'}) – Type of output error; statistical error (‘stat’) calculated with rms and error propagation, or root variance (‘var’) over azimuthal angles. If error_type = stat, rms must be provided.

  • istokes (int, optional) – Index of the stokes axis.

  • ivelocity (int, optional) – Index of the velocity axis.

Returns:

  • r (ndarray) – Radial coordinates

  • pa (ndarray, optional) – Position angles. Output only if return_all = True.

  • cslice (ndarray, optional) – 2D data mapped to radial-PA plane. Output only if return_all = True.

  • w_e (ndarray, optional) – Weightings to account for oversampling. Output only if return_all = True.

  • prof (ndarray) – Azimuthally-averaged radial profile.

  • e_prof (ndarray) – Error of the radia profile.

imfits.au.sky_deprojection(image, pa, inc, inmode_data=False, xx=[], yy=[], method='linear', conserve_flux=True, istokes=None, ivelocity=None)

Deproject image assuming a thin disk.

Parameters:
  • image (Imfits object) – Input image.

  • pa (float, optional) – Position angle of the object. Used to deproject image.

  • inc (float, optional) – Inclination angle of the object. Used to deproject image.

  • inmode_data (bool) – If True, the input image is recognized as ndarray. Default False.

  • xx (ndarray, optional) – x coordinates 2D array, required if inmode_data = True.

  • yy (ndarray, optional) – y coordinates 2D array, required if inmode_data = True.

  • method (str) – Interpolation method.

  • conserve_flux (bool) – Intensity is rescaled for conserving flux if True. Default is True. For conserving the intensity scale, set it to Fales.

  • istokes (int, optional) – Index of the stokes axis.

  • ivelocity (int, optional) – Index of the velocity axis.

Return type:

Deprojected image as ndarray.