tensorcircuit-nightly 1.3.0.dev20250729__py3-none-any.whl → 1.3.0.dev20250731__py3-none-any.whl

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.

Potentially problematic release.


This version of tensorcircuit-nightly might be problematic. Click here for more details.

tensorcircuit/__init__.py CHANGED
@@ -1,4 +1,4 @@
1
- __version__ = "1.3.0.dev20250729"
1
+ __version__ = "1.3.0.dev20250731"
2
2
  __author__ = "TensorCircuit Authors"
3
3
  __creator__ = "refraction-ray"
4
4
 
@@ -808,6 +808,21 @@ class ExtendedBackend:
808
808
  "Backend '{}' has not implemented `solve`.".format(self.name)
809
809
  )
810
810
 
811
+ def special_jv(self: Any, v: int, z: Tensor, M: int) -> Tensor:
812
+ """
813
+ Special function: Bessel function of the first kind.
814
+
815
+ :param v: The order of the Bessel function.
816
+ :type v: int
817
+ :param z: The argument of the Bessel function.
818
+ :type z: Tensor
819
+ :return: The value of the Bessel function [J_0, ...J_{v-1}(z)].
820
+ :rtype: Tensor
821
+ """
822
+ raise NotImplementedError(
823
+ "Backend '{}' has not implemented `special_jv`.".format(self.name)
824
+ )
825
+
811
826
  def searchsorted(self: Any, a: Tensor, v: Tensor, side: str = "left") -> Tensor:
812
827
  """
813
828
  Find indices where elements should be inserted to maintain order.
@@ -1251,6 +1266,26 @@ class ExtendedBackend:
1251
1266
  "Backend '{}' has not implemented `sparse_dense_matmul`.".format(self.name)
1252
1267
  )
1253
1268
 
1269
+ def sparse_csr_from_coo(self: Any, coo: Tensor, strict: bool = False) -> Tensor:
1270
+ """
1271
+ transform a coo matrix to a csr matrix
1272
+
1273
+ :param coo: a coo matrix
1274
+ :type coo: Tensor
1275
+ :param strict: whether to enforce the transform, defaults to False,
1276
+ corresponding to return the coo matrix if there is no implementation for specific backend.
1277
+ :type strict: bool, optional
1278
+ :return: a csr matrix
1279
+ :rtype: Tensor
1280
+ """
1281
+ if strict:
1282
+ raise NotImplementedError(
1283
+ "Backend '{}' has not implemented `sparse_csr_from_coo`.".format(
1284
+ self.name
1285
+ )
1286
+ )
1287
+ return coo
1288
+
1254
1289
  def to_dense(self: Any, sp_a: Tensor) -> Tensor:
1255
1290
  """
1256
1291
  Convert a sparse matrix to dense tensor.
@@ -1389,10 +1424,49 @@ class ExtendedBackend:
1389
1424
  :rtype: Tensor
1390
1425
  """
1391
1426
  carry = init
1392
- for x in xs:
1393
- carry = f(carry, x)
1427
+ # Check if `xs` is a PyTree (tuple or list) of arrays.
1428
+ if isinstance(xs, (tuple, list)):
1429
+ for x_slice_tuple in zip(*xs):
1430
+ # x_slice_tuple will be (k_elems[i], j_elems[i]) at each step.
1431
+ carry = f(carry, x_slice_tuple)
1432
+ else:
1433
+ # If xs is a single array, iterate normally.
1434
+ for x in xs:
1435
+ carry = f(carry, x)
1436
+
1394
1437
  return carry
1395
1438
 
1439
+ def jaxy_scan(
1440
+ self: Any, f: Callable[[Tensor, Tensor], Tensor], init: Tensor, xs: Tensor
1441
+ ) -> Tensor:
1442
+ """
1443
+ This API follows jax scan style. TF use plain for loop
1444
+
1445
+ :param f: _description_
1446
+ :type f: Callable[[Tensor, Tensor], Tensor]
1447
+ :param init: _description_
1448
+ :type init: Tensor
1449
+ :param xs: _description_
1450
+ :type xs: Tensor
1451
+ :raises ValueError: _description_
1452
+ :return: _description_
1453
+ :rtype: Tensor
1454
+ """
1455
+ if xs is None:
1456
+ raise ValueError("Either xs or length must be provided.")
1457
+ if xs is not None:
1458
+ length = len(xs)
1459
+ carry, outputs_to_stack = init, []
1460
+ for i in range(length):
1461
+ if isinstance(xs, (tuple, list)):
1462
+ x = [ele[i] for ele in xs]
1463
+ else:
1464
+ x = xs[i]
1465
+ new_carry, y = f(carry, x)
1466
+ carry = new_carry
1467
+ outputs_to_stack.append(y)
1468
+ return carry, self.stack(outputs_to_stack)
1469
+
1396
1470
  def stop_gradient(self: Any, a: Tensor) -> Tensor:
1397
1471
  """
1398
1472
  Stop backpropagation from ``a``.
@@ -418,6 +418,11 @@ class JaxBackend(jax_backend.JaxBackend, ExtendedBackend): # type: ignore
418
418
  def solve(self, A: Tensor, b: Tensor, assume_a: str = "gen") -> Tensor: # type: ignore
419
419
  return jsp.linalg.solve(A, b, assume_a=assume_a)
420
420
 
421
+ def special_jv(self, v: int, z: Tensor, M: int) -> Tensor:
422
+ from .jax_ops import bessel_jv_jax_rescaled
423
+
424
+ return bessel_jv_jax_rescaled(v, z, M)
425
+
421
426
  def searchsorted(self, a: Tensor, v: Tensor, side: str = "left") -> Tensor:
422
427
  if not self.is_tensor(a):
423
428
  a = self.convert_to_tensor(a)
@@ -615,6 +620,11 @@ class JaxBackend(jax_backend.JaxBackend, ExtendedBackend): # type: ignore
615
620
  carry, _ = libjax.lax.scan(f_jax, init, xs)
616
621
  return carry
617
622
 
623
+ def jaxy_scan(
624
+ self, f: Callable[[Tensor, Tensor], Tensor], init: Tensor, xs: Tensor
625
+ ) -> Tensor:
626
+ return libjax.lax.scan(f, init, xs)
627
+
618
628
  def scatter(self, operand: Tensor, indices: Tensor, updates: Tensor) -> Tensor:
619
629
  # updates = jnp.reshape(updates, indices.shape)
620
630
  # return operand.at[indices].set(updates)
@@ -639,11 +649,20 @@ class JaxBackend(jax_backend.JaxBackend, ExtendedBackend): # type: ignore
639
649
  ) -> Tensor:
640
650
  return sp_a @ b
641
651
 
652
+ def sparse_csr_from_coo(self, coo: Tensor, strict: bool = False) -> Tensor:
653
+ try:
654
+ return sparse.BCSR.from_bcoo(coo) # type: ignore
655
+ except AttributeError as e:
656
+ if not strict:
657
+ return coo
658
+ else:
659
+ raise e
660
+
642
661
  def to_dense(self, sp_a: Tensor) -> Tensor:
643
662
  return sp_a.todense()
644
663
 
645
664
  def is_sparse(self, a: Tensor) -> bool:
646
- return isinstance(a, sparse.BCOO) # type: ignore
665
+ return isinstance(a, sparse.JAXSparse) # type: ignore
647
666
 
648
667
  def device(self, a: Tensor) -> str:
649
668
  (dev,) = a.devices()
@@ -3,8 +3,11 @@ Customized ops for ML framework
3
3
  """
4
4
 
5
5
  # pylint: disable=invalid-name
6
+ # pylint: disable=unused-variable
7
+
6
8
 
7
9
  from typing import Any, Tuple, Sequence
10
+ from functools import partial
8
11
 
9
12
  import jax
10
13
  import jax.numpy as jnp
@@ -174,3 +177,108 @@ def jaxeigh_bwd(r: Array, tangents: Array) -> Array:
174
177
 
175
178
  adaware_eigh.defvjp(jaxeigh_fwd, jaxeigh_bwd)
176
179
  adaware_eigh_jit = jax.jit(adaware_eigh)
180
+
181
+
182
+ @partial(jax.jit, static_argnums=[0, 2])
183
+ def bessel_jv_jax_rescaled(k: int, x: jnp.ndarray, M: int) -> jnp.ndarray:
184
+ """
185
+ Computes Bessel function Jv using Miller's algorithm with dynamic rescaling,
186
+ implemented in JAX.
187
+ """
188
+ if M <= k:
189
+ raise ValueError(
190
+ f"Recurrence length M ({M}) must be greater than the required order k ({k})."
191
+ )
192
+
193
+ # Use vmap to handle array inputs for x efficiently.
194
+ # We map _bessel_jv_scalar_rescaled over the last dimension of x.
195
+ return _bessel_jv_scalar_rescaled(k, M, x)
196
+
197
+
198
+ def _bessel_jv_scalar_rescaled(k: int, M: int, x_val: jnp.ndarray) -> jnp.ndarray:
199
+ """
200
+ JAX implementation for a scalar input x_val.
201
+ This function will be vmapped for array inputs.
202
+ """
203
+ rescale_threshold = 1e250
204
+
205
+ # Define the body of the recurrence loop
206
+ def recurrence_body(i, state): # type: ignore
207
+ # M - i is the current 'm' value in the original loop.
208
+ # Loop from M down to 1. jax.lax.fori_loop goes from lower to upper-1.
209
+ # So for m from M down to 1, we map i from 0 to M-1.
210
+ # Current m_val = M - i
211
+ # The loop range for m in numpy was `range(M, 0, -1)`, which means m goes from M, M-1, ..., 1.
212
+ # For lax.fori_loop (start, stop, body_fn, init_val), start is inclusive, stop is exclusive.
213
+ # So to iterate M times for m from M down to 1, we do i from 0 to M-1.
214
+ # m_val = M - i means that for i=0, m_val=M; for i=M-1, m_val=1.
215
+ m_val = M - i
216
+ f_m, f_m_p1, f_vals = state
217
+
218
+ # If x_val is near zero, this division could be an issue,
219
+ # but the outer lax.cond handles the x_val near zero case before this loop runs.
220
+ f_m_m1 = (2.0 * m_val / x_val) * f_m - f_m_p1
221
+
222
+ # --- Rescaling Step ---
223
+ # jax.lax.cond requires all branches to return the exact same type and shape.
224
+ def rescale_branch(vals): # type: ignore
225
+ f_m_val, f_m_p1_val, f_vals_arr = vals
226
+ scale_factor = f_m_m1
227
+ # Return new f_m, f_m_p1, updated f_vals_arr, and the new f_m_m1 value (which is 1.0)
228
+ return (
229
+ f_m_val / scale_factor,
230
+ f_m_p1_val / scale_factor,
231
+ f_vals_arr / scale_factor,
232
+ 1.0,
233
+ )
234
+
235
+ def no_rescale_branch(vals): # type: ignore
236
+ f_m_val, f_m_p1_val, f_vals_arr = (
237
+ vals # Unpack to keep signatures consistent
238
+ )
239
+ # Return original f_m, f_m_p1, original f_vals_arr, and the computed f_m_m1
240
+ return (f_m_val, f_m_p1_val, f_vals_arr, f_m_m1)
241
+
242
+ f_m_rescaled, f_m_p1_rescaled, f_vals_rescaled, f_m_m1_effective = jax.lax.cond(
243
+ jnp.abs(f_m_m1) > rescale_threshold,
244
+ rescale_branch,
245
+ no_rescale_branch,
246
+ (f_m, f_m_p1, f_vals), # Arguments passed to branches
247
+ )
248
+
249
+ # Update f_vals at index m_val - 1. JAX uses .at[idx].set(val) for non-in-place updates.
250
+ f_vals_updated = f_vals_rescaled.at[m_val - 1].set(f_m_m1_effective)
251
+
252
+ # Return new state for the next iteration: (new f_m, new f_m_p1, updated f_vals)
253
+ return (f_m_m1_effective, f_m_rescaled, f_vals_updated)
254
+
255
+ # Initial state for the recurrence loop
256
+ f_m_p1_init = 0.0
257
+ f_m_init = 1e-30 # Start with a very small number
258
+ f_vals_init = jnp.zeros(M + 1).at[M].set(f_m_init)
259
+
260
+ # Use jax.lax.fori_loop for the backward recurrence
261
+ # Loop from i = 0 to M-1 (total M iterations)
262
+ # The 'body' function gets current 'i' and 'state', returns 'new_state'.
263
+ # We don't need the final f_m_p1, only f_m and f_vals.
264
+ final_f_m, _, f_vals = jax.lax.fori_loop(
265
+ 0, M, recurrence_body, (f_m_init, f_m_p1_init, f_vals_init)
266
+ )
267
+
268
+ # Normalization using Neumann's sum rule
269
+ even_sum = jnp.sum(f_vals[2::2])
270
+ norm_const = f_vals[0] + 2.0 * even_sum
271
+
272
+ # Handle division by near-zero normalization constant
273
+ norm_const_safe = jnp.where(jnp.abs(norm_const) < 1e-12, 1e-12, norm_const)
274
+
275
+ # Conditional logic for x_val close to zero
276
+ def x_is_zero_case() -> jnp.ndarray:
277
+ # For x=0, J_0(0)=1, J_k(0)=0 for k>0
278
+ return jnp.zeros(k).at[0].set(1.0)
279
+
280
+ def x_is_not_zero_case() -> jnp.ndarray:
281
+ return f_vals[:k] / norm_const_safe # type: ignore
282
+
283
+ # Use lax.cond to select between the two cases based on x_val
284
+ return jax.lax.cond(jnp.abs(x_val) < 1e-12, x_is_zero_case, x_is_not_zero_case) # type: ignore
@@ -17,7 +17,7 @@ except ImportError: # np2.0 compatibility
17
17
 
18
18
  import tensornetwork
19
19
  from scipy.linalg import expm, solve, schur
20
- from scipy.special import softmax, expit
20
+ from scipy.special import softmax, expit, jv
21
21
  from scipy.sparse import coo_matrix, issparse
22
22
  from tensornetwork.backends.numpy import numpy_backend
23
23
  from .abstract_backend import ExtendedBackend
@@ -200,6 +200,7 @@ class NumpyBackend(numpy_backend.NumPyBackend, ExtendedBackend): # type: ignore
200
200
  return softmax(a, axis=axis)
201
201
 
202
202
  def onehot(self, a: Tensor, num: int) -> Tensor:
203
+ a = np.asarray(a)
203
204
  res = np.eye(num)[a.reshape([-1])]
204
205
  return res.reshape(list(a.shape) + [num])
205
206
  # https://stackoverflow.com/questions/38592324/one-hot-encoding-using-numpy
@@ -244,6 +245,9 @@ class NumpyBackend(numpy_backend.NumPyBackend, ExtendedBackend): # type: ignore
244
245
  # https://stackoverflow.com/questions/44672029/difference-between-numpy-linalg-solve-and-numpy-linalg-lu-solve/44710451
245
246
  return solve(A, b, assume_a=assume_a)
246
247
 
248
+ def special_jv(self, v: int, z: Tensor, M: int) -> Tensor:
249
+ return jv(np.arange(v), z)
250
+
247
251
  def searchsorted(self, a: Tensor, v: Tensor, side: str = "left") -> Tensor:
248
252
  return np.searchsorted(a, v, side=side) # type: ignore
249
253
 
@@ -329,6 +333,9 @@ class NumpyBackend(numpy_backend.NumPyBackend, ExtendedBackend): # type: ignore
329
333
  ) -> Tensor:
330
334
  return sp_a @ b
331
335
 
336
+ def sparse_csr_from_coo(self, coo: Tensor, strict: bool = False) -> Tensor:
337
+ return coo.tocsr()
338
+
332
339
  def to_dense(self, sp_a: Tensor) -> Tensor:
333
340
  return sp_a.todense()
334
341
 
@@ -360,6 +360,38 @@ tensornetwork.backends.tensorflow.tensorflow_backend.TensorFlowBackend.rq = _rq_
360
360
  tensornetwork.backends.tensorflow.tensorflow_backend.TensorFlowBackend.svd = _svd_tf
361
361
 
362
362
 
363
+ def sparse_tensor_matmul(self: Tensor, other: Tensor) -> Tensor:
364
+ """
365
+ An implementation of matrix multiplication (@) for tf.SparseTensor.
366
+
367
+ This function is designed to be monkey-patched onto the tf.SparseTensor class.
368
+ It handles multiplication with a dense vector (rank-1 Tensor) by temporarily
369
+ promoting it to a matrix (rank-2 Tensor) for the underlying TensorFlow call.
370
+ """
371
+ # Ensure the 'other' tensor is of a compatible dtype
372
+ if not other.dtype.is_compatible_with(self.dtype):
373
+ other = tf.cast(other, self.dtype)
374
+
375
+ # tf.sparse.sparse_dense_matmul requires the dense tensor to be a 2D matrix.
376
+ # If we get a 1D vector, we need to reshape it.
377
+ is_vector = len(other.shape) == 1
378
+
379
+ if is_vector:
380
+ # Promote the vector to a column matrix [N] -> [N, 1]
381
+ other_matrix = tf.expand_dims(other, axis=1)
382
+ else:
383
+ other_matrix = other
384
+
385
+ # Perform the actual multiplication
386
+ result_matrix = tf.sparse.sparse_dense_matmul(self, other_matrix)
387
+
388
+ if is_vector:
389
+ # Demote the result matrix back to a vector [M, 1] -> [M]
390
+ return tf.squeeze(result_matrix, axis=1)
391
+ else:
392
+ return result_matrix
393
+
394
+
363
395
  class TensorFlowBackend(tensorflow_backend.TensorFlowBackend, ExtendedBackend): # type: ignore
364
396
  """
365
397
  See the original backend API at `tensorflow backend
@@ -378,6 +410,8 @@ class TensorFlowBackend(tensorflow_backend.TensorFlowBackend, ExtendedBackend):
378
410
  )
379
411
  tf = tensorflow
380
412
  tf.sparse.SparseTensor.__add__ = tf.sparse.add
413
+ tf.SparseTensor.__matmul__ = sparse_tensor_matmul
414
+
381
415
  self.minor = int(tf.__version__.split(".")[1])
382
416
  self.name = "tensorflow"
383
417
  logger = tf.get_logger() # .setLevel('ERROR')
@@ -719,7 +753,10 @@ class TensorFlowBackend(tensorflow_backend.TensorFlowBackend, ExtendedBackend):
719
753
  def scan(
720
754
  self, f: Callable[[Tensor, Tensor], Tensor], xs: Tensor, init: Tensor
721
755
  ) -> Tensor:
722
- return tf.scan(f, xs, init)[-1]
756
+ stacked_results = tf.scan(f, xs, init)
757
+ final_state = tf.nest.map_structure(lambda x: x[-1], stacked_results)
758
+ return final_state
759
+ # return tf.scan(f, xs, init)[-1]
723
760
 
724
761
  def device(self, a: Tensor) -> str:
725
762
  dev = a.device
tensorcircuit/fgs.py CHANGED
@@ -28,7 +28,6 @@ def onehot_matrix(i: int, j: int, N: int) -> Tensor:
28
28
 
29
29
  # TODO(@refraction-ray): efficiency benchmark with jit
30
30
  # TODO(@refraction-ray): FGS mixed state support?
31
- # TODO(@refraction-ray): overlap?
32
31
  # TODO(@refraction-ray): fermionic logarithmic negativity
33
32
 
34
33
 
@@ -227,7 +226,7 @@ class FGSSimulator:
227
226
  return self.alpha
228
227
 
229
228
  def get_cmatrix(self, now_i: bool = True, now_j: bool = True) -> Tensor:
230
- """
229
+ r"""
231
230
  Calculates the correlation matrix.
232
231
 
233
232
  The correlation matrix is defined as :math:`C_{ij} = \langle c_i^\dagger c_j \rangle`.
@@ -509,7 +508,7 @@ class FGSSimulator:
509
508
 
510
509
  @staticmethod
511
510
  def hopping(chi: Tensor, i: int, j: int, L: int) -> Tensor:
512
- """
511
+ r"""
513
512
  Constructs the hopping Hamiltonian between two sites.
514
513
 
515
514
  The hopping Hamiltonian is given by :math:`\chi c_i^\dagger c_j + h.c.`.
@@ -550,7 +549,7 @@ class FGSSimulator:
550
549
 
551
550
  @staticmethod
552
551
  def chemical_potential(chi: Tensor, i: int, L: int) -> Tensor:
553
- """
552
+ r"""
554
553
  Constructs the chemical potential Hamiltonian for a single site.
555
554
 
556
555
  The chemical potential Hamiltonian is given by :math:`\chi c_i^\dagger c_i`.
@@ -572,7 +571,7 @@ class FGSSimulator:
572
571
 
573
572
  @staticmethod
574
573
  def sc_pairing(chi: Tensor, i: int, j: int, L: int) -> Tensor:
575
- """
574
+ r"""
576
575
  Constructs the superconducting pairing Hamiltonian between two sites.
577
576
 
578
577
  The superconducting pairing Hamiltonian is given by :math:`\chi c_i^\dagger c_j^\dagger + h.c.`.
@@ -637,7 +636,7 @@ class FGSSimulator:
637
636
  self.evol_ihamiltonian(self.chemical_potential(chi, i, self.L))
638
637
 
639
638
  def get_bogoliubov_uv(self) -> Tuple[Tensor, Tensor]:
640
- """
639
+ r"""
641
640
  Returns the u and v matrices of the Bogoliubov transformation.
642
641
 
643
642
  The Bogoliubov transformation is defined as:
tensorcircuit/quantum.py CHANGED
@@ -1433,7 +1433,7 @@ def PauliStringSum2Dense(
1433
1433
  return sparsem.todense()
1434
1434
  sparsem = backend.coo_sparse_matrix_from_numpy(sparsem)
1435
1435
  densem = backend.to_dense(sparsem)
1436
- return densem
1436
+ return backend.convert_to_tensor(densem)
1437
1437
 
1438
1438
 
1439
1439
  # already implemented as backend method
@@ -96,10 +96,12 @@ class StabilizerCircuit(AbstractCircuit):
96
96
 
97
97
  if name.lower() in self.gate_map:
98
98
  # self._stim_circuit.append(gate_map[name.lower()], list(index))
99
- instruction = f"{self.gate_map[name.lower()]} {' '.join(map(str, index))}"
99
+ gn = self.gate_map[name.lower()]
100
+ instruction = f"{gn} {' '.join(map(str, index))}"
100
101
  self._stim_circuit.append_from_stim_program_text(instruction)
101
102
  # append is much slower
102
- self.current_sim.do(stim.Circuit(instruction))
103
+ # self.current_sim.do(stim.Circuit(instruction))
104
+ getattr(self.current_sim, gn.lower())(*index)
103
105
  else:
104
106
  raise ValueError(f"Gate {name} is not supported in stabilizer simulation")
105
107