Skip to content

Instantly share code, notes, and snippets.

@astromme
Created June 16, 2017 01:04
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save astromme/599de466236adc534bc6e33cf2af8e7b to your computer and use it in GitHub Desktop.
Save astromme/599de466236adc534bc6e33cf2af8e7b to your computer and use it in GitHub Desktop.
Generate random points within quad
import random
import numpy as np
from shapely.geometry import Point
from shapely.geometry.polygon import Polygon
points = [
[0, 0],
[0, 1],
[1, 0],
[1, 1]
]
triangles = points[0:3], points[1:4]
def triangle_area(triangle):
v0, v1, v2 = triangle
x0, y0 = v0
x1, y1 = v1
x2, y2 = v2
return abs(0.5*(x0*(y0-y1)+x1*(y2-y0)+x2*(y0-y1)))
areas = [triangle_area(triangle) for triangle in triangles]
total_area = sum(areas)
weights = [area / total_area for area in areas]
for i, weight in enumerate(weights):
print("Weight {} (area of Triangle {} / total area)")
print(weight)
# currently works for 2 triangles
def pick_random(weights, triangles):
if random.random() < weights[0]:
i = 0
else:
i = 1
print("picked triangle {}".format(i))
a0 = random.random()
a1 = random.random()
print("a0: {}; a1: {}".format(a0, a1))
v0, v1, v2 = [np.array(v) for v in triangles[i]]
v3 = (v1 - v0) + (v2 - v0)
p = a0 * (v1 - v2) + a1 * (v2 - v0)
print("v0, v1, v2, v3: {}".format((v0, v1, v2, v3)))
print("p: {}".format(p))
polygon = Polygon([v0, v1, v2])
if polygon.contains(Point(p)):
return p
else:
print("not in triangle")
p = v0 + (v3 - p)
print(polygon.contains(Point(p)))
return p
for i in range(10):
print("random: {}".format(pick_random(weights, triangles)))
print()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment