@@ -1333,25 +1333,47 @@ def PauliStringSum2COO(
1333
1333
# numpy version is 3* faster!
1334
1334
1335
1335
nterms = len (ls )
1336
- n = len (ls [0 ])
1337
- s = 0b1 << n
1336
+ # n = len(ls[0])
1337
+ # s = 0b1 << n
1338
1338
if weight is None :
1339
1339
weight = [1.0 for _ in range (nterms )]
1340
1340
if not (isinstance (weight , tf .Tensor ) or isinstance (weight , tf .Variable )):
1341
1341
weight = tf .constant (weight , dtype = getattr (tf , dtypestr ))
1342
- rsparse = get_backend ("numpy" ).coo_sparse_matrix (
1343
- indices = np .array ([[0 , 0 ]], dtype = np .int64 ),
1344
- values = np .array ([0.0 ], dtype = getattr (np , dtypestr )),
1345
- shape = (s , s ),
1346
- )
1347
- for i in range (nterms ):
1348
- rsparse += get_backend ("tensorflow" ).numpy (PauliString2COO (ls [i ], weight [i ])) # type: ignore
1349
- # auto transformed into csr format!!
1342
+ # rsparse = get_backend("numpy").coo_sparse_matrix(
1343
+ # indices=np.array([[0, 0]], dtype=np.int64),
1344
+ # values=np.array([0.0], dtype=getattr(np, dtypestr)),
1345
+ # shape=(s, s),
1346
+ # )
1347
+ rsparses = [
1348
+ get_backend ("tensorflow" ).numpy (PauliString2COO (ls [i ], weight [i ])) # type: ignore
1349
+ for i in range (nterms )
1350
+ ]
1351
+ rsparse = _dc_sum (rsparses )
1352
+ # auto transformed into csr format!!
1353
+
1354
+ # for i in range(nterms):
1355
+ # rsparse += get_backend("tensorflow").numpy(PauliString2COO(ls[i], weight[i])) # type: ignore
1350
1356
rsparse = rsparse .tocoo ()
1351
1357
if numpy :
1352
1358
return rsparse
1353
1359
return backend .coo_sparse_matrix_from_numpy (rsparse )
1354
1360
1361
+ def _dc_sum (l : List [Any ]) -> Any :
1362
+ """
1363
+ For the sparse sum, the speed is determined by the non zero terms,
1364
+ so the DC way to do the sum can indeed bring some speed advantage (several times)
1365
+
1366
+ :param l: _description_
1367
+ :type l: List[Any]
1368
+ :return: _description_
1369
+ :rtype: Any
1370
+ """
1371
+ n = len (l )
1372
+ if n > 2 :
1373
+ return _dc_sum (l [: n // 2 ]) + _dc_sum (l [n // 2 :])
1374
+ else :
1375
+ return sum (l )
1376
+
1355
1377
PauliStringSum2COO_numpy = partial (PauliStringSum2COO , numpy = True )
1356
1378
1357
1379
def PauliStringSum2COO_tf (
0 commit comments