4

My goal is to plot a profile of a 2D FITS file that I already asked the user for with a try/except. I want to slice a part of this FITS file and then plot this part. I will just put my whole code here. I don't think there is anything wrong with the try/except part but the slicing and plotting have some erros.

My main problem is that the programme is giving me the following error ValueError: x and y can be no greater than 2-D, but have shapes (1L,) and (1L, 28L, 28L)

import os

files = [f for f in os.listdir('.') if os.path.isfile(f)]
for f in files:
if f.endswith(".fits"):
    print(f)

which gives me the two FITS files i have in my folder

from astropy.io import fits

valid = False
while not valid:
filename = input("Name of 2D FITS file:")
hdulist = fits.open(filename)
hdr= hdulist[0].header
try:
    naxis = hdr['NAXIS']
    valid = (naxis == 2)
    if not valid:
        print("Data structure is not two dimensional")
except Exception as e:
    print(e)
    valid = False

print("Valid input:", valid)  

hdulist = fits.open(filename)
hdr= hdulist[0].header 

Here ends my try/except and starts the messy part where i try to slice the FITS file over an angle

from matplotlib.pyplot import figure, show
from astropy.io import fits
data=hdulist[0].data

B=input("Enter the y value of the pixel defined as your starting value of the slice B=")
C=input("Enter the y value of the pixel defined as your stopping value of the slice C=")
D=input("Enter the x value of the pixel defined as your starting value of the slice D=")
E=input("Enter the x value of the pixel defined as your stopping value of the slice E=")

A = data[B:C,D:E]
astd = A.std()
print(astd)

fig = figure()
frame = fig.add_subplot(1,1,1)
mappable = frame.imshow(A, interpolation='none', origin="lower", cmap='jet', vmin=1500, vmax=8000)
cbar = fig.colorbar(mappable, ax=frame, fraction=0.046, pad=0.04)
show()

#the figure below always adjusts the axis such that the starting value is in the 
#lower left corner and the stopping value in the upper right corner

import math
R= math.degrees(math.atan((C-B)/(E-D)))
L= ((E-D)**2+(C-B)**2)**(0.5)

print("The line from the starting to the stopping point has a length of:", L)
print("The line from the starting to the stopping point has an angle in degrees of:", R)

F=int(L)
print(F)

This gives me a slice, now i want to put this in a profile and plot the whole thing.

# construct interpolation function
import numpy
import scipy
from scipy import interpolate
x = numpy.arange(data.shape[1])
y = numpy.arange(data.shape[0])
f = scipy.interpolate.interp2d(x, y, data)

# extract values on line from D, B to E, C  (degrees are not even necessary)
num_points = F
xvalues = numpy.linspace(D, E, num_points)
yvalues = numpy.linspace(B, C, num_points)
zvalues = f(xvalues, yvalues)

print(zvalues)

import numpy as np
from numpy import random
from matplotlib.pyplot import figure, show
from scipy import stats
from numpy import pi

profile=np.array([zvalues])

This is where i start to design the plot i used a previous design where velocity was used therefore the name "vels"

#Plot of profile

vels = np.linspace(0, 100, len(profile))

gam = profile.sum()
XY = (vels*profile).sum()
X0 = XY/gam
var = (1/gam)*(profile*(vels-X0)**2).sum()
sigma = var**0.5
skew = (1/gam)*(profile*(vels-X0)**3).sum()/sigma**3
kurt = (1/gam)*(profile*(vels-X0)**4).sum()/sigma**4

print("Mean:", X0)
print("Standard deviation:", sigma)
print("Skewness:", skew)
print("Fisher Kurtosis:", kurt-3)

a=profile.max
N=1000

def f(x,mu,sigma,a):
    return a*(np.exp)((-(x-mu)**2)/(2*sigma**2))

fig = figure()
frame = fig.add_subplot(1,1,1)
frame.plot(vels, profile,)
frame.plot(vels,f(vels,X0, sigma,profile.max()), color="pink")
frame.set_xlabel('x-axis')
frame.set_ylabel('y-axis')
frame.grid(True)
show()

This is what the programme returns once I try to execute it.

('Mean:', 0.0)
('Standard deviation:', 0.0)
('Skewness:', nan)
('Fisher Kurtosis:', nan)
C:\Users\Thomas\Anaconda2\lib\site-packages\ipykernel\__main__.py:10: RuntimeWarning: invalid value encountered in double_scalars
C:\Users\Thomas\Anaconda2\lib\site-packages\ipykernel\__main__.py:11: RuntimeWarning: invalid value encountered in double_scalars
---------------------------------------------------------------------------
ValueError                                Traceback (most recent call last)
<ipython-input-13-80786b6f31c3> in <module>()
     24 fig = figure()
     25 frame = fig.add_subplot(1,1,1)
---> 26 frame.plot(vels, profile,)
     27 frame.plot(vels,f(vels,X0, sigma,profile.max()), color="pink")
     28 frame.set_xlabel('x-axis')

C:\Users\Thomas\Anaconda2\lib\site-packages\matplotlib\__init__.pyc in inner(ax, *args, **kwargs)
   1889                     warnings.warn(msg % (label_namer, func.__name__),
   1890                                   RuntimeWarning, stacklevel=2)
-> 1891             return func(ax, *args, **kwargs)
   1892         pre_doc = inner.__doc__
   1893         if pre_doc is None:

C:\Users\Thomas\Anaconda2\lib\site-packages\matplotlib\axes\_axes.pyc in plot(self, *args, **kwargs)
   1404         kwargs = cbook.normalize_kwargs(kwargs, _alias_map)
   1405 
-> 1406         for line in self._get_lines(*args, **kwargs):
   1407             self.add_line(line)
   1408             lines.append(line)

C:\Users\Thomas\Anaconda2\lib\site-packages\matplotlib\axes\_base.pyc in _grab_next_args(self, *args, **kwargs)
    405                 return
    406             if len(remaining) <= 3:
--> 407                 for seg in self._plot_args(remaining, kwargs):
    408                     yield seg
    409                 return

C:\Users\Thomas\Anaconda2\lib\site-packages\matplotlib\axes\_base.pyc in _plot_args(self, tup, kwargs)
    383             x, y = index_of(tup[-1])
    384 
--> 385         x, y = self._xy_from_xy(x, y)
    386 
    387         if self.command == 'plot':

C:\Users\Thomas\Anaconda2\lib\site-packages\matplotlib\axes\_base.pyc in _xy_from_xy(self, x, y)
    245         if x.ndim > 2 or y.ndim > 2:
    246             raise ValueError("x and y can be no greater than 2-D, but have "
--> 247                              "shapes {} and {}".format(x.shape, y.shape))
    248 
    249         if x.ndim == 1:

ValueError: x and y can be no greater than 2-D, but have shapes (1L,) and (1L, 28L, 28L)
Iguananaut
  • 21,810
  • 5
  • 50
  • 63
Thomas
  • 53
  • 1
  • 6
  • Why did you introduce the third axis in `profile=np.array([zvalues])`? – user2357112 May 25 '17 at 20:48
  • I don't see where I've done that, zvalues has two axis right? Sorry I just started coding so my knowledge of code is limited. I re-used this part from a previous task I did. – Thomas May 26 '17 at 08:09
  • Ah, i just used `print(profile.shape)` and it gives me the following `(1L, 28L, 28L)`. I have no clue where that came from. Thanks for pointing me where my error is. – Thomas May 26 '17 at 08:18
  • Okay, using just my zvalues as profile finally gives me a plot without an error. Does `np.array()` always introduce a third axis? Thank you very much for your help! – Thomas May 26 '17 at 08:25
  • No, it's the extra brackets you put in there that introduced the third axis. – user2357112 May 26 '17 at 15:57
  • Ah okay, Thank you for your help! – Thomas May 29 '17 at 14:50

0 Answers0