0

I have a function g(psi, k) where psi is a two components array and k is a real parameter. I would like to display the g function in a 3D contour plot with respect to the coordinates psi given a selected parameter k. How can I do that in Python?

I tried using the function contour3D with a wrapper function in the following way:

import numpy as np
import matplotlib.pyplot as plt

k = 32 # Change this value to display different plots

# Wrapper of the g function
def f(x, y):
    psi = np.array([x, y])
    return g(psi, k)

x = np.linspace(-6, 6, 30)
y = np.linspace(-6, 6, 30)

X, Y = np.meshgrid(x, y)
Z = f(X, Y)

fig = plt.figure()
ax = plt.axes(projection='3d')
ax.contour3D(X, Y, Z, 50, cmap='binary')
plt.show()

But I get the following error relative to the line Z = f(X, Y):

ValueError: setting an array element with a sequence.

Running simply:

print(f(-0.33, -0.5))

I obtain a real value as expected:

28.08105396614395

How can I fix it? Is there any other way more straightforward to display the plot of g(psi, 32)?

0

1 Answer 1

1

Your function g(psi, k) is probably only working with psi being a 1D array, meaning only accepting x and y being scalars. Either call f in a loop, or vectorize the g function. Here is how to call the function f in a loop:

Z = np.empty(shape=(X.shape))
for row, (xx, yy) in enumerate(zip(X,Y)):          # into rows
    for col, (xxx, yyy) in enumerate(zip(xx,yy)):  # rows to single values
        Z[row, col] = f(xxx, yyy)
Sign up to request clarification or add additional context in comments.

1 Comment

Yes I confirm you what you wrote about the g function :) your workaround works, thanks! I gave it a +1 but I will wait a little more to confirm it as the correct answer. I hope there is a more compact way of doing this. Thanks again!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.