def reset_world(self, world): self.l_locations = poisson_disc_samples(width=self.world_radius * 2, height=self.world_radius * 2, r=self.agent_size * 4.5, random=self.random.random) while len(self.l_locations) < len(world.landmarks): self.l_locations = poisson_disc_samples( width=self.world_radius * 2, height=self.world_radius * 2, r=self.agent_size * 4.5, random=self.random.random) print('regenerate l location') # random properties for agents for i, agent in enumerate(world.agents): agent.color = np.array([0.35, 0.35, 0.85]) # random properties for landmarks for i, landmark in enumerate(world.landmarks): landmark.color = np.array([0.25, 0.25, 0.25]) # set random initial states for agent in world.agents: agent.state.p_pos = self.np_rnd.uniform(-self.world_radius, +self.world_radius, world.dim_p) agent.state.p_vel = np.zeros(world.dim_p) agent.state.c = np.zeros(world.dim_c) l_locations = np.array( self.random.sample(self.l_locations, len( world.landmarks))) - self.world_radius for i, landmark in enumerate(world.landmarks): landmark.state.p_pos = l_locations[i, :] landmark.state.p_vel = np.zeros(world.dim_p) self.collide_th = 2 * world.agents[0].size
def toy_circle_labels(width, height, radius, intensity_prob, noise_func): labels = np.zeros((height, width), dtype=np.uint16) sketch = np.zeros_like(labels, dtype=float) # r is the distance between two center points, so we need to multiply by 2 centers = poisson_disc_samples(width=width, height=height, r=radius * 2) ys = np.arange(height) xs = np.arange(width) meshy, meshx = np.meshgrid(ys, xs, indexing="ij") for i, (x, y) in enumerate(centers): dist = (meshx - x)**2 + (meshy - y)**2 tmp_radius = np.random.uniform(radius / 2, radius) mask = dist < tmp_radius**2 # enumerate starts at 0, but 0 is background labels[mask] = i + 1 tmp_intensity = np.random.uniform(*intensity_prob) sketch[mask] = (tmp_radius - np.sqrt(dist[mask])) / tmp_radius * tmp_intensity noise = noise_func(sketch) return labels, sketch, noise
def test_r50(self): r = 50 samples = poisson_disc_samples(100, 100, r=r, random=self.prng.random) self.assertGreater(len(samples), 2) for i, p in enumerate(samples): for q in samples[i + 1:]: dx = p[0] - q[0] dy = p[1] - q[1] self.assertGreater(math.sqrt(dx * dx + dy * dy), r)
def add_crowd(num, region=None, angle=None, velocity_k=1.): ''' sample positions either randomly or within specified region ''' if region == None: # positions = env_size * np.random.rand(num, 2) positions = np.array( random.sample(poisson_disc_samples(width=env_size, height=env_size, r=2 * rad), k=num)).reshape(num, 2) else: # positions_x = np.random.uniform(low=region[0][0], high=region[1][0], size=[num]) # positions_y = np.random.uniform(low=region[0][1], high=region[1][1], size=[num]) positions = np.array( random.sample(poisson_disc_samples( width=region[1][0] - region[0][0], height=region[1][1] - region[0][1], r=2 * rad), k=num)).reshape(num, 2) # positions = np.column_stack((positions_x, positions_y)) positions[:, 0] += region[0][0] positions[:, 1] += region[0][1] ''' sample velocities either randomly or with a specified angle and magnitude ''' if angle == None: angles_local = 2 * 3.14 * np.random.rand(num, 1) else: angles_local = np.full(num, angle) velocities = np.empty(shape=(num, 2)) velocities[:, 0] = np.cos(angles_local).reshape(num) velocities[:, 1] = np.sin(angles_local).reshape(num) velocities *= velocity_k goal_velocities = 1.5 * np.copy(velocities) return positions, goal_velocities, velocities
def bridson_poisson_N(r1=.15, r2=.075, CA=.9, W=1.8, H=1.8, Nlenslets=1e9): p = np.array(poisson_disc_samples(width=W, height=H, r=r1)) p_circ_x, p_circ_y = ms_utils.project_to_aperture(p[:, 0] - W / 2, p[:, 1] - H / 2, CA - r2, mode='delete') if Nlenslets < len(p_circ_x): inds = np.random.choice(len(p_circ_x), Nlenslets, replace=False) else: inds = range(len(p_circ_x)) return p_circ_x[inds], p_circ_y[inds]
def crazy_stars(cfg): # random.seed(42) name = "crazy-stars" debug_svg = svgwrite.Drawing(f'{name}.svg', profile='tiny') WIDTH = 146 NUM_WALLS = 1 PAD = 10 points = poisson_disc_samples(width=cfg.width + 50 + (WIDTH + PAD) * NUM_WALLS, height=cfg.height + 50, r=cfg.r) total_x = NUM_WALLS * (WIDTH + PAD) for i in range(NUM_WALLS): x_offset = 25 + i * (WIDTH + PAD) selected = [ p for p in points if x_offset - 25 < p[0] < x_offset + WIDTH + 25 ] make_wall(cfg, selected, f"{name}-{i}", debug_svg, x_offset, total_x) debug_svg.save()
def fun_circles(cfg, seed: int): random.seed(seed) wall = Wall(f"fun-circles-{seed}", cfg) points = poisson_disc_samples(width=cfg.width * 3, height=cfg.height * 3, r=cfg.r * 0.80) radii = {} for i in range(len(points)): radii[i] = min( distance(points[i], points[j]) for j in range(len(points)) if i != j) / 2 for i, point in enumerate(points): r = radii[i] * 0.95 center = Vec(*point) points = circle_points(center, r, 20) poly = Polygon.Polygon([p.point2 for p in points]) & wall.window wall.result = wall.result + poly wall.result = wall.wall - wall.result wall.make_stl()
def toy_voronoi_labels_affinities( width_, height_, radius, opening_radius, deform_sigma, deform_points, intensity_prob, noise_sigma ): # we will create bigger images such that we can crop out regions, # that look good offset = 2 * radius height = height_ + 2 * offset width = width_ + 2 * offset shape = (height, width) labels = np.zeros(shape, dtype=np.uint16) sketch = np.zeros_like(labels, dtype=float) # r is the distance between two center points, so we need to multiply by 2 centers = poisson_disc_samples(width=width, height=height, r=radius * 2) # append far points to centers to complete voronoi regions x_max = width + 1 y_max = height + 1 centers = centers + [(-1, -1), (-1, y_max), (x_max, -1), (x_max, y_max)] vor = Voronoi(centers) # create selem with provided radius to apply clsoing selem = disk(opening_radius) for i, region in enumerate(vor.regions): if -1 in region or len(region) == 0: continue polygon = [vor.vertices[i] for i in region] mask = polygon2mask(shape, polygon) # close polygon mask with provided selem and radius mask = binary_opening(mask, selem) # enumerate starts at 0, but 0 is background labels[mask] = i + 1 edt = distance_transform_edt(mask) edt = edt / edt.max() tmp_intensity = np.random.uniform(*intensity_prob) sketch[mask] = edt[mask] * tmp_intensity sketch = scipy.ndimage.gaussian_filter(sketch, radius / 4) [labels, sketch] = elasticdeform.deform_random_grid( [labels, sketch], sigma=deform_sigma, points=deform_points, # labels must be interpolated by nearest neighbor order=[0, 3], crop=( slice(offset, offset + height_ + 1), slice(offset, offset + width_ + 1) ) ) # labels = labels[offset:-offset + 1, offset:-offset + 1] # sketch = sketch[offset:-offset + 1, offset:-offset + 1] noise = sketch + np.random.normal(0, noise_sigma, size=sketch.shape) affinities = get_affinities(labels) return labels[:-1, :-1], sketch[:-1, :-1], noise[:-1, :-1], affinities
def get_random_points(width, height, num_points): points = poisson_disc_samples(width=width, height=height, r=10) random.shuffle(points) return np.round(points[:num_points])
def make(self, prod_svg, debug_svg): x0, y0 = self.x0, self.y0 x1, y1 = self.x1, self.y1 b0 = (x1 - x0) / 2 - (6.125 + 7.5) block = Polygon.Polygon([ (x0 + b0, y0 + 0), (x1 - b0, y0 + 0), (x1 - b0, y0 + 14.25 + 7.5), (x0 + b0, y0 + 14.25 + 7.5), ]) b1 = (x1 - x0) / 2 - 6.125 tunnel = Polygon.Polygon([ (x0 + b1, y0 + -10), (x1 - b1, y0 + -10), (x1 - b1, y0 + 14.25), (x0 + b1, y0 + 14.25), ]) width = (x1 - x0) + 150 height = (y1 - y0) + 150 points = poisson_disc_samples(width=width, height=height, r=self.cfg.r) points = [(p[0] + x0 - 75, y1 - p[1] + 75) for p in points] # for p in points: # prod_svg.add(prod_svg.circle(p, 0.5, fill="green")) dely = DelaunayTri(points) cells = spooky_cells(dely) wx0 = min(p[0] for p in self.window[0]) wx1 = max(p[0] for p in self.window[0]) wy0 = min(p[1] for p in self.window[0]) wy1 = max(p[1] for p in self.window[0]) g0 = Graph(prod_svg, (wx0, wx1), (10, 10 + 30), (0.0, 1.0), "darkblue") g1 = Graph(prod_svg, (wx0, wx1), (10 + 30 + 5, 10 + 30 + 5 + 30), (0.0, 1.0), "darkgreen") for i, cell in sorted(cells.items()): inbounds = all(x0 - 50 < x < x1 + 50 and y0 - 50 < y < y1 + 50 for (x, y) in cell) if not inbounds: continue fixed = make_convex(cell) cx, cy = centroid(fixed) t = cx / (wx1 - wx0) s = cy / (wy1 - wy0) v = 0.73 * ( 0.5 + noise.snoise2(0.5 * s, 0.25 * t) + 0.5 * noise.snoise2(1 * s, 0.5 * t + 100) + 0.25 * noise.snoise2(2 * s, 1 * t + 200) ) v = geom.clamp(0, v, 1) g0.plot(cx, v) boost = inset_boost(v) g1.plot(cx, boost) inset_amount = self.cfg.line_width / 2.0 + boost p = inset(fixed, inset_amount) if p is None: continue cell = Polygon.Polygon(p) if len(cell & self.wall) == 0: continue c = centroid(cell.contour(0)) a = cell.area(0) r = (a / pi) ** 0.5 circle = Polygon.Polygon([p.point2 for p in circle_points(Vec(*c), r, 20)]) debug_svg.add(debug_svg.polygon(cell.contour(0), fill_opacity=0, stroke="black", stroke_width=0.25)) debug_svg.add(debug_svg.circle(c, r, fill_opacity=0, stroke="black", stroke_width=0.25)) # svg.save() new = geom.interpolate_poly_circle(debug_svg, cell.contour(0), c, r, 1 - v) new = Polygon.Polygon([p.point2 for p in new]) debug_svg.add(debug_svg.polygon(new.contour(0), fill_opacity=0, stroke="orange", stroke_width=0.25)) cell &= self.window circle &= self.window new &= self.window self.result += new debug_svg.add(debug_svg.polygon(self.window.contour(0), fill_opacity=0, stroke="black", stroke_width=0.25)) debug_svg.add(debug_svg.polygon(self.wall.contour(0), fill_opacity=0, stroke="black", stroke_width=0.25)) self.result = self.wall - self.result
plt.savefig('Sobol sequence.jpg', dpi=600) # # Poisson disk sampling # In[1592]: from bridson import poisson_disc_samples # ### Poisson sampling # In[1593]: num = 200 r = np.sqrt(2) * np.sqrt((16 / np.pi) / num) poss = poisson_disc_samples(width=4, height=4, r=r) x = [x - 2 for x, y in poss] y = [y - 2 for x, y in poss] plt.scatter(x, y, s=10) plt.scatter(x, y, color='', marker='o', edgecolors='g', s=100) plt.xlabel('Possion disk sampling') plt.savefig('Pos_sampling.jpg', dpi=600) # ### Change sample numbers # In[1468]: ponumlist = np.arange(1260, 12600, 100) maxiter = 1000 pd_simulationlis = 100
def random_place(self, obj=False, seed=0): np.random.seed(seed) obj_cls = np.array([ i.split('/')[-1] for i in glob.glob(os.path.join(self.data_path, 'clipped_obj/*')) ]) obj_f = [] # choose obj ind = np.arange(0, len(obj_cls)) np.random.shuffle(ind) ind = ind[:self.obj_sum] obj_cls = obj_cls[ind] for cls in obj_cls: obj_f.append( (cls, glob.glob( os.path.join(self.data_path, 'clipped_obj/{}/*.png'.format(cls))))) # choose obj pose pose_id = np.random.choice(len(obj_f[0][1]), self.obj_sum) f = [] for ind, (cls, fl) in enumerate(obj_f): f.append(fl[pose_id[ind]]) obj_img = [] for name in f: im = cv2.imread(name, cv2.IMREAD_UNCHANGED) im = cv2.resize(im, (int(im.shape[1]), int(im.shape[0]))) obj_img.append(im) redo = True while redo: bg = cv2.imread(os.path.join(self.data_path, 'background/0.png')) bg = cv2.resize(bg, (self.image_size, self.image_size)) h, w = bg.shape[:2] while True: res = np.array( poisson_disc_samples(h - self.border, w - self.border, self.collision_radius, random=np.random.rand)) if res.shape[0] >= self.obj_sum: ind = np.arange(res.shape[0]) np.random.shuffle(ind) ind = ind[:self.obj_sum] res = res[ind, :].astype(np.int32) break ret = [] for img, cls, coord in zip(obj_img, obj_cls, res): try: # print(img.shape, coord) bg = place_obj(bg, img[..., 0:3], img[..., -1], coord[0], coord[1]) ret.append([ coord[0] + img.shape[0] // 2, coord[1] + img.shape[1] // 2, self.cls_dict[cls] ]) except: break else: redo = False # (H, W, C) [(H, W, C)], [[x,y,id]] if obj: obj_img = [ cv2.resize(cv2.imread(name), (self.object_size, self.object_size)) for name in f ] return bg, obj_img, ret else: return bg, ret