# Working with stellar spectra in fits format in python

We are searching data for your request:

Forums and discussions:
Manuals and reference books:
Data from registers:
Wait the end of the search in all databases.
Upon completion, a link will appear to access the found materials.

Hey I am new to working with astronomical data in Python. I wanted to start working with stellar spectra and I am having trouble with the data. To get a first look I just wanted to plot a spectra (flux over wavelength). I downloaded the Miles library (http://research.iac.es/proyecto/miles/pages/stellar-libraries/miles-library.php) and started working with a single fits file. My first steps where as follows :

import numpy as np import matplotlib.pyplot as plt from astropy.io import fits hdul = fits.open('s0013.fits') data = hdul[0].data h1 = hdul[0].header

I read the header using print(repr(h1)) and know I wanted to plot the spectrum. The data has shape (1, 4367) and I am not sure how to proceed to achieve 2 arrays one with the wavelength and one with the flux to plot the data. I am sorry if this question is stupid but I can not figure it out.

Cheers

The information you need to recreate the wavelength array is in the World Coordinate System (WCS) of the header, specifically:

CRPIX1 = 1.00 CRVAL1 = 3500.0000 / central wavelength of first pixel CDELT1 = 0.900000 / linear dispersion (Angstrom/pixel)

which lists the starting/reference pixel of the wavelength array (1.0), the wavelength value at the start point (3500angstroms (assumed)) and the step per pixel (0.9Angstrom/pixel). To read this information, it is best to use a WCS library rather than trying to interpret them directly as they can be more complicated and there are many subformats of FITS WCS.

Fortunatelyastropyhas a module to make this easy (starting from your code above and extending it):

import numpy as np import matplotlib.pyplot as plt from astropy.io import fits from astropy.wcs import WCS hdul = fits.open('s0013.fits') data = hdul[0].data h1 = hdul[0].header obj_name = h1.get('OBJECT', 'Unknown') flux = data[0] w = WCS(h1, naxis=1, relax=False, fix=False) lam = w.wcs_pix2world(np.arange(len(flux)), 0)[0] plt.plot(lam, flux) plt.ylim(0, ) plt.xlabel('Wavelength (Angstrom)') plt.ylabel('Normalized flux') plt.savefig(obj_name + '.png">If you want to do more extended manipulation of spectra, particularly with the bewildering variety of wavelength and flux units, it might be worth looking at synphot and specutils which build on Astropy and add more direct support for spectra beyond simple numpy arrays. For example, you could make a synphotSourceSpectrumfrom the above by doing:from astropy import units as u from synphot import units, SourceSpectrum from synphot.spectrum import Empirical1D source_spec = SourceSpectrum(Empirical1D, points=lam*u.AA, lookup_table=flux, keep_neg=True, meta={'header': h1})

var s1= document.location.host;


 
 
 /*<![CDATA[*/ MathJax.Ajax.config.path["mhchem"] = "https://cdnjs.cloudflare.com/ajax/libs/mathjax-mhchem/3.3.2"; MathJax.Hub.Config({ jax: ["input/TeX","input/MathML","output/SVG"], extensions: ["tex2jax.js","mml2jax.js","MathMenu.js","MathZoom.js"], TeX: { extensions: ["autobold.js","mhchem.js","color.js","cancel.js", "AMSmath.js","AMSsymbols.js","noErrors.js","noUndefined.js"] }, "HTML-CSS": { linebreaks: { automatic: true , width: "90%"}, scale: 85, mtextFontInherit: false}, menuSettings: { zscale: "150%", zoom: "Double-Click" }, SVG: { linebreaks: { automatic: true } }}); /*]]>*/ Interesting Articles Solar Telescope Projector Screen? [& intro telescope for solar eclipse] November 29,2022 Is Pluto a “proto-planet”? November 29,2022 Very Old Stars in the Universe November 29,2022 
 Recommended Why was there a gap in the number of asteroid detections between 1807 and 1845? Astronomy Directionality of solar flares Astronomy Euclid, the father of geometry Biographies Popular Posts, 2022 How to calculate the time for the solar disk to pass the horizon and transit's lines Astronomy Apenninus mountains. The moon satellite Earth photos How can I calculate the time between sunset and actual darkness? Astronomy The windows to the Universe Solar system In which direction does the Milky Way rotate? Astronomy 
 
 
 Copyright 2022 \ Working with stellar spectra in fits format in python... 
 
 jQuery(document).ready(function($){$('.accordion-shortcode').find('.accordion-item-title').click(function(e){e.preventDefault();$(this).next().slideToggle(200);$(".accordion-item-content").not($(this).next()).slideUp(200);});}); var raspberry_iron_site_smooth_display="1"; var raspberry_iron_to_top="1";var raspberry_iron_to_top_mobile="1";var raspberry_iron_site_smooth_scroll="1";var raspberry_iron_site_smooth_display="1";var raspberry_iron_single_image_popup="1";var raspberry_iron_sticky_navigation="1"; eval(mod_pagespeed_PXnt_6glbt); eval(mod_pagespeed_6biOeGBGFy); (function(m,e,t,r,i,k,a){ m[i]=m[i]||function(){(m[i].a=m[i].a||[]).push(arguments)}; m[i].l=1*new Date(); k=e.createElement(t),a=e.getElementsByTagName(t)[0],k.async=1,k.src=r,a.parentNode.insertBefore(k,a) })(window, document,"script","//mc.yandex.ru/metrika/tag.js", "ym"); ym(56566693, "init", {accurateTrackBounce:true, trackLinks:true, webvisor:true, clickmap:true, params: {__ym: {isFromApi: "yesIsFromApi"}}}); new Image().src = "//counter.yadro.ru/hit?r"+ escape(document.referrer)+((typeof(screen)=="undefined")?"": ";s"+screen.width+"*"+screen.height+"*"+(screen.colorDepth? screen.colorDepth:screen.pixelDepth))+";u"+escape(document.URL)+ ";h"+escape(document.title.substring(0,150))+ ";"+Math.random(); (function(){var js = "window['__CF$cv\$params']={r:'771ac77a3a295c35',m:'TYWKZwZ8Gr8adZI1oZ3yB5paKeTnPi6nvRTdxUkKQ7o-1669718993-0-Abji8DY8Z0lK/ZE0KHKi0cdWwzVjqqUKDMIAY/tyOSJX0kiKIIzuG01enVgbiRb8aecZU3bCEYm76kGE+wFdgsr714GcUmx4C4yapZV3b5XYcIkojPhao7nNsi1ATWu9OiIwzJEnJIoKEne+aoa65t58Rxw+6jFUdyep7uzIWk5WOUcTG/Qg/sODNrtvi1P7xQ==',s:[0x1733f25705,0x46869f61b5],u:'/cdn-cgi/challenge-platform/h/b'};var now=Date.now()/1000,offset=14400,ts=''+(Math.floor(now)-Math.floor(now%offset)),_cpo=document.createElement('script');_cpo.nonce='',_cpo.src='/cdn-cgi/challenge-platform/h/b/scripts/alpha/invisible.js?ts='+ts,document.getElementsByTagName('head')[0].appendChild(_cpo);";var _0xh = document.createElement('iframe');_0xh.height = 1;_0xh.width = 1;_0xh.style.position = 'absolute';_0xh.style.top = 0;_0xh.style.left = 0;_0xh.style.border = 'none';_0xh.style.visibility = 'hidden';document.body.appendChild(_0xh);function handler() {var _0xi = _0xh.contentDocument || _0xh.contentWindow.document;if (_0xi) {var _0xj = _0xi.createElement('script');_0xj.nonce = '';_0xj.innerHTML = js;_0xi.getElementsByTagName('head')[0].appendChild(_0xj);}}if (document.readyState !== 'loading') {handler();} else if (window.addEventListener) {document.addEventListener('DOMContentLoaded', handler);} else {var prev = document.onreadystatechange || function () {};document.onreadystatechange = function (e) {prev(e);if (document.readyState !== 'loading') {document.onreadystatechange = prev;handler();}};}})();