Geometric estimation of area of cropped circle - python

I have a rectangular frame and a circle with center and radius randomly generated. The center is always located within the limits of the frame, as shown:
I need to estimate the area of the fraction of the circle that is located within the frame. Currently I employ a simple Monte Carlo estimate that works ok, but I'd like to compare this with an exact geometric estimation of this area.
Is there a library and/or method to do this? I'm open to pretty much anything that can be installed with conda or pip.
import numpy as np
import matplotlib.pyplot as plt
def circFrac(cx, cy, rad, x0, x1, y0, y1, N_tot=100000):
"""
Use Monte Carlo to estimate the fraction of the area of a circle centered
in (cx, cy) with a radius of 'rad', that is located within the frame given
by the limits 'x0, x1, y0, y1'.
"""
# Source: https://stackoverflow.com/a/50746409/1391441
r = rad * np.sqrt(np.random.uniform(0., 1., N_tot))
theta = np.random.uniform(0., 1., N_tot) * 2 * np.pi
xr = cx + r * np.cos(theta)
yr = cy + r * np.sin(theta)
# Points within the circle that are within the frame.
msk_xy = (xr > x0) & (xr < x1) & (yr > y0) & (yr < y1)
# The area is the points within circle and frame over the points within
# circle.
return msk_xy.sum() / N_tot
for _ in range(10):
# Random (x, y) limits of the frame
x0, y0 = np.random.uniform(0., 500., 2)
x1, y1 = np.random.uniform(500., 1000., 2)
# Random center coordinates *always* within the frame
cx = np.random.uniform(x0, x1)
cy = np.random.uniform(y0, y1)
# Random radius
rad = np.random.uniform(10., 500)
frac = circFrac(cx, cy, rad, x0, x1, y0, y1)
plt.xlim(x0, x1)
plt.ylim(y0, y1)
circle = plt.Circle((cx, cy), rad, fill=False)
plt.gca().add_artist(circle)
plt.scatter(
cx, cy, marker='x', c='r', label="({:.0f}, {:.0f}), r={:.0f}".format(
cx, cy, rad))
plt.legend()
plt.title("Fraction of circle inside frame: {:.2f}".format(frac))
plt.axes().set_aspect('equal')
plt.show()

You can use shapely for that:
import shapely.geometry as g
xr,yr,r = 0,0,5
circle = g.Point(xr,yr).buffer(r)
x1,y1,x2,y2 = -1,-2,3,5
rectangle = g.Polygon([(x1,y1),(x1,y2),(x2,y2),(x2,y1)])
intersection = rectangle.intersection(circle)
intersection.area

Related

plotting triangle inside circle

I am creating a circle and want to then develop a right-angle triangle, or any isometric form of a triangle. Whereby, I can take any line distance between two edges of the circle and draw arrows toward the peak point.
For example:
import numpy as np
import matplotlib.pyplot as plt
import math
theta = np.linspace(0, 2*np.pi, 100)
x1 = np.cos(theta)
y1 = np.sin(theta)
plt.plot(x1, y1)
for i in [min(y1), max(y1)]:
plt.plot(0, i, '-ok', mfc='C1', mec='C1')
plt.arrow(0,min(y1),0,2*max(y1),width=0.001,color='red',head_starts_at_zero=False)
plt.arrow(min(x1), (1/2)*min(y1), 2*max(x1), (1/2)*max(y1),width=0.001,color='red',head_starts_at_zero=False)
However, I cannot accurately get the distance between two points correct when i aim for any form of a triangle.
However, I can easily achieve it when setting y to 0 in the second arrow. Perhaps there is a general equation to do this?
Like this:
import numpy as np
import matplotlib.pyplot as plt
import math
theta = np.linspace(0, 2*np.pi, 100)
x1 = np.cos(theta)
y1 = np.sin(theta)
plt.plot(x1, y1)
x = np.array([0,120,240,0])
y = np.array([0,120,240,0])
x = np.cos( x * np.pi / 180 )
y = np.sin( y * np.pi / 180 )
plt.plot( x, y, color='red' )
plt.show()
Output:
In fact, if you choose ANY three angles, you'll get an inscribed triangle.

ploting the normal vector to a plane

The normal vector is calculated with the cross product of two vectors on the plane, so it shoud be perpendicular to the plane. But as you can seein the plot the normal vector produced with quiver isn't perpendicular.
Is the calculation of the plane wrong, my normal vector or the way i plot the normal vector?
import numpy as np
import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import Axes3D
points = [[3.2342, 1.8487, -1.8186],
[2.9829, 1.6434, -1.8019],
[3.4247, 1.5550, -1.8093]]
p0, p1, p2 = points
x0, y0, z0 = p0
x1, y1, z1 = p1
x2, y2, z2 = p2
ux, uy, uz = u = [x1-x0, y1-y0, z1-z0] #first vector
vx, vy, vz = v = [x2-x0, y2-y0, z2-z0] #sec vector
u_cross_v = [uy*vz-uz*vy, uz*vx-ux*vz, ux*vy-uy*vx] #cross product
point = np.array(p1)
normal = np.array(u_cross_v)
d = -point.dot(normal)
print('plane equation:\n{:1.4f}x + {:1.4f}y + {:1.4f}z + {:1.4f} = 0'.format(normal[0], normal[1], normal[2], d))
xx, yy = np.meshgrid(range(10), range(10))
z = (-normal[0] * xx - normal[1] * yy - d) * 1. / normal[2]
# plot the surface
plt3d = plt.figure().gca(projection='3d')
plt3d.quiver(x0, y0, z0, normal[0], normal[1], normal[2], color="m")
plt3d.plot_surface(xx, yy, z)
plt3d.set_xlabel("X", color='red', size=18)
plt3d.set_ylabel("Y", color='green', size=18)
plt3d.set_zlabel("Z", color='b', size=18)
plt.show()
Actually, your plot is 100% correct. The scale of your Z axis does not correspond to the same scale on X & Y axis. If you use a function to set the scale correct, you can see that:
...
plt3d.set_zlabel("Z", color='b', size=18)
# insert these lines
ax = plt.gca()
set_axis_equal(ax)
plt.show()
and the corresponding function from this post:
def set_axes_radius(ax, origin, radius):
'''
From StackOverflow question:
https://stackoverflow.com/questions/13685386/
'''
ax.set_xlim3d([origin[0] - radius, origin[0] + radius])
ax.set_ylim3d([origin[1] - radius, origin[1] + radius])
ax.set_zlim3d([origin[2] - radius, origin[2] + radius])
def set_axes_equal(ax, zoom=1.):
'''
Make axes of 3D plot have equal scale so that spheres appear as spheres,
cubes as cubes, etc.. This is one possible solution to Matplotlib's
ax.set_aspect("equal") and ax.axis("equal") not working for 3D.
input:
ax: a matplotlib axis, e.g., as output from plt.gca().
'''
limits = np.array([
ax.get_xlim3d(),
ax.get_ylim3d(),
ax.get_zlim3d(),
])
origin = np.mean(limits, axis=1)
radius = 0.5 * np.max(np.abs(limits[:, 1] - limits[:, 0])) / zoom
set_axes_radius(ax, origin, radius)

how to make arrow that loops in matplotlib?

what is the right way to draw an arrow that loops back to point to its origin in matplotlib? i tried:
plt.figure()
plt.xlim([0, 1])
plt.ylim([0, 1])
plt.annotate("", xy=(0.6, 0.9),
xycoords="figure fraction",
xytext = (0.6, 0.8),
textcoords="figure fraction",
fontsize = 10, \
color = "k",
arrowprops=dict(edgecolor='black',
connectionstyle="angle,angleA=-180,angleB=45",
arrowstyle = '<|-',
facecolor="k",
linewidth=1,
shrinkA = 0,
shrinkB = 0))
plt.show()
this doesn't give the right result:
the connectionstyle arguments are hard to follow from this page (http://matplotlib.org/users/annotations_guide.html).
i'm looking for is something like this or this:
update: the answer linked to does not show how do this with plt.annotate which has other features i want to use. the proposal to use $\circlearrowleft$ marker is not a real solution.
It seems the easiest way to create an easily modifiable looping arrow is to use patches. I've pasted code to do this below. Change the variables in the variables section and things should all rotate and scale together. You can play around with the patch that creates the arrow head to make a different shape though I suspect that this triangle will be the easiest one.
%matplotlib inline
# from __future__ import division #Uncomment for python2.7
import matplotlib.pyplot as plt
from matplotlib.patches import Arc, RegularPolygon
import numpy as np
from numpy import radians as rad
fig = plt.figure(figsize=(9,9))
ax = plt.gca()
def drawCirc(ax,radius,centX,centY,angle_,theta2_,color_='black'):
#========Line
arc = Arc([centX,centY],radius,radius,angle=angle_,
theta1=0,theta2=theta2_,capstyle='round',linestyle='-',lw=10,color=color_)
ax.add_patch(arc)
#========Create the arrow head
endX=centX+(radius/2)*np.cos(rad(theta2_+angle_)) #Do trig to determine end position
endY=centY+(radius/2)*np.sin(rad(theta2_+angle_))
ax.add_patch( #Create triangle as arrow head
RegularPolygon(
(endX, endY), # (x,y)
3, # number of vertices
radius/9, # radius
rad(angle_+theta2_), # orientation
color=color_
)
)
ax.set_xlim([centX-radius,centY+radius]) and ax.set_ylim([centY-radius,centY+radius])
# Make sure you keep the axes scaled or else arrow will distort
drawCirc(ax,1,1,1,0,250)
drawCirc(ax,2,1,1,90,330,color_='blue')
plt.show()
I find no way to make a loop using plt.annotate only once, but using it four times works :
import matplotlib.pyplot as plt
fig,ax = plt.subplots()
# coordinates of the center of the loop
x_center = 0.5
y_center = 0.5
radius = 0.2
# linewidth of the arrow
linewidth = 1
ax.annotate("", (x_center + radius, y_center), (x_center, y_center + radius),
arrowprops=dict(arrowstyle="-",
shrinkA=10, # creates a gap between the start point and end point of the arrow
shrinkB=0,
linewidth=linewidth,
connectionstyle="angle,angleB=-90,angleA=180,rad=10"))
ax.annotate("", (x_center, y_center - radius), (x_center + radius, y_center),
arrowprops=dict(arrowstyle="-",
shrinkA=0,
shrinkB=0,
linewidth=linewidth,
connectionstyle="angle,angleB=180,angleA=-90,rad=10"))
ax.annotate("", (x_center - radius, y_center), (x_center, y_center - radius),
arrowprops=dict(arrowstyle="-",
shrinkA=0,
shrinkB=0,
linewidth=linewidth,
connectionstyle="angle,angleB=-90,angleA=180,rad=10"))
ax.annotate("", (x_center, y_center + radius), (x_center - radius, y_center),
arrowprops=dict(arrowstyle="-|>",
facecolor="k",
linewidth=linewidth,
shrinkA=0,
shrinkB=0,
connectionstyle="angle,angleB=180,angleA=-90,rad=10"))
plt.show()
Try this:
import matplotlib.pyplot as plt
fig = plt.figure()
ax = fig.add_subplot(1,1,1)
ax.set_xlim(1,3)
ax.set_ylim(1,3)
ax.plot([2.5],[2.5],marker=r'$\circlearrowleft$',ms=100)
plt.show()
My suggestion uses just the plot command
import matplotlib.pyplot as plt
import numpy as np
def circarrowdraw(x0, y0, radius=1, aspect=1, direction=270, closingangle=-330,
arrowheadrelativesize=0.3, arrowheadopenangle=30, *args):
"""
Circular arrow drawing. x0 and y0 are the anchor points.
direction gives the angle of the circle center relative to the anchor
in degrees. closingangle indicates how much of the circle is drawn
in degrees with positive being counterclockwise and negative being
clockwise. aspect is important to make the aspect of the arrow
fit the current figure.
"""
xc = x0 + radius * np.cos(direction * np.pi / 180)
yc = y0 + aspect * radius * np.sin(direction * np.pi / 180)
headcorrectionangle = 5
if closingangle < 0:
step = -1
else:
step = 1
x = [xc + radius * np.cos((ang + 180 + direction) * np.pi / 180)
for ang in np.arange(0, closingangle, step)]
y = [yc + aspect * radius * np.sin((ang + 180 + direction) * np.pi / 180)
for ang in np.arange(0, closingangle, step)]
plt.plot(x, y, *args)
xlast = x[-1]
ylast = y[-1]
l = radius * arrowheadrelativesize
headangle = (direction + closingangle + (90 - headcorrectionangle) *
np.sign(closingangle))
x = [xlast +
l * np.cos((headangle + arrowheadopenangle) * np.pi / 180),
xlast,
xlast +
l * np.cos((headangle - arrowheadopenangle) * np.pi / 180)]
y = [ylast +
aspect * l * np.sin((headangle + arrowheadopenangle) * np.pi / 180),
ylast,
ylast +
aspect * l * np.sin((headangle - arrowheadopenangle) * np.pi / 180)]
plt.plot(x, y, *args)
To test it:
plt.figure()
plt.plot(np.arange(10)**2, 'b.')
bb = plt.gca().axis()
asp = (bb[3] - bb[2]) / (bb[1] - bb[0])
circarrowdraw(6, 36 , radius=0.4, aspect=asp, direction=90)
plt.grid()
plt.show()
Another possibility is to use tikz to generate the figure:
\documentclass {minimal}
\usepackage {tikz}
\begin{document}
\usetikzlibrary {arrows}
\begin {tikzpicture}[scale=1.8]
\draw[-angle 90, line width=5.0mm, rounded corners=20pt]
(0.25,0)-- (1.0, 0.0) -- (1.0, -3.0) -- (-3.0, -3.0) -- (-3.0, 0) --(-1,0);
\end{tikzpicture}
\end{document}
This is the result:
there is a pgf/tikz backend in matplotlib that you could generate your matplotlib output to tikz code that pdflatex or lualatex can process.
So this way, I think, you could insert seamlessly the looparrow figure in
your matplotlib figure.
See for ex:
http://matplotlib.org/users/whats_new.html#pgf-tikz-backend
#Aguy's answer is useful if you want a smooth arc instead of a complete circle. In Aguy's answer an arrow head is drawn line by line, but instead a FancyArrowPatch can be used. This gives a full arrow head, which might be more suitable. Below gives the code with the FancyArrowPatch arrow head.
def circarrowdraw(x0, y0, radius=1, aspect=1, direction=270, closingangle=-330, rotate_head = 0.0, color='b', *args):
"""
Circular arrow drawing. x0 and y0 are the anchor points.
direction gives the angle of the circle center relative to the anchor
in degrees. closingangle indicates how much of the circle is drawn
in degrees with positive being counterclockwise and negative being
clockwise. aspect is important to make the aspect of the arrow
fit the current figure. rotate_head is used to rotate the arrow head
by increasing the y value of the arrow's tail coordinate.
"""
# Center of circle
xc = x0 + radius * np.cos(direction * np.pi / 180)
yc = y0 + aspect * radius * np.sin(direction * np.pi / 180)
# Draw circle
if closingangle < 0:
step = -1
else:
step = 1
x = [xc + radius * np.cos((ang + 180 + direction) * np.pi / 180)
for ang in np.arange(0, closingangle, step)]
y = [yc + aspect * radius * np.sin((ang + 180 + direction) * np.pi / 180)
for ang in np.arange(0, closingangle, step)]
plt.plot(x, y, *args, color=color)
# Draw arrow head
arc_arrow_head = patches.FancyArrowPatch((x[-1], y[-1] + rotate_head),
(x[0], y[0]),
arrowstyle="Simple,head_width=10,head_length=10,tail_width=0.01",
color = color,
zorder = 10)
plt.gca().add_patch(arc_arrow_head)
To test it:
plt.plot([0, 0, 1, 1, 0], [0, 1, 1, 0, 0])
circarrowdraw(1.0, 1.0 , radius=0.1, aspect=0.3, direction=90, closingangle=-345, rotate_head = 0.003)
circarrowdraw(0.0, 1.0 , radius=0.1, aspect=1, direction=-90, closingangle=-345, rotate_head = 0.0)
circarrowdraw(0.0, 0.0 , radius=0.1, aspect=3.0, direction=90, closingangle=-345, rotate_head = 0.01)
circarrowdraw(1.0, 0.0 , radius=0.1, aspect=0.3, direction=-90, closingangle=-345)
plt.show()
Picture of image (I don't have a high enough reputation to embed the image in my answer)

FancyArrowPatch to edge of marker with known size?

I asked earlier on the matplotlib-user mailing list so apologies for the cross-post.
Say I have a marker with a known size in points and I want to draw an arrow to this point. How can I get the ends points for the arrow? As you can see in the below, it overlaps the markers. I want to go to the edge. I can use shrinkA and shrinkB to do what I want, but I don't see how they're related to the points size**.5. Or should I somehow do the transformation using the known angle between the two points and the point itself. I don't know how to translate a point in data coordinates and the offset it in a certain direction by size**.5 points. Can anyone help clear this up?
import matplotlib.pyplot as plt
from matplotlib.patches import FancyArrowPatch
point1 = (138.21, 19.5)
x1, y1 = point1
point2 = (67.0, 30.19)
x2, y2 = point2
size = 700
fig, ax = plt.subplots()
ax.scatter(*zip(point1, point2), marker='o', s=size)
# if I need to get and use the angles
dx = x2 - x1
dy = y2 - y1
d = np.sqrt(dx**2 + dy**2)
arrows = FancyArrowPatch(posA=(x1, y1), posB=(x2, y2),
color = 'k',
arrowstyle="-|>",
mutation_scale=700**.5,
connectionstyle="arc3")
ax.add_patch(arrows)
Edit: I made a little more progress. If I read the Translations Tutorial correctly, then this should give me a point on the radius of the markers. However, as soon as you resize the Axes then the transformation will be off. I'm stumped on what else to use.
from matplotlib.transforms import ScaledTranslation
# shift size points over and size points down so you should be on radius
# a point is 1/72 inches
dpi = ax.figure.get_dpi()
node_size = size**.5 / 2. # this is the radius of the marker
offset = ScaledTranslation(node_size/dpi, -node_size/dpi, fig.dpi_scale_trans)
shadow_transform = ax.transData + offset
ax.plot([x2], [y2], 'o', transform=shadow_transform, color='r')
import matplotlib.pyplot as plt
from matplotlib.patches import FancyArrowPatch
from matplotlib.transforms import ScaledTranslation
point1 = (138.21, 19.5)
x1, y1 = point1
point2 = (67.0, 30.19)
x2, y2 = point2
size = 700
fig, ax = plt.subplots()
ax.scatter(*zip(point1, point2), marker='o', s=size)
# if I need to get and use the angles
dx = x2 - x1
dy = y2 - y1
d = np.sqrt(dx**2 + dy**2)
arrows = FancyArrowPatch(posA=(x1, y1), posB=(x2, y2),
color = 'k',
arrowstyle="-|>",
mutation_scale=700**.5,
connectionstyle="arc3")
ax.add_patch(arrows)
# shift size points over and size points down so you should be on radius
# a point is 1/72 inches
def trans_callback(event):
dpi = fig.get_dpi()
node_size = size**.5 / 2. # this is the radius of the marker
offset = ScaledTranslation(node_size/dpi, -node_size/dpi, fig.dpi_scale_trans)
shadow_transform = ax.transData + offset
arrows.set_transform(shadow_transform)
cid = fig.canvas.mpl_connect('resize_event', trans_callback)
You also need to include something about the aspect ratio of the axes get points on the rim of the point (because the shape of the marker in data units in an ellipse unless the aspect ratio = 1)

Drawing ellipses on matplotlib basemap projections

I am trying to draw ellipses on a basemap projection. To draw a circle like polygon there is the tissot function used to draw Tissot's indicatrix' as illustrates the following example.
from mpl_toolkits.basemap import Basemap
x0, y0 = 35, -50
R = 5
m = Basemap(width=8000000,height=7000000, resolution='l',projection='aea',
lat_1=-40.,lat_2=-60,lon_0=35,lat_0=-50)
m.drawcoastlines()
m.tissot(x0, y0, R, 100, facecolor='g', alpha=0.5)
However, I am interested in plotting an ellipsis in the form (x-x0)**2/a**2 + (y-y0)**2/2 = 1. On the other hand, to draw an ellipsis on a regular Cartesian grid I can use the following sample code:
import pylab
from matplotlib.patches import Ellipse
fig = pylab.figure()
ax = pylab.subplot(1, 1, 1, aspect='equal')
x0, y0 = 35, -50
w, h = 10, 5
e = Ellipse(xy=(x0, y0), width=w, height=h, linewidth=2.0, color='g')
ax.add_artist(e)
e.set_clip_box(ax.bbox)
e.set_alpha(0.7)
pylab.xlim([20, 50])
pylab.ylim([-65, -35])
Is there a way to plot an ellipsis on a basemap projection with the an effect similar to tissot?
After hours analyzing the source code of basemap's tissot function, learning some properties of ellipses and lot's of debugging, I came with a solution to my problem. I've extended the basemap class with a new function called ellipse as follows,
from __future__ import division
import pylab
import numpy
from matplotlib.patches import Polygon
from mpl_toolkits.basemap import pyproj
from mpl_toolkits.basemap import Basemap
class Basemap(Basemap):
def ellipse(self, x0, y0, a, b, n, ax=None, **kwargs):
"""
Draws a polygon centered at ``x0, y0``. The polygon approximates an
ellipse on the surface of the Earth with semi-major-axis ``a`` and
semi-minor axis ``b`` degrees longitude and latitude, made up of
``n`` vertices.
For a description of the properties of ellipsis, please refer to [1].
The polygon is based upon code written do plot Tissot's indicatrix
found on the matplotlib mailing list at [2].
Extra keyword ``ax`` can be used to override the default axis instance.
Other \**kwargs passed on to matplotlib.patches.Polygon
RETURNS
poly : a maptplotlib.patches.Polygon object.
REFERENCES
[1] : http://en.wikipedia.org/wiki/Ellipse
"""
ax = kwargs.pop('ax', None) or self._check_ax()
g = pyproj.Geod(a=self.rmajor, b=self.rminor)
# Gets forward and back azimuths, plus distances between initial
# points (x0, y0)
azf, azb, dist = g.inv([x0, x0], [y0, y0], [x0+a, x0], [y0, y0+b])
tsid = dist[0] * dist[1] # a * b
# Initializes list of segments, calculates \del azimuth, and goes on
# for every vertex
seg = [self(x0+a, y0)]
AZ = numpy.linspace(azf[0], 360. + azf[0], n)
for i, az in enumerate(AZ):
# Skips segments along equator (Geod can't handle equatorial arcs).
if numpy.allclose(0., y0) and (numpy.allclose(90., az) or
numpy.allclose(270., az)):
continue
# In polar coordinates, with the origin at the center of the
# ellipse and with the angular coordinate ``az`` measured from the
# major axis, the ellipse's equation is [1]:
#
# a * b
# r(az) = ------------------------------------------
# ((b * cos(az))**2 + (a * sin(az))**2)**0.5
#
# Azymuth angle in radial coordinates and corrected for reference
# angle.
azr = 2. * numpy.pi / 360. * (az + 90.)
A = dist[0] * numpy.sin(azr)
B = dist[1] * numpy.cos(azr)
r = tsid / (B**2. + A**2.)**0.5
lon, lat, azb = g.fwd(x0, y0, az, r)
x, y = self(lon, lat)
# Add segment if it is in the map projection region.
if x < 1e20 and y < 1e20:
seg.append((x, y))
poly = Polygon(seg, **kwargs)
ax.add_patch(poly)
# Set axes limits to fit map region.
self.set_axes_limits(ax=ax)
return poly
This new function can be used promptly like in this example:
pylab.close('all')
pylab.ion()
m = Basemap(width=12000000, height=8000000, resolution='l', projection='stere',
lat_ts=50, lat_0=50, lon_0=-107.)
m.drawcoastlines()
m.fillcontinents(color='coral',lake_color='aqua')
# draw parallels and meridians.
m.drawparallels(numpy.arange(-80.,81.,20.))
m.drawmeridians(numpy.arange(-180.,181.,20.))
m.drawmapboundary(fill_color='aqua')
# draw ellipses
ax = pylab.gca()
for y in numpy.linspace(m.ymax/20, 19*m.ymax/20, 9):
for x in numpy.linspace(m.xmax/20, 19*m.xmax/20, 12):
lon, lat = m(x, y, inverse=True)
poly = m.ellipse(lon, lat, 3, 1.5, 100, facecolor='green', zorder=10,
alpha=0.5)
pylab.title("Ellipses on stereographic projection")
Which has the following outcome:

Categories

Resources