original_docstring: Create a silhouette plot indicating between relative to within label distance
  
      Args:
          distance: (pandas dataframe) brain_distance matrix
          labels: (pandas dataframe) group labels
          ax: axis to plot (default=None)
          permutation_test: (boolean)
          n_permute: (int) number of samples for permuation test
      Optional keyword args:
          figsize: (list) dimensions of silhouette plot
          colors: (list) color triplets for silhouettes. Length must equal number of unique labels
      Returns:
          # f: heatmap
          # out: pandas dataframe of pairwise distance between conditions
          # within_dist_out: average pairwise distance matrix
          # mn_dist_out: (optional if permutation_test=True) average difference in distance between conditions
          # p_dist_out: (optional if permutation_test=True) p-value for difference in distance between conditions
      
docstring: Create a silhouette plot indicating between relative to within label distance
docstring_tokens: Create a silhouette plot indicating between relative to within label distance
code: def plot_silhouette(
      distance, labels, ax=None, permutation_test=True, n_permute=5000, **kwargs
  ):
      """Create a silhouette plot indicating between relative to within label distance
  
      Args:
          distance: (pandas dataframe) brain_distance matrix
          labels: (pandas dataframe) group labels
          ax: axis to plot (default=None)
          permutation_test: (boolean)
          n_permute: (int) number of samples for permuation test
      Optional keyword args:
          figsize: (list) dimensions of silhouette plot
          colors: (list) color triplets for silhouettes. Length must equal number of unique labels
      Returns:
          # f: heatmap
          # out: pandas dataframe of pairwise distance between conditions
          # within_dist_out: average pairwise distance matrix
          # mn_dist_out: (optional if permutation_test=True) average difference in distance between conditions
          # p_dist_out: (optional if permutation_test=True) p-value for difference in distance between conditions
      """
  
      # Define label set
      labelSet = np.unique(np.array(labels))
      n_clusters = len(labelSet)
  
      # Set defaults for plot design
      if "colors" not in kwargs.keys():
          colors = sns.color_palette("hls", n_clusters)
      if "figsize" not in kwargs.keys():
          figsize = (6, 4)
  
      # Compute silhouette scores
      out = pd.DataFrame(columns=("Label", "MeanWit", "MeanBet", "Sil"))
      for index in range(len(labels)):
          label = labels.iloc[index]
          sameIndices = [
              i for i, labelcur in enumerate(labels) if (labelcur == label) & (i != index)
          ]
          within = distance.iloc[index, sameIndices].values.flatten()
          otherIndices = [i for i, labelcur in enumerate(labels) if (labelcur != label)]
          between = distance.iloc[index, otherIndices].values.flatten()
          silhouetteScore = (np.mean(between) - np.mean(within)) / max(
              np.mean(between), np.mean(within)
          )
          out_tmp = pd.DataFrame(columns=out.columns)
          out_tmp.at[index] = index
          out_tmp["Label"] = label
          out_tmp["MeanWit"] = np.mean(within)
          out_tmp["MeanBet"] = np.mean(between)
          out_tmp["Sil"] = silhouetteScore
          out = out.append(out_tmp)
      sample_silhouette_values = out["Sil"]
  
      # Plot
      with sns.axes_style("white"):
          if ax is None:
              _, ax = plt.subplots(1, figsize=figsize)
          else:
              plt.plot(figsize=figsize)
      x_lower = 10
      labelX = []
      for labelInd in range(n_clusters):
          label = labelSet[labelInd]
          ith_cluster_silhouette_values = sample_silhouette_values[labels == label]
          ith_cluster_silhouette_values.sort_values(inplace=True)
          size_cluster_i = ith_cluster_silhouette_values.shape[0]
          x_upper = x_lower + size_cluster_i
  
          color = colors[labelInd]
          with sns.axes_style("white"):
              plt.fill_between(
                  np.arange(x_lower, x_upper),
                  0,
                  ith_cluster_silhouette_values,
                  facecolor=color,
                  edgecolor=color,
              )
  
          labelX = np.hstack((labelX, np.mean([x_lower, x_upper])))
          x_lower = x_upper + 3
  
      # Format plot
      ax.set_xticks(labelX)
      ax.set_xticklabels(labelSet)
      ax.set_title("Silhouettes", fontsize=18)
      ax.set_xlim([5, 10 + len(labels) + n_clusters * 3])
  
      # Permutation test on mean silhouette score per label
      if permutation_test:
          outAll = pd.DataFrame(columns=["label", "mean", "p"])
          for labelInd in range(n_clusters):
              temp = pd.DataFrame(columns=outAll.columns)
              label = labelSet[labelInd]
              data = sample_silhouette_values[labels == label]
              temp.loc[labelInd, "label"] = label
              temp.loc[labelInd, "mean"] = np.mean(data)
              if np.mean(data) > 0:  # Only test positive mean silhouette scores
                  statsout = one_sample_permutation(data, n_permute=n_permute)
                  temp["p"] = statsout["p"]
              else:
                  temp["p"] = 999
              outAll = outAll.append(temp)
          return outAll
      else:
          return
code_tokens: def plot_silhouette ( distance , labels , ax = None , permutation_test = True , n_permute = 5000 , ** kwargs ) : labelSet = np . unique ( np . array ( labels ) ) n_clusters = len ( labelSet ) if "colors" not in kwargs . keys ( ) : colors = sns . color_palette ( "hls" , n_clusters ) if "figsize" not in kwargs . keys ( ) : figsize = ( 6 , 4 ) out = pd . DataFrame ( columns = ( "Label" , "MeanWit" , "MeanBet" , "Sil" ) ) for index in range ( len ( labels ) ) : label = labels . iloc [ index ] sameIndices = [ i for i , labelcur in enumerate ( labels ) if ( labelcur == label ) & ( i != index ) ] within = distance . iloc [ index , sameIndices ] . values . flatten ( ) otherIndices = [ i for i , labelcur in enumerate ( labels ) if ( labelcur != label ) ] between = distance . iloc [ index , otherIndices ] . values . flatten ( ) silhouetteScore = ( np . mean ( between ) - np . mean ( within ) ) / max ( np . mean ( between ) , np . mean ( within ) ) out_tmp = pd . DataFrame ( columns = out . columns ) out_tmp . at [ index ] = index out_tmp [ "Label" ] = label out_tmp [ "MeanWit" ] = np . mean ( within ) out_tmp [ "MeanBet" ] = np . mean ( between ) out_tmp [ "Sil" ] = silhouetteScore out = out . append ( out_tmp ) sample_silhouette_values = out [ "Sil" ] with sns . axes_style ( "white" ) : if ax is None : _ , ax = plt . subplots ( 1 , figsize = figsize ) else : plt . plot ( figsize = figsize ) x_lower = 10 labelX = [ ] for labelInd in range ( n_clusters ) : label = labelSet [ labelInd ] ith_cluster_silhouette_values = sample_silhouette_values [ labels == label ] ith_cluster_silhouette_values . sort_values ( inplace = True ) size_cluster_i = ith_cluster_silhouette_values . shape [ 0 ] x_upper = x_lower + size_cluster_i color = colors [ labelInd ] with sns . axes_style ( "white" ) : plt . fill_between ( np . arange ( x_lower , x_upper ) , 0 , ith_cluster_silhouette_values , facecolor = color , edgecolor = color , ) labelX = np . hstack ( ( labelX , np . mean ( [ x_lower , x_upper ] ) ) ) x_lower = x_upper + 3 ax . set_xticks ( labelX ) ax . set_xticklabels ( labelSet ) ax . set_title ( "Silhouettes" , fontsize = 18 ) ax . set_xlim ( [ 5 , 10 + len ( labels ) + n_clusters * 3 ] ) if permutation_test : outAll = pd . DataFrame ( columns = [ "label" , "mean" , "p" ] ) for labelInd in range ( n_clusters ) : temp = pd . DataFrame ( columns = outAll . columns ) label = labelSet [ labelInd ] data = sample_silhouette_values [ labels == label ] temp . loc [ labelInd , "label" ] = label temp . loc [ labelInd , "mean" ] = np . mean ( data ) if np . mean ( data ) > 0 : statsout = one_sample_permutation ( data , n_permute = n_permute ) temp [ "p" ] = statsout [ "p" ] else : temp [ "p" ] = 999 outAll = outAll . append ( temp ) return outAll else : return
short_docstring: Create a silhouette plot indicating between relative to within label distance
short_docstring_tokens: Create a silhouette plot indicating between relative to within label distance
comment: """Create a silhouette plot indicating between relative to within label distance
  
      Args:
          distance: (pandas dataframe) brain_distance matrix
          labels: (pandas dataframe) group labels
          ax: axis to plot (default=None)
          permutation_test: (boolean)
          n_permute: (int) number of samples for permuation test
      Optional keyword args:
          figsize: (list) dimensions of silhouette plot
          colors: (list) color triplets for silhouettes. Length must equal number of unique labels
      Returns:
          # f: heatmap
          # out: pandas dataframe of pairwise distance between conditions
          # within_dist_out: average pairwise distance matrix
          # mn_dist_out: (optional if permutation_test=True) average difference in distance between conditions
          # p_dist_out: (optional if permutation_test=True) p-value for difference in distance between conditions
      """$SEP$# Define label set$SEP$# Set defaults for plot design$SEP$# Compute silhouette scores$SEP$# Plot$SEP$# Format plot$SEP$# Permutation test on mean silhouette score per label$SEP$# Only test positive mean silhouette scores