Skip to content

Commit

Permalink
Add read, write, as_table, and from_qtable to SpectralRegion
Browse files Browse the repository at this point in the history
  • Loading branch information
rosteen committed Apr 23, 2024
1 parent 75d9446 commit 7d6473f
Showing 1 changed file with 59 additions and 0 deletions.
59 changes: 59 additions & 0 deletions specutils/spectra/spectral_region.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,8 @@
import itertools
from functools import cached_property
import sys

from astropy.table import QTable
import astropy.units as u


Expand Down Expand Up @@ -106,6 +108,40 @@ def from_line_list(cls, table, width=1):
return cls([(x - width * 0.5, x + width * 0.5)
for x in table['line_center']])

@classmethod
def from_qtable(cls, table):
"""
Generate a ``SpectralRegion`` instance from an `~astropy.table.QTable`
object has has ``lower_bound`` and ``upper_bound`` columns
Parameters
----------
table : `~astropy.table.QTable`
Returns
-------
`~specutils.SpectralRegion`
The spectral region based on the table of bounds.
"""
subregions = []
for row in table:
subregions.append([row["lower_bound"], row["upper_bound"]])

return cls(subregions)

@classmethod
def read(cls, filename):
"""
Read in the ecsv file format output by the SpectralRegion.write method.
Parameters
----------
filename : str
The name of the ecsv file on disk to be read in as a SpectralRegion.
"""
table = QTable.read(filename)
return cls.from_qtable(table)

def _info(self):
"""
Pretty print the sub-regions.
Expand Down Expand Up @@ -337,3 +373,26 @@ def invert(self, lower_bound, upper_bound):
#

return SpectralRegion([(x, y) for x, y in zip(newlist[0::2], newlist[1::2])])

@cached_property
def _table(self):
# Return the information defining the spectral region as an astropy QTable
lower_bounds = []
upper_bounds = []
for subregion in self.subregions:
lower_bounds.append(subregion[0])
upper_bounds.append(subregion[1])

return QTable([lower_bounds, upper_bounds], names=("lower_bound", "upper_bound"))

def as_table(self):
return self._table

def write(self, filename="spectral_region.ecsv", overwrite=True):
"""
Write the SpectralRegion to an ecsv file using `~astropy.table.QTable`.
"""
if not filename.endswith("ecsv"):
raise ValueError("SpectralRegions can only be written out to ecsv files.")

self._table.write(filename, overwrite=overwrite)

0 comments on commit 7d6473f

Please sign in to comment.