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
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
import collections
from collections import deque
import datetime
from functools import partial
import importlib
import os
from os import PathLike
import pathlib
import sys
import time

from scipy.optimize import OptimizeResult

from tqdm_loggable.auto import tqdm

import h5py

import numpy as np

import jax
from jax import jit
import jax.numpy as jnp
from jax.lax import scan, cond
from jax.flatten_util import ravel_pytree

from varipeps import varipeps_config, varipeps_global_state
from varipeps.config import Optimizing_Methods, Slurm_Restart_Mode
from varipeps.peps import PEPS_Unit_Cell
from varipeps.expectation import Expectation_Model
from varipeps.config import Projector_Method
from varipeps.mapping import Map_To_PEPS_Model
from varipeps.ctmrg import CTMRGNotConvergedError, CTMRGGradientNotConvergedError
from varipeps.utils.random import PEPS_Random_Number_Generator
from varipeps.utils.slurm import SlurmUtils
from varipeps.contractions import apply_contraction_jitted
from varipeps.utils.debug_print import debug_print

from .inner_function import (
    calc_ctmrg_expectation,
    calc_preconverged_ctmrg_value_and_grad,
    calc_ctmrg_expectation_custom_value_and_grad,
)
from .line_search import line_search, NoSuitableStepSizeError, _scalar_descent_grad

from typing import List, Union, Tuple, cast, Sequence, Callable, Optional, Dict, Any


@jit
def _cg_workhorse(new_gradient, old_gradient, old_descent_dir):
    new_grad_vec, new_grad_unravel = ravel_pytree(new_gradient)
    old_grad_vec, old_grad_unravel = ravel_pytree(old_gradient)
    old_des_dir_vec, old_des_dir_unravel = ravel_pytree(old_descent_dir)

    new_grad_len = new_grad_vec.size
    iscomplex = jnp.iscomplexobj(new_grad_vec)

    if iscomplex:
        new_grad_vec = jnp.concatenate((jnp.real(new_grad_vec), jnp.imag(new_grad_vec)))
        old_grad_vec = jnp.concatenate((jnp.real(old_grad_vec), jnp.imag(old_grad_vec)))
        old_des_dir_vec = jnp.concatenate(
            (jnp.real(old_des_dir_vec), jnp.imag(old_des_dir_vec))
        )

    grad_diff = new_grad_vec - old_grad_vec

    # dx = -new_grad_vec
    # dx_old = -old_grad_vec
    # dx_real = jnp.concatenate((jnp.real(dx), jnp.imag(dx)))
    # dx_old_real = jnp.concatenate((jnp.real(dx_old), jnp.imag(dx_old)))
    # old_des_dir_real = jnp.concatenate(
    #     (jnp.real(old_descent_dir), jnp.imag(old_descent_dir))
    # )
    # PRP
    # beta = jnp.sum(dx_real * (dx_real - dx_old_real)) / jnp.sum(dx_old_real * dx_old_real)
    # LS parameter
    # beta = jnp.sum(dx_real * (dx_old_real - dx_real)) / jnp.sum(
    #     old_des_dir_real * dx_old_real
    # )

    # Hager-Zhang
    eta = 0.4
    eta_k = -1 / (
        jnp.linalg.norm(old_des_dir_vec) * jnp.fmin(eta, jnp.linalg.norm(old_grad_vec))
    )
    old_des_grad_diff = jnp.dot(old_des_dir_vec, grad_diff)
    beta = (
        grad_diff - 2 * jnp.linalg.norm(grad_diff) * old_des_dir_vec / old_des_grad_diff
    )
    beta = jnp.dot(beta, new_grad_vec) / old_des_grad_diff
    beta = jnp.fmax(eta_k, beta)

    beta = jnp.fmax(0, beta)

    result = -new_grad_vec + beta * old_des_dir_vec

    if iscomplex:
        result = result[:new_grad_len] + 1j * result[new_grad_len:]

    return new_grad_unravel(result), beta


@partial(jit, static_argnums=(5,))
def _bfgs_workhorse(
    new_gradient, old_gradient, old_descent_dir, old_alpha, B_inv, calc_new_B_inv
):
    new_grad_vec, new_grad_unravel = ravel_pytree(new_gradient)
    new_grad_len = new_grad_vec.size

    iscomplex = jnp.iscomplexobj(new_grad_vec)
    if iscomplex:
        new_grad_vec = jnp.concatenate((jnp.real(new_grad_vec), jnp.imag(new_grad_vec)))

    if calc_new_B_inv:
        old_grad_vec, old_grad_unravel = ravel_pytree(old_gradient)
        old_descent_dir_vec, old_descent_dir_unravel = ravel_pytree(old_descent_dir)
        if iscomplex:
            old_grad_vec = jnp.concatenate(
                (jnp.real(old_grad_vec), jnp.imag(old_grad_vec))
            )
            old_descent_dir_vec = jnp.concatenate(
                (jnp.real(old_descent_dir_vec), jnp.imag(old_descent_dir_vec))
            )

        sk = old_alpha * old_descent_dir_vec
        yk = new_grad_vec - old_grad_vec

        skyk_scalar = jnp.dot(sk, yk)
        B_inv_yk = jnp.dot(B_inv, yk)

        new_B_inv = (
            B_inv
            + ((skyk_scalar + jnp.dot(yk, B_inv_yk)) / (skyk_scalar**2))
            * jnp.outer(sk, sk)
            - (jnp.outer(B_inv_yk, sk) + jnp.outer(sk, B_inv_yk)) / skyk_scalar
        )
    else:
        new_B_inv = B_inv

    result = -jnp.dot(new_B_inv, new_grad_vec)

    if iscomplex:
        result = result[:new_grad_len] + 1j * result[new_grad_len:]

    return new_grad_unravel(result), new_B_inv


@jit
def _l_bfgs_workhorse(value_tuple, gradient_tuple, t_objs, config):
    gradient_elem_0, gradient_unravel = ravel_pytree(gradient_tuple[0])
    gradient_len = gradient_elem_0.size

    iscomplex = jnp.iscomplexobj(gradient_elem_0)

    def _make_1d(x):
        x_1d, _ = ravel_pytree(x)
        if iscomplex:
            return jnp.concatenate((jnp.real(x_1d), jnp.imag(x_1d)))
        return x_1d

    gradient_elem_0_1d = _make_1d(gradient_elem_0)
    norm_grad_square = jnp.sum(gradient_elem_0_1d * gradient_elem_0_1d)

    value_arr = jnp.asarray([_make_1d(e) for e in value_tuple])
    gradient_arr = jnp.asarray([_make_1d(e) for e in gradient_tuple])

    s_arr = -jnp.diff(value_arr, axis=0)
    y_arr = -jnp.diff(gradient_arr, axis=0)
    pho_arr = 1 / jnp.sum(y_arr * s_arr, axis=1)

    def first_loop(q, x):
        pho_s, y = x
        alpha_i = jnp.sum(pho_s * q)
        return q - alpha_i * y, alpha_i

    q, alpha_arr = scan(
        first_loop,
        gradient_arr[0],
        (pho_arr[:, jnp.newaxis] * s_arr, y_arr),
    )

    def apply_precond(x):
        if hasattr(t_objs[0], "is_triangular_peps") and t_objs[0].is_triangular_peps:
            contraction = "precondition_operator_triangular"
        elif hasattr(t_objs[0], "is_split_transfer") and t_objs[0].is_split_transfer:
            contraction = "precondition_operator_split_transfer"
        else:
            contraction = "precondition_operator"

        if iscomplex:
            x = x[:gradient_len] + 1j * x[gradient_len:]
        x = gradient_unravel(x)
        x = [
            apply_contraction_jitted(contraction, (te.tensor,), (te,), (xe,))
            + norm_grad_square * xe
            for te, xe in zip(t_objs, x[: len(t_objs)], strict=True)
        ] + list(x[len(t_objs) :])

        return _make_1d(x)

    if config.optimizer_use_preconditioning:
        y_precond, _ = jax.scipy.sparse.linalg.gmres(
            apply_precond,
            y_arr[0],
            y_arr[0],
            restart=config.optimizer_precond_gmres_krylov_subspace_size,
            maxiter=config.optimizer_precond_gmres_maxiter,
            solve_method="incremental",
        )

        def calc_q_precond(y, y_precond, q):
            q_precond, _ = jax.scipy.sparse.linalg.gmres(
                apply_precond,
                q,
                q,
                restart=config.optimizer_precond_gmres_krylov_subspace_size,
                maxiter=config.optimizer_precond_gmres_maxiter,
                solve_method="incremental",
            )

            return cond(
                jnp.sum(q_precond * q) >= 0,
                lambda y, y_precond, q, q_precond: (y_precond, q_precond),
                lambda y, y_precond, q, q_precond: (y, q),
                y,
                y_precond,
                q,
                q_precond,
            )

        y_precond, q_precond = cond(
            jnp.sum(y_precond * y_arr[0]) >= 0,
            calc_q_precond,
            lambda y, y_precond, q: (y, q),
            y_arr[0],
            y_precond,
            q,
        )
    else:
        y_precond = y_arr[0]
        q_precond = q

    gamma = jnp.sum(s_arr[0] * y_arr[0]) / jnp.sum(y_arr[0] * y_precond)
    z_result = gamma * q_precond

    def second_loop(z, x):
        pho_y, s, alpha_i = x
        beta_i = jnp.sum(pho_y * z)
        return z + s * (alpha_i - beta_i), None

    z_result, _ = scan(
        second_loop,
        z_result,
        (pho_arr[:, jnp.newaxis] * y_arr, s_arr, alpha_arr),
        reverse=True,
    )

    z_result = -z_result
    if iscomplex:
        z_result = z_result[:gradient_len] + 1j * z_result[gradient_len:]
    return gradient_unravel(z_result)


def autosave_function(
    filename: PathLike,
    tensors: jnp.ndarray,
    unitcell: PEPS_Unit_Cell,
    counter: Optional[Union[int, str]] = None,
    auxiliary_data: Optional[Dict[str, Any]] = None,
) -> None:
    if counter is not None:
        unitcell.save_to_file(
            f"{str(filename)}.{counter}", auxiliary_data=auxiliary_data
        )
    else:
        unitcell.save_to_file(filename, auxiliary_data=auxiliary_data)


def autosave_function_restartable(
    filename,
    tensors,
    unitcell,
    counter,
    auxiliary_data,
    expectation_func,
    convert_to_unitcell_func,
    old_gradient,
    old_descent_dir,
    best_value,
    best_tensors,
    best_unitcell,
    random_noise_retries,
    descent_method_tuple,
    count,
    linesearch_step,
    projector_method,
    signal_reset_descent_dir,
) -> None:
    state_filename = os.environ.get("VARIPEPS_STATE_FILE")
    if state_filename is None:
        state_filename = f"{str(filename)}.restartable"
    with h5py.File(state_filename, "w", libver=("earliest", "v110")) as f:
        grp = f.create_group("unitcell")
        unitcell.save_to_group(grp, True)

        grp_aux = f.create_group("auxiliary_data")
        unitcell.save_auxiliary_data(grp_aux, auxiliary_data)

        grp_restart_data = f.create_group("restart_data")

        grp_restart_data.attrs["autosave_filename"] = filename

        grp_expectation_func = grp_restart_data.create_group("expectation_func")
        try:
            expectation_func.save_to_group(grp_expectation_func)
        except AttributeError:
            pass

        if convert_to_unitcell_func is not None:
            pass

        if old_gradient is not None:
            grp_old_grad = grp_restart_data.create_group(
                "old_gradient", track_order=True
            )
            grp_old_grad.attrs["len"] = len(old_gradient)
            for i, g in enumerate(old_gradient):
                if g.ndim == 0:
                    grp_old_grad.create_dataset(f"old_grad_{i:d}", data=g)
                else:
                    grp_old_grad.create_dataset(
                        f"old_grad_{i:d}",
                        data=g,
                        compression="gzip",
                        compression_opts=6,
                    )

        if old_descent_dir is not None:
            grp_old_des_dir = grp_restart_data.create_group(
                "old_descent_dir", track_order=True
            )
            grp_old_des_dir.attrs["len"] = len(old_descent_dir)
            for i, d in enumerate(old_descent_dir):
                if d.ndim == 0:
                    grp_old_des_dir.create_dataset(
                        f"old_descent_dir_{i:d}",
                        data=d,
                    )
                else:
                    grp_old_des_dir.create_dataset(
                        f"old_descent_dir_{i:d}",
                        data=d,
                        compression="gzip",
                        compression_opts=6,
                    )

        if best_unitcell is not None:
            grp_best_t = grp_restart_data.create_group("best_tensors", track_order=True)
            grp_best_t.attrs["len"] = len(best_tensors)
            for i, t in enumerate(best_tensors):
                if t.ndim == 0:
                    grp_best_t.create_dataset(
                        f"best_tensor_{i:d}",
                        data=t,
                    )
                else:
                    grp_best_t.create_dataset(
                        f"best_tensor_{i:d}",
                        data=t,
                        compression="gzip",
                        compression_opts=6,
                    )

            grp_best_u = grp_restart_data.create_group("best_unitcell")
            best_unitcell.save_to_group(grp_best_u, False)

            grp_restart_data.attrs["best_value"] = best_value

        grp_restart_data.attrs["random_noise_retries"] = random_noise_retries
        grp_restart_data.attrs["count"] = count
        grp_restart_data.attrs["projector_method"] = projector_method
        grp_restart_data.attrs["signal_reset_descent_dir"] = signal_reset_descent_dir

        if linesearch_step is not None:
            grp_restart_data.attrs["linesearch_step"] = linesearch_step

        if varipeps_config.optimizer_method is Optimizing_Methods.BFGS:
            bfgs_prefactor, bfgs_B_inv = descent_method_tuple
            grp_restart_data.attrs["bfgs_prefactor"] = bfgs_prefactor
            grp_restart_data.create_dataset(
                "bfgs_B_inv", data=bfgs_B_inv, compression="gzip", compression_opts=6
            )
        elif varipeps_config.optimizer_method is Optimizing_Methods.L_BFGS:
            l_bfgs_x_cache, l_bfgs_grad_cache = descent_method_tuple

            grp_l_bfgs = grp_restart_data.create_group("l_bfgs", track_order=True)
            grp_l_bfgs.attrs["len"] = len(l_bfgs_x_cache)
            if len(l_bfgs_x_cache) > 0:
                grp_l_bfgs.attrs["len_elems"] = len(l_bfgs_x_cache[0])
            for i, (x, g) in enumerate(
                zip(l_bfgs_x_cache, l_bfgs_grad_cache, strict=True)
            ):
                if len(x) != len(g) != grp_l_bfgs.attrs["len_elems"]:
                    raise ValueError("L-BFGS list lengths mismatch.")
                for j in range(grp_l_bfgs.attrs["len_elems"]):
                    if x[j].ndim == 0:
                        grp_l_bfgs.create_dataset(
                            f"x_{i:d}_{j:d}",
                            data=x[j],
                        )
                    else:
                        grp_l_bfgs.create_dataset(
                            f"x_{i:d}_{j:d}",
                            data=x[j],
                            compression="gzip",
                            compression_opts=6,
                        )
                    if g[j].ndim == 0:
                        grp_l_bfgs.create_dataset(
                            f"grad_{i:d}_{j:d}",
                            data=g[j],
                        )
                    else:
                        grp_l_bfgs.create_dataset(
                            f"grad_{i:d}_{j:d}",
                            data=g[j],
                            compression="gzip",
                            compression_opts=6,
                        )


def _autosave_wrapper(
    autosave_func,
    autosave_filename,
    working_tensors,
    working_unitcell,
    working_value,
    counter,
    best_run,
    max_trunc_error_list,
    step_energies,
    step_chi,
    step_conv,
    step_runtime,
    spiral_indices,
    additional_input,
):
    auxiliary_data = {
        "best_run": jnp.array(best_run if best_run is not None else 0),
        "current_energy": working_value,
    }

    for k in sorted(max_trunc_error_list.keys()):
        auxiliary_data[f"max_trunc_error_list_{k:d}"] = max_trunc_error_list[k]
        auxiliary_data[f"step_energies_{k:d}"] = step_energies[k]
        auxiliary_data[f"step_chi_{k:d}"] = step_chi[k]
        auxiliary_data[f"step_conv_{k:d}"] = step_conv[k]
        auxiliary_data[f"step_runtime_{k:d}"] = step_runtime[k]

    spiral_vectors = None
    if spiral_indices is not None:
        spiral_mode = "BOTH_INDEPENDENT"

        spiral_vectors = [working_tensors[spiral_i] for spiral_i in spiral_indices]

        if any(i.size == 1 for i in spiral_vectors):
            spiral_mode = "BOTH_SAME"

            spiral_vectors_x = additional_input.get("spiral_vectors_x")
            spiral_vectors_y = additional_input.get("spiral_vectors_y")
            if spiral_vectors_x is not None:
                spiral_mode = "FIXED_X"
                if isinstance(spiral_vectors_x, jnp.ndarray):
                    spiral_vectors_x = (spiral_vectors_x,)
                spiral_vectors = tuple(
                    jnp.array((sx, sy))
                    for sx, sy in zip(spiral_vectors_x, spiral_vectors, strict=True)
                )
            elif spiral_vectors_y is not None:
                spiral_mode = "FIXED_Y"
                if isinstance(spiral_vectors_y, jnp.ndarray):
                    spiral_vectors_y = (spiral_vectors_y,)
                spiral_vectors = tuple(
                    jnp.array((sx, sy))
                    for sx, sy in zip(spiral_vectors, spiral_vectors_y, strict=True)
                )
    elif additional_input.get("spiral_vectors") is not None:
        spiral_mode = "FIXED"

        spiral_vectors = additional_input.get("spiral_vectors")
        if isinstance(spiral_vectors, jnp.ndarray):
            spiral_vectors = (spiral_vectors,)

    if spiral_vectors is not None:
        auxiliary_data["spiral_mode"] = spiral_mode

        spiral_vectors = [
            e if e.size == 2 else jnp.array((e, e)).reshape(2) for e in spiral_vectors
        ]

        if len(spiral_vectors) == 1:
            auxiliary_data["spiral_vector"] = spiral_vectors[0]
        else:
            for spiral_i, vec in enumerate(spiral_vectors):
                spiral_i += 1
                auxiliary_data[f"spiral_vector_{spiral_i:d}"] = vec

    autosave_func(
        autosave_filename,
        working_tensors,
        working_unitcell,
        counter=counter,
        auxiliary_data=auxiliary_data,
    )


def optimize_peps_network(
    input_tensors: Union[PEPS_Unit_Cell, Sequence[jnp.ndarray]],
    expectation_func: Expectation_Model,
    convert_to_unitcell_func: Optional[Map_To_PEPS_Model] = None,
    autosave_filename: PathLike = "data/autosave.hdf5",
    autosave_func: Callable[
        [PathLike, Sequence[jnp.ndarray], PEPS_Unit_Cell], None
    ] = autosave_function,
    additional_input: Dict[str, jnp.ndarray] = {},
    restart_state: Dict[str, Any] = {},
) -> Tuple[Sequence[jnp.ndarray], PEPS_Unit_Cell, Union[float, jnp.ndarray]]:
    """
    Optimize a PEPS unitcell using a variational method.

    As convergence criterion the norm of the gradient is used.

    If the very first CTMRG calculation does not converge,
    a object of type :obj:`scipy.optimize.OptimizeResult`
    is returned with Success=False. This case should be
    handled by the scriptcalling this function.

    Args:
      input_tensors (:obj:`~varipeps.peps.PEPS_Unit_Cell` or :term:`sequence` of :obj:`jax.numpy.ndarray`):
        The PEPS unitcell to work on or the tensors which should be mapped by
        `convert_to_unitcell_func` to a PEPS unitcell.
      expectation_func (:obj:`~varipeps.expectation.Expectation_Model`):
        Callable to calculate one expectation value which is used as loss
        loss function of the model. Likely the function to calculate the energy.
      convert_to_unitcell_func (:obj:`~varipeps.mapping.Map_To_PEPS_Model`):
        Function to convert the `input_tensors` to a PEPS unitcell. If ommited,
        it is assumed that a PEPS unitcell is the first input parameter.
      autosave_filename (:obj:`os.PathLike`):
        Filename where intermediate results are automatically saved.
      autosave_func (:term:`callable`):
        Function which is called to autosave the intermediate results.
        The function has to accept the arguments `(filename, tensors, unitcell)`.
      additional_input (:obj:`dict` of :obj:`str` to :obj:`jax.numpy.ndarray` mapping):
        Dict with additional inputs which should be considered in the
        calculation of the expectation value.
    Returns:
      :obj:`scipy.optimize.OptimizeResult`:
        OptimizeResult object with the optimized tensors, network and the
        final expectation value. See the type definition for other possible
        fields.
    """
    rng = PEPS_Random_Number_Generator.get_generator(backend="jax")

    def random_noise(a):
        return (
            a
            + a
            * rng.block(a.shape, dtype=a.dtype)
            * varipeps_config.optimizer_random_noise_relative_amplitude
        )

    if isinstance(input_tensors, PEPS_Unit_Cell):
        working_tensors = cast(
            List[jnp.ndarray], [i.tensor for i in input_tensors.get_unique_tensors()]
        )
        working_unitcell = input_tensors
        generate_unitcell = True
    else:
        if isinstance(input_tensors, collections.abc.Sequence) and isinstance(
            input_tensors[0], PEPS_Unit_Cell
        ):
            if len(input_tensors[0].get_unique_tensors()) != 1:
                raise ValueError(
                    "You want to use spiral PEPS but you use a unit cell with more than one site. Seems wrong to me!"
                )
            working_tensors = cast(
                List[jnp.ndarray],
                [i.tensor for i in input_tensors[0].get_unique_tensors()],
            ) + list(input_tensors[1:])
            working_unitcell = input_tensors[0]
            generate_unitcell = True
        else:
            working_tensors = input_tensors
            working_unitcell = None
            generate_unitcell = False

    old_gradient = restart_state.get("old_gradient")
    old_descent_dir = restart_state.get("old_descent_dir")
    descent_dir = None
    working_value = None

    max_trunc_error = jnp.nan

    best_value = restart_state.get("best_value", jnp.inf)
    best_tensors = restart_state.get("best_tensors")
    best_unitcell = restart_state.get("best_unitcell")
    best_run = restart_state.get("best_run")

    random_noise_retries = restart_state.get("random_noise_retries", 0)

    signal_reset_descent_dir = restart_state.get("signal_reset_descent_dir", False)

    spiral_indices = None
    if (
        hasattr(expectation_func, "is_spiral_peps")
        and expectation_func.is_spiral_peps
        and additional_input.get("spiral_vectors") is None
    ):
        if isinstance(input_tensors, collections.abc.Sequence) and isinstance(
            input_tensors[0], PEPS_Unit_Cell
        ):
            spiral_indices = list(range(1, len(input_tensors)))
        else:
            raise NotImplementedError("Only support spiral PEPS for unitcell input yet")

    if varipeps_config.optimizer_method is Optimizing_Methods.BFGS:
        bfgs_prefactor = restart_state.get(
            "bfgs_prefactor",
            2 if any(jnp.iscomplexobj(t) for t in working_tensors) else 1,
        )
        bfgs_B_inv = restart_state.get(
            "bfgs_B_inv",
            jnp.eye(bfgs_prefactor * sum([t.size for t in working_tensors])),
        )
    elif varipeps_config.optimizer_method is Optimizing_Methods.L_BFGS:
        l_bfgs_x_cache = deque(
            restart_state.get("l_bfgs_x_cache", []),
            maxlen=varipeps_config.optimizer_l_bfgs_maxlen + 1,
        )
        l_bfgs_grad_cache = deque(
            restart_state.get("l_bfgs_grad_cache", []),
            maxlen=varipeps_config.optimizer_l_bfgs_maxlen + 1,
        )

    count = restart_state.get("count", 0)
    linesearch_step: Optional[Union[float, jnp.ndarray]] = restart_state.get(
        "linesearch_step"
    )
    working_value: Union[float, jnp.ndarray]
    max_trunc_error_list = restart_state.get(
        "max_trunc_error_list", {random_noise_retries: []}
    )
    step_energies = restart_state.get("step_energies", {random_noise_retries: []})
    step_chi = restart_state.get("step_chi", {random_noise_retries: []})
    step_conv = restart_state.get("step_conv", {random_noise_retries: []})
    step_runtime = restart_state.get("step_runtime", {random_noise_retries: []})

    if (
        varipeps_config.optimizer_preconverge_with_half_projectors
        and not varipeps_global_state.basinhopping_disable_half_projector
    ):
        varipeps_global_state.ctmrg_projector_method = (
            Projector_Method.HALF
            if restart_state.get("projector_method", "HALF") == "HALF"
            else None
        )
    else:
        varipeps_global_state.ctmrg_projector_method = None

    slurm_restart_written = False
    slurm_new_job_id = None

    with tqdm(desc="Optimizing PEPS state", initial=count) as pbar:
        while count < varipeps_config.optimizer_max_steps:
            runtime_start = time.perf_counter()

            chi_before_ctmrg = working_unitcell[0, 0][0][0].chi
            try:
                if varipeps_config.ad_use_custom_vjp:
                    (
                        working_value,
                        (working_unitcell, _),
                    ), working_gradient_seq = calc_ctmrg_expectation_custom_value_and_grad(
                        working_tensors,
                        working_unitcell,
                        expectation_func,
                        convert_to_unitcell_func,
                        additional_input,
                    )
                else:
                    (
                        working_value,
                        (working_unitcell, _),
                    ), working_gradient_seq = calc_preconverged_ctmrg_value_and_grad(
                        working_tensors,
                        working_unitcell,
                        expectation_func,
                        convert_to_unitcell_func,
                        additional_input,
                        calc_preconverged=(count == 0),
                    )
            except (CTMRGNotConvergedError, CTMRGGradientNotConvergedError) as e:
                varipeps_global_state.ctmrg_projector_method = None

                if random_noise_retries == 0:
                    return OptimizeResult(
                        success=False,
                        message=str(type(e)),
                        x=working_tensors,
                        fun=working_value,
                        unitcell=working_unitcell,
                        nit=count,
                        max_trunc_error_list=max_trunc_error_list,
                        step_energies=step_energies,
                        step_chi=step_chi,
                        step_conv=step_conv,
                        step_runtime=step_runtime,
                        best_run=0,
                    )
                elif (
                    random_noise_retries
                    >= varipeps_config.optimizer_random_noise_max_retries
                ):
                    working_value = jnp.inf
                    break
                else:
                    if isinstance(input_tensors, PEPS_Unit_Cell) or (
                        isinstance(input_tensors, collections.abc.Sequence)
                        and isinstance(input_tensors[0], PEPS_Unit_Cell)
                    ):
                        working_tensors = (
                            cast(
                                List[jnp.ndarray],
                                [i.tensor for i in best_unitcell.get_unique_tensors()],
                            )
                            + best_tensors[best_unitcell.get_len_unique_tensors() :]
                        )

                        working_tensors = [random_noise(i) for i in working_tensors]

                        working_tensors_obj = [
                            e.replace_tensor(working_tensors[i])
                            for i, e in enumerate(best_unitcell.get_unique_tensors())
                        ]

                        working_unitcell = best_unitcell.replace_unique_tensors(
                            working_tensors_obj
                        )
                    else:
                        working_tensors = [random_noise(i) for i in best_tensors]
                        working_unitcell = None

                    descent_dir = None
                    working_gradient = None
                    signal_reset_descent_dir = True
                    count = 0
                    random_noise_retries += 1
                    old_descent_dir = descent_dir
                    old_gradient = working_gradient

                    step_energies[random_noise_retries] = []
                    step_chi[random_noise_retries] = []
                    step_conv[random_noise_retries] = []
                    max_trunc_error_list[random_noise_retries] = []
                    step_runtime[random_noise_retries] = []

                    pbar.reset()
                    pbar.refresh()

                    continue

            if working_unitcell[0, 0][0][0].chi != chi_before_ctmrg:
                jax.clear_caches()

            working_gradient = [elem.conj() for elem in working_gradient_seq]

            if signal_reset_descent_dir:
                if varipeps_config.optimizer_method is Optimizing_Methods.BFGS:
                    bfgs_prefactor = (
                        2 if any(jnp.iscomplexobj(t) for t in working_tensors) else 1
                    )
                    bfgs_B_inv = jnp.eye(
                        bfgs_prefactor * sum([t.size for t in working_tensors])
                    )
                elif varipeps_config.optimizer_method is Optimizing_Methods.L_BFGS:
                    l_bfgs_x_cache = deque(
                        maxlen=varipeps_config.optimizer_l_bfgs_maxlen + 1
                    )
                    l_bfgs_grad_cache = deque(
                        maxlen=varipeps_config.optimizer_l_bfgs_maxlen + 1
                    )

            if varipeps_config.optimizer_method is Optimizing_Methods.STEEPEST:
                descent_dir = [-elem for elem in working_gradient]
            elif varipeps_config.optimizer_method is Optimizing_Methods.CG:
                if count == 0 or signal_reset_descent_dir:
                    descent_dir = [-elem for elem in working_gradient]
                else:
                    descent_dir, beta = _cg_workhorse(
                        working_gradient, old_gradient, old_descent_dir
                    )
            elif varipeps_config.optimizer_method is Optimizing_Methods.BFGS:
                if count == 0 or signal_reset_descent_dir:
                    descent_dir, _ = _bfgs_workhorse(
                        working_gradient, None, None, None, bfgs_B_inv, False
                    )
                else:
                    descent_dir, bfgs_B_inv = _bfgs_workhorse(
                        working_gradient,
                        old_gradient,
                        old_descent_dir,
                        linesearch_step,
                        bfgs_B_inv,
                        True,
                    )
            elif varipeps_config.optimizer_method is Optimizing_Methods.L_BFGS:
                l_bfgs_x_cache.appendleft(tuple(working_tensors))
                l_bfgs_grad_cache.appendleft(tuple(working_gradient))

                if count == 0 or signal_reset_descent_dir:
                    descent_dir = [-elem for elem in working_gradient]

                    if varipeps_config.optimizer_use_preconditioning:
                        if (
                            hasattr(
                                working_unitcell.get_unique_tensors()[0],
                                "is_triangular_peps",
                            )
                            and working_unitcell.get_unique_tensors()[
                                0
                            ].is_triangular_peps
                        ):
                            contraction = "precondition_operator_triangular"
                        elif (
                            hasattr(
                                working_unitcell.get_unique_tensors()[0],
                                "is_split_transfer",
                            )
                            and working_unitcell.get_unique_tensors()[
                                0
                            ].is_split_transfer
                        ):
                            contraction = "precondition_operator_split_transfer"
                        else:
                            contraction = "precondition_operator"

                        grad_norm_squared = 1e-2 * (
                            jnp.linalg.norm(ravel_pytree(working_gradient)[0]) ** 2
                        )

                        tmp_descent_dir = [
                            jax.scipy.sparse.linalg.gmres(
                                lambda x: (
                                    apply_contraction_jitted(
                                        contraction, (te.tensor,), (te,), (x,)
                                    )
                                    + grad_norm_squared * x
                                ),
                                xe,
                                xe,
                                restart=varipeps_config.optimizer_precond_gmres_krylov_subspace_size,
                                maxiter=varipeps_config.optimizer_precond_gmres_maxiter,
                                solve_method="incremental",
                            )[0]
                            for te, xe in zip(
                                working_unitcell.get_unique_tensors(),
                                descent_dir[
                                    : working_unitcell.get_len_unique_tensors()
                                ],
                                strict=True,
                            )
                        ] + list(
                            descent_dir[working_unitcell.get_len_unique_tensors() :]
                        )
                        if all(
                            jnp.sum(xe * x2e.conj()) >= 0
                            for xe, x2e in zip(
                                descent_dir, tmp_descent_dir, strict=True
                            )
                        ):
                            descent_dir = tmp_descent_dir
                        else:
                            tqdm.write("Warning: Non-positive preconditioner")
                        del contraction
                        del grad_norm_squared
                else:
                    descent_dir = _l_bfgs_workhorse(
                        tuple(l_bfgs_x_cache),
                        tuple(l_bfgs_grad_cache),
                        working_unitcell.get_unique_tensors(),
                        varipeps_config,
                    )
            else:
                raise ValueError("Unknown optimization method.")

            signal_reset_descent_dir = False

            if _scalar_descent_grad(descent_dir, working_gradient) > 0:
                tqdm.write("Found bad descent dir. Reset to negative gradient!")
                descent_dir = [-elem for elem in working_gradient]

            conv = jnp.linalg.norm(ravel_pytree(working_gradient)[0])
            if jnp.isinf(conv) or jnp.isnan(conv):
                conv = 0
            step_conv[random_noise_retries].append(conv)

            try:
                (
                    working_tensors,
                    working_unitcell,
                    working_value,
                    linesearch_step,
                    signal_reset_descent_dir,
                    max_trunc_error,
                ) = line_search(
                    working_tensors,
                    working_unitcell,
                    expectation_func,
                    working_gradient,
                    descent_dir,
                    working_value,
                    linesearch_step,
                    convert_to_unitcell_func,
                    generate_unitcell,
                    spiral_indices,
                    additional_input,
                    conv > varipeps_config.optimizer_reuse_env_eps,
                )
            except NoSuitableStepSizeError:
                runtime = time.perf_counter() - runtime_start
                step_runtime[random_noise_retries].append(runtime)

                if varipeps_config.optimizer_fail_if_no_step_size_found:
                    raise
                else:
                    if (
                        (
                            conv > varipeps_config.optimizer_random_noise_eps
                            or working_value > best_value
                        )
                        and random_noise_retries
                        < varipeps_config.optimizer_random_noise_max_retries
                        and not (
                            varipeps_config.optimizer_preconverge_with_half_projectors
                            and not varipeps_global_state.basinhopping_disable_half_projector
                            and varipeps_global_state.ctmrg_projector_method
                            is Projector_Method.HALF
                        )
                    ):
                        tqdm.write(
                            "Convergence is not sufficient. Retry with some random noise on best result."
                        )

                        if working_value < best_value:
                            best_value = working_value
                            best_tensors = working_tensors
                            best_unitcell = working_unitcell
                            best_run = random_noise_retries

                            _autosave_wrapper(
                                autosave_func,
                                autosave_filename,
                                working_tensors,
                                working_unitcell,
                                working_value,
                                "best",
                                best_run,
                                max_trunc_error_list,
                                step_energies,
                                step_chi,
                                step_conv,
                                step_runtime,
                                spiral_indices,
                                additional_input,
                            )

                        if isinstance(input_tensors, PEPS_Unit_Cell) or (
                            isinstance(input_tensors, collections.abc.Sequence)
                            and isinstance(input_tensors[0], PEPS_Unit_Cell)
                        ):
                            working_tensors = (
                                cast(
                                    List[jnp.ndarray],
                                    [
                                        i.tensor
                                        for i in best_unitcell.get_unique_tensors()
                                    ],
                                )
                                + best_tensors[best_unitcell.get_len_unique_tensors() :]
                            )

                            working_tensors = [random_noise(i) for i in working_tensors]

                            working_tensors_obj = [
                                e.replace_tensor(working_tensors[i])
                                for i, e in enumerate(
                                    best_unitcell.get_unique_tensors()
                                )
                            ]

                            working_unitcell = best_unitcell.replace_unique_tensors(
                                working_tensors_obj
                            )
                        else:
                            working_tensors = [random_noise(i) for i in best_tensors]
                            working_unitcell = None

                        descent_dir = None
                        working_gradient = None
                        signal_reset_descent_dir = True
                        count = 0
                        random_noise_retries += 1
                        old_descent_dir = descent_dir
                        old_gradient = working_gradient

                        step_energies[random_noise_retries] = []
                        step_chi[random_noise_retries] = []
                        step_conv[random_noise_retries] = []
                        max_trunc_error_list[random_noise_retries] = []
                        step_runtime[random_noise_retries] = []

                        if autosave_func is autosave_function:
                            descent_method_tuple = None
                            if (
                                varipeps_config.optimizer_method
                                is Optimizing_Methods.BFGS
                            ):
                                descent_method_tuple = (bfgs_prefactor, bfgs_B_inv)
                            elif (
                                varipeps_config.optimizer_method
                                is Optimizing_Methods.L_BFGS
                            ):
                                descent_method_tuple = (
                                    l_bfgs_x_cache,
                                    l_bfgs_grad_cache,
                                )
                            _autosave_wrapper(
                                partial(
                                    autosave_function_restartable,
                                    expectation_func=expectation_func,
                                    convert_to_unitcell_func=convert_to_unitcell_func,
                                    old_gradient=old_gradient,
                                    old_descent_dir=old_descent_dir,
                                    best_value=best_value,
                                    best_tensors=best_tensors,
                                    best_unitcell=best_unitcell,
                                    random_noise_retries=random_noise_retries,
                                    descent_method_tuple=descent_method_tuple,
                                    count=count,
                                    linesearch_step=linesearch_step,
                                    projector_method=(
                                        "HALF"
                                        if varipeps_global_state.ctmrg_projector_method
                                        is Projector_Method.HALF
                                        else "FULL"
                                    ),
                                    signal_reset_descent_dir=signal_reset_descent_dir,
                                ),
                                autosave_filename,
                                working_tensors,
                                working_unitcell,
                                working_value,
                                None,
                                best_run,
                                max_trunc_error_list,
                                step_energies,
                                step_chi,
                                step_conv,
                                step_runtime,
                                spiral_indices,
                                additional_input,
                            )

                        pbar.reset()
                        pbar.refresh()

                        continue
                    else:
                        conv = 0
            else:
                runtime = time.perf_counter() - runtime_start
                step_runtime[random_noise_retries].append(runtime)
                max_trunc_error_list[random_noise_retries].append(max_trunc_error)
                step_energies[random_noise_retries].append(working_value)
                step_chi[random_noise_retries].append(
                    working_unitcell.get_unique_tensors()[0].chi
                )

            if (
                varipeps_config.optimizer_preconverge_with_half_projectors
                and not varipeps_global_state.basinhopping_disable_half_projector
                and varipeps_global_state.ctmrg_projector_method
                is Projector_Method.HALF
                and conv
                < varipeps_config.optimizer_preconverge_with_half_projectors_eps
            ):
                varipeps_global_state.ctmrg_projector_method = (
                    varipeps_config.ctmrg_full_projector_method
                )

                working_value, (working_unitcell, max_trunc_error) = (
                    calc_ctmrg_expectation(
                        working_tensors,
                        working_unitcell,
                        expectation_func,
                        convert_to_unitcell_func,
                        additional_input,
                        enforce_elementwise_convergence=varipeps_config.ad_use_custom_vjp,
                    )
                )
                descent_dir = None
                working_gradient = None
                signal_reset_descent_dir = True
                conv = jnp.inf
                linesearch_step = None

            if conv < varipeps_config.optimizer_convergence_eps:
                working_value, (
                    working_unitcell,
                    max_trunc_error,
                ) = calc_ctmrg_expectation(
                    working_tensors,
                    working_unitcell,
                    expectation_func,
                    convert_to_unitcell_func,
                    additional_input,
                    enforce_elementwise_convergence=varipeps_config.ad_use_custom_vjp,
                )

                try:
                    max_trunc_error_list[random_noise_retries][-1] = max_trunc_error
                except IndexError:
                    max_trunc_error_list[random_noise_retries].append(max_trunc_error)

                try:
                    step_energies[random_noise_retries][-1] = working_value
                except IndexError:
                    step_energies[random_noise_retries].append(working_value)

                try:
                    step_chi[random_noise_retries][
                        -1
                    ] = working_unitcell.get_unique_tensors()[0].chi
                except IndexError:
                    step_chi[random_noise_retries].append(
                        working_unitcell.get_unique_tensors()[0].chi
                    )

                break

            old_descent_dir = descent_dir
            old_gradient = working_gradient

            count += 1

            pbar.update()
            pbar.set_postfix(
                {
                    "Energy": f"{working_value:0.10f}",
                    "Retries": random_noise_retries,
                    "Convergence": f"{conv:0.8f}",
                    "Line search step": (
                        f"{linesearch_step:0.8f}"
                        if linesearch_step is not None
                        else "0"
                    ),
                    "Max. trunc. err.": f"{max_trunc_error:0.8g}",
                }
            )
            pbar.refresh()

            if count % varipeps_config.optimizer_autosave_step_count == 0:
                _autosave_wrapper(
                    autosave_func,
                    autosave_filename,
                    working_tensors,
                    working_unitcell,
                    working_value,
                    random_noise_retries,
                    best_run,
                    max_trunc_error_list,
                    step_energies,
                    step_chi,
                    step_conv,
                    step_runtime,
                    spiral_indices,
                    additional_input,
                )

                if working_value < best_value and not (
                    varipeps_config.optimizer_preconverge_with_half_projectors
                    and not varipeps_global_state.basinhopping_disable_half_projector
                    and varipeps_global_state.ctmrg_projector_method
                    is Projector_Method.HALF
                ):
                    _autosave_wrapper(
                        autosave_func,
                        autosave_filename,
                        working_tensors,
                        working_unitcell,
                        working_value,
                        "best",
                        random_noise_retries,
                        max_trunc_error_list,
                        step_energies,
                        step_chi,
                        step_conv,
                        step_runtime,
                        spiral_indices,
                        additional_input,
                    )

                if autosave_func is autosave_function:
                    descent_method_tuple = None
                    if varipeps_config.optimizer_method is Optimizing_Methods.BFGS:
                        descent_method_tuple = (bfgs_prefactor, bfgs_B_inv)
                    elif varipeps_config.optimizer_method is Optimizing_Methods.L_BFGS:
                        descent_method_tuple = (l_bfgs_x_cache, l_bfgs_grad_cache)
                    _autosave_wrapper(
                        partial(
                            autosave_function_restartable,
                            expectation_func=expectation_func,
                            convert_to_unitcell_func=convert_to_unitcell_func,
                            old_gradient=old_gradient,
                            old_descent_dir=old_descent_dir,
                            best_value=best_value,
                            best_tensors=best_tensors,
                            best_unitcell=best_unitcell,
                            random_noise_retries=random_noise_retries,
                            descent_method_tuple=descent_method_tuple,
                            count=count,
                            linesearch_step=linesearch_step,
                            projector_method=(
                                "HALF"
                                if varipeps_global_state.ctmrg_projector_method
                                is Projector_Method.HALF
                                else "FULL"
                            ),
                            signal_reset_descent_dir=signal_reset_descent_dir,
                        ),
                        autosave_filename,
                        working_tensors,
                        working_unitcell,
                        working_value,
                        None,
                        best_run,
                        max_trunc_error_list,
                        step_energies,
                        step_chi,
                        step_conv,
                        step_runtime,
                        spiral_indices,
                        additional_input,
                    )

            if working_value < best_value and not (
                varipeps_config.optimizer_preconverge_with_half_projectors
                and not varipeps_global_state.basinhopping_disable_half_projector
                and varipeps_global_state.ctmrg_projector_method
                is Projector_Method.HALF
            ):
                best_value = working_value
                best_tensors = working_tensors
                best_unitcell = working_unitcell
                best_run = random_noise_retries

            if (
                varipeps_config.slurm_restart_mode is not Slurm_Restart_Mode.DISABLED
                and (slurm_data := SlurmUtils.get_own_job_data()) is not None
            ):
                flatten_runtime = [j for i in step_runtime for j in step_runtime[i]]
                runtime_mean = np.mean(flatten_runtime)
                runtime_std = np.std(flatten_runtime)

                remaining_slurm_time = slurm_data["TimeLimit"] - slurm_data["RunTime"]

                if (
                    remaining_time_correction := os.environ.get(
                        "VARIPEPS_REMAINING_TIME_CORRECTION"
                    )
                ) is not None:
                    try:
                        remaining_time_correction = int(remaining_time_correction)
                        remaining_slurm_time -= datetime.timedelta(
                            seconds=remaining_time_correction
                        )
                    except (TypeError, ValueError):
                        pass

                time_of_one_step = datetime.timedelta(
                    seconds=runtime_mean + 3 * runtime_std
                )

                if remaining_slurm_time < time_of_one_step:
                    print(
                        "Average time of optimizer step below remaining Slurm runtime",
                        file=sys.stderr,
                    )

                    if (
                        restart_needed_filename := os.environ.get(
                            "VARIPEPS_NEED_RESTART_FILE"
                        )
                    ) is not None:
                        pathlib.Path(restart_needed_filename).touch()

                    if (
                        varipeps_config.slurm_restart_mode
                        is Slurm_Restart_Mode.WRITE_RESTART_SCRIPT
                        or varipeps_config.slurm_restart_mode
                        is Slurm_Restart_Mode.AUTOMATIC_RESTART
                    ):
                        SlurmUtils.generate_restart_scripts(
                            f"{str(autosave_filename)}.restart.slurm",
                            f"{str(autosave_filename)}.restart.py",
                            f"{str(autosave_filename)}.restartable",
                            slurm_data,
                        )

                        slurm_restart_written = True

                    if (
                        varipeps_config.slurm_restart_mode
                        is Slurm_Restart_Mode.AUTOMATIC_RESTART
                    ):
                        slurm_new_job_id = SlurmUtils.run_slurm_script(
                            f"{str(autosave_filename)}.restart.slurm",
                            slurm_data["WorkDir"],
                        )
                        if slurm_new_job_id is None:
                            tqdm.write(
                                "Failed to start new Slurm job or parse its job id."
                            )
                        break

    if working_value < best_value:
        best_value = working_value
        best_tensors = working_tensors
        best_unitcell = working_unitcell
        best_run = random_noise_retries

        if not (
            varipeps_config.optimizer_preconverge_with_half_projectors
            and not varipeps_global_state.basinhopping_disable_half_projector
            and varipeps_global_state.ctmrg_projector_method is Projector_Method.HALF
        ):
            _autosave_wrapper(
                autosave_func,
                autosave_filename,
                working_tensors,
                working_unitcell,
                working_value,
                "best",
                best_run,
                max_trunc_error_list,
                step_energies,
                step_chi,
                step_conv,
                step_runtime,
                spiral_indices,
                additional_input,
            )

    varipeps_global_state.ctmrg_projector_method = None

    print(f"Best energy result found: {best_value}")

    if slurm_restart_written:
        print("Wrote script to restart optimizer job with Slurm.")
    if slurm_new_job_id is not None:
        print(f"Started new Slurm job with ID {slurm_new_job_id:d}.")

    return OptimizeResult(
        success=True,
        x=best_tensors,
        fun=best_value,
        unitcell=best_unitcell,
        nit=count,
        max_trunc_error_list=max_trunc_error_list,
        step_energies=step_energies,
        step_chi=step_chi,
        step_conv=step_conv,
        step_runtime=step_runtime,
        best_run=best_run,
        slurm_restart_written=slurm_restart_written,
        slurm_new_job_id=slurm_new_job_id,
    )


def optimize_peps_unitcell(
    unitcell,
    expectation_func,
    autosave_filename="data/autosave.hdf5",
    restart_state={},
):
    return optimize_peps_network(
        unitcell,
        expectation_func,
        autosave_filename=autosave_filename,
        restart_state=restart_state,
    )


def optimize_unitcell_fixed_spiral_vector(
    unitcell,
    spiral_vector,
    expectation_func,
    autosave_filename="data/autosave.hdf5",
    restart_state={},
):
    return optimize_peps_network(
        unitcell,
        expectation_func,
        additional_input={"spiral_vectors": spiral_vector},
        autosave_filename=autosave_filename,
        restart_state=restart_state,
    )


def _map_spiral_func(input_tensors, generate_unitcell):
    return input_tensors[:1], input_tensors[1:]


def optimize_unitcell_full_spiral_vector(
    unitcell,
    spiral_vector,
    expectation_func,
    autosave_filename="data/autosave.hdf5",
    restart_state={},
):
    return optimize_peps_network(
        (unitcell, spiral_vector),
        expectation_func,
        _map_spiral_func,
        autosave_filename=autosave_filename,
        restart_state=restart_state,
    )


def optimize_unitcell_spiral_vector_x_component(
    unitcell,
    spiral_vector_x,
    spiral_vector_fixed_y,
    expectation_func,
    autosave_filename="data/autosave.hdf5",
    restart_state={},
):
    return optimize_peps_network(
        (unitcell, spiral_vector_x),
        expectation_func,
        _map_spiral_func,
        additional_input={"spiral_vectors_y": spiral_vector_fixed_y},
        autosave_filename=autosave_filename,
        restart_state=restart_state,
    )


def optimize_unitcell_spiral_vector_y_component(
    unitcell,
    spiral_vector_fixed_x,
    spiral_vector_y,
    expectation_func,
    autosave_filename="data/autosave.hdf5",
    restart_state={},
):
    return optimize_peps_network(
        (unitcell, spiral_vector_y),
        expectation_func,
        _map_spiral_func,
        additional_input={"spiral_vectors_x": spiral_vector_fixed_x},
        autosave_filename=autosave_filename,
        restart_state=restart_state,
    )


def restart_from_state_file(filename: PathLike):
    with h5py.File(filename, "r") as f:
        unitcell, config = PEPS_Unit_Cell.load_from_group(
            f["unitcell"], return_config=True
        )

        auxiliary_data = PEPS_Unit_Cell.load_auxiliary_data(f["auxiliary_data"])

        grp_restart_data = f["restart_data"]

        grp_expectation_func = grp_restart_data["expectation_func"]
        exp_func_class = grp_expectation_func.attrs["class"]
        if exp_func_class.split(".", maxsplit=1)[0] != "varipeps":
            raise ValueError(
                "Do not support restart from expectation function outside of the library."
            )

        exp_func_module, exp_func_class = exp_func_class.rsplit(".", maxsplit=1)
        exp_func_module = importlib.import_module(exp_func_module)
        exp_func_class = getattr(exp_func_module, exp_func_class)

        exp_func = exp_func_class.load_from_group(grp_expectation_func)

        restart_state = {}

        if grp_restart_data.get("old_gradient") is not None:
            restart_state["old_gradient"] = [
                jnp.asarray(grp_restart_data["old_gradient"][f"old_grad_{i:d}"])
                for i in range(grp_restart_data["old_gradient"].attrs["len"])
            ]
        else:
            restart_state["old_gradient"] = None

        if grp_restart_data.get("old_descent_dir") is not None:
            restart_state["old_descent_dir"] = [
                jnp.asarray(
                    grp_restart_data["old_descent_dir"][f"old_descent_dir_{i:d}"]
                )
                for i in range(grp_restart_data["old_descent_dir"].attrs["len"])
            ]
        else:
            restart_state["old_descent_dir"] = None

        restart_state["best_run"] = auxiliary_data["best_run"]

        if (grp_best_u := grp_restart_data.get("best_unitcell")) is not None:
            restart_state["best_unitcell"] = PEPS_Unit_Cell.load_from_group(grp_best_u)

            restart_state["best_tensors"] = [
                jnp.asarray(grp_restart_data["best_tensors"][f"best_tensor_{i:d}"])
                for i in range(grp_restart_data["best_tensors"].attrs["len"])
            ]

            restart_state["best_value"] = grp_restart_data.attrs["best_value"]

        random_noise_retries = int(grp_restart_data.attrs["random_noise_retries"])
        restart_state["random_noise_retries"] = random_noise_retries
        restart_state["count"] = int(grp_restart_data.attrs["count"])
        restart_state["projector_method"] = grp_restart_data.attrs["projector_method"]
        restart_state["signal_reset_descent_dir"] = grp_restart_data.attrs[
            "signal_reset_descent_dir"
        ]

        restart_state["linesearch_step"] = grp_restart_data.attrs.get("linesearch_step")

        restart_state["max_trunc_error_list"] = {
            k: None for k in range(random_noise_retries + 1)
        }
        restart_state["step_energies"] = {
            k: None for k in range(random_noise_retries + 1)
        }
        restart_state["step_chi"] = {k: None for k in range(random_noise_retries + 1)}
        restart_state["step_conv"] = {k: None for k in range(random_noise_retries + 1)}
        restart_state["step_runtime"] = {
            k: None for k in range(random_noise_retries + 1)
        }

        for k in range(random_noise_retries + 1):
            restart_state["max_trunc_error_list"][k] = list(
                auxiliary_data[f"max_trunc_error_list_{k:d}"]
            )
            restart_state["step_energies"][k] = list(
                auxiliary_data[f"step_energies_{k:d}"]
            )
            restart_state["step_chi"][k] = list(auxiliary_data[f"step_chi_{k:d}"])
            restart_state["step_conv"][k] = list(auxiliary_data[f"step_conv_{k:d}"])
            restart_state["step_runtime"][k] = list(
                auxiliary_data[f"step_runtime_{k:d}"]
            )

        if config.optimizer_method is Optimizing_Methods.BFGS:
            restart_state["bfgs_prefactor"] = grp_restart_data.attrs["bfgs_prefactor"]
            restart_state["bfgs_B_inv"] = jnp.asarray(grp_restart_data["bfgs_B_inv"])
        elif config.optimizer_method is Optimizing_Methods.L_BFGS:
            restart_state["l_bfgs_x_cache"] = [
                [
                    jnp.asarray(grp_restart_data["l_bfgs"][f"x_{i:d}_{j:d}"])
                    for j in range(grp_restart_data["l_bfgs"].attrs["len_elems"])
                ]
                for i in range(grp_restart_data["l_bfgs"].attrs["len"])
            ]
            restart_state["l_bfgs_grad_cache"] = [
                [
                    jnp.asarray(grp_restart_data["l_bfgs"][f"grad_{i:d}_{j:d}"])
                    for j in range(grp_restart_data["l_bfgs"].attrs["len_elems"])
                ]
                for i in range(grp_restart_data["l_bfgs"].attrs["len"])
            ]

        autosave_filename = grp_restart_data.attrs["autosave_filename"]

    varipeps_config.update_from_config_object(config)

    if exp_func.is_spiral_peps:
        spiral_mode = auxiliary_data["spiral_mode"]
        spiral_vector = auxiliary_data["spiral_vector"]

        if spiral_mode == "FIXED":
            return optimize_unitcell_fixed_spiral_vector(
                unitcell,
                spiral_vector,
                exp_func,
                autosave_filename=autosave_filename,
                restart_state=restart_state,
            )
        elif spiral_mode == "BOTH_SAME":
            return optimize_unitcell_full_spiral_vector(
                unitcell,
                spiral_vector[0],
                exp_func,
                autosave_filename=autosave_filename,
                restart_state=restart_state,
            )
        elif spiral_mode == "BOTH_INDEPENDENT":
            return optimize_unitcell_full_spiral_vector(
                unitcell,
                spiral_vector,
                exp_func,
                autosave_filename=autosave_filename,
                restart_state=restart_state,
            )
        elif spiral_mode == "FIXED_X":
            return optimize_unitcell_spiral_vector_y_component(
                unitcell,
                spiral_vector[0],
                spiral_vector[1],
                exp_func,
                autosave_filename=autosave_filename,
                restart_state=restart_state,
            )
        elif spiral_mode == "FIXED_Y":
            return optimize_unitcell_spiral_vector_x_component(
                unitcell,
                spiral_vector[0],
                spiral_vector[1],
                exp_func,
                autosave_filename=autosave_filename,
                restart_state=restart_state,
            )
        else:
            raise ValueError("Unknown mode")

    return optimize_peps_unitcell(
        unitcell,
        exp_func,
        autosave_filename=autosave_filename,
        restart_state=restart_state,
    )