Skip to content

Instantly share code, notes, and snippets.

@tupui
Created July 28, 2018 00:11
Show Gist options
  • Save tupui/2719245158f2dc2366a9256b58a85519 to your computer and use it in GitHub Desktop.
Save tupui/2719245158f2dc2366a9256b58a85519 to your computer and use it in GitHub Desktop.
Minimum Spanning Tree applied to Design of Experiments
"""Minimum Spanning Tree.
MST is used here as a discrepancy criterion.
Comparing two different designs: the higher the mean, the better the design is
in terms of space filling.
---------------------------
MIT License
Copyright (c) 2018 Pamphile Tupui ROY
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
"""
import numpy as np
from scipy.sparse.csgraph import minimum_spanning_tree
from scipy.spatial.distance import cdist
import matplotlib.pyplot as plt
# Define here your sample of shape (n_samples, n_dims)
sample = np.random.random_sample((50, 2))
dist = cdist(sample, sample)
mst = minimum_spanning_tree(dist)
mean = mst.data.mean()
var = mst.data.var()
print(f'Mean: {mean} - Variance: {var}')
mst = mst.toarray()
edges = np.where(mst > 0)
edges = np.array(edges).T
print(f'Edges:\n{edges}')
fig, ax = plt.subplots()
for edge in edges:
ax.plot(sample[edge, 0], sample[edge, 1], c='k')
ax.scatter(sample[:, 0], sample[:, 1])
plt.show()
@tupui
Copy link
Author

tupui commented Jul 28, 2018

capture d ecran 2018-07-28 a 02 09 19

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment