NXW
NXW

Reputation: 61

Struggling to Understand Error Message

I'm trying to run the code below, where Bwavelength, throughput and newflux are lists.

def ABconversion(Bwavelength, throughput):
    ABconstant=[]

    c=3e18
    i=0
    for i in range(0, len(Bwavelength)):
        ABconstant.append(((3e18/((Bwavelength[i])**2))*throughput[i]))
        i+=1
        print len(Bwavelength), len(ABconstant), ABconstant
        a=Bwavelength[0]
        b=Bwavelength[-1]
        h=((b-a)/len(Bwavelength))
        ABflux = numpy.trapz(Bwavelength, ABconstant, h)
        return ABflux

 def ABmagnitude(newflux, ABflux):
    ABmagarray=[]
    for i in range(len(newflux)):
        ABmag = -2.5*log10((newflux[i])/ABflux) - 48.6
        ABmagarray.append(ABmag)
    return ABmagarray

ABflux1 = ABconversion(Bwavelength, throughput)
print ABflux1
ABmagarray = ABmagnitude(z, ABflux1)
print epoch, ABmagarray

z is defined earlier in the file and is also a list.

However, when I run this I get the message:

Traceback (most recent call last):
  File "Rewrite17.11.2014.py", line 196, in <module>
    ABflux1 = ABconversion(Bwavelength, throughput)
  File "Rewrite17.11.2014.py", line 186, in ABconversion
    ABflux = numpy.trapz(Bwavelength, ABconstant, h)
  File "C:\Python27\lib\site-packages\numpy\lib\function_base.py, line 3234, in trapz
    ret = add.reduce(d * (y[slice1]+y[slice2]/2.0, axis)
ValueError: Operands could not be broadcast together with shapes (0,) (444,)

I don't quite understand the error (I'm fairly new to programming), but I think it means the two "shapes" don't have the same dimensions. I'm not sure why this is.

Thanks in advance.

Upvotes: 0

Views: 285

Answers (2)

Irshad Bhat
Irshad Bhat

Reputation: 8709

Replace:

numpy.trapz(Bwavelength, ABconstant, h)

with:

numpy.trapz(np.array(Bwavelength)[:,np.newaxis], ABconstant, h)

Upvotes: 1

ErikR
ErikR

Reputation: 52039

According to this documentation the parameters to trapz(y, x, dx, axis) are:

  • y - Array like - input array to integrate.
  • x - Optional array - If x is None, then spacing between all y elements is dx.
  • dx - Optional scalar - If x is None, spacing given by dx is assumed. Default is 1.
  • axis - Optional Int - specify the axis.

So you shouldn't specify both x and dx - one of them should be None.

Perhaps this is what you want: trapz(Bwavelength, None, h).

See this answer for more details on the error message and NumPy's "braodcasting rule".

Upvotes: 1

Related Questions