Exemple #1
0
def test_get_ligolw_element():
    from ligo.lw.ligolw import (Document, LIGO_LW)
    xmldoc = Document()
    llw = xmldoc.appendChild(LIGO_LW())
    assert io_ligolw.get_ligolw_element(llw) is llw
    assert io_ligolw.get_ligolw_element(xmldoc) is llw
    with pytest.raises(ValueError):
        io_ligolw.get_ligolw_element(Document())
Exemple #2
0
def test_get_ligolw_element():
    from ligo.lw.ligolw import (Document, LIGO_LW)
    xmldoc = Document()
    llw = xmldoc.appendChild(LIGO_LW())
    assert io_ligolw.get_ligolw_element(llw) is llw
    assert io_ligolw.get_ligolw_element(xmldoc) is llw
    with pytest.raises(ValueError):
        io_ligolw.get_ligolw_element(Document())
Exemple #3
0
def llwtable():
    from ligo.lw.ligolw import (Document, LIGO_LW)

    # build dummy document with two tables
    xmldoc = Document()
    llw = xmldoc.appendChild(LIGO_LW())
    tables = [new_table('process'), new_table('sngl_ringdown')]
    for t in tables:
        llw.appendChild(t)
    return xmldoc
Exemple #4
0
def llwtable():
    from ligo.lw.ligolw import (Document, LIGO_LW)

    # build dummy document with two tables
    xmldoc = Document()
    llw = xmldoc.appendChild(LIGO_LW())
    tables = [new_table('process'), new_table('sngl_ringdown')]
    for t in tables:
        llw.appendChild(t)
    return xmldoc
Exemple #5
0
def write_tables(target, tables, append=False, overwrite=False, **kwargs):
    """Write an LIGO_LW table to file

    Parameters
    ----------
    target : `str`, `file`, :class:`~ligo.lw.ligolw.Document`
        the file or document to write into

    tables : `list`, `tuple` of :class:`~ligo.lw.table.Table`
        the tables to write

    append : `bool`, optional, default: `False`
        if `True`, append to an existing file/table, otherwise `overwrite`

    overwrite : `bool`, optional, default: `False`
        if `True`, delete an existing instance of the table type, otherwise
        append new rows

    **kwargs
        other keyword arguments to pass to
        :func:`~ligo.lw.utils.load_filename`, or
        :func:`~ligo.lw.utils.load_fileobj` as appropriate
    """
    from ligo.lw.ligolw import (Document, LIGO_LW, LIGOLWContentHandler)
    from ligo.lw import utils as ligolw_utils

    # allow writing directly to XML
    if isinstance(target, (Document, LIGO_LW)):
        xmldoc = target
    # open existing document, if possible
    elif append:
        xmldoc = open_xmldoc(target,
                             contenthandler=kwargs.pop('contenthandler',
                                                       LIGOLWContentHandler))
    # fail on existing document and not overwriting
    elif (not overwrite and isinstance(target, str)
          and os.path.isfile(target)):
        raise IOError("File exists: {}".format(target))
    else:  # or create a new document
        xmldoc = Document()

    # convert table to format
    write_tables_to_document(xmldoc, tables, overwrite=overwrite)

    # find writer function and target filename
    if isinstance(target, FILE_LIKE):
        writer = ligolw_utils.write_fileobj
        name = target.name
    else:
        writer = ligolw_utils.write_filename
        name = str(target)

    # handle gzip compression kwargs
    if name.endswith('.gz') and writer.__module__.startswith('glue'):
        kwargs.setdefault('gz', True)
    elif name.endswith('.gz'):
        kwargs.setdefault('compress', 'gz')

    # write XML
    writer(xmldoc, target, **kwargs)
Exemple #6
0
def read_ligolw(source, contenthandler=LIGOLWContentHandler, **kwargs):
    """Read one or more LIGO_LW format files

    Parameters
    ----------
    source : `str`, `file`
        the open file or file path to read

    contenthandler : `~xml.sax.handler.ContentHandler`, optional
        content handler used to parse document

    verbose : `bool`, optional
        be verbose when reading files, default: `False`

    Returns
    -------
    xmldoc : :class:`~ligo.lw.ligolw.Document`
        the document object as parsed from the file(s)
    """
    from ligo.lw.ligolw import Document
    from ligo.lw import types
    from ligo.lw.lsctables import use_in
    from ligo.lw.utils import (load_url, ligolw_add)

    # mock ToPyType to link to numpy dtypes
    topytype = types.ToPyType.copy()
    for key in types.ToPyType:
        if key in types.ToNumPyType:
            types.ToPyType[key] = numpy.dtype(types.ToNumPyType[key]).type

    contenthandler = use_in(contenthandler)

    # read one or more files into a single Document
    source = file_list(source)
    try:
        if len(source) == 1:
            return load_url(source[0], contenthandler=contenthandler, **kwargs)
        return ligolw_add.ligolw_add(Document(),
                                     source,
                                     contenthandler=contenthandler,
                                     **kwargs)
    except LigolwElementError as exc:
        # failed to read with ligo.lw,
        # try again with glue.ligolw (ilwdchar_compat)
        if LIGO_LW_COMPAT_ERROR.search(str(exc)):
            try:
                return read_ligolw(source,
                                   contenthandler=contenthandler,
                                   ilwdchar_compat=True,
                                   **kwargs)
            except Exception:  # if fails for any reason, use original error
                pass
        raise
    finally:  # replace ToPyType
        types.ToPyType = topytype
Exemple #7
0
def open_xmldoc(fobj, **kwargs):
    """Try and open an existing LIGO_LW-format file, or create a new Document

    Parameters
    ----------
    fobj : `str`, `file`
        file path or open file object to read

    **kwargs
        other keyword arguments to pass to
        :func:`~ligo.lw.utils.load_filename`, or
        :func:`~ligo.lw.utils.load_fileobj` as appropriate

    Returns
    --------
    xmldoc : :class:`~ligo.lw.ligolw.Document`
        either the `Document` as parsed from an existing file, or a new, empty
        `Document`
    """
    from ligo.lw.ligolw import (Document, LIGOLWContentHandler)
    from ligo.lw.lsctables import use_in
    from ligo.lw.utils import (load_filename, load_fileobj)

    use_in(kwargs.setdefault('contenthandler', LIGOLWContentHandler))

    try:  # try and load existing file
        if isinstance(fobj, str):
            return load_filename(fobj, **kwargs)
        if isinstance(fobj, FILE_LIKE):
            return load_fileobj(fobj, **kwargs)[0]
    except (OSError, IOError):  # or just create a new Document
        return Document()
    except LigolwElementError as exc:
        if LIGO_LW_COMPAT_ERROR.search(str(exc)):
            try:
                return open_xmldoc(fobj, ilwdchar_compat=True, **kwargs)
            except Exception:  # for any reason, raise original
                pass
        raise