Blog

A blog of Python-related topics and code.

Non-linear least squares fitting of a two-dimensional data

The scipy.optimize.curve_fit routine can be used to fit two-dimensional data, but the fitted data (the ydata argument) must be repacked as a one-dimensional array first. The independent variable (the xdata argument) must then be an array of shape (2,M) where M is the total number of data points.

ExB drift for an arbitrary electric potential

As described in the previous blog post charged particle moving in crossed constant magnetic and electric fields exhibits a drift velocity, $(\boldsymbol{E}\times\boldsymbol{B})/B^2$, perpendicular to both $\boldsymbol{E}$ and $\boldsymbol{B}$. The particle's trajectory in this situation can be found analytically. For an arbitrary $\boldsymbol{E}$, some kind of numerical integration of the equation of motion is usually necessary, but the force that the particle experiences at an instant is perpendicular to to the electric field and the particle therefore undergoes its gyromotion along an isocontour of electrostatic potential, $V$ (since $\boldsymbol{E} = -\nabla V$).

ExB drift for constant crossed electric and magnetic fields

A charged particle moving in an electromagnetic field exhibits a "drift" in addition to its gyromotion and any acceleration due to a component of the electric field parallel to the magnetic field. This drift motion has velocity $(\boldsymbol{E}\times\boldsymbol{B})/B^2$ and is therefore known as the $\boldsymbol{E}\times\boldsymbol{B}$ drift. In the simple case of constant, crossed magnetic and electric fields, the Lorentz equation of motion, $m\ddot{\boldsymbol{r}} = q(\boldsymbol{E} + \dot{\boldsymbol{r}} \times \boldsymbol{B})$ can be solved analytically to give the particle's trajectory: $$ \begin{align} x &= \frac{1}{\Omega}\left( v_\perp - \frac{E_y}{B_z}\right)\sin \Omega t + \frac{E_y}{B_z}t,\\ y &= \frac{1}{\Omega}\left( v_\perp - \frac{E_y}{B_z}\right)\left(1 - \cos \Omega t \right),\\ z &= 0, \end{align} $$ where the fields are $\boldsymbol{B} = (0,0,B_z)$ and $\boldsymbol{E} = (0,E_y,0)$; the initial velocity is $\boldsymbol{v} = (0,v_\perp,0)$; the gyrofrequency is $\Omega = qB_z/m$; and $m$ and $q$ are the particle's mass and charge respectively.

Depicting a torus as an SVG image

SVG may not be the most obvious choice for depicting a 3-D object, but with some care over the perspective and ordering of the plotted points, it can be done.

Generating an SVG clock face

This is a simple Python function to generate a clock face indicating a specified time. It can be used in the script below to generate 1, 2, 4 or 6 faces indicating random times to teach children how to tell the time. Run this script from the command line as