def start(self):
        if self.settings['player1'] == "grid":
            player1 = GridPlayer()
        elif self.settings['player1'] == "circle":
            player1 = CirclePlayer(300)
        elif self.settings['player1'] == "line":
            player1 = LinePlayer()
        else:
            player1 = RandomPlayer()

        logging.info("Get player 1's points")
        points1 = player1.get_points(number_of_points=self.settings['number_of_points1'], settings=self.settings)
        delaunay_triangulation_player1 = Delaunay.computeDelaunay(points1, self.settings['point_loc_method'])
        voronoi_player1 = Voronoi.computeVoronoi(delaunay_triangulation_player1, self.settings['width'], self.settings['height'])
        if self.settings['player2'] == "grid":
            player2 = GridPlayer()
        elif self.settings['player2'] == "circle":
            player2 = CirclePlayer(300)
        elif self.settings['player2'] == "line":
            player2 = LinePlayer()
        elif self.settings['player2'] == "longest Delaunay edge":
            player2 = LongestEdgePlayer(delaunay_triangulation_player1)
        elif self.settings['player2'] == "largest Voronoi face":
            player2 = LargestFacePlayer(voronoi_player1)
        else:
            player2 = RandomPlayer()
        logging.info("Get player 2's points")
        points2 = player2.get_points(number_of_points=self.settings['number_of_points2'], settings=self.settings,
                                     points=points1)
        self.points = points1 + points2
        shuffle(self.points)
        logging.info("Compute Delaunay triangulation")

        self.delaunay_triangulation = Delaunay.computeDelaunay(self.points, self.settings['point_loc_method'])
        logging.info("Compute Voronoi diagram")
        self.voronoi_diagram = Voronoi.computeVoronoi(self.delaunay_triangulation, self.settings['width'], self.settings['height'])
        self.voronoi_areas = Voronoi.get_area_percentages(self.voronoi_diagram, self.settings['width'], self.settings['height'])
Example #2
0
    def onClickCalculate(self):
        if not self.LOCK_FLAG:
            self.LOCK_FLAG = True

            pObj = self.w.find_all()
            points = []
            for p in pObj:
                coord = self.w.coords(p)
                points.append((coord[0] + self.RADIUS, coord[1] + self.RADIUS))

            print(points)
            vp = Voronoi.Voronoi(points)
            vp.process()
            lines = vp.get_output()
            self.drawLinesOnCanvas(lines)

            print(lines)
Example #3
0
    def generate(self, vertcount, mapObject):
        if mapObject is None:
            return

        mesh = mapObject.data

        bpy.ops.object.select_all(action='DESELECT')
        bpy.ops.object.mode_set(mode='OBJECT')
        mapObject.select = True
        count = (vertcount / len(mesh.vertices) - 1)
        if count >= 0:
            bpy.ops.object.mode_set(mode='EDIT')
            bpy.ops.mesh.subdivide(number_cuts=count)
            bpy.ops.object.mode_set(mode='OBJECT')
            bpy.context.scene['lastMapObject'] = mapObject
        else:
            if bpy.context.scene['lastMapObject'] != mapObject:
                bpy.context.scene['lastMapObject'] = mapObject

        voromap = Voronoi.VoronoiMap(512, 512, pointscount=500)
        image = voromap.toimage()
        with NamedTemporaryFile(suffix=".jpg", dir=BASE_PATH) as tmp:
            name = tmp.name
            tmp.close()
        image.save(name, "JPEG")

        bpy.ops.uv.unwrap(method='ANGLE_BASED', margin=0.001)
        bpy.ops.material.new()
        tex = bpy.data.textures.new("SomeName", 'IMAGE')
        bpy.context.object.active_material.name = "map_mat"
        mat = bpy.context.object.active_material
        slot = mat.texture_slots.add()
        slot.texture = tex
        mesh.materials.append(mat)

        try:
            img = bpy.data.images.load(name)
        except:
            print("Cannot load image %s" % name)
            return
        tex.image = img
 def get_points(self, number_of_points, settings, points):
     self.color = "red"
     if points is not None:
         self.color = "blue"
     result = []
     # Sort existing points by face area
     print(self.voronoi_diagram)
     points.sort(reverse=True,
                 key=lambda p: Voronoi.get_area(p, self.voronoi_diagram[p]))
     for point in points:
         if len(result) >= number_of_points:
             break
         face = [p for p in self.voronoi_diagram[point]]
         face.sort(key=lambda p: math.atan2(point.y - p[1], point.x - p[0]))
         # Candidate line that are perpendicular to a Voronoi edge and that go through the Delaunay point
         candidates = {}
         for i in range(len(face)):
             # Voronoi edge
             e = (face[i], face[(i + 1) % len(face)])
             # Find the edge that the perpendicular line through point intersects
             normal = ((-(e[1][1] - e[0][1]), e[1][0] - e[0][0]),
                       (e[1][1] - e[0][1], -(e[1][0] - e[0][0])))
             multiplier = self.get_length(
                 ((0, 0), (settings['width'],
                           settings['height']))) / self.get_length(normal)
             normal = ((normal[0][0] * multiplier,
                        normal[0][1] * multiplier),
                       (normal[1][0] * multiplier,
                        normal[1][1] * multiplier))
             perp_edge = ((point.x, point.y),
                          (point.x + normal[0][0] - normal[1][0],
                           point.x + normal[0][1] - normal[1][1]))
             for j in range(len(face)):
                 intersect_edge = (face[j], face[(j + 1) % len(face)])
                 if self.is_intersecting(perp_edge, intersect_edge):
                     break
             #print("intersect_edge", intersect_edge)
             #print("e", e)
             #print("perp_edge", perp_edge)
             intersect1 = self.get_intersection(e, perp_edge)
             intersect2 = self.get_intersection(intersect_edge, perp_edge)
             candidates[e] = (intersect1, intersect2)
         # Best candidate
         e = None
         best_candidate_perp = None
         best_candidate_length = sys.float_info.max
         # Find the shortest perpendicular edge
         for voronoi_edge, perp_edge in candidates.items():
             if self.get_length(perp_edge) < best_candidate_length:
                 best_candidate_length = self.get_length(perp_edge)
                 e = voronoi_edge
                 best_candidate_perp = perp_edge
         # Find the voronoi edges that intersect with the line parallel to best_candidate through point
         multiplier = self.get_length(
             ((0, 0),
              (settings['width'], settings['height']))) / self.get_length(e)
         # Check both directions from the point
         result_line1 = ((point.x, point.y),
                         (point.x + multiplier * (e[1][0] - e[0][0]),
                          point.y + multiplier * (e[1][1] - e[0][1])))
         result_line2 = ((point.x, point.y),
                         (point.x - multiplier * (e[1][0] - e[0][0]),
                          point.y - multiplier * (e[1][1] - e[0][1])))
         for voronoi_edge in candidates:
             if self.is_intersecting(result_line1, voronoi_edge):
                 intersect_voronoi1 = self.get_intersection(
                     result_line1, voronoi_edge)
             if self.is_intersecting(result_line2, voronoi_edge):
                 intersect_voronoi2 = self.get_intersection(
                     result_line2, voronoi_edge)
         best_intersect = intersect_voronoi1
         if self.get_length(
             ((point.x, point.y), intersect_voronoi2)) > self.get_length(
                 ((point.x, point.y), intersect_voronoi1)):
             best_intersect = intersect_voronoi2
         xdiff = best_intersect[0] - point.x
         ydiff = best_intersect[1] - point.y
         print("xdiff", xdiff, "ydiff", ydiff)
         result.append(
             Point(
                 point.x + .01 * xdiff +
                 uniform(0.0001 * xdiff, 0.001 * xdiff), point.y +
                 .01 * ydiff + uniform(0.0001 * ydiff, 0.001 * ydiff),
                 self.color))
     return result
Example #5
0
def plot(chain, generation, experiment=None, colour_palette=None, use_rgb=False, spectrum=[0.5, 1.0], show_prototypes=False, label_cells=False, join_contiguous_cells=False, colour_candidates=False, random_seed=False, save_location=False):

  # Determine experiment number if none supplied
  if experiment == None:
    experiment = basics.determine_experiment_number(chain)

  # Get strings and triangles for this generation
  strings = basics.getWords(experiment, chain, generation, 's')
  triangles = basics.getTriangles(experiment, chain, generation, 's')

  # Pick a colour palette if none has been supplied
  if colour_palette == None:
    colour_palette, random_seed = generate_colour_palette(strings, use_rgb, spectrum, random_seed)
    chain_palette = False
  else:
    chain_palette = True

  if type(colour_candidates) == int:
    candidate_num = '_' + str(random_seed)
  else:
    candidate_num = ''

  # Organize strings and triangles into categories
  word_dict = {}
  triangle_dict = {}
  for i in range(0, len(strings)):
    if strings[i] in word_dict.keys():
      word_dict[strings[i]].append(i)
      triangle_dict[strings[i]].append(triangles[i])
    else:
      word_dict[strings[i]] = [i]
      triangle_dict[strings[i]] = [triangles[i]]

  # Set up subplot in top left
  plt.subplots(figsize=(figure_width, figure_width/1.375))
  ax1 = plt.subplot2grid((11,2), (0,0), rowspan=7)

  # Determine the optimum size for the grid of triangle images / grid of legend labels
  # (a square number larger than the number of unique strings)
  for square in [1, 4, 9, 16, 25, 36, 49]:
    if square >= len(word_dict.keys()):
      break
  grid_size = int(np.sqrt(square))

  # Rearrange words so that they'll appear in alphabetical order along rows of the legend
  words = rearrange(word_dict.keys(), grid_size)

  # Plot MDS coordinates and the Voronoi polygons
  for word in words:
    indices = word_dict[word]
    colour, colour_light = colour_palette[word]
    X, Y = triangle_coordinates[indices, 0], triangle_coordinates[indices, 1]
    plt.scatter(X, Y, c=colour_light, label=word, marker='o', s=12, linewidth=0, zorder=0)
    plt.scatter(X, Y, c=colour, marker='o', s=12, linewidth=0, zorder=2)
    if join_contiguous_cells == True:
      regional_polys = Voronoi.join_contiguous_polygons(voronoi_polygons[indices])
      for poly in regional_polys:
        ax1.add_patch(patches.Polygon(poly, facecolor=colour_light, edgecolor='white', linewidth=0.5, zorder=1))
    else:
      for i in indices:
        ax1.add_patch(patches.Polygon(voronoi_polygons[i], facecolor=colour_light, edgecolor='white', linewidth=0.5, zorder=0))
        if label_cells == True:
          x, y = centroid(voronoi_polygons[i])
          ax1.text(x, y, word, {'fontsize':5}, ha='center', va='center')
  
  # Set axis style
  plt.xlim(-1, 1)
  plt.ylim(-1, 1)
  plt.xlabel("MDS dimension 1", fontsize=label_font_size)
  plt.ylabel("MDS dimension 2", fontsize=label_font_size)
  plt.xticks(fontsize=axis_font_size)
  plt.yticks(fontsize=axis_font_size)

  # Set up subplot at bottom for legend
  ax2 = plt.subplot2grid((11,2), (7,0), colspan=2)
  plt.axis('off')

  # Produce the legend
  handles, labels = ax1.get_legend_handles_labels()
  ax2.legend(handles, labels, loc='upper center', bbox_to_anchor=[0.45, 0.5], frameon=False, prop={'size':legend_font_size}, ncol=grid_size, scatterpoints=1, handletextpad=0.01, markerscale=2.5)
  
  # Tighten plot layout
  plt.tight_layout(pad=0.2, h_pad=0.0)

  # Determine filename and directory if none has been specified
  if type(save_location) == bool and save_location == False:
    save_location = basics.desktop_location

  if chain_palette == True:
    filename = save_location + chain + str(generation) + '.svg'
  else:
    filename = save_location + chain + str(generation) + '_' + str(random_seed) + '.svg'

  # Save matplotlib plot as SVG file

  plt.savefig(filename)
  plt.close()

  # Draw the triangle images and splice them into the matplotlib SVG file
  triangle_code = draw_triangles(triangle_dict, colour_palette, show_prototypes, grid_size)
  splice_in_triangles(filename, triangle_code)

  # If multiple colour palette candidates have been requested, run plot() again.
  if colour_candidates > 1:
    plot(chain, generation, experiment, None, use_rgb, spectrum, show_prototypes, label_cells, join_contiguous_cells, colour_candidates-1, False, save_location)
Example #6
0
  n = len(mds_coordinates)
  mds_distances = [ED(mds_coordinates[i], mds_coordinates[j]) for i in range(n) for j in range(i+1, n)]
  return np.corrcoef(distances, mds_distances)[0,1]


# Calculate stress-1
def stress_1(raw_stress, distances):
  return np.sqrt(raw_stress / sum(distances ** 2))


# Get dissimilarity ratings and format as square distance matrix
triangle_distances = rater_analysis.reliable_distance_array
triangle_distance_matrix = distance.squareform(triangle_distances, 'tomatrix')

# Run ratings through MDS to get coordinates in 2-dimensional space
triangle_mds = MDS(dissimilarity="precomputed", n_components=2, n_init=25, max_iter=2000, random_state=10)
triangle_coordinates = triangle_mds.fit_transform(triangle_distance_matrix)

# Scale each dimension over the interval [-0.9, 0.9] for a tidy plot
for dim in range(0, triangle_coordinates.shape[1]):
  minimum = triangle_coordinates[:, dim].min()
  difference = triangle_coordinates[:, dim].max() - minimum
  triangle_coordinates[:, dim] = (((triangle_coordinates[:, dim] - minimum) / difference) * 1.8) - 0.9

# Compute the Voronoi polygons for these MDS coordinates
voronoi_polygons = Voronoi.polygons(triangle_coordinates, [[-1,-1], [-1,1], [1,1], [1,-1]])

# Print MDS goodness-of-fit stats
#print('Correspondence: %s' % correspondence_correlation(triangle_distances, triangle_coordinates))
#print('Stress-1: %s' % stress_1(triangle_mds.stress_, triangle_distances))
import random
import time
import Voronoi as V

tab = []


def losowe(n):
    for i in range(n):
        x = random.randrange(-100, 100)
        y = random.randrange(-100, 100)
        tab.append((x, y))


losowe(100)
print(len(tab))
start = time.time()
vp = V.Voronoi(tab)
vp.process()
print(vp.get_output())

end = time.time()

print((end - start))