SOURCE topf/src/topf/topfmain.py SHA256 26af1240e91ccbb0ea8a1b0e067da03030a0a29f3c39b107f4384ca535dfa7bf

27: def topf(
28:     base_points,
29:     complex_type="auto",
30:     thresh_distance=0,
31:     max_hom_dim=1.0,
32:     max_rel_quot=0.1,
33:     interpolation_coefficient=0.3,
34:     weight_exponent=-1,
35:     simplex_threshs=(0.1, 0.1),
36:     max_num_simplices_drawn=750,
37:     n_clusters="auto",
38:     draw_reps=False,
39:     draw_scaled_vecs=False,
40:     draw_final_clustering=False,

331:             verbose=verbose,
332:         )
333:         multi_eigen_vecs[cur_d] = eigen_vecs
334:         multi_scaled_vecs_save.append([np.copy(array) for array in scaled_vecs])
335:         if eigenvector_tresholding:
336:             for i, vec in enumerate(scaled_vecs):
337:                 scaled_vecs[i] = np.array(
338:                     [
339:                         my_threshold(
340:                             value=v,
341:                             threshold=eigenvector_threshold,
342:                             thresholding_type=thresholding_type,
343:                         )
344:                         for v in vec
345:                     ]
346:                 )
347:         multi_scaled_vecs[cur_d] = [np.copy(array) for array in scaled_vecs]
348:         multi_all_num_k_simplices_in_p[cur_d] = all_num_k_simplices_in_p

974: def generate_short_point_signatures(long_point_signatures, aggregation_mode="mean"):
975:     """
976:         Shortens the long point signatures.
977:     """
978:     short_signatures = []
979:     short_flat_signatures = []
980:     for single_point_signature in long_point_signatures:
981:         short_point_signature = []
982:         short_flat_point_signature = []
983:         for dim_signature in single_point_signature:
984:             short_dim_signature = []
985:             for eigenvec_signature in dim_signature:
986:                 if aggregation_mode == "mean":
987:                     if len(eigenvec_signature) == 0:
988:                         new_entry = 0
989:                     else:
990:                         new_entry = np.mean(np.array(eigenvec_signature))
991:                 else:
992:                     new_entry = np.max(np.array(eigenvec_signature + [0]))
993:                 short_dim_signature.append(new_entry)
994:                 short_flat_point_signature.append(new_entry)
995:             short_point_signature.append(short_dim_signature)
996:         short_signatures.append(short_point_signature)
997:         short_flat_signatures.append(short_flat_point_signature)
998:     return np.array(short_flat_signatures)
999: 
1000: 
1001: def generate_long_point_signatures(
1002:     base_points, multi_inds, multi_multi_simplices, multi_scaled_vecs
1003: ):
1004:     """
1005:         Generates the long point signatures from the eigenvector components on the higher-order simplices.
1006:     """
1007:     long_point_signatures = []
1008:     for i in range(len(base_points)):
1009:         cur_signature = []
1010:         for inds in multi_inds:
1011:             cur_temp_signature = []
1012:             for ind in inds:
1013:                 cur_temp_signature.append([])
1014:             cur_signature.append(cur_temp_signature)
1015:         long_point_signatures.append(cur_signature)
1016:     for d, inds in enumerate(multi_inds):
1017:         for i in range(len(inds)):
1018:             for h, simplex in enumerate(multi_multi_simplices[d][i][d]):
1019:                 for vertex in simplex:
1020:                     long_point_signatures[vertex][d][i].append(
1021:                         multi_scaled_vecs[d][i][h]
1022:                     )
1023:     return long_point_signatures

1426:         if verbose:
1427:             print(cur_d)
1428:         if verbose:
1429:             print(num_k_simplices_in_p)
1430:         char_vector = np.zeros(num_k_simplices_in_p[cur_d])
1431:         if verbose:
1432:             print("We are at cur_d = " + str(cur_d))
1433:             print("We are at i = " + str(i))
1434:             print("Total multi_reps_length: " + str(len(multi_reps)))
1435:             print("Current multi_reps length: " + str(len(multi_reps[cur_d])))
1436:         for rep in multi_reps[cur_d][i]:
1437:             simplex = rep[0]
1438:             value = rep[1]
1439:             simplex_key = str([int(i) for i in list(np.flip(simplex))])
1440:             if simplex_key in simplexdict[cur_d]:
1441:                 char_vector[simplexdict[cur_d][simplex_key]] = (value + 1 % 3) - 1
1442:         if cur_d == 0:
1443:             if verbose:
1444:                 print(np.sum(char_vector))
1445:             vec = char_vector
1446:             success = True
1447:         else:
1448:             success = is_cycle(char_vector, boundary_operators[cur_d -1])
1449:             if not success:
1450:                 if verbose:
1451:                     print("Char vector is not a cycle, attempting to fix.")
1452:                 char_vector, success = fix_char_vector(char_vector, boundary_operators[cur_d -1])
1453:             if success:
1454:                 if use_eff_resistance:
1455:                     vec = compute_weighted_harmonic_projection_lower_res(
1456:                         Bkm=boundary_operators[cur_d - 1],
1457:                         Bk=boundary_operators[cur_d],
1458:                         vec=char_vector,
1459:                         exponent=eff_resistance_exponent,
1460:                     )
1461:                 else:
1462:                     if len(boundary_operators) < cur_d + 2:
1463:                         boundary_operators.append(
1464:                             np.zeros((num_k_simplices_in_p[cur_d], 1))
1465:                         )
1466:                         if verbose:
1467:                             print("We are at cur_d = " + str(cur_d))
1468:                             print(
1469:                                 "length boundary operator:" + str(len(boundary_operators))
1470:                             )
1471:                     vec = compute_weighted_harmonic_projection_num_tris(
1472:                         Bkm=boundary_operators[cur_d - 1],
1473:                         Bk=boundary_operators[cur_d],
1474:                         vec=char_vector,
1475:                         exponent=weight_exponent,
1476:                     )
1477:         if success:
1478:             eigen_vecs.append(vec)
1479:             scaled_vecs.append(np.abs(vec) / np.max(np.abs(vec) + 1e-13))
1480:             all_num_k_simplices_in_p.append(num_k_simplices_in_p)
1481:             multi_points.append(cur_points)
1482:             multi_simplices.append(simplices)
1483:         else:
1484:             warnings.warn(
1485:                         "Topological feature with life_times "+str(multi_life_times[cur_d][cur_index])+" could not be lifted to real coefficients. Skipping this representative.",
1486:                         category=RuntimeWarning,
1487:                     )
1488:             if verbose:
1489:                 print("Char vector could not be fixed.")
1490:             del(multi_inds[cur_d][i])
1491:     return (
1492:         eigen_vecs,
1493:         scaled_vecs,
1494:         all_num_k_simplices_in_p,
1495:         multi_points,
1496:         multi_simplices,
1497:         multi_inds,
1498:     )
1499: 
1500: def fix_char_vector(char_vector, Bkm):
1501:     """
1502:     Fixes the char_vector to be in the kernel of the matrix Bkm.
1503:     """
1504:     gradient_generator = Bkm @ char_vector
1505:     constraints = LinearConstraint(Bkm, gradient_generator // 3, gradient_generator // 3)
1506:     objective = np.zeros((len(char_vector))) # Any solution will do solution
1507:     integrality = np.ones((len(char_vector))) # enforce integrality for all variables
1508:     bounds = scipy.optimize.Bounds() # default bounds are (-inf, inf)
1509:     milp_return = milp(
1510:         objective,
1511:         bounds = bounds, #if not specified, only positive values are allowed
1512:         integrality=integrality, 
1513:         constraints=constraints,
1514:     )
1515:     if not milp_return["success"]:
1516:         return char_vector, False
1517:     else:
1518:         solution = milp_return["x"]
1519:         fixed_char_vector = char_vector - 3 * solution
1520:         if (Bkm@fixed_char_vector).any():
1521:             print("Error: Fixed char vector is not in the kernel of the matrix.")
1522:         return fixed_char_vector, True

1600:             ast.literal_eval(data[0].replace("Int128, ", "").replace("Int128","").replace("Tuple{}","")),
1601:             ast.literal_eval(data[1].replace("Int128, ", "").replace("Int128","").replace("Tuple{}",""))
1602:             ]
1603:             for data in np.array(cur_df[[2, 3]])
1604:         ]
1605:         cur_reps = []
1606:         for representations in base_reps:
1607:             cur_rep = []
1608:             for i, rep in enumerate(representations[0]):
1609:                 cur_rep.append([np.array(rep) - 1, (representations[1][i] + 1) % 3 - 1])
1610:             cur_reps.append(cur_rep)
1611:         multi_representations.append(cur_reps)
1612:         if thresh_julia > 0:
1613:             finite_inds = np.where(cur_life_times[:, 1] < np.inf)

1654:                 cur_persistence = cur_persistence[finite_inds[0]]
1655:         if complex_type == "alpha":
1656:             cur_life_times = cur_life_times / 2
1657:             thresh_julia = thresh_julia / 2
1658:             if verbose:
1659:                 print("Alpha complex life times halved")
1660:         multi_life_times.append(cur_life_times)

1897: def compute_weighted_harmonic_projection(Bkm, Bk, vec, weights, verbose=False):
1898:     """
1899:     Computes the weighted harmonic projection of a vector onto the kernel of the boundary operators.
1900:     """
1901:     exp = 0.5
1902:     vec = vec / (weights ** exp + 1e-13)
1903:     weight_matrix = scipy.sparse.diags(weights ** exp)
1904:     inv_weight_matrix = scipy.sparse.diags(1 / weights ** exp)
1905:     grad_gen = scipy.sparse.linalg.lsmr(weight_matrix @ Bkm.T, vec)[0]
1906:     grad_component = weight_matrix @ Bkm.T @ grad_gen
1907:     curl_gen = scipy.sparse.linalg.lsmr(inv_weight_matrix @ Bk, vec - grad_component)[0]
1908:     curl_component = inv_weight_matrix @ Bk @ curl_gen
1909:     if verbose:
1910:         print("grad component norm: ", np.linalg.norm(grad_component))
1911:     if verbose:
1912:         print("curl component norm: ", np.linalg.norm(curl_component))
1913:     return vec - grad_component - curl_component
1914: 
1915: 
1916: def compute_weighted_harmonic_projection_num_tris(Bkm, Bk, vec, exponent=-1):
1917:     """
1918:     Computes the weighted harmonic projection by number of upper-adjacent simplices of a vector onto the kernel of the boundary operators.
1919:     """
1920:     tri_counts = np.array(np.sum(np.abs(Bk), axis=1)).flatten() + 1
1921:     weights = np.power(tri_counts, exponent)
1922:     return compute_weighted_harmonic_projection(Bkm, Bk, vec, weights)

1999: def extract_boundary_operators(simplices, simplexdict, num_k_simplices_in_p):
2000:     """
2001:     Extracts the boundary operators from the simplices and the simplexdict.
2002:     """
2003:     maxdim = len(num_k_simplices_in_p) - 1
2004:     boundary_operators = []
2005:     for k in range(maxdim):
2006:         coordi = []
2007:         coordj = []
2008:         entries = []
2009:         for simplex in simplices[k + 1]:
2010:             simplex_index = simplexdict[k + 1][str(simplex)]
2011:             for i in range(k + 2):
2012:                 new_simplex = simplex.copy()
2013:                 new_simplex.pop(i)
2014:                 new_simplex_index = simplexdict[k][str(new_simplex)]
2015:                 coordi.append(new_simplex_index)
2016:                 coordj.append(simplex_index)
2017:                 if i % 2 == 0:
2018:                     entries.append(1)
2019:                 else:
2020:                     entries.append(-1)
2021:         boundary_operators.append(
2022:             scipy.sparse.csc_matrix(
2023:                 (np.array(entries), (np.array(coordi), np.array(coordj))),
2024:                 shape=(num_k_simplices_in_p[k], num_k_simplices_in_p[k + 1]),
2025:                 dtype=float,
2026:             )
2027:         )
2028:     return boundary_operators

SOURCE topf/src/topf/HomologyGeneratorsMultiD.jl SHA256 aafbeeb26e245470cd7831eaeac9e27fae784fd9911ad963204158c9cc607d6a

40: complex_construction_time = end_time - start_time
41: RipsResults = Ripserer.ripserer(RipsComplex; modulus=:3, reps=true, dim_max=dim_max + 1, alg=:involuted)
42: start_time = end_time
43: end_time = time()
44: homology_time = end_time - start_time
45: num_entries = length(RipsResults[1])
46: subset_size = min(1000, max(min(50, num_entries), Int(ceil(0.1 * num_entries))))
47: subset = RipsResults[1][end-subset_size+1:end]
48: CSV.write(Base.stdout, permutedims(DataFrame([[HomClass[1], HomClass[2], [vertices(rep) for rep in HomClass.representative], [1 for rep in HomClass.representative]] for HomClass in subset], :auto)), header=false)
49: print("newfile")
50: #only consider first ten percent of homology classes
51: num_entries = length(RipsResults[2])
52: subset_size = min(1000, max(min(50, num_entries), Int(ceil(0.1 * num_entries))))
53: subset = RipsResults[2][end-subset_size+1:end]
54: CSV.write(Base.stdout, permutedims(DataFrame([[HomClass[1], HomClass[2], [vertices(rep.simplex) for rep in HomClass.representative], [Int(rep[2]) for rep in HomClass.representative]] for HomClass in subset], :auto)), header=false)
55: if dim_max == 2
56:     print("newfile")
57:     num_entries = length(RipsResults[3])
58:     subset_size = min(1000, max(min(50, num_entries), Int(ceil(0.1 * num_entries))))
59:     subset = RipsResults[3][end-subset_size+1:end]

SOURCE dependencies/Ripserer.jl/src/computation/zerodimensional.jl SHA256 5da1b1cb52213ca6c34ebf8d8b02cc456a5893632458644742aa836af0ac8e75

78:     birth_time, birth_vertex = birth(dset, vertex)
79:     death_time = isnothing(edge) ? Inf : birth(edge)
80:     if death_time - birth_time > cutoff
81:         birth_simplex::simplex_type(filtration, 0) = simplex(
82:             filtration, Val(0), (birth_vertex,)
83:         )
84:         if reps
85:             rep = (;
86:                 representative=sort!([
87:                     simplex(filtration, Val(0), (v,)) for v in find_leaves!(dset, vertex)
88:                 ])
89:             )
90:         else
91:             rep = NamedTuple()
92:         end
93:         meta = (; birth_simplex=birth_simplex, death_simplex=edge, rep...)
94:         return PersistenceInterval(birth_time, death_time, meta)
95:     else
96:         return nothing
97:     end
98: end
99: 
100: """
101:     zeroth_intervals(filtration, cutoff, verbose, field_type, reps)
102: 
103: Compute 0-dimensional persistent homology using Kruskal's Algorithm.
104: 
105: Only keep intervals with desired birth/death `cutoff`. Compute homology with coefficients in
106: `field_type`. If `reps` is `true`, compute representative cocycles. Show a progress bar if
107: `verbose` is set.
108: """
109: function zeroth_intervals(filtration, cutoff, verbose, ::Type{F}, reps) where {F}

SOURCE dependencies/Ripserer.jl/src/filtrations/alpha.jl SHA256 306f26b678642da1949af8973d8f261f6de85b2c041d2fdf3ffe6273e416a696

142:     circumradii. This makes the scale of the results comparable to `Rips`. If you need
143:     radius based values, divide your data or the resulting interval endpoints by 2.
144: 
145: !!! warning
146:     This filtration uses [MiniQhull.jl](https://github.com/gridap/MiniQhull.jl). Please see
147:     the installation instructions if constructions cause errors. MiniQhull currently has
148:     problems running on Windows. See [this
149:     issue](https://github.com/gridap/MiniQhull.jl/issues/5) for more info.
150: 
151: # Constructors
152: 
153: * `Alpha(points; threshold, verbose)`: `points` should be a vector of `Tuple`s, `SVector`s