io.py 1.3 KB
Newer Older
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
# -*- coding: utf-8 -*-
# Copyright (C) 2014 Yannick Roehlly
# Licensed under the CeCILL-v2 licence - see Licence_CeCILL_V2-en.txt
# Author: Yannick Roehlly

"""
Various utility function for pcigale
"""

from astropy.table import Table
from astropy.io.ascii.core import InconsistentTableError


def read_table(file_):
    """Read a data table using astropy

    This function first tries to automatically read the table with astropy,
    if that fails, it tries with the ascii format.

Yannick Roehlly's avatar
Yannick Roehlly committed
20
21
    All the integer columns, except the "id" column, are converted to float.

22
23
    Parameters
    ----------
24
    file_: string
25
26
27
28
29
30
31
32
33
34
35
36
        Name of the file to read.

    Return
    ------
    an astropy.table.Table object

    Raise
    -----
    An error is raised when the table can not be parsed.

    """
    try:
37
        table = Table.read(file_)
38
39
    except Exception:  # astropy should raise a specific exception
        try:
40
            table = Table.read(file_, format="ascii", delimiter='\s')
41
        except InconsistentTableError:
42
43
            raise Exception(f"The file {file_} can not be parsed as a data "
                            "table.")
44

Yannick Roehlly's avatar
Yannick Roehlly committed
45
46
47
48
49
50
    # Convert all the integers to floats.
    return Table([
        col.astype(float) if col.name != 'id' and col.dtype == int
        else col
        for col in table.columns.values()
    ])