voevent-parse API reference¶
Warning
Much of the content within assumes the reader has at least a summary understanding of the VOEvent specifications.
Note
The top-level __init__.py
file imports key classes and subroutines
into the top-level voeventparse
namespace, for brevity.
voeventparse.voevent
- Basic VOEvent packet manipulation¶
Routines for handling etrees representing VOEvent packets.
-
voeventparse.voevent.
Voevent
(stream, stream_id, role)[source]¶ Create a new VOEvent element tree, with specified IVORN and role.
Parameters: - stream (str) –
used to construct the IVORN like so:
ivorn = 'ivo://' + stream + '#' + stream_id
(N.B.
stream_id
is converted to string if required.) So, e.g. we might set:stream='voevent.soton.ac.uk/super_exciting_events' stream_id=77
- stream_id (str) – See above.
- role (str) – role as defined in VOEvent spec.
(See also
definitions.roles
)
Returns: Root-node of the VOEvent, as represented by an lxml.objectify element tree (‘etree’). See also http://lxml.de/objectify.html#the-lxml-objectify-api
- stream (str) –
-
voeventparse.voevent.
loads
(s, check_version=True)[source]¶ Load VOEvent from bytes.
This parses a VOEvent XML packet string, taking care of some subtleties. For Python 3 users,
s
should be a bytes object - see also http://lxml.de/FAQ.html, “Why can’t lxml parse my XML from unicode strings?” (Python 2 users can stick with old-schoolstr
type if preferred)By default, will raise an exception if the VOEvent is not of version 2.0. This can be disabled but voevent-parse routines are untested with other versions.
Parameters: Returns: Root-node of the etree.
Return type: Raises: ValueError
– If passed a VOEvent of wrong schema version (i.e. schema 1.1)
-
voeventparse.voevent.
load
(file, check_version=True)[source]¶ Load VOEvent from file object.
A simple wrapper to read a file before passing the contents to
loads()
. Use with an open file object, e.g.:with open('/path/to/voevent.xml', 'rb') as f: v = vp.load(f)
Parameters: - file (io.IOBase) – An open file object (binary mode preferred), see also http://lxml.de/FAQ.html : “Can lxml parse from file objects opened in unicode/text mode?”
- check_version (bool) – (Default=True) Checks that the VOEvent is of a supported schema version - currently only v2.0 is supported.
Returns: Root-node of the etree.
Return type:
-
voeventparse.voevent.
dumps
(voevent, pretty_print=False, xml_declaration=True, encoding='UTF-8')[source]¶ Converts voevent to string.
Note
Default encoding is UTF-8, in line with VOE2.0 schema. Declaring the encoding can cause diffs with the original loaded VOEvent, but I think it’s probably the right thing to do (and lxml doesn’t really give you a choice anyway).
Parameters: - voevent (
Voevent
) – Root node of the VOevent etree. - pretty_print (bool) – indent the output for improved human-legibility when possible. See also: http://lxml.de/FAQ.html#why-doesn-t-the-pretty-print-option-reformat-my-xml-output
- xml_declaration (bool) – Prepends a doctype tag to the string output,
i.e. something like
<?xml version='1.0' encoding='UTF-8'?>
Returns: Bytestring containing raw XML representation of VOEvent.
Return type: - voevent (
-
voeventparse.voevent.
dump
(voevent, file, pretty_print=True, xml_declaration=True)[source]¶ Writes the voevent to the file object.
e.g.:
with open('/tmp/myvoevent.xml','wb') as f: voeventparse.dump(v, f)
Parameters:
-
voeventparse.voevent.
valid_as_v2_0
(voevent)[source]¶ Tests if a voevent conforms to the schema.
Parameters: voevent ( Voevent
) – Root node of a VOEvent etree.Returns: Whether VOEvent is valid Return type: bool
-
voeventparse.voevent.
assert_valid_as_v2_0
(voevent)[source]¶ Raises
lxml.etree.DocumentInvalid
if voevent is invalid.Especially useful for debugging, since the stack trace contains a reason for the invalidation.
Parameters: voevent ( Voevent
) – Root node of a VOEvent etree.Raises: lxml.etree.DocumentInvalid
– if VOEvent does not conform to schema.
-
voeventparse.voevent.
set_who
(voevent, date=None, author_ivorn=None)[source]¶ Sets the minimal ‘Who’ attributes: date of authoring, AuthorIVORN.
Parameters: - voevent (
Voevent
) – Root node of a VOEvent etree. - date (datetime.datetime) – Date of authoring. NB Microseconds are ignored, as per the VOEvent spec.
- author_ivorn (str) – Short author identifier,
e.g.
voevent.4pisky.org/ALARRM
. Note that the prefixivo://
will be prepended internally.
- voevent (
For setting fields in the detailed author description.
This can optionally be neglected if a well defined AuthorIVORN is supplied.
Note
Unusually for this library, the args here use CamelCase naming convention, since there’s a direct mapping to the
Author.*
attributes to which they will be assigned.Parameters: voevent ( Voevent
) – Root node of a VOEvent etree. The rest of the arguments are strings corresponding to child elements.
-
voeventparse.voevent.
add_where_when
(voevent, coords, obs_time, observatory_location, allow_tz_naive_datetime=False)[source]¶ Add details of an observation to the WhereWhen section.
We
Parameters: - voevent (
Voevent
) – Root node of a VOEvent etree. - coords (
Position2D
) – Sky co-ordinates of event. - obs_time (datetime.datetime) – Nominal DateTime of the observation. Must
either be timezone-aware, or should be carefully verified as
representing UTC and then set parameter
allow_tz_naive_datetime=True
. - observatory_location (str) – Telescope locale, e.g. ‘La Palma’.
May be a generic location as listed under
voeventparse.definitions.observatory_location
. - allow_tz_naive_datetime (bool) – (Default False). Accept timezone-naive
datetime-timestamps. See comments for
obs_time
.
- voevent (
-
voeventparse.voevent.
add_how
(voevent, descriptions=None, references=None)[source]¶ Add descriptions or references to the How section.
Parameters: - voevent (
Voevent
) – Root node of a VOEvent etree. - descriptions (str) – Description string, or list of description strings.
- references (
voeventparse.misc.Reference
) – A reference element (or list thereof).
- voevent (
-
voeventparse.voevent.
add_why
(voevent, importance=None, expires=None, inferences=None)[source]¶ Add Inferences, or set importance / expires attributes of the Why section.
Note
importance
/expires
are ‘Why’ attributes, therefore setting them will overwrite previous values.inferences
, on the other hand, are appended to the list.Parameters: - voevent (
Voevent
) – Root node of a VOEvent etree. - importance (float) – Value from 0.0 to 1.0
- expires (datetime.datetime) – Expiration date given inferred reason (See voevent spec).
- inferences (
voeventparse.misc.Inference
) – Inference or list of inferences, denoting probable identifications or associations, etc.
- voevent (
-
voeventparse.voevent.
add_citations
(voevent, event_ivorns)[source]¶ Add citations to other voevents.
The schema mandates that the ‘Citations’ section must either be entirely absent, or non-empty - hence we require this wrapper function for its creation prior to listing the first citation.
Parameters: - voevent (
Voevent
) – Root node of a VOEvent etree. - event_ivorns (
voeventparse.misc.EventIvorn
) – List of EventIvorn elements to add to citation list.
- voevent (
voeventparse.misc
- Subtree-elements and other helpers¶
Routines for creating sub-elements of the VOEvent tree, and a few other helper classes.
-
class
voeventparse.misc.
Position2D
[source]¶ A namedtuple for simple representation of a 2D position as described by the VOEvent spec.
Parameters: - ra (float) – Right ascension.
- dec (float) – Declination
- err (float) – Error radius.
- units (str) – Coordinate units, cf
definitions.units
e.g. degrees, radians. - system (str) – Co-ordinate system, e.g. UTC-FK5-GEO
cf
definitions.sky_coord_system
-
voeventparse.misc.
Param
(name, value=None, unit=None, ucd=None, dataType=None, utype=None, ac=True)[source]¶ ‘Parameter’, used as a general purpose key-value entry in the ‘What’ section.
May be assembled into a
Group
.NB
name
is not mandated by schema, but is mandated in full spec.Parameters: - value (str) –
String representing parameter value. Or, if
ac
is true, then ‘autoconversion’ is attempted, in which casevalue
can also be an instance of one of the following:This allows you to create Params without littering your code with string casts, or worrying if the passed value is a float or a string, etc. NB the value is always stored as a string representation, as per VO spec.
- unit (str) – Units of value. See
definitions.units
- ucd (str) – unified content descriptor. For a list of valid UCDs, see: http://vocabularies.referata.com/wiki/Category:IVOA_UCD.
- dataType (str) – Denotes type of
value
; restricted to 3 options:string
(default),int
, orfloat
. (NB not to be confused with standard XML Datatypes, which have many more possible values.) - utype (str) – See http://wiki.ivoa.net/twiki/bin/view/IVOA/Utypes
- ac (bool) – Attempt automatic conversion of passed
value
to string, and setdataType
accordingly (only attempted ifdataType
is the default, i.e.None
). (NB only supports types listed in _datatypes_autoconversion dict)
- value (str) –
-
voeventparse.misc.
Group
(params, name=None, type=None)[source]¶ Groups together Params for adding under the ‘What’ section.
Parameters:
-
voeventparse.misc.
Reference
(uri, meaning=None)[source]¶ Represents external information, typically original obs data and metadata.
Parameters:
-
voeventparse.misc.
Inference
(probability=None, relation=None, name=None, concept=None)[source]¶ Represents a probable cause / relation between this event and some prior.
Parameters: - probability (float) – Value 0.0 to 1.0.
- relation (str) – e.g. ‘associated’ or ‘identified’ (see Voevent spec)
- name (str) – e.g. name of identified progenitor.
- concept (str) – One of a ‘formal UCD-like vocabulary of astronomical concepts’, e.g. http://ivoat.ivoa.net/stars.supernova.Ia - see VOEvent spec.
-
voeventparse.misc.
EventIvorn
(ivorn, cite_type)[source]¶ Used to cite earlier VOEvents.
Use in conjunction with
add_citations()
Parameters: - ivorn (str) – It is assumed this will be copied verbatim from elsewhere, and so these should have any prefix (e.g. ‘ivo://’,’http://’) already in place - the function will not alter the value.
- cite_type (
definitions.cite_types
) – String conforming to one of the standard citation types.
-
voeventparse.misc.
Citation
(ivorn, cite_type)[source]¶ Deprecated alias of
EventIvorn()
voeventparse.convenience
- Convenience routines¶
Convenience routines for common actions on VOEvent objects
-
voeventparse.convenience.
get_event_time_as_utc
(voevent, index=0)[source]¶ Extracts the event time from a given WhereWhen.ObsDataLocation.
Returns a datetime (timezone-aware, UTC).
Accesses a WhereWhere.ObsDataLocation.ObservationLocation element and returns the AstroCoords.Time.TimeInstant.ISOTime element, converted to a (UTC-timezoned) datetime.
Note that a packet may include multiple ‘ObsDataLocation’ entries under the ‘WhereWhen’ section, for example giving locations of an object moving over time. Most packets will have only one, however, so the default is to access the first.
This function now implements conversion from the TDB (Barycentric Dynamical Time) time scale in ISOTime format, since this is the format used by GAIA VOEvents. (See also http://docs.astropy.org/en/stable/time/#time-scale )
Other timescales (i.e. TT, GPS) will presumably be formatted as a TimeOffset, parsing this format is not yet implemented.
Parameters: - voevent (
voeventparse.voevent.Voevent
) – Root node of the VOevent etree. - index (int) – Index of the ObsDataLocation to extract an ISOtime from.
Returns: Datetime representing the event-timestamp, converted to UTC (timezone aware).
Return type: - voevent (
-
voeventparse.convenience.
get_event_position
(voevent, index=0)[source]¶ Extracts the AstroCoords from a given WhereWhen.ObsDataLocation.
Note that a packet may include multiple ‘ObsDataLocation’ entries under the ‘WhereWhen’ section, for example giving locations of an object moving over time. Most packets will have only one, however, so the default is to just return co-ords extracted from the first.
Parameters: - voevent (
voeventparse.voevent.Voevent
) – Root node of the VOEvent etree. - index (int) – Index of the ObsDataLocation to extract AstroCoords from.
Returns: The sky position defined in the ObsDataLocation.
Return type: Position (
Position2D
)- voevent (
-
voeventparse.convenience.
get_grouped_params
(voevent)[source]¶ Fetch grouped Params from the What section of a voevent as an omdict.
This fetches ‘grouped’ Params, i.e. those enclosed in a Group element, and returns them as a nested dict-like structure, keyed by GroupName->ParamName->AttribName.
Note that since multiple Params may share the same ParamName, the returned data-structure is actually an orderedmultidict.omdict and has extra methods such as ‘getlist’ to allow retrieval of all values.
Parameters: voevent ( voeventparse.voevent.Voevent
) – Root node of the VOevent etree.- Returns (orderedmultidict.omdict):
Mapping of
ParamName->Attribs
. Typical access like so:foo_val = top_params['foo']['value'] # If there are multiple Param entries named 'foo': all_foo_vals = [atts['value'] for atts in top_params.getlist('foo')]
-
voeventparse.convenience.
get_toplevel_params
(voevent)[source]¶ Fetch ungrouped Params from the What section of a voevent as an omdict.
This fetches ‘toplevel’ Params, i.e. those not enclosed in a Group element, and returns them as a nested dict-like structure, keyed like ParamName->AttribName.
Note that since multiple Params may share the same ParamName, the returned data-structure is actually an orderedmultidict.omdict and has extra methods such as ‘getlist’ to allow retrieval of all values.
Any Params with no defined name (technically off-spec, but not invalidated by the XML schema) are returned under the dict-key
None
.Parameters: voevent ( voeventparse.voevent.Voevent
) – Root node of the VOevent etree.- Returns (orderedmultidict.omdict):
Mapping of
ParamName->Attribs
. Typical access like so:foo_val = top_params['foo']['value'] # If there are multiple Param entries named 'foo': all_foo_vals = [atts['value'] for atts in top_params.getlist('foo')]
-
voeventparse.convenience.
pull_astro_coords
(voevent, index=0)[source]¶ Deprecated alias of
get_event_position()
-
voeventparse.convenience.
pull_isotime
(voevent, index=0)[source]¶ Deprecated alias of
get_event_time_as_utc()
-
voeventparse.convenience.
pull_params
(voevent)[source]¶ Attempts to load the What section of a voevent as a nested dictionary.
Warning
Deprecated due to Missing name attributes issues.
Param or Group entries which are missing the name attribute will be entered under a dictionary key of
None
. This means that if there are multiple entries missing the name attribute then earlier entries will be overwritten by later entries, so you will not be able to use this convenience routine effectively. Useget_grouped_params()
andget_toplevel_params()
instead.Parameters: voevent ( voeventparse.voevent.Voevent
) – Root node of the VOevent etree.Returns: Mapping of Group->Param->Attribs
. Access like so:foo_param_val = what_dict['GroupName']['ParamName']['value']
Note
Parameters without a group are indexed under the key ‘None’ - otherwise, we might get name-clashes between params and groups (unlikely but possible) so for ungrouped Params you’ll need something like:
what_dict[None]['ParamName']['value']
Return type: dict
-
voeventparse.convenience.
prettystr
(subtree)[source]¶ Print an element tree with nice indentation.
Prettyprinting a whole VOEvent often doesn’t seem to work, probably for issues relating to whitespace cf. http://lxml.de/FAQ.html#why-doesn-t-the-pretty-print-option-reformat-my-xml-output This function is a quick workaround for prettyprinting a subsection of a VOEvent, for easier desk-checking.
Parameters: subtree( – class`lxml.etree.ElementTree`): A node in the VOEvent element tree. Returns: Prettyprinted string representation of the raw XML. Return type: str
voeventparse.definitions
- Standard or common string values¶
This module simply serves to store the XML schema, a ‘skeleton’ VOEvent xml document for creation of new instances, and various other minor definitions.
These values may be used in place of literal strings, to allow autocompletion and document the fact that they are ‘standardized’ values.
-
class
voeventparse.definitions.
roles
[source]¶ -
observation
= 'observation'¶
-
prediction
= 'prediction'¶
-
utility
= 'utility'¶
-
test
= 'test'¶
-
-
class
voeventparse.definitions.
sky_coord_system
[source]¶ Common coordinate system identifiers. See also
Position2D
.This is not a simple combinatorial mix of all components, it’s a reproduction of the enumeration in the XML schema. Note some entries in the schema enumeration are repeated, which leads me to think it may be flawed, but that’s an investigation for another day.
-
gps_fk5_topo
= 'GPS-FK5-TOPO'¶
-
gps_icrs_geo
= 'GPS-ICRS-GEO'¶
-
gps_icrs_topo
= 'GPS-ICRS-TOPO'¶
-
tdb_fk5_bary
= 'TDB-FK5-BARY'¶
-
tdb_icrs_bary
= 'TDB-ICRS-BARY'¶
-
tt_fk5_geo
= 'TT-FK5-GEO'¶
-
tt_fk5_topo
= 'TT-FK5-TOPO'¶
-
tt_icrs_geo
= 'TT-ICRS-GEO'¶
-
tt_icrs_topo
= 'TT-ICRS-TOPO'¶
-
utc_fk5_geo
= 'UTC-FK5-GEO'¶
-
utc_fk5_topo
= 'UTC-FK5-TOPO'¶
-
utc_icrs_geo
= 'UTC-ICRS-GEO'¶
-
utc_icrs_topo
= 'UTC-ICRS-TOPO'¶
-
-
class
voeventparse.definitions.
observatory_location
[source]¶ Common generic values for the WhereWhen.ObservatoryLocation attribute.
-
geosurface
= 'GEOSURFACE'¶
-
geolunar
= 'GEOLUN'¶
-
-
class
voeventparse.definitions.
units
[source]¶ Unit abbreviations as defined by CDS (incomplete listing)
cf http://vizier.u-strasbg.fr/doc/catstd-3.2.htx
-
degree
= 'deg'¶
-
degrees
= 'deg'¶
-
arcsecond
= 'arcsec'¶
-
milliarcsecond
= 'mas'¶
-
day
= 'd'¶
-
hour
= 'h'¶
-
minute
= 'min'¶
-
year
= 'yr'¶
-
count
= 'ct'¶
-
hertz
= 'Hz'¶
-
jansky
= 'Jy'¶
-
magnitude
= 'mag'¶
-