如何显示ESO Harps s1d fits文件?(Python)
嗨,我想在一个fits文件的python上绘制一个光谱图。ESO有一个关于如何显示1D光谱的指南和一个应能工作的代码,如下所示:如何显示ESO Harps s1d fits文件?(Python),python,astropy,astronomy,fits,specutils,Python,Astropy,Astronomy,Fits,Specutils,嗨,我想在一个fits文件的python上绘制一个光谱图。ESO有一个关于如何显示1D光谱的指南和一个应能工作的代码,如下所示: import sys from astropy.io import fits as pyfits import numpy as np # hdulist = pyfits.open( "your_1d_spectrum_here.fits" ) # print column information hdulist[1].columns #
import sys
from astropy.io import fits as pyfits
import numpy as np
#
hdulist = pyfits.open( "your_1d_spectrum_here.fits" )
# print column information
hdulist[1].columns
# get to the data part (in extension 1)
scidata = hdulist[1].data
wave = scidata[0][0]
arr1 = scidata[0][1]
arr2 = scidata[0][2]
# etc.
# where arr1 will contain the data corresponding to the column named: hdulist[1].columns[1]
# where arr2 will contain the data corresponding to the column named: hdulist[1].columns[2]
# etc.
# To plot using maptplotlib:
import matplotlib.pyplot as plt
plt.plot(wave, arr1)
plt.show()
但是,当将此代码放入并使用s1d文件时,我发现indexer:list index超出了范围
HDUlist.info()由一个索引为0的主HDU组成
No. Name Ver Type Cards Dimensions Format
0 PRIMARY 1 PrimaryHDU 3051 (313088,) float32
打印这些数据表明它是一个1d阵列:
[ 45.182148 71.06376 3.1499128 ... 631.7653 628.2799
632.91364]
所以我不知道如何绘制这个光谱,因为它只有1d
Eso还有一个更复杂的代码来绘制光谱,可以在网站上找到。文件是1dspectrum.py,可以下载。一旦我在那里输入了我的文件,我也会得到一个索引错误,这可以在gyazo中看到
伊瓜纳努特的解决方案
将其作为以下代码:
import numpy as np
from astropy.io import fits
from astropy.units import u
import matplotlib.pyplot as plt
import specutils
f = fits.open('C:/Users/Rp199/Desktop/J0608_59_harps_2018/HARPS.2018-05-23T23_44_45.005_s1d_A.fits')
f.info()
No. Name Ver Type Cards Dimensions Format
0 PRIMARY 1 PrimaryHDU 3055 (313093,) float32
检查了标题,它们是相同的,所以我删除了BUNIT,并将CTYPE1更改为CUNIT1
del header['BUNIT']
header['CTYPE1'] = header['CUNIT1']
del header['CTYPE1']
然后我尝试使用spectrum1D.read
spec = specutils.Spectrum1D.read(f)
spec
这给了我以下的错误
IORegistryError Traceback (most recent call last)
<ipython-input-28-62aceed26d07> in <module>
----> 1 spec = specutils.Spectrum1D.read(f)
2 spec
~\anaconda3\lib\site-packages\astropy\nddata\mixins\ndio.py in __call__(self, *args, **kwargs)
54
55 def __call__(self, *args, **kwargs):
---> 56 return registry.read(self._cls, *args, **kwargs)
57
58
~\anaconda3\lib\site-packages\astropy\io\registry.py in read(cls, format, *args, **kwargs)
517 fileobj = args[0]
518
--> 519 format = _get_valid_format(
520 'read', cls, path, fileobj, args, kwargs)
521
~\anaconda3\lib\site-packages\astropy\io\registry.py in _get_valid_format(mode, cls, path, fileobj, args, kwargs)
597 if len(valid_formats) == 0:
598 format_table_str = _get_format_table_str(cls, mode.capitalize())
--> 599 raise IORegistryError("Format could not be identified based on the"
600 " file name or contents, please provide a"
601 " 'format' argument.\n"
IORegistryError: Format could not be identified based on the file name or contents, please provide a 'format' argument.
The available formats are:
Format Read Write Auto-identify
----------------- ---- ----- -------------
APOGEE apStar Yes No Yes
APOGEE apVisit Yes No Yes
APOGEE aspcapStar Yes No Yes
ASCII Yes No Yes
ECSV Yes No Yes
HST/COS Yes No Yes
HST/STIS Yes No Yes
IPAC Yes No Yes
JWST s2d Yes No Yes
JWST s3d Yes No Yes
JWST x1d Yes No Yes
SDSS-I/II spSpec Yes No Yes
SDSS-III/IV spec Yes No Yes
Subaru-pfsObject Yes No Yes
iraf Yes No Yes
muscles-sed Yes No Yes
tabular-fits Yes Yes Yes
wcs1d-fits Yes No Yes
我被退回这个,
TypeError Traceback (most recent call last)
<ipython-input-29-c038104effad> in <module>
----> 1 spec = specutils.Spectrum1D.read(f, format="wcs1d-fits")
2 spec
~\anaconda3\lib\site-packages\astropy\nddata\mixins\ndio.py in __call__(self, *args, **kwargs)
54
55 def __call__(self, *args, **kwargs):
---> 56 return registry.read(self._cls, *args, **kwargs)
57
58
~\anaconda3\lib\site-packages\astropy\io\registry.py in read(cls, format, *args, **kwargs)
521
522 reader = get_reader(format, cls)
--> 523 data = reader(*args, **kwargs)
524
525 if not isinstance(data, cls):
~\anaconda3\lib\site-packages\specutils\io\default_loaders\wcs_fits.py in wcs1d_fits_loader(file_name, spectral_axis_unit, flux_unit, hdu_idx, **kwargs)
63 logging.info("Spectrum file looks like wcs1d-fits")
64
---> 65 with fits.open(file_name, **kwargs) as hdulist:
66 header = hdulist[hdu_idx].header
67 wcs = WCS(header)
~\anaconda3\lib\site-packages\astropy\io\fits\hdu\hdulist.py in fitsopen(name, mode, memmap, save_backup, cache, lazy_load_hdus, **kwargs)
162 raise ValueError(f'Empty filename: {name!r}')
163
--> 164 return HDUList.fromfile(name, mode, memmap, save_backup, cache,
165 lazy_load_hdus, **kwargs)
166
~\anaconda3\lib\site-packages\astropy\io\fits\hdu\hdulist.py in fromfile(cls, fileobj, mode, memmap, save_backup, cache, lazy_load_hdus, **kwargs)
401 """
402
--> 403 return cls._readfrom(fileobj=fileobj, mode=mode, memmap=memmap,
404 save_backup=save_backup, cache=cache,
405 lazy_load_hdus=lazy_load_hdus, **kwargs)
~\anaconda3\lib\site-packages\astropy\io\fits\hdu\hdulist.py in _readfrom(cls, fileobj, data, mode, memmap, save_backup, cache, lazy_load_hdus, **kwargs)
1052 if not isinstance(fileobj, _File):
1053 # instantiate a FITS file object (ffo)
-> 1054 fileobj = _File(fileobj, mode=mode, memmap=memmap, cache=cache)
1055 # The Astropy mode is determined by the _File initializer if the
1056 # supplied mode was None
~\anaconda3\lib\site-packages\astropy\utils\decorators.py in wrapper(*args, **kwargs)
533 warnings.warn(message, warning_type, stacklevel=2)
534
--> 535 return function(*args, **kwargs)
536
537 return wrapper
~\anaconda3\lib\site-packages\astropy\io\fits\file.py in __init__(self, fileobj, mode, memmap, overwrite, cache)
193 self._open_filename(fileobj, mode, overwrite)
194 else:
--> 195 self._open_filelike(fileobj, mode, overwrite)
196
197 self.fileobj_mode = fileobj_mode(self._file)
~\anaconda3\lib\site-packages\astropy\io\fits\file.py in _open_filelike(self, fileobj, mode, overwrite)
544
545 if mode == 'ostream':
--> 546 self._overwrite_existing(overwrite, fileobj, False)
547
548 # Any "writeable" mode requires a write() method on the file object
~\anaconda3\lib\site-packages\astropy\io\fits\file.py in _overwrite_existing(self, overwrite, fileobj, closed)
442 # The file will be overwritten...
443 if ((self.file_like and hasattr(fileobj, 'len') and fileobj.len > 0) or
--> 444 (os.path.exists(self.name) and os.path.getsize(self.name) != 0)):
445 if overwrite:
446 if self.file_like and hasattr(fileobj, 'truncate'):
~\anaconda3\lib\genericpath.py in exists(path)
17 """Test whether a path exists. Returns False for broken symbolic links"""
18 try:
---> 19 os.stat(path)
20 except (OSError, ValueError):
21 return False
TypeError: stat: path should be string, bytes, os.PathLike or integer, not method
TypeError回溯(最近一次调用)
在里面
---->1 spec=specutils.Spectrum1D.read(f,format=“wcs1d-fits”)
2规格
~\anaconda3\lib\site packages\astropy\nddata\mixins\ndio.py在调用中(self,*args,**kwargs)
54
55定义调用(self,*args,**kwargs):
--->56返回注册表。读取(self._cls,*args,**kwargs)
57
58
读取中的~\anaconda3\lib\site packages\astropy\io\registry.py(cls,格式,*args,**kwargs)
521
522读取器=获取读取器(格式,cls)
-->523数据=读卡器(*args,**kwargs)
524
525如果不存在(数据、cls):
~\anaconda3\lib\site packages\specutils\io\default\u loaders\wcs1d\u fits\u loader中的wcs\u fits.py(文件名、光谱轴单位、通量单位、hdu\u idx、**kwargs)
63 logging.info(“频谱文件看起来像wcs1d适合”)
64
--->65带有fits.open(文件名,**kwargs)作为hdulist:
66 header=hdulist[hdu_idx]。header
67 wcs=wcs(收割台)
fitsopen中的~\anaconda3\lib\site packages\astropy\io\fits\hdu\hdulist.py(名称、模式、memmap、保存、备份、缓存、延迟加载、**kwargs)
162 raise VALUERROR(f'空文件名:{name!r}')
163
-->164返回HDUList.fromfile(名称、模式、memmap、save\u备份、缓存、,
165延迟加载HDU,**kwargs)
166
~\anaconda3\lib\site packages\astropy\io\fits\hdu\hdulist.py在fromfile中(cls、fileobj、mode、memmap、save\u backup、cache、lazy\u load\u hdus、**kwargs)
401 """
402
-->403返回cls.\u readfrom(fileobj=fileobj,mode=mode,memmap=memmap,
404保存备份=保存备份,缓存=缓存,
405延迟加载hdus=延迟加载hdus,**kwargs)
~\anaconda3\lib\site packages\astropy\io\fits\hdu\hdulist.py in\u readfrom(cls、fileobj、数据、模式、memmap、save\u备份、缓存、延迟加载\u hdus、**kwargs)
1052如果不存在(文件对象,_文件):
1053#实例化FITS文件对象(ffo)
->1054 fileobj=_文件(fileobj,mode=mode,memmap=memmap,cache=cache)
1055 35;如果
1056#提供的模式为无
包装中的~\anaconda3\lib\site packages\astropy\utils\decorators.py(*args,**kwargs)
533警告。警告(消息,警告类型,堆栈级别=2)
534
-->535返回函数(*args,**kwargs)
536
537返回包装器
~\anaconda3\lib\site packages\astropy\io\fits\file.py in\uuuuuu init\uuuuuu(self、fileobj、mode、memmap、overwrite、cache)
193 self.\u open\u文件名(fileobj,mode,overwrite)
194其他:
-->195 self.\u open\u filelike(fileobj,mode,overwrite)
196
197 self.fileobj_模式=fileobj_模式(self._文件)
~\anaconda3\lib\site packages\astropy\io\fits\file.py in\u open\u filelike(self、fileobj、mode、overwrite)
544
545如果模式=='ostream':
-->546 self.\u overwrite\u existing(overwrite,fileobj,False)
547
548#任何“可写”模式都需要文件对象上的write()方法
~\anaconda3\lib\site packages\astropy\io\fits\file.py在现有的覆盖中(self,overwrite,fileobj,closed)
442#文件将被覆盖。。。
443如果((self.file_like和hasattr(fileobj,'len')和fileobj.len>0)或
-->444(os.path.exists(self.name)和os.path.getsize(self.name)!=0)):
445如果覆盖:
446如果self.file_like和hasattr(fileobj,'truncate'):
存在中的~\anaconda3\lib\genericpath.py(路径)
17“测试路径是否存在。对于断开的符号链接“”返回False
18试试:
--->19操作系统状态(路径)
20除(操作错误、值错误)外:
21返回错误
TypeError:stat:path应该是字符串、字节、os.PathLike或整数,而不是方法
我查看了从下载的随机频谱。实际上,它只包含一个HDU,因此如果您尝试从不存在的HDU访问数据,您将获得一个索引器
链接到的代码可能很旧(毕竟它位于“归档”页面上),并且也只是一个示例,不一定适合打印任何FITS文件中的数据
该软件包有许多用于分析和绘制一维光谱的实用程序。它还可以从许多常见的FITS格式中读取光谱,而无需手动执行太多操作
我是这样做的。首先我打开了文件,尤其是这个文件:
>f=fits.open('https://www.eso.org/sci/facilities/lasilla/instruments/harps/inst/monitoring/sundata/ceres_2006-05-22_s1d.fits')
>>>f.信息()
f=配合。打开('https://www.eso.org/sci/facilities/lasilla/instruments/harps/inst/monitoring/sundata/ceres_2006-05-22_s1d.fits'
TypeError Traceback (most recent call last)
<ipython-input-29-c038104effad> in <module>
----> 1 spec = specutils.Spectrum1D.read(f, format="wcs1d-fits")
2 spec
~\anaconda3\lib\site-packages\astropy\nddata\mixins\ndio.py in __call__(self, *args, **kwargs)
54
55 def __call__(self, *args, **kwargs):
---> 56 return registry.read(self._cls, *args, **kwargs)
57
58
~\anaconda3\lib\site-packages\astropy\io\registry.py in read(cls, format, *args, **kwargs)
521
522 reader = get_reader(format, cls)
--> 523 data = reader(*args, **kwargs)
524
525 if not isinstance(data, cls):
~\anaconda3\lib\site-packages\specutils\io\default_loaders\wcs_fits.py in wcs1d_fits_loader(file_name, spectral_axis_unit, flux_unit, hdu_idx, **kwargs)
63 logging.info("Spectrum file looks like wcs1d-fits")
64
---> 65 with fits.open(file_name, **kwargs) as hdulist:
66 header = hdulist[hdu_idx].header
67 wcs = WCS(header)
~\anaconda3\lib\site-packages\astropy\io\fits\hdu\hdulist.py in fitsopen(name, mode, memmap, save_backup, cache, lazy_load_hdus, **kwargs)
162 raise ValueError(f'Empty filename: {name!r}')
163
--> 164 return HDUList.fromfile(name, mode, memmap, save_backup, cache,
165 lazy_load_hdus, **kwargs)
166
~\anaconda3\lib\site-packages\astropy\io\fits\hdu\hdulist.py in fromfile(cls, fileobj, mode, memmap, save_backup, cache, lazy_load_hdus, **kwargs)
401 """
402
--> 403 return cls._readfrom(fileobj=fileobj, mode=mode, memmap=memmap,
404 save_backup=save_backup, cache=cache,
405 lazy_load_hdus=lazy_load_hdus, **kwargs)
~\anaconda3\lib\site-packages\astropy\io\fits\hdu\hdulist.py in _readfrom(cls, fileobj, data, mode, memmap, save_backup, cache, lazy_load_hdus, **kwargs)
1052 if not isinstance(fileobj, _File):
1053 # instantiate a FITS file object (ffo)
-> 1054 fileobj = _File(fileobj, mode=mode, memmap=memmap, cache=cache)
1055 # The Astropy mode is determined by the _File initializer if the
1056 # supplied mode was None
~\anaconda3\lib\site-packages\astropy\utils\decorators.py in wrapper(*args, **kwargs)
533 warnings.warn(message, warning_type, stacklevel=2)
534
--> 535 return function(*args, **kwargs)
536
537 return wrapper
~\anaconda3\lib\site-packages\astropy\io\fits\file.py in __init__(self, fileobj, mode, memmap, overwrite, cache)
193 self._open_filename(fileobj, mode, overwrite)
194 else:
--> 195 self._open_filelike(fileobj, mode, overwrite)
196
197 self.fileobj_mode = fileobj_mode(self._file)
~\anaconda3\lib\site-packages\astropy\io\fits\file.py in _open_filelike(self, fileobj, mode, overwrite)
544
545 if mode == 'ostream':
--> 546 self._overwrite_existing(overwrite, fileobj, False)
547
548 # Any "writeable" mode requires a write() method on the file object
~\anaconda3\lib\site-packages\astropy\io\fits\file.py in _overwrite_existing(self, overwrite, fileobj, closed)
442 # The file will be overwritten...
443 if ((self.file_like and hasattr(fileobj, 'len') and fileobj.len > 0) or
--> 444 (os.path.exists(self.name) and os.path.getsize(self.name) != 0)):
445 if overwrite:
446 if self.file_like and hasattr(fileobj, 'truncate'):
~\anaconda3\lib\genericpath.py in exists(path)
17 """Test whether a path exists. Returns False for broken symbolic links"""
18 try:
---> 19 os.stat(path)
20 except (OSError, ValueError):
21 return False
TypeError: stat: path should be string, bytes, os.PathLike or integer, not method
>>> header = f[0].header
>>> header[:12]
SIMPLE = T / file does conform to FITS standard
BITPIX = -32 / number of bits per data pixel
NAXIS = 1 / number of data axes
NAXIS1 = 313237 / length of data axis 1
EXTEND = T / FITS dataset may contain extensions
COMMENT FITS (Flexible Image Transport System) format is defined in 'Astronomy
COMMENT and Astrophysics', volume 376, page 359; bibcode: 2001A&A...376..359H
CRPIX1 = 1. / Reference pixel
CRVAL1 = 3781.19 / Coordinate at reference pixel
CDELT1 = 0.01 / Coordinate increment par pixel
CTYPE1 = 'Angstrom' / Units of coordinate
BUNIT = 'Relative Flux' / Units of data values
ValueError: 'Relative Flux' did not parse as unit: At col 0, Relative is not a valid unit. If this is meant to be a custom unit, define it with 'u.def_unit'. To have it recognized inside a file reader or other code, enable it with 'u.add_enabled_units'. For details, see https://docs.astropy.org/en/latest/units/combining_and_defining.html