On Github sdaityari / mathematical.modeling.slides
Shaumik Daityari / @ds_mikhttp://sdaityari.github.io/mathematical.modeling.slides
# Assume an initial point p p = (x, y) dt = 1 year trace = [] for i in range(1000): p[0] += u(at x = p[0], y = p[1]) * dt p[1] += v(at x = p[0], y = p[1]) * dt trace.append(p) # plot trace
# For a circle with center (h, k) and radius r center = (h, k) circumference = [(h + r * cos(θ), k + r * sin (θ)) for θ in range(360)] dt = 1 year strain_ellipse = [] for point in circumference: for i in range(1000): point[0] += u(at x = point[0], y = point[1]) * dt point[1] += v(at x = point[0], y = point[1]) * dt strain_ellipse.append(point) # Appending the final state of material point
class Cluster(): def __init__(self, points, center = None): self.points = points self.center = ... #Compute the center from the list of points # or use initial value provided for empty cluster def distance(self, Cluster): # compute distance of one cluster from another cluster def merge_clusters(new_cluster): # merge two clusters and return the merged cluster
def hierarchical_clustering(cluster_list, num_clusters): """ Compute a hierarchical clustering of a set of clusters Note: the function mutates cluster_list Input: List of clusters, number of clusters Output: List of clusters whose length is num_clusters """ new_cluster_list = cluster_list[:] while len(new_cluster_list) > num_clusters: _, node1, node2 = fast_closest_pair(new_cluster_list) new_cluster_list[node1].merge_clusters(new_cluster_list[node2]) del new_cluster_list[node2] return new_cluster_list
def kmeans_clustering(cluster_list, num_clusters, num_iterations): cluster_n = len(cluster_list) miu_k = sorted(cluster_list, key=lambda c: c.total_population())[-num_clusters:] miu_k = [c.copy() for c in miu_k] # n: cluster_n # q: num_iterations for _ in xrange(num_iterations): cluster_result = [alg_cluster.Cluster(set([]), 0, 0, 0, 0) for _ in range(num_clusters)] # put the node into closet center node for jjj in xrange(cluster_n): min_num_k = 0 min_dist_k = float('inf') for num_k in xrange(len(miu_k)): dist = cluster_list[jjj].distance(miu_k[num_k]) if dist < min_dist_k: min_dist_k = dist min_num_k = num_k cluster_result[min_num_k].merge_clusters(cluster_list[jjj]) # re-computer its center node for kkk in xrange(len(miu_k)): miu_k[kkk] = cluster_result[kkk] return cluster_result
Any questions?