-
Notifications
You must be signed in to change notification settings - Fork 4
/
Copy pathlapackdrivers.pyx
1745 lines (1350 loc) · 65.4 KB
/
lapackdrivers.pyx
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
# -*- coding: utf-8 -*-
#
# Set Cython compiler directives. This section must appear before any code!
#
# For available directives, see:
#
# http://docs.cython.org/en/latest/src/reference/compilation.html
#
# cython: wraparound = False
# cython: boundscheck = False
# cython: cdivision = True
#
"""Simple Python interface to LAPACK for solving many independent linear equation systems efficiently in parallel. Built on top of scipy.linalg.cython_lapack.
Some scaling (preconditioning) routines are also provided, including two symmetry-preserving iterative algorithms.
This module:
- adds OpenMP parallelization for independent problem instances on top of SciPy's Cython-level LAPACK interface,
- makes it convenient to solve with many LHSs, also in parallel
- hides practical details such as creation/destruction of work arrays, making the interface simple to use.
Two interfaces are provided:
- a simple Python interface using Cython memoryviews (compatible with np.arrays)
- a low-level C interface using raw pointers and explicit sizes (useful for cimport'ing from other Cython modules)
Note that cython_lapack already converts LAPACK errors into Python exceptions; we simply pass them through.
** IMPORTANT **
- Real-valued data only (dtype np.float64)
- Compatible with Fortran-contiguous arrays only! (so pass order='F' when creating np.arrays to use with this)
- Fast, not safe; be sure to provide correct sizes etc.!
Naming scheme (in shellglob notation):
*s = multiple RHS (but with the same LHS for all).
These are one-shot deals that reuse the matrix factorization internally.
However, the pivot information is not returned, so the matrix A
is destroyed (overwritten) during the call.
m* = multiple LHS (a separate single RHS for each)
These simply loop over the problem instances.
*p = parallel (multi-threaded using OpenMP)
These introduce parallel looping over problem instances.
*factor* = the routine that factors the matrix and generates pivot information.
*factored* = the solver routine that uses the factored matrix and pivot information.
The factoring routines are useful for solving with many RHSs, when all the RHSs are not available at once
(e.g. in PDE solvers, timestepping with a mass matrix that remains constant in time).
See the function docstrings for details.
JJ 2016-10-07
"""
from __future__ import division, print_function, absolute_import
cimport cython
cimport cython.parallel
cimport openmp
from libc.math cimport sqrt
from libc.math cimport fabs as c_abs
from libc.stdlib cimport malloc, free
import numpy as np
# triangular solver
from scipy.linalg.cython_lapack cimport dgtsv
# symmetric solver
from scipy.linalg.cython_lapack cimport dsysv, dsytrf, dsytrs
# general solver
from scipy.linalg.cython_lapack cimport dgesv, dgetrf, dgetrs
# other routines
from scipy.linalg.cython_lapack cimport dgeequ, dgesvd
# fast inline min/max for C code
#
cdef inline int cimin(int a, int b) nogil:
return a if a < b else b
cdef inline int cimax(int a, int b) nogil:
return a if a > b else b
##############################################################################################################
# Parallelization helper
##############################################################################################################
def distribute_items( int nitems, int ntasks ): # Python wrapper
"""def distribute_items( int nitems, int ntasks ):
Distribute work items (numbered 0, 1, ..., nitems-1) across ntasks tasks, assuming equal workload per item.
"""
cdef int[::1] blocksizes = np.empty( (ntasks,), dtype=np.int32 )
cdef int[::1] baseidxs = np.empty( (ntasks,), dtype=np.int32 )
distribute_items_c( nitems, ntasks, &blocksizes[0], &baseidxs[0] ) # ntasks usually very small, no point in "with nogil:"
return (blocksizes, baseidxs)
# nitems : in, number of items
# ntasks : in, number of tasks
# blocksizes : out, an array of size (ntasks,) containing the number of items for each task
# baseidxs : out, an array of size (ntasks,) containing the index of the first item for each task
#
# All arrays must be allocated by caller!
#
cdef void distribute_items_c( int nitems, int ntasks, int* blocksizes, int* baseidxs ) nogil: # C implementation
cdef int baseblocksize = nitems // ntasks # how many items per task
cdef int remainder = nitems % ntasks
if baseblocksize == 0: # no whole blocks?
ntasks = remainder
cdef int k
for k in range(ntasks):
blocksizes[k] = baseblocksize
if k < remainder:
blocksizes[k] += 1 # distribute the remainder across the first tasks
baseidxs[0] = 0
for k in range(1,ntasks):
baseidxs[k] = baseidxs[k-1] + blocksizes[k-1]
##############################################################################################################
# Matrix handling helpers
##############################################################################################################
def copygeneral( double[::1,:] O, double[::1,:] I ):
"""def copygeneral( double[::1,:] O, double[::1,:] I ):
Copy a Fortran-contiguous rank-2 array I into a Fortran-contiguous rank-2 array O.
O must have the same shape as I, and must have been allocated by the caller.
"""
cdef int ncols=I.shape[0], nrows=I.shape[1]
with nogil:
copygeneral_c( &O[0,0], &I[0,0], nrows, ncols )
cdef void copygeneral_c( double* O, double* I, int nrows, int ncols ) nogil:
cdef int nelems=ncols*nrows
cdef int e # element storage offset as counted from the beginning of the matrix
for e in range(nelems): # TODO: maybe we could even memcpy(&O[0], &I[0], nelems*sizeof(double))?
O[e] = I[e]
def copysymmu( double[::1,:] O, double[::1,:] I ):
"""def copysymmu( double[::1,:] O, double[::1,:] I ):
Copy the upper triangle (including the diagonal) of a square Fortran-contiguous rank-2 array I into a square Fortran-contiguous rank-2 array O.
The strict lower triangles of I and O are not referenced.
O must have the same shape as I, and must have been allocated by the caller.
"""
cdef int ncols=I.shape[0], nrows=I.shape[1]
with nogil:
copysymmu_c( &O[0,0], &I[0,0], nrows, ncols )
cdef void copysymmu_c( double* O, double* I, int nrows, int ncols ) nogil:
cdef int j, i, colbaseidx, e
for j in range(ncols): # column
colbaseidx = j*nrows
# general rectangular array would need range(min(j+1, m)), we skip the min since we need this to work for square arrays only
for i in range(j+1): # row - handle the upper triangular part only (since A is symmetric and the lower triangle is not used)
e = colbaseidx + i # element storage offset as counted from the beginning of the matrix
O[e] = I[e]
def symmetrize( double[::1,:] A ):
"""def symmetrize( double[::1,:] A ):
Symmetrize a square Fortran-contiguous rank-2 array in-place.
This is a fast Cython implementation of:
A = 0.5 * (A + A.T)
"""
cdef int ncols=A.shape[0], nrows=A.shape[1] # cols, rows
with nogil:
symmetrize_c( &A[0,0], nrows, ncols )
cdef void symmetrize_c( double* A, int nrows, int ncols ) nogil:
cdef int i, j
cdef double tmp
# loop over strict upper triangle only
for j in range(1,ncols): # column
for i in range(j): # row
tmp = 0.5 * (A[i + j*nrows] + A[j + i*nrows]) # A[i,j] + A[j,i]
A[i + j*nrows] = tmp
A[j + i*nrows] = tmp
def msymmetrize( double[::1,:,:] A ):
"""def msymmetrize( double[::1,:,:] A ):
Symmetrize many square Fortran-contiguous arrays in-place, single-threaded.
A : a Fortran-contiguous rank-3 array, shape (N,n,n).
This is a fast Cython implementation of:
for j in range(N):
A[j,:,:] = 0.5 * (A[j,:,:] + A[j,:,:].T)
"""
cdef int ncols=A.shape[0], nrows=A.shape[1], nlhs=A.shape[2] # cols, rows, arrays
with nogil:
msymmetrize_c( &A[0,0,0], nrows, ncols, nlhs )
cdef void msymmetrize_c( double* A, int nrows, int ncols, int nlhs ) nogil:
cdef int nelems=nrows*ncols
cdef int i, j, k
cdef double tmp
for k in range(nlhs):
# loop over strict upper triangle only
for j in range(1,ncols): # column
for i in range(j): # row
tmp = 0.5 * ( A[i + nrows*j + nelems*k] + A[j + nrows*i + nelems*k] ) # A[i,j,k] + A[j,i,k]
A[i + nrows*j + nelems*k] = tmp
A[j + nrows*i + nelems*k] = tmp
def msymmetrizep( double[::1,:,:] A, int ntasks ):
"""def msymmetrizep( double[::1,:,:] A, int ntasks ):
Symmetrize many square Fortran-contiguous arrays in-place, multi-threaded.
A : a Fortran-contiguous rank-3 array, shape (N,n,n).
ntasks : number of threads for OpenMP
"""
cdef int ncols=A.shape[0], nrows=A.shape[1], nlhs=A.shape[2] # cols, rows, arrays
with nogil:
msymmetrizep_c( &A[0,0,0], nrows, ncols, nlhs, ntasks )
cdef void msymmetrizep_c( double* A, int nrows, int ncols, int nlhs, int ntasks ) nogil:
cdef int nelems=nrows*ncols
cdef int i, j, k
cdef double tmp
for k in cython.parallel.prange(nlhs, num_threads=ntasks):
# loop over strict upper triangle only
for j in range(1,ncols): # column
for i in range(j): # row
tmp = 0.5 * ( A[i + nrows*j + nelems*k] + A[j + nrows*i + nelems*k] ) # A[i,j,k] + A[j,i,k]
A[i + nrows*j + nelems*k] = tmp
A[j + nrows*i + nelems*k] = tmp
##############################################################################################################
# Preconditioning (scaling)
##############################################################################################################
# With the exception of apply_scaling_c(), the low-level routines treat A as input only.
# The scaling factors will be written to the arrays row_scale[] and col_scale[].
#
# The routine apply_scaling_c() freezes the current scaling by applying the scaling factors in-place.
# This should be done last, before handing A to one of the solver routines.
#
# But be sure not to destroy row_scale[] and col_scale[] immediately; it is the caller's responsibility
# to scale the RHS accordingly (b[j] *= row_scale[j]), and after solving the linear system,
# to scale the solution (x[m] *= col_scale[m]).
# For all C routines in this section:
#
# - arrays passed as raw pointer + explicit size
# - all arrays must be allocated by caller
#
# A : in (out for apply_scaling_c() only), matrix of size (nrows,ncols), Fortran-contiguous
# nrows : in, number of rows
# ncols : in, number of columns
# row_scale : out, vector of row scalings, size (nrows,) (needed by caller for scaling RHSs; scaled_b[j] = original_b[j] * row_scale[j])
# col_scale : out, vector of column scalings, size (ncols,) (needed by caller for scaling the solution; final_x[m] = scaled_x[m] * col_scale[m])
# Initialize scaling for rows and columns of a general matrix A.
cdef void init_scaling_c( int nrows, int ncols, double* row_scale, double* col_scale ) nogil:
cdef int j, m
for m in range(ncols): # col
col_scale[m] = 1.
for j in range(nrows): # row
row_scale[j] = 1.
# Freeze the given scaling factors by applying them to A in-place.
cdef void apply_scaling_c( double* A, int nrows, int ncols, double* row_scale, double* col_scale ) nogil:
cdef int j, m
cdef double c
for m in range(ncols):
c = col_scale[m]
for j in range(nrows):
A[j + nrows*m] *= (row_scale[j] * c)
# Helpers for do_rescale()
#
ctypedef int (*rescale_func_ptr)(double*, int, int, double*, double*) nogil
class ScalingAlgo: # enum (TODO: use real enum type for Python 3.4+)
"""Enum for scaling algorithms for do_rescale()."""
ALGO_COLS_EUCL = 1
ALGO_ROWS_EUCL = 2
ALGO_TWOPASS = 3
ALGO_RUIZ2001 = 4
ALGO_SCALGM = 5
ALGO_DGEEQU = 6
def do_rescale( double[::1,:] A, int algo ):
"""def do_rescale( double[::1,:] A, int algo ):
Generic dispatcher for matrix scaling (preconditioning) routines.
Scaling is useful to reduce the condition number of A, giving more correct digits in the numerical solution
of a linear equation system involving A.
Specifically, DGESV (used by general()) works by LU factorization with pivoting. For this algorithm the
relative accuracy is O(kappa(A) * machine_epsilon), where at double precision, machine_epsilon ~ 1e-16.
( See e.g. http://scicomp.stackexchange.com/questions/19289/are-direct-solvers-affect-by-the-condition-number-of-a-matrix )
This routine handles the creation of the row_scale and col_scale arrays, calls the scaling routine,
scales A in-place, and returns the pair of arrays (row_scale, col_scale).
Parameters:
A : general matrix as Fortran-contiguous rank-2 arraylike, shape (nrows,ncols) (shape determined automatically)
algo : int, see class ScalingAlgo for available values
Return value: tuple (row_scale, col_scale), where
row_scale : out, vector of row scalings, shape (nrows,)
Needed by caller for scaling the RHS. In A*x = b, on the input side:
for j in range(nrows):
scaled_b[j] = original_b[j] * row_scale[j]
col_scale : out, vector of column scalings, shape (ncols,)
Needed by caller for scaling the solution. In A*x = b, on the output side:
for m in range(ncols):
true_x[m] = scaled_x[m] * col_scale[m]
"""
# create result arrays
cdef int nrows=A.shape[0], ncols=A.shape[1]
cdef double[::1] row_scale = np.empty( (nrows,), dtype=np.float64 )
cdef double[::1] col_scale = np.empty( (ncols,), dtype=np.float64 )
cdef rescale_func_ptr scaler
if algo == ScalingAlgo.ALGO_COLS_EUCL:
scaler = rescale_columns_c
elif algo == ScalingAlgo.ALGO_ROWS_EUCL:
scaler = rescale_rows_c
elif algo == ScalingAlgo.ALGO_TWOPASS:
scaler = rescale_twopass_c
elif algo == ScalingAlgo.ALGO_RUIZ2001:
scaler = rescale_ruiz2001_c
elif algo == ScalingAlgo.ALGO_SCALGM:
scaler = rescale_scalgm_c
elif algo == ScalingAlgo.ALGO_DGEEQU:
scaler = rescale_dgeequ_c
else:
raise ValueError("Unknown algorithm identifier, got %d" % (algo))
with nogil:
scaler( &A[0,0], nrows, ncols, &row_scale[0], &col_scale[0] ) # internally calls init_scaling_c()
apply_scaling_c( &A[0,0], nrows, ncols, &row_scale[0], &col_scale[0] )
return (row_scale, col_scale)
# Python interface methods for specific algorithms.
#
# A : in, rank-2 arraylike (Fortran-contiguous)
#
# return value: tuple (row_scale, col_scale) of rank-1 arrays
#
def rescale_columns( double[::1,:] A ):
"""def rescale_columns( double[::1,:] A ):
Algorithm: column scaling only.
Do not call this directly; instead, use do_rescale(). This function is exported only to make its docstring visible.
- changes the "size of units" of the elements of x
- so the caller must undo this when reading "x" after solving the linear equation system.
- in an ODE/PDE context, intuitively, this balances the size of numbers needed for function values
themselves and different orders of derivatives, by undoing the effect of multiplications by
different powers of grid spacing (usually "one unit of derivative" is very small,
so many of them are required to represent even a moderate slope).
- destroys symmetry of the matrix!
"""
return do_rescale( A, ScalingAlgo.ALGO_COLS_EUCL )
cdef int rescale_columns_c( double* A, int nrows, int ncols, double* row_scale, double* col_scale ) nogil:
init_scaling_c( nrows, ncols, row_scale, col_scale )
cdef int j, m
cdef double acc, tmp, c
for m in range(ncols):
c = col_scale[m] # old column scaling multiplier in column m
acc = 0.
for j in range(nrows):
tmp = A[j + nrows*m] * (c * row_scale[j]) # A[j,m], with old scaling
acc += tmp*tmp # | A[j,m] |**2
col_scale[m] /= sqrt(acc) # update column scaling by euclidean norm of A[:,m] (in old scaling)
return 1
def rescale_rows( double[::1,:] A ):
"""def rescale_rows( double[::1,:] A ):
Algorithm: row scaling only
Do not call this directly; instead, use do_rescale(). This function is exported only to make its docstring visible.
- changes the scaling of the RHS
- so the caller must scale "b" by the same factor, too
- intuitively, balances the size of numbers needed in different equations of the linear equation system
- does NOT affect the scaling of the components of x
- destroys symmetry of the matrix!
"""
return do_rescale( A, ScalingAlgo.ALGO_ROWS_EUCL )
cdef int rescale_rows_c( double* A, int nrows, int ncols, double* row_scale, double* col_scale ) nogil:
init_scaling_c( nrows, ncols, row_scale, col_scale )
cdef int j, m
cdef double acc, tmp, r
for j in range(nrows):
r = row_scale[j] # old row scaling multiplier on row j
acc = 0.
for m in range(ncols):
tmp = A[j + nrows*m] * (r * col_scale[m]) # A[j,m], with old scaling
acc += tmp*tmp # | A[j,m] |**2
row_scale[j] /= sqrt(acc) # update row scaling by euclidean norm of A[j,:] (in old scaling)
return 1
def rescale_twopass( double[::1,:] A ):
"""def rescale_twopass( double[::1,:] A ):
Naive two-pass rescale of columns first, then rows.
Do not call this directly; instead, use do_rescale(). This function is exported only to make its docstring visible.
Destroys symmetry, but is simple and fast (no iteration needed).
- we scale the columns of A, producing a column-scaled matrix A'
- then we scale the rows of A', producing A''
- after the second step the columns are no longer balanced, so A'' will *not* be doubly stochastic
If one wants a doubly stochastic matrix, iterative approaches are possible.
See rescale_ruiz2001() and rescale_scalgm().
"""
return do_rescale( A, ScalingAlgo.ALGO_TWOPASS )
cdef int rescale_twopass_c( double* A, int nrows, int ncols, double* row_scale, double* col_scale ) nogil:
init_scaling_c( nrows, ncols, row_scale, col_scale )
cdef int j, m
cdef double acc, tmp, c, r
for m in range(ncols):
c = col_scale[m] # old column scaling multiplier in column m
acc = 0.
for j in range(nrows):
tmp = A[j + nrows*m] * (c * row_scale[j]) # A[j,m], with old scaling
acc += tmp*tmp # | A[j,m] |**2
col_scale[m] /= sqrt(acc) # update column scaling by euclidean norm of A[:,m] (in old scaling)
for j in range(nrows):
r = row_scale[j] # old row scaling multiplier on row j
acc = 0.
for m in range(ncols):
tmp = A[j + nrows*m] * (r * col_scale[m]) # A[j,m], with old scaling
acc += tmp*tmp # | A[j,m] |**2
row_scale[j] /= sqrt(acc) # update row scaling by euclidean norm of A[j,:] (in old scaling)
return 1
def rescale_dgeequ( double[::1,:] A ):
"""def rescale_dgeequ( double[::1,:] A ):
Scaling using DGEEQU from LAPACK.
Do not call this directly; instead, use do_rescale(). This function is exported only to make its docstring visible.
Destroys symmetry, but is simple and fast (no iteration needed).
Similar to twopass, but uses the l-infinity norm.
See:
http://www.netlib.org/lapack/explore-3.1.1-html/dgeequ.f.html
"""
return do_rescale( A, ScalingAlgo.ALGO_DGEEQU )
# FIXME: Unfortunately, we must ignore exceptions to fit the rescale_func_ptr signature.
cdef int rescale_dgeequ_c( double* A, int nrows, int ncols, double* row_scale, double* col_scale ) nogil:
# SUBROUTINE DGEEQU( M, N, A, LDA, R, C, ROWCND, COLCND, AMAX, INFO )
cdef double rowcnd, colcnd, amax
cdef int info
dgeequ( &nrows, &ncols, A, &nrows, row_scale, col_scale, &rowcnd, &colcnd, &amax, &info )
return 1
def rescale_ruiz2001( double[::1,:] A ):
"""def rescale_ruiz2001( double[::1,:] A ):
Simultaneous row and column iterative scaling using algorithm of Ruiz (2001).
Do not call this directly; instead, use do_rescale(). This function is exported only to make its docstring visible.
Preserves matrix symmetry, at the cost of requiring an iterative process to find the scaling factors.
The rows and columns are equilibrated in the l-infinity norm (maximum absolute value of element).
Reference:
Daniel Ruiz, A Scaling Algorithm to Equilibrate Both Rows and Columns Norms in Matrices. Report RAL-TR-2001-034. 2001.
"""
return do_rescale( A, ScalingAlgo.ALGO_RUIZ2001 )
cdef int rescale_ruiz2001_c( double* A, int nrows, int ncols, double* row_scale, double* col_scale ) nogil:
# temporary work space
cdef double* DR = <double*>malloc( nrows*sizeof(double) )
cdef double* DC = <double*>malloc( ncols*sizeof(double) )
cdef double* DRprev = <double*>malloc( nrows*sizeof(double) )
cdef double* DCprev = <double*>malloc( ncols*sizeof(double) )
init_scaling_c( nrows, ncols, row_scale, col_scale ) # D1 and D2 in algorithm 2.1 in Ruiz (2001)
init_scaling_c( nrows, ncols, DR, DC ) # DR and DC in algorithm 2.1 (curr iterate)
init_scaling_c( nrows, ncols, DRprev, DCprev ) # DR and DC in algorithm 2.1 (prev iterate)
cdef int k, j, m
cdef double acc, tmp
DEF epsilon = 1e-15 # maybe appropriate for double precision?
DEF niters = 100 # maximum number of iterations to take
for k in range(niters):
# compute new DR
for j in range(nrows):
r = DRprev[j] # old row scaling multiplier on row j
acc = 0.
for m in range(ncols):
tmp = c_abs( A[j + nrows*m] / (r * DCprev[m]) ) # |A[j,m]|, with old scaling
if tmp > acc: # l-infinity norm (largest abs(element))
acc = tmp
DR[j] = sqrt(acc) # update row scaling by norm of A[j,:] (in old scaling)
# compute new DC
for m in range(ncols):
c = DCprev[m] # old column scaling multiplier in column m
acc = 0.
for j in range(nrows):
tmp = c_abs( A[j + nrows*m] / (c * DRprev[j]) ) # |A[j,m]|, with old scaling
if tmp > acc: # l-infinity norm (largest abs(element))
acc = tmp
DC[m] = sqrt(acc) # update column scaling by norm of A[:,m] (in old scaling)
# update D1, D2, DR, DC
for j in range(nrows):
DRprev[j] *= DR[j]
row_scale[j] /= DR[j] # our convention: one should *multiply* by the scale factors
for m in range(ncols):
DCprev[m] *= DC[m]
col_scale[m] /= DC[m]
# convergence check
#
# find max abs(1 - |r_j|_infty), j = 0, ..., nrows-1
#
acc = c_abs(1. - DR[0]*DR[0]) # DR[j] stores the square root of the infinity-norm
for j in range(1, nrows):
tmp = c_abs(1. - DR[j]*DR[j])
if tmp > acc:
acc = tmp
if acc < epsilon: # rows converged, check columns too
# find max abs(1 - |c_m|_infty), m = 0, ..., ncols-1
#
acc = c_abs(1. - DC[0]*DC[0]) # DC[m] stores the square root of the infinity-norm
for m in range(1, ncols):
tmp = c_abs(1. - DC[m]*DC[m])
if tmp > acc:
acc = tmp
if acc < epsilon: # columns converged too
break
free( <void*>DCprev )
free( <void*>DRprev )
free( <void*>DC )
free( <void*>DR )
return k+1 # number of iterations taken
def rescale_scalgm( double[::1,:] A ):
"""def rescale_scalgm( double[::1,:] A ):
Simultaneous row and column iterative scaling using the SCALGM algorithm of Chiang and Chandler (2008).
Preserves matrix symmetry, at the cost of requiring an iterative process to find the scaling factors.
The rows and columns are equilibrated in the l-infinity norm (maximum absolute value of element).
The result is the same as by Ruiz (2001) (see rescale_ruiz2001()); both algorithms are provided,
because they may exhibit different performance.
Reference:
Chin-Chieh Chiang and John P. Chandler. An Approximate Equation for the Condition Numbers
of Well-scaled Matrices. Paper 036, ENG 183, in Proceedings of The 2008 IAJC-IJME
International Conference. ISBN 978-1-60643-379-9.
"""
return do_rescale( A, ScalingAlgo.ALGO_SCALGM )
# Helper for SCALGM
cdef void basic_scale_up_rows( double* A, int nrows, int ncols, double* rs, double* cs, double* mod_cs, double* new_rs ) nogil:
cdef int j, m
cdef double r, acc, tmp
if mod_cs != <double*>0: # multiplicative modifier from previous column scaling not yet applied in current rs,cs
# (this can be used to implement "scale columns first, then rows" without updating rs,cs)
for j in range(nrows):
r = rs[j] # current row scaling multiplier on row j
acc = 0.
for m in range(ncols):
tmp = c_abs( A[j + nrows*m] * (r * cs[m] * mod_cs[m]) ) # |A[j,m]|, with current scaling and mod_cs applied
if acc == 0. or tmp > 0. and tmp < acc:
acc = tmp
new_rs[j] = 1./acc # acc = smallest non-zero magnitude of any element on row j
else: # no modifier
for j in range(nrows):
r = rs[j] # current row scaling multiplier on row j
acc = 0.
for m in range(ncols):
tmp = c_abs( A[j + nrows*m] * (r * cs[m]) ) # |A[j,m]|, with current scaling
if acc == 0. or tmp > 0. and tmp < acc:
acc = tmp
new_rs[j] = 1./acc # acc = smallest non-zero magnitude of any element on row j
# Helper for SCALGM
cdef void basic_scale_up_cols( double* A, int nrows, int ncols, double* rs, double* mod_rs, double* cs, double* new_cs ) nogil:
cdef int j, m
cdef double c, acc, tmp
if mod_rs != <double*>0: # multiplicative modifier from previous row scaling not yet applied in current rs,cs
# (this can be used to implement "scale rows first, then columns" without updating rs,cs)
for m in range(ncols):
c = cs[m] # current column scaling multiplier in column j
acc = 0.
for j in range(nrows):
tmp = c_abs( A[j + nrows*m] * (c * rs[j] * mod_rs[j]) ) # |A[j,m]|, with current scaling and mod_rs applied
if acc == 0. or tmp > 0. and tmp < acc:
acc = tmp
new_cs[m] = 1./acc # acc = smallest non-zero magnitude of any element in column m
else: # no modifier
for m in range(ncols):
c = cs[m] # current column scaling multiplier in column j
acc = 0.
for j in range(nrows):
tmp = c_abs( A[j + nrows*m] * (c * rs[j]) ) # |A[j,m]|, with current scaling
if acc == 0. or tmp > 0. and tmp < acc:
acc = tmp
new_cs[m] = 1./acc # acc = smallest non-zero magnitude of any element in column m
# Helper for SCALGM
cdef void basic_scale_down_rows( double* A, int nrows, int ncols, double* rs, double* cs, double* mod_cs, double* new_rs ) nogil:
cdef int j, m
cdef double r, acc, tmp
if mod_cs != <double*>0: # multiplicative modifier from previous column scaling not yet applied in current rs,cs
# (this can be used to implement "scale columns first, then rows" without updating rs,cs)
for j in range(nrows):
r = rs[j] # current row scaling multiplier on row j
acc = 0.
for m in range(ncols):
tmp = c_abs( A[j + nrows*m] * (r * cs[m] * mod_cs[m]) ) # |A[j,m]|, with current scaling and mod_cs applied
if tmp > acc:
acc = tmp
new_rs[j] = 1./acc # acc = largest magnitude of any element on row j
else: # no modifier
for j in range(nrows):
r = rs[j] # current row scaling multiplier on row j
acc = 0.
for m in range(ncols):
tmp = c_abs( A[j + nrows*m] * (r * cs[m]) ) # |A[j,m]|, with current scaling
if tmp > acc:
acc = tmp
new_rs[j] = 1./acc # acc = largest magnitude of any element on row j
# Helper for SCALGM
cdef void basic_scale_down_cols( double* A, int nrows, int ncols, double* rs, double* mod_rs, double* cs, double* new_cs ) nogil:
cdef int j, m
cdef double c, acc, tmp
if mod_rs != <double*>0: # multiplicative modifier from previous row scaling not yet applied in current rs,cs
# (this can be used to implement "scale rows first, then columns" without updating rs,cs)
for m in range(ncols):
c = cs[m] # current column scaling multiplier in column j
acc = 0.
for j in range(nrows):
tmp = c_abs( A[j + nrows*m] * (c * rs[j] * mod_rs[j]) ) # |A[j,m]|, with current scaling and mod_rs applied
if tmp > acc:
acc = tmp
new_cs[m] = 1./acc # acc = largest magnitude of any element in column m
else: # no modifier
for m in range(ncols):
c = cs[m] # current column scaling multiplier in column j
acc = 0.
for j in range(nrows):
tmp = c_abs( A[j + nrows*m] * (c * rs[j]) ) # |A[j,m]|, with current scaling
if tmp > acc:
acc = tmp
new_cs[m] = 1./acc # acc = largest magnitude of any element in column m
# SCALGM driver
cdef int rescale_scalgm_c( double* A, int nrows, int ncols, double* row_scale, double* col_scale ) nogil:
# temporary work space
cdef double* DR1 = <double*>malloc( nrows*sizeof(double) )
cdef double* DC1 = <double*>malloc( ncols*sizeof(double) )
cdef double* DR2 = <double*>malloc( nrows*sizeof(double) )
cdef double* DC2 = <double*>malloc( ncols*sizeof(double) )
init_scaling_c( nrows, ncols, row_scale, col_scale )
init_scaling_c( nrows, ncols, DR1, DC1 )
init_scaling_c( nrows, ncols, DR2, DC2 )
cdef int k, j, m
cdef double acc, acc2, tmp
cdef int operation_mode = 1
DEF epsilon = 1e-15 # maybe appropriate for double precision?
DEF niters = 100 # maximum number of iterations to take
for k in range(niters):
# let "original matrix" = the matrix at the start of the iteration.
if operation_mode == 1: # still iterating also steps 1-3?
# step 1: scale up the original matrix by rows, then columns using the "basic" algorithm
#
basic_scale_up_rows( A, nrows, ncols, row_scale, col_scale, <double*>0, DR1 )
basic_scale_up_cols( A, nrows, ncols, row_scale, DR1, col_scale, DC1 ) # apply also DR1 when computing DC1
# step 2: scale up the original matrix by columns, then rows using the "basic" algorithm
#
basic_scale_up_cols( A, nrows, ncols, row_scale, <double*>0, col_scale, DC2 )
basic_scale_up_rows( A, nrows, ncols, row_scale, col_scale, DC2, DR2 ) # apply also DC2 when computing DR2
# step 3: scale up the original matrix by the geometric mean of the two row/column factors
#
# (updating the scaling info!)
#
for j in range(nrows):
row_scale[j] *= sqrt( DR1[j] * DR2[j] )
for m in range(ncols):
col_scale[m] *= sqrt( DC1[m] * DC2[m] )
# let "resulting matrix" = the result of step 3, if operation_mode == 1; else "resulting matrix" = the original matrix.
# step 4: scale down the resulting matrix down by rows, then columns using the "basic" algorithm
#
basic_scale_down_rows( A, nrows, ncols, row_scale, col_scale, <double*>0, DR1 )
basic_scale_down_cols( A, nrows, ncols, row_scale, DR1, col_scale, DC1 ) # apply also DR1 when computing DC1
# step 5: scale down the resulting matrix by columns, then rows using the "basic" algorithm
#
basic_scale_down_cols( A, nrows, ncols, row_scale, <double*>0, col_scale, DC2 )
basic_scale_down_rows( A, nrows, ncols, row_scale, col_scale, DC2, DR2 ) # apply also DC2 when computing DR2
# step 6: scale down the resulting matrix by the geometric mean of the two row/column factors
#
# (again, updating the scaling info!)
#
for j in range(nrows):
row_scale[j] *= sqrt( DR1[j] * DR2[j] )
for m in range(ncols):
col_scale[m] *= sqrt( DC1[m] * DC2[m] )
# convergence check
#
# find max abs(1 - |r_j|_infty), j = 0, ..., nrows-1
#
acc2 = 0.
for j in range(nrows):
r = row_scale[j] # old row scaling multiplier on row j
acc = 0.
for m in range(ncols):
tmp = c_abs( A[j + nrows*m] * (r * col_scale[m]) ) # |A[j,m]|, with old scaling
if tmp > acc:
acc = tmp
tmp = c_abs(1. - acc)
if tmp > acc2:
acc2 = tmp
if acc2 < epsilon: # rows converged, check columns too
# find max abs(1 - |c_m|_infty), m = 0, ..., ncols-1
#
acc2 = 0.
for m in range(ncols):
c = col_scale[m] # old row scaling multiplier in column m
acc = 0.
for j in range(nrows):
tmp = c_abs( A[j + nrows*m] * (c * row_scale[j]) ) # |A[j,m]|, with old scaling
if c_abs(tmp) > acc:
acc = c_abs(tmp)
tmp = c_abs(1. - acc)
if tmp > acc2:
acc2 = tmp
if acc2 < epsilon: # columns converged too
if operation_mode == 1:
operation_mode = 2 # switch operation mode to iterate only steps 4-6
else:
break # all done
free( <void*>DC2 )
free( <void*>DR2 )
free( <void*>DC1 )
free( <void*>DR1 )
return k+1 # number of iterations taken
##############################################################################################################
# Simple example (tridiagonal matrices)
##############################################################################################################
cpdef int tridiag( double[::1] a, double[::1] b, double[::1] c, double[::1] x ) nogil except -1:
"""cpdef int tridiag( double[::1] a, double[::1] b, double[::1] c, double[::1] x ) nogil except -1:
Tridiagonal solver example from:
Henriksen, Ian. Circumventing The Linker: Using SciPy’s BLAS and LAPACK Within Cython. PROC. OF THE 14th PYTHON IN SCIENCE CONF. (SCIPY 2015), 49-52.
http://conference.scipy.org/proceedings/scipy2015/pdfs/ian_henriksen.pdf
This routine is provided mainly as a minimal form of documentation; the main purpose of this module is
in the routines for general and symmetric matrices.
For the parameters, see a,b,c,x of LAPACK's DGTSV.
For the double[::1] syntax, see "Typed Memoryviews" in Cython documentation:
http://cython.readthedocs.io/en/latest/src/userguide/memoryviews.html
For the "except -1", see:
http://docs.cython.org/en/latest/src/reference/language_basics.html#error-and-exception-handling
"""
cdef int n=b.shape[0], nrhs=1, info
# Solution is written over the values in x.
# http://www.netlib.org/lapack/lapack-3.1.1/html/dgtsv.f.html
dgtsv(&n, &nrhs, &a[0], &b[0], &c[0], &x[0], &n, &info)
return 0
##############################################################################################################
# Symmetric matrices
##############################################################################################################
def symmetric2x2( double[::1,:] A, double[::1] b ):
"""def symmetric2x2( double[::1,:] A, double[::1] b ):
Solve a symmetric 2x2 system.
This is provided for completeness; the special case of a 2x2 matrix is fastest to just compute directly.
To match the other routines, we use only the upper triangle.
A : symmetric 2x2 matrix as Fortran-contiguous rank-2 arraylike, shape (2,2)
b : rank-1 arraylike, shape (2,)
in : RHS
out : solution x to A*x = b
"""
symmetric2x2_c( &A[0,0], &b[0] )
cdef int symmetric2x2_c( double* A, double* b ) nogil except -1:
# Ainv = 1/Adet * [ [A22, -A12], [-A21, A11] ]
# x = Ainv*b
#
# with A21 = A12
# each of these gets at least two accesses (a01 gets four)
cdef double a00 = A[0]
cdef double a01 = A[2] # A[0,1] in Fortran-contiguous storage
cdef double a11 = A[3]
cdef double b0 = b[0]
cdef double b1 = b[1]
# solve, overwrite b with solution
cdef double dm1 = 1. / ( a00*a11 - a01*a01 )
b[0] = dm1 * ( a11*b0 - a01*b1 )
b[1] = dm1 * ( a00*b1 - a01*b0 )
return 0
def symmetric( double[::1,:] A, double[::1] b ):
"""def symmetric( double[::1,:] A, double[::1] b ):
Solve a symmetric system.
Only the upper triangle of A is used.
A : symmetric matrix as Fortran-contiguous rank-2 arraylike, shape (n,n)
in : matrix A
out : destroyed (overwritten)
b : rank-1 arraylike, shape (n,)
in : RHS
out : solution x to A*x = b
"""
cdef int n=b.shape[0]
with nogil:
symmetrics_c( &A[0,0], &b[0], n, 1 )
cdef int symmetric_c( double* A, double* b, int n ) nogil except -1:
return symmetrics_c( A, b, n, 1 )
def symmetricfactor( double[::1,:] A ):
"""def symmetricfactor( double[::1,:] A ):
Compute the UDUT factorization only.
A : symmetric matrix as Fortran-contiguous rank-2 arraylike, shape (n,n)
in : matrix A
out : the UDUT factorization of A, as returned by DSYTRF
Return value:
pivot array (rank-1, shape (n,), dtype np.int32). This is needed for the solve step.
"""
cdef int n=A.shape[0]
cdef int[::1] ipiv = np.empty( (n,), dtype=np.int32 )
with nogil:
symmetricfactor_c( &A[0,0], &ipiv[0], n )
return ipiv
cdef int symmetricfactor_c( double* A, int* ipiv, int n ) nogil except -1:
return msymmetricfactor_c( A, ipiv, n, 1 )
def symmetricfactored( double[::1,:] A, int[::1] ipiv, double[::1] b ):
"""def symmetricfactored( double[::1,:] A, int[::1] ipiv, double[::1] b ):
Solve a symmetric system using an already factored A and its pivot array.
Caveat:
The solution is computed by LAPACK's DSYTRS, which uses level 2 BLAS, so the performance is not optimal.
The solution may slightly differ from that returned by symmetric(), because DSYSV uses DSYTRS2
(with level 3 BLAS) internally.
This difference is because cython_lapack does not expose DSYTRS2.
A : symmetric matrix as Fortran-contiguous rank-2 arraylike, shape (n,n)
in : the UDUT factorization of A
out : unchanged
ipiv : pivot array as rank-1 arraylike, shape (n,), dtype np.int32
in : the pivot array (see symmetricfactor())
out : unchanged
b : rank-1 arraylike, shape (n,)
in : RHS
out : solution x to A*x = b
"""
cdef int n=A.shape[0]
with nogil:
symmetricfactored_c( &A[0,0], &ipiv[0], &b[0], n )
cdef int symmetricfactored_c( double* A, int* ipiv, double* b, int n ) nogil except -1:
return msymmetricfactored_c( A, ipiv, b, n, 1 )
def symmetrics( double[::1,:] A, double[::1,:] b ):
"""def symmetrics( double[::1,:] A, double[::1,:] b ):
Like symmetric(); single-threaded for multiple RHS.
Uses LAPACK's multiple RHS functionality. Factorizes A only once.
A : shape (n, n)
in : matrix A
out : destroyed (overwritten)
b : shape (n, nrhs)
in : RHSs
out : solutions x to A*x = b for each RHS
"""
cdef int n=b.shape[0], nrhs=b.shape[1]
with nogil:
symmetrics_c( &A[0,0], &b[0,0], n, nrhs )
cdef int symmetrics_c( double* A, double* b, int n, int nrhs ) nogil except -1:
cdef int info
cdef char uplo='U'
# query optimal work size (will be written at &worksize[0])
cdef double worksize
cdef int lwork=-1
dsysv( &uplo, &n, &nrhs, A, &n, <int*>0, b, &n, &worksize, &lwork, &info )
lwork = <int>worksize
cdef double* p_work = <double*>malloc( lwork*sizeof(double) )
# solve (on exit, b is overwritten by the solution)
#
# http://www.netlib.org/lapack/lapack-3.1.1/html/dsysv.f.html
# UPLO, N, NRHS, A, LDA, IPIV, B, LDB, WORK, LWORK, INFO