Gradient and arrow plots

from scipy import *
import matplotlib.pyplot as plt


def plot_elines(x_grid, y_grid, potential, field):
    fig, ax = plt.subplots(figsize=(13, 13))
    im_cs = ax.contour(x_grid, y_grid, potential, 18, cmap='inferno')
    plt.clabel(im_cs, inline=1, fontsize=7)
    ax.quiver(x_grid[::3, ::3], y_grid[::3, ::3],
              field[0, ::3, ::3], field[1, ::3, ::3],)
    ax.set_xlabel("$x$")
    ax.set_ylabel("$y$")
    plt.show()


# define q configuration (x,y positions)
charges = [
    [1, 1],
]

xx, yy = meshgrid(linspace(-4, 4), linspace(-4, 4))
# potential function
e_pot = 0.
for idx, q in enumerate(charges):
    dx, dy = xx-q[0], yy-q[1]
    rr = hypot(dx, dy)
    e_pot += 1/(4*pi) * 1./rr
e_field = gradient(-e_pot)
e_field /= hypot(e_field[0], e_field[1]) * 5

# why is this needed?
e_field[0] = e_field[0].T
e_field[1] = e_field[1].T

plot_elines(xx, yy, e_pot, e_field)

I have a query concerning the usage of the gradient functionality from numpy/scipy.

In my current visualization, I am displaying the electric field equipotential lines and the field vectors for a single positive charge. According to the formula:

E = -grad(V)

The direction of the field vectors (quiver) and equipotential lines (contour) should be orthogonal at all points in space, directed away from the positive charge. However, when calculating E using scipy's gradient function, I noticed that transposing the x-y grid output is necessary for correct results.

When comparing the two outputs with and without .T:

vs

Why is the transpose operation required? Is there a mistake in how I am plotting the data?

Thank you.

Answer №1

It is interesting to note that the correct plot is achieved by coincidence when using the transpose, as the charge is symmetrically positioned along the x and y axes (i.e., on the 45° line).

The main issue arises from misinterpreting the numpy.gradient function. This function returns the gradient axis-wise, with the first array corresponding to axis 0 (y-axis) and the second array corresponding to axis 1 (x-axis).

e_field_y, e_field_x = numpy.gradient(-e_pot)

Therefore, when selecting the field components for the quiver plot, you should choose the first entry as the y component and the second entry as the x component.

ax.quiver(x_grid[::3, ::3], y_grid[::3, ::3],
          field[1, ::3, ::3], field[0, ::3, ::3],)

The complete code would look like this:

import numpy as np
import matplotlib.pyplot as plt

# Rest of the code follows here...
... 

In this revised version of the code, the charge has been placed off the anti-diagonal for demonstration purposes.

https://i.stack.imgur.com/R8MFQ.png

A useful tip: To ensure code consistency, try using grids with non-identical shapes. For instance, using different numbers of points along the x and y axes can help uncover errors earlier in the coding process.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Who snatched the python requests shib_idp_session cookies from the cookie jar's grasp?

Currently, I am experimenting with leveraging Python (3.9.1) along with requests (2.25.1) to log in using Shibboleth and Duo two-factor authentication (2FA). I possess all the necessary credentials for this process and regularly perform manual logins throu ...

What is the method for sorting a Python list both numerically in descending order and alphabetically in ascending order simultaneously?

My goal is to arrange a list that contains tuples with a word and a number. my_list = [('hello',25), ('hell',4), ('bell',4)] I am looking for a way to sort this list (maybe using lambda) in order to achieve the following: [ ...

Wait for the Selenium test to continue only when a specific element is visible on

<img style="width: 640; height: 640;" id="img108686545" alt="Loading Word War..." src="www.something.com/anu.jpg"> Is there a way to detect when this particular element is visible on the page? The value of the "id" attributes keeps changing with eac ...

Unpacking Key-Value Pairs in Python

I am developing a software program where I have a dictionary that contains only one key and one value. My goal is to assign the key to a variable named 'key' and the value to a variable named 'value.' Here is the relevant code snippet: ...

Using Sqlalchemy to apply a filter on an object

I am currently working on a script that will test various conditions of objects within a SQLAlachemy ORM driven database. The dynamic nature of this process has presented some challenges for me. My goal is to query the minimum number of objects for all te ...

Excluding specific elements using BeautifulSoup 4 in Python

Attempting to eliminate (rather than extract) data from a span. Here is the HTML snippet: <li><span>Type:</span> Cardiac Ultrasound</li> This is the code being used: item_description_infos = listing_soup.find(class_='item_desc ...

python selenium perform a click action at the present cursor location

I am dealing with a dropdown menu that requires clicking to activate. Unfortunately, the elements of the dropdown are not visible in the html code, making it impossible for me to locate and click on them directly. To navigate the dropdown, I use arrow keys ...

Using the Pandas library in Python to apply functions to column values based on a pattern in column names

I am working with a dataset: a b val1_b1 val1_b2 val2_b1 val2_v2 1 2 5 9 4 6 My goal is to find the maximum value for each column group, resulting in the transformed dataset: a b val1 val2 1 2 9 6 Alternatively, I am also ...

Is there a way to activate anti-detect settings for Selenium Chromedriver on tabs initiated by the webdriver?

Within Selenium Chromedriver, I have implemented various features such as adding a proxy, using a fake user agent, disabling WebRTC through an extension, and spoofing Webgl with selenium-stealth. Additionally, I have also spoofed the time zone and language ...

Looking for a Python library that supports proxy for Twitter Streaming API?

Anyone know of a Python library for the Twitter Streaming API that supports proxies? I like tweepy, but haven't found a way to use an HTTP proxy. Any suggestions? ...

Generating a figure with multiple subplots using Sympy

Currently working with sympy and matplotlib, I am aiming to create a plot with multiple subplots in a similar fashion to how it's done using pylab.subplot while utilizing numpy. In theory, this task should be straightforward, but as I delved into it, ...

Is it possible to operate a selenium webdriver without displaying the browser window?

I attempted to find a solution on this website because there is a question that closely resembles mine. Unfortunately, the suggested solution did not resolve my issue. Below is the current code I am working with... Is it feasible to initiate the webdriver ...

Mastering the art of list comprehension in Python: avoiding the common pitfall of getting stuck with a list of booleans

My goal is to eliminate periods, commas, single and double quotes from the end of each string within a list. Each string is part of a larger list of strings. string_list= ["cars." , "red" , "orange," , "man'" , "thus:"] desired_output --->["cars" ...

Python re.sub() function introduces additional backslashes to the characters

I am currently working with a json string that is enclosed in single quotes, leading me to escape single quotes within the string using a single backslash. However, when I try to write the output to a file, it ends up writing two backslashes instead of on ...

Using Python and Selenium to interact with dropdown menus in the browser

Being new to this, I've reviewed some of the examples provided here but despite their simplicity, I'm still struggling to make it work. The website I am trying to navigate is: www.webauto.de Below is my code for selecting a car make, model, and ...

Error: The __init__() function is lacking the required argument 'timeout.'

Despite initializing the super class constructor, I am encountering an error while trying to run some basic test cases for a simple project. Here is the code snippet: home.py class home(Pages): user = (By.NAME, "user-name") utxt = " ...

Allow SSL certificate using Marionette with Python's Splinter library in Firefox WebDriver

While utilizing Python Splinter with Firefox 47 and the new Marionette webdriver, I encounter a certificate error when trying to access a specific website. I attempted to resolve this issue by accepting SSL certificates using the following code: browser = ...

Searching for a solution on interacting with elements within the Shadow DOM using Selenium in Python?

Apologies for the lack of details, allow me to provide a comprehensive explanation. Situation: I aim to click on the 3-dot option menu, then select "Export" from the popup sub-menu and choose "CSV" in the subsequent pop-up sub-menu. Issue at Hand: The 3- ...

Manipulate JSON insertions and character replacements using JavaScript or Python

I have a JSON file that contains an array of 500 objects. The structure of each object is as follows: { "books":[ { "title":"Title 1", "year":"2012", "authors":"Jack ; George", }, { "title":"Title 2", "year":" ...

Utilizing aioprometheus and FastAPI to integrate metrics with external services

I'm currently working on integrating metrics for external services using aioprometheus within a FastAPI application. Below is an example showcasing my approach in a simplified manner. Let's consider a wrapper App class like this: from aioprometh ...