Create a target from a file

This commit is contained in:
Lukas Klass 2020-04-08 13:38:08 +02:00
parent bb59bf9240
commit 23e2cf726b
2 changed files with 44 additions and 0 deletions

View File

@ -0,0 +1,43 @@
from ..target.ATarget import ATarget
from ..SpectralQty import SpectralQty
import astropy.units as u
from astropy.io import ascii
import re
class FileTarget(ATarget):
"""
A class to create a target from a file containing the spectral flux densities
"""
def __init__(self, file: str):
"""
Initialize a new target from a file containing the spectral flux density values
Parameters
----------
file : str
The file to read the spectral flux density values from. The file needs to provide two columns: wavelength
and the corresponding spectral flux density. The format of the file will be guessed by
`astropy.io.ascii.read(). If the file doesn't provide units via astropy's enhanced CSV format, the units will
be read from the column headers or otherwise assumed to be *nm* and *W / m^2 / nm*.
"""
# Read the file
data = ascii.read(file)
# Check if units are given
if data[data.colnames[0]].unit is None:
# Convert values to float
data[data.colnames[0]] = list(map(float, data[data.colnames[0]]))
data[data.colnames[1]] = list(map(float, data[data.colnames[1]]))
# Check if units are given in column headers
if all([re.search("\\[.+\\]", x) for x in data.colnames]):
# Extract units from headers and apply them on the columns
units = [u.Unit(re.findall("(?<=\\[).+(?=\\])", x)[0]) for x in data.colnames]
data[data.colnames[0]].unit = units[0]
data[data.colnames[1]].unit = units[1]
# Use default units
else:
data[data.colnames[0]].unit = u.nm
data[data.colnames[1]].unit = u.W / (u.m ** 2 * u.nm)
# Create a spectral quantity from the data and initialize the super class
super().__init__(SpectralQty(data[data.colnames[0]].quantity, data[data.colnames[1]].quantity))

View File

@ -1,2 +1,3 @@
from esbo_etc.classes.target.ATarget import *
from esbo_etc.classes.target.BlackBodyTarget import *
from esbo_etc.classes.target.FileTarget import *