PyQrackIsing 9.13.0__tar.gz → 9.14.0__tar.gz

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (35) hide show
  1. {pyqrackising-9.13.0/pyqrackising.egg-info → pyqrackising-9.14.0}/PKG-INFO +1 -1
  2. {pyqrackising-9.13.0 → pyqrackising-9.14.0}/README.md +15 -2
  3. {pyqrackising-9.13.0 → pyqrackising-9.14.0}/pyproject.toml +1 -1
  4. {pyqrackising-9.13.0 → pyqrackising-9.14.0}/pyqrackising/spin_glass_solver.py +173 -11
  5. {pyqrackising-9.13.0 → pyqrackising-9.14.0}/pyqrackising/spin_glass_solver_sparse.py +204 -11
  6. {pyqrackising-9.13.0 → pyqrackising-9.14.0}/pyqrackising/spin_glass_solver_streaming.py +173 -10
  7. {pyqrackising-9.13.0 → pyqrackising-9.14.0/pyqrackising.egg-info}/PKG-INFO +1 -1
  8. {pyqrackising-9.13.0 → pyqrackising-9.14.0}/setup.py +1 -1
  9. {pyqrackising-9.13.0 → pyqrackising-9.14.0}/LICENSE.md +0 -0
  10. {pyqrackising-9.13.0 → pyqrackising-9.14.0}/MANIFEST.in +0 -0
  11. {pyqrackising-9.13.0 → pyqrackising-9.14.0}/pyqrackising/__init__.py +0 -0
  12. {pyqrackising-9.13.0 → pyqrackising-9.14.0}/pyqrackising/convert_tensor_network_to_tsp.py +0 -0
  13. {pyqrackising-9.13.0 → pyqrackising-9.14.0}/pyqrackising/generate_tfim_samples.py +0 -0
  14. {pyqrackising-9.13.0 → pyqrackising-9.14.0}/pyqrackising/kernels.cl +0 -0
  15. {pyqrackising-9.13.0 → pyqrackising-9.14.0}/pyqrackising/maxcut_tfim.py +0 -0
  16. {pyqrackising-9.13.0 → pyqrackising-9.14.0}/pyqrackising/maxcut_tfim_sparse.py +0 -0
  17. {pyqrackising-9.13.0 → pyqrackising-9.14.0}/pyqrackising/maxcut_tfim_streaming.py +0 -0
  18. {pyqrackising-9.13.0 → pyqrackising-9.14.0}/pyqrackising/maxcut_tfim_util.py +0 -0
  19. {pyqrackising-9.13.0 → pyqrackising-9.14.0}/pyqrackising/otoc.py +0 -0
  20. {pyqrackising-9.13.0 → pyqrackising-9.14.0}/pyqrackising/solve_maxcut_bnb.py +0 -0
  21. {pyqrackising-9.13.0 → pyqrackising-9.14.0}/pyqrackising/solve_maxcut_bnb_sparse.py +0 -0
  22. {pyqrackising-9.13.0 → pyqrackising-9.14.0}/pyqrackising/solve_maxcut_bnb_streaming.py +0 -0
  23. {pyqrackising-9.13.0 → pyqrackising-9.14.0}/pyqrackising/solve_maxcut_exact.py +0 -0
  24. {pyqrackising-9.13.0 → pyqrackising-9.14.0}/pyqrackising/solve_maxcut_exact_sparse.py +0 -0
  25. {pyqrackising-9.13.0 → pyqrackising-9.14.0}/pyqrackising/solve_maxcut_exact_streaming.py +0 -0
  26. {pyqrackising-9.13.0 → pyqrackising-9.14.0}/pyqrackising/tfim_magnetization.py +0 -0
  27. {pyqrackising-9.13.0 → pyqrackising-9.14.0}/pyqrackising/tfim_square_magnetization.py +0 -0
  28. {pyqrackising-9.13.0 → pyqrackising-9.14.0}/pyqrackising/tsp.py +0 -0
  29. {pyqrackising-9.13.0 → pyqrackising-9.14.0}/pyqrackising/tsp_maxcut.py +0 -0
  30. {pyqrackising-9.13.0 → pyqrackising-9.14.0}/pyqrackising.egg-info/SOURCES.txt +0 -0
  31. {pyqrackising-9.13.0 → pyqrackising-9.14.0}/pyqrackising.egg-info/dependency_links.txt +0 -0
  32. {pyqrackising-9.13.0 → pyqrackising-9.14.0}/pyqrackising.egg-info/not-zip-safe +0 -0
  33. {pyqrackising-9.13.0 → pyqrackising-9.14.0}/pyqrackising.egg-info/requires.txt +0 -0
  34. {pyqrackising-9.13.0 → pyqrackising-9.14.0}/pyqrackising.egg-info/top_level.txt +0 -0
  35. {pyqrackising-9.13.0 → pyqrackising-9.14.0}/setup.cfg +0 -0
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: pyqrackising
3
- Version: 9.13.0
3
+ Version: 9.14.0
4
4
  Summary: Fast MAXCUT, TSP, and sampling heuristics from near-ideal transverse field Ising model (TFIM)
5
5
  Home-page: https://github.com/vm6502q/PyQrackIsing
6
6
  Author: Dan Strano
@@ -73,10 +73,23 @@ def generate_spin_glass_graph(n_nodes=16, degree=3, seed=None):
73
73
 
74
74
 
75
75
  G = generate_spin_glass_graph(n_nodes=64, seed=42)
76
- solution_bit_string, cut_value, node_groups, energy = spin_glass_solver(G, quality=6, shots=None, anneal_t=8.0, anneal_h=8.0, is_spin_glass=True, best_guess=None, is_maxcut_gpu=True, gray_iterations=None, gray_seed_multiple=None)
76
+ solution_bit_string, cut_value, node_groups, energy = spin_glass_solver(
77
+ G,
78
+ quality=6,
79
+ shots=None,
80
+ anneal_t=8.0,
81
+ anneal_h=8.0,
82
+ is_spin_glass=True,
83
+ best_guess=None,
84
+ is_maxcut_gpu=True,
85
+ gray_iterations=None,
86
+ gray_seed_multiple=None,
87
+ bp_scale=None,
88
+ bp_damping=0.5
89
+ )
77
90
  # solution_bit_string, cut_value, node_groups, energy = spin_glass_solver(G, best_guess=maxcut_tfim(G, quality=6)[0])
78
91
  ```
79
- We also provide `spin_glass_solver_sparse(G)` and `spin_glass_solver_streaming(G_func, nodes)`. `best_guess` gives the option to seed the algorithm with a best guess as to the maximal cut (as an integer, binary string, or list of booleans). By default, `spin_glass_solver()` uses `maxcut_tfim(G)` with passed-through `quality` as `best_guess`, which typically works well, but it could be seeded with higher `maxcut_tfim()` `quality` or Goemans-Williamson, for example. `is_spin_glass` controls whether the solver optimizes for cut value or spin-glass energy. This function is designed with a sign convention for weights such that it can immediately be used as a MAXCUT solver itself: you might need to reverse the sign convention on your weights for spin glass graphs, but this is only convention. `gray_iterations` gives manual control over how many iterations are carried out of a parallel Gray-code search on `best_guess`. `gray_seed_multiple` controls how many parallel search seeds (as a multiple of your CPU thread count) are tested for the best parallel seeds, and a value of `1` will perfectly cover the search space without collision if your node count is a power of 2.
92
+ We also provide `spin_glass_solver_sparse(G)` and `spin_glass_solver_streaming(G_func, nodes)`. `best_guess` gives the option to seed the algorithm with a best guess as to the maximal cut (as an integer, binary string, or list of booleans). By default, `spin_glass_solver()` uses `maxcut_tfim(G)` with passed-through `quality` as `best_guess`, which typically works well, but it could be seeded with higher `maxcut_tfim()` `quality` or Goemans-Williamson, for example. `is_spin_glass` controls whether the solver optimizes for cut value or spin-glass energy. This function is designed with a sign convention for weights such that it can immediately be used as a MAXCUT solver itself: you might need to reverse the sign convention on your weights for spin glass graphs, but this is only convention. `gray_iterations` gives manual control over how many iterations are carried out of a parallel Gray-code search on `best_guess`. `gray_seed_multiple` controls how many parallel search seeds (as a multiple of your CPU thread count) are tested for the best parallel seeds, and a value of `1` will perfectly cover the search space without collision if your node count is a power of 2. `bp_scale` controls opt-in and time complexity scaling for _belief propagation_ as a competing "warm start," with `None` disabling this option completely, `1.0` representing a budget of exactly `O(n^3)` time complexity, and lesser or greater values representing a linear multiplier on that budget. `bp_damping` similarly controls belief propagation damping.
80
93
 
81
94
  These solvers above can be used as a "warm state" for _MaxSAT-based_ solvers or _branch-and-bound_ solvers, potentially to reach _exact_ solutions to MAXCUT:
82
95
 
@@ -7,7 +7,7 @@ build-backend = "setuptools.build_meta"
7
7
 
8
8
  [project]
9
9
  name = "pyqrackising"
10
- version = "9.13.0"
10
+ version = "9.14.0"
11
11
  requires-python = ">=3.8"
12
12
  description = "Fast MAXCUT, TSP, and sampling heuristics from near-ideal transverse field Ising model (TFIM)"
13
13
  readme = {file = "README.txt", content-type = "text/markdown"}
@@ -307,6 +307,120 @@ def run_gray_search_opencl(
307
307
  return energy, theta
308
308
 
309
309
 
310
+ # Belief propagation was added by (Anthropic) Claude
311
+ def belief_propagation_marginals_dense(G_m, n, bp_scale=1.0, damping=0.5):
312
+ """
313
+ Run loopy belief propagation on the dense (upper-triangular) adjacency
314
+ matrix to produce per-node marginals for warm-starting the partition.
315
+
316
+ The dense solver stores G_m as a full n×n matrix; we read only the
317
+ upper triangle (j > i) to match the sparse convention, so behaviour
318
+ is consistent across all three solver variants.
319
+
320
+ Parameters
321
+ ----------
322
+ G_m : ndarray, shape (n, n)
323
+ Dense adjacency/weight matrix. May be full or upper-triangular.
324
+ n : int
325
+ Number of nodes.
326
+ bp_scale : float
327
+ Iteration cap = int(bp_scale * n). Gives O(n * m) total work,
328
+ <= O(n^3) for any graph density. User-controlled.
329
+ damping : float
330
+ Message damping factor in [0, 1). Stabilises oscillating marginals
331
+ on dense or heavily frustrated graphs.
332
+
333
+ Returns
334
+ -------
335
+ marginals : ndarray, shape (n,)
336
+ Soft assignment in (-1, +1). Positive values favour partition 1,
337
+ negative values favour partition 0.
338
+ """
339
+ max_iterations = max(1, int(bp_scale * n))
340
+
341
+ # Collect undirected edges from upper triangle
342
+ us = []
343
+ vs = []
344
+ ws = []
345
+ for i in range(n):
346
+ for j in range(i + 1, n):
347
+ w = G_m[i, j]
348
+ if abs(w) > 1e-12:
349
+ us.append(i)
350
+ vs.append(j)
351
+ ws.append(w)
352
+
353
+ m = len(us)
354
+ if m == 0:
355
+ return np.zeros(n, dtype=np.float64)
356
+
357
+ us = np.array(us, dtype=np.int32)
358
+ vs = np.array(vs, dtype=np.int32)
359
+ ws = np.array(ws, dtype=np.float64)
360
+
361
+ # msg_fwd[k] = message from us[k] -> vs[k]
362
+ # msg_bwd[k] = message from vs[k] -> us[k]
363
+ msg_fwd = np.zeros(m, dtype=np.float64)
364
+ msg_bwd = np.zeros(m, dtype=np.float64)
365
+
366
+ # Build neighbour index: node -> list of (edge_idx, direction)
367
+ # direction=0: node is 'u' end, incoming = msg_bwd[k]
368
+ # direction=1: node is 'v' end, incoming = msg_fwd[k]
369
+ node_edges = [[] for _ in range(n)]
370
+ for k in range(m):
371
+ node_edges[us[k]].append((k, 0))
372
+ node_edges[vs[k]].append((k, 1))
373
+
374
+ for _ in range(max_iterations):
375
+ new_fwd = np.empty(m, dtype=np.float64)
376
+ new_bwd = np.empty(m, dtype=np.float64)
377
+
378
+ for k in range(m):
379
+ u = us[k]
380
+ v = vs[k]
381
+ w = ws[k]
382
+
383
+ # Message u -> v: aggregate incoming to u excluding v
384
+ h_u = 0.0
385
+ for (ek, direction) in node_edges[u]:
386
+ if ek == k:
387
+ continue
388
+ h_u += msg_bwd[ek] if direction == 0 else msg_fwd[ek]
389
+
390
+ tanh_w = np.tanh(w)
391
+ product = tanh_w * np.tanh(h_u)
392
+ product = np.clip(product, -1.0 + 1e-9, 1.0 - 1e-9)
393
+ new_fwd[k] = damping * msg_fwd[k] + (1.0 - damping) * np.arctanh(product)
394
+
395
+ # Message v -> u: aggregate incoming to v excluding u
396
+ h_v = 0.0
397
+ for (ek, direction) in node_edges[v]:
398
+ if ek == k:
399
+ continue
400
+ h_v += msg_bwd[ek] if direction == 0 else msg_fwd[ek]
401
+
402
+ product_v = tanh_w * np.tanh(h_v)
403
+ product_v = np.clip(product_v, -1.0 + 1e-9, 1.0 - 1e-9)
404
+ new_bwd[k] = damping * msg_bwd[k] + (1.0 - damping) * np.arctanh(product_v)
405
+
406
+ msg_fwd = new_fwd
407
+ msg_bwd = new_bwd
408
+
409
+ # Marginals: sum all incoming messages per node
410
+ marginals = np.zeros(n, dtype=np.float64)
411
+ for k in range(m):
412
+ marginals[us[k]] += msg_bwd[k]
413
+ marginals[vs[k]] += msg_fwd[k]
414
+
415
+ return np.tanh(marginals)
416
+
417
+
418
+ def bp_warm_start_dense(G_m, n, bp_scale=1.0, damping=0.5):
419
+ """Partition bitstring from BP marginals over the dense adjacency matrix."""
420
+ marginals = belief_propagation_marginals_dense(G_m, n, bp_scale, damping)
421
+ return marginals > 0.0
422
+
423
+
310
424
  def spin_glass_solver(
311
425
  G,
312
426
  quality=None,
@@ -320,7 +434,23 @@ def spin_glass_solver(
320
434
  is_log=False,
321
435
  gray_iterations=None,
322
436
  gray_seed_multiple=None,
437
+ bp_scale=None,
438
+ bp_damping=0.5,
323
439
  ):
440
+ """
441
+ Dense spin glass / MaxCut solver with optional belief propagation warm-start.
442
+
443
+ Parameters
444
+ ----------
445
+ bp_scale : float or None
446
+ Controls BP iteration count as int(bp_scale * n_qubits).
447
+ Default None disables BP. Set to 1.0 to enable with O(n*m) cost
448
+ (<=O(n^3) for any graph density). Increase for more BP iterations
449
+ at proportionally higher cost.
450
+ bp_damping : float
451
+ Message damping in [0, 1). Default 0.5. Higher values help
452
+ convergence on dense or heavily frustrated graphs.
453
+ """
324
454
  dtype = opencl_context.dtype
325
455
  nodes = None
326
456
  n_qubits = 0
@@ -360,17 +490,49 @@ def spin_glass_solver(
360
490
  elif isinstance(best_guess, list):
361
491
  bitstring = "".join(["1" if b else "0" for b in best_guess])
362
492
  else:
363
- bitstring, cut_value, _ = maxcut_tfim(
364
- G_m,
365
- quality=quality,
366
- shots=shots,
367
- is_spin_glass=is_spin_glass,
368
- anneal_t=anneal_t,
369
- anneal_h=anneal_h,
370
- repulsion_base=repulsion_base,
371
- is_maxcut_gpu=is_maxcut_gpu,
372
- is_nested=True,
373
- )
493
+ # BP warm-start: run before the sampling heuristic if bp_scale is set,
494
+ # so that the cascade local search begins from a sign-aware partition
495
+ # rather than the TFIM prior alone.
496
+ if bp_scale is not None and n_qubits >= heuristic_threshold:
497
+ bp_theta = bp_warm_start_dense(G_m, n_qubits, bp_scale, bp_damping)
498
+ bitstring, cut_value, _ = maxcut_tfim(
499
+ G_m,
500
+ quality=quality,
501
+ shots=shots,
502
+ is_spin_glass=is_spin_glass,
503
+ anneal_t=anneal_t,
504
+ anneal_h=anneal_h,
505
+ repulsion_base=repulsion_base,
506
+ is_maxcut_gpu=is_maxcut_gpu,
507
+ is_nested=True,
508
+ )
509
+ # Keep whichever of BP or sampling gave the better cut
510
+ bp_energy = (
511
+ compute_energy(bp_theta, G_m, n_qubits)
512
+ if is_spin_glass
513
+ else compute_cut(bp_theta, G_m, n_qubits)
514
+ )
515
+ sample_theta = np.array([b == "1" for b in list(bitstring)], dtype=np.bool_)
516
+ sample_energy = (
517
+ compute_energy(sample_theta, G_m, n_qubits)
518
+ if is_spin_glass
519
+ else compute_cut(sample_theta, G_m, n_qubits)
520
+ )
521
+ if bp_energy > sample_energy:
522
+ bitstring = "".join(["1" if b else "0" for b in bp_theta])
523
+ cut_value = bp_energy if not is_spin_glass else None
524
+ else:
525
+ bitstring, cut_value, _ = maxcut_tfim(
526
+ G_m,
527
+ quality=quality,
528
+ shots=shots,
529
+ is_spin_glass=is_spin_glass,
530
+ anneal_t=anneal_t,
531
+ anneal_h=anneal_h,
532
+ repulsion_base=repulsion_base,
533
+ is_maxcut_gpu=is_maxcut_gpu,
534
+ is_nested=True,
535
+ )
374
536
 
375
537
  best_theta = np.array([b == "1" for b in list(bitstring)], dtype=np.bool_)
376
538
  if is_spin_glass:
@@ -374,6 +374,146 @@ def run_gray_search_opencl(
374
374
  return energy, theta
375
375
 
376
376
 
377
+ # Belief propagation was added by (Anthropic) Claude
378
+ def belief_propagation_marginals(G_data, G_rows, G_cols, n, bp_scale=1.0, damping=0.5):
379
+ """
380
+ Run loopy belief propagation on the signed graph to produce per-node
381
+ marginals suitable for biasing the initial partition assignment.
382
+
383
+ Messages are defined on directed edges (i->j) in the MaxCut factor graph.
384
+ Since the CSR matrix is upper-triangular, we iterate over stored edges and
385
+ maintain both directions explicitly.
386
+
387
+ Parameters
388
+ ----------
389
+ G_data : ndarray
390
+ Edge weights from upper-triangular CSR.
391
+ G_rows : ndarray
392
+ CSR row pointers.
393
+ G_cols : ndarray
394
+ CSR column indices.
395
+ n : int
396
+ Number of nodes.
397
+ bp_scale : float
398
+ Iteration cap = int(bp_scale * n). Default 1.0 keeps total work
399
+ O(n * m), which is <= O(n^3) for any graph density. User-controlled.
400
+ damping : float
401
+ Message damping factor in [0, 1). Higher values slow convergence
402
+ but stabilise oscillating marginals on dense frustrated graphs.
403
+
404
+ Returns
405
+ -------
406
+ marginals : ndarray, shape (n,)
407
+ Soft assignment in (-1, +1). Positive values favour partition 1,
408
+ negative values favour partition 0.
409
+ """
410
+ max_iterations = max(1, int(bp_scale * n))
411
+
412
+ # Messages: msg[i, j] = current message from i to j.
413
+ # We store all directed edges as two dicts indexed by (src, dst).
414
+ # For memory efficiency on sparse graphs we use flat arrays parallel
415
+ # to the CSR structure, holding both directions.
416
+
417
+ # Number of undirected edges
418
+ m = G_data.shape[0]
419
+
420
+ # For each undirected edge k: (u, v) with u < v (upper triangular)
421
+ # we store two directed messages: fwd[k] = msg u->v, bwd[k] = msg v->u
422
+ msg_fwd = np.zeros(m, dtype=np.float64) # u -> v
423
+ msg_bwd = np.zeros(m, dtype=np.float64) # v -> u
424
+
425
+ # Build a reverse index: for each node, list of (edge_idx, direction)
426
+ # direction=0 means node is the 'u' end (row), direction=1 means 'v' end (col)
427
+ node_edges = [[] for _ in range(n)]
428
+ edge_u = np.empty(m, dtype=np.int32)
429
+ edge_v = np.empty(m, dtype=np.int32)
430
+
431
+ k = 0
432
+ for u in range(n):
433
+ for ptr in range(G_rows[u], G_rows[u + 1]):
434
+ v = G_cols[ptr]
435
+ edge_u[k] = u
436
+ edge_v[k] = v
437
+ node_edges[u].append((k, 0)) # u is src of fwd message
438
+ node_edges[v].append((k, 1)) # v is src of bwd message
439
+ k += 1
440
+
441
+ for _ in range(max_iterations):
442
+ new_fwd = np.empty(m, dtype=np.float64)
443
+ new_bwd = np.empty(m, dtype=np.float64)
444
+
445
+ for k in range(m):
446
+ u = edge_u[k]
447
+ v = edge_v[k]
448
+ w = G_data[k]
449
+
450
+ # Message u -> v: sum of incoming messages to u from all
451
+ # neighbours except v, passed through the edge factor.
452
+ # For MaxCut, the factor encourages u and v to differ;
453
+ # for negative edges it encourages them to agree.
454
+ # The update rule: new_msg(u->v) = atanh(tanh(w) * tanh(sum_excl))
455
+ # where sum_excl is the sum of all incoming messages to u except
456
+ # the one from v.
457
+ h_u = 0.0
458
+ for (ek, direction) in node_edges[u]:
459
+ if ek == k:
460
+ continue # exclude the v->u message
461
+ if direction == 0:
462
+ # u is the fwd src on edge ek, so incoming to u is bwd[ek]
463
+ h_u += msg_bwd[ek]
464
+ else:
465
+ # u is the bwd src on edge ek, so incoming to u is fwd[ek]
466
+ h_u += msg_fwd[ek]
467
+
468
+ tanh_w = np.tanh(w)
469
+ tanh_h = np.tanh(h_u)
470
+ product = tanh_w * tanh_h
471
+ # Clamp to avoid atanh singularity
472
+ product = np.clip(product, -1.0 + 1e-9, 1.0 - 1e-9)
473
+ raw_fwd = np.arctanh(product)
474
+ new_fwd[k] = damping * msg_fwd[k] + (1.0 - damping) * raw_fwd
475
+
476
+ # Message v -> u (symmetric, swap roles)
477
+ h_v = 0.0
478
+ for (ek, direction) in node_edges[v]:
479
+ if ek == k:
480
+ continue # exclude the u->v message
481
+ if direction == 0:
482
+ h_v += msg_bwd[ek]
483
+ else:
484
+ h_v += msg_fwd[ek]
485
+
486
+ tanh_h_v = np.tanh(h_v)
487
+ product_v = tanh_w * tanh_h_v
488
+ product_v = np.clip(product_v, -1.0 + 1e-9, 1.0 - 1e-9)
489
+ raw_bwd = np.arctanh(product_v)
490
+ new_bwd[k] = damping * msg_bwd[k] + (1.0 - damping) * raw_bwd
491
+
492
+ msg_fwd = new_fwd
493
+ msg_bwd = new_bwd
494
+
495
+ # Compute marginals: for each node, sum all incoming messages
496
+ marginals = np.zeros(n, dtype=np.float64)
497
+ for k in range(m):
498
+ u = edge_u[k]
499
+ v = edge_v[k]
500
+ marginals[u] += msg_bwd[k] # incoming to u from v
501
+ marginals[v] += msg_fwd[k] # incoming to v from u
502
+
503
+ return np.tanh(marginals)
504
+
505
+
506
+ def bp_warm_start(G_data, G_rows, G_cols, n, bp_scale=1.0, damping=0.5):
507
+ """
508
+ Produce an initial partition bitstring from BP marginals.
509
+ Nodes with positive marginal go to partition 1, negative to partition 0.
510
+ Falls back to all-zeros (trivial) if BP produces a degenerate result.
511
+ """
512
+ marginals = belief_propagation_marginals(G_data, G_rows, G_cols, n, bp_scale, damping)
513
+ theta = marginals > 0.0
514
+ return theta
515
+
516
+
377
517
  def spin_glass_solver_sparse(
378
518
  G,
379
519
  quality=None,
@@ -387,7 +527,23 @@ def spin_glass_solver_sparse(
387
527
  is_log=False,
388
528
  gray_iterations=None,
389
529
  gray_seed_multiple=None,
530
+ bp_scale=None,
531
+ bp_damping=0.5,
390
532
  ):
533
+ """
534
+ Spin glass / MaxCut solver with optional belief propagation warm-start.
535
+
536
+ Parameters
537
+ ----------
538
+ bp_scale : float or None
539
+ Controls BP iteration count as int(bp_scale * n_qubits).
540
+ Default None disables BP. Set to 1.0 to enable with O(n*m) cost
541
+ (<=O(n^3) for any graph density). Increase for more BP iterations
542
+ at proportionally higher cost.
543
+ bp_damping : float
544
+ Message damping in [0, 1). Default 0.5. Higher values help
545
+ convergence on dense or heavily frustrated graphs.
546
+ """
391
547
  dtype = opencl_context.dtype
392
548
  nodes = None
393
549
  n_qubits = 0
@@ -427,17 +583,54 @@ def spin_glass_solver_sparse(
427
583
  elif isinstance(best_guess, list):
428
584
  bitstring = "".join(["1" if b else "0" for b in best_guess])
429
585
  else:
430
- bitstring, cut_value, _ = maxcut_tfim_sparse(
431
- G_m,
432
- quality=quality,
433
- shots=shots,
434
- is_spin_glass=is_spin_glass,
435
- anneal_t=anneal_t,
436
- anneal_h=anneal_h,
437
- repulsion_base=repulsion_base,
438
- is_maxcut_gpu=is_maxcut_gpu,
439
- is_nested=True,
440
- )
586
+ # BP warm-start: run before the sampling heuristic if bp_scale is set,
587
+ # so that the cascade local search begins from a sign-aware partition
588
+ # rather than the TFIM prior alone.
589
+ if bp_scale is not None and n_qubits >= heuristic_threshold_sparse:
590
+ bp_theta = bp_warm_start(
591
+ G_m.data, G_m.indptr, G_m.indices, n_qubits, bp_scale, bp_damping
592
+ )
593
+ bp_bitstring = "".join(["1" if b else "0" for b in bp_theta])
594
+ # Pass BP result as best_guess into maxcut_tfim_sparse so the
595
+ # sampling heuristic can compete against it or build on it.
596
+ bitstring, cut_value, _ = maxcut_tfim_sparse(
597
+ G_m,
598
+ quality=quality,
599
+ shots=shots,
600
+ is_spin_glass=is_spin_glass,
601
+ anneal_t=anneal_t,
602
+ anneal_h=anneal_h,
603
+ repulsion_base=repulsion_base,
604
+ is_maxcut_gpu=is_maxcut_gpu,
605
+ is_nested=True,
606
+ )
607
+ # Keep whichever of BP or sampling gave the better cut
608
+ bp_energy = (
609
+ compute_energy_sparse(bp_theta, G_m.data, G_m.indptr, G_m.indices, n_qubits)
610
+ if is_spin_glass
611
+ else compute_cut_sparse(bp_theta, G_m.data, G_m.indptr, G_m.indices, n_qubits)
612
+ )
613
+ sample_theta = np.array([b == "1" for b in list(bitstring)], dtype=np.bool_)
614
+ sample_energy = (
615
+ compute_energy_sparse(sample_theta, G_m.data, G_m.indptr, G_m.indices, n_qubits)
616
+ if is_spin_glass
617
+ else compute_cut_sparse(sample_theta, G_m.data, G_m.indptr, G_m.indices, n_qubits)
618
+ )
619
+ if bp_energy > sample_energy:
620
+ bitstring = bp_bitstring
621
+ cut_value = bp_energy if not is_spin_glass else None
622
+ else:
623
+ bitstring, cut_value, _ = maxcut_tfim_sparse(
624
+ G_m,
625
+ quality=quality,
626
+ shots=shots,
627
+ is_spin_glass=is_spin_glass,
628
+ anneal_t=anneal_t,
629
+ anneal_h=anneal_h,
630
+ repulsion_base=repulsion_base,
631
+ is_maxcut_gpu=is_maxcut_gpu,
632
+ is_nested=True,
633
+ )
441
634
 
442
635
  best_theta = np.array([b == "1" for b in list(bitstring)], dtype=np.bool_)
443
636
  if is_spin_glass:
@@ -144,6 +144,122 @@ def run_gray_optimization(best_theta, iterators, gray_iterations, thread_count,
144
144
  return best_energy, best_state
145
145
 
146
146
 
147
+ # Belief propagation was added by (Anthropic) Claude
148
+ def belief_propagation_marginals_streaming(G_func, nodes, n, bp_scale=1.0, damping=0.5):
149
+ """
150
+ Run loopy belief propagation using the streaming edge accessor to produce
151
+ per-node marginals for warm-starting the partition.
152
+
153
+ Since the streaming solver has no pre-built adjacency structure, we make
154
+ one O(n^2) pass over node pairs to discover non-zero edges before running
155
+ BP iterations. This matches the streaming solver's own access pattern and
156
+ keeps total cost O(n * m) iterations on top of the O(n^2) discovery pass,
157
+ remaining <= O(n^3) overall.
158
+
159
+ Parameters
160
+ ----------
161
+ G_func : callable
162
+ Edge weight accessor: G_func(u, v) -> float. Returns 0.0 for absent edges.
163
+ nodes : sequence
164
+ Node identifiers corresponding to qubit indices.
165
+ n : int
166
+ Number of nodes.
167
+ bp_scale : float
168
+ Iteration cap = int(bp_scale * n). User-controlled; default 1.0
169
+ keeps total work <= O(n^3).
170
+ damping : float
171
+ Message damping factor in [0, 1).
172
+
173
+ Returns
174
+ -------
175
+ marginals : ndarray, shape (n,)
176
+ Soft assignment in (-1, +1).
177
+ """
178
+ max_iterations = max(1, int(bp_scale * n))
179
+
180
+ # Discover edges via one O(n^2) pass — unavoidable for the streaming case
181
+ us = []
182
+ vs = []
183
+ ws = []
184
+ for i in range(n):
185
+ for j in range(i + 1, n):
186
+ w = G_func(nodes[i], nodes[j])
187
+ if abs(w) > 1e-12:
188
+ us.append(i)
189
+ vs.append(j)
190
+ ws.append(w)
191
+
192
+ m = len(us)
193
+ if m == 0:
194
+ return np.zeros(n, dtype=np.float64)
195
+
196
+ us = np.array(us, dtype=np.int32)
197
+ vs = np.array(vs, dtype=np.int32)
198
+ ws = np.array(ws, dtype=np.float64)
199
+
200
+ # msg_fwd[k] = message from us[k] -> vs[k]
201
+ # msg_bwd[k] = message from vs[k] -> us[k]
202
+ msg_fwd = np.zeros(m, dtype=np.float64)
203
+ msg_bwd = np.zeros(m, dtype=np.float64)
204
+
205
+ # Build neighbour index: node -> list of (edge_idx, direction)
206
+ # direction=0: node is 'u' end, incoming = msg_bwd[k]
207
+ # direction=1: node is 'v' end, incoming = msg_fwd[k]
208
+ node_edges = [[] for _ in range(n)]
209
+ for k in range(m):
210
+ node_edges[us[k]].append((k, 0))
211
+ node_edges[vs[k]].append((k, 1))
212
+
213
+ for _ in range(max_iterations):
214
+ new_fwd = np.empty(m, dtype=np.float64)
215
+ new_bwd = np.empty(m, dtype=np.float64)
216
+
217
+ for k in range(m):
218
+ u = us[k]
219
+ v = vs[k]
220
+ w = ws[k]
221
+
222
+ # Message u -> v: aggregate incoming to u excluding v
223
+ h_u = 0.0
224
+ for (ek, direction) in node_edges[u]:
225
+ if ek == k:
226
+ continue
227
+ h_u += msg_bwd[ek] if direction == 0 else msg_fwd[ek]
228
+
229
+ tanh_w = np.tanh(w)
230
+ product = tanh_w * np.tanh(h_u)
231
+ product = np.clip(product, -1.0 + 1e-9, 1.0 - 1e-9)
232
+ new_fwd[k] = damping * msg_fwd[k] + (1.0 - damping) * np.arctanh(product)
233
+
234
+ # Message v -> u: aggregate incoming to v excluding u
235
+ h_v = 0.0
236
+ for (ek, direction) in node_edges[v]:
237
+ if ek == k:
238
+ continue
239
+ h_v += msg_bwd[ek] if direction == 0 else msg_fwd[ek]
240
+
241
+ product_v = tanh_w * np.tanh(h_v)
242
+ product_v = np.clip(product_v, -1.0 + 1e-9, 1.0 - 1e-9)
243
+ new_bwd[k] = damping * msg_bwd[k] + (1.0 - damping) * np.arctanh(product_v)
244
+
245
+ msg_fwd = new_fwd
246
+ msg_bwd = new_bwd
247
+
248
+ # Marginals: sum all incoming messages per node
249
+ marginals = np.zeros(n, dtype=np.float64)
250
+ for k in range(m):
251
+ marginals[us[k]] += msg_bwd[k]
252
+ marginals[vs[k]] += msg_fwd[k]
253
+
254
+ return np.tanh(marginals)
255
+
256
+
257
+ def bp_warm_start_streaming(G_func, nodes, n, bp_scale=1.0, damping=0.5):
258
+ """Partition bitstring from BP marginals over the streaming graph."""
259
+ marginals = belief_propagation_marginals_streaming(G_func, nodes, n, bp_scale, damping)
260
+ return marginals > 0.0
261
+
262
+
147
263
  def spin_glass_solver_streaming(
148
264
  G_func,
149
265
  nodes,
@@ -158,7 +274,23 @@ def spin_glass_solver_streaming(
158
274
  is_log=False,
159
275
  gray_iterations=None,
160
276
  gray_seed_multiple=None,
277
+ bp_scale=None,
278
+ bp_damping=0.5,
161
279
  ):
280
+ """
281
+ Streaming spin glass / MaxCut solver with optional belief propagation warm-start.
282
+
283
+ Parameters
284
+ ----------
285
+ bp_scale : float or None
286
+ Controls BP iteration count as int(bp_scale * n_qubits).
287
+ Default None disables BP. Set to 1.0 to enable with O(n*m) cost
288
+ (<=O(n^3) for any graph density). Note: the streaming solver incurs
289
+ an additional O(n^2) edge-discovery pass when BP is enabled, since
290
+ no adjacency structure is pre-built.
291
+ bp_damping : float
292
+ Message damping in [0, 1). Default 0.5.
293
+ """
162
294
  dtype = opencl_context.dtype
163
295
  n_qubits = len(nodes)
164
296
 
@@ -188,16 +320,47 @@ def spin_glass_solver_streaming(
188
320
  elif isinstance(best_guess, list):
189
321
  bitstring = "".join(["1" if b else "0" for b in best_guess])
190
322
  else:
191
- bitstring, cut_value, _ = maxcut_tfim_streaming(
192
- G_func,
193
- nodes,
194
- quality=quality,
195
- shots=shots,
196
- is_spin_glass=is_spin_glass,
197
- anneal_t=anneal_t,
198
- anneal_h=anneal_h,
199
- repulsion_base=repulsion_base,
200
- )
323
+ # BP warm-start: run before the sampling heuristic if bp_scale is set,
324
+ # so that the cascade local search begins from a sign-aware partition
325
+ # rather than the TFIM prior alone.
326
+ if bp_scale is not None and n_qubits >= heuristic_threshold:
327
+ bp_theta = bp_warm_start_streaming(G_func, nodes, n_qubits, bp_scale, bp_damping)
328
+ bitstring, cut_value, _ = maxcut_tfim_streaming(
329
+ G_func,
330
+ nodes,
331
+ quality=quality,
332
+ shots=shots,
333
+ is_spin_glass=is_spin_glass,
334
+ anneal_t=anneal_t,
335
+ anneal_h=anneal_h,
336
+ repulsion_base=repulsion_base,
337
+ )
338
+ # Keep whichever of BP or sampling gave the better cut
339
+ bp_energy = (
340
+ compute_energy_streaming(bp_theta, G_func, nodes, n_qubits)
341
+ if is_spin_glass
342
+ else compute_cut_streaming(bp_theta, G_func, nodes, n_qubits)
343
+ )
344
+ sample_theta = np.array([b == "1" for b in list(bitstring)], dtype=np.bool_)
345
+ sample_energy = (
346
+ compute_energy_streaming(sample_theta, G_func, nodes, n_qubits)
347
+ if is_spin_glass
348
+ else compute_cut_streaming(sample_theta, G_func, nodes, n_qubits)
349
+ )
350
+ if bp_energy > sample_energy:
351
+ bitstring = "".join(["1" if b else "0" for b in bp_theta])
352
+ cut_value = bp_energy if not is_spin_glass else None
353
+ else:
354
+ bitstring, cut_value, _ = maxcut_tfim_streaming(
355
+ G_func,
356
+ nodes,
357
+ quality=quality,
358
+ shots=shots,
359
+ is_spin_glass=is_spin_glass,
360
+ anneal_t=anneal_t,
361
+ anneal_h=anneal_h,
362
+ repulsion_base=repulsion_base,
363
+ )
201
364
 
202
365
  best_theta = np.array([b == "1" for b in list(bitstring)], dtype=np.bool_)
203
366
  if is_spin_glass:
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: pyqrackising
3
- Version: 9.13.0
3
+ Version: 9.14.0
4
4
  Summary: Fast MAXCUT, TSP, and sampling heuristics from near-ideal transverse field Ising model (TFIM)
5
5
  Home-page: https://github.com/vm6502q/PyQrackIsing
6
6
  Author: Dan Strano
@@ -7,7 +7,7 @@ with open(README_PATH) as readme_file:
7
7
 
8
8
  setup(
9
9
  name="pyqrackising",
10
- version="9.13.0",
10
+ version="9.14.0",
11
11
  author="Dan Strano",
12
12
  author_email="stranoj@gmail.com",
13
13
  description="Fast MAXCUT, TSP, and sampling heuristics from near-ideal transverse field Ising model (TFIM)",
File without changes
File without changes
File without changes