1# Licensed under a 3-clause BSD style license - see LICENSE.rst
2# -*- coding: utf-8 -*-
3"""
4.. _warnings:
5
6Warnings
7--------
8
9.. note::
10    Most of the following warnings indicate violations of the VOTable
11    specification.  They should be reported to the authors of the
12    tools that produced the VOTable file.
13
14    To control the warnings emitted, use the standard Python
15    :mod:`warnings` module and the ``astropy.io.votable.exceptions.conf.max_warnings``
16    configuration item.  Most of these are of the type `VOTableSpecWarning`.
17
18{warnings}
19
20.. _exceptions:
21
22Exceptions
23----------
24
25.. note::
26
27    This is a list of many of the fatal exceptions emitted by ``astropy.io.votable``
28    when the file does not conform to spec.  Other exceptions may be
29    raised due to unforeseen cases or bugs in ``astropy.io.votable`` itself.
30
31{exceptions}
32"""
33
34# STDLIB
35import io
36import re
37
38from textwrap import dedent
39from warnings import warn
40
41from astropy import config as _config
42from astropy.utils.exceptions import AstropyWarning
43
44__all__ = [
45    'Conf', 'conf', 'warn_or_raise', 'vo_raise', 'vo_reraise', 'vo_warn',
46    'warn_unknown_attrs', 'parse_vowarning', 'VOWarning',
47    'VOTableChangeWarning', 'VOTableSpecWarning',
48    'UnimplementedWarning', 'IOWarning', 'VOTableSpecError']
49
50
51# NOTE: Cannot put this in __init__.py due to circular import.
52class Conf(_config.ConfigNamespace):
53    """
54    Configuration parameters for `astropy.io.votable.exceptions`.
55    """
56    max_warnings = _config.ConfigItem(
57        10,
58        'Number of times the same type of warning is displayed '
59        'before being suppressed',
60        cfgtype='integer')
61
62
63conf = Conf()
64
65
66def _format_message(message, name, config=None, pos=None):
67    if config is None:
68        config = {}
69    if pos is None:
70        pos = ('?', '?')
71    filename = config.get('filename', '?')
72    return f'{filename}:{pos[0]}:{pos[1]}: {name}: {message}'
73
74
75def _suppressed_warning(warning, config, stacklevel=2):
76    warning_class = type(warning)
77    config.setdefault('_warning_counts', dict()).setdefault(warning_class, 0)
78    config['_warning_counts'][warning_class] += 1
79    message_count = config['_warning_counts'][warning_class]
80    if message_count <= conf.max_warnings:
81        if message_count == conf.max_warnings:
82            warning.formatted_message += \
83                ' (suppressing further warnings of this type...)'
84        warn(warning, stacklevel=stacklevel+1)
85
86
87def warn_or_raise(warning_class, exception_class=None, args=(), config=None,
88                  pos=None, stacklevel=1):
89    """
90    Warn or raise an exception, depending on the verify setting.
91    """
92    if config is None:
93        config = {}
94    # NOTE: the default here is deliberately warn rather than ignore, since
95    # one would expect that calling warn_or_raise without config should not
96    # silence the warnings.
97    config_value = config.get('verify', 'warn')
98    if config_value == 'exception':
99        if exception_class is None:
100            exception_class = warning_class
101        vo_raise(exception_class, args, config, pos)
102    elif config_value == 'warn':
103        vo_warn(warning_class, args, config, pos, stacklevel=stacklevel+1)
104
105
106def vo_raise(exception_class, args=(), config=None, pos=None):
107    """
108    Raise an exception, with proper position information if available.
109    """
110    if config is None:
111        config = {}
112    raise exception_class(args, config, pos)
113
114
115def vo_reraise(exc, config=None, pos=None, additional=''):
116    """
117    Raise an exception, with proper position information if available.
118
119    Restores the original traceback of the exception, and should only
120    be called within an "except:" block of code.
121    """
122    if config is None:
123        config = {}
124    message = _format_message(str(exc), exc.__class__.__name__, config, pos)
125    if message.split()[0] == str(exc).split()[0]:
126        message = str(exc)
127    if len(additional):
128        message += ' ' + additional
129    exc.args = (message,)
130    raise exc
131
132
133def vo_warn(warning_class, args=(), config=None, pos=None, stacklevel=1):
134    """
135    Warn, with proper position information if available.
136    """
137    if config is None:
138        config = {}
139    # NOTE: the default here is deliberately warn rather than ignore, since
140    # one would expect that calling warn_or_raise without config should not
141    # silence the warnings.
142    if config.get('verify', 'warn') != 'ignore':
143        warning = warning_class(args, config, pos)
144        _suppressed_warning(warning, config, stacklevel=stacklevel+1)
145
146
147def warn_unknown_attrs(element, attrs, config, pos, good_attr=[], stacklevel=1):
148    for attr in attrs:
149        if attr not in good_attr:
150            vo_warn(W48, (attr, element), config, pos, stacklevel=stacklevel+1)
151
152
153_warning_pat = re.compile(
154    r":?(?P<nline>[0-9?]+):(?P<nchar>[0-9?]+): " +
155    r"((?P<warning>[WE]\d+): )?(?P<rest>.*)$")
156
157
158def parse_vowarning(line):
159    """
160    Parses the vo warning string back into its parts.
161    """
162    result = {}
163    match = _warning_pat.search(line)
164    if match:
165        result['warning'] = warning = match.group('warning')
166        if warning is not None:
167            result['is_warning'] = (warning[0].upper() == 'W')
168            result['is_exception'] = not result['is_warning']
169            result['number'] = int(match.group('warning')[1:])
170            result['doc_url'] = f"io/votable/api_exceptions.html#{warning.lower()}"
171        else:
172            result['is_warning'] = False
173            result['is_exception'] = False
174            result['is_other'] = True
175            result['number'] = None
176            result['doc_url'] = None
177        try:
178            result['nline'] = int(match.group('nline'))
179        except ValueError:
180            result['nline'] = 0
181        try:
182            result['nchar'] = int(match.group('nchar'))
183        except ValueError:
184            result['nchar'] = 0
185        result['message'] = match.group('rest')
186        result['is_something'] = True
187    else:
188        result['warning'] = None
189        result['is_warning'] = False
190        result['is_exception'] = False
191        result['is_other'] = False
192        result['is_something'] = False
193        if not isinstance(line, str):
194            line = line.decode('utf-8')
195        result['message'] = line
196
197    return result
198
199
200class VOWarning(AstropyWarning):
201    """
202    The base class of all VO warnings and exceptions.
203
204    Handles the formatting of the message with a warning or exception
205    code, filename, line and column number.
206    """
207    default_args = ()
208    message_template = ''
209
210    def __init__(self, args, config=None, pos=None):
211        if config is None:
212            config = {}
213        if not isinstance(args, tuple):
214            args = (args, )
215        msg = self.message_template.format(*args)
216
217        self.formatted_message = _format_message(
218            msg, self.__class__.__name__, config, pos)
219        Warning.__init__(self, self.formatted_message)
220
221    def __str__(self):
222        return self.formatted_message
223
224    @classmethod
225    def get_short_name(cls):
226        if len(cls.default_args):
227            return cls.message_template.format(*cls.default_args)
228        return cls.message_template
229
230
231class VOTableChangeWarning(VOWarning, SyntaxWarning):
232    """
233    A change has been made to the input XML file.
234    """
235
236
237class VOTableSpecWarning(VOWarning, SyntaxWarning):
238    """
239    The input XML file violates the spec, but there is an obvious workaround.
240    """
241
242
243class UnimplementedWarning(VOWarning, SyntaxWarning):
244    """
245    A feature of the VOTABLE_ spec is not implemented.
246    """
247
248
249class IOWarning(VOWarning, RuntimeWarning):
250    """
251    A network or IO error occurred, but was recovered using the cache.
252    """
253
254
255class VOTableSpecError(VOWarning, ValueError):
256    """
257    The input XML file violates the spec and there is no good workaround.
258    """
259
260
261class W01(VOTableSpecWarning):
262    """
263    The VOTable spec states:
264
265        If a cell contains an array or complex number, it should be
266        encoded as multiple numbers separated by whitespace.
267
268    Many VOTable files in the wild use commas as a separator instead,
269    and ``astropy.io.votable`` can support this convention depending on the
270    :ref:`astropy:verifying-votables` setting.
271
272    ``astropy.io.votable`` always outputs files using only spaces, regardless of
273    how they were input.
274
275    **References**: `1.1
276    <http://www.ivoa.net/documents/VOTable/20040811/REC-VOTable-1.1-20040811.html#toc-header-35>`__,
277    `1.2
278    <http://www.ivoa.net/documents/VOTable/20091130/REC-VOTable-1.2.html#sec:TABLEDATA>`__
279    """
280
281    message_template = "Array uses commas rather than whitespace"
282
283
284class W02(VOTableSpecWarning):
285    r"""
286    XML ids must match the following regular expression::
287
288        ^[A-Za-z_][A-Za-z0-9_\.\-]*$
289
290    The VOTable 1.1 says the following:
291
292        According to the XML standard, the attribute ``ID`` is a
293        string beginning with a letter or underscore (``_``), followed
294        by a sequence of letters, digits, or any of the punctuation
295        characters ``.`` (dot), ``-`` (dash), ``_`` (underscore), or
296        ``:`` (colon).
297
298    However, this is in conflict with the XML standard, which says
299    colons may not be used.  VOTable 1.1's own schema does not allow a
300    colon here.  Therefore, ``astropy.io.votable`` disallows the colon.
301
302    VOTable 1.2 corrects this error in the specification.
303
304    **References**: `1.1
305    <http://www.ivoa.net/documents/VOTable/20040811/REC-VOTable-1.1-20040811.html#sec:name>`__,
306    `XML Names <http://www.w3.org/TR/REC-xml/#NT-Name>`__
307    """
308
309    message_template = "{} attribute '{}' is invalid.  Must be a standard XML id"
310    default_args = ('x', 'y')
311
312
313class W03(VOTableChangeWarning):
314    """
315    The VOTable 1.1 spec says the following about ``name`` vs. ``ID``
316    on ``FIELD`` and ``VALUE`` elements:
317
318        ``ID`` and ``name`` attributes have a different role in
319        VOTable: the ``ID`` is meant as a *unique identifier* of an
320        element seen as a VOTable component, while the ``name`` is
321        meant for presentation purposes, and need not to be unique
322        throughout the VOTable document. The ``ID`` attribute is
323        therefore required in the elements which have to be
324        referenced, but in principle any element may have an ``ID``
325        attribute. ... In summary, the ``ID`` is different from the
326        ``name`` attribute in that (a) the ``ID`` attribute is made
327        from a restricted character set, and must be unique throughout
328        a VOTable document whereas names are standard XML attributes
329        and need not be unique; and (b) there should be support in the
330        parsing software to look up references and extract the
331        relevant element with matching ``ID``.
332
333    It is further recommended in the VOTable 1.2 spec:
334
335        While the ``ID`` attribute has to be unique in a VOTable
336        document, the ``name`` attribute need not. It is however
337        recommended, as a good practice, to assign unique names within
338        a ``TABLE`` element. This recommendation means that, between a
339        ``TABLE`` and its corresponding closing ``TABLE`` tag,
340        ``name`` attributes of ``FIELD``, ``PARAM`` and optional
341        ``GROUP`` elements should be all different.
342
343    Since ``astropy.io.votable`` requires a unique identifier for each of its
344    columns, ``ID`` is used for the column name when present.
345    However, when ``ID`` is not present, (since it is not required by
346    the specification) ``name`` is used instead.  However, ``name``
347    must be cleansed by replacing invalid characters (such as
348    whitespace) with underscores.
349
350    .. note::
351        This warning does not indicate that the input file is invalid
352        with respect to the VOTable specification, only that the
353        column names in the record array may not match exactly the
354        ``name`` attributes specified in the file.
355
356    **References**: `1.1
357    <http://www.ivoa.net/documents/VOTable/20040811/REC-VOTable-1.1-20040811.html#sec:name>`__,
358    `1.2
359    <http://www.ivoa.net/documents/VOTable/20091130/REC-VOTable-1.2.html#sec:name>`__
360    """
361
362    message_template = "Implicitly generating an ID from a name '{}' -> '{}'"
363    default_args = ('x', 'y')
364
365
366class W04(VOTableSpecWarning):
367    """
368    The ``content-type`` attribute must use MIME content-type syntax as
369    defined in `RFC 2046 <https://tools.ietf.org/html/rfc2046>`__.
370
371    The current check for validity is somewhat over-permissive.
372
373    **References**: `1.1
374    <http://www.ivoa.net/documents/VOTable/20040811/REC-VOTable-1.1-20040811.html#sec:link>`__,
375    `1.2
376    <http://www.ivoa.net/documents/VOTable/20091130/REC-VOTable-1.2.html#sec:link>`__
377    """
378
379    message_template = "content-type '{}' must be a valid MIME content type"
380    default_args = ('x',)
381
382
383class W05(VOTableSpecWarning):
384    """
385    The attribute must be a valid URI as defined in `RFC 2396
386    <https://www.ietf.org/rfc/rfc2396.txt>`_.
387    """
388
389    message_template = "'{}' is not a valid URI"
390    default_args = ('x',)
391
392
393class W06(VOTableSpecWarning):
394    """
395    This warning is emitted when a ``ucd`` attribute does not match
396    the syntax of a `unified content descriptor
397    <http://vizier.u-strasbg.fr/doc/UCD.htx>`__.
398
399    If the VOTable version is 1.2 or later, the UCD will also be
400    checked to ensure it conforms to the controlled vocabulary defined
401    by UCD1+.
402
403    **References**: `1.1
404    <http://www.ivoa.net/documents/VOTable/20040811/REC-VOTable-1.1-20040811.html#sec:ucd>`__,
405    `1.2
406    <http://www.ivoa.net/documents/VOTable/20091130/REC-VOTable-1.2.html#sec:ucd>`__
407    """
408
409    message_template = "Invalid UCD '{}': {}"
410    default_args = ('x', 'explanation')
411
412
413class W07(VOTableSpecWarning):
414    """
415    As astro year field is a Besselian or Julian year matching the
416    regular expression::
417
418        ^[JB]?[0-9]+([.][0-9]*)?$
419
420    Defined in this XML Schema snippet::
421
422        <xs:simpleType  name="astroYear">
423          <xs:restriction base="xs:token">
424            <xs:pattern  value="[JB]?[0-9]+([.][0-9]*)?"/>
425          </xs:restriction>
426        </xs:simpleType>
427    """
428
429    message_template = "Invalid astroYear in {}: '{}'"
430    default_args = ('x', 'y')
431
432
433class W08(VOTableSpecWarning):
434    """
435    To avoid local-dependent number parsing differences, ``astropy.io.votable``
436    may require a string or unicode string where a numeric type may
437    make more sense.
438    """
439
440    message_template = "'{}' must be a str or bytes object"
441
442    default_args = ('x',)
443
444
445class W09(VOTableSpecWarning):
446    """
447    The VOTable specification uses the attribute name ``ID`` (with
448    uppercase letters) to specify unique identifiers.  Some
449    VOTable-producing tools use the more standard lowercase ``id``
450    instead. ``astropy.io.votable`` accepts ``id`` and emits this warning if
451    ``verify`` is ``'warn'``.
452
453    **References**: `1.1
454    <http://www.ivoa.net/documents/VOTable/20040811/REC-VOTable-1.1-20040811.html#sec:name>`__,
455    `1.2
456    <http://www.ivoa.net/documents/VOTable/20091130/REC-VOTable-1.2.html#sec:name>`__
457    """
458
459    message_template = "ID attribute not capitalized"
460
461
462class W10(VOTableSpecWarning):
463    """
464    The parser has encountered an element that does not exist in the
465    specification, or appears in an invalid context.  Check the file
466    against the VOTable schema (with a tool such as `xmllint
467    <http://xmlsoft.org/xmllint.html>`__.  If the file validates
468    against the schema, and you still receive this warning, this may
469    indicate a bug in ``astropy.io.votable``.
470
471    **References**: `1.1
472    <http://www.ivoa.net/documents/VOTable/20040811/REC-VOTable-1.1-20040811.html#ToC54>`__,
473    `1.2
474    <http://www.ivoa.net/documents/VOTable/20091130/REC-VOTable-1.2.html#ToC58>`__
475    """
476
477    message_template = "Unknown tag '{}'.  Ignoring"
478    default_args = ('x',)
479
480
481class W11(VOTableSpecWarning):
482    """
483    Earlier versions of the VOTable specification used a ``gref``
484    attribute on the ``LINK`` element to specify a `GLU reference
485    <http://aladin.u-strasbg.fr/glu/>`__.  New files should
486    specify a ``glu:`` protocol using the ``href`` attribute.
487
488    Since ``astropy.io.votable`` does not currently support GLU references, it
489    likewise does not automatically convert the ``gref`` attribute to
490    the new form.
491
492    **References**: `1.1
493    <http://www.ivoa.net/documents/VOTable/20040811/REC-VOTable-1.1-20040811.html#sec:link>`__,
494    `1.2
495    <http://www.ivoa.net/documents/VOTable/20091130/REC-VOTable-1.2.html#sec:link>`__
496    """
497
498    message_template = "The gref attribute on LINK is deprecated in VOTable 1.1"
499
500
501class W12(VOTableChangeWarning):
502    """
503    In order to name the columns of the Numpy record array, each
504    ``FIELD`` element must have either an ``ID`` or ``name`` attribute
505    to derive a name from.  Strictly speaking, according to the
506    VOTable schema, the ``name`` attribute is required.  However, if
507    ``name`` is not present by ``ID`` is, and ``verify`` is not ``'exception'``,
508    ``astropy.io.votable`` will continue without a ``name`` defined.
509
510    **References**: `1.1
511    <http://www.ivoa.net/documents/VOTable/20040811/REC-VOTable-1.1-20040811.html#sec:name>`__,
512    `1.2
513    <http://www.ivoa.net/documents/VOTable/20091130/REC-VOTable-1.2.html#sec:name>`__
514    """
515
516    message_template = (
517        "'{}' element must have at least one of 'ID' or 'name' attributes")
518    default_args = ('x',)
519
520
521class W13(VOTableSpecWarning):
522    """
523    Some VOTable files in the wild use non-standard datatype names.  These
524    are mapped to standard ones using the following mapping::
525
526       string        -> char
527       unicodeString -> unicodeChar
528       int16         -> short
529       int32         -> int
530       int64         -> long
531       float32       -> float
532       float64       -> double
533       unsignedInt   -> long
534       unsignedShort -> int
535
536    To add more datatype mappings during parsing, use the
537    ``datatype_mapping`` keyword to `astropy.io.votable.parse`.
538
539    **References**: `1.1
540    <http://www.ivoa.net/documents/VOTable/20040811/REC-VOTable-1.1-20040811.html#sec:datatypes>`__,
541    `1.2
542    <http://www.ivoa.net/documents/VOTable/20091130/REC-VOTable-1.2.html#sec:datatypes>`__
543    """
544
545    message_template = "'{}' is not a valid VOTable datatype, should be '{}'"
546    default_args = ('x', 'y')
547
548
549# W14: Deprecated
550
551
552class W15(VOTableSpecWarning):
553    """
554    The ``name`` attribute is required on every ``FIELD`` element.
555    However, many VOTable files in the wild omit it and provide only
556    an ``ID`` instead.  In this case, when ``verify`` is not ``'exception'``
557    ``astropy.io.votable`` will copy the ``name`` attribute to a new ``ID``
558    attribute.
559
560    **References**: `1.1
561    <http://www.ivoa.net/documents/VOTable/20040811/REC-VOTable-1.1-20040811.html#sec:name>`__,
562    `1.2
563    <http://www.ivoa.net/documents/VOTable/20091130/REC-VOTable-1.2.html#sec:name>`__
564    """
565
566    message_template = "{} element missing required 'name' attribute"
567    default_args = ('x',)
568
569# W16: Deprecated
570
571
572class W17(VOTableSpecWarning):
573    """
574    A ``DESCRIPTION`` element can only appear once within its parent
575    element.
576
577    According to the schema, it may only occur once (`1.1
578    <http://www.ivoa.net/documents/VOTable/20040811/REC-VOTable-1.1-20040811.html#ToC54>`__,
579    `1.2
580    <http://www.ivoa.net/documents/VOTable/20091130/REC-VOTable-1.2.html#ToC58>`__)
581
582    However, it is a `proposed extension
583    <http://www.ivoa.net/documents/VOTable/20091130/REC-VOTable-1.2.html#sec:addesc>`__
584    to VOTable 1.2.
585    """
586
587    message_template = "{} element contains more than one DESCRIPTION element"
588    default_args = ('x',)
589
590
591class W18(VOTableSpecWarning):
592    """
593    The number of rows explicitly specified in the ``nrows`` attribute
594    does not match the actual number of rows (``TR`` elements) present
595    in the ``TABLE``.  This may indicate truncation of the file, or an
596    internal error in the tool that produced it.  If ``verify`` is not
597    ``'exception'``, parsing will proceed, with the loss of some performance.
598
599    **References:** `1.1
600    <http://www.ivoa.net/documents/VOTable/20040811/REC-VOTable-1.1-20040811.html#ToC10>`__,
601    `1.2
602    <http://www.ivoa.net/documents/VOTable/20091130/REC-VOTable-1.2.html#ToC10>`__
603    """
604
605    message_template = 'TABLE specified nrows={}, but table contains {} rows'
606    default_args = ('x', 'y')
607
608
609class W19(VOTableSpecWarning):
610    """
611    The column fields as defined using ``FIELD`` elements do not match
612    those in the headers of the embedded FITS file.  If ``verify`` is not
613    ``'exception'``, the embedded FITS file will take precedence.
614    """
615
616    message_template = (
617        'The fields defined in the VOTable do not match those in the ' +
618        'embedded FITS file')
619
620
621class W20(VOTableSpecWarning):
622    """
623    If no version number is explicitly given in the VOTable file, the
624    parser assumes it is written to the VOTable 1.1 specification.
625    """
626
627    message_template = 'No version number specified in file.  Assuming {}'
628    default_args = ('1.1',)
629
630
631class W21(UnimplementedWarning):
632    """
633    Unknown issues may arise using ``astropy.io.votable`` with VOTable files
634    from a version other than 1.1, 1.2, 1.3, or 1.4.
635    """
636
637    message_template = (
638        'astropy.io.votable is designed for VOTable version 1.1, 1.2, 1.3,'
639        ' and 1.4, but this file is {}')
640    default_args = ('x',)
641
642
643class W22(VOTableSpecWarning):
644    """
645    Version 1.0 of the VOTable specification used the ``DEFINITIONS``
646    element to define coordinate systems.  Version 1.1 now uses
647    ``COOSYS`` elements throughout the document.
648
649    **References:** `1.1
650    <http://www.ivoa.net/documents/VOTable/20040811/REC-VOTable-1.1-20040811.html#sec:definitions>`__,
651    `1.2
652    <http://www.ivoa.net/documents/VOTable/20091130/REC-VOTable-1.2.html#sec:definitions>`__
653    """
654
655    message_template = 'The DEFINITIONS element is deprecated in VOTable 1.1.  Ignoring'
656
657
658class W23(IOWarning):
659    """
660    Raised when the VO service database can not be updated (possibly
661    due to a network outage).  This is only a warning, since an older
662    and possible out-of-date VO service database was available
663    locally.
664    """
665
666    message_template = "Unable to update service information for '{}'"
667    default_args = ('x',)
668
669
670class W24(VOWarning, FutureWarning):
671    """
672    The VO catalog database retrieved from the www is designed for a
673    newer version of ``astropy.io.votable``.  This may cause problems or limited
674    features performing service queries.  Consider upgrading ``astropy.io.votable``
675    to the latest version.
676    """
677
678    message_template = "The VO catalog database is for a later version of astropy.io.votable"
679
680
681class W25(IOWarning):
682    """
683    A VO service query failed due to a network error or malformed
684    arguments.  Another alternative service may be attempted.  If all
685    services fail, an exception will be raised.
686    """
687
688    message_template = "'{}' failed with: {}"
689    default_args = ('service', '...')
690
691
692class W26(VOTableSpecWarning):
693    """
694    The given element was not supported inside of the given element
695    until the specified VOTable version, however the version declared
696    in the file is for an earlier version.  These attributes may not
697    be written out to the file.
698    """
699
700    message_template = "'{}' inside '{}' added in VOTable {}"
701    default_args = ('child', 'parent', 'X.X')
702
703
704class W27(VOTableSpecWarning):
705    """
706    The ``COOSYS`` element was deprecated in VOTABLE version 1.2 in
707    favor of a reference to the Space-Time Coordinate (STC) data
708    model (see `utype
709    <http://www.ivoa.net/documents/VOTable/20091130/REC-VOTable-1.2.html#sec:utype>`__
710    and the IVOA note `referencing STC in VOTable
711    <http://ivoa.net/Documents/latest/VOTableSTC.html>`__.
712    """
713
714    message_template = "COOSYS deprecated in VOTable 1.2"
715
716
717class W28(VOTableSpecWarning):
718    """
719    The given attribute was not supported on the given element until the
720    specified VOTable version, however the version declared in the file is
721    for an earlier version.  These attributes may not be written out to
722    the file.
723    """
724
725    message_template = "'{}' on '{}' added in VOTable {}"
726    default_args = ('attribute', 'element', 'X.X')
727
728
729class W29(VOTableSpecWarning):
730    """
731    Some VOTable files specify their version number in the form "v1.0",
732    when the only supported forms in the spec are "1.0".
733
734    **References**: `1.1
735    <http://www.ivoa.net/documents/VOTable/20040811/REC-VOTable-1.1-20040811.html#ToC54>`__,
736    `1.2
737    <http://www.ivoa.net/documents/VOTable/20091130/REC-VOTable-1.2.html#ToC58>`__
738    """
739
740    message_template = "Version specified in non-standard form '{}'"
741    default_args = ('v1.0',)
742
743
744class W30(VOTableSpecWarning):
745    """
746    Some VOTable files write missing floating-point values in non-standard ways,
747    such as "null" and "-".  If ``verify`` is not ``'exception'``, any
748    non-standard floating-point literals are treated as missing values.
749
750    **References**: `1.1
751    <http://www.ivoa.net/documents/VOTable/20040811/REC-VOTable-1.1-20040811.html#sec:datatypes>`__,
752    `1.2
753    <http://www.ivoa.net/documents/VOTable/20091130/REC-VOTable-1.2.html#sec:datatypes>`__
754    """
755
756    message_template = "Invalid literal for float '{}'.  Treating as empty."
757    default_args = ('x',)
758
759
760class W31(VOTableSpecWarning):
761    """
762    Since NaN's can not be represented in integer fields directly, a null
763    value must be specified in the FIELD descriptor to support reading
764    NaN's from the tabledata.
765
766    **References**: `1.1
767    <http://www.ivoa.net/documents/VOTable/20040811/REC-VOTable-1.1-20040811.html#sec:datatypes>`__,
768    `1.2
769    <http://www.ivoa.net/documents/VOTable/20091130/REC-VOTable-1.2.html#sec:datatypes>`__
770    """
771
772    message_template = "NaN given in an integral field without a specified null value"
773
774
775class W32(VOTableSpecWarning):
776    """
777    Each field in a table must have a unique ID.  If two or more fields
778    have the same ID, some will be renamed to ensure that all IDs are
779    unique.
780
781    From the VOTable 1.2 spec:
782
783        The ``ID`` and ``ref`` attributes are defined as XML types
784        ``ID`` and ``IDREF`` respectively. This means that the
785        contents of ``ID`` is an identifier which must be unique
786        throughout a VOTable document, and that the contents of the
787        ``ref`` attribute represents a reference to an identifier
788        which must exist in the VOTable document.
789
790    **References**: `1.1
791    <http://www.ivoa.net/documents/VOTable/20040811/REC-VOTable-1.1-20040811.html#sec:name>`__,
792    `1.2
793    <http://www.ivoa.net/documents/VOTable/20091130/REC-VOTable-1.2.html#sec:name>`__
794    """
795
796    message_template = "Duplicate ID '{}' renamed to '{}' to ensure uniqueness"
797    default_args = ('x', 'x_2')
798
799
800class W33(VOTableChangeWarning):
801    """
802    Each field in a table must have a unique name.  If two or more
803    fields have the same name, some will be renamed to ensure that all
804    names are unique.
805
806    **References**: `1.1
807    <http://www.ivoa.net/documents/VOTable/20040811/REC-VOTable-1.1-20040811.html#sec:name>`__,
808    `1.2
809    <http://www.ivoa.net/documents/VOTable/20091130/REC-VOTable-1.2.html#sec:name>`__
810    """
811
812    message_template = "Column name '{}' renamed to '{}' to ensure uniqueness"
813    default_args = ('x', 'x_2')
814
815
816class W34(VOTableSpecWarning):
817    """
818    The attribute requires the value to be a valid XML token, as
819    defined by `XML 1.0
820    <http://www.w3.org/TR/2000/WD-xml-2e-20000814#NT-Nmtoken>`__.
821    """
822
823    message_template = "'{}' is an invalid token for attribute '{}'"
824    default_args = ('x', 'y')
825
826
827class W35(VOTableSpecWarning):
828    """
829    The ``name`` and ``value`` attributes are required on all ``INFO``
830    elements.
831
832    **References:** `1.1
833    <http://www.ivoa.net/documents/VOTable/20040811/REC-VOTable-1.1-20040811.html#ToC54>`__,
834    `1.2
835    <http://www.ivoa.net/documents/VOTable/20091130/REC-VOTable-1.2.html#ToC32>`__
836    """
837
838    message_template = "'{}' attribute required for INFO elements"
839    default_args = ('x',)
840
841
842class W36(VOTableSpecWarning):
843    """
844    If the field specifies a ``null`` value, that value must conform
845    to the given ``datatype``.
846
847    **References:** `1.1
848    <http://www.ivoa.net/documents/VOTable/20040811/REC-VOTable-1.1-20040811.html#sec:values>`__,
849    `1.2
850    <http://www.ivoa.net/documents/VOTable/20091130/REC-VOTable-1.2.html#sec:values>`__
851    """
852
853    message_template = "null value '{}' does not match field datatype, setting to 0"
854    default_args = ('x',)
855
856
857class W37(UnimplementedWarning):
858    """
859    The 3 datatypes defined in the VOTable specification and supported by
860    ``astropy.io.votable`` are ``TABLEDATA``, ``BINARY`` and ``FITS``.
861
862    **References:** `1.1
863    <http://www.ivoa.net/documents/VOTable/20040811/REC-VOTable-1.1-20040811.html#sec:data>`__,
864    `1.2
865    <http://www.ivoa.net/documents/VOTable/20091130/REC-VOTable-1.2.html#sec:data>`__
866    """
867
868    message_template = "Unsupported data format '{}'"
869    default_args = ('x',)
870
871
872class W38(VOTableSpecWarning):
873    """
874    The only encoding for local binary data supported by the VOTable
875    specification is base64.
876    """
877
878    message_template = "Inline binary data must be base64 encoded, got '{}'"
879    default_args = ('x',)
880
881
882class W39(VOTableSpecWarning):
883    """
884    Bit values do not support masking.  This warning is raised upon
885    setting masked data in a bit column.
886
887    **References**: `1.1
888    <http://www.ivoa.net/documents/VOTable/20040811/REC-VOTable-1.1-20040811.html#sec:datatypes>`__,
889    `1.2
890    <http://www.ivoa.net/documents/VOTable/20091130/REC-VOTable-1.2.html#sec:datatypes>`__
891    """
892
893    message_template = "Bit values can not be masked"
894
895
896class W40(VOTableSpecWarning):
897    """
898    This is a terrible hack to support Simple Image Access Protocol
899    results from `archive.noao.edu <http://archive.noao.edu>`__.  It
900    creates a field for the coordinate projection type of type "double",
901    which actually contains character data.  We have to hack the field
902    to store character data, or we can't read it in.  A warning will be
903    raised when this happens.
904    """
905
906    message_template = "'cprojection' datatype repaired"
907
908
909class W41(VOTableSpecWarning):
910    """
911    An XML namespace was specified on the ``VOTABLE`` element, but the
912    namespace does not match what is expected for a ``VOTABLE`` file.
913
914    The ``VOTABLE`` namespace is::
915
916      http://www.ivoa.net/xml/VOTable/vX.X
917
918    where "X.X" is the version number.
919
920    Some files in the wild set the namespace to the location of the
921    VOTable schema, which is not correct and will not pass some
922    validating parsers.
923    """
924
925    message_template = (
926        "An XML namespace is specified, but is incorrect.  Expected " +
927        "'{}', got '{}'")
928    default_args = ('x', 'y')
929
930
931class W42(VOTableSpecWarning):
932    """
933    The root element should specify a namespace.
934
935    The ``VOTABLE`` namespace is::
936
937        http://www.ivoa.net/xml/VOTable/vX.X
938
939    where "X.X" is the version number.
940    """
941
942    message_template = "No XML namespace specified"
943
944
945class W43(VOTableSpecWarning):
946    """
947    Referenced elements should be defined before referees.  From the
948    VOTable 1.2 spec:
949
950       In VOTable1.2, it is further recommended to place the ID
951       attribute prior to referencing it whenever possible.
952    """
953
954    message_template = "{} ref='{}' which has not already been defined"
955    default_args = ('element', 'x',)
956
957
958class W44(VOTableSpecWarning):
959    """
960    ``VALUES`` elements that reference another element should not have
961    their own content.
962
963    From the VOTable 1.2 spec:
964
965        The ``ref`` attribute of a ``VALUES`` element can be used to
966        avoid a repetition of the domain definition, by referring to a
967        previously defined ``VALUES`` element having the referenced
968        ``ID`` attribute. When specified, the ``ref`` attribute
969        defines completely the domain without any other element or
970        attribute, as e.g. ``<VALUES ref="RAdomain"/>``
971    """
972
973    message_template = "VALUES element with ref attribute has content ('{}')"
974    default_args = ('element',)
975
976
977class W45(VOWarning, ValueError):
978    """
979    The ``content-role`` attribute on the ``LINK`` element must be one of
980    the following::
981
982        query, hints, doc, location
983
984    And in VOTable 1.3, additionally::
985
986        type
987
988    **References**: `1.1
989    <http://www.ivoa.net/documents/VOTable/20040811/REC-VOTable-1.1-20040811.html#ToC54>`__,
990    `1.2
991    <http://www.ivoa.net/documents/VOTable/20091130/REC-VOTable-1.2.html#ToC58>`__
992    `1.3
993    <http://www.ivoa.net/documents/VOTable/20130315/PR-VOTable-1.3-20130315.html#sec:link>`__
994    """
995
996    message_template = "content-role attribute '{}' invalid"
997    default_args = ('x',)
998
999
1000class W46(VOTableSpecWarning):
1001    """
1002    The given char or unicode string is too long for the specified
1003    field length.
1004    """
1005
1006    message_template = "{} value is too long for specified length of {}"
1007    default_args = ('char or unicode', 'x')
1008
1009
1010class W47(VOTableSpecWarning):
1011    """
1012    If no arraysize is specified on a char field, the default of '1'
1013    is implied, but this is rarely what is intended.
1014    """
1015
1016    message_template = "Missing arraysize indicates length 1"
1017
1018
1019class W48(VOTableSpecWarning):
1020    """
1021    The attribute is not defined in the specification.
1022    """
1023
1024    message_template = "Unknown attribute '{}' on {}"
1025    default_args = ('attribute', 'element')
1026
1027
1028class W49(VOTableSpecWarning):
1029    """
1030    Prior to VOTable 1.3, the empty cell was illegal for integer
1031    fields.
1032
1033    If a \"null\" value was specified for the cell, it will be used
1034    for the value, otherwise, 0 will be used.
1035    """
1036
1037    message_template = "Empty cell illegal for integer fields."
1038
1039
1040class W50(VOTableSpecWarning):
1041    """
1042    Invalid unit string as defined in the `Units in the VO, Version 1.0
1043    <https://www.ivoa.net/documents/VOUnits>`_ (VOTable version >= 1.4)
1044    or `Standards for Astronomical Catalogues, Version 2.0
1045    <http://cdsarc.u-strasbg.fr/doc/catstd-3.2.htx>`_ (version < 1.4).
1046
1047    Consider passing an explicit ``unit_format`` parameter if the units
1048    in this file conform to another specification.
1049    """
1050
1051    message_template = "Invalid unit string '{}'"
1052    default_args = ('x',)
1053
1054
1055class W51(VOTableSpecWarning):
1056    """
1057    The integer value is out of range for the size of the field.
1058    """
1059
1060    message_template = "Value '{}' is out of range for a {} integer field"
1061    default_args = ('x', 'n-bit')
1062
1063
1064class W52(VOTableSpecWarning):
1065    """
1066    The BINARY2 format was introduced in VOTable 1.3.  It should
1067    not be present in files marked as an earlier version.
1068    """
1069
1070    message_template = ("The BINARY2 format was introduced in VOTable 1.3, but "
1071                        "this file is declared as version '{}'")
1072    default_args = ('1.2',)
1073
1074
1075class W53(VOTableSpecWarning):
1076    """
1077    The VOTABLE element must contain at least one RESOURCE element.
1078    """
1079
1080    message_template = ("VOTABLE element must contain at least one RESOURCE element.")
1081    default_args = ()
1082
1083
1084class W54(VOTableSpecWarning):
1085    """
1086    The TIMESYS element was introduced in VOTable 1.4.  It should
1087    not be present in files marked as an earlier version.
1088    """
1089
1090    message_template = (
1091        "The TIMESYS element was introduced in VOTable 1.4, but "
1092        "this file is declared as version '{}'")
1093    default_args = ('1.3',)
1094
1095
1096class W55(VOTableSpecWarning):
1097    """
1098    When non-ASCII characters are detected when reading
1099    a TABLEDATA value for a FIELD with ``datatype="char"``, we
1100    can issue this warning.
1101    """
1102
1103    message_template = (
1104        'FIELD ({}) has datatype="char" but contains non-ASCII '
1105        'value ({})')
1106    default_args = ('', '')
1107
1108
1109class E01(VOWarning, ValueError):
1110    """
1111    The size specifier for a ``char`` or ``unicode`` field must be
1112    only a number followed, optionally, by an asterisk.
1113    Multi-dimensional size specifiers are not supported for these
1114    datatypes.
1115
1116    Strings, which are defined as a set of characters, can be
1117    represented in VOTable as a fixed- or variable-length array of
1118    characters::
1119
1120        <FIELD name="unboundedString" datatype="char" arraysize="*"/>
1121
1122    A 1D array of strings can be represented as a 2D array of
1123    characters, but given the logic above, it is possible to define a
1124    variable-length array of fixed-length strings, but not a
1125    fixed-length array of variable-length strings.
1126    """
1127
1128    message_template = "Invalid size specifier '{}' for a {} field (in field '{}')"
1129    default_args = ('x', 'char/unicode', 'y')
1130
1131
1132class E02(VOWarning, ValueError):
1133    """
1134    The number of array elements in the data does not match that specified
1135    in the FIELD specifier.
1136    """
1137
1138    message_template = (
1139        "Incorrect number of elements in array. " +
1140        "Expected multiple of {}, got {}")
1141    default_args = ('x', 'y')
1142
1143
1144class E03(VOWarning, ValueError):
1145    """
1146    Complex numbers should be two values separated by whitespace.
1147
1148    **References**: `1.1
1149    <http://www.ivoa.net/documents/VOTable/20040811/REC-VOTable-1.1-20040811.html#sec:datatypes>`__,
1150    `1.2
1151    <http://www.ivoa.net/documents/VOTable/20091130/REC-VOTable-1.2.html#sec:datatypes>`__
1152    """
1153
1154    message_template = "'{}' does not parse as a complex number"
1155    default_args = ('x',)
1156
1157
1158class E04(VOWarning, ValueError):
1159    """
1160    A ``bit`` array should be a string of '0's and '1's.
1161
1162    **References**: `1.1
1163    <http://www.ivoa.net/documents/VOTable/20040811/REC-VOTable-1.1-20040811.html#sec:datatypes>`__,
1164    `1.2
1165    <http://www.ivoa.net/documents/VOTable/20091130/REC-VOTable-1.2.html#sec:datatypes>`__
1166    """
1167
1168    message_template = "Invalid bit value '{}'"
1169    default_args = ('x',)
1170
1171
1172class E05(VOWarning, ValueError):
1173    r"""
1174    A ``boolean`` value should be one of the following strings (case
1175    insensitive) in the ``TABLEDATA`` format::
1176
1177        'TRUE', 'FALSE', '1', '0', 'T', 'F', '\0', ' ', '?'
1178
1179    and in ``BINARY`` format::
1180
1181        'T', 'F', '1', '0', '\0', ' ', '?'
1182
1183    **References**: `1.1
1184    <http://www.ivoa.net/documents/VOTable/20040811/REC-VOTable-1.1-20040811.html#sec:datatypes>`__,
1185    `1.2
1186    <http://www.ivoa.net/documents/VOTable/20091130/REC-VOTable-1.2.html#sec:datatypes>`__
1187    """
1188
1189    message_template = "Invalid boolean value '{}'"
1190    default_args = ('x',)
1191
1192
1193class E06(VOWarning, ValueError):
1194    """
1195    The supported datatypes are::
1196
1197        double, float, bit, boolean, unsignedByte, short, int, long,
1198        floatComplex, doubleComplex, char, unicodeChar
1199
1200    The following non-standard aliases are also supported, but in
1201    these case :ref:`W13 <W13>` will be raised::
1202
1203        string        -> char
1204        unicodeString -> unicodeChar
1205        int16         -> short
1206        int32         -> int
1207        int64         -> long
1208        float32       -> float
1209        float64       -> double
1210        unsignedInt   -> long
1211        unsignedShort -> int
1212
1213    To add more datatype mappings during parsing, use the
1214    ``datatype_mapping`` keyword to `astropy.io.votable.parse`.
1215
1216    **References**: `1.1
1217    <http://www.ivoa.net/documents/VOTable/20040811/REC-VOTable-1.1-20040811.html#sec:datatypes>`__,
1218    `1.2
1219    <http://www.ivoa.net/documents/VOTable/20091130/REC-VOTable-1.2.html#sec:datatypes>`__
1220    """
1221
1222    message_template = "Unknown datatype '{}' on field '{}'"
1223    default_args = ('x', 'y')
1224
1225# E07: Deprecated
1226
1227
1228class E08(VOWarning, ValueError):
1229    """
1230    The ``type`` attribute on the ``VALUES`` element must be either
1231    ``legal`` or ``actual``.
1232
1233    **References**: `1.1
1234    <http://www.ivoa.net/documents/VOTable/20040811/REC-VOTable-1.1-20040811.html#sec:values>`__,
1235    `1.2
1236    <http://www.ivoa.net/documents/VOTable/20091130/REC-VOTable-1.2.html#sec:values>`__
1237    """
1238
1239    message_template = "type must be 'legal' or 'actual', but is '{}'"
1240    default_args = ('x',)
1241
1242
1243class E09(VOWarning, ValueError):
1244    """
1245    The ``MIN``, ``MAX`` and ``OPTION`` elements must always have a
1246    ``value`` attribute.
1247
1248    **References**: `1.1
1249    <http://www.ivoa.net/documents/VOTable/20040811/REC-VOTable-1.1-20040811.html#sec:values>`__,
1250    `1.2
1251    <http://www.ivoa.net/documents/VOTable/20091130/REC-VOTable-1.2.html#sec:values>`__
1252    """
1253
1254    message_template = "'{}' must have a value attribute"
1255    default_args = ('x',)
1256
1257
1258class E10(VOWarning, ValueError):
1259    """
1260    From VOTable 1.1 and later, ``FIELD`` and ``PARAM`` elements must have
1261    a ``datatype`` field.
1262
1263    **References**: `1.1
1264    <http://www.ivoa.net/documents/VOTable/20040811/REC-VOTable-1.1-20040811.html#elem:FIELD>`__,
1265    `1.2
1266    <http://www.ivoa.net/documents/VOTable/20091130/REC-VOTable-1.2.html#elem:FIELD>`__
1267    """
1268
1269    message_template = "'datatype' attribute required on all '{}' elements"
1270    default_args = ('FIELD',)
1271
1272
1273class E11(VOWarning, ValueError):
1274    """
1275    The precision attribute is meant to express the number of significant
1276    digits, either as a number of decimal places (e.g. ``precision="F2"`` or
1277    equivalently ``precision="2"`` to express 2 significant figures
1278    after the decimal point), or as a number of significant figures
1279    (e.g. ``precision="E5"`` indicates a relative precision of 10-5).
1280
1281    It is validated using the following regular expression::
1282
1283        [EF]?[1-9][0-9]*
1284
1285    **References**: `1.1
1286    <http://www.ivoa.net/documents/VOTable/20040811/REC-VOTable-1.1-20040811.html#sec:form>`__,
1287    `1.2
1288    <http://www.ivoa.net/documents/VOTable/20091130/REC-VOTable-1.2.html#sec:form>`__
1289    """
1290
1291    message_template = "precision '{}' is invalid"
1292    default_args = ('x',)
1293
1294
1295class E12(VOWarning, ValueError):
1296    """
1297    The width attribute is meant to indicate to the application the
1298    number of characters to be used for input or output of the
1299    quantity.
1300
1301    **References**: `1.1
1302    <http://www.ivoa.net/documents/VOTable/20040811/REC-VOTable-1.1-20040811.html#sec:form>`__,
1303    `1.2
1304    <http://www.ivoa.net/documents/VOTable/20091130/REC-VOTable-1.2.html#sec:form>`__
1305    """
1306
1307    message_template = "width must be a positive integer, got '{}'"
1308    default_args = ('x',)
1309
1310
1311class E13(VOWarning, ValueError):
1312    r"""
1313    From the VOTable 1.2 spec:
1314
1315        A table cell can contain an array of a given primitive type,
1316        with a fixed or variable number of elements; the array may
1317        even be multidimensional. For instance, the position of a
1318        point in a 3D space can be defined by the following::
1319
1320            <FIELD ID="point_3D" datatype="double" arraysize="3"/>
1321
1322        and each cell corresponding to that definition must contain
1323        exactly 3 numbers. An asterisk (\*) may be appended to
1324        indicate a variable number of elements in the array, as in::
1325
1326            <FIELD ID="values" datatype="int" arraysize="100*"/>
1327
1328        where it is specified that each cell corresponding to that
1329        definition contains 0 to 100 integer numbers. The number may
1330        be omitted to specify an unbounded array (in practice up to
1331        =~2×10⁹ elements).
1332
1333        A table cell can also contain a multidimensional array of a
1334        given primitive type. This is specified by a sequence of
1335        dimensions separated by the ``x`` character, with the first
1336        dimension changing fastest; as in the case of a simple array,
1337        the last dimension may be variable in length. As an example,
1338        the following definition declares a table cell which may
1339        contain a set of up to 10 images, each of 64×64 bytes::
1340
1341            <FIELD ID="thumbs" datatype="unsignedByte" arraysize="64×64×10*"/>
1342
1343    **References**: `1.1
1344    <http://www.ivoa.net/documents/VOTable/20040811/REC-VOTable-1.1-20040811.html#sec:dim>`__,
1345    `1.2
1346    <http://www.ivoa.net/documents/VOTable/20091130/REC-VOTable-1.2.html#sec:dim>`__
1347    """
1348
1349    message_template = "Invalid arraysize attribute '{}'"
1350    default_args = ('x',)
1351
1352
1353class E14(VOWarning, ValueError):
1354    """
1355    All ``PARAM`` elements must have a ``value`` attribute.
1356
1357    **References**: `1.1
1358    <http://www.ivoa.net/documents/VOTable/20040811/REC-VOTable-1.1-20040811.html#elem:FIELD>`__,
1359    `1.2
1360    <http://www.ivoa.net/documents/VOTable/20091130/REC-VOTable-1.2.html#elem:FIELD>`__
1361    """
1362
1363    message_template = "value attribute is required for all PARAM elements"
1364
1365
1366class E15(VOWarning, ValueError):
1367    """
1368    All ``COOSYS`` elements must have an ``ID`` attribute.
1369
1370    Note that the VOTable 1.1 specification says this attribute is
1371    optional, but its corresponding schema indicates it is required.
1372
1373    In VOTable 1.2, the ``COOSYS`` element is deprecated.
1374    """
1375
1376    message_template = "ID attribute is required for all COOSYS elements"
1377
1378
1379class E16(VOTableSpecWarning):
1380    """
1381    The ``system`` attribute on the ``COOSYS`` element must be one of the
1382    following::
1383
1384      'eq_FK4', 'eq_FK5', 'ICRS', 'ecl_FK4', 'ecl_FK5', 'galactic',
1385      'supergalactic', 'xy', 'barycentric', 'geo_app'
1386
1387    **References**: `1.1
1388    <http://www.ivoa.net/documents/VOTable/20040811/REC-VOTable-1.1-20040811.html#elem:COOSYS>`__
1389    """
1390
1391    message_template = "Invalid system attribute '{}'"
1392    default_args = ('x',)
1393
1394
1395class E17(VOWarning, ValueError):
1396    """
1397    ``extnum`` attribute must be a positive integer.
1398
1399    **References**: `1.1
1400    <http://www.ivoa.net/documents/VOTable/20040811/REC-VOTable-1.1-20040811.html#ToC54>`__,
1401    `1.2
1402    <http://www.ivoa.net/documents/VOTable/20091130/REC-VOTable-1.2.html#ToC58>`__
1403    """
1404
1405    message_template = "extnum must be a positive integer"
1406
1407
1408class E18(VOWarning, ValueError):
1409    """
1410    The ``type`` attribute of the ``RESOURCE`` element must be one of
1411    "results" or "meta".
1412
1413    **References**: `1.1
1414    <http://www.ivoa.net/documents/VOTable/20040811/REC-VOTable-1.1-20040811.html#ToC54>`__,
1415    `1.2
1416    <http://www.ivoa.net/documents/VOTable/20091130/REC-VOTable-1.2.html#ToC58>`__
1417    """
1418
1419    message_template = "type must be 'results' or 'meta', not '{}'"
1420    default_args = ('x',)
1421
1422
1423class E19(VOWarning, ValueError):
1424    """
1425    Raised either when the file doesn't appear to be XML, or the root
1426    element is not VOTABLE.
1427    """
1428
1429    message_template = "File does not appear to be a VOTABLE"
1430
1431
1432class E20(VOTableSpecError):
1433    """
1434    The table had only *x* fields defined, but the data itself has more
1435    columns than that.
1436    """
1437
1438    message_template = "Data has more columns than are defined in the header ({})"
1439    default_args = ('x',)
1440
1441
1442class E21(VOWarning, ValueError):
1443    """
1444    The table had *x* fields defined, but the data itself has only *y*
1445    columns.
1446    """
1447
1448    message_template = "Data has fewer columns ({}) than are defined in the header ({})"
1449    default_args = ('x', 'y')
1450
1451
1452class E22(VOWarning, ValueError):
1453    """
1454    All ``TIMESYS`` elements must have an ``ID`` attribute.
1455    """
1456
1457    message_template = "ID attribute is required for all TIMESYS elements"
1458
1459
1460class E23(VOTableSpecWarning):
1461    """
1462    The ``timeorigin`` attribute on the ``TIMESYS`` element must be
1463    either a floating point literal specifying a valid Julian Date,
1464    or, for convenience, the string "MJD-origin" (standing for 2400000.5)
1465    or the string "JD-origin" (standing for 0).
1466
1467    **References**: `1.4
1468    <http://www.ivoa.net/documents/VOTable/20191021/REC-VOTable-1.4-20191021.html#ToC21>`__
1469    """
1470
1471    message_template = "Invalid timeorigin attribute '{}'"
1472    default_args = ('x',)
1473
1474
1475class E24(VOWarning, ValueError):
1476    """
1477    Non-ASCII unicode values should not be written when the FIELD ``datatype="char"``,
1478    and cannot be written in BINARY or BINARY2 serialization.
1479    """
1480
1481    message_template = (
1482        'Attempt to write non-ASCII value ({}) to FIELD ({}) which '
1483        'has datatype="char"')
1484    default_args = ('', '')
1485
1486
1487class E25(VOTableSpecWarning):
1488    """
1489    A VOTable cannot have a DATA section without any defined FIELD; DATA will be ignored.
1490    """
1491
1492    message_template = "No FIELDs are defined; DATA section will be ignored."
1493
1494
1495def _get_warning_and_exception_classes(prefix):
1496    classes = []
1497    for key, val in globals().items():
1498        if re.match(prefix + "[0-9]{2}", key):
1499            classes.append((key, val))
1500    classes.sort()
1501    return classes
1502
1503
1504def _build_doc_string():
1505    def generate_set(prefix):
1506        classes = _get_warning_and_exception_classes(prefix)
1507
1508        out = io.StringIO()
1509
1510        for name, cls in classes:
1511            out.write(f".. _{name}:\n\n")
1512            msg = f"{cls.__name__}: {cls.get_short_name()}"
1513            if not isinstance(msg, str):
1514                msg = msg.decode('utf-8')
1515            out.write(msg)
1516            out.write('\n')
1517            out.write('~' * len(msg))
1518            out.write('\n\n')
1519            doc = cls.__doc__
1520            if not isinstance(doc, str):
1521                doc = doc.decode('utf-8')
1522            out.write(dedent(doc))
1523            out.write('\n\n')
1524
1525        return out.getvalue()
1526
1527    warnings = generate_set('W')
1528    exceptions = generate_set('E')
1529
1530    return {'warnings': warnings,
1531            'exceptions': exceptions}
1532
1533
1534if __doc__ is not None:
1535    __doc__ = __doc__.format(**_build_doc_string())
1536
1537__all__.extend([x[0] for x in _get_warning_and_exception_classes('W')])
1538__all__.extend([x[0] for x in _get_warning_and_exception_classes('E')])
1539