本文整理汇总了Python中MatrixUtil.m_to_string方法的典型用法代码示例。如果您正苦于以下问题:Python MatrixUtil.m_to_string方法的具体用法?Python MatrixUtil.m_to_string怎么用?Python MatrixUtil.m_to_string使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类MatrixUtil
的用法示例。
在下文中一共展示了MatrixUtil.m_to_string方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: get_response_content
# 需要导入模块: import MatrixUtil [as 别名]
# 或者: from MatrixUtil import m_to_string [as 别名]
def get_response_content(fs):
# arbitrarily define the size of the alphabet
k = 4
# define the response
out = StringIO()
# get the tree
tree = NewickIO.parse(fs.tree, FelTree.NewickTree)
# define the order of the tip names
ordered_tip_names = list(sorted(node.get_name() for node in tree.gen_tips()))
n = len(ordered_tip_names)
# get the matrix of pairwise distances among the tips
D = np.array(tree.get_distance_matrix(ordered_tip_names))
D_vector = get_principal_coordinate(D)
# get the dissimilarity matrix from the distance matrix
dissimilarity = np.array([[distance_to_dissimilarity(d, k) for d in row] for row in D])
dissimilarity_vector = get_principal_coordinate(dissimilarity)
# get the principal coordinates of the distance-like matrices
print >> out, 'original distance matrix:'
print >> out, MatrixUtil.m_to_string(D)
print >> out
print >> out, 'projections onto the principal coordinate using the original distance matrix:'
for name, value in zip(ordered_tip_names, D_vector):
print >> out, '\t'.join((name, str(value)))
print >> out
print >> out, 'dissimilarity matrix:'
print >> out, MatrixUtil.m_to_string(dissimilarity)
print >> out
print >> out, 'projections onto the principal coordinate using the dissimilarity matrix:'
for name, value in zip(ordered_tip_names, dissimilarity_vector):
print >> out, '\t'.join((name, str(value)))
print >> out
# return the response
return out.getvalue()
示例2: get_response_content
# 需要导入模块: import MatrixUtil [as 别名]
# 或者: from MatrixUtil import m_to_string [as 别名]
def get_response_content(fs):
# read the matrix
D = fs.matrix
n = len(D)
if n < 3:
raise HandlingError('the matrix should have at least three rows')
# define the other matrices
D_inv = np.linalg.inv(D)
row_sums = np.sum(D_inv, 0)
grand_sum = np.sum(D_inv)
A = np.zeros((n,n))
B = np.zeros((n,n))
for i in range(n):
for j in range(n):
A[i][j] = row_sums[i] + row_sums[j] - grand_sum
B[i][j] = row_sums[i] * row_sums[j] / grand_sum
C = np.zeros((n,n))
for i in range(n):
for j in range(n):
C[i][j] = D_inv[i][j] - B[i][j]
# define the response
out = StringIO()
print >> out, 'additive:'
print >> out, MatrixUtil.m_to_string(A)
print >> out, 'multiplicative:'
print >> out, MatrixUtil.m_to_string(B)
for row in C:
print >> out, sum(row)
# return the response
return out.getvalue()
示例3: hard_coded_analysis_a
# 需要导入模块: import MatrixUtil [as 别名]
# 或者: from MatrixUtil import m_to_string [as 别名]
def hard_coded_analysis_a():
tree_string = '(a:1, (b:2, d:5):1, c:4);'
tree = NewickIO.parse(tree_string, FelTree.NewickTree)
states = []
id_list = []
for state, id_ in sorted((node.name, id(node))
for node in tree.gen_tips()):
id_list.append(id_)
states.append(state)
for node in tree.gen_internal_nodes():
id_list.append(id(node))
states.append('')
n = len(states)
for method in ('tips', 'full'):
# get the distance matrix from the tree
if method == 'tips':
print 'leaves only:'
distance_matrix = tree.get_distance_matrix(states)
else:
print 'leaves and internal nodes:'
distance_matrix = tree.get_full_distance_matrix(id_list)
print 'distance matrix from the tree:'
print MatrixUtil.m_to_string(distance_matrix)
# get the equivalent euclidean points
z_points = list(gen_euclidean_points(distance_matrix))
for state, point in zip(states, z_points):
print state, point
# get the distance matrix from the transformed points
print 'distance matrix from the transformed points:'
distance_matrix = get_euclidean_distance_matrix(z_points)
print MatrixUtil.m_to_string(distance_matrix)
print
示例4: get_response_content
# 需要导入模块: import MatrixUtil [as 别名]
# 或者: from MatrixUtil import m_to_string [as 别名]
def get_response_content(fs):
# get the tree
tree = NewickIO.parse(fs.tree, FelTree.NewickTree)
# assert the the given labels are tips of the tree
tip_name_set = set(node.get_name() for node in tree.gen_tips())
user_name_set = set([fs.lhs_a, fs.lhs_b, fs.rhs_a, fs.rhs_b])
bad_names = user_name_set - tip_name_set
if bad_names:
msg = 'these labels are not valid tips: %s' % ', '.join(bad_names)
raise HandlingError(msg)
# get the submatrix of the distance matrix
ordered_names = list(sorted(node.get_name() for node in tree.gen_tips()))
D = np.array(tree.get_distance_matrix(ordered_names))
# get the response matrix
R = Clustering.get_R_stone(D)
# get the two by two matrix
name_to_index = dict((name, i) for i, name in enumerate(ordered_names))
R_reduced = np.zeros((2,2))
la = name_to_index[fs.lhs_a]
lb = name_to_index[fs.lhs_b]
ra = name_to_index[fs.rhs_a]
rb = name_to_index[fs.rhs_b]
R_reduced[0][0] = R[la][ra]
R_reduced[0][1] = R[la][rb]
R_reduced[1][0] = R[lb][ra]
R_reduced[1][1] = R[lb][rb]
epsilon = 1e-13
criterion = np.linalg.det(R_reduced)
if abs(criterion) < epsilon:
criterion = 0
# in analogy to the four point condition, use two different ways of calculating the distance
blen_a = (D[la][rb] + D[lb][ra] - D[la][lb] - D[ra][rb]) / 2.0
blen_b = (D[la][ra] + D[lb][rb] - D[la][lb] - D[ra][rb]) / 2.0
blen = min(blen_a, blen_b)
# define the response
out = StringIO()
paragraphs = []
if fs.show_response:
paragraph = [
'response matrix with rows ordered alphabetically by leaf label:',
MatrixUtil.m_to_string(R)]
paragraphs.append(paragraph)
if fs.show_reduced_response:
paragraph = [
'2x2 submatrix of the response matrix:',
MatrixUtil.m_to_string(R_reduced)]
paragraphs.append(paragraph)
if True:
paragraph = [
'determinant of the 2x2 submatrix of the response matrix:',
str(criterion)]
paragraphs.append(paragraph)
if fs.show_blen:
paragraph = [
'branch length defined by the split:',
str(blen)]
paragraphs.append(paragraph)
# return the response
return '\n\n'.join('\n'.join(p) for p in paragraphs) + '\n'
示例5: get_response_content
# 需要导入模块: import MatrixUtil [as 别名]
# 或者: from MatrixUtil import m_to_string [as 别名]
def get_response_content(fs):
# get the tree
tree = NewickIO.parse(fs.tree, FelTree.NewickTree)
# get the arbitrarily ordered names
ordered_names = set(node.get_name() for node in tree.preorder())
# get the corresponding ordered ids
name_to_id = dict((node.get_name(), id(node)) for node in tree.preorder())
ordered_ids = [name_to_id[name] for name in ordered_names]
# get the full distance matrix
D_direct = np.array(tree.get_full_distance_matrix(ordered_ids))
# get the full weighted adjacency matrix
A = np.array(tree.get_affinity_matrix(ordered_ids))
# get the full degree matrix
degree_matrix = np.diag(np.sum(A, 0))
# get the sum of the branch lengths
n = len(ordered_names)
gamma_inv = 0
for i in range(n):
for j in range(n):
if i < j:
if A[i][j]:
gamma_inv += 1.0 / A[i][j]
gamma = 1.0 / gamma_inv
# get the delta vector
delta_list = []
for row in A:
nonzero_edge_count = sum(1 for x in row if x)
delta_list.append(2 - nonzero_edge_count)
d = np.array(delta_list)
# get the full distance matrix using the clever formula
J = np.ones((n, n))
D_clever = 2*np.linalg.inv(A + gamma * np.outer(d, d) - degree_matrix)
# check whether the distance matrices are close
closeness_string = 'the distance matrices are close'
if not np.allclose(D_direct, D_clever):
closeness_string = 'the distance matrices are not close'
# define the response
out = StringIO()
paragraphs = []
if fs.show_direct_d:
paragraph = [
'directly calculated distance matrix:',
MatrixUtil.m_to_string(D_direct)]
paragraphs.append(paragraph)
if fs.show_clever_d:
paragraph = [
'cleverly calculated distance matrix:',
MatrixUtil.m_to_string(D_clever)]
paragraphs.append(paragraph)
if fs.show_closeness:
paragraph = [
'closeness:',
closeness_string]
paragraphs.append(paragraph)
# return the response
return '\n\n'.join('\n'.join(p) for p in paragraphs) + '\n'
示例6: get_response_content
# 需要导入模块: import MatrixUtil [as 别名]
# 或者: from MatrixUtil import m_to_string [as 别名]
def get_response_content(fs):
# get the tree
tree = NewickIO.parse(fs.tree, FelTree.NewickTree)
alphabetically_ordered_states = list(sorted(node.name for node in tree.gen_tips()))
n = len(alphabetically_ordered_states)
if n < 2:
raise HandlingError("the newick tree should have at least two leaves")
# read the ordered labels
states = Util.get_stripped_lines(StringIO(fs.inlabels))
if len(states) > 1:
if set(states) != set(alphabetically_ordered_states):
msg_a = "if ordered labels are provided, "
msg_b = "each should correspond to a leaf of the newick tree"
raise HandlingError(msg_a + msg_b)
else:
states = alphabetically_ordered_states
# create the distance matrix
D = tree.get_distance_matrix(states)
# create the perturbed distance matrix if necessary
if fs.strength:
P = [row[:] for row in D]
for i in range(n):
for j in range(i):
x = random.normalvariate(0, fs.strength)
new_distance = D[i][j] * math.exp(x)
P[i][j] = new_distance
P[j][i] = new_distance
else:
P = D
# start collecting the paragraphs
paragraphs = []
# show the distance matrix if requested
if fs.perturbed:
paragraph = StringIO()
print >> paragraph, "a perturbed distance matrix:"
print >> paragraph, MatrixUtil.m_to_string(P)
paragraphs.append(paragraph.getvalue().strip())
# show the distance matrix if requested
if fs.distance:
paragraph = StringIO()
print >> paragraph, "the original distance matrix:"
print >> paragraph, MatrixUtil.m_to_string(D)
paragraphs.append(paragraph.getvalue().strip())
# show the ordered labels if requested
if fs.outlabels:
paragraph = StringIO()
print >> paragraph, "ordered labels:"
print >> paragraph, "\n".join(states)
paragraphs.append(paragraph.getvalue().strip())
# return the response
return "\n\n".join(paragraphs) + "\n"
示例7: get_response_content
# 需要导入模块: import MatrixUtil [as 别名]
# 或者: from MatrixUtil import m_to_string [as 别名]
def get_response_content(fs):
out = StringIO()
# read the distance matrix
D = fs.matrix
n = len(D)
# get the list of implied variances
V = [sum(row) / (n - 2) for row in D]
# create the sigma matrix
sigma = np.empty((n,n))
for i in range(n):
for j in range(n):
sigma[i][j] = (V[i] + V[j] - D[i][j]) / 2.0
# compute the eigendecomposition
w, v = scipy.linalg.eigh(sigma)
# write the response
print >> out, 'covariance-like matrix:'
print >> out, MatrixUtil.m_to_string(sigma)
print >> out
print >> out, 'eigenvalues:'
print >> out, w
print >> out
print >> out, 'eigenvectors:'
print >> out, v
print >> out
# return the response
return out.getvalue().rstrip()
示例8: do_first_method
# 需要导入模块: import MatrixUtil [as 别名]
# 或者: from MatrixUtil import m_to_string [as 别名]
def do_first_method(subtree_a, subtree_b,
taxa_a1, taxa_a2, taxa_b1, taxa_b2, connecting_branch_length, out):
# define the branch lengths of the reduced tree
blen_a1, blen_a2, blen_ar = get_branch_length_equivalents(
subtree_a, taxa_a1, taxa_a2)
blen_b1, blen_b2, blen_br = get_branch_length_equivalents(
subtree_b, taxa_b1, taxa_b2)
# define the distance matrix of the reduced tree
a, b = blen_a1, blen_a2
c, d = blen_b1, blen_b2
e = connecting_branch_length + blen_ar + blen_br
reduced_D = [
[0, a+b, a+e+c, a+e+d],
[b+a, 0, b+e+c, b+e+d],
[c+e+a, c+e+b, 0, c+d],
[d+e+a, d+e+b, d+c, 0]]
# get the R matrix of the reduced tree
reduced_R = Clustering.get_R_balaji(reduced_D)
print >> out, 'first method:'
print >> out, 'equivalent subtree A:', '(a1:%f, a2:%f);' % (a, b)
print >> out, 'equivalent subtree B:', '(b1:%f, b2:%f);' % (c, d)
print >> out, 'equivalent connecting branch length:', e
print >> out, 'M for the equivalent tree:'
print >> out, MatrixUtil.m_to_string(reduced_R)
print >> out
示例9: get_response_content
# 需要导入模块: import MatrixUtil [as 别名]
# 或者: from MatrixUtil import m_to_string [as 别名]
def get_response_content(fs):
"""
@param fs: a FieldStorage object containing the cgi arguments
@return: a (response_headers, response_text) pair
"""
# get the tree
tree = NewickIO.parse(fs.tree, FelTree.NewickTree)
# read the ordered labels
ordered_labels = Util.get_stripped_lines(StringIO(fs.labels))
# validate the input
observed_label_set = set(node.get_name() for node in tree.gen_tips())
if set(ordered_labels) != observed_label_set:
msg = 'the labels should match the labels of the leaves of the tree'
raise HandlingError(msg)
# get the matrix of pairwise distances among the tips
D = np.array(tree.get_distance_matrix(ordered_labels))
L = Euclid.edm_to_laplacian(D)
w, v = get_eigendecomposition(L)
C = get_contrast_matrix(w, v)
# set elements with small absolute value to zero
C[abs(C) < fs.epsilon] = 0
# start to prepare the reponse
out = StringIO()
if fs.plain_format:
print >> out, MatrixUtil.m_to_string(C)
elif fs.matlab_format:
print >> out, MatrixUtil.m_to_matlab_string(C)
elif fs.r_format:
print >> out, MatrixUtil.m_to_R_string(C)
# write the response
return out.getvalue()
示例10: get_response_content
# 需要导入模块: import MatrixUtil [as 别名]
# 或者: from MatrixUtil import m_to_string [as 别名]
def get_response_content(fs):
# read the matrix
L = fs.laplacian
# read the ordered labels
ordered_labels = Util.get_stripped_lines(StringIO(fs.labels))
if not ordered_labels:
raise HandlingError('no ordered taxa were provided')
if len(ordered_labels) != len(set(ordered_labels)):
raise HandlingError('the ordered taxa should be unique')
# get the label selection and its complement
min_selected_labels = 2
min_unselected_labels = 1
selected_labels = set(Util.get_stripped_lines(StringIO(fs.selection)))
if len(selected_labels) < min_selected_labels:
raise HandlingError('at least %d taxa should be selected to be grouped' % min_selected_labels)
# get the set of labels in the complement
unselected_labels = set(ordered_labels) - selected_labels
if len(unselected_labels) < min_unselected_labels:
raise HandlingError('at least %d taxa should remain outside the selected group' % min_unselected_labels)
# assert that no bizarre labels were selected
weird_labels = selected_labels - set(ordered_labels)
if weird_labels:
raise HandlingError('some selected taxa are invalid: ' + str(weird_labels))
# assert that the size of the distance matrix is compatible with the number of ordered labels
if len(L) != len(ordered_labels):
raise HandlingError('the number of listed taxa does not match the number of rows in the distance matrix')
# get the set of selected indices and its complement
n = len(L)
index_selection = set(i for i, label in enumerate(ordered_labels) if label in selected_labels)
index_complement = set(range(n)) - index_selection
# begin the response
out = StringIO()
# calculate the new laplacian matrix
L_small = SchurAlgebra.mschur(L, index_selection)
D_small = Euclid.laplacian_to_edm(L_small)
# print the matrices and the labels of its rows
print >> out, 'new laplacian matrix:'
print >> out, MatrixUtil.m_to_string(L_small)
print >> out
print >> out, 'new distance matrix:'
print >> out, MatrixUtil.m_to_string(D_small)
print >> out
print >> out, 'new taxon labels:'
for index in sorted(index_complement):
print >> out, ordered_labels[index]
# write the response
return out.getvalue()
示例11: get_response_content
# 需要导入模块: import MatrixUtil [as 别名]
# 或者: from MatrixUtil import m_to_string [as 别名]
def get_response_content(fs):
out = StringIO()
# try to make some graphs
unconnected_count = 0
invalid_split_count = 0
valid_split_count = 0
for graph_index in range(fs.ngraphs):
G = erdos_renyi(fs.nvertices, fs.pedge)
if is_connected(G):
# add interesting edge weights
add_exponential_weights(G)
# turn the adjacency matrix into a laplacian matrix
L = Euclid.adjacency_to_laplacian(G)
for v in range(fs.nvertices):
small_index_to_big_index = {}
for i_small, i_big in enumerate([i for i in range(fs.nvertices) if i != v]):
small_index_to_big_index[i_small] = i_big
# take the schur complement with respect to the given vertex
L_reduced = get_single_element_schur_complement(L, v)
assert len(L_reduced) == len(L) - 1
# get the loadings of the vertices of the reduced graph
if fs.fiedler_cut:
Y_reduced = BuildTreeTopology.laplacian_to_fiedler(L_reduced)
elif fs.random_cut:
Y_reduced = get_random_vector(L_reduced)
assert len(Y_reduced) == len(L_reduced)
# expand the fiedler vector with positive and negative valuations for the removed vertex
found_valid_split = False
for augmented_loading in (-1.0, 1.0):
# get the augmented split vector for this assignment of the removed vertex
Y_full = [0]*len(G)
for i_reduced, loading in enumerate(Y_reduced):
i_big = small_index_to_big_index[i_reduced]
Y_full[i_big] = loading
Y_full[v] = augmented_loading
assert len(Y_full) == len(G)
# get the two graphs defined by the split
subgraph_a, subgraph_b = list(gen_subgraphs(G, Y_full))
# if the subgraphs are both connected then the split is valid
if is_connected(subgraph_a) and is_connected(subgraph_b):
found_valid_split = True
# if a valid split was not found then show the matrix
if found_valid_split:
valid_split_count += 1
else:
print >> out, 'Found a matrix that was split incompatibly by a cut of its schur complement!'
print >> out, 'matrix:'
print >> out, MatrixUtil.m_to_string(G)
print >> out, 'index that was removed:', v
invalid_split_count += 1
else:
unconnected_count += 1
# show the number of connected and of unconnected graphs
print >> out, 'this many random graphs were connected:', fs.ngraphs - unconnected_count
print >> out, 'this many random graphs were not connected:', unconnected_count
print >> out, 'this many splits were valid:', valid_split_count
print >> out, 'this many splits were invalid:', invalid_split_count
# return the result
return out.getvalue()
示例12: get_response_content
# 需要导入模块: import MatrixUtil [as 别名]
# 或者: from MatrixUtil import m_to_string [as 别名]
def get_response_content(fs):
# begin the response
out = StringIO()
# create the adjacency matrix
n = 3**fs.iterations
M = np.zeros((n, n))
add_sierpinski(M, 0, fs.iterations)
M = M + M.T
if fs.adjacency:
print >> out, MatrixUtil.m_to_string(M)
elif fs.laplacian:
for i, row in enumerate(M):
M[i][i] = -sum(row)
M = -M
print >> out, MatrixUtil.m_to_string(M)
# write the response
return out.getvalue()
示例13: get_response_content
# 需要导入模块: import MatrixUtil [as 别名]
# 或者: from MatrixUtil import m_to_string [as 别名]
def get_response_content(fs):
# read the distance matrix
D = fs.matrix
L = Euclid.edm_to_laplacian(D)
resistor = -1/L
resistor -= np.diag(np.diag(resistor))
# return the edge resistor matrix
return MatrixUtil.m_to_string(resistor) + '\n'
示例14: get_response_content
# 需要导入模块: import MatrixUtil [as 别名]
# 或者: from MatrixUtil import m_to_string [as 别名]
def get_response_content(fs):
# read the matrix
M = fs.matrix
# get the pseudo inverse
M_pinv = np.linalg.pinv(M)
# set small values to zero in the output
M_pinv[abs(M_pinv) < fs.epsilon] = 0
# return the response string
return MatrixUtil.m_to_string(M_pinv) + '\n'
示例15: get_response_content
# 需要导入模块: import MatrixUtil [as 别名]
# 或者: from MatrixUtil import m_to_string [as 别名]
def get_response_content(fs):
# read the matrix
L = fs.laplacian
# get the distance matrix
if fs.correct:
D = get_correct_distance_matrix(L)
else:
D = get_incorrect_distance_matrix(L)
# return the response
return MatrixUtil.m_to_string(D) + '\n'