-
Notifications
You must be signed in to change notification settings - Fork 28
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
custom clustering now takes position matrix instead of distance^2 matrix #87
Open
AdamOrmondroyd
wants to merge
48
commits into
PolyChord:custom_cluster
Choose a base branch
from
AdamOrmondroyd:ormorod-custom_cluster
base: custom_cluster
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Open
Changes from all commits
Commits
Show all changes
48 commits
Select commit
Hold shift + click to select a range
f1f52ed
neighbor spelling (assuming we're sticking to American spelling!)
AdamOrmondroyd 1c40b21
custom clustering now takes position matrix instead of distance^2 mat…
AdamOrmondroyd 634a4b8
corrected order of dimensions of position_matrix
AdamOrmondroyd d98cd08
renamed calculate_similarity_matrix() to calculate_position_matrix()
AdamOrmondroyd a04231a
renamed calculate_similarity_matrix() to calculate_position2_matrix()
AdamOrmondroyd d9571a3
Merge branch 'ormorod-custom_cluster' of github.com:Ormorod/PolyChord…
AdamOrmondroyd 9568985
corrected index in default_cluster
AdamOrmondroyd 92b3809
added new dimension to cluster input as position_matrix is not square…
AdamOrmondroyd db02cc2
changed cluster interfaces to add extra dimension for position_matrix
AdamOrmondroyd 876de66
Merge branch 'master' into ormorod-custom_cluster
williamjameshandley f5f8c93
Updated CI to work on pull request to all branches
williamjameshandley eeb83ac
changed cluster interfaces to add extra dimension for position_matrix
AdamOrmondroyd 4d68c9d
changed distance2_matrix to no longer be square
AdamOrmondroyd b6885cb
added extra dimension to cluster argument for non-square distance2_ma…
AdamOrmondroyd 4f638f2
Merge branch 'ormorod-custom_cluster' of github.com:Ormorod/PolyChord…
AdamOrmondroyd 7da5423
renamed m to nDims, n to nPoints, and position_matrix (and distance2_…
AdamOrmondroyd fa5c42d
changed neighbour to ~~correct~~ UK spelling
AdamOrmondroyd 5184835
forgot to change the interface in clustering itself
AdamOrmondroyd 3ed846c
another clustering interface using the wrong dimension of points
AdamOrmondroyd e4622f5
swapped indices over
AdamOrmondroyd 1b90073
Merge branch 'ormorod-custom_cluster' of github.com:Ormorod/PolyChord…
AdamOrmondroyd 23d8db8
Revert "swapped indices over"
AdamOrmondroyd 4a9bf0a
now uses c indexing in c and python, and fortran indexing in fortran
AdamOrmondroyd 2f0c339
Merge branch 'PolyChord:master' into master
AdamOrmondroyd f68dcb3
similarity matrix renamed to distance^2 in comments
AdamOrmondroyd da78633
wrap_cluster() adds one to the cluster list, as Python algos number c…
AdamOrmondroyd 512fca1
Merge branch 'ormorod-custom_cluster' of github.com:Ormorod/PolyChord…
AdamOrmondroyd be3467a
example cluster now returns -1
AdamOrmondroyd eb412c3
Merge branch 'master' into ormorod-custom_cluster
AdamOrmondroyd 9fbf7a3
Merge branch 'custom_cluster' of github.com:PolyChord/PolyChordLite i…
AdamOrmondroyd 14efda1
example to test custom clustering
AdamOrmondroyd 3029e60
equal weights of each Gaussian peak, corrected comments
AdamOrmondroyd 88572e3
remove mutual_nearest_neighbours function
AdamOrmondroyd b49fb80
replace sklearn dependence with compute_knn
AdamOrmondroyd f8dc320
compute_knn() computed the full nn ordering, then returned the first …
AdamOrmondroyd 4d95077
realised the for loop in the copied knn clustering is actually a whil…
AdamOrmondroyd 2d99c89
Removed unused num_clusters_old from native clustering
AdamOrmondroyd 1a561de
comment reminds that clustering algorithm should be 0-indexed
AdamOrmondroyd f67543d
updated run_pypolychord.ipynb with py2nb
AdamOrmondroyd 8954de3
correct docstring to clarify cluster function must number clusters fr…
AdamOrmondroyd ebf3b91
further correction to clustering in docstring
AdamOrmondroyd e1102fb
change cluster function example comments to docstring
AdamOrmondroyd 4d3adcc
remove unnecessary np.sqrt import
AdamOrmondroyd 70628a5
Correct root=root -> root=0 in make_resume_file (#92)
AdamOrmondroyd 6cf0fc4
PWD->CURDIR
williamjameshandley 3084a81
Updated PWD to CURDIR in setup.py
williamjameshandley 1854372
Update python3.6 CI (#96)
AdamOrmondroyd cfc77c4
Merge branch 'master' into ormorod-custom_cluster
AdamOrmondroyd File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Large diffs are not rendered by default.
Oops, something went wrong.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,151 @@ | ||
|
||
from numpy import pi, log, sqrt | ||
import numpy as np | ||
import pypolychord | ||
from pypolychord.settings import PolyChordSettings | ||
from pypolychord.priors import UniformPrior | ||
from scipy.spatial import distance_matrix | ||
from scipy.special import logsumexp | ||
try: | ||
from mpi4py import MPI | ||
except ImportError: | ||
pass | ||
|
||
|
||
|
||
#| Define a four-dimensional twin-spherical gaussian likelihood, | ||
#| width sigma=0.1, centered on ±[0.5]^nDims with one derived parameter. | ||
#| The derived parameter is the squared radius from [0]^nDims | ||
|
||
nDims = 4 | ||
nDerived = 1 | ||
sigma = 0.1 | ||
|
||
centres = np.array([[-0.5] * nDims, [0.5] * nDims]) | ||
weights = np.array([0.5, 0.5]) | ||
|
||
|
||
def likelihood(theta): | ||
"""Twin Gaussian likelihood.""" | ||
nDims = len(theta) | ||
logL = -np.log(2 * np.pi * sigma * sigma) * nDims / 2 | ||
logL += logsumexp(-np.sum((theta - centres) ** 2, axis=-1) / 2 / sigma / sigma, b = weights) | ||
return logL, [np.sum(theta**2)] | ||
|
||
|
||
#| Define a box uniform prior from -1 to 1 | ||
|
||
def prior(hypercube): | ||
""" Uniform prior from [-1,1]^D. """ | ||
return UniformPrior(-1, 1)(hypercube) | ||
|
||
|
||
#| Optional cluster function allow user-defined clustering | ||
## KNN clustering algorithm translated from clustering.F90 | ||
|
||
def compute_nn(position_matrix): | ||
return np.argsort(distance_matrix(position_matrix, position_matrix)) | ||
|
||
|
||
def relabel(labels): | ||
k = max(labels) | ||
appearance_order = {} | ||
num_found = 0 | ||
|
||
for label in labels: | ||
if label not in appearance_order: | ||
appearance_order[label] = num_found | ||
num_found += 1 | ||
|
||
for i, old_label in enumerate(labels): | ||
labels[i] = appearance_order[old_label] | ||
return labels | ||
|
||
|
||
def do_clustering(knn_array): | ||
num_points = knn_array.shape[0] | ||
labels = np.arange(num_points) | ||
for iii in range(num_points): | ||
for ii in range(iii + 1, num_points): | ||
if labels[ii] != labels[iii]: | ||
if (ii in knn_array[iii]) or (iii in knn_array[ii]): | ||
for i in range(num_points): | ||
if labels[i] == labels[ii] or labels[i] == labels[iii]: | ||
labels[i] = min([labels[ii], labels[iii]]) | ||
return relabel(labels) | ||
|
||
|
||
def knn_cluster(position_matrix): | ||
"""slight concern if two points are the same because sklearn""" | ||
npoints = position_matrix.shape[0] | ||
k = min(npoints, 10) | ||
nn_array = compute_nn(position_matrix) | ||
labels = np.arange(npoints) | ||
num_clusters = npoints | ||
|
||
labels_old = labels | ||
|
||
n = 2 | ||
while n <= k: | ||
labels = do_clustering(nn_array[:, :n]) | ||
num_clusters = max(labels) + 1 | ||
|
||
if num_clusters <= 0: | ||
raise ValueError("somehow got <= 0 clusters") | ||
elif 1 == num_clusters: | ||
return labels | ||
elif np.all(labels == labels_old): | ||
break | ||
elif k == n: | ||
k = min(k * 2, npoints) | ||
|
||
labels_old = labels | ||
n += 1 | ||
|
||
if num_clusters > 1: | ||
i_cluster = 0 | ||
while i_cluster < num_clusters: | ||
cluster = position_matrix[labels == i_cluster] | ||
labels[labels == i_cluster] = knn_cluster(cluster) + num_clusters | ||
labels = relabel(labels) | ||
if num_clusters - 1 == max(labels): | ||
i_cluster += 1 | ||
return labels | ||
|
||
|
||
#| Initialise the settings | ||
|
||
settings = PolyChordSettings(nDims, nDerived) | ||
settings.file_root = "custom_clustering" | ||
settings.nlive = 200 | ||
settings.do_clustering = True | ||
settings.read_resume = False | ||
|
||
#| Run PolyChord | ||
|
||
output = pypolychord.run_polychord(likelihood, nDims, nDerived, settings, prior, cluster=knn_cluster) | ||
|
||
#| Create a paramnames file | ||
|
||
paramnames = [('p%i' % i, r'\theta_%i' % i) for i in range(nDims)] | ||
paramnames += [('r*', 'r')] | ||
output.make_paramnames_files(paramnames) | ||
|
||
#| Make an anesthetic plot (could also use getdist) | ||
try: | ||
from anesthetic import NestedSamples | ||
samples = NestedSamples(root= settings.base_dir + '/' + settings.file_root) | ||
fig, axes = samples.plot_2d(['p0','p1','p2','p3','r']) | ||
fig.savefig('posterior.pdf') | ||
|
||
except ImportError: | ||
try: | ||
import getdist.plots | ||
posterior = output.posterior | ||
g = getdist.plots.getSubplotPlotter() | ||
g.triangle_plot(posterior, filled=True) | ||
g.export('custom_clustering.pdf') | ||
except ImportError: | ||
print("Install matplotlib and getdist for plotting examples") | ||
|
||
print("Install anesthetic or getdist for for plotting examples") |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Could you merge PolyChord:master into Ormorod:ormorod-custom_cluster so that the diff is cleaner?
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
It would also be good to add a python test of clustering if you have time.