|
20 | 20 | # import from Sage library |
21 | 21 | from sage.graphs.graph import Graph |
22 | 22 | from math import sin, cos, pi |
| 23 | +from numpy import corrcoef |
| 24 | +from sage.matrix.constructor import Matrix |
23 | 25 |
|
24 | 26 |
|
25 | 27 | def BullGraph(): |
@@ -393,6 +395,43 @@ def CompleteGraph(n): |
393 | 395 | G.add_edges(((i, j) for i in range(n) for j in range(i + 1, n))) |
394 | 396 | return G |
395 | 397 |
|
| 398 | +def CorrelationGraph(seqs, alpha, include_anticorrelation): |
| 399 | + """ |
| 400 | + Constructs and returns a correlation graph with a node corresponding to each sequence in `seqs`. |
| 401 | +
|
| 402 | + Edges are added between nodes where the corresponding sequences have a correlation coeffecient greater than alpha. |
| 403 | +
|
| 404 | + If include_anticorrelation is true, then edges are also added between nodes with correlation coeffecient less than -alpha. |
| 405 | +
|
| 406 | + EXAMPLES: |
| 407 | +
|
| 408 | + sage: from sage.graphs.generators.basic import CorrelationGraph |
| 409 | + sage: data=[[1,2,3],[4,5,6],[7,8,9999]] |
| 410 | + sage: CG1 = CorrelationGraph(data, 0.9, False) |
| 411 | + sage: CG2 = CorrelationGraph(data, 0.9, True) |
| 412 | + sage: CG3 = CorrelationGraph(data, 0.1, True) |
| 413 | + sage: CG1.edges(sort=False) |
| 414 | + [(0, 0, None), (0, 1, None), (1, 1, None), (2, 2, None)] |
| 415 | + sage: CG2.edges(sort=False) |
| 416 | + [(0, 0, None), (0, 1, None), (1, 1, None), (2, 2, None)] |
| 417 | + sage: CG3.edges(sort=False) |
| 418 | + [(0, 0, None), (0, 1, None), (0, 2, None), (1, 1, None), (1, 2, None), (2, 2, None)] |
| 419 | +
|
| 420 | + """ |
| 421 | + |
| 422 | + # compute pairwise correlation coeffecients |
| 423 | + corrs = corrcoef(seqs) |
| 424 | + |
| 425 | + # compare against alpha to get adjacency matrix |
| 426 | + if include_anticorrelation: |
| 427 | + boolean_adjacency_matrix = abs(corrs)>=alpha |
| 428 | + else: |
| 429 | + boolean_adjacency_matrix = corrs>=alpha |
| 430 | + |
| 431 | + adjacency_matrix = Matrix(boolean_adjacency_matrix.astype(int)) |
| 432 | + |
| 433 | + # call graph constructor |
| 434 | + return Graph(adjacency_matrix, format="adjacency_matrix", name="Correlation Graph") |
396 | 435 |
|
397 | 436 | def CompleteBipartiteGraph(p, q, set_position=True): |
398 | 437 | r""" |
|
0 commit comments