carta package
carta.backend module
This module provides a backend object which corresponds to a CARTA backend process. It is used by the wrapper to manage a local or remote backend process directly when creating a headless browser session.
- class carta.backend.Backend(params, executable_path='carta', remote_host=None, token=None, frontend_url_timeout=10, session_creation_timeout=0)
Bases:
object
Helper class for managing a CARTA backend process.
You should not need to instantiate this directly; it is created on demand by a
carta.browser.Browser
object.- Parameters:
params (iterable) – Parameters to pass to the CARTA backend process. Example:
["--verbosity", 5, "--port", 3010]
executable_path (string) – The path to the backend executable. Default:
"carta"
.remote_host (string) – If this is set, an attempt will be made to start the backend over
ssh
on this host.token (
carta.token.BackendToken
) – If this is set, this will be used as the security token and no attempt will be made to parse the token from the backend output.frontend_url_timeout (integer) – How long to keep checking the output for the frontend URL. Default: 10 seconds.
session_creation_timeout (integer) – How long to keep checking the output for a default session ID. If this is set to zero (which is the default), no attempt is made to parse a session ID from the output. The calling function should set this to a non-zero value if parsing the session ID is required.
- Variables:
proc (
subprocess.Popen
) – The backend subprocess object. Set by thecarta.backend.Backend.start
method.frontend_url (string) – The URL of the running frontend, parsed from the output of the backend process. Set by the
carta.backend.Backend.start
method.token (
carta.token.BackendToken
) – The security token of the running backend, either parsed from the output of the backend process and set by thecarta.backend.Backend.start
method, or overridden with a parameter.debug_no_auth (boolean) – If this is set, the backend will accept HTTP connections with no authentication token. This is provided for debugging purposes only and should not be used under normal circumstances. This value is automatically detected from the provided backend parameters.
output (list of strings) – All output of the backend process, split into lines, terminated by newline characters.
errors (list of strings) – Error output of the backend process, split into lines, terminated by newline characters.
last_session_id (integer) – The ID of the last session connected to this backend process, parsed from the process output. This is likely to be the default session automatically created in the user’s browser on startup, if this functionality was not suppressed with the
--no_browser
flag. This value is used by thecarta.session.Session.start_and_interact
method, which connects to this default session. It is not used by the session creation methods which use a wrapper-controlled headless browser, as those parse the session ID from the browser session.frontend_url_timeout (integer) – How long to keep checking the output for the frontend URL.
session_creation_timeout (integer) – How long to keep checking the output for a default session ID. If this is set to zero, no attempt is made to parse a session ID from the output.
- Returns:
A backend object with a process which has not been started.
- Return type:
- FRONTEND_URL = re.compile('CARTA is accessible at (http://.*?:\\d+/\\?token=(.*))')
- FRONTEND_URL_NO_AUTH = re.compile('CARTA is accessible at (http://(.*?):\\d+.*)')
- SESSION_ID = re.compile('Session (\\d+) \\[[\\d.]+\\] Connected.')
- start()
Start the backend process.
This method creates the subprocess object and parses the backend host and the frontend URL from the process output.
- stop()
Stop the backend process.
This method terminates the backend process if it exists and is running.
carta.browser module
This module provides browser objects which can be used to create new sessions. It depends on the selenium
library. The desired browser and its corresponding web driver also have to be installed.
- class carta.browser.Browser(driver_class, **kwargs)
Bases:
object
The top-level browser class.
Some common use cases are provided as subclasses, but you may instantiate this class directly to create a browser with custom configuration.
- Parameters:
driver_class (a selenium web driver class) – The class to use for the browser driver.
**kwargs – Keyword arguments which will be passed to the driver class constructor.
- Variables:
driver (
selenium.webdriver.remote.webdriver.WebDriver
) – The browser driver.
- close()
Shut down the browser driver.
- exit(msg)
Exit the browser with an error.
- new_session_from_url(frontend_url, token=None, backend=None, timeout=10, debug_no_auth=False)
Create a new session by connecting to an existing backend.
You can use
carta.session.Session.create
, which wraps this method.- Parameters:
frontend_url (string) – The URL of the frontend.
token (
carta.token.Token
, optional) – The security token used by the CARTA instance. May be omitted if the URL contains a token.backend (
carta.backend.Backend
) – The backend object associated with this session, if any. This is set if this method is called fromcarta.browser.Browser.new_session_with_backend
.timeout (number, optional) – The number of seconds to spend parsing the frontend for connection information. 10 seconds by default.
debug_no_auth (boolean) – Disable authentication. This should be set if the backend has been started with the
--debug_no_auth
option. This is provided for debugging purposes only and should not be used under normal circumstances.
- Returns:
A session object connected to a new frontend session running in this browser.
- Return type:
- Raises:
CartaBadToken – If an invalid token was provided.
CartaBadUrl – If an invalid URL was provided.
CartaBadSession – If the session object could not be created.
- new_session_with_backend(executable_path='carta', remote_host=None, params=(), timeout=10, token=None, frontend_url_timeout=10)
Create a new session after launching a new backend process.
You can use
carta.session.Session.start_and_create
, which wraps this method. This method starts a backend process, parses the frontend URL from the output, and callscarta.browser.Browser.new_session_from_url
.- Parameters:
executable_path (string, optional) – A custom path to the CARTA backend executable. The default is
"carta"
.remote_host (string, optional) – A remote host where the backend process should be launched, which must be accessible through passwordless ssh. By default the backend process is launched on the local host.
params (iterable, optional) – Additional parameters to be passed to the backend process. By default scripting is enabled and the automatic browser is disabled. The parameters are appended to the end of the command, so a positional parameter for a data directory can be included. Example:
["--verbosity", 5, "--port", 3010]
timeout (number, optional) – The number of seconds to spend parsing the frontend for connection information. 10 seconds by default.
token (
carta.token.BackendToken
, optional) – The security token to use. Parsed from the backend output by default.frontend_url_timeout (integer) – How long to keep checking the backend output for the frontend URL. Default: 10 seconds.
- Returns:
A session object connected to a new frontend session running in this browser.
- Return type:
- Raises:
CartaBadToken – If an invalid token was provided.
CartaBadUrl – If an invalid URL was provided.
CartaBadSession – If the session object could not be created.
- class carta.browser.Chrome(headless=True, browser_path=None, driver_path=None, options=())
Bases:
Browser
Chrome or Chromium, optionally headless.
- Parameters:
headless (boolean, optional) – Run the browser headless (this is the default).
browser_path (string, optional) – A path to a custom chrome or chromium executable.
driver_path (string, optional) – A path to a custom chromedriver executable.
options (iterable, optional) – Additional options. A list of strings, one per option (
--option
or--option=argument
).
carta.constants module
This module provides a collection of enums corresponding to various enumerated types and other literal lists of options defined in the frontend. The members of these enums should be used in place of literal strings and numbers to represent these values; for example: Colormap.VIRIDIS
rather than "viridis"
.
- class carta.constants.Auto(value, names=None, *, module=None, qualname=None, type=None, start=1, boundary=None)
Bases:
StrEnum
Special value for parameters to be calculated automatically.
- AUTO = 'Auto'
- class carta.constants.BeamType(value, names=None, *, module=None, qualname=None, type=None, start=1, boundary=None)
Bases:
StrEnum
Beam types.
- OPEN = 'Open'
- SOLID = 'Solid'
- class carta.constants.Colormap(value, names=None, *, module=None, qualname=None, type=None, start=1, boundary=None)
Bases:
StrEnum
All available colormaps.
- ACCENT = 'accent'
- AFMHOT = 'afmhot'
- AUTUMN = 'autumn'
- BINARY = 'binary'
- BLUES = 'Blues'
- BONE = 'bone'
- BRBG = 'BrBG'
- BRG = 'brg'
- BUGN = 'BuGn'
- BUPU = 'BuPu'
- BWR = 'bwr'
- CMRMAP = 'CMRmap'
- COOL = 'cool'
- COOLWARM = 'coolwarm'
- COPPER = 'copper'
- CUBEHELIX = 'cubehelix'
- DARK2 = 'dark2'
- FLAG = 'flag'
- GIST_EARTH = 'gist_earth'
- GIST_GRAY = 'gist_gray'
- GIST_HEAT = 'gist_heat'
- GIST_NCAR = 'gist_ncar'
- GIST_RAINBOW = 'gist_rainbow'
- GIST_STERN = 'gist_stern'
- GIST_YARG = 'gist_yarg'
- GNBU = 'GnBu'
- GNUPLOT = 'gnuplot'
- GNUPLOT2 = 'gnuplot2'
- GRAY = 'gray'
- GREENS = 'greens'
- GREYS = 'greys'
- HOT = 'hot'
- HSV = 'hsv'
- INFERNO = 'inferno'
- JET = 'jet'
- MAGMA = 'magma'
- NIPY_SPECTRAL = 'nipy_spectral'
- OCEAN = 'ocean'
- ORANGES = 'oranges'
- ORRD = 'OrRd'
- PAIRED = 'paired'
- PASTEL1 = 'pastel1'
- PASTEL2 = 'pastel2'
- PINK = 'pink'
- PIYG = 'PiYG'
- PLASMA = 'plasma'
- PRGN = 'PRGn'
- PRISM = 'prism'
- PUBU = 'PuBu'
- PUBUGN = 'PuBuGn'
- PUOR = 'PuOr'
- PURD = 'PuRd'
- PURPLES = 'purples'
- RAINBOW = 'rainbow'
- RDBU = 'RdBu'
- RDGY = 'RdGy'
- RDPU = 'RdPu'
- RDYLBU = 'RdYlBu'
- RDYLGN = 'RdYlGn'
- REDS = 'reds'
- SEISMIC = 'seismic'
- SET1 = 'set1'
- SET2 = 'set2'
- SET3 = 'set3'
- SPECTRAL = 'spectral'
- SPRING = 'spring'
- SUMMER = 'summer'
- TAB10 = 'tab10'
- TAB20 = 'tab20'
- TAB20B = 'tab20b'
- TAB20C = 'tab20c'
- TERRAIN = 'terrain'
- VIRIDIS = 'viridis'
- WINTER = 'winter'
- WISTIA = 'Wistia'
- YLGN = 'YlGn'
- YLGNBU = 'YlGnBu'
- YLORBR = 'YlOrBr'
- YLORRD = 'YlOrRd'
- class carta.constants.ComplexComponent(value, names=None, *, module=None, qualname=None, type=None, start=1, boundary=None)
Bases:
StrEnum
Complex component.
- AMPLITUDE = 'AMPLITUDE'
- IMAG = 'IMAG'
- PHASE = 'PHASE'
- REAL = 'REAL'
- class carta.constants.ContourDashMode(value, names=None, *, module=None, qualname=None, type=None, start=1, boundary=None)
Bases:
StrEnum
Contour dash modes.
- DASHED = 'Dashed'
- NEGATIVE_ONLY = 'NegativeOnly'
- NONE = 'None'
- class carta.constants.CoordinateSystem(value, names=None, *, module=None, qualname=None, type=None, start=1, boundary=None)
Bases:
StrEnum
Coordinate systems.
- AUTO = 'AUTO'
- ECLIPTIC = 'ECLIPTIC'
- FK4 = 'FK4'
- FK5 = 'FK5'
- GALACTIC = 'GALACTIC'
- ICRS = 'ICRS'
- class carta.constants.GridMode(value, names=None, *, module=None, qualname=None, type=None, start=1, boundary=None)
Bases:
StrEnum
Grid modes.
- DYNAMIC = 'dynamic'
- FIXED = 'fixed'
- class carta.constants.LabelType(value, names=None, *, module=None, qualname=None, type=None, start=1, boundary=None)
Bases:
StrEnum
Label types.
- EXTERIOR = 'Exterior'
- INTERIOR = 'Interior'
- class carta.constants.NumberFormat(value, names=None, *, module=None, qualname=None, type=None, start=1, boundary=None)
Bases:
StrEnum
Number formats.
- DEGREES = 'd'
- DMS = 'dms'
- HMS = 'hms'
- class carta.constants.Overlay(value, names=None, *, module=None, qualname=None, type=None, start=1, boundary=None)
Bases:
StrEnum
Overlay elements.
Member values are paths to stores corresponding to these elements, relative to the overlay store.
- AXES = 'axes'
- BEAM = 'beam.settingsForDisplay'
- BORDER = 'border'
- COLORBAR = 'colorbar'
- GLOBAL = 'global'
- GRID = 'grid'
- LABELS = 'labels'
- NUMBERS = 'numbers'
- TICKS = 'ticks'
- TITLE = 'title'
- class carta.constants.PaletteColor(value, names=None, *, module=None, qualname=None, type=None, start=1, boundary=None)
Bases:
StrEnum
Palette colours used for overlay elements.
Members of this enum class have additional attributes.
- Variables:
rgb_light (string) – The RGB value of this palette colour in the light theme.
rgb_dark (string) – The RGB value of this palette colour in the dark theme.
- BLACK = 'auto-black'
- BLUE = 'auto-blue'
- COBALT = 'auto-cobalt'
- DARK_GRAY = 'auto-dark_gray'
- FOREST = 'auto-forest'
- GOLD = 'auto-gold'
- GRAY = 'auto-gray'
- GREEN = 'auto-green'
- INDIGO = 'auto-indigo'
- LIGHT_GRAY = 'auto-light_gray'
- LIME = 'auto-lime'
- ORANGE = 'auto-orange'
- RED = 'auto-red'
- ROSE = 'auto-rose'
- SEPIA = 'auto-sepia'
- TURQUOISE = 'auto-turquoise'
- VERMILION = 'auto-vermilion'
- VIOLET = 'auto-violet'
- WHITE = 'auto-white'
- class carta.constants.PanelMode(value, names=None, *, module=None, qualname=None, type=None, start=1, boundary=None)
Bases:
IntEnum
Panel modes.
- MULTIPLE = 1
- SINGLE = 0
- class carta.constants.Polarization(value, names=None, *, module=None, qualname=None, type=None, start=1, boundary=None)
Bases:
IntEnum
Polarizations, corresponding to the POLARIZATIONS enum in the frontend.
- I = 1
- LL = -2
- LR = -4
- PANGLE = 17
- PFLINEAR = 16
- PFTOTAL = 15
- PLINEAR = 14
- PTOTAL = 13
- Q = 2
- RL = -3
- RR = -1
- U = 3
- V = 4
- XX = -5
- XY = -7
- YX = -8
- YY = -6
- class carta.constants.Scaling(value, names=None, *, module=None, qualname=None, type=None, start=1, boundary=None)
Bases:
IntEnum
Colormap scaling types.
- GAMMA = 5
- LINEAR = 0
- LOG = 1
- POWER = 4
- SQRT = 2
- SQUARE = 3
- class carta.constants.SmoothingMode(value, names=None, *, module=None, qualname=None, type=None, start=1, boundary=None)
Bases:
IntEnum
Contour smoothing modes.
- BLOCK_AVERAGE = 1
- GAUSSIAN_BLUR = 2
- NO_SMOOTHING = 0
carta.image module
This module contains an image class which represents a single image open in the session.
Image objects should not be instantiated directly, and should only be created through methods on the carta.session.Session
object.
- class carta.image.Image(session, image_id)
Bases:
BasePathMixin
This object corresponds to an image open in a CARTA frontend session.
This class should not be instantiated directly. Instead, use the session object’s methods for opening new images or retrieving existing images.
- Parameters:
session (
carta.session.Session
) – The session object associated with this image.image_id (integer) – The ID identifying this image within the session. This is a unique number which is not reused, not the index of the image within the list of currently open images.
- Variables:
session (
carta.session.Session
) – The session object associated with this image.image_id (integer) – The ID identifying this image within the session.
- apply_contours()
Apply the contour configuration.
- clear_contours()
Clear the contours.
- close()
Close this image.
- configure_contours(levels=None, smoothing_mode=None, smoothing_factor=None)
Configure contours.
- Parameters:
levels (an iterable in which each element is a number or
None
) – The contour levels. This may be a numeric numpy array; e.g. the output ofarange
. If this is unset, the current configured levels will be used.smoothing_mode (a member of
carta.constants.SmoothingMode
orNone
) – The smoothing mode. If this is unset, the frontend default will be used.smoothing_factor (a number or
None
) – The smoothing kernel size in pixels. If this is unset, the frontend default will be used.
- property depth
The depth of the image. This value is transparently cached on the parent object.
- Returns:
The depth.
- Return type:
integer
- property directory
The path to the directory containing the image. This value is transparently cached on the parent object.
- Returns:
The directory path.
- Return type:
string
- property file_name
The name of the image. This value is transparently cached on the parent object.
- Returns:
The image name.
- Return type:
string
- classmethod from_list(session, image_list)
Create a list of image objects from a list of open images retrieved from the frontend.
This method should not be used directly. It is wrapped by
carta.session.Session.image_list
.- Parameters:
session (
carta.session.Session
) – The session object.image_list (list of dicts) – The JSON object representing frame names retrieved from the frontend.
- Returns:
A list of new image objects.
- Return type:
list of
carta.image.Image
- property header
The header of the image, parsed from the raw frontend data (see
carta.metadata.parse_header
). This value is transparently cached on the parent object.- Returns:
The header of the image, with field names as keys.
- Return type:
dict of string to string, integer, float, boolean,
None
or list of strings
- property height
The height of the image in pixels. This value is transparently cached on the parent object.
- Returns:
The height.
- Return type:
integer
- hide_contours()
Hide the contours.
- hide_raster()
Hide the raster image.
- make_active()
Make this the active image.
- make_raster_scaling_reference()
Make this image the raster scaling reference.
- make_spatial_reference()
Make this image the spatial reference.
- make_spectral_reference()
Make this image the spectral reference.
- property ndim
The number of dimensions of the image. This value is transparently cached on the parent object.
- Returns:
The number of dimensions.
- Return type:
integer
- classmethod new(session, directory, file_name, hdu, append, image_arithmetic, make_active=True, update_directory=False)
Open or append a new image in the session and return an image object associated with it.
This method should not be used directly. It is wrapped by
carta.session.Session.open_image
,carta.session.Session.open_complex_image
andcarta.session.Session.open_LEL_image
.- Parameters:
session (
carta.session.Session
) – The session object.directory (string) – The directory containing the image file or the base directory for the LEL arithmetic expression, either relative to the session’s current directory or an absolute path relative to the CARTA backend’s root directory.
file_name (string) – The name of the image file, or a LEL arithmetic expression.
hdu (string) – The HDU to open.
append (boolean) – Whether the image should be appended.
image_arithmetic (boolean) – Whether the file name should be interpreted as a LEL expression.
make_active (boolean) – Whether the image should be made active in the frontend. This only applies if an image is being appended. The default is
True
.update_directory (boolean) – Whether the starting directory of the frontend file browser should be updated to the directory provided. The default is
False
.
- Returns:
A new image object.
- Return type:
- property num_polarizations
The number of polarizations of the image, excluding computed polarizations. This value is transparently cached on the parent object.
- Returns:
The number of polarizations.
- Return type:
integer
- plot_contours(levels=None, smoothing_mode=None, smoothing_factor=None, dash_mode=None, thickness=None, color=None, colormap=None, bias=None, contrast=None)
Configure contour levels, scaling, dash, and colour or colourmap; and apply contours; in a single step.
If both a colour and a colourmap are provided, the colourmap will be visible.
- Parameters:
levels (an iterable in which each element is a number or
None
) – The contour levels. This may be a numeric numpy array; e.g. the output ofarange
. If this is unset, the current configured levels will be used.smoothing_mode (a member of
carta.constants.SmoothingMode
orNone
) – The smoothing mode. If this is unset, the frontend default will be used.smoothing_factor (a number or
None
) – The smoothing kernel size in pixels. If this is unset, the frontend default will be used.dash_mode (a member of
carta.constants.ContourDashMode
orNone
) – The dash mode.thickness (a number or
None
) – The dash thickness.color (an HTML color specification or
None
) – The color. The default is green.colormap (a member of
carta.constants.Colormap
orNone
) – The colormap. The default iscarta.constants.Colormap.VIRIDIS
.bias (a number or
None
) – The colormap bias.contrast (a number or
None
) – The colormap contrast.
- property polarizations
The available polarizations of the image. This value is transparently cached on the parent object.
This includes Stokes parameters, correlations, and computed components.
- Returns:
The available polarizations.
- Return type:
list of members of
carta.constants.Polarization
- set_center(x, y)
Set the center position, in image or world coordinates.
World coordinates are interpreted according to the session’s globally set coordinate system and any custom number formats. These can be changed using
carta.session.set_coordinate_system
andset_custom_number_format
.Coordinates must either both be image coordinates or match the current number formats. Numbers are interpreted as image coordinates, and numeric strings with no units are interpreted as degrees.
- Parameters:
x (a number, a string in H:M:S or D:M:S format, or a numeric string with degree units) – The X position.
y (a number, a string in H:M:S or D:M:S format, or a numeric string with degree units) – The Y position.
- Raises:
ValueError – If a mix of image and world coordinates is provided, if world coordinates are provided and the image has no valid WCS information, or if world coordinates do not match the session-wide number formats.
- set_channel(channel, recursive=True)
Set the channel.
- Parameters:
channel (a number greater than or equal to
0
and smaller thanself.depth
, in increments of 1, evaluated at runtime) – The desired channel.recursive (a boolean) – Whether to perform the same change on all spectrally matched images. Defaults to True.
- set_clip_percentile(rank)
Set the clip percentile.
- Parameters:
rank (a number greater than or equal to
0
and smaller than or equal to100
) – The percentile rank.
- set_colormap(colormap, invert=False, bias=None, contrast=None)
Set the colormap.
By default the colormap is not inverted, and the bias and contrast are reset to the frontend defaults of
0
and1
respectively.- Parameters:
colormap (a member of
carta.constants.Colormap
) – The colormap.invert (a boolean) – Whether the colormap should be inverted.
bias (a number or
None
) – A custom bias.contrast (a number or
None
) – A custom contrast.
- set_contour_color(color)
Set the contour color.
This automatically disables use of the contour colormap.
- Parameters:
color (an HTML color specification) – The color. The default is green.
- set_contour_colormap(colormap, bias=None, contrast=None)
Set the contour colormap.
This automatically enables use of the contour colormap.
- Parameters:
colormap (a member of
carta.constants.Colormap
) – The colormap. The default iscarta.constants.Colormap.VIRIDIS
.bias (a number or
None
) – The colormap bias.contrast (a number or
None
) – The colormap contrast.
- set_contour_dash(dash_mode=None, thickness=None)
Set the contour dash style.
- Parameters:
dash_mode (a member of
carta.constants.ContourDashMode
orNone
) – The dash mode.thickness (a number or
None
) – The dash thickness.
- set_contours_visible(state)
Set the contour visibility.
- Parameters:
state (a boolean) – The desired visibility state.
- set_cube_matching(state)
Enable or disable spatial and spectral matching.
- Parameters:
state (boolean) – The desired spatial and spectral matching state.
- set_polarization(polarization, recursive=True)
Set the polarization.
- Parameters:
polarization (one of *self.polarizations, evaluated at runtime) – The desired polarization.
recursive (a boolean) – Whether to perform the same change on all spectrally matched images. Defaults to True.
- set_raster_scaling_matching(state)
Enable or disable raster scaling matching.
- Parameters:
state (boolean) – The desired raster scaling matching state.
- set_raster_visible(state)
Set the raster image visibility.
- Parameters:
state (a boolean) – The desired visibility state.
- set_scaling(scaling, alpha=None, gamma=None, rank=None, min=None, max=None)
Set the colormap scaling.
- Parameters:
scaling (a member of
carta.constants.Scaling
) – The scaling type.alpha (a number or
None
) – The alpha value (only applicable toLOG
andPOWER
scaling types).gamma (a number or
None
) – The gamma value (only applicable to theGAMMA
scaling type).rank (a number greater than or equal to
0
and smaller than or equal to100
orNone
) – The clip percentile rank. If this is set, min and max are ignored, and will be calculated automatically.min (a number or
None
) – Custom clip minimum. Only used if both min and max are set. Ignored if rank is set.max (a number or
None
) – Custom clip maximum. Only used if both min and max are set. Ignored if rank is set.
- set_spatial_matching(state)
Enable or disable spatial matching.
- Parameters:
state (boolean) – The desired spatial matching state.
- set_spectral_matching(state)
Enable or disable spectral matching.
- Parameters:
state (boolean) – The desired spectral matching state.
- set_zoom_level(zoom, absolute=True)
Set the zoom level.
TODO: explain this more rigorously.
- Parameters:
zoom (a number) – The zoom level.
absolute (a boolean) – Whether the zoom level should be treated as absolute. By default it is adjusted by a scaling factor.
- property shape
The shape of the image. This value is transparently cached on the parent object.
- Returns:
The shape of the image; dimensions ordered with width last.
- Return type:
list of integers
- show_contours()
Show the contours.
- show_raster()
Show the raster image.
- use_channel_histogram(contours=False)
Use the channel histogram.
- Parameters:
contours (a boolean) – Apply to the contours. By default this is applied to the raster image.
- use_cube_histogram(contours=False)
Use the cube histogram.
- Parameters:
contours (a boolean) – Apply to the contours. By default this is applied to the raster image.
- property valid_wcs
Whether the image contains valid WCS information. This value is transparently cached on the parent object.
- Returns:
Whether the image has WCS information.
- Return type:
boolean
- property width
The width of the image in pixels. This value is transparently cached on the parent object.
- Returns:
The width.
- Return type:
integer
- zoom_to_size(size, axis)
Zoom to the given size along the specified axis.
Numbers are interpreted as pixel sizes. Numeric strings with no units are interpreted as arcseconds.
- Parameters:
size (a number or a numeric string with valid size units) – The size to zoom to.
axis (a member of
carta.constants.SpatialAxis
) – The spatial axis to use.
- Raises:
ValueError – If an angular size is provided and the image has no valid WCS information.
carta.metadata module
This module provides a collection of helper objects for storing and accessing file metadata.
- carta.metadata.parse_header(raw_header)
Parse raw image header entries from the frontend into a more user-friendly format.
Entries with T or F string values are automatically converted to booleans.
HISTORY
,COMMENT
and blank keyword entries are aggregated into single entries with list values and with'HISTORY'
,'COMMENT'
and''
as keys, respectively. An entry in the history list which begins with'>'
will be concatenated with the previous entry.Adjacent
COMMENT
entries are not concatenated automatically.Any other header entries with no values are given values of
None
.- Parameters:
raw_header (dict) – The raw header entries received from the frontend.
- Returns:
The header of the image, with field names as keys.
- Return type:
dict of string to string, integer, float, boolean,
None
or list of strings
carta.protocol module
This module provides classes and functions used to send HTTP requests to a backend or a controller.
- class carta.protocol.AuthType
Bases:
object
The type of authentication used to connect to the backend or controller.
- BACKEND = 0
- CONTROLLER = 1
- NONE = 2
- class carta.protocol.Protocol(frontend_url, token=None, debug_no_auth=False)
Bases:
object
This object manages connections to a backend or controller instance, including any required authentication.
It should not be instantiated directly; it is created on demand when a
carta.session.Session
object is created using one of the convenience class methods provided.- Parameters:
frontend_url (string) – The URL of the frontend.
token (
carta.token.Token
, optional) – The security token used by the CARTA instance. May be omitted if the URL contains a token. If this is a controller token, it will be assumed to be a refresh token, and controller authentication will be enabled. If it’s a backend token, backend authentication will be enabled.debug_no_auth (boolean) – Disable authentication. This should be set if the backend has been started with the
--debug_no_auth
option. This is provided for debugging purposes only and should not be used under normal circumstances.
- Variables:
frontend_url (string) – The URL of the frontend.
base_url (string) – The base frontend URL (with the token parameter, if any, removed).
auth (integer) – The authentication type. One of
carta.protocol.AuthType.BACKEND
,carta.protocol.AuthType.CONTROLLER
orcarta.protocol.AuthType.NONE
.refresh_token (
carta.token.ControllerToken
, optional) – The controller refresh token. Will be set to thetoken
parameter if it is a controller token.backend_token (
carta.token.BackendToken
, optional) – The backend token. Will be set to thetoken
parameter if it is a backend token. If thetoken
parameter is omitted, and a token string can be parsed from the URL, it will be created from that string.
- Raises:
CartaBadToken – If an invalid token was provided.
CartaBadUrl – If an invalid URL was provided.
- ACTION_PATH = '/api/scripting/action'
- REFRESH_TOKEN_PATH = '/api/auth/login'
- SCRIPTING_TOKEN_PATH = '/api/auth/refresh'
- property backend_auth
Is backend authentication enabled?
- Returns:
Whether backend authentication is enabled.
- Return type:
boolean
- check_refresh_token()
Check whether the refresh token has expired.
- Raises:
CartaBadToken – If the refresh token has expired.
- property controller_auth
Is controller authentication enabled?
- Returns:
Whether controller authentication is enabled.
- Return type:
boolean
- cookie()
The refresh token in the form of a cookie.
- property domain
The domain extracted from the frontend URL.
- Returns:
The domain.
- Return type:
string
- property no_auth
Is authentication disabled?
- Returns:
Whether authentication is disabled.
- Return type:
boolean
- classmethod request_refresh_token(frontend_url, username, path=None)
Request a refresh token from a controller and optionally save it to a file.
This function must be run interactively. It securely prompts the user to enter a password.
- Parameters:
frontend_url (string) – The URL of the frontend.
username (string) – The username to use to authenticate with the controller.
path (string, optional) – A path to a file where the refresh token should be saved.
- Returns:
The token object created using the returned refresh token.
- Return type:
carta.token.ControllerToken
object- Raises:
CartaBadRequest – If the request was invalid.
CartaRequestFailed – If the request failed.
CartaBadResponse – If the response could not be decoded.
- request_scripting_action(session_id, path, *args, **kwargs)
Call an action on the frontend through the backend’s scripting interface.
- Parameters:
path (string) – The full dot-separated path to a frontend action.
*args – A variable-length list of parameters to pass to the action.
carta.util.Macro
objects may be used to refer to frontend objects which will be evaluated dynamically. This parameter list will be serialized into a JSON string withcarta.util.CartaEncoder
.**kwargs – Arbitrary keyword arguments. At present only three are used: async (boolean) is passed to indicate that the request should return a response as soon as the action is called, without waiting for the action to complete. response_expected (boolean) indicates that the action should return a JSON object. This is set automatically if return_path is set. return_path specifies a subobject of the action’s response which should be returned instead of the whole response. timeout (boolean) is the maximum time in seconds to wait for an action request to complete (the default is 10).
- Returns:
If the action returns a JSON object, this method will return that response deserialized into a Python object.
- Return type:
None or an object
- Raises:
CartaBadRequest – If the request was invalid.
CartaRequestFailed – If the backend could not send the request to the frontend.
CartaActionFailed – If the action failed.
CartaBadResponse – If a request which was expected to have a JSON response did not have one, or if a JSON response could not be decoded.
- request_scripting_token()
Request a scripting token from the controller and cache it on this object.
- Raises:
CartaBadRequest – If the request was invalid.
CartaRequestFailed – If the request failed.
CartaBadResponse – If the response could not be decoded.
- static split_token_from_url(url)
Extract a backend token from a frontend URL.
- Parameters:
url (string) – The URL of the frontend.
- Returns:
string – The URL with the backend token removed.
carta.token.BackendToken
object or None – The object representing the backend token.
- Raises:
CartaBadUrl – If an invalid URL was provided.
carta.session module
This is the main module of the CARTA Python wrapper. It contains a session class which represents a CARTA frontend session.
The user can interact with an existing CARTA session open in their browser by creating a session object using the carta.session.Session.interact
classmethod.
Alternatively, the user can create a new session which runs in a headless browser controlled by the wrapper. The user can connect to an existing CARTA backend instance (using the carta.session.Session.connect
classmethod), or first start a new CARTA backend instance which is also controlled by the wrapper (using the carta.session.Session.new
classmethod). The backend can be started either on the local host or on a remote host which the user can access with passwordless SSH.
- class carta.session.Session(session_id, protocol, browser=None, backend=None)
Bases:
object
This object corresponds to a CARTA frontend session.
This class provides the core generic method for calling actions on the frontend (through the backend), as well as convenience methods which wrap this generic method and provide a more intuitive and user-friendly interface to frontend functionality associated with the session as a whole.
This class should not be instantiated directly. Four class methods are provided for creating different types of sessions with all the appropriate parameters set:
carta.session.Session.interact
for interacting with an existing CARTA session open in the user’s browser.carta.session.Session.start_and_interact
for starting a new backend instance and then interacting with the default session which is automatically opened by the backend in the user’s browser.carta.session.Session.create
for creating a new CARTA session in a headless browser by connecting to an existing CARTA backend or controller instance.carta.session.Session.start_and_create
for starting a new backend instance and then connecting to it to create a new session in a headless browser.
The session object can be used to create image objects, which provide analogous convenience methods for functionality associated with individual images.
- Parameters:
session_id (integer) – The ID of the CARTA frontend session associated with this object. This is set automatically when a new session is created with
carta.session.Session.create
orcarta.session.Session.start_and_create
.protocol (
carta.protocol.Protocol
) – The protocol object which handles HTTP communication with the CARTA scripting API. This is created automatically when a new session is created with one of the three class methods for creating sessions.browser (
carta.browser.Browser
) – The browser object associated with this session. This is created automatically when a new session is created withcarta.session.Session.create
orcarta.session.Session.start_and_create
.backend (
carta.backend.Backend
) – The backend object associated with this session. This is created automatically when a new session is created withcarta.session.Session.start_and_create
.
- Variables:
session_id (integer) – The ID of the CARTA frontend session associated with this object.
- active_frame()
Return the currently active image.
- Returns:
The currently active image.
- Return type:
- call_action(path, *args, **kwargs)
Call an action on the frontend through the backend’s scripting interface.
This method is the core of the session class, and provides a generic interface for calling any action on the frontend. This is exposed as a public method to give developers the option of writing experimental functionality; wherever possible script writers should instead use the more user-friendly methods on the session and image objects which wrap this method.
- Parameters:
path (string) – The full dot-separated path to a frontend action.
*args – A variable-length list of parameters to pass to the action.
carta.util.Macro
objects may be used to refer to frontend objects which will be evaluated dynamically. This parameter list will be serialized into a JSON string withcarta.util.CartaEncoder
.**kwargs – Arbitrary keyword arguments. At present only three are used: async (boolean) is passed to indicate that the request should return a response as soon as the action is called, without waiting for the action to complete. response_expected (boolean) indicates that the action should return a JSON object. This is set automatically if return_path is set. return_path specifies a subobject of the action’s response which should be returned instead of the whole response. timeout (boolean) is the maximum time in seconds to wait for an action request to complete (the default is 10).
- Returns:
If the action returns a JSON object, this method will return that response deserialized into a Python object.
- Return type:
None or an object
- Raises:
CartaBadRequest – If the request was invalid.
CartaRequestFailed – If the backend could not send the request to the frontend.
CartaActionFailed – If the action failed.
CartaBadResponse – If a request which was expected to have a JSON response did not have one, or if a JSON response could not be decoded.
- call_overlay_action(component, path, *args, **kwargs)
Helper method for calling overlay component actions.
This method calls
carta.session.Session.call_action
after prepending this component’s base path to the path parameter.- Parameters:
component (a member of
carta.constants.Overlay
) – The overlay component to use as the base of the path.path (string) – The path to an action relative to this overlay component.
*args – A variable-length list of parameters. These are passed unmodified to
carta.Session.call_action
.**kwargs – Arbitrary keyword parameters. These are passed unmodified to
carta.Session.call_action
.
- cd(path)
Change the current directory.
This function changes the frontend file browser’s starting directory.
- Parameters:
path (string) – The path to the new directory, which may be relative to the current directory or absolute (relative to the CARTA backend root).
- clear_color(component)
Clear the custom color from an overlay component.
- Parameters:
component (a member of
carta.constants.Overlay
excluding<Overlay.GLOBAL: 'global'>
) – The overlay component.
- clear_custom_number_format()
Disable the custom X and Y number format.
- clear_raster_scaling_reference()
Clear the raster scaling reference.
- clear_spatial_reference()
Clear the spatial reference.
- clear_spectral_reference()
Clear the spectral reference.
- clear_text()
Clear all custom title and axis text.
- close()
Close any browser sessions and backend processes controlled by this session object.
If this session opened a CARTA frontend session in a headless browser, this method will close the browser together with that session. If this session is interacting with a session running in an external browser, that browser session will be unaffected. This includes the new CARTA frontend session which is started automatically when
carta.session.Session.start_and_interact
is used: that frontend session is opened in the user’s browser, which is not controlled by this object.If this session started a new backend process, this method will stop that process. If this session is interacting with an externally started backend process, that process will be unaffected.
- color(component)
The color of an overlay component.
If called on the global overlay options, this function returns the global (default) overlay color. For any single overlay component other than the beam, it returns its custom color if a custom color is enabled, otherwise None. For the beam it returns the beam color.
- Parameters:
component (a member of
carta.constants.Overlay
) – The overlay component.- Returns:
The color of the component or None if no custom color is set on the component.
- Return type:
A member of
carta.constants.PaletteColor
or None
- coordinate_system()
Get the coordinate system.
- Returns:
The coordinate system.
- Return type:
- classmethod create(browser, frontend_url, token=None, timeout=10, debug_no_auth=False)
Connect to an existing CARTA backend or CARTA controller instance and create a new session.
- Parameters:
browser (
carta.browser.Browser
) – The browser to use to open the frontend.frontend_url (string) – The frontend URL of the CARTA instance.
token (
carta.token.Token
, optional) – The security token used by the CARTA instance. You may omit this if the URL contains a token.timeout (integer, optional) – The number of seconds to spend retrying parsing connection information from the frontend (default: 10).
debug_no_auth (boolean, optional) – Disable authentication. Set this if the backend has been started with the
--debug_no_auth
option. This is provided for debugging purposes only and should not be used under normal circumstances.
- Returns:
A session object connected to a new frontend session running in the browser provided.
- Return type:
- Raises:
CartaBadToken – If an invalid token was provided.
CartaBadUrl – If an invalid URL was provided.
CartaBadSession – If the session object could not be created.
- get_overlay_value(component, path)
Helper method for retrieving the values of overlay component attributes.
This method calls
carta.session.Session.get_value
after prepending this component’s base path to the path parameter.- Parameters:
component (a member of
carta.constants.Overlay
) – The overlay component to use as the base of the path.path (string) – The path to an attribute relative to this overlay component.
- Returns:
The value of the attribute, deserialized from a JSON string.
- Return type:
object
- get_value(path, return_path=None)
Get the value of an attribute from a frontend store.
Like the
carta.session.Session.call_action
method, this is exposed in the public API but is not intended to be used directly under normal circumstances.- Parameters:
path (string) – The full path to the attribute.
return_path (string, optional) – Specifies a subobject of the attribute value which should be returned instead of the whole object.
- Returns:
The value of the attribute, deserialized from a JSON string.
- Return type:
object
- hide(component)
Hide an overlay component.
- Parameters:
component (a member of
carta.constants.Overlay
excluding<Overlay.GLOBAL: 'global'>
) – The overlay component.
- image_list()
Return the list of currently open images.
- Returns:
The list of images open in this session.
- Return type:
list of
carta.image.Image
objects
- classmethod interact(frontend_url, session_id, token=None, debug_no_auth=False, backend=None)
Interact with an existing CARTA frontend session.
- Parameters:
frontend_url (string) – The frontend URL of the CARTA instance.
session_id (integer) – The ID of an existing CARTA frontend session. You may supply this as a string of digits; it will be converted to an integer automatically.
token (
carta.token.Token
, optional) – The security token used by the CARTA instance. You may omit this if the URL contains a token.debug_no_auth (boolean, optional) – Disable authentication. Set this if the backend has been started with the
--debug_no_auth
option. This is provided for debugging purposes only and should not be used under normal circumstances.backend (
carta.backend.Backend
) – The backend object associated with this session, if any. This is set if this method is called fromcarta.session.Session.start_and_interact
.
- Returns:
A session object associated with the frontend session provided.
- Return type:
- Raises:
CartaBadID – If the ID provided cannot be converted to an integer
CartaBadToken – If an invalid token was provided.
CartaBadUrl – If an invalid URL was provided.
CartaBadSession – If the session object could not be created.
- ls()
The current directory listing.
- Returns:
The list of files and subdirectories in the frontend file browser’s current starting directory.
- Return type:
list
- next_page()
Go to next page in viewer.
- number_format()
Return the current X and Y number formats, and whether they are a custom setting.
If the image has no WCS information, both the X and Y formats will be
None
.If a custom number format is not set, the format is derived from the coordinate system.
- Returns:
A tuple containing the X format, the Y format, and whether a custom format is set.
- Return type:
tuple (a member of
carta.constants.NumberFormat
orNone
, a member ofcarta.constants.NumberFormat
orNone
, boolean)
- open_LEL_image(expression, directory='.', append=False, make_active=True, update_directory=False)
Open or append a new image via the Lattice Expression Language (LEL) interface.
- Parameters:
expression (a string) – The LEL arithmetic expression.
directory (a string) – The base directory for the LEL expression, either relative to the session’s current directory or an absolute path relative to the CARTA backend’s root directory. Defaults to the session’s current directory.
append (a boolean) – Whether the image should be appended to existing images. By default this is
False
and any existing open images are closed.make_active (a boolean) – Whether the image should be made active in the frontend. This only applies if an image is being appended. The default is
True
.update_directory (a boolean) – Whether the starting directory of the frontend file browser should be updated to the base directory of the LEL expression. The default is
False
.
- Returns:
The opened image.
- Return type:
- open_complex_image(path, component=ComplexComponent.AMPLITUDE, append=False, make_active=True, update_directory=False)
Open or append a new complex-valued image.
- Parameters:
path (a string) – The path to the complex-valued image file, either relative to the session’s current directory or an absolute path relative to the CARTA backend’s root directory.
component (a member of
carta.constants.ComplexComponent
) – The complex component to select when opening the image. The default iscarta.constants.ComplexComponent.AMPLITUDE
.append (a boolean) – Whether the image should be appended to existing images. By default this is
False
and any existing open images are closed.make_active (a boolean) – Whether the image should be made active in the frontend. This only applies if an image is being appended. The default is
True
.update_directory (a boolean) – Whether the starting directory of the frontend file browser should be updated to the parent directory of the image. The default is
False
.
- Returns:
The opened image.
- Return type:
- open_hypercube(image_paths, append=False)
Open multiple images merged into a polarization hypercube.
- Parameters:
image_paths (an iterable with at least 2 elements in which each element is a string or a dictionary with at least 2 elements in which each key is a member of
carta.constants.Polarization
and each value is a string) – The image paths, either relative to the session’s current directory or absolute paths relative to the CARTA backend’s root directory. If this is a list of paths, the polarizations will be deduced from the image headers or names. If this is a dictionary, the polarizations must be used as keys.append (a boolean) – Whether the hypercube should be appended to existing images. By default this is
False
and any existing open images are closed.
- Returns:
The opened hypercube.
- Return type:
- Raises:
ValueError – If explicit polarizations are not provided, and cannot be deduced from the image headers or names.
- open_image(path, hdu='', append=False, make_active=True, update_directory=False)
Open or append a new image.
- Parameters:
path (a string) – The path to the image file, either relative to the session’s current directory or an absolute path relative to the CARTA backend’s root directory.
hdu (a string matching
\d*
) – The HDU to select inside the file.append (a boolean) – Whether the image should be appended to existing images. By default this is
False
and any existing open images are closed.make_active (a boolean) – Whether the image should be made active in the frontend. This only applies if an image is being appended. The default is
True
.update_directory (a boolean) – Whether the starting directory of the frontend file browser should be updated to the parent directory of the image. The default is
False
.
- Returns:
The opened image.
- Return type:
- open_images(image_paths, append=False)
Open multiple images
This is a utility function for adding multiple images in a single command. It assumes that the images are not complex-valued or LEL expressions, and that the default HDU can be used for each image. For more complicated use cases, the methods for opening individual images should be used.
- Parameters:
image_paths (an iterable in which each element is a string) – The image paths, either relative to the session’s current directory or absolute paths relative to the CARTA backend’s root directory.
append (a boolean) – Whether the images should be appended to existing images. By default this is
False
and any existing open images are closed.
- Returns:
The list of opened images.
- Return type:
list of
carta.image.Image
objects
- palette_to_rgb(color)
Convert a palette colour to RGB.
The RGB value depends on whether the session is using the light theme or the dark theme.
- Parameters:
color (a member of
carta.constants.PaletteColor
) – The colour to convert.- Returns:
The RGB value of the palette colour in the session’s current theme, as a 6-digit hexadecimal with a leading
#
.- Return type:
string
- previous_page()
Go to previous page in viewer.
- pwd()
The current directory.
This is the frontend file browser’s currently saved starting directory. Whenever an image file is opened with the frontend’s file browser (which may happen if the wrapper is connected to an interactive session), this directory is changed to the file’s parent directory. By default, this directory is not changed if an image is opened through the wrapper (which bypasses the file browser).
- Returns:
The session’s current directory.
- Return type:
string
- rendered_view_data(background_color=None)
Get the decoded data of the rendered active image.
- Parameters:
background_color (an HTML color specification or
None
) – The background color. By default the background will be transparent.- Returns:
The decoded PNG image data.
- Return type:
bytes
- rendered_view_url(background_color=None)
Get a data URL of the rendered active image.
- Parameters:
background_color (an HTML color specification or
None
) – The background color. By default the background will be transparent.- Returns:
A data URL for the rendered image in PNG format, base64-encoded.
- Return type:
string
- resolve_file_path(path)
Convert a file path to an absolute path.
This function prepends the session’s current directory to a relative path, and normalizes the path to remove redundant separators and references.
- Parameters:
path (string) – The file path, which may be absolute or relative to the current directory.
- Returns:
The absolute file path, relative to the CARTA backend’s root.
- Return type:
string
- save_rendered_view(file_name, background_color=None)
Save the decoded data of the rendered active image to a file.
- Parameters:
file_name (a string) – The name of the file.
background_color (an HTML color specification or
None
) – The background color. By default the background will be transparent.
- set_beam(beam_type=None, width=None, shift_x=None, shift_y=None)
Set the beam properties.
- Parameters:
beam_type (a member of
carta.constants.BeamType
orNone
) – The beam type.width (a number or
None
) – The beam width.shift_x (a number or
None
) – The X position.shift_y (a number or
None
) – The Y position.
- set_color(color, component=Overlay.GLOBAL)
Set the custom color on an overlay component, or the global color.
- Parameters:
color (a member of
carta.constants.PaletteColor
) – The color.component (a member of
carta.constants.Overlay
) – The overlay component.
- set_coordinate_system(system=CoordinateSystem.AUTO)
Set the coordinate system.
- Parameters:
system (a member of
carta.constants.CoordinateSystem
) – The coordinate system.
- set_cursor(x, y)
Set the curson position.
TODO: this is a precursor to making z-profiles available, but currently the relevant functionality is not exposed by the frontend.
- Parameters:
x (a number) – The X position.
y (a number) – The Y position.
- set_custom_number_format(x_format=None, y_format=None)
Set a custom X and Y number format.
- Parameters:
x_format (a member of
carta.constants.NumberFormat
orNone
) – The X format. If this is unset, the last custom X format to be set will be restored.x_format (a member of
carta.constants.NumberFormat
orNone
) – The Y format. If this is unset, the last custom Y format to be set will be restored.
- set_font(component, font=None, font_size=None)
Set the font and/or font size of an overlay component.
TODO: can we get the allowed font names from somewhere?
- Parameters:
component (one of title, numbers, labels) – The overlay component.
font (a string or
None
) – The font name.font_size (a number or
None
) – The font size.
- set_label_type(label_type)
Set the label type.
- Parameters:
label_type (a member of
carta.constants.LabelType
) – The label type.
- set_text(title=None, label_x=None, label_y=None)
Set custom title and/or the axis label text.
- Parameters:
title (a string or
None
) – The title text.label_x (a string or
None
) – The X-axis text.label_y (a string or
None
) – The Y-axis text.
- set_view_area(width, height)
Set the dimensions of the view area.
- Parameters:
width (a number) – The new width, in pixels, divided by the device pixel ratio.
height (a number) – The new height, in pixels, divided by the device pixel ratio.
- set_viewer_grid(rows, columns, grid_mode=GridMode.FIXED)
Set number of columns and rows in viewer grid.
- Parameters:
rows (a number greater than or equal to
1
and smaller than or equal to10
, in increments of 1) – Number of rows.columns (a number greater than or equal to
1
and smaller than or equal to10
, in increments of 1) – Number of columns.grid_mode (a member of
carta.constants.GridMode
) – The grid mode to adopt. The default iscarta.constants.GridMode.FIXED
.
- set_viewer_mode(panel_mode)
Switch between single-panel mode and multiple-panel mode.
- Parameters:
panel_mode (a member of
carta.constants.PanelMode
) – The panel mode to adopt.
- set_visible(component, visible)
Set the visibility of an overlay component.
Ticks cannot be shown or hidden in AST, but it is possible to set the width to a very small non-zero number to make them effectively invisible.
- Parameters:
component (a member of
carta.constants.Overlay
excluding<Overlay.GLOBAL: 'global'>
) – The overlay component.visible (a boolean) – The visibility state.
- set_width(width, component)
Set the line width of an overlay component.
- Parameters:
component (a number greater than
0
) – The overlay component.
- show(component)
Show an overlay component.
- Parameters:
component (a member of
carta.constants.Overlay
excluding<Overlay.GLOBAL: 'global'>
) – The overlay component.
- classmethod start_and_create(browser, executable_path='carta', remote_host=None, params=(), timeout=10, token=None, frontend_url_timeout=10)
Start a new CARTA backend instance and create a new session. This method cannot be used with a CARTA controller instance (which already starts and stops backend instances for the user on demand).
- Parameters:
browser (
carta.browser.Browser
) – The browser to use to open the frontend.executable_path (string, optional) – A custom path to the CARTA backend executable. The default is
"carta"
.remote_host (string, optional) – A remote host where the backend process should be launched, which must be accessible through passwordless ssh. By default the backend process is launched on the local host.
params (iterable, optional) – Additional parameters to be passed to the backend process. By default scripting is enabled and the automatic browser is disabled. The parameters are appended to the end of the command, so a positional parameter for a data directory can be included. Example:
["--verbosity", 5, "--port", 3010]
timeout (integer, optional) – The number of seconds to spend parsing the frontend for connection information. 10 seconds by default.
token (
carta.token.Token
, optional) – The security token to use. Parsed from the backend output by default.frontend_url_timeout (integer) – How long to keep checking the backend output for the frontend URL. Default: 10 seconds.
- Returns:
A session object connected to a new frontend session running in the browser provided.
- Return type:
- Raises:
CartaBadToken – If an invalid token was provided.
CartaBadUrl – If an invalid URL was provided.
CartaBadSession – If the session object could not be created.
- classmethod start_and_interact(executable_path='carta', remote_host=None, params=(), token=None, frontend_url_timeout=10, session_creation_timeout=10)
Start a new CARTA backend instance and interact with the default CARTA frontend session which is created automatically in the user’s browser. This method cannot be used with a CARTA controller instance.
- Parameters:
executable_path (string, optional) – A custom path to the CARTA backend executable. The default is
"carta"
.remote_host (string, optional) – A remote host where the backend process should be launched, which must be accessible through passwordless ssh. By default the backend process is launched on the local host.
params (iterable, optional) – Additional parameters to be passed to the backend process. By default scripting is enabled. The parameters are appended to the end of the command, so a positional parameter for a data directory can be included. Example:
["--verbosity", 5, "--port", 3010]
token (
carta.token.Token
, optional) – The security token to use. Parsed from the backend output by default.frontend_url_timeout (integer) – How long to keep checking the backend output for the frontend URL. Default: 10 seconds.
session_creation_timeout (integer) – How long to keep checking the output for a default session ID. Default: 10 seconds.
- Returns:
A session object associated with the frontend session provided.
- Return type:
- Raises:
CartaBadID – If a valid ID cannot be obtained from the backend process output.
CartaBadToken – If a valid token cannot be obtained from the backend process output, or the provided token is invalid.
CartaBadUrl – If a valid URL cannot be obtained from the backend process output.
CartaBadSession – If the session object could not be created.
- toggle_labels()
Toggle the overlay labels.
- visible(component)
Whether an overlay component is visible.
Ticks cannot be shown or hidden in AST.
- Parameters:
component (a member of
carta.constants.Overlay
excluding<Overlay.GLOBAL: 'global'>
) – The overlay component.- Returns:
Whether the component is visible, or None for an invalid component.
- Return type:
boolean or None
- width(component)
The line width of an overlay component.
- Parameters:
component (one of grid, border, ticks, axes, colorbar) – The overlay component.
- Returns:
The line width of the component.
- Return type:
number
carta.token module
This module provides classes and functions for managing backend and controller tokens.
- class carta.token.BackendToken(string)
Bases:
Token
An object representing a security token used by the backend. These tokens are strings with no additional meaning, and may be generated automatically or overridden by the user with a fixed value.
- Parameters:
string (string) – The token string.
- class carta.token.ControllerToken(string)
Bases:
Token
An object representing a security token used by the controller. These tokens are JWTs (JSON Web Tokens) which encode additional information such as an expiration date. The controller uses multiple types of tokens. This interface makes use of long-lived refresh tokens (used to log into the controller and to obtain scripting tokens) and short-lived scripting tokens (used to make scripting requests).
- Parameters:
string (string) – The token string.
- as_cookie(domain)
Create a cookie from this refresh token.
- Parameters:
domain (string) – The domain to use in the cookie.
- Returns:
The cookie as a dictionary of string keys and values.
- Return type:
dict
- Raises:
CartaBadToken – If the token string is not a valid JWT or if this is not a refresh token.
- property expires
The expiration date of this token.
- Returns:
The expiration date.
- Return type:
datetime.datetime
object- Raises:
CartaBadToken – If the token string is not a vaild JWT.
- classmethod from_file(path)
Load a controller token from a file.
- Parameters:
path (string) – The path to the file.
- Returns:
The controller token.
- Return type:
- property refresh
Is this a refresh token?
- Returns:
Whether this is a refresh token.
- Return type:
boolean
- Raises:
CartaBadToken – If the token string is not a vaild JWT.
- save(path)
Save this token to a file.
- Parameters:
path (string) – The path to the file where the token should be saved.
- property scripting
Is this a scripting token?
- Returns:
Whether this is a scripting token.
- Return type:
boolean
- Raises:
CartaBadToken – If the token string is not a vaild JWT.
- property username
The username encoded in this token.
- Returns:
The username.
- Return type:
string
- Raises:
CartaBadToken – If the token string is not a vaild JWT.
- valid()
Is this token valid?
- Returns:
Whether this token is valid.
- Return type:
boolean
- Raises:
CartaBadToken – If the token string is not a vaild JWT.
- class carta.token.Token(string)
Bases:
object
The parent token class. This should not be instantiated directly.
- Parameters:
string (string) – The token string.
- Variables:
string (string) – The token string.
carta.units module
This module provides helper objects for unit conversion.
- class carta.units.AngularSize(value)
Bases:
object
An angular size.
This class provides methods for parsing angular sizes with any known unit, and should not be instantiated directly. Child classes can be used directly if the unit is known.
Child class instances have a string representation in a normalized format which can be parsed by the frontend.
- FORMATS = {'': <class 'carta.units.ArcsecSize'>, '"': <class 'carta.units.ArcsecSize'>, "'": <class 'carta.units.ArcminSize'>, 'amin': <class 'carta.units.ArcminSize'>, 'arcmin': <class 'carta.units.ArcminSize'>, 'arcminute': <class 'carta.units.ArcminSize'>, 'arcminutes': <class 'carta.units.ArcminSize'>, 'arcsec': <class 'carta.units.ArcsecSize'>, 'arcsecond': <class 'carta.units.ArcsecSize'>, 'arcseconds': <class 'carta.units.ArcsecSize'>, 'asec': <class 'carta.units.ArcsecSize'>, 'deg': <class 'carta.units.DegreesSize'>, 'degree': <class 'carta.units.DegreesSize'>, 'degrees': <class 'carta.units.DegreesSize'>, 'mas': <class 'carta.units.MilliarcsecSize'>, 'microarcsec': <class 'carta.units.MicroarcsecSize'>, 'microarcsecond': <class 'carta.units.MicroarcsecSize'>, 'microarcseconds': <class 'carta.units.MicroarcsecSize'>, 'milliarcsec': <class 'carta.units.MilliarcsecSize'>, 'milliarcsecond': <class 'carta.units.MilliarcsecSize'>, 'milliarcseconds': <class 'carta.units.MilliarcsecSize'>, 'uas': <class 'carta.units.MicroarcsecSize'>, 'µas': <class 'carta.units.MicroarcsecSize'>, '′': <class 'carta.units.ArcminSize'>, '″': <class 'carta.units.ArcsecSize'>}
- NAME = 'angular size'
- SYMBOL_UNIT_REGEX = '^(\\d+(?:\\.\\d+)?)(|"|\'|″|′)$'
- WORD_UNIT_REGEX = '^(\\d+(?:\\.\\d+)?)\\s*(arcsecond|arcseconds|uas|mas|arcminute|degree|arcminutes|microarcsec|amin|arcsec|milliarcsec|deg|microarcseconds|arcmin|asec|degrees|milliarcsecond|µas|milliarcseconds|microarcsecond)$'
- classmethod from_string(value)
Construct an angular size object from a string.
A number without a unit is assumed to be in arcseconds. Permitted unit strings and their mappings to normalized units are stored in subclasses of
carta.util.AngularSize
. Whitespace is permitted after the number and before a unit which is a word, but not before a single-character unit.This method may also be used from child classes if a specific format is required.
- Parameters:
value (string) – The string representation of the angular size.
- Returns:
The angular size object.
- Return type:
carta.util.AngularSize
- Raises:
ValueError – If the angular size string is not in a recognized format.
- classmethod valid(value)
Whether the input string is a numeric value followed by an angular size unit.
A number without a unit is assumed to be in arcseconds. Permitted unit strings and their mappings to normalized units are stored in subclasses of
carta.util.AngularSize
. Whitespace is permitted after the number and before a unit which is a word, but not before a single-character unit.This method may also be used from child classes if a specific format is required.
- Parameters:
value (string) – The input string.
- Returns:
Whether the input string is an angular size.
- Return type:
boolean
- class carta.units.ArcminSize(value)
Bases:
AngularSize
An angular size in arcminutes.
- FACTOR = 1
- INPUT_UNITS = {"'", 'amin', 'arcmin', 'arcminute', 'arcminutes', '′'}
- NAME = 'arcminute'
- OUTPUT_UNIT = "'"
- SYMBOL_UNIT_REGEX = "^(\\d+(?:\\.\\d+)?)(′|')$"
- WORD_UNIT_REGEX = '^(\\d+(?:\\.\\d+)?)\\s*(arcminutes|amin|arcmin|arcminute)$'
- class carta.units.ArcsecSize(value)
Bases:
AngularSize
An angular size in arcseconds.
- FACTOR = 1
- INPUT_UNITS = {'', '"', 'arcsec', 'arcsecond', 'arcseconds', 'asec', '″'}
- NAME = 'arcsecond'
- OUTPUT_UNIT = '"'
- SYMBOL_UNIT_REGEX = '^(\\d+(?:\\.\\d+)?)(|"|″)$'
- WORD_UNIT_REGEX = '^(\\d+(?:\\.\\d+)?)\\s*(arcsecond|asec|arcseconds|arcsec)$'
- class carta.units.DMSCoordinate(hours_or_degrees, minutes, seconds)
Bases:
SexagesimalCoordinate
A world coordinate in DMS format.
- FMT = 'dms'
- REGEX = {'COLON': '^(-?\\d+)?:([0-5]?\\d)?:([0-5]?\\d(?:\\.\\d+)?)?$', 'LETTER': '^(?:(-?\\d+)d)?(?:([0-5]?\\d)m)?(?:([0-5]?\\d(?:\\.\\d+)?)s)?$'}
- classmethod from_string(value, axis)
Construct a world coordinate object in DMS format from a string.
Coordinates may be provided in DMS format with colons or letters as separators. The value range will be validated for the provided spatial axis.
- Parameters:
value (string) – The input string.
axis (
carta.constants.SpatialAxis
) – The spatial axis of this coordinate.
- Returns:
The coordinate object.
- Return type:
carta.util.DMSCoordinate
- class carta.units.DegreesCoordinate(degrees)
Bases:
WorldCoordinate
A world coordinate in decimal degree format.
- DEGREE_UNITS = {'deg', 'degree', 'degrees'}
- FMT = 'd'
- REGEX = {'DECIMAL': '^-?\\d+(\\.\\d+)?$', 'DEGREE_UNIT': '^-?(\\d+(?:\\.\\d+)?)\\s*(degrees|degree|deg)$'}
- classmethod from_string(value, axis)
Construct a world coordinate object in decimal degree format from a string.
Coordinates may be provided with or without an explicit unit. Permitted degree unit strings are stored in
carta.util.DegreesCoordinate.DEGREE_UNITS
.- Parameters:
value (string) – The input string.
axis (
carta.constants.SpatialAxis
) – The spatial axis of this coordinate.
- Returns:
The coordinate object.
- Return type:
carta.util.DegreesCoordinate
- class carta.units.DegreesSize(value)
Bases:
AngularSize
An angular size in degrees.
- FACTOR = 1
- INPUT_UNITS = {'deg', 'degree', 'degrees'}
- NAME = 'degree'
- OUTPUT_UNIT = 'deg'
- SYMBOL_UNIT_REGEX = '^(\\d+(?:\\.\\d+)?)()$'
- WORD_UNIT_REGEX = '^(\\d+(?:\\.\\d+)?)\\s*(degrees|degree|deg)$'
- class carta.units.HMSCoordinate(hours_or_degrees, minutes, seconds)
Bases:
SexagesimalCoordinate
A world coordinate in HMS format.
- FMT = 'hms'
- REGEX = {'COLON': '^(-?(?:\\d|[01]\\d|2[0-3]))?:([0-5]?\\d)?:([0-5]?\\d(?:\\.\\d+)?)?$', 'LETTER': '^(?:(-?(?:\\d|[01]\\d|2[0-3]))h)?(?:([0-5]?\\d)m)?(?:([0-5]?\\d(?:\\.\\d+)?)s)?$'}
- classmethod from_string(value, axis)
Construct a world coordinate object in HMS format from a string.
Coordinates may be provided in HMS format with colons or letters as separators. The value range will be validated for the provided spatial axis.
- Parameters:
value (string) – The input string.
axis (
carta.constants.SpatialAxis
) – The spatial axis of this coordinate.
- Returns:
The coordinate object.
- Return type:
carta.util.HMSCoordinate
- class carta.units.MicroarcsecSize(value)
Bases:
AngularSize
An angular size in microarcseconds.
- FACTOR = 1e-06
- INPUT_UNITS = {'microarcsec', 'microarcsecond', 'microarcseconds', 'uas', 'µas'}
- NAME = 'microarcsecond'
- OUTPUT_UNIT = '"'
- SYMBOL_UNIT_REGEX = '^(\\d+(?:\\.\\d+)?)()$'
- WORD_UNIT_REGEX = '^(\\d+(?:\\.\\d+)?)\\s*(µas|microarcseconds|microarcsec|uas|microarcsecond)$'
- class carta.units.MilliarcsecSize(value)
Bases:
AngularSize
An angular size in milliarcseconds.
- FACTOR = 0.001
- INPUT_UNITS = {'mas', 'milliarcsec', 'milliarcsecond', 'milliarcseconds'}
- NAME = 'milliarcsecond'
- OUTPUT_UNIT = '"'
- SYMBOL_UNIT_REGEX = '^(\\d+(?:\\.\\d+)?)()$'
- WORD_UNIT_REGEX = '^(\\d+(?:\\.\\d+)?)\\s*(milliarcsecond|milliarcsec|mas|milliarcseconds)$'
- class carta.units.SexagesimalCoordinate(hours_or_degrees, minutes, seconds)
Bases:
WorldCoordinate
A world coordinate in sexagesimal format.
This class contains common functionality for parsing the HMS and DMS formats.
- as_tuple()
The tuple representation of this coordinate.
- classmethod from_string(value, axis)
Construct a world coordinate object in sexagesimal format from a string.
Coordinates may be provided in HMS or DMS format with colons or letters as separators. The value range will be validated for the provided spatial axis.
- Parameters:
value (string) – The input string.
axis (
carta.constants.SpatialAxis
) – The spatial axis of this coordinate.
- Returns:
The coordinate object.
- Return type:
carta.util.SexagesimalCoordinate
- class carta.units.WorldCoordinate
Bases:
object
A world coordinate.
- FMT = None
- FORMATS = {NumberFormat.DEGREES: <class 'carta.units.DegreesCoordinate'>, NumberFormat.DMS: <class 'carta.units.DMSCoordinate'>, NumberFormat.HMS: <class 'carta.units.HMSCoordinate'>}
- classmethod from_string(value, axis)
Construct a world coordinate object from a string.
This is implemented in subclasses corresponding to different formats.
- Parameters:
value (string) – The input string.
axis (
carta.constants.SpatialAxis
) – The spatial axis of this coordinate.
- Returns:
The coordinate object.
- Return type:
carta.util.WorldCoordinate
- classmethod valid(value)
Whether the input string is a world coordinate string in any of the recognised formats.
Coordinates may be provided in HMS or DMS format (with colons or letters as separators), or in degrees (with or without an explicit unit). Permitted degree unit strings are stored in
carta.util.DegreesCoordinate.DEGREE_UNITS
.- Parameters:
value (string) – The input string.
- Returns:
Whether the input string is a valid world coordinate.
- Return type:
boolean
- classmethod with_format(fmt)
Return the subclass of
carta.util.WorldCoordinate
corresponding to the specified format.
carta.util module
This module provides miscellaneous utility classes and functions used by the wrapper.
- class carta.util.BasePathMixin
Bases:
object
A mixin which provides
call_action
andget_value
methods which prepend the object’s base path to the path before calling the correspondingcarta.session.Session
methods.It also provides a
macro
method which prepends the path when creating acarta.util.Macro
.A class inheriting from this mixin must define a _base_path attribute (the string prefix) and a session attribute (a
carta.session.Session
object).- call_action(path, *args, **kwargs)
Convenience wrapper for the session object’s generic action method.
This method calls
carta.session.Session.call_action
after prepending this object’s base path to the path parameter.- Parameters:
path (string) – The path to an action relative to this object’s store.
*args – A variable-length list of parameters. These are passed unmodified to the session method.
**kwargs – Arbitrary keyword parameters. These are passed unmodified to the session method.
- Returns:
The unmodified return value of the session method.
- Return type:
object or None
- get_value(path, return_path=None)
Convenience wrapper for the session object’s generic method for retrieving attribute values.
This method calls
carta.session.Session.get_value
after prepending this object’s base path to the path parameter.- Parameters:
path (string) – The path to an attribute relative to this object’s store.
return_path (string, optional) – Specifies a subobject of the attribute value which should be returned instead of the whole object.
- Returns:
The unmodified return value of the session method.
- Return type:
object
- macro(target, variable)
Convenience wrapper for creating a
carta.util.Macro
for an object property.This method prepends this object’s base path to the target parameter. If target is the empty string, the base path will be substituted.
- Parameters:
target (str) – The target frontend object.
variable (str) – The variable on the target object.
- Returns:
A placeholder for a variable which will be evaluated dynamically by the frontend.
- Return type:
obj:carta.util.Macro
- exception carta.util.CartaActionFailed
Bases:
CartaScriptingException
An action request received a failure response from the CARTA frontend.
- exception carta.util.CartaBadID
Bases:
CartaScriptingException
A session ID is invalid.
- exception carta.util.CartaBadRequest
Bases:
CartaScriptingException
A request sent to the CARTA backend was rejected.
- exception carta.util.CartaBadResponse
Bases:
CartaScriptingException
An action request received an unexpected response from the CARTA frontend.
- exception carta.util.CartaBadSession
Bases:
CartaScriptingException
A session could not be constructed.
- exception carta.util.CartaBadToken
Bases:
CartaScriptingException
A token has expired or is invalid.
- exception carta.util.CartaBadUrl
Bases:
CartaScriptingException
An URL is invalid.
- class carta.util.CartaEncoder(*, skipkeys=False, ensure_ascii=True, check_circular=True, allow_nan=True, sort_keys=False, indent=None, separators=None, default=None)
Bases:
JSONEncoder
A custom encoder to JSON which correctly serialises custom objects with a
json
method, and numpy arrays.- default(obj)
This method is overridden from the parent class and performs the substitution.
- exception carta.util.CartaRequestFailed
Bases:
CartaScriptingException
A request received a failure response from the CARTA backend.
- exception carta.util.CartaScriptingException
Bases:
Exception
The top-level exception for all scripting errors.
- exception carta.util.CartaValidationFailed
Bases:
CartaScriptingException
Invalid parameters were passed to a function with a
carta.validation.validate
decorator.
- class carta.util.Macro(target, variable)
Bases:
object
A placeholder for a target and a variable which will be evaluated dynamically by the frontend.
- Parameters:
target (str) – The target frontend object.
variable (str) – The variable on the target object.
- Variables:
target (str) – The target frontend object.
variable (str) – The variable on the target object.
- UNDEFINED = Macro('', 'undefined')
- json()
The JSON serialization of this object.
- carta.util.cached(func)
A decorator which transparently caches the return value of the decorated method on the parent object.
This should only be used on methods with return values which are not expected to change for the lifetime of the object.
- carta.util.split_action_path(path)
Extracts a path to a frontend object store and an action from a combined path.
carta.validation module
This module provides a collection of descriptors of the permitted types and values of parameters passed to carta.session.Session
and carta.image.Image
methods. They are associated with methods through a decorator which performs the validation at runtime and also injects parameter descriptions into the methods’ docstrings.
- class carta.validation.Attr
Bases:
str
A wrapper for arguments to be passed to the
carta.validation.Evaluate
descriptor. These arguments are string names of properties on the parent object of the decorated method, which will be evaluated at runtime.
- class carta.validation.Attrs
Bases:
str
A wrapper for arguments to be passed to the
carta.validation.Evaluate
descriptor. These arguments are string names of properties on the parent object of the decorated method, which will be evaluated at runtime. Unlike carta.validation.Attr, the wrapped property is assumed to be an iterable which should be unpacked.
- class carta.validation.Boolean
Bases:
Parameter
A boolean parameter.
- property description
A human-readable description of this parameter descriptor.
- Returns:
The description.
- Return type:
string
- validate(value, parent)
Check if the value is boolean. It may be expressed as a numeric 1 or 0 value.
See
carta.validation.Parameter.validate
for general information about this method.
- class carta.validation.Color
Bases:
Union
Any valid HTML color specification: a 3- or 6-digit hex triplet, an RBG(A) or HSL(A) tuple, or one of the 147 named colors.
- class carta.validation.Constant(clazz, exclude=())
Bases:
OneOf
A parameter which must be a member of the given enum class. For consistency and compatibility, a parameter will be accepted if it evaluates as equal to a member of the enum. Intended for use with the string and integer constants defined in
carta.constants
.- Parameters:
clazz (enum class) – The parameter must be a member of this enum class or have the same value as a member of this enum class.
exclude (iterable, optional) – An iterable of members to exclude.
- Variables:
options (iterable) – An iterable of the permitted options.
clazz (enum class) – The parameter must be a member of this enum class or have the same value as a member of this enum class.
exclude (iterable) – An iterable of members which are excluded.
- property description
A human-readable description of this parameter descriptor.
- Returns:
The description.
- Return type:
string
- class carta.validation.Coordinate
Bases:
Union
A representation of a world coordinate or image coordinate. Can be a number, a string in H:M:S or D:M:S format, or a numeric string with degree units. A number is assumed to be a pixel value. Validates strings using
carta.util.WorldCoordinate
.- class WorldCoordinate(regex=None, flags=0)
Bases:
String
Helper validator class which uses
carta.util.WorldCoordinate
to validate strings.- validate(value, parent)
Check if the value can be parsed as a world coordinate.
See
carta.validation.Parameter.validate
for general information about this method.
- class carta.validation.Evaluate(paramclass, *args, **kwargs)
Bases:
Parameter
A descriptor which is constructed at runtime using properties of the parent object of the decorated method.
- Parameters:
paramclass (a
carta.validation.Parameter
class) – The class of the parameter descriptor to construct.*args (iterable) – Positional arguments to pass to the constructor; either literals or
carta.validation.Attr
objects which will be evaluated from properties on the parent object at runtime.**kwargs (iterable) – Keyword arguments to pass to the constructor; either literals or
carta.validation.Attr
objects which will be evaluated from properties on the parent object at runtime.
- Variables:
paramclass (a
carta.validation.Parameter
class) – The class of the parameter descriptor to construct.args (iterable) – Positional arguments to pass to the constructor.
kwargs (iterable) – Keyword arguments to pass to the constructor.
- property description
A human-readable description of this parameter descriptor.
- Returns:
The description.
- Return type:
string
- validate(value, parent)
Validate the value after constructing the parameter descriptor object.
See
carta.validation.Parameter.validate
for general information about this method.
- class carta.validation.InstanceOf(types)
Bases:
Parameter
A parameter which is an instance of the provided type or tuple of types.
This validator uses
isinstance
, and has the same behaviour. An instance of a child class is also an instance of a parent class.- Parameters:
types (type or tuple of types)
- property description
A human-readable description of this parameter descriptor.
- Returns:
The description.
- Return type:
string
- validate(value, parent)
Check if the value is an instance of the provided type or types.
See
carta.validation.Parameter.validate
for general information about this method.
- class carta.validation.IterableOf(param, min_size=None, max_size=None)
Bases:
Parameter
An iterable of values which must match the given descriptor.
- Parameters:
param (
carta.validation.Parameter
) – The parameter descriptor.min_size (integer, optional) – The minimum size.
max_size (integer, optional) – The maximum size.
- Variables:
param (
carta.validation.Parameter
) – The parameter descriptor.min_size (integer, optional) – The minimum size.
max_size (integer, optional) – The maximum size.
- property description
A human-readable description of this parameter descriptor.
- Returns:
The description.
- Return type:
string
- validate(value, parent)
Check if each element of the iterable can be validated with the given descriptor.
See
carta.validation.Parameter.validate
for general information about this method.
- class carta.validation.MapOf(key_param, value_param, min_size=None, max_size=None)
Bases:
IterableOf
A dictionary of keys and values which must match the given descriptors.
- Parameters:
value_param (
carta.validation.Parameter
) – The value parameter descriptor.- Variables:
value_param (
carta.validation.Parameter
) – The value parameter descriptor.
- property description
A human-readable description of this parameter descriptor.
- Returns:
The description.
- Return type:
string
- validate(value, parent)
Check if each element of the iterable can be validated with the given descriptor.
See
carta.validation.Parameter.validate
for general information about this method.
- class carta.validation.NoneOr(*options, description=None)
Bases:
Union
A union of other parameter descriptors as well as
None
.In the most common use case, this is used with a single other parameter type for optional parameters which are
None
by default. In more complex cases this can be used as shorthand in place of acarta.validation.Union
with an explicitcarta.validation.NoneParameter
option. Also seecarta.validation.all_optional
for a less verbose way to specify multiple sequential optional parameters.- Parameters:
*options (iterable of
carta.validation.Parameter
objects) – An iterable of valid descriptors for this parameter, in addition toNone
.description (str, optional) – A custom description. The default is generated from the descriptions of the provided options.
- Variables:
options (iterable of
carta.validation.Parameter
objects) – An iterable of valid descriptors for this parameter, in addition toNone
.
- class carta.validation.NoneParameter
Bases:
Parameter
A parameter which must be
None
. This is not intended to be used directly; it is used together withcarta.validation.Union
for optional parameters with a default value ofNone
.- property description
A human-readable description of this parameter descriptor.
- Returns:
The description.
- Return type:
string
- validate(value, parent)
Check if the value is
None
.See
carta.validation.Parameter.validate
for general information about this method.
- class carta.validation.Number(min=None, max=None, interval=3, step=None, offset=None)
Bases:
Parameter
An integer or floating point scalar numeric parameter.
- Parameters:
min (number, optional) – The lower bound.
max (number, optional) – The upper bound.
interval (int) – A bitmask which describes whether the bounds are included or excluded. The constant attributes defined on this class should be used. By default both bounds are included.
step (number, optional) – A step size to which the value must conform. May be a fractional value. If this is unset, any value within the range is permitted.
offset (number, optional) – A step offset. Ignored if a step size is not set. By default permitted values are aligned with the lower bound if it is set, otherwise with zero.
- Variables:
min (number) – The lower bound.
max (number) – The upper bound.
min_included (bool) – Whether the lower bound is included.
max_included (bool) – Whether the upper bound is included.
step (number, optional) – The step size.
offset (number, optional) – The step offset.
- EXCLUDE = 0
- INCLUDE = 3
- INCLUDE_MAX = 2
- INCLUDE_MIN = 1
- property description
A human-readable description of this parameter descriptor.
- Returns:
The description.
- Return type:
string
- validate(value, parent)
Check if the value is a number and falls within any bounds that were provided.
We check the type by attempting to convert the value to
float
. We do this instead of comparing types directly to support compatible numeric types from e.g. the numpy library without having to anticipate and check for them explicitly and without introducing import dependencies.See
carta.validation.Parameter.validate
for general information about this method.
- class carta.validation.OneOf(*options, normalize=None)
Bases:
Parameter
A parameter which must be one of several discrete values.
- Parameters:
*options (iterable) – An iterable of permitted values.
normalize (function, optional) – A function for applying a transformation to the value before the comparison: for example,
lambda x: x.lower()
.
- Variables:
options (iterable) – An iterable of permitted values.
normalize (function, optional) – A function for applying a transformation to the value before the comparison.
- property description
A human-readable description of this parameter descriptor.
- Returns:
The description.
- Return type:
string
- validate(value, parent)
Check if the value is equal to one of the provided options. If a normalization function is given, this is first used to transform the value.
See
carta.validation.Parameter.validate
for general information about this method.
- class carta.validation.Parameter
Bases:
object
The top-level class for parameter validation.
- property description
A human-readable description of this parameter descriptor.
- Returns:
The description.
- Return type:
string
- validate(value, parent)
Validate the value provided.
- Parameters:
value – The value to be validated.
parent – The object which owns the decorated method.
- Raises:
TypeError – If the value provided is not of the correct type.
ValueError – If the value provided is of the correct type but has an invalid value.
AttributeError – If the check depends on an attribute on the parent object of the decorated method, and it does not exist.
- class carta.validation.Size
Bases:
Union
A representation of an angular size or a size in pixels. Can be a number or a numeric string with valid size units. A number is assumed to be a pixel value. Validates strings using
carta.util.AngularSize
.- class AngularSize(regex=None, flags=0)
Bases:
String
Helper validator class which uses
carta.util.AngularSize
to validate strings.- validate(value, parent)
Check if the value can be parsed as an angular size.
See
carta.validation.Parameter.validate
for general information about this method.
- class carta.validation.String(regex=None, flags=0)
Bases:
Parameter
A string parameter.
- Parameters:
regex (str, optional) – A regular expression string which the parameter must match.
flags (int, optional) – The flags to use when matching the regular expression. Set to zero (no flags) by default.
- Variables:
regex (str) – A regular expression string which the parameter must match.
flags (int) – The flags to use when matching the regular expression.
- property description
A human-readable description of this parameter descriptor.
- Returns:
The description.
- Return type:
string
- validate(value, parent)
Check if the value is a string and if it matches a regex if one was provided.
See
carta.validation.Parameter.validate
for general information about this method.
- class carta.validation.TupleColor
Bases:
Parameter
An HTML color tuple. Not intended to be used directly; you probably want
carta.validation.Color
instead.- property description
A human-readable description of this parameter descriptor.
- Returns:
The description.
- Return type:
string
- validate(value, parent)
Check if the value can be parsed as a color tuple, and validate the tuple elements.
See
carta.validation.Parameter.validate
for general information about this method.
- class carta.validation.Union(*options, description=None)
Bases:
Parameter
A union of other parameter descriptors.
- Parameters:
*options (iterable of
carta.validation.Parameter
objects) – An iterable of valid descriptors for this parameter.description (str, optional) – A custom description. The default is generated from the descriptions of the provided options.
- Variables:
options (iterable of
carta.validation.Parameter
objects) – An iterable of valid descriptors for this parameter.
- property description
A human-readable description of this parameter descriptor.
- Returns:
The description.
- Return type:
string
- validate(value, parent)
Check if the value can be validated with one of the provided descriptors. The descriptors are evaluated in the order that they are given, and the function exits after the first successful validation.
See
carta.validation.Parameter.validate
for general information about this method.
- carta.validation.all_optional(*vargs)
Wrapper to make all parameters in an iterable optional.
For improved legibility in functions with many sequential optional parameters. Can also enable reuse of validation parameters in functions which call other functions.
- Parameters:
*vargs (iterable of
carta.validation.Parameter
objects)- Returns:
The same parameters in the same order, but with all non-optional parameters made optional (that is, wrapped in a obj:carta.validation.NoneOr parameter).
- Return type:
iterable of
carta.validation.Parameter
objects
- carta.validation.validate(*vargs)
The function which returns the decorator used to validate method parameters.
It is assumed that the function to be decorated is an object method and the first parameter is
self
; this parameter is therefore ignored by the decorator. The remaining positional parameters are validated in order using the provided descriptors. The descriptors are also combined pairwise with the parameter names in the signature of the original function to create a dictionary for validating keyword parameters.Functions with
*args
or**kwargs
are not currently supported: use iterables and explicit keyword parameters instead.The decorator inserts the descriptions of the parameters into the docstring of the decorated function, if placeholders have been left for them in the original docstring. The descriptions are passed as positional parameters to
str.format
.The
self
parameter is passed into the validation method of each descriptor, so that checks can depend on properties to be evaluated at runtime (this is currently used bycarta.validation.Evaluate
).The decorated function raises a
carta.util.CartaValidationFailed
if one of the parameters fails to validate.- Parameters:
*vargs (iterable of
carta.validation.Parameter
objects) – Descriptors to be used to validate the function parameters, in the same order as the parameters.- Returns:
The decorator function.
- Return type:
function
carta.vector_overlay module
This module contains functionality for interacting with the vector overlay of an image. The class in this module should not be instantiated directly. When an image object is created, a vector overlay object is automatically created as a property.
- class carta.vector_overlay.VectorOverlay(image)
Bases:
BasePathMixin
Utility object for collecting image functions related to the vector overlay.
- Parameters:
image (
carta.image.Image
object) – The image associated with this vector overlay.- Variables:
image (
carta.image.Image
object) – The image associated with this vector overlay.session (
carta.session.Session
object) – The session object associated with this vector overlay.
- apply()
Apply the vector overlay configuration.
- clear()
Clear the vector overlay configuration.
- configure(angular_source=None, intensity_source=None, pixel_averaging_enabled=None, pixel_averaging=None, fractional_intensity=None, threshold_enabled=None, threshold=None, debiasing=None, q_error=None, u_error=None)
Configure vector overlay.
All parameters are optional. For each option that is not provided, the value currently set in the frontend will be preserved. Initial frontend settings are noted below.
We deduce some boolean options. For example, providing an explicit pixel averaging width with the pixel_averaging parameter will automatically enable pixel averaging unless pixel_averaging_enabled is also explicitly set to
False
. To disable pixel averaging, explicitly set pixel_averaging_enabled toFalse
.- Parameters:
angular_source (a member of
carta.constants.VectorOverlaySource
orNone
) – The angular source. This is initially set to computed PA if the image contains Stokes information, otherwise to the current image.intensity_source (a member of
carta.constants.VectorOverlaySource
orNone
) – The intensity source. This is initially set to computed PI if the image contains Stokes information, otherwise to the current image.pixel_averaging_enabled (a boolean or
None
) – Enable pixel averaging. This is initially enabled if the pixel averaging width is positive.pixel_averaging (a number or
None
) – The pixel averaging width in pixels. The initial value can be configured in the frontend preferences (the default is4
).fractional_intensity (a number or
None
) – Enable fractional polarization intensity. The initial value can be configured in the frontend preferences. By default this is disabled and the absolute polarization intensity is used.threshold_enabled (a boolean or
None
) – Enable threshold. Initially the threshold is disabled.threshold (a number or
None
) – The threshold in Jy/pixels. The initial value is zero.debiasing (a boolean or
None
) – Enable debiasing. This is initially disabled.q_error (a number or
None
) – The Stokes Q error in Jy/beam. Set both this andu_error
to enable debiasing. Initially set to zero.u_error (a number or
None
) – The Stokes U error in Jy/beam. Set both this andq_error
to enable debiasing. Initially set to zero.
- hide()
Hide the vector overlay.
- plot(angular_source=None, intensity_source=None, pixel_averaging_enabled=None, pixel_averaging=None, fractional_intensity=None, threshold_enabled=None, threshold=None, debiasing=None, q_error=None, u_error=None, thickness=None, intensity_min=None, intensity_max=None, length_min=None, length_max=None, rotation_offset=None, color=None, colormap=None, bias=None, contrast=None)
Set the vector overlay configuration, styling and color or colormap; and apply vector overlay; in a single step.
If both a color and a colormap are provided, the colormap will be enabled.
- Parameters:
angular_source (a member of
carta.constants.VectorOverlaySource
orNone
) – The angular source. This is initially set to computed PA if the image contains Stokes information, otherwise to the current image.intensity_source (a member of
carta.constants.VectorOverlaySource
orNone
) – The intensity source. This is initially set to computed PI if the image contains Stokes information, otherwise to the current image.pixel_averaging_enabled (a boolean or
None
) – Enable pixel averaging. This is initially enabled if the pixel averaging width is positive.pixel_averaging (a number or
None
) – The pixel averaging width in pixels. The initial value can be configured in the frontend preferences (the default is4
).fractional_intensity (a number or
None
) – Enable fractional polarization intensity. The initial value can be configured in the frontend preferences. By default this is disabled and the absolute polarization intensity is used.threshold_enabled (a boolean or
None
) – Enable threshold. Initially the threshold is disabled.threshold (a number or
None
) – The threshold in Jy/pixels. The initial value is zero.debiasing (a boolean or
None
) – Enable debiasing. This is initially disabled.q_error (a number or
None
) – The Stokes Q error in Jy/beam. Set both this andu_error
to enable debiasing. Initially set to zero.u_error (a number or
None
) – The Stokes U error in Jy/beam. Set both this andq_error
to enable debiasing. Initially set to zero.thickness (a number or
None
) – The line thickness in pixels. The initial value is1
.intensity_min (a number or a member of
carta.constants.Auto
orNone
) – The minimum value of intensity in Jy/pixel. Usecarta.constants.Auto.AUTO
to clear the custom value and calculate it automatically.intensity_max (a number or a member of
carta.constants.Auto
orNone
) – The maximum value of intensity in Jy/pixel. Usecarta.constants.Auto.AUTO
to clear the custom value and calculate it automatically.length_min (a number or
None
) – The minimum value of line length in pixels. The initial value is0
.length_max (a number or
None
) – The maximum value of line length in pixels. The initial value is20
.rotation_offset (a number or
None
) – The rotation offset in degrees. The initial value is0
.color (an HTML color specification or
None
) – The color. The initial value value is#238551
(a shade of green).colormap (a member of
carta.constants.Colormap
orNone
) – The colormap. The initial value iscarta.constants.Colormap.VIRIDIS
.bias (a number greater than or equal to
-1
and smaller than or equal to1
orNone
) – The colormap bias. The initial value is0
.contrast (a number greater than or equal to
0
and smaller than or equal to2
orNone
) – The colormap contrast. The initial value is1
.
- set_color(color)
Set the vector overlay color.
This automatically disables use of the vector overlay colormap.
- Parameters:
color (an HTML color specification) – The color. The initial value is
#238551
(a shade of green).
- set_colormap(colormap=None, bias=None, contrast=None)
Set the vector overlay colormap and/or the colormap options.
- Parameters:
colormap (a member of
carta.constants.Colormap
orNone
) – The colormap. The initial value iscarta.constants.Colormap.VIRIDIS
. If this parameter is set, the overlay colormap is automatically enabled.bias (a number greater than or equal to
-1
and smaller than or equal to1
orNone
) – The colormap bias. The initial value is0
.contrast (a number greater than or equal to
0
and smaller than or equal to2
orNone
) – The colormap contrast. The initial value is1
.
- set_style(thickness=None, intensity_min=None, intensity_max=None, length_min=None, length_max=None, rotation_offset=None)
Set the styling (line thickness, intensity range, line length range, rotation offset) of vector overlay.
- Parameters:
thickness (a number or
None
) – The line thickness in pixels. The initial value is1
.intensity_min (a number or a member of
carta.constants.Auto
orNone
) – The minimum value of intensity in Jy/pixel. Usecarta.constants.Auto.AUTO
to clear the custom value and calculate it automatically.intensity_max (a number or a member of
carta.constants.Auto
orNone
) – The maximum value of intensity in Jy/pixel. Usecarta.constants.Auto.AUTO
to clear the custom value and calculate it automatically.length_min (a number or
None
) – The minimum value of line length in pixels. The initial value is0
.length_max (a number or
None
) – The maximum value of line length in pixels. The initial value is20
.rotation_offset (a number or
None
) – The rotation offset in degrees. The initial value is0
.
- set_visible(state)
Set the vector overlay visibility.
- Parameters:
state (a boolean) – The desired visibility state.
- show()
Show the vector overlay.