-
Notifications
You must be signed in to change notification settings - Fork 125
Expand file tree
/
Copy pathcls_basic.py
More file actions
1536 lines (1364 loc) · 55.3 KB
/
cls_basic.py
File metadata and controls
1536 lines (1364 loc) · 55.3 KB
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
__all__ = [
"CG",
"CGLS",
"LSQR",
]
import time
from typing import TYPE_CHECKING
import numpy as np
from pylops.optimization.basesolver import Solver, _units
from pylops.optimization.callback import _callback_stop
from pylops.utils.backend import (
get_array_module,
get_module_name,
to_numpy,
to_numpy_conditional,
)
from pylops.utils.typing import NDArray, Tmemunit
if TYPE_CHECKING:
from pylops.linearoperator import LinearOperator
class CG(Solver):
r"""Conjugate gradient
Solve a square system of equations given an operator ``Op`` and
data ``y`` using conjugate gradient iterations.
Parameters
----------
Op : :obj:`pylops.LinearOperator`
Operator to invert of size :math:`[N \times N]`
Attributes
----------
ncp : :obj:`module`
Array module used by the solver (obtained via
:func:`pylops.utils.backend.get_array_module`)
). Available only after ``setup`` is called.
isjax : :obj:`bool`
True if the input data is a JAX array. Available only after
``setup`` is called and updated at each call to ``step``.
r : :obj:`numpy.ndarray`
Residual vector of size :math:`[N \times 1]`. Available only after
``setup`` is called and updated at each call to ``step``.
c : :obj:`numpy.ndarray`
Conjugate direction vector of size :math:`[N \times 1]`. Available
only after ``setup`` is called and updated at each call to ``step``.
c1 : :obj:`numpy.ndarray`
Pre-allocated vector of size :math:`[N \times 1]` used in the
solver when ``preallocate=True``. Available only after ``setup``
is called and updated at each call to ``step``.
kold : :obj:`float`
Squared norm of the residual at previous iteration. Available
only after ``setup`` is called and updated at each call to ``step``.
cost : :obj:`list`
History of the L2 norm of the residual. Available only after
``setup`` is called and updated at each call to ``step``.
iiter : :obj:`int`
Current iteration number. Available only after
``setup`` is called and updated at each call to ``step``.
Notes
-----
Solve the :math:`\mathbf{y} = \mathbf{Op}\,\mathbf{x}` problem using conjugate gradient
iterations [1]_.
.. [1] Hestenes, M R., Stiefel, E., “Methods of Conjugate Gradients for Solving
Linear Systems”, Journal of Research of the National Bureau of Standards.
vol. 49. 1952.
"""
def _print_setup(self, xcomplex: bool = False) -> None:
self._print_solver(nbar=55)
if self.niter is not None:
strpar = f"tol = {self.tol:10e}\tniter = {self.niter}"
else:
strpar = f"tol = {self.tol:10e}"
print(strpar)
print("-" * 55 + "\n")
if not xcomplex:
head1 = " Itn x[0] r2norm"
else:
head1 = " Itn x[0] r2norm"
print(head1)
def _print_step(self, x: NDArray) -> None:
strx = f"{x[0]:1.2e} " if np.iscomplexobj(x) else f"{x[0]:11.4e} "
msg = f"{self.iiter:6g} " + strx + f"{self.cost[self.iiter]:11.4e}"
print(msg)
def memory_usage(
self,
show: bool = False,
unit: Tmemunit = "B",
) -> float:
"""Compute memory usage of the solver
Parameters
----------
show : :obj:`bool`, optional
Display memory usage
unit: :obj:`str`, optional
Unit used to display memory usage (
``B``, ``KB``, ``MB`` or ``GB``)
Returns
-------
memuse :obj:`float`
Memory usage in Bytes
"""
# Get number of bytes of dtype used in the solver
nbytes = np.dtype(self.Op.dtype).itemsize
# Setup: x0 - y, self.r, self.c
memuse = (self.Op.shape[1] + 3 * self.Op.shape[0]) * nbytes
# Step (additional variables to those in setup): c1 - Opc
memuse += (self.Op.shape[1] + self.Op.shape[0]) * nbytes
if show:
print(f"CG predicted memory usage: {memuse / _units[unit]:.2f} {unit}")
return memuse
def setup(
self,
y: NDArray,
x0: NDArray | None = None,
niter: int | None = None,
tol: float = 1e-4,
preallocate: bool = False,
show: bool = False,
) -> NDArray:
r"""Setup solver
Parameters
----------
y : :obj:`numpy.ndarray`
Data of size :math:`[N \times 1]`
x0 : :obj:`numpy.ndarray`, optional
Initial guess of size :math:`[N \times 1]`. If ``None``, initialize
internally as zero vector
niter : :obj:`int`, optional
Number of iterations (default to ``None`` in case a user wants to
manually step over the solver)
tol : :obj:`float`, optional
Absolute tolerance on residual norm. Stops the solver when the
residual norm is below this value.
preallocate : :obj:`bool`, optional
.. versionadded:: 2.6.0
Pre-allocate all variables used by the solver. Note that if ``y``
is a JAX array, this option is ignored and variables are not
pre-allocated since JAX does not support in-place operations.
show : :obj:`bool`, optional
Display setup log
Returns
-------
x : :obj:`numpy.ndarray`
Initial guess of size :math:`[N \times 1]`
"""
self.y = y
self.niter = niter
self.tol = tol
self.ncp = get_array_module(y)
self.isjax = get_module_name(self.ncp) == "jax"
self._setpreallocate(preallocate)
# initialize solver
if x0 is None:
x = self.ncp.zeros(self.Op.shape[1], dtype=self.y.dtype)
self.r = self.y.copy()
else:
x = x0.copy()
if not self.preallocate:
self.r = self.y - self.Op.matvec(x)
else:
self.r = self.ncp.empty_like(self.y)
self.ncp.subtract(self.y, self.Op.matvec(x), out=self.r)
self.c = self.r.copy()
self.kold = self.ncp.abs(self.r.dot(self.r.conj()))
# initialize other internal variabled
if self.preallocate:
self.c1 = self.ncp.empty_like(x)
# create variables to track the residual norm and iterations
self.cost: list = []
self.cost.append(float(np.sqrt(self.kold)))
self.iiter = 0
# print setup
if show:
self._print_setup(np.iscomplexobj(x))
return x
def step(self, x: NDArray, show: bool = False) -> NDArray:
r"""Run one step of solver
Parameters
----------
x : :obj:`numpy.ndarray`
Current model vector to be updated by a step of CG
show : :obj:`bool`, optional
Display iteration log
Returns
-------
x : :obj:`numpy.ndarray`
Updated model vector
"""
Opc = self.Op.matvec(self.c)
cOpc = self.ncp.abs(self.c.dot(Opc.conj()))
a = self.kold / cOpc
if not self.preallocate:
x += a * self.c
self.r -= a * Opc
else:
self.ncp.multiply(self.c, a, out=self.c1)
self.ncp.add(x, self.c1, out=x)
self.ncp.multiply(Opc, a, out=Opc)
self.ncp.subtract(self.r, Opc, out=self.r)
k = self.ncp.abs(self.r.dot(self.r.conj()))
b = k / self.kold
if not self.preallocate:
self.c = self.r + b * self.c
else:
self.ncp.multiply(self.c, b, out=self.c)
self.ncp.add(self.c, self.r, out=self.c)
self.kold = k
self.iiter += 1
self.cost.append(float(np.sqrt(self.kold)))
if show:
self._print_step(x)
return x
def run(
self,
x: NDArray,
niter: int | None = None,
show: bool = False,
itershow: tuple[int, int, int] = (10, 10, 10),
) -> NDArray:
r"""Run solver
Parameters
----------
x : :obj:`numpy.ndarray`
Current model vector to be updated by multiple steps of CG
niter : :obj:`int`, optional
Number of iterations. Can be set to ``None`` if already
provided in the setup call
show : :obj:`bool`, optional
Display logs
itershow : :obj:`tuple`, optional
Display set log for the first N1 steps, last N2 steps,
and every N3 steps in between where N1, N2, N3 are the
three element of the list.
Returns
-------
x : :obj:`numpy.ndarray`
Estimated model of size :math:`[M \times 1]`
"""
niter = self.niter if niter is None else niter
if niter is None:
msg = "`niter` must not be None"
raise ValueError(msg)
while self.iiter < niter and self.kold > self.tol:
showstep = (
True
if show
and (
self.iiter < itershow[0]
or niter - self.iiter < itershow[1]
or self.iiter % itershow[2] == 0
)
else False
)
x = self.step(x, showstep)
self.callback(x)
# check if any callback has raised a stop flag
stop = _callback_stop(self.callbacks)
if stop:
break
return x
def finalize(self, show: bool = False) -> None:
r"""Finalize solver
Parameters
----------
show : :obj:`bool`, optional
Display finalize log
"""
self.tend = time.time()
self.telapsed = self.tend - self.tstart
self.cost = np.array(self.cost)
if show:
self._print_finalize(nbar=55)
def solve(
self,
y: NDArray,
x0: NDArray | None = None,
niter: int = 10,
tol: float = 1e-4,
preallocate: bool = False,
show: bool = False,
itershow: tuple[int, int, int] = (10, 10, 10),
) -> tuple[NDArray, int, NDArray]:
r"""Run entire solver
Parameters
----------
y : :obj:`numpy.ndarray`
Data of size :math:`[N \times 1]`
x0 : :obj:`numpy.ndarray`, optional
Initial guess of size :math:`[N \times 1]`. If ``None``, initialize
internally as zero vector
niter : :obj:`int`, optional
Number of iterations
tol : :obj:`float`, optional
Absolute tolerance on residual norm. Stops the solver when the
residual norm is below this value.
preallocate : :obj:`bool`, optional
.. versionadded:: 2.6.0
Pre-allocate all variables used by the solver. Note that if ``y``
is a JAX array, this option is ignored and variables are not
pre-allocated since JAX does not support in-place operations.
show : :obj:`bool`, optional
Display logs
itershow : :obj:`tuple`, optional
Display set log for the first N1 steps, last N2 steps,
and every N3 steps in between where N1, N2, N3 are the
three element of the list.
Returns
-------
x : :obj:`numpy.ndarray`
Estimated model of size :math:`[N \times 1]`
iit : :obj:`int`
Number of executed iterations
cost : :obj:`numpy.ndarray`
History of the L2 norm of the residual
"""
x = self.setup(
y=y, x0=x0, niter=niter, tol=tol, preallocate=preallocate, show=show
)
x = self.run(x, niter, show=show, itershow=itershow)
self.finalize(show)
return x, self.iiter, self.cost
class CGLS(Solver):
r"""Conjugate gradient least squares
Solve an overdetermined system of equations given an operator ``Op`` and
data ``y`` using conjugate gradient iterations.
Parameters
----------
Op : :obj:`pylops.LinearOperator`
Operator to invert of size :math:`[N \times M]`
Attributes
----------
ncp : :obj:`module`
Array module used by the solver (obtained via
:func:`pylops.utils.backend.get_array_module`)
). Available only after ``setup`` is called.
isjax : :obj:`bool`
True if the input data is a JAX array. Available only after
``setup`` is called and updated at each call to ``step``.
s : :obj:`numpy.ndarray`
Temporary vector of size :math:`[N \times 1]`. Available only after
``setup`` is called and updated at each call to ``step``.
c : :obj:`numpy.ndarray`
Conjugate direction vector of size :math:`[N \times 1]`. Available
only after ``setup`` is called and updated at each call to ``step``.
q : :obj:`numpy.ndarray`
Temporary vector of size :math:`[M \times 1]`. Available only after
``setup`` is called and updated at each call to ``step``.
c1 : :obj:`numpy.ndarray`
Pre-allocated vector of size :math:`[N \times 1]` used in the
solver when ``preallocate=True``. Available only after ``setup``
is called and updated at each call to ``step``.
x1 : :obj:`numpy.ndarray`
Pre-allocated vector of size :math:`[M \times 1]` used in the
solver when ``preallocate=True``. Available only after ``setup``
is called and updated at each call to ``step``.
r : :obj:`numpy.ndarray`
Residual vector of size :math:`[N \times 1]` used in the
solver when ``preallocate=True``. Available only after ``setup``
is called and updated at each call to ``step``.
kold : :obj:`float`
Squared norm of the residual at previous iteration. Available
only after ``setup`` is called and updated at each call to ``step``.
cost : :obj:`list`
History of the L2 norm of the residual. Available only after
``setup`` is called and updated at each call to ``step``.
cost1 : :obj:`list`
History of the L2 norm of the entire objective function (residual
plus regularization). Available only after
``setup`` is called and updated at each call to ``step``.
iiter : :obj:`int`
Current iteration number. Available only after
``setup`` is called and updated at each call to ``step``.
Notes
-----
Minimize the following functional using conjugate gradient iterations:
.. math::
J = || \mathbf{y} - \mathbf{Op}\,\mathbf{x} ||_2^2 +
\epsilon^2 || \mathbf{x} ||_2^2
where :math:`\epsilon` is the damping coefficient.
"""
def _print_setup(self, xcomplex: bool = False) -> None:
self._print_solver(nbar=65)
if self.niter is not None:
strpar = (
f"damp = {self.damp:10e}\ttol = {self.tol:10e}\tniter = {self.niter}"
)
else:
strpar = f"damp = {self.damp:10e}\ttol = {self.tol:10e}\t"
print(strpar)
print("-" * 65 + "\n")
if not xcomplex:
head1 = " Itn x[0] r1norm r2norm"
else:
head1 = " Itn x[0] r1norm r2norm"
print(head1)
def _print_step(self, x: NDArray) -> None:
strx = f"{x[0]:1.2e} " if np.iscomplexobj(x) else f"{x[0]:11.4e} "
msg = (
f"{self.iiter:6g} "
+ strx
+ f"{self.cost[self.iiter]:11.4e} {self.cost1[self.iiter]:11.4e}"
)
print(msg)
def memory_usage(
self,
show: bool = False,
unit: Tmemunit = "B",
) -> float:
"""Compute memory usage of the solver
Parameters
----------
show : :obj:`bool`, optional
Display memory usage
unit: :obj:`str`, optional
Unit used to display memory usage (
``B``, ``KB``, ``MB`` or ``GB``)
Returns
-------
memuse :obj:`float`
Memory usage in Bytes
"""
# Get number of bytes of dtype used in the solver
nbytes = np.dtype(self.Op.dtype).itemsize
# Setup: x0, self.c - y, self.s, self.q
memuse = (2 * self.Op.shape[1] + 3 * self.Op.shape[0]) * nbytes
# Step (additional variables to those in setup): r, x1, c1
memuse += (3 * self.Op.shape[1]) * nbytes
if show:
print(f"CGLS predicted memory usage: {memuse / _units[unit]:.2f} {unit}")
return memuse
def setup(
self,
y: NDArray,
x0: NDArray | None = None,
niter: int | None = None,
damp: float = 0.0,
tol: float = 1e-4,
preallocate: bool = False,
show: bool = False,
) -> NDArray:
r"""Setup solver
Parameters
----------
y : :obj:`numpy.ndarray`
Data of size :math:`[N \times 1]`
x0 : :obj:`numpy.ndarray`, optional
Initial guess of size :math:`[M \times 1]`. If ``None``, initialize
internally as zero vector
niter : :obj:`int`, optional
Number of iterations (default to ``None`` in case a user wants to
manually step over the solver)
damp : :obj:`float`, optional
Damping coefficient
tol : :obj:`float`, optional
Absolute tolerance on residual norm. Stops the solver when the
residual norm is below this value.
preallocate : :obj:`bool`, optional
.. versionadded:: 2.6.0
Pre-allocate all variables used by the solver. Note that if ``y``
is a JAX array, this option is ignored and variables are not
pre-allocated since JAX does not support in-place operations.
show : :obj:`bool`, optional
Display setup log
Returns
-------
x : :obj:`numpy.ndarray`
Initial guess of size :math:`[N \times 1]`
"""
self.y = y
self.damp = damp**2.0
self.tol = tol
self.niter = niter
self.ncp = get_array_module(y)
self.isjax = get_module_name(self.ncp) == "jax"
self._setpreallocate(preallocate)
# initialize solver
if x0 is None:
x = self.ncp.zeros(self.Op.shape[1], dtype=y.dtype)
self.s = self.y.copy()
self.c = self.Op.rmatvec(self.s)
else:
x = x0.copy()
if not self.preallocate:
self.s = self.y - self.Op.matvec(x)
self.c = self.Op.rmatvec(self.s) - damp * x
else:
self.s = self.ncp.empty_like(self.y)
self.ncp.subtract(self.y, self.Op.matvec(x), out=self.s)
x1 = self.ncp.empty_like(x)
self.c = self.ncp.empty_like(x)
self.ncp.multiply(x, damp, out=x1)
self.ncp.subtract(self.Op.rmatvec(self.s), x1, out=self.c)
self.q = self.Op.matvec(self.c)
self.kold = self.ncp.abs(self.c.dot(self.c.conj()))
# initialize other internal variables
if self.preallocate:
self.c1 = self.ncp.empty_like(self.c)
self.x1 = self.ncp.empty_like(x)
self.r = self.ncp.empty_like(x)
# create variables to track the residual norm and iterations
self.cost = []
self.cost1 = []
self.cost.append(float(self.ncp.linalg.norm(self.s)))
self.cost1.append(
float(
self.ncp.sqrt(
self.cost[0] ** 2.0 + damp * self.ncp.abs(x.dot(x.conj()))
)
)
)
self.iiter = 0
# print setup
if show:
self._print_setup(np.iscomplexobj(x))
return x
def step(self, x: NDArray, show: bool = False) -> NDArray:
r"""Run one step of solver
Parameters
----------
x : :obj:`numpy.ndarray`
Current model vector to be updated by a step of CG
show : :obj:`bool`, optional
Display iteration log
"""
a = self.kold / (
self.q.dot(self.q.conj()) + self.damp * self.c.dot(self.c.conj())
)
if not self.preallocate:
x = x + a * self.c
self.s = self.s - a * self.q
r = self.Op.rmatvec(self.s) - self.damp * x
else:
self.ncp.multiply(self.c, a, out=self.c1)
self.ncp.add(x, self.c1, out=x)
self.ncp.multiply(self.q, a, out=self.q)
self.ncp.subtract(self.s, self.q, out=self.s)
self.ncp.multiply(x, self.damp, out=self.x1)
self.ncp.subtract(
self.Op.rmatvec(self.s),
self.x1,
out=self.r,
)
k = self.ncp.abs(
self.r.dot(self.r.conj()) if self.preallocate else r.dot(r.conj())
)
b = k / self.kold
if not self.preallocate:
self.c = r + b * self.c
else:
self.ncp.multiply(self.c, b, out=self.c)
self.ncp.add(self.c, self.r, out=self.c)
self.q = self.Op.matvec(self.c)
self.kold = k
self.iiter += 1
self.cost.append(float(self.ncp.linalg.norm(self.s)))
self.cost1.append(
self.ncp.sqrt(
float(
self.cost[self.iiter] ** 2.0
+ self.damp * self.ncp.abs(x.dot(x.conj()))
)
)
)
if show:
self._print_step(x)
return x
def run(
self,
x: NDArray,
niter: int | None = None,
show: bool = False,
itershow: tuple[int, int, int] = (10, 10, 10),
) -> NDArray:
r"""Run solver
Parameters
----------
x : :obj:`numpy.ndarray`
Current model vector to be updated by multiple steps of CGLS
niter : :obj:`int`, optional
Number of iterations. Can be set to ``None`` if already
provided in the setup call
show : :obj:`bool`, optional
Display iterations log
itershow : :obj:`tuple`, optional
Display set log for the first N1 steps, last N2 steps,
and every N3 steps in between where N1, N2, N3 are the
three element of the list.
Returns
-------
x : :obj:`numpy.ndarray`
Estimated model of size :math:`[M \times 1]`
"""
self.niter = self.niter if niter is None else niter
if self.niter is None:
msg = "`niter` must not be None"
raise ValueError(msg)
while self.iiter < self.niter and self.kold > self.tol:
showstep = (
True
if show
and (
self.iiter < itershow[0]
or self.niter - self.iiter < itershow[1]
or self.iiter % itershow[2] == 0
)
else False
)
x = self.step(x, showstep)
self.callback(x)
# check if any callback has raised a stop flag
stop = _callback_stop(self.callbacks)
if stop:
break
return x
def finalize(self, show: bool = False) -> None:
r"""Finalize solver
Parameters
----------
show : :obj:`bool`, optional
Display finalize log
"""
self.tend = time.time()
self.telapsed = self.tend - self.tstart
# reason for termination
if self.kold < self.tol:
self.istop = 1
elif self.iiter >= self.niter:
self.istop = 2
else:
self.istop = 3
self.r1norm = self.kold
self.r2norm = self.cost1[self.iiter]
if show:
self._print_finalize(nbar=65)
self.cost = np.array(self.cost)
def solve(
self,
y: NDArray,
x0: NDArray | None = None,
niter: int = 10,
damp: float = 0.0,
tol: float = 1e-4,
preallocate: bool = False,
show: bool = False,
itershow: tuple[int, int, int] = (10, 10, 10),
) -> tuple[NDArray, int, int, float, float, NDArray]:
r"""Run entire solver
Parameters
----------
y : :obj:`numpy.ndarray`
Data of size :math:`[N \times 1]`
x0 : :obj:`numpy.ndarray`
Initial guess of size :math:`[M \times 1]`. If ``None``, initialize
internally as zero vector
niter : :obj:`int`, optional
Number of iterations (default to ``None`` in case a user wants to
manually step over the solver)
damp : :obj:`float`, optional
Damping coefficient
tol : :obj:`float`, optional
Absolute tolerance on residual norm. Stops the solver when the
residual norm is below this value.
preallocate : :obj:`bool`, optional
.. versionadded:: 2.6.0
Pre-allocate all variables used by the solver. Note that if ``y``
is a JAX array, this option is ignored and variables are not
pre-allocated since JAX does not support in-place operations.
show : :obj:`bool`, optional
Display logs
itershow : :obj:`tuple`, optional
Display set log for the first N1 steps, last N2 steps,
and every N3 steps in between where N1, N2, N3 are the
three element of the list.
Returns
-------
x : :obj:`numpy.ndarray`
Estimated model of size :math:`[M \times 1]`
istop : :obj:`int`
Gives the reason for termination
``1`` means :math:`\mathbf{x}` is an approximate solution to
:math:`\mathbf{y} = \mathbf{Op}\,\mathbf{x}` with the provided
tolerance ``tol``
``2`` means :math:`\mathbf{x}` approximately solves the least-squares
problem (reached the maximum number of iterations ``niter``)
``3`` means another stopping criterion implemented via a callback
was reached
iit : :obj:`int`
Iteration number upon termination
r1norm : :obj:`float`
:math:`||\mathbf{r}||_2`, where
:math:`\mathbf{r} = \mathbf{y} - \mathbf{Op}\,\mathbf{x}`
r2norm : :obj:`float`
:math:`\sqrt{\mathbf{r}^T\mathbf{r} +
\epsilon^2 \mathbf{x}^T\mathbf{x}}`.
Equal to ``r1norm`` if :math:`\epsilon=0`
cost : :obj:`numpy.ndarray`, optional
History of r1norm through iterations
"""
x = self.setup(
y=y,
x0=x0,
niter=niter,
damp=damp,
tol=tol,
preallocate=preallocate,
show=show,
)
x = self.run(x, niter, show=show, itershow=itershow)
self.finalize(show)
return x, self.istop, self.iiter, self.r1norm, self.r2norm, self.cost
class LSQR(Solver):
r"""LSQR
Solve an overdetermined system of equations given an operator ``Op`` and
data ``y`` using LSQR iterations.
.. math::
\DeclareMathOperator{\cond}{cond}
Parameters
----------
Op : :obj:`pylops.LinearOperator`
Operator to invert of size :math:`[N \times M]`
Attributes
----------
ncp : :obj:`module`
Array module used by the solver (obtained via
:func:`pylops.utils.backend.get_array_module`)
). Available only after ``setup`` is called.
isjax : :obj:`bool`
True if the input data is a JAX array. Available only after
``setup`` is called and updated at each call to ``step``.
var : :obj:`numpy.ndarray` or :obj:`None`
Variance vector of size :math:`[M \times 1]`. Available only after
``setup`` is called and updated at each call to ``step``. Set to
``None`` if ``calc_var=False``.
istop : :obj:`int`
Gives the reason for termination. Available only after ``setup`` is
called and updated at each call to ``step``.
ctol : :obj:`float`
Tolerance on the condition number of the augmented system (defined as
reciprocal of ``conlim`). Available only after ``setup`` is called
and updated at each call to ``step``.
anorm : :obj:`float`
Estimate of Frobenius norm of :math:`\overline{\mathbf{Op}} =
[\mathbf{Op} \; \epsilon \mathbf{I}]`. Available only after ``setup`` is
called and updated at each call to ``step``.
acond : :obj:`float`
Estimate of :math:`\cond(\overline{\mathbf{Op}})`. Available only after ``setup`` is
called and updated at each call to ``step``.
arnorm : :obj:`float`
Estimate of norm of :math:`\cond(\mathbf{Op}^H\mathbf{r}-
\epsilon^2\mathbf{x})`. Available only after ``step`` is
called for the first time and updated at each subsequent call to ``step``.
xnorm : :obj:`float`
:math:`||\mathbf{x}||_2`. Available only after ``setup`` is
called and updated at each call to ``step``.
u : :obj:`numpy.ndarray`
Temporary vector of size :math:`[N \times 1]`. Available only after
``setup`` is called and updated at each call to ``step``.
v : :obj:`numpy.ndarray`
Temporary vector of size :math:`[M \times 1]`. Available only after
``setup`` is called and updated at each call to ``step``.
w : :obj:`numpy.ndarray`
Temporary vector of size :math:`[M \times 1]`. Available only after
``setup`` is called and updated at each call to ``step``.
dk : :obj:`numpy.ndarray`
Temporary vector of size :math:`[M \times 1]`. Available only after
``setup`` is called and updated at each call to ``step``.
w1 : :obj:`numpy.ndarray`
Temporary vector of size :math:`[M \times 1]`. Available only after
``setup`` is called and updated at each call to ``step``.
alfa : :obj:`float`
:math:`\alpha` parameter of the bidiagonalization process. Available only
after ``setup`` is called and updated at each call to ``step``.
beta : :obj:`float`
:math:`\beta` parameter of the bidiagonalization process. Available only
after ``setup`` is called and updated at each call to ``step``.
arnorm0 : :obj:`float`
Initial value of ``arnorm``. Available only after ``setup`` is
called.
rhobar : :obj:`float`
Parameter of the QR factorization of the bidiagonal matrix.
Available only after ``setup`` is called and updated at each
call to ``step``.
phibar : :obj:`float`
Parameter of the QR factorization of the bidiagonal matrix.
Available only after ``setup`` is called and updated at each
call to ``step``.
bnorm : :obj:`float`
:math:`||\mathbf{y}||_2`. Available only after ``setup`` is
called and updated at each call to ``step``.
rnorm : :obj:`float`
:math:`||\mathbf{r}||_2`. Available only after ``setup`` is
called and updated at each call to ``step``.
r1norm : :obj:`float`
:math:`||\mathbf{r}||_2`, where
:math:`\mathbf{r} = \mathbf{y} - \mathbf{Op}\,\mathbf{x}`. Available only after
``setup`` is called and updated at each call to ``step``.
r2norm : :obj:`float`
:math:`\sqrt{\mathbf{r}^T\mathbf{r} + \epsilon^2 \mathbf{x}^T\mathbf{x}}`.
Equal to ``r1norm`` if :math:`\epsilon=0`. Available only after
``setup`` is called and updated at each call to ``step``.
cost : :obj:`numpy.ndarray`, optional
History of r1norm through iterations
iiter : :obj:`int`
Current iteration number. Available only after
``setup`` is called and updated at each call to ``step``.
Notes
-----
Minimize the following functional using LSQR iterations [1]_:
.. math::
J = || \mathbf{y} - \mathbf{Op}\,\mathbf{x} ||_2^2 +
\epsilon^2 || \mathbf{x} ||_2^2
where :math:`\epsilon` is the damping coefficient.
.. [1] Paige, C. C., and Saunders, M. A. "LSQR: An algorithm for sparse
linear equations and sparse least squares", ACM TOMS, vol. 8, pp. 43-71,
1982.
"""
def __init__(self, Op: "LinearOperator"):
super().__init__(Op)
self.msg = (
"The exact solution is x = 0 ",
"Op x - b is small enough, given atol, btol ",
"The least-squares solution is good enough, given atol ",
"The estimate of cond(Opbar) has exceeded conlim ",
"Op x - b is small enough for this machine ",
"The least-squares solution is good enough for this machine",
"Cond(Opbar) seems to be too large for this machine ",
"The iteration limit has been reached ",
)
def _print_setup(self, x: NDArray, xcomplex: bool = False) -> None:
self._print_solver(nbar=90)
print(f"damp = {self.damp:20.14e} calc_var = {self.calc_var:6g}")
print(f"atol = {self.atol:8.2e} conlim = {self.conlim:8.2e}")
if self.niter is not None:
strpar = f"btol = {self.btol:8.2e} niter = {self.niter:8g}"
else:
strpar = f"btol = {self.btol:8.2e}"
print(strpar)
print("-" * 90)
head2 = " Compatible LS Norm A Cond A"
if not xcomplex:
head1 = " Itn x[0] r1norm r2norm "
else:
head1 = " Itn x[0] r1norm r2norm "
print(head1 + head2)
test1: int = 1
test2: float = self.alfa / self.beta
strx: str = f"{x[0]:1.2e} " if np.iscomplexobj(x) else f"{x[0]:11.4e}"
str1: str = f"{0:6g} " + strx
str2: str = f" {self.r1norm:10.3e} {self.r2norm:10.3e}"
str3: str = f" {test1:8.1e} {test2:8.1e}"
print(str1 + str2 + str3)
def _print_step(self, x: NDArray) -> None:
strx = f"{x[0]:1.2e} " if np.iscomplexobj(x) else f"{x[0]:11.4e}"
str1 = f"{self.iiter:6g} " + strx
str2 = f" {self.r1norm:10.3e} {self.r2norm:10.3e}"
str3 = f" {self.test1:8.1e} {self.test2:8.1e}"
str4 = f" {self.anorm:8.1e} {self.acond:8.1e}"
print(str1 + str2 + str3 + str4)
def _print_finalize(self) -> None:
print(" ")
print(f"LSQR finished, {self.msg[self.istop]}")
print(" ")
str1 = f"istop ={self.istop:8g} r1norm ={self.r1norm:8.1e}"
str2 = f"anorm ={self.anorm:8.1e} arnorm ={self.arnorm:8.1e}"
str3 = f"itn ={self.iiter:8g} r2norm ={self.r2norm:8.1e}"
str4 = f"acond ={self.acond:8.1e} xnorm ={self.xnorm:8.1e}"
str5 = f"Total time (s) = {self.telapsed:.2f}"
print(str1 + " " + str2)
print(str3 + " " + str4)
print(str5)
print("-" * 90 + "\n")
def memory_usage(
self,
show: bool = False,
unit: Tmemunit = "B",
) -> float:
"""Compute memory usage of the solver
Parameters
----------
show : :obj:`bool`, optional
Display memory usage
unit: :obj:`str`, optional
Unit used to display memory usage (
``B``, ``KB``, ``MB`` or ``GB``)
Returns
-------