Beispiel #1
0
def generation_results(experiment, chain, generation, set_type, symbolism="shape", permutations=1000):
    words = basics.getWords(experiment, chain, generation, set_type)
    triangles = basics.getTriangles(experiment, chain, generation, set_type)
    if symbolism == "shape":
        return correlate_form_and_symbolism(
            words, roundedness_phonemes, triangles, geometry.equilateralness, permutations
        )
    elif symbolism == "size":
        return correlate_form_and_symbolism(words, bigness_phonemes, triangles, geometry.centroid_size, permutations)
    else:
        raise ValueError('Invalid symbolism argument. Should be "shape" or "size".')
  return results

def chain_results(experiment, chain):
  results = []
  for generation in range(0,11):
    results.append(generation_results(experiment, chain, generation))
  return results

def generation_results(experiment, chain, generation):
  strings = basics.getWords(experiment, chain, generation, 's')
  # Return None if there are < 3 unique strings
  if len(set(strings)) > 2:
    string_distances = basics.stringDistances(strings)
    # Iterate through feature combinations to find the best correlation
    best_r = -1
    for i in range(0, len(all_combination_matrices)):
      r = np.corrcoef(string_distances, all_combination_matrices[i])[0,1]
      if r > best_r:
        best_matrix = i
        best_r = r
    # Return type number and correlation coefficient for combination of features with strongest correlation
    return best_matrix + 1, best_r
  return None

########################################

metrics = [location_distance, orientation_distance, shape_distance, size_distance]
static_set_triangles = basics.getTriangles(1, 'A', 0, 's')
individual_matrices = feature_matrices(static_set_triangles, metrics)
all_combination_matrices = combination_matrices(individual_matrices)
Beispiel #3
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)