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 (string) –

    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 (string) – See above.
  • role (string) – 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

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-school str 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:
  • s (bytes) – Bytes containing raw XML.
  • check_version (bool) – (Default=True) Checks that the VOEvent is of a supported schema version - currently only v2.0 is supported.
Returns:

voevent – Root-node of the etree.

Return type:

Voevent

Raises:

exceptions.ValueError

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 (file) – 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:

voevent – Root-node of the etree.

Return type:

Voevent

voeventparse.voevent.dumps(voevent, pretty_print=False, xml_declaration=True, encoding=u'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:
Returns:

Bytes containing raw XML representation of 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:
  • voevent (Voevent) – Root node of the VOevent etree.
  • file (file) – An open (binary mode) file object for writing.
  • pretty_print (bool) –
  • pretty_print – See dumps()
  • xml_declaration (bool) – See dumps()
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: Bool (VOEvent is valid?)

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.
Returns: None. NB 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 (string) – Short author identifier, e.g. voevent.4pisky.org/ALARRM. Note that the prefix ivo:// will be prepended internally.
voeventparse.voevent.set_author(voevent, title=None, shortName=None, logoURL=None, contactName=None, contactEmail=None, contactPhone=None, contributor=None)[source]

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)[source]

Add details of an observation to the WhereWhen section.

Parameters:
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 (string) – Description string, or list of description strings.
  • references (voeventparse.misc.Reference) – A reference element (or list thereof).
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.
voeventparse.voevent.add_citations(voevent, citations)[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:

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:
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 (string) –

    String representing parameter value. Or, if ac is true, then ‘autoconversion’ is attempted, in which case value 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 (string) – Units of value. See definitions.units
  • ucd (string) – unified content descriptor. For a list of valid UCDs, see: http://vocabularies.referata.com/wiki/Category:IVOA_UCD.
  • dataType (string) – Denotes type of value; restricted to 3 options: string (default), int , or float. (NB not to be confused with standard XML Datatypes, which have many more possible values.)
  • utype (string) – See http://wiki.ivoa.net/twiki/bin/view/IVOA/Utypes
  • ac (bool) – Attempt automatic conversion of passed value to string, and set dataType accordingly (only attempted if dataType is the default, i.e. None). (NB only supports types listed in _datatypes_autoconversion dict)
voeventparse.misc.Group(params, name=None, type=None)[source]

Groups together Params for adding under the ‘What’ section.

Parameters:
  • params (list of Param()) – Parameter elements to go in this group.
  • name (string) – Group name. NB None is valid, since the group may be best identified by its type.
  • type (string) – Type of group, e.g. ‘complex’ (for real and imaginary).
voeventparse.misc.Reference(uri, meaning=None)[source]

Represents external information, typically original obs data and metadata.

Parameters:
  • uri (string) – Uniform resource identifier for external data, e.g. FITS file.
  • meaning (string) – The nature of the document referenced, e.g. what instrument and filter was used to create the data?
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 (string) – e.g. ‘associated’ or ‘identified’ (see Voevent spec)
  • name (string) – e.g. name of identified progenitor.
  • concept (string) – One of a ‘formal UCD-like vocabulary of astronomical concepts’, e.g. http://ivoat.ivoa.net/stars.supernova.Ia - see VOEvent spec.
voeventparse.misc.Citation(ivorn, cite_type)[source]

Used to cite earlier VOEvents.

Parameters:
  • ivorn (string) – 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.convenience - Convenience routines

Convenience routines for common actions on VOEvent objects

voeventparse.convenience.pull_astro_coords(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:
Returns:

Position – The sky position defined in the ObsDataLocation.

Return type:

Position2D

voeventparse.convenience.pull_isotime(voevent, index=0)[source]

Extracts the event time from a given WhereWhen.ObsDataLocation.

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.

Warning

This function currently only works with UTC time-system coords. Future updates may implement conversion from other systems (TT, GPS) using astropy functionality.

Parameters:
Returns:

isotime – Datetime object as parsed by iso8601 (with UTC timezone).

Return type:

datetime.datetime

voeventparse.convenience.pull_params(voevent)[source]

Attempts to load the What section of a voevent as a nested dictionary.

Warning

Missing name attributes

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.

Parameters:voevent (voeventparse.voevent.Voevent) – Root node of the VOevent etree.
Returns:Nested dict – 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 (lxml.etree) – A node in the VOEvent element tree.
Returns:Prettyprinted string representation of the raw XML.
Return type:string

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 = u'observation'
prediction = u'prediction'
utility = u'utility'
test = u'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 = u'GPS-FK5-TOPO'
gps_icrs_geo = u'GPS-ICRS-GEO'
gps_icrs_topo = u'GPS-ICRS-TOPO'
tdb_fk5_bary = u'TDB-FK5-BARY'
tdb_icrs_bary = u'TDB-ICRS-BARY'
tt_fk5_geo = u'TT-FK5-GEO'
tt_fk5_topo = u'TT-FK5-TOPO'
tt_icrs_geo = u'TT-ICRS-GEO'
tt_icrs_topo = u'TT-ICRS-TOPO'
utc_fk5_geo = u'UTC-FK5-GEO'
utc_fk5_topo = u'UTC-FK5-TOPO'
utc_icrs_geo = u'UTC-ICRS-GEO'
utc_icrs_topo = u'UTC-ICRS-TOPO'
class voeventparse.definitions.observatory_location[source]

Common generic values for the WhereWhen.ObservatoryLocation attribute.

geosurface = u'GEOSURFACE'
geolunar = u'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 = u'deg'
degrees = u'deg'
arcsecond = u'arcsec'
milliarcsecond = u'mas'
day = u'd'
hour = u'h'
minute = u'min'
year = u'yr'
count = u'ct'
hertz = u'Hz'
jansky = u'Jy'
magnitude = u'mag'
class voeventparse.definitions.cite_types[source]

Possible types of Citation()

followup = u'followup'
supersedes = u'supersedes'
retraction = u'retraction'