def kmedoids(E, number=100, simdist_function="pearson_correlation"):
    importr("cluster")

    distances = simdist(E, simdist_function, similarity=False)
    rresults = ro.r["pam"](distances, diss=True, k=number)
    modules = convert_labels2modules(list(rresults.rx2("clustering")), E.columns)
    return modules
def agglom(E, k=100, linkage="complete", simdist_function="pearson_correlation"):
    importr("cluster")
    ro.globalenv["distances"] =  simdist(E, simdist_function, similarity=False)
    ro.r("hclust_results = hclust(as.dist(distances), method='{linkage}')".format(**locals()))
    rresults = ro.r("labels = cutree(hclust_results, k={k})".format(**locals()))
    modules = convert_labels2modules(list(rresults), E.columns)
    return modules
def dclust(E, rho=0.5, delta=0.5, simdist_function="pearson_correlation"):
    ro.packages.importr("densityClust")

    distances = simdist(E, simdist_function, False)
    rresults =  ro.r["densityClust"](ro.r["as.dist"](distances))
    rresults = ro.r["findClusters"](rresults, rho=rho, delta=delta)

    modules = convert_labels2modules(list(rresults.rx2("clusters")), E.columns)

    return modules
def sota(E, maxCycles=1000, maxEpochs=1000, distance="euclidean", wcell=0.01, pcell=0.005, scell=0.001, delta=1e-04, neighb_level=0, alpha=0.95, unrest_growth=False):
    importr("clValid")

    distances = simdist(standardize(E), "euclidean", False)
    maxDiversity = np.percentile(distances.as_matrix().flatten(), maxDiversity_percentile)

    rresults = ro.r["sota"](standardize(E).T, maxCycles, maxEpochs, distance, wcell, pcell, scell, delta, neighb_level, maxDiversity, unrest_growth)

    modules = convert_labels2modules(list(rresults.rx2("clust")), E.columns)

    return modules
def affinity(E, preference_fraction=0.5, simdist_function="pearson_correlation", damping=0.5, max_iter=200):
    similarities = simdist(E, simdist_function)

    similarities_max, similarities_min = similarities.as_matrix().max(), similarities.as_matrix().min()
    preference = (similarities_max - similarities_min) * preference_fraction

    ro.packages.importr("apcluster")

    rresults = ro.r["apcluster"](s=ro.Matrix(similarities.as_matrix()), p=preference)
    labels = np.array(ro.r["labels"](rresults, "enum"))

    modules = convert_labels2modules(labels, E.columns)

    return modules
def spectral_similarity(E, k=100, seed=None, simdist_function="pearson_correlation"):
    similarities = simdist(E, simdist_function)
    spectral = sklearn.cluster.SpectralClustering(n_clusters=int(k), affinity="precomputed", random_state = seed)
    spectral.fit(similarities+1)
        
    return convert_labels2modules(spectral.labels_, E.columns)