I'm trying to do a blank Stüve diagram.
My code is:
R=287.04 #Jkg^-1K^-1
cp=1005 #Jkg^-1K^-1
p0=1000 #hPa
L=2.5*10**6 #J kg^-1
temp_celsius = np.array(range(-80,41))
temp_kelvin=temp_celsius+273.15
pressure_hPa=np.array(range(1050,90,-10))
#make a grid of the data
tempdata,pressdata=np.meshgrid(temp_kelvin,pressure_hPa*100.)
#Initialise the arrays
pot_temp_kelvin=np.zeros(tempdata.shape)
es=pot_temp_kelvin
ms=es
pseudo_pot_temp_kelvin=es
#Get the potential temperature
pot_temp_kelvin=tempdata*(p0*100/pressdata)**(R/cp)
#Get the saturation mix ratio
#first the saturation vapor pressure after Magnus
#Definition of constants for the Magnus-formula
c1=17.62
c2=243.12
es=6.112*np.exp((17.62*(tempdata-273.15))/(243.12+tempdata-273.15)) #hPa
#Now I'm calculation the saturation mixing ratio
ms=622*(es/(pressdata/100-es)) #g/kg
#At least I need the pseudo-adiabatic potential temperature
pseudo_pot_temp_kelvin=pot_temp_kelvin*np.exp(L*ms/1000./cp/tempdata)
#define the levels which should be plotted in the figure
levels_theta=np.array(range(200,405,5))
levels_ms=np.array([0.1,0.2,0.5, 1.0, 1.5, 2.0, 3.0, 4.0, 6.0, 8.0, 10.0, 12.0, 15.0, 20.0, 25.0, 30.0])
levels_theta_e=np.array(range(220,410,10))
#The plot
fig = plt.figure(figsize=(15,15))
theta=plt.contour(temp_celsius,pressure_hPa,pot_temp_kelvin,levels_theta,colors='blue')
plt.clabel(theta,levels_theta[0::2], fontsize=10, fmt='%1.0f')
sat_mix_ratio=plt.contour(temp_celsius,pressure_hPa,ms,levels_ms,colors='green')
plt.clabel(sat_mix_ratio,fontsize=10,fmt='%1.1f')
theta_e=plt.contour(temp_celsius,pressure_hPa,pseudo_pot_temp_kelvin,levels_theta_e,colors='red')
plt.clabel(theta_e,levels_theta_e[1::2],fontsize=10,fmt='%1.0f')
plt.xlabel('Temperature [$^\circ$C]')
plt.ylabel('Pressure [hPa]')
plt.xticks(range(-80,45,5))
plt.xlim((-80,50))
plt.yticks(range(1050,50,-50))
plt.gca().invert_yaxis()
plt.grid(color='black',linestyle='-')
plt.show()
Everything works well but the real Stüve diagram should look like Stüve diagram with sounding
As you can see, the y-axis has a specific scale: p**(R/cp).... (=p**(287.04)/1005)
What do I have to do with my program so that my y-axis looks like the axis in the example?
You will have to define your own axis scale for this. My answer is based on this answer and the custom scale example.
This is the custom scaling class:
import matplotlib.pyplot as plt
import numpy as np
from matplotlib.ticker import FormatStrFormatter
from matplotlib import scale as mscale
from matplotlib import transforms as mtransforms
class CustomScale(mscale.ScaleBase):
name = 'custom'
def __init__(self, axis, **kwargs):
mscale.ScaleBase.__init__(self)
self.thresh = None #thresh
def get_transform(self):
return self.CustomTransform(self.thresh)
def set_default_locators_and_formatters(self, axis):
pass
class CustomTransform(mtransforms.Transform):
input_dims = 1
output_dims = 1
is_separable = True
def __init__(self, thresh):
mtransforms.Transform.__init__(self)
self.thresh = thresh
def transform_non_affine(self, a):
return a**(R/cp)
def inverted(self):
return CustomScale.InvertedCustomTransform(self.thresh)
class InvertedCustomTransform(mtransforms.Transform):
input_dims = 1
output_dims = 1
is_separable = True
def __init__(self, thresh):
mtransforms.Transform.__init__(self)
self.thresh = thresh
def transform_non_affine(self, a):
return a**(cp/R)
def inverted(self):
return CustomScale.CustomTransform(self.thresh)
# Now that the Scale class has been defined, it must be registered so
# that ``matplotlib`` can find it.
mscale.register_scale(CustomScale)
Now, you can use the following option to provide your custom scale to your y=axis:
plt.gca().set_yscale('custom')
The following plot compares the custom scale to a log-scale (plt.gca().set_yscale('log')) and the default without scale:
Related
I am attempting to create a program which simulates particles colliding in a 2D box, but each particle is labeled with a random 5 character string name and each collision is tracked in a list along each particle. So after the simulation, I would like a list from each particle listing which particles it has hit. I have forked this great simulation https://github.com/xnx/collision and added the name and history attributes to the particle class. However, whenever I attempt to access .name or .history, my kernel dies. The output says:
Kernel died, restarting
Restarting kernel...
The failure happens in the handle_collisions function (line 197), or whenever I try to access the history or the name, so there must be something wrong in my implementation of the name and history attributes. I have also tried to instantiate name and history in the init_particles function instead of place_particles but that had the same results. I'm not exactly sure how to correctly implement them. Thanks for your help.
import numpy as np
import matplotlib.pyplot as plt
from matplotlib.patches import Circle
from matplotlib import animation
from itertools import combinations
import random
import string
class Particle:
"""A class representing a two-dimensional particle."""
def __init__(self, x, y, vx, vy, name, history, radius=0.01, styles=None):
"""Initialize the particle's position, velocity, name, history and radius.
Any key-value pairs passed in the styles dictionary will be passed
as arguments to Matplotlib's Circle patch constructor.
"""
self.r = np.array((x, y))
self.v = np.array((vx, vy))
self.radius = radius
self.mass = self.radius**2
self.styles = styles
if not self.styles:
# Default circle styles
self.styles = {'edgecolor': 'b', 'fill': False}
# For convenience, map the components of the particle's position and
# velocity vector onto the attributes x, y, vx and vy.
#property
def x(self):
return self.r[0]
#x.setter
def x(self, value):
self.r[0] = value
#property
def y(self):
return self.r[1]
#y.setter
def y(self, value):
self.r[1] = value
#property
def vx(self):
return self.v[0]
#vx.setter
def vx(self, value):
self.v[0] = value
#property
def vy(self):
return self.v[1]
#vy.setter
def vy(self, value):
self.v[1] = value
#property
def history(self):
return self.history
#history.setter
def history(self,value):
self.history=value
#property
def name(self):
return self.name
#name.setter
def name(self,value):
self.name=value
def overlaps(self, other):
"""Does the circle of this Particle overlap that of other?"""
return np.hypot(*(self.r - other.r)) < self.radius + other.radius
def draw(self, ax):
"""Add this Particle's Circle patch to the Matplotlib Axes ax."""
circle = Circle(xy=self.r, radius=self.radius, **self.styles)
ax.add_patch(circle)
return circle
def advance(self, dt):
"""Advance the Particle's position forward in time by dt."""
self.r += self.v * dt
class Simulation:
"""A class for a simple hard-circle molecular dynamics simulation.
The simulation is carried out on a square domain: 0 <= x < 1, 0 <= y < 1.
"""
ParticleClass = Particle
def __init__(self, n, radius=0.01, styles=None):
"""Initialize the simulation with n Particles with radii radius.
Each particle is initialized with a 10 letter string name and an empty history.
radius can be a single value or a sequence with n values.
Any key-value pairs passed in the styles dictionary will be passed
as arguments to Matplotlib's Circle patch constructor when drawing
the Particles.
"""
self.init_particles(n, radius, styles)
self.dt = 0.01
def place_particle(self, rad, styles):
# Choose x, y so that the Particle is entirely inside the
# domain of the simulation.
x, y = rad + (1 - 2*rad) * np.random.random(2)
# Choose a random velocity (within some reasonable range of
# values) for the Particle.
vr = 0.1 * np.sqrt(np.random.random()) + 0.05
vphi = 2*np.pi * np.random.random()
vx, vy = vr * np.cos(vphi), vr * np.sin(vphi)
name = self.assignname
history = []
particle = self.ParticleClass(x, y, vx, vy, name, history, rad, styles)
# Check that the Particle doesn't overlap one that's already
# been placed.
for p2 in self.particles:
if p2.overlaps(particle):
break
else:
self.particles.append(particle)
return True
return False
def assignname(self):
letters = string.ascii_lowercase
name=''.join(random.choice(letters) for i in range(5))
return name
def init_particles(self, n, radius, styles=None):
"""Initialize the n Particles of the simulation.
Positions and velocities are chosen randomly; radius can be a single
value or a sequence with n values.
"""
try:
iterator = iter(radius)
assert n == len(radius)
except TypeError:
# r isn't iterable: turn it into a generator that returns the
# same value n times.
def r_gen(n, radius):
for i in range(n):
yield radius
radius = r_gen(n, radius)
self.n = n
self.particles = []
for i, rad in enumerate(radius):
# Try to find a random initial position for this particle.
while not self.place_particle(rad, styles):
pass
def change_velocities(self, p1, p2):
"""
Particles p1 and p2 have collided elastically: update their
velocities.
"""
m1, m2 = p1.mass, p2.mass
M = m1 + m2
r1, r2 = p1.r, p2.r
d = np.linalg.norm(r1 - r2)**2
v1, v2 = p1.v, p2.v
u1 = v1 - 2*m2 / M * np.dot(v1-v2, r1-r2) / d * (r1 - r2)
u2 = v2 - 2*m1 / M * np.dot(v2-v1, r2-r1) / d * (r2 - r1)
p1.v = u1
p2.v = u2
def handle_collisions(self):
"""Detect and handle any collisions between the Particles.
When two Particles collide, they do so elastically: their velocities
change such that both energy and momentum are conserved.
"""
# We're going to need a sequence of all of the pairs of particles when
# we are detecting collisions. combinations generates pairs of indexes
# into the self.particles list of Particles on the fly.
#particles share history when they collide
pairs = combinations(range(self.n), 2)
for i,j in pairs:
if self.particles[i].overlaps(self.particles[j]):
self.change_velocities(self.particles[i], self.particles[j])
#FAILS HERE
#self.particles[i].history.append(self.particles[j].name)
#self.particles[j].history.append(self.particles[i].name)
def handle_boundary_collisions(self, p):
"""Bounce the particles off the walls elastically."""
if p.x - p.radius < 0:
p.x = p.radius
p.vx = -p.vx
if p.x + p.radius > 1:
p.x = 1-p.radius
p.vx = -p.vx
if p.y - p.radius < 0:
p.y = p.radius
p.vy = -p.vy
if p.y + p.radius > 1:
p.y = 1-p.radius
p.vy = -p.vy
def apply_forces(self):
"""Override this method to accelerate the particles."""
pass
def advance_animation(self):
"""Advance the animation by dt, returning the updated Circles list."""
for i, p in enumerate(self.particles):
p.advance(self.dt)
self.handle_boundary_collisions(p)
self.circles[i].center = p.r
self.handle_collisions()
self.apply_forces()
return self.circles
def advance(self):
"""Advance the animation by dt."""
for i, p in enumerate(self.particles):
p.advance(self.dt)
self.handle_boundary_collisions(p)
self.handle_collisions()
self.apply_forces()
def init(self):
"""Initialize the Matplotlib animation."""
self.circles = []
for particle in self.particles:
self.circles.append(particle.draw(self.ax))
return self.circles
def animate(self, i):
"""The function passed to Matplotlib's FuncAnimation routine."""
self.advance_animation()
return self.circles
def setup_animation(self):
self.fig, self.ax = plt.subplots()
for s in ['top','bottom','left','right']:
self.ax.spines[s].set_linewidth(2)
self.ax.set_aspect('equal', 'box')
self.ax.set_xlim(0, 1)
self.ax.set_ylim(0, 1)
self.ax.xaxis.set_ticks([])
self.ax.yaxis.set_ticks([])
def save_or_show_animation(self, anim, save, filename='collision.mp4'):
if save:
Writer = animation.writers['ffmpeg']
writer = Writer(fps=10, bitrate=1800)
anim.save(filename, writer=writer)
else:
plt.show()
def do_animation(self, save=False, interval=1, filename='collision.mp4'):
"""Set up and carry out the animation of the molecular dynamics.
To save the animation as a MP4 movie, set save=True.
"""
self.setup_animation()
anim = animation.FuncAnimation(self.fig, self.animate,
init_func=self.init, frames=800, interval=interval, blit=True)
self.save_or_show_animation(anim, save, filename)
if __name__ == '__main__':
nparticles = 20
radii = .02
styles = {'edgecolor': 'C0', 'linewidth': 2, 'fill': None}
sim = Simulation(nparticles, radii, styles)
sim.do_animation(save=False)
I see two immediate problems in your code.
First: you did add history as a Particle.__init__ parameter but you never initialize the property itself.
Add something like this:
def __init__(self, x, y, vx, vy, name, history, radius=0.01, styles=None):
self._history = history
And bigger problem: you have an infinite recursion in your #property definition:
#property
def history(self):
return self.history
#history.setter
def history(self,value):
self.history=value
So in your getter you called history you call itself return self.history which will loop itself until program will crash.
Rename internal property to _history:
#property
def history(self):
return self._history
#history.setter
def history(self,value):
self._history=value
I'm trying to scale the x axis of a plot with math.log(1+x) instead of the usual 'log' scale option, and I've looked over some of the custom scaling examples but I can't get mine to work! Here's my MWE:
import matplotlib.pyplot as plt
import numpy as np
import math
from matplotlib.ticker import FormatStrFormatter
from matplotlib import scale as mscale
from matplotlib import transforms as mtransforms
class CustomScale(mscale.ScaleBase):
name = 'custom'
def __init__(self, axis, **kwargs):
mscale.ScaleBase.__init__(self)
self.thresh = None #thresh
def get_transform(self):
return self.CustomTransform(self.thresh)
def set_default_locators_and_formatters(self, axis):
pass
class CustomTransform(mtransforms.Transform):
input_dims = 1
output_dims = 1
is_separable = True
def __init__(self, thresh):
mtransforms.Transform.__init__(self)
self.thresh = thresh
def transform_non_affine(self, a):
return math.log(1+a)
def inverted(self):
return CustomScale.InvertedCustomTransform(self.thresh)
class InvertedCustomTransform(mtransforms.Transform):
input_dims = 1
output_dims = 1
is_separable = True
def __init__(self, thresh):
mtransforms.Transform.__init__(self)
self.thresh = thresh
def transform_non_affine(self, a):
return math.log(1+a)
def inverted(self):
return CustomScale.CustomTransform(self.thresh)
# Now that the Scale class has been defined, it must be registered so
# that ``matplotlib`` can find it.
mscale.register_scale(CustomScale)
z = [0,0.1,0.3,0.9,1,2,5]
thick = [20,40,20,60,37,32,21]
fig = plt.figure(figsize=(8,5))
ax1 = fig.add_subplot(111)
ax1.plot(z, thick, marker='o', linewidth=2, c='k')
plt.xlabel(r'$\rm{redshift}$', size=16)
plt.ylabel(r'$\rm{thickness\ (kpc)}$', size=16)
plt.gca().set_xscale('custom')
plt.show()
The scale consists of two Transform classes, each of which needs to provide a transform_non_affine method. One class needs to transform from data to display coordinates, which would be log(a+1), the other is the inverse and needs to transform from display to data coordinates, which would in this case be exp(a)-1.
Those methods need to handle numpy arrays, so they should use the respective numpy functions instead of those from the math package.
class CustomTransform(mtransforms.Transform):
....
def transform_non_affine(self, a):
return np.log(1+a)
class InvertedCustomTransform(mtransforms.Transform):
....
def transform_non_affine(self, a):
return np.exp(a)-1
There's no need to define classes yourself even the answer from #ImportanceOfBeingErnest does work.
You can use either FunctionScale or FunctionScaleLog to do this in one line. Take the FunctionScaleLog as example:
plt.gca().set_xscale("functionlog", functions=[lambda x: x + 1, lambda x: x - 1])
And with your full code:
import matplotlib.pyplot as plt
import numpy as np
z = [0, 0.1, 0.3, 0.9, 1, 2, 5]
thick = [20, 40, 20, 60, 37, 32, 21]
fig = plt.figure(figsize=(8, 5))
ax1 = fig.add_subplot(111)
ax1.plot(z, thick, marker="o", linewidth=2, c="k")
plt.xlabel(r"$\rm{redshift}$", size=16)
plt.ylabel(r"$\rm{thickness\ (kpc)}$", size=16)
# Below is my code
plt.gca().set_xscale("functionlog", functions=[lambda x: x + 1, lambda x: x - 1])
plt.gca().set_xticks(np.arange(0, 6))
plt.gca().set_xticklabels(np.arange(0, 6))
And the result is:
UPDATED:
I would like to plot real time y values generated randomly from Random_Generation_List.py. I have imported the python file and have them in the same folder. The points are only being printed and show only a vertical line on the graph. How do I fix this to make the points plot onto the graph in real time? Like a point every 0.001?
Random_Generation_List:
import random
import threading
def main():
for count in range(12000):
y = random.randint(0,1000)
print(y)
def getvalues():
return [random.randint(0,1000) for count in range(12000)]
def coordinate():
threading.Timer(0.0001, coordinate).start ()
coordinate()
main()
Real_Time_Graph
import time
from collections import deque
from matplotlib import pyplot as plt
from matplotlib import style
import Random_Generation_List
start = time.time()
class RealtimePlot:
def __init__(self, axes, max_entries = 100):
self.axis_x = deque(maxlen=max_entries)
self.axis_y = deque(maxlen=max_entries)
self.axes = axes
self.max_entries = max_entries
self.lineplot, = axes.plot([], [], "g-")
self.axes.set_autoscaley_on(True)
def add(self, x, y):
self.axis_x.append(x)
self.axis_y.append(y)
self.lineplot.set_data(self.axis_x, self.axis_y)
self.axes.set_xlim(self.axis_x[0], self.axis_x[-1] + 1e-15)
self.axes.relim(); self.axes.autoscale_view() # rescale the y-axis
def animate(self, figure, callback, interval = 50):
def wrapper(frame_index):
self.add(*callback(frame_index))
self.axes.relim(); self.axes.autoscale_view() # rescale the y-axis
return self.lineplot
def main():
style.use('dark_background')
fig, axes = plt.subplots()
display = RealtimePlot(axes)
axes.set_xlabel("Seconds")
axes.set_ylabel("Amplitude")
values = Random_Generation_List.getvalues()
print(values)
while True:
display.add(time.time() - start, values)
plt.pause(0.001)
display.animate(fig, lambda frame_index: (time.time() - start, values))
plt.show()
if __name__ == "__main__": main()
Error Message:
raise RuntimeError('xdata and ydata must be the same length')
RuntimeError: xdata and ydata must be the same length
I see that set_xscale accepts a base parameter, but I also want to scale with a factor; i.e. if the base is 4 and the factor is 10, then:
40, 160, 640, ...
Also, the documentation says that the sub-grid values represented by subsx should be integers, but I will want floating-point values.
What is the cleanest way to do this?
I'm not aware of any built-in method to apply a scaling factor after the exponent, but you could create a custom tick locator and formatter by subclassing matplotlib.ticker.LogLocator and matplotlib.ticker.LogFormatter.
Here's a fairly quick-and-dirty hack that does what you're looking for:
from matplotlib import pyplot as plt
from matplotlib.ticker import LogLocator, LogFormatter, ScalarFormatter, \
is_close_to_int, nearest_long
import numpy as np
import math
class ScaledLogLocator(LogLocator):
def __init__(self, *args, scale=10.0, **kwargs):
self._scale = scale
LogLocator.__init__(self, *args, **kwargs)
def view_limits(self, vmin, vmax):
s = self._scale
vmin, vmax = LogLocator.view_limits(self, vmin / s, vmax / s)
return s * vmin, s * vmax
def tick_values(self, vmin, vmax):
s = self._scale
locs = LogLocator.tick_values(self, vmin / s, vmax / s)
return s * locs
class ScaledLogFormatter(LogFormatter):
def __init__(self, *args, scale=10.0, **kwargs):
self._scale = scale
LogFormatter.__init__(self, *args, **kwargs)
def __call__(self, x, pos=None):
b = self._base
s = self._scale
# only label the decades
if x == 0:
return '$\mathdefault{0}$'
fx = math.log(abs(x / s)) / math.log(b)
is_decade = is_close_to_int(fx)
sign_string = '-' if x < 0 else ''
# use string formatting of the base if it is not an integer
if b % 1 == 0.0:
base = '%d' % b
else:
base = '%s' % b
scale = '%d' % s
if not is_decade and self.labelOnlyBase:
return ''
elif not is_decade:
return ('$\mathdefault{%s%s\times%s^{%.2f}}$'
% (sign_string, scale, base, fx))
else:
return (r'$%s%s\times%s^{%d}$'
% (sign_string, scale, base, nearest_long(fx)))
For example:
fig, ax = plt.subplots(1, 1)
x = np.arange(1000)
y = np.random.randn(1000)
ax.plot(x, y)
ax.set_xscale('log')
subs = np.linspace(0, 1, 10)
majloc = ScaledLogLocator(scale=10, base=4)
minloc = ScaledLogLocator(scale=10, base=4, subs=subs)
fmt = ScaledLogFormatter(scale=10, base=4)
ax.xaxis.set_major_locator(majloc)
ax.xaxis.set_minor_locator(minloc)
ax.xaxis.set_major_formatter(fmt)
ax.grid(True)
# show the same tick locations with non-exponential labels
ax2 = ax.twiny()
ax2.set_xscale('log')
ax2.set_xlim(*ax.get_xlim())
fmt2 = ScalarFormatter()
ax2.xaxis.set_major_locator(majloc)
ax2.xaxis.set_minor_locator(minloc)
ax2.xaxis.set_major_formatter(fmt2)
I have a class which accepts three arguments:
class Spheroid(object):
def __init__(self, shortaxis, longaxis, height):
self.shortax = shortaxis
self.longax = longaxis
self.h = height
self.alpha = longaxis/shortaxis
This is fine, but sometimes I like to do something like:
heights = np.linspace(0,1,100)
a = Spheroid(1.0,2.0,heights)
a.h
which gives me an array of the heights.
The longaxis and shortaxis are input parameters which I measure, but sometimes I'd like to do something like
class Spheroid(object):
def __init__(self, alpha, height):
self.alpha = alpha
self.h = height
alphas = np.linspace(0,3,30)
b = Spheroids(alphas, 0.5)
b.alpha
but I want to keep the longax and shortax as input parameters so I don't have to calculate alpha by hand.
Any ideas on how I can design this class to do what I want?