File: cs_sla.c

package info (click to toggle)
code-saturne 4.3.3%2Brepack-1
  • links: PTS, VCS
  • area: main
  • in suites: stretch
  • size: 77,992 kB
  • sloc: ansic: 281,257; f90: 122,305; python: 56,490; makefile: 3,915; xml: 3,285; cpp: 3,183; sh: 1,139; lex: 176; yacc: 101; sed: 16
file content (3951 lines) | stat: -rw-r--r-- 115,185 bytes parent folder | download
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
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654
3655
3656
3657
3658
3659
3660
3661
3662
3663
3664
3665
3666
3667
3668
3669
3670
3671
3672
3673
3674
3675
3676
3677
3678
3679
3680
3681
3682
3683
3684
3685
3686
3687
3688
3689
3690
3691
3692
3693
3694
3695
3696
3697
3698
3699
3700
3701
3702
3703
3704
3705
3706
3707
3708
3709
3710
3711
3712
3713
3714
3715
3716
3717
3718
3719
3720
3721
3722
3723
3724
3725
3726
3727
3728
3729
3730
3731
3732
3733
3734
3735
3736
3737
3738
3739
3740
3741
3742
3743
3744
3745
3746
3747
3748
3749
3750
3751
3752
3753
3754
3755
3756
3757
3758
3759
3760
3761
3762
3763
3764
3765
3766
3767
3768
3769
3770
3771
3772
3773
3774
3775
3776
3777
3778
3779
3780
3781
3782
3783
3784
3785
3786
3787
3788
3789
3790
3791
3792
3793
3794
3795
3796
3797
3798
3799
3800
3801
3802
3803
3804
3805
3806
3807
3808
3809
3810
3811
3812
3813
3814
3815
3816
3817
3818
3819
3820
3821
3822
3823
3824
3825
3826
3827
3828
3829
3830
3831
3832
3833
3834
3835
3836
3837
3838
3839
3840
3841
3842
3843
3844
3845
3846
3847
3848
3849
3850
3851
3852
3853
3854
3855
3856
3857
3858
3859
3860
3861
3862
3863
3864
3865
3866
3867
3868
3869
3870
3871
3872
3873
3874
3875
3876
3877
3878
3879
3880
3881
3882
3883
3884
3885
3886
3887
3888
3889
3890
3891
3892
3893
3894
3895
3896
3897
3898
3899
3900
3901
3902
3903
3904
3905
3906
3907
3908
3909
3910
3911
3912
3913
3914
3915
3916
3917
3918
3919
3920
3921
3922
3923
3924
3925
3926
3927
3928
3929
3930
3931
3932
3933
3934
3935
3936
3937
3938
3939
3940
3941
3942
3943
3944
3945
3946
3947
3948
3949
3950
3951
/*============================================================================
 * Sparse linear algebra related to CDO techniques
 * Matrix operations (matvec, matmat, and other manipulations)
 * Generic functions related to the linear systems to solve
 *============================================================================*/

/*
  This file is part of Code_Saturne, a general-purpose CFD tool.

  Copyright (C) 1998-2016 EDF S.A.

  This program is free software; you can redistribute it and/or modify it under
  the terms of the GNU General Public License as published by the Free Software
  Foundation; either version 2 of the License, or (at your option) any later
  version.

  This program is distributed in the hope that it will be useful, but WITHOUT
  ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
  FOR A PARTICULAR PURPOSE.  See the GNU General Public License for more
  details.

  You should have received a copy of the GNU General Public License along with
  this program; if not, write to the Free Software Foundation, Inc., 51 Franklin
  Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/

/*----------------------------------------------------------------------------*/

#include "cs_defs.h"

/*----------------------------------------------------------------------------
 * Standard C library headers
 *----------------------------------------------------------------------------*/

#include <string.h>
#include <assert.h>
#include <math.h>
#include <float.h>

/*----------------------------------------------------------------------------
 *  Local headers
 *----------------------------------------------------------------------------*/

#include "bft_mem.h"
#include "bft_printf.h"

#include "cs_math.h"
#include "cs_sort.h"
#include "cs_search.h"

/*----------------------------------------------------------------------------
 * Header for the current file
 *----------------------------------------------------------------------------*/

#include "cs_sla.h"

/*----------------------------------------------------------------------------*/

BEGIN_C_DECLS

/*=============================================================================
 * Local Macro definitions and structure definitions
 *============================================================================*/

#define  CS_SLA_DBG 1

/* Sparse Accumulator: see Gilbert etal. and Buluc (PhD) */
/* ===================================================== */

typedef struct { /* for CSR or MSR matrix operations */

  cs_lnum_t  *tag;  /* size n_cols */
  double     *val;  /* size n_cols */

  size_t      size; /* size of the allocated list */
  size_t      nnz;  /* number of non empty in the list */
  cs_lnum_t  *lst;

} _spa_t;

typedef struct { /* for DEC matrix operations */

  cs_lnum_t  *tag;  /* size n_cols */
  short int  *sgn;  /* size n_cols */

  size_t      size; /* size of the allocated list */
  size_t      nnz;  /* number of non empty in the list */
  cs_lnum_t  *lst;

} _spa_dec_t;

/*============================================================================
 * Private constant variables
 *============================================================================*/

static const char  _sla_err_stride[] =
  "  Incompatible stride value (>1).\n   Stop matrix computation.\n";

static const char _sla_matrix_type[CS_SLA_MAT_N_TYPES][CS_BASE_STRING_LEN] = {
  "None",
  "DEC",
  "CSR",
  "MSR"
};

/*============================================================================
 * Private function prototypes
 *============================================================================*/

/*----------------------------------------------------------------------------*/
/*!
 * \brief   Initialize a Sparse Accumulator (SPA) for MSR and CSR type
 *
 * \param[in]  a_size     size of tag and val arrays
 * \param[in]  l_size     size of lst
 *
 * \return a pointer to a new allocated and initialize SPA struct.
 */
/*----------------------------------------------------------------------------*/

static _spa_t *
_spa_init(size_t   a_size,
          size_t   l_size)
{
  size_t  i;

  _spa_t  *spa = NULL;

  BFT_MALLOC(spa, 1, _spa_t);

  BFT_MALLOC(spa->tag, a_size, cs_lnum_t);
  BFT_MALLOC(spa->val, a_size, double);

  for (i = 0; i < a_size; i++) {
    spa->tag[i] = -1; /* not used by default */
    spa->val[i] = 0.0;
  }

  spa->size = l_size;
  spa->nnz = 0;
  BFT_MALLOC(spa->lst, l_size, cs_lnum_t);

  return spa;
}

/*----------------------------------------------------------------------------*/
/*!
 * \brief   Free a Sparse Accumulator (SPA) for MSR and CSR type
 *
 * \param[in, out]   spa    pointer to a SPA struct. to free
 *
 * \return a NULL pointer
 */
/*----------------------------------------------------------------------------*/

static _spa_t *
_spa_free(_spa_t  *spa)
{
  if (spa == NULL)
    return spa;

  BFT_FREE(spa->tag);
  BFT_FREE(spa->val);
  BFT_FREE(spa->lst);

  BFT_FREE(spa);

  return spa;
}

/*----------------------------------------------------------------------------*/
/*!
 * \brief   Initialize a Sparse Accumulator (SPA) for DEC type
 *
 * \param[in]  a_size     size of tag and connect arrays
 * \param[in]  l_size     size of lst
 *
 * \return a pointer to a new allocated and initialize SPA struct.
 */
/*----------------------------------------------------------------------------*/

static _spa_dec_t *
_spa_dec_init(size_t   a_size,
              size_t   l_size)
{
  size_t  i;

  _spa_dec_t  *spa = NULL;

  BFT_MALLOC(spa, 1, _spa_dec_t);

  BFT_MALLOC(spa->tag, a_size, cs_lnum_t);
  BFT_MALLOC(spa->sgn, a_size, short int);

  for (i = 0; i < a_size; i++) {
    spa->tag[i] = -1; /* not used by default */
    spa->sgn[i] = 0;
  }

  spa->size = l_size;
  spa->nnz = 0;
  BFT_MALLOC(spa->lst, l_size, cs_lnum_t);

  return spa;
}

/*----------------------------------------------------------------------------*/
/*!
 * \brief   Free a Sparse Accumulator (SPA) for MSR and CSR type
 *
 * \param[in, out]   spa    pointer to a SPA struct. to free
 *
 * \return a NULL pointer
 */
/*----------------------------------------------------------------------------*/

static _spa_dec_t *
_spa_dec_free(_spa_dec_t  *spa)
{
  if (spa == NULL)
    return spa;

  BFT_FREE(spa->tag);
  BFT_FREE(spa->sgn);
  BFT_FREE(spa->lst);

  BFT_FREE(spa);

  return spa;
}

/*----------------------------------------------------------------------------*/
/*!
 * \brief   Add the contribution of a new entry
 *
 * \param[in, out]  spa     pointer to the SPA struct. to update
 * \param[in]       value   value to add
 * \param[in]       pos     position related to this value
 * \param[in]       row_id  current row
 *
 */
/*----------------------------------------------------------------------------*/

inline static void
_spa_add(_spa_t     *spa,
         double      value,
         cs_lnum_t   pos,
         cs_lnum_t   row_id)
{
  if (spa->tag[pos] != row_id) { /* Add a new item in lst */

    if (spa->nnz == spa->size) {  /* Increase size */
      spa->size = CS_MAX(spa->size + 1, 2*spa->size);
      BFT_REALLOC(spa->lst, spa->size, cs_lnum_t);
    }
    spa->lst[spa->nnz] = pos;
    spa->nnz += 1;

    spa->tag[pos] = row_id;
    spa->val[pos] = value;

  }
  else /* Entry already defined */
    spa->val[pos] += value;

}

/*----------------------------------------------------------------------------*/
/*!
 * \brief   Add the contribution of a new entry
 *
 * \param[in, out]  spa     pointer to the SPA struct. to update
 * \param[in]       value   value to add
 * \param[in]       pos     position related to this value
 * \param[in]       row_id  current row
 *
 */
/*----------------------------------------------------------------------------*/

static inline void
_spa_dec_add(_spa_dec_t   *spa,
             short int     value,
             cs_lnum_t     pos,
             cs_lnum_t     row_id)
{
  if (spa->tag[pos] != row_id) { /* Add a new item in lst */

    if (spa->nnz == spa->size) {  /* Increase size */
      spa->size = CS_MAX(spa->size + 1, 2*spa->size);
      BFT_REALLOC(spa->lst, spa->size, cs_lnum_t);
    }
    spa->lst[spa->nnz] = pos;
    spa->nnz += 1;

    spa->tag[pos] = row_id;
    spa->sgn[pos] = value;

  }
  else /* Entry already defined */
    spa->sgn[pos] += value;

}

/*----------------------------------------------------------------------------*/
/*!
 * \brief   Gather data from the current SPA state to update matrix structure
 *          Do not add zero entries.
 *
 * \param[in]      spa      pointer to the SPA struct.
 * \param[in]      idx      current index position
 * \param[in, out] col_id   pointer to matrix->col_id array
 * \param[in, out] val      pointer to matrix->val array
 *
 * \return the number of entries added
 */
/*----------------------------------------------------------------------------*/

static size_t
_spa_gather(_spa_t     *spa,
            size_t      idx,
            cs_lnum_t  *col_id,
            double     *val)
{
  size_t  i, shift;

  size_t  n_entries = 0;

  for (i = 0; i < spa->nnz; i++) {

    cs_lnum_t  pos = spa->lst[i];
    double  value = spa->val[pos];

    /* Do not affect an entry with zero value */
    if (value > DBL_EPSILON || value < -DBL_EPSILON) {
      shift = idx + n_entries;
      col_id[shift] = pos;
      val[shift] = value;
      n_entries++;
    }

    /* Initialize for a future use */
    spa->val[pos] = 0.0;

  } /* End of loop on elements of SPA */

  /* Reset */
  spa->nnz = 0;

  return n_entries;
}

/*----------------------------------------------------------------------------*/
/*!
 * \brief   Gather data from the current SPA state to update matrix structure
 *          Do not add zero entries.
 *
 * \param[in]     spa     pointer to the SPA struct.
 * \param[in]     idx     current index position
 * \param[in,out] col_id  pointer to matrix->col_id array
 * \param[in,out] connect pointer to matrix->sgn array
 *
 * \return the number of entries added
 */
/*----------------------------------------------------------------------------*/

static size_t
_spa_dec_gather(_spa_dec_t  *spa,
                size_t       idx,
                cs_lnum_t   *col_id,
                short int   *connect)
{
  size_t  i, shift;

  size_t  n_entries = 0;

  for (i = 0; i < spa->nnz; i++) {

    cs_lnum_t  pos = spa->lst[i];
    short int  value = spa->sgn[pos];

    /* Do not affect an entry with zero value */
    if (value != 0) {
      shift = idx + n_entries;
      col_id[shift] = pos;
      connect[shift] = value;
      n_entries++;
    }

    /* Initialize for a future use */
    spa->sgn[pos] = 0;

  } /* End of loop on elements of SPA */

  /* Reset */
  spa->nnz = 0;

  return n_entries;
}

/*----------------------------------------------------------------------------*/
/*!
 * \brief   Estimate roughly the number of nnz of the matrix c = a*b and the
 *          stencil of c.
 *          Size estimation is given by E. Cohen (1997) in
 *          Structure Prediction and Computation of Sparse Matrix Product
 *
 * \param[in]      a        pointer to the matrix struct. a
 * \param[in]      b        pointer to the matrix struct. b
 * \param[in, out] nnz      size_t element
 * \param[in, out] stencil  size_t element
 *
 */
/*----------------------------------------------------------------------------*/

static void
_estimate_sizes(const cs_sla_matrix_t   *a,
                const cs_sla_matrix_t   *b,
                size_t                  *nnz,
                size_t                  *stencil)
{
  size_t  as = a->idx[a->n_rows], bs = b->idx[b->n_rows];
  size_t  ab = as*bs, bb = b->n_rows*b->n_cols;

  if (a->n_cols == 0)
    *nnz = 0;
  else
    *nnz = CS_MAX(5, ab/a->n_cols);

  if (bb == 0)
    *stencil = 0;
  else
    *stencil = CS_MAX(2, ab/bb);

  if (*nnz == 0 || *stencil == 0)
    printf(" << WARNING >> operation on an empty matrix. Check data !\n");
}

/*----------------------------------------------------------------------------
  Allocate a CSR matrix "c" coming from "c = a*b"
  ----------------------------------------------------------------------------*/

static cs_sla_matrix_t *
_init_mat(const cs_sla_matrix_t   *a,
          const cs_sla_matrix_t   *b,
          cs_sla_matrix_type_t     type,
          size_t                   guess_size)
{
  cs_sla_matrix_t  *c = NULL;
  _Bool  sym = false;

  if ((a->flag & CS_SLA_MATRIX_SYM) &&
      (b->flag & CS_SLA_MATRIX_SYM))
    sym = true;

  c = cs_sla_matrix_create(a->n_rows, b->n_cols, 1, type, sym);

  BFT_MALLOC(c->col_id, guess_size, cs_lnum_t);

  if (type == CS_SLA_MAT_CSR || type == CS_SLA_MAT_MSR)
    BFT_MALLOC(c->val, guess_size, double);
  else if (type == CS_SLA_MAT_DEC)
    BFT_MALLOC(c->sgn, guess_size, short int);

  return c;
}

/*----------------------------------------------------------------------------
  Resize a CSR matrix
  ----------------------------------------------------------------------------*/

static void
_resize_mat(cs_sla_matrix_t   *mat,
            size_t             cur_size,
            size_t            *max_size)
{
  size_t  ms = *max_size;

  if (cur_size + 1 > ms) { /* Realloc */

    ms = CS_MAX(cur_size + 1, floor(1.3*ms));
    BFT_REALLOC(mat->col_id, ms, cs_lnum_t);

    if (mat->type == CS_SLA_MAT_CSR || mat->type == CS_SLA_MAT_MSR)
      BFT_REALLOC(mat->val, ms, double);
    else if (mat->type == CS_SLA_MAT_DEC)
      BFT_REALLOC(mat->sgn, ms, short int);

  }
  *max_size = ms;
}

/*----------------------------------------------------------------------------*/
/*!
 * \brief   Compute c = a*b for a and b in DEC storage
 *
 * \param[in]    a        pointer to the matrix struct. a
 * \param[in]    b        pointer to the matrix struct. b
 *
 * \return a pointer to matrix struct. c
 */
/*----------------------------------------------------------------------------*/

static cs_sla_matrix_t *
_multiply_dec_matrices(const cs_sla_matrix_t  *a,
                       const cs_sla_matrix_t  *b)
{
  int  ii, j, jj, k, kk;
  short int  val;

  size_t  idx = 0, n_entries = 0, size_max = 0, lst_size_init = 0;
  _spa_dec_t  *spa = NULL;
  cs_sla_matrix_t  *c = NULL;

  /* Sanity check */
  assert(a->type == CS_SLA_MAT_DEC && b->type == CS_SLA_MAT_DEC);

  /* Initialize structures */
  _estimate_sizes(a, b, &size_max, &lst_size_init);
  c = _init_mat(a, b, CS_SLA_MAT_DEC, size_max);
  spa = _spa_dec_init(b->n_cols, lst_size_init);

  /* Compute c = a*b line by line */
  for (ii = 0; ii < a->n_rows; ii++) {

    for (j = a->idx[ii]; j < a->idx[ii+1]; j++) {

      jj = a->col_id[j], val = a->sgn[j];
      for (k = b->idx[jj]; k < b->idx[jj+1]; k++)
        kk = b->col_id[k], _spa_dec_add(spa, val*b->sgn[k], kk, ii);

    } /* End of loop on non-empty columnd of row ii of a */

    /* Fill a new row in c and prepare next step */
    if (spa->nnz + idx > size_max)
      _resize_mat(c, spa->nnz + idx, &size_max);
    n_entries = _spa_dec_gather(spa, idx, c->col_id, c->sgn);
    c->idx[ii+1] = idx + n_entries;
    idx = c->idx[ii+1];

  } /* End of loop on row ii of a */

  /* Memory management */
  BFT_REALLOC(c->col_id, c->idx[c->n_rows], cs_lnum_t);
  BFT_REALLOC(c->sgn, c->idx[c->n_rows], short int);
  spa = _spa_dec_free(spa);

  return c;
}

/*----------------------------------------------------------------------------*/
/*!
 * \brief   Compute c = a*b for a and b in CSR storage
 *
 * \param[in]    a        pointer to the matrix struct. a
 * \param[in]    b        pointer to the matrix struct. b
 *
 * \return a pointer to matrix struct. c
 */
/*----------------------------------------------------------------------------*/

static cs_sla_matrix_t *
_multiply_csr_matrices(const cs_sla_matrix_t  *a,
                       const cs_sla_matrix_t  *b)
{
  int  ii, j, jj, k, kk;
  double  val;

  size_t  idx = 0, n_entries = 0, size_max = 0, lst_size_init = 0;
  _spa_t  *spa = NULL;
  cs_sla_matrix_t  *c = NULL;

  /* Sanity check */
  assert(a->type == CS_SLA_MAT_CSR && b->type == CS_SLA_MAT_CSR);

  /* Initialize structures */
  _estimate_sizes(a, b, &size_max, &lst_size_init);
  c = _init_mat(a, b, CS_SLA_MAT_CSR, size_max);
  spa = _spa_init(b->n_cols, lst_size_init);

  /* Compute c = a*b line by line */
  for (ii = 0; ii < a->n_rows; ii++) {

    for (j = a->idx[ii]; j < a->idx[ii+1]; j++) {

      jj = a->col_id[j], val = a->val[j];
      for (k = b->idx[jj]; k < b->idx[jj+1]; k++)
        kk = b->col_id[k], _spa_add(spa, val*b->val[k], kk, ii);

    } /* End of loop on non-empty columns of row ii of a */

    /* Fill a new row in c and prepare next step */
    if (spa->nnz + idx > size_max)
      _resize_mat(c, spa->nnz + idx, &size_max);
    n_entries = _spa_gather(spa, idx, c->col_id, c->val);
    c->idx[ii+1] = idx + n_entries;
    idx = c->idx[ii+1];

  } /* End of loop on row ii of a */

  /* Memory management */
  BFT_REALLOC(c->col_id, c->idx[c->n_rows], cs_lnum_t);
  BFT_REALLOC(c->val, c->idx[c->n_rows], double);
  spa = _spa_free(spa);

  return c;
}

/*----------------------------------------------------------------------------*/
/*!
 * \brief   Compute c = a*b for a in DEC storage and b in CSR storage
 *
 * \param[in]    a        pointer to the matrix struct. a
 * \param[in]    b        pointer to the matrix struct. b
 *
 * \return a pointer to matrix struct. c
 */
/*----------------------------------------------------------------------------*/

static cs_sla_matrix_t *
_multiply_deccsr_matrices(const cs_sla_matrix_t  *a,
                          const cs_sla_matrix_t  *b)
{
  int  ii, j, jj, k, kk;
  double  val;

  size_t  idx = 0, n_entries = 0, size_max = 0, lst_size_init = 0;
  _spa_t  *spa = NULL;
  cs_sla_matrix_t  *c = NULL;

  /* Sanity checks */
  assert(a->type == CS_SLA_MAT_DEC && b->type == CS_SLA_MAT_CSR);

  /* Initialize structures */
  _estimate_sizes(a, b, &size_max, &lst_size_init);
  c = _init_mat(a, b, CS_SLA_MAT_CSR, size_max);
  spa = _spa_init(b->n_cols, lst_size_init);

  /* Compute c = a*b line by line */
  for (ii = 0; ii < a->n_rows; ii++) {

    for (j = a->idx[ii]; j < a->idx[ii+1]; j++) {

      jj = a->col_id[j], val = a->sgn[j];
      for (k = b->idx[jj]; k < b->idx[jj+1]; k++)
        kk = b->col_id[k], _spa_add(spa, val*b->val[k], kk, ii);

    } /* End of loop on non-empty columns of row ii of a */

    /* Fill a new row in c and prepare next step */
    if (spa->nnz + idx > size_max)
      _resize_mat(c, spa->nnz + idx, &size_max);
    n_entries = _spa_gather(spa, idx, c->col_id, c->val);
    c->idx[ii+1] = idx + n_entries;
    idx = c->idx[ii+1];

  } /* End of loop on row ii of a */

  /* Memory management */
  BFT_REALLOC(c->col_id, c->idx[c->n_rows], cs_lnum_t);
  BFT_REALLOC(c->val, c->idx[c->n_rows], double);
  spa = _spa_free(spa);

  return c;
}

/*----------------------------------------------------------------------------*/
/*!
 * \brief   Compute c = a*b for a in CSR storage and b in DEC storage
 *
 * \param[in]    a        pointer to the matrix struct. a
 * \param[in]    b        pointer to the matrix struct. b
 *
 * \return a pointer to matrix struct. c
 */
/*----------------------------------------------------------------------------*/

static cs_sla_matrix_t *
_multiply_csrdec_matrices(const cs_sla_matrix_t  *a,
                          const cs_sla_matrix_t  *b)
{
  int  ii, j, jj, k, kk;
  double  val;

  size_t  idx = 0, n_entries = 0, size_max = 0, lst_size_init = 0;
  _spa_t  *spa = NULL;
  cs_sla_matrix_t  *c = NULL;

  /* Sanity checks */
  assert(a->type == CS_SLA_MAT_CSR && b->type == CS_SLA_MAT_DEC);

  /* Initialize structures */
  _estimate_sizes(a, b, &size_max, &lst_size_init);
  c = _init_mat(a, b, CS_SLA_MAT_CSR, size_max);
  spa = _spa_init(b->n_cols, lst_size_init);

  /* Compute c = a*b line by line */
  for (ii = 0; ii < a->n_rows; ii++) {

    for (j = a->idx[ii]; j < a->idx[ii+1]; j++) {

      jj = a->col_id[j], val = a->val[j];
      for (k = b->idx[jj]; k < b->idx[jj+1]; k++)
        kk = b->col_id[k], _spa_add(spa, val*b->sgn[k], kk, ii);

    } /* End of loop on non-empty columns of row ii of a */

    /* Fill a new row in c and prepare next step */
    if (spa->nnz + idx > size_max)
      _resize_mat(c, spa->nnz + idx, &size_max);
    n_entries = _spa_gather(spa, idx, c->col_id, c->val);
    c->idx[ii+1] = idx + n_entries;
    idx = c->idx[ii+1];

  } /* End of loop on row ii of a */

  /* Memory management */
  BFT_REALLOC(c->col_id, c->idx[c->n_rows], cs_lnum_t);
  BFT_REALLOC(c->val, c->idx[c->n_rows], double);
  spa = _spa_free(spa);

  return c;
}

/*----------------------------------------------------------------------------*/
/*!
 * \brief   Compute c = a*b for a in DEC storage and b in MSR storage
 *
 * \param[in]    a        pointer to the matrix struct. a
 * \param[in]    b        pointer to the matrix struct. b
 *
 * \return a pointer to matrix struct. c
 */
/*----------------------------------------------------------------------------*/

static cs_sla_matrix_t *
_multiply_decmsr_matrices(const cs_sla_matrix_t  *a,
                          const cs_sla_matrix_t  *b)
{
  int  ii, j, jj, k, kk;
  double  val;

  size_t  idx = 0, n_entries = 0, size_max = 0, lst_size_init = 0;
  _spa_t  *spa = NULL;
  cs_sla_matrix_t  *c = NULL;

  /* Sanity checks */
  assert(a->type == CS_SLA_MAT_DEC && b->type == CS_SLA_MAT_MSR);

  /* Initialize structures */
  _estimate_sizes(a, b, &size_max, &lst_size_init);
  c = _init_mat(a, b, CS_SLA_MAT_CSR, size_max);
  spa = _spa_init(b->n_cols, lst_size_init);

  for (ii = 0; ii < a->n_rows; ii++) {

    for (j = a->idx[ii]; j < a->idx[ii+1]; j++) {

      jj = a->col_id[j], val = a->sgn[j];

      /* Diagonal term */
      _spa_add(spa, val*b->diag[jj], jj, ii);

      /* Extra diag term */
      for (k = b->idx[jj]; k < b->idx[jj+1]; k++)
        kk = b->col_id[k], _spa_add(spa, val*b->val[k], kk, ii);

    } /* End of loop on non-empty columns of row ii of a */

    /* Fill a new row in c and prepare next step */
    if (spa->nnz + idx > size_max)
      _resize_mat(c, spa->nnz + idx, &size_max);
    n_entries = _spa_gather(spa, idx, c->col_id, c->val);
    c->idx[ii+1] = idx + n_entries;
    idx = c->idx[ii+1];

  } /* End of loop on row ii of a */

  /* Memory management */
  BFT_REALLOC(c->col_id, c->idx[c->n_rows], cs_lnum_t);
  BFT_REALLOC(c->val, c->idx[c->n_rows], double);
  spa = _spa_free(spa);

  return c;
}

/*----------------------------------------------------------------------------*/
/*!
 * \brief   Compute c = a*b for a in MSR storage and b in DEC storage
 *
 * \param[in]    a        pointer to the matrix struct. a
 * \param[in]    b        pointer to the matrix struct. b
 *
 * \return a pointer to matrix struct. c
 */
/*----------------------------------------------------------------------------*/

static cs_sla_matrix_t *
_multiply_msrdec_matrices(const cs_sla_matrix_t  *a,
                          const cs_sla_matrix_t  *b)
{
  int  ii, j, jj, k, kk;
  double  val;

  size_t  idx = 0, n_entries = 0, size_max = 0, lst_size_init = 0;
  _spa_t  *spa = NULL;
  cs_sla_matrix_t  *c = NULL;

  /* Sanity checks */
  assert(a->type == CS_SLA_MAT_MSR && b->type == CS_SLA_MAT_DEC);

  /* Initialize structures */
  _estimate_sizes(a, b, &size_max, &lst_size_init);
  c = _init_mat(a, b, CS_SLA_MAT_CSR, size_max);
  spa = _spa_init(b->n_cols, lst_size_init);

  /* Compute c = a*b line by line */
  for (ii = 0; ii < a->n_rows; ii++) {

    /* Diagonal term */
    val = a->diag[ii];
    for (k = b->idx[ii]; k < b->idx[ii+1]; k++)
      kk = b->col_id[k], _spa_add(spa, val*b->sgn[k], kk, ii);

    /* Extra-diagonal terms */
    for (j = a->idx[ii]; j < a->idx[ii+1]; j++) {

      jj = a->col_id[j], val = a->val[j];
      for (k = b->idx[jj]; k < b->idx[jj+1]; k++)
        kk = b->col_id[k], _spa_add(spa, val*b->sgn[k], kk, ii);

    } /* End of loop on non-empty columns of row ii of a */

    /* Fill a new row in c and prepare next step */
    if (spa->nnz + idx > size_max)
      _resize_mat(c, spa->nnz + idx, &size_max);
    n_entries = _spa_gather(spa, idx, c->col_id, c->val);
    c->idx[ii+1] = idx + n_entries;
    idx = c->idx[ii+1];

  } /* End of loop on row ii of a */

  /* Memory management */
  BFT_REALLOC(c->col_id, c->idx[c->n_rows], cs_lnum_t);
  BFT_REALLOC(c->val, c->idx[c->n_rows], double);
  spa = _spa_free(spa);

  return c;
}

/*----------------------------------------------------------------------------*/
/*!
 * \brief   Compute the product C = At * Diag * A
 *          where A and At are DEC matrices
 *
 * \param[in]       At   pointer to a cs_sla_matrix_t struct. (DEC type)
 * \param[in]       D    array standing for a diagonal operator
 * \param[in]       A    pointer to a cs_sla_matrix_t struct. (DEC type)
 * \param[in, out]  C    pointer to a cs_sla_matrix_t storing the result
 * \param[in, out]  w    work buffer
 */
/*----------------------------------------------------------------------------*/

static void
_decdec_AtDA(const cs_sla_matrix_t  *At,
             const double            D[],
             const cs_sla_matrix_t  *A,
             cs_sla_matrix_t        *C,
             int                    *w)
{
  int  ii, j, jj, kk, k, shift;
  double  val;

  int  size = 0, size_max = At->n_rows;

  /* Sanity check */
  assert(A->type == CS_SLA_MAT_DEC);
  assert(At->type == CS_SLA_MAT_DEC);

  /* Default allocation */
  BFT_MALLOC(C->col_id, size_max, cs_lnum_t);
  BFT_MALLOC(C->val, size_max, double);

  /* Compute the double multiplication */
  for (ii = 0; ii < At->n_rows; ii++) {
    for (j = At->idx[ii]; j < At->idx[ii+1]; j++) {

      jj = At->col_id[j];
      val = D[jj-1] * At->sgn[j];

      for (k = A->idx[jj]; k < A->idx[jj+1]; k++) {

        kk = A->col_id[k];
        shift = w[kk];

        if (shift == -1) { /* Add a new entry */
          if (size + 1 > size_max) { /* Realloc buffers */
            size_max *= 1.5;
            assert(size_max > size);
            BFT_REALLOC(C->col_id, size_max, cs_lnum_t);
            BFT_REALLOC(C->val, size_max, double);
          }

          w[kk] = size;
          C->col_id[size] = kk;
          C->val[size] = val * A->sgn[k];
          size++;

        }
        else /* Entry is already defined */
          C->val[shift] += val * A->sgn[k];

      } /* End of loop on non-empty coloms of row jj of A */
    } /* End of loop on non-empty coloms of row ii of At */

    C->idx[ii+1] = size;
    shift = C->idx[ii];

    for (k = shift; k < C->idx[ii+1]; k++) {
      w[C->col_id[k]] = -1;
      if (fabs(C->val[k]) > cs_math_zero_threshold) { /* Clean zero entry */
        if (k != shift) {
          C->col_id[shift] = C->col_id[k];
          C->val[shift] = C->val[k];
        }
        shift++;
      }
    } /* End of loop on new elements */

    C->idx[ii+1] = shift;
    size = shift;

  } /* End of loop on row ii of a */

}

/*----------------------------------------------------------------------------*/
/*!
 * \brief   Compute the product C = At * Diag * A
 *          where A and At are CSR matrices
 *
 * \param[in]       At   pointer to a cs_sla_matrix_t struct. (CSR type)
 * \param[in]       D    array standing for a diagonal operator
 * \param[in]       A    pointer to a cs_sla_matrix_t struct. (CSR type)
 * \param[in, out]  C    pointer to a cs_sla_matrix_t storing the result
 * \param[in, out]  w    work buffer
 */
/*----------------------------------------------------------------------------*/

static void
_csrcsr_AtDA(const cs_sla_matrix_t  *At,
             const double            D[],
             const cs_sla_matrix_t  *A,
             cs_sla_matrix_t        *C,
             int                    *w)
{
  int  ii, j, jj, kk, k, shift;
  double  val;

  int  size = 0, size_max = A->n_rows;

  /* Sanity check */
  assert(A->type == CS_SLA_MAT_CSR);
  assert(At->type == CS_SLA_MAT_CSR);

  /* Default allocation */
  BFT_MALLOC(C->col_id, size_max, int);
  BFT_MALLOC(C->val, size_max, double);

  /* Compute the double multiplication */
  for (ii = 0; ii < At->n_rows; ii++) {
    for (j = At->idx[ii]; j < At->idx[ii+1]; j++) {

      jj = At->col_id[j];
      val = D[jj] * At->val[j];

      for (k = A->idx[jj]; k < A->idx[jj+1]; k++) {

        kk = A->col_id[k];
        shift = w[kk];

        if (shift == -1) { /* Add a new entry */
          if (size + 1 > size_max) { /* Realloc buffers */
            size_max *= 1.5;
            assert(size_max > size);
            BFT_REALLOC(C->col_id, size_max, int);
            BFT_REALLOC(C->val, size_max, double);
          }

          w[kk] = size;
          C->col_id[size] = kk;
          C->val[size] = val * A->val[k];
          size++;

        }
        else /* Entry is already defined */
          C->val[shift] += val * A->val[k];

      } /* End of loop on non-empty coloms of row jj of A */
    } /* End of loop on non-empty coloms of row ii of At */

    C->idx[ii+1] = size;
    shift = C->idx[ii];

    for (k = shift; k < C->idx[ii+1]; k++) {
      w[C->col_id[k]] = -1;
      if (fabs(C->val[k]) > cs_math_zero_threshold) { /* Clean zero entry */
        if (k != shift) {
          C->col_id[shift] = C->col_id[k];
          C->val[shift] = C->val[k];
        }
        shift++;
      }
    } /* End of loop on new elements */

    C->idx[ii+1] = shift;
    size = shift;

  } /* End of loop on row ii of a */

}

/*----------------------------------------------------------------------------*/
/*!
 * \brief   Fill a matrix resulting from an extraction of row/column for
 *          matrix in DEC format
 *
 * \param[in, out]  final        pointer to the final matrix struct.
 * \param[in]       init         init matrix to work with
 * \param[in]       row_z2i_ids  zipped -> init numbering for rows
 * \param[in]       col_i2z_ids  init   -> zipped numbering for columns
 *
 * \return a pointer to the new final matrix struct
 */
/*----------------------------------------------------------------------------*/

static void
_pack_dec(cs_sla_matrix_t         *final,
          const cs_sla_matrix_t   *init,
          const cs_lnum_t         *row_z2i_ids,
          const cs_lnum_t         *col_i2z_ids)
{
  int  j, shift, zrow_id, irow_id, icol_id;

  /* Fill entries */
  if (final->n_cols == init->n_cols) { /* No extraction of columns */

    for (zrow_id = 0; zrow_id < final->n_rows; zrow_id++) {
      irow_id = row_z2i_ids[zrow_id];
      shift = final->idx[zrow_id];
      for (j = init->idx[irow_id]; j < init->idx[irow_id+1]; j++, shift++) {
        final->col_id[shift] = init->col_id[j];
        final->sgn[shift] = init->sgn[j];
      }
    }

  }
  else {

    for (zrow_id = 0; zrow_id < final->n_rows; zrow_id++) {
      irow_id = row_z2i_ids[zrow_id];
      shift = final->idx[zrow_id];
      for (j = init->idx[irow_id]; j < init->idx[irow_id+1]; j++) {
        icol_id = init->col_id[j];
        if (col_i2z_ids[icol_id] > -1) { /* Not removed */
          final->col_id[shift] = col_i2z_ids[icol_id];
          final->sgn[shift] = init->sgn[j];
          shift++;
        }
      } /* Loop on columns in init */

    } /* Loop on rows in final */

  }

}

/*----------------------------------------------------------------------------*/
/*!
 * \brief   Fill a matrix resulting from an extraction of row/column for
 *          matrix in CSR format
 *
 * \param[in, out]  final        pointer to the block matrix struct.
 * \param[in]       init         init matrix to work with
 * \param[in]       row_z2i_ids  zipped -> init numbering for rows
 * \param[in]       col_i2z_ids  init -> zipped numbering for columns
 *
 * \return a pointer to the new final matrix struct
 */
/*----------------------------------------------------------------------------*/

static void
_pack_csr(cs_sla_matrix_t         *final,
          const cs_sla_matrix_t   *init,
          const cs_lnum_t         *row_z2i_ids,
          const cs_lnum_t         *col_i2z_ids)
{
  int  j, shift, zrow_id, irow_id, icol_id;

  /* Fill entries */
  if (final->n_cols == init->n_cols) { /* No extraction of columns */

    for (zrow_id = 0; zrow_id < final->n_rows; zrow_id++) {
      irow_id = row_z2i_ids[zrow_id];
      shift = final->idx[zrow_id];
      for (j = init->idx[irow_id]; j < init->idx[irow_id+1]; j++, shift++) {
        final->col_id[shift] = init->col_id[j];
        final->val[shift] = init->val[j];
      }
    }

  }
  else {

    for (zrow_id = 0; zrow_id < final->n_rows; zrow_id++) {
      irow_id = row_z2i_ids[zrow_id];
      shift = final->idx[zrow_id];
      for (j = init->idx[irow_id]; j < init->idx[irow_id+1]; j++) {
        icol_id = init->col_id[j];
        if (col_i2z_ids[icol_id] > -1) { /* Not removed */
          final->col_id[shift] = col_i2z_ids[icol_id];
          final->val[shift] = init->val[j];
          shift++;
        }
      } /* Loop on columns in init */

    } /* Loop on rows in final */

  }

}

/*----------------------------------------------------------------------------*/
/*!
 * \brief   Fill a matrix resulting from an extraction of row/column for
 *          matrix in MSR format
 *
 * \param[in, out]  final        pointer to the block matrix struct.
 * \param[in]       init         init matrix to work with
 * \param[in]       row_z2i_ids  zipped -> init numbering for rows
 * \param[in]       col_i2z_ids  init -> zipped numbering for columns
 * \param[in]       msr2csr      change matrix type
 *
 * \return a pointer to the new final matrix struct
 */
/*----------------------------------------------------------------------------*/

static void
_pack_msr(cs_sla_matrix_t         *final,
          const cs_sla_matrix_t   *init,
          const cs_lnum_t         *row_z2i_ids,
          const cs_lnum_t         *col_i2z_ids,
          _Bool                    msr2csr)
{
  int  j, shift, zrow_id, irow_id, icol_id;

  /* Fill entries */
  if (final->n_cols == init->n_cols) { /* No extraction of columns */

    if (msr2csr) {

      for (zrow_id = 0; zrow_id < final->n_rows; zrow_id++) {
        shift = final->idx[zrow_id];
        irow_id = row_z2i_ids[zrow_id];
        if (zrow_id < final->n_cols) { // Diag. entry
          final->col_id[shift] = zrow_id;
          final->val[shift] = init->diag[irow_id];
          shift++;
        }
        for (j = init->idx[irow_id]; j < init->idx[irow_id+1]; j++, shift++) {
          final->col_id[shift] = init->col_id[j];
          final->val[shift] = init->val[j];
        }
      }

    }
    else { /* msr2csr = false */

      for (zrow_id = 0; zrow_id < final->n_rows; zrow_id++) {
        irow_id = row_z2i_ids[zrow_id];
        final->diag[zrow_id] = init->diag[irow_id];
        shift = final->idx[zrow_id];
        for (j = init->idx[irow_id]; j < init->idx[irow_id+1]; j++, shift++) {
          final->col_id[shift] = init->col_id[j];
          final->val[shift] = init->val[j];
        }
      }

    } /* msr2csr */

  }
  else { /* Column and row extraction */

    if (msr2csr) {

      for (zrow_id = 0; zrow_id < final->n_rows; zrow_id++) {
        irow_id = row_z2i_ids[zrow_id];
        shift = final->idx[zrow_id];
        if (zrow_id < final->n_cols) {
          final->col_id[shift] = zrow_id;
          final->val[shift] = init->diag[irow_id];
          shift++;
        }
        for (j = init->idx[irow_id]; j < init->idx[irow_id+1]; j++) {
          icol_id = init->col_id[j];
          if (col_i2z_ids[icol_id] > -1) { /* Not removed */
            final->col_id[shift] = col_i2z_ids[icol_id];
            final->val[shift] = init->val[j];
            shift++;
          }
        } /* Loop on columns in init */
      } /* Loop on rows in final */

    }
    else { /* msr2csr = false */

      for (zrow_id = 0; zrow_id < final->n_rows; zrow_id++) {
        irow_id = row_z2i_ids[zrow_id];
        final->diag[zrow_id] = init->diag[irow_id];
        shift = final->idx[zrow_id];
        for (j = init->idx[irow_id]; j < init->idx[irow_id+1]; j++) {
          icol_id = init->col_id[j];
          if (col_i2z_ids[icol_id] > -1) { /* Not removed */
            final->col_id[shift] = col_i2z_ids[icol_id];
            final->val[shift] = init->val[j];
            shift++;
          }
        } /* Loop on columns in init */
      } /* Loop on rows in final */

    } /* test msr2csr */

  } /* test final->n_cols */

}

/*============================================================================
 * Public function prototypes
 *============================================================================*/

/*----------------------------------------------------------------------------*/
/*!
 * \brief   Create a cs_sla_matrix_t structure
 *
 * \param[in]  n_rows     number of rows
 * \param[in]  n_cols     number of columns
 * \param[in]  stride     number of values related to each entry
 * \param[in]  type       kind of matrix
 * \param[in]  sym        true or false
 *
 * \return  a pointer to new allocated matrix structure
 */
/*----------------------------------------------------------------------------*/

cs_sla_matrix_t *
cs_sla_matrix_create(cs_lnum_t             n_rows,
                     cs_lnum_t             n_cols,
                     int                   stride,
                     cs_sla_matrix_type_t  type,
                     bool                  sym)
{
  cs_sla_matrix_t  *m = NULL;

  assert(n_rows > -1 && n_cols > -1);

  BFT_MALLOC(m, 1, cs_sla_matrix_t);

  /* Default initialization */
  m->info.stencil_min = 0;
  m->info.stencil_max = 0;
  m->info.stencil_mean = 0;
  m->info.nnz = 0;
  m->info.fillin = 0;

  m->n_rows = n_rows;
  m->n_cols = n_cols;
  m->stride = stride;
  m->type = type;
  m->flag = 0;
  if (sym) m->flag |= CS_SLA_MATRIX_SYM;

  m->diag = NULL;
  m->idx = NULL;
  m->didx = NULL;
  m->col_id = NULL;
  m->sgn = NULL;
  m->val = NULL;

  if (m->type != CS_SLA_MAT_NONE) {

    BFT_MALLOC(m->idx, n_rows + 1, int);
# pragma omp parallel for if (m->n_rows > CS_THR_MIN)
    for (cs_lnum_t i = 0; i < n_rows + 1; i++)
      m->idx[i] = 0;

    if (m->type == CS_SLA_MAT_CSR && n_rows == n_cols) {
      BFT_MALLOC(m->didx, n_rows, int);
# pragma omp parallel for if (m->n_rows > CS_THR_MIN)
      for (cs_lnum_t i = 0; i < n_rows; i++)
        m->didx[i] = -1; /* Not set */
    }

    if (m->type == CS_SLA_MAT_MSR) {
      assert(n_rows == n_cols);
      BFT_MALLOC(m->diag, stride*n_rows, double);
# pragma omp parallel for if (m->n_rows > CS_THR_MIN)
      for (cs_lnum_t i = 0; i < stride*n_cols; i++)
        m->diag[i] = 0.0;
    }

  } /* Not an undefined type */

  return m;
}

/*----------------------------------------------------------------------------*/
/*!
 * \brief   Create a cs_sla_matrix_t structure from an existing one.
 *          idx, didx and col_id are shared with ref.
 *          Initialize related buffers.
 *
 * \param[in]  ref      pointer to a reference matrix with the same pattern
 * \param[in]  type     type of the matrix to create
 * \param[in]  stride   number of values for each entry
 *
 * \return  a pointer to new allocated matrix structure
 */
/*----------------------------------------------------------------------------*/

cs_sla_matrix_t *
cs_sla_matrix_create_from_ref(const cs_sla_matrix_t   *ref,
                              cs_sla_matrix_type_t     type,
                              int                      stride)
{
  cs_lnum_t  nnz = 0;

  cs_sla_matrix_t  *m = NULL;

  /* Sanity check */
  assert(ref != NULL);
  assert(ref->type != CS_SLA_MAT_NONE);

  BFT_MALLOC(m, 1, cs_sla_matrix_t);

  /* Default initialization */
  if (ref->flag & CS_SLA_MATRIX_INFO) {
    m->info.stencil_min = ref->info.stencil_min;
    m->info.stencil_max = ref->info.stencil_max;
    m->info.stencil_mean = ref->info.stencil_mean;
    nnz = m->info.nnz = ref->info.nnz;
    m->info.fillin = ref->info.fillin;
  }
  else {
    m->info.stencil_min = 0;
    m->info.stencil_max = 0;
    m->info.stencil_mean = 0;
    m->info.nnz = 0;
    m->info.fillin = 0;
  }

  m->type = type;
  m->n_rows = ref->n_rows;
  m->n_cols = ref->n_cols;
  m->stride = stride;
  m->diag = NULL;
  m->sgn = NULL;
  m->val = NULL;

  m->flag = ref->flag | CS_SLA_MATRIX_SHARED;
  m->idx = ref->idx;
  m->col_id = ref->col_id;
  m->didx = ref->didx;

  if (nnz == 0)
    nnz = m->idx[m->n_rows];

  switch (m->type) {

  case CS_SLA_MAT_DEC:
    assert(stride == 1);
    BFT_MALLOC(m->sgn, nnz, short int);
# pragma omp parallel for if (nnz > CS_THR_MIN)
    for (cs_lnum_t i = 0; i < nnz; i++)
      m->sgn[i] = 0;
    break;

  case CS_SLA_MAT_CSR:
    BFT_MALLOC(m->val, nnz*stride, double);
# pragma omp parallel for if (stride*nnz > CS_THR_MIN)
    for (cs_lnum_t i = 0; i < stride*nnz; i++)
      m->val[i] = 0.0;
    break;

  case CS_SLA_MAT_MSR:
    assert(m->n_rows == m->n_cols);
    BFT_MALLOC(m->diag, stride*m->n_rows, double);
# pragma omp parallel for if (m->n_rows > CS_THR_MIN)
    for (cs_lnum_t i = 0; i < stride*m->n_rows; i++)
      m->diag[i] = 0.0;
    BFT_MALLOC(m->val, nnz*stride, double);
# pragma omp parallel for if (nnz > CS_THR_MIN)
    for (cs_lnum_t i = 0; i < stride*nnz; i++)
      m->val[i] = 0.0;
    break;

  default:
    break; // Nothing to do

  } /* End of switch */

  return m;
}

/*----------------------------------------------------------------------------*/
/*!
 * \brief   Create a cs_sla_matrix_t structure with MSR type from an existing
 *          connectivity index.
 *          Be aware of removing the diagonal entry in the connectivity index
 *          before the call to this routine.
 *
 * \param[in]  connect_idx     pointer to a connectivity index
 * \param[in]  is_symmetric    true or false
 * \param[in]  sorted_idx      true if the connectivity index is sorted
 * \param[in]  stride          number of values for each entry
 *
 * \return  a pointer to new (shared) matrix structure
 */
/*----------------------------------------------------------------------------*/

cs_sla_matrix_t *
cs_sla_matrix_create_msr_from_index(const cs_connect_index_t   *connect_idx,
                                    bool                        is_symmetric,
                                    bool                        sorted_idx,
                                    int                         stride)
{
  cs_sla_matrix_t  *m = NULL;

  /* Sanity check */
  assert(connect_idx != NULL);

  BFT_MALLOC(m, 1, cs_sla_matrix_t);

  m->type = CS_SLA_MAT_MSR;
  m->n_rows = connect_idx->n;
  m->n_cols = connect_idx->n;
  m->stride = stride;
  m->idx = connect_idx->idx;
  m->col_id = connect_idx->ids;
  m->flag = CS_SLA_MATRIX_SHARED;
  if (sorted_idx) m->flag |= CS_SLA_MATRIX_SORTED;
  if (is_symmetric) m->flag |= CS_SLA_MATRIX_SYM;

  /* not used by default for MSR matrix */
  m->didx = NULL;
  m->sgn = NULL;

  /* Compute information on index */
  cs_sla_matrix_set_info(m);

  /* Initialize diagonal */
  m->diag = NULL;
  BFT_MALLOC(m->diag, stride*m->n_rows, cs_real_t);
# pragma omp parallel for if (m->n_rows*stride > CS_THR_MIN)
  for (cs_lnum_t i = 0; i < stride*m->n_rows; i++)
    m->diag[i] = 0.0;

  /* Initialize values */
  m->val = NULL;
  size_t  nnz = m->idx[m->n_rows]*stride;
  BFT_MALLOC(m->val, nnz, cs_real_t);
# pragma omp parallel for if (nnz > CS_THR_MIN)
  for (size_t i = 0; i < nnz; i++)
    m->val[i] = 0.0;

  return m;
}

/*----------------------------------------------------------------------------*/
/*!
 * \brief   Create a new matrix structure from the copy of an existing one.
 *
 * \param[in] a       matrix to copy
 * \param[in] shared  true: index information (idx, col_id) is shared
 *
 * \return the matrix corresponding to this operation
 */
/*----------------------------------------------------------------------------*/

cs_sla_matrix_t *
cs_sla_matrix_copy(const cs_sla_matrix_t  *a,
                   bool                    shared)
{
  cs_sla_matrix_t  *b = NULL;

  if (a == NULL)
    return b;

  if (shared)
    b = cs_sla_matrix_create_from_ref(a, a->type, a->stride);

  else { /* Create and copy pattern */

    if (a->flag & CS_SLA_MATRIX_SYM)
      b = cs_sla_matrix_create(a->n_rows, a->n_cols, a->stride, a->type, true);
    else
      b = cs_sla_matrix_create(a->n_rows, a->n_cols, a->stride, a->type, false);

    if (a->type != CS_SLA_MAT_NONE) { /* Copy pattern */

      /* Copy matrix info */
      b->info.stencil_min = a->info.stencil_min;
      b->info.stencil_max = a->info.stencil_max;
      b->info.stencil_mean = a->info.stencil_mean;
      b->info.nnz = a->info.nnz;
      b->info.fillin = a->info.fillin;

      b->flag = a->flag;

      BFT_MALLOC(b->col_id, a->idx[a->n_rows], cs_lnum_t);
      memcpy(b->idx, a->idx, (a->n_rows+1)*sizeof(cs_lnum_t));
      memcpy(b->col_id, a->col_id, a->idx[a->n_rows]*sizeof(cs_lnum_t));

      if (a->didx != NULL) {
        BFT_MALLOC(b->didx, a->n_rows, int);
        memcpy(b->didx, a->didx, a->n_rows*sizeof(cs_lnum_t));
      }

    } /* type != CS_SLA_MAT_NONE */

    size_t  idx_size = a->idx[a->n_rows];

    switch (a->type) {

    case CS_SLA_MAT_DEC:
      assert(a->stride == 1);
      BFT_MALLOC(b->sgn, idx_size, short int);
      memcpy(b->sgn, a->sgn, idx_size*sizeof(short int));
      break;

    case CS_SLA_MAT_CSR:
      BFT_MALLOC(b->val, idx_size*a->stride, double);
      memcpy(b->val, a->val, a->stride*idx_size*sizeof(double));
      break;

    case CS_SLA_MAT_MSR:
      /* Diag has been allocated in cs_matrix_create() */
      memcpy(b->diag, a->diag, a->n_rows*a->stride*sizeof(double));
      BFT_MALLOC(b->val, idx_size*a->stride, double);
      memcpy(b->val, a->val, a->stride*idx_size*sizeof(double));
      break;

    default:
      break; // Nothing to do

    } /* End of switch */

  } /* Shared or not */

  return b;
}

/*----------------------------------------------------------------------------*/
/*!
 * \brief   Transpose a cs_sla_matrix_t structure
 *
 * \param[in]  a       matrix to transpose
 *
 * \return  a pointer to new allocated matrix which is transposed to mat
 */
/*----------------------------------------------------------------------------*/

cs_sla_matrix_t *
cs_sla_matrix_transpose(const cs_sla_matrix_t  *a)
{
  int  i, j, nnz, shift, row_id;

  int  *count = NULL;
  cs_sla_matrix_t  *at = NULL;

  if (a == NULL)
    return at;

  if (a->stride > 1)
    bft_error(__FILE__, __LINE__, 0, _sla_err_stride);

  /* Simple cases: symmetric matrix */
  if (a->flag & CS_SLA_MATRIX_SYM) {
    at = cs_sla_matrix_copy(a, true); /* share pattern with a */
    return at;
  }

  at = cs_sla_matrix_create(a->n_cols, a->n_rows, a->stride, a->type, false);

  if (a->type == CS_SLA_MAT_NONE)
    return at;

  /* General case: 1) build index */
  BFT_MALLOC(at->col_id, a->idx[a->n_rows], cs_lnum_t);
  BFT_MALLOC(count, at->n_rows, int);

  for (i = 0; i < a->n_rows; i++)
    for (j = a->idx[i]; j < a->idx[i+1]; j++)
      at->idx[a->col_id[j]+1] += 1;

  for (i = 0; i < at->n_rows; i++) {
    count[i] = 0;
    at->idx[i+1] += at->idx[i];
  }

  nnz = a->idx[a->n_rows];
  assert(at->idx[at->n_rows] == nnz);

  switch (a->type) {

  case CS_SLA_MAT_DEC:

    BFT_MALLOC(at->sgn, nnz, short int);

    for (i = 0; i < a->n_rows; i++) {
      for (j = a->idx[i]; j < a->idx[i+1]; j++) {

        row_id = a->col_id[j];
        shift = at->idx[row_id] + count[row_id];
        at->col_id[shift] = i;
        at->sgn[shift] = a->sgn[j];
        count[row_id] += 1;

      }
    }
    break;

  case CS_SLA_MAT_MSR:

    assert(at->diag != NULL);
    for (i = 0; i < a->n_rows; i++)
      at->diag[i] = a->diag[i];

  case CS_SLA_MAT_CSR:

    BFT_MALLOC(at->val, nnz, double);

    for (i = 0; i < a->n_rows; i++) {
      for (j = a->idx[i]; j < a->idx[i+1]; j++) {

        row_id = a->col_id[j];
        shift = at->idx[row_id] + count[row_id];
        at->col_id[shift] = i;
        at->val[shift] = a->val[j];
        count[row_id] += 1;

      }
    }

    cs_sla_matrix_diag_idx(at);

    break;

  default:
    break;

  } /* End of switch */

  BFT_FREE(count);

  return at;
}

/*----------------------------------------------------------------------------*/
/*!
 * \brief   Free a cs_sla_matrix_t structure
 *
 * \param[in]  m     matrix to free
 *
 * \return  a NULL pointer
 */
/*----------------------------------------------------------------------------*/

cs_sla_matrix_t *
cs_sla_matrix_free(cs_sla_matrix_t  *m)
{
  if (m == NULL)
    return NULL;

  if (m->type != CS_SLA_MAT_NONE) {

    switch (m->type) {

    case CS_SLA_MAT_DEC:
      BFT_FREE(m->sgn);
      break;
    case CS_SLA_MAT_CSR:
      BFT_FREE(m->val);
      if (m->diag != NULL)
        BFT_FREE(m->diag);
      break;
    case CS_SLA_MAT_MSR:
      BFT_FREE(m->val);
      BFT_FREE(m->diag);
      break;
    default:
      break;

    } /* End switch */

    /* Common pointers defining the pattern */
    if (!(m->flag & CS_SLA_MATRIX_SHARED)) {
      BFT_FREE(m->idx);
      BFT_FREE(m->col_id);
      if (m->didx != NULL) /* Should be only for square CSR matrix */
        BFT_FREE(m->didx);
    }

  } /* TYPE_NONE */

  m->type = CS_SLA_MAT_NONE;
  BFT_FREE(m);

  return NULL;
}

/*----------------------------------------------------------------------------*/
/*!
 * \brief   Reset to 0 all entries below a given threshold
 *          Only available for CSR and MSR matrices with stride = 1
 *
 * \param[in, out] m             matrix to clean
 * \param[in]      threshold     threshold below one sets the value to zero
 * \param[in]      verbosity     indicate if one prints or not a message
 */
/*----------------------------------------------------------------------------*/

void
cs_sla_matrix_clean_zeros(cs_sla_matrix_t   *m,
                          double             threshold,
                          int                verbosity)
{
  if (m == NULL)
    return;
  if (m->type != CS_SLA_MAT_MSR && m->type != CS_SLA_MAT_CSR)
    return;

  if (m->stride > 1)
    bft_error(__FILE__, __LINE__, 0, _sla_err_stride);

  int  counter = 0;

  for (cs_lnum_t i = 0; i < m->idx[m->n_rows]; i++) {
    if (fabs(m->val[i]) < threshold) { /* Set this value to 0 */
      m->val[i] = 0.;
      counter++;
    } /* End of loop on row entries */
  } /* End of loop on rows */

  if (counter > 0 && verbosity > 2) // temporary
    bft_printf(" -msg- cs_sla_matrix_clean_zeros >>"
               " type: %s; n_rows: %6d; threshold: %6.3e; cleaning done: %d\n",
               _sla_matrix_type[m->type], m->n_rows, threshold, counter);

}

/*----------------------------------------------------------------------------*/
/*!
 * \brief   Set to zero entries in a cs_sla_matrix_t structure if the ratio
 *          |a(i,j)| < eps * max|a(i,j)| is below a given threshold.
 *          Be careful when using this function since one can loose the symmetry
 *          Only available for matrices with stride = 1
 *
 * \param[in, out] m           matrix to clean
 * \param[in]      verbosity   indicate if one prints or not a message
 * \param[in]      threshold   value of the threshold
 */
/*----------------------------------------------------------------------------*/

void
cs_sla_matrix_clean(int                verbosity,
                    double             threshold,
                    cs_sla_matrix_t   *m)
{
  if (m == NULL)
    return;
  if (m->type != CS_SLA_MAT_MSR && m->type != CS_SLA_MAT_CSR)
    return;

  if (m->stride > 1)
    bft_error(__FILE__, __LINE__, 0, _sla_err_stride);

  int  counter = 0;
# pragma omp parallel for reduction(+:counter) if (m->n_rows > CS_THR_MIN)
  for (cs_lnum_t row_id = 0; row_id < m->n_rows; row_id++) {

    /* Get the max absolute value and compute the row threshold */
    double max_val = -DBL_MAX;
    for (cs_lnum_t i = m->idx[row_id]; i < m->idx[row_id+1]; i++)
      max_val = fmax(fabs(m->val[i]), max_val);
    const double _thd = max_val*threshold;

    /* Set to zero too small entries */
    for (cs_lnum_t i = m->idx[row_id]; i < m->idx[row_id+1]; i++) {
      double absval = fabs(m->val[i]);
      if (absval > DBL_MIN && absval < _thd)
        m->val[i] = 0., counter++;
    }

  } // Loop on matrix rows

  if (counter > 0 && verbosity > 2)
    bft_printf(" -msg- Matrix cleaning >>"
               " n_rows: %6d; threshold: %6.3e; %d entries set to zero\n",
               m->n_rows, threshold, counter);

}

/*----------------------------------------------------------------------------*/
/*!
 * \brief   Retrieve the number of non-zeros (nnz) elements in a matrix
 *
 * \param[in]  m       matrix
 *
 * \return the number of nnz
 */
/*----------------------------------------------------------------------------*/

size_t
cs_sla_matrix_get_nnz(const cs_sla_matrix_t   *m)
{
  size_t  nnz = 0;

  if (m == NULL)
    return nnz;

  if (m->type == CS_SLA_MAT_NONE)
    return nnz;

  nnz = m->idx[m->n_rows];
  if (m->type == CS_SLA_MAT_MSR)
    nnz += m->n_rows;

  return nnz;
}

/*----------------------------------------------------------------------------*/
/*!
 * \brief   Build diagonal index
 *
 * \param[in, out]  m   matrix to work with
 */
/*----------------------------------------------------------------------------*/

void
cs_sla_matrix_diag_idx(cs_sla_matrix_t    *m)
{
  cs_lnum_t  row_id, pos;

  if (m == NULL)
    return;

  if (m->type == CS_SLA_MAT_CSR && m->n_rows == m->n_cols) {

    if (m->flag & CS_SLA_MATRIX_SHARED)
      bft_error(__FILE__, __LINE__, 0,
                _(" Cannot build diagonal index. Pattern is shared.\n"
                  " Stop execution.\n"));

    if (m->didx == NULL)
      BFT_MALLOC(m->didx, m->n_rows, int);

    for (row_id = 0; row_id < m->n_rows; row_id++) {
      m->didx[row_id] = -1; /* Default initialization: no diagonal entry */
      for (pos = m->idx[row_id]; pos < m->idx[row_id+1]; pos++) {
        if (m->col_id[pos] == row_id) {
          m->didx[row_id] = pos;
          break;
        }
      }
    } /* Loop on rows */

  } /* CSR + square */

}

/*----------------------------------------------------------------------------*/
/*!
 * \brief   Get the diagonal entries of a given matrix.
 *
 * \param[in]      m        matrix to work with
 * \param[in, out] p_diag   pointer to diag array to define (allocated if NULL)
 */
/*----------------------------------------------------------------------------*/

void
cs_sla_matrix_get_diag(const cs_sla_matrix_t  *m,
                       double                 *p_diag[])
{
  int  i, j, k;

  double  *diag = *p_diag;

  /* Sanity checks */
  assert(m != NULL);
  assert(m->n_rows == m->n_cols); /* Only for squared matrices */
  assert(m->type == CS_SLA_MAT_MSR || m->type == CS_SLA_MAT_CSR);

  if (diag == NULL)
    BFT_MALLOC(diag, m->n_rows*m->stride, double);

  if (m->diag != NULL)
    memcpy(diag, m->diag, m->n_rows*m->stride*sizeof(double));

  else if (m->didx != NULL) { /* Diagonal is straightforward */

    if (m->stride > 1) {
      const int  stride = m->stride;

      for (i = 0; i < m->n_rows; i++) {
        if (m->didx[i] != -1) {
          for (k = 0; k < stride; k++)
            diag[stride*i+k] = m->val[m->didx[i]*stride+k];
        }
        else { /* No diagonal entry */
          for (k = 0; k < stride; k++)
            diag[stride*i+k] = 0;
        }
      } /* Loop on rows */

    }
    else { /* stride == 1 */

      for (i = 0; i < m->n_rows; i++) {
        if (m->didx[i] != -1)
          diag[i] = m->val[m->didx[i]];
        else /* No diagonal entry */
          diag[i] = 0;
      } /* Loop on rows */

    } /* stride == 1 */

  }
  else {

    /* Initialize diagonal entries */
    for (i = 0; i < m->n_rows*m->stride; i++)
      diag[i] = 0.0;

    /* Fill diagonal entries */
    if (m->stride > 1) {

      const int  stride = m->stride;

      for (i = 0; i < m->n_rows; i++) {
        for (j = m->idx[i]; j < m->idx[i+1]; j++) {
          if (m->col_id[j] == i) {
            for (k = 0; k < stride; k++)
              diag[i*stride+k] = m->val[j*stride+k];
            break;
          }
        }
      }

    }
    else {

      for (i = 0; i < m->n_rows; i++) {
        for (j = m->idx[i]; j < m->idx[i+1]; j++) {
          if (m->col_id[j] == i) {
            diag[i] = m->val[j];
            break;
          }
        }
      }

    } /* stride == 1 */

  } /* m->diag == NULL */

  /* return pointer */
  *p_diag = diag;
}

/*----------------------------------------------------------------------------*/
/*!
 * \brief   Sort each row by increasing colomn number
 *
 * \param[in]  m       matrix to sort
 */
/*----------------------------------------------------------------------------*/

void
cs_sla_matrix_sort(cs_sla_matrix_t  *m)
{
  int  ii;

  if (m == NULL)
    return;
  if (m->flag & CS_SLA_MATRIX_SORTED)
    return; /* Nothing to do */

  m->flag |= CS_SLA_MATRIX_SORTED;

  if (m->type == CS_SLA_MAT_CSR || m->type == CS_SLA_MAT_MSR)
    for (ii = 0; ii < m->n_rows; ii++)
      cs_sort_dcoupled_shell(m->idx[ii],
                             m->idx[ii + 1],
                             m->col_id,
                             m->val);

  else if (m->type == CS_SLA_MAT_DEC)
    for (ii = 0; ii < m->n_rows; ii++)
      cs_sort_sicoupled_shell(m->idx[ii],
                              m->idx[ii + 1],
                              m->col_id,
                              m->sgn);
}

/*----------------------------------------------------------------------------*/
/*!
 * \brief   Compute general information related to a cs_sla_matrix_t structure
 *          and store it into a cs_sla_matrix_info_t structure
 *
 * \param[in, out]  m           matrix to analyse
 */
/*----------------------------------------------------------------------------*/

void
cs_sla_matrix_set_info(cs_sla_matrix_t    *m)
{
  int  i;
  cs_data_info_t  dinfo;

  int  *row_size = NULL;

  if (m == NULL)
    return;

  /* Default initialization */
  m->info.stencil_min = 0;
  m->info.stencil_max = 0;
  m->info.stencil_mean = 0;
  m->info.nnz = 0;
  m->info.fillin = 0;

  if (m->type == CS_SLA_MAT_NONE)
    return;

  /* Compute information */
  m->info.nnz = cs_sla_matrix_get_nnz(m);
  m->info.fillin = (double)(m->info.nnz/m->n_rows)*(100./m->n_cols);

  /* Stencil */
  BFT_MALLOC(row_size, m->n_rows, int);
  if (m->type == CS_SLA_MAT_MSR) {
    for (i = 0; i < m->n_rows; i++)
      row_size[i] = 1 + m->idx[i+1] - m->idx[i];
  }
  else {
    for (i = 0; i < m->n_rows; i++)
      row_size[i] = m->idx[i+1] - m->idx[i];
  }

  dinfo = cs_analysis_data(m->n_rows,  // n_elts
                           1,          // stride
                           CS_INT32,   // datatype
                           row_size,   // data
                           false);     // do_abs

  BFT_FREE(row_size);

  /* Stencil information */
  m->info.stencil_min = dinfo.min.number;
  m->info.stencil_max = dinfo.max.number;
  m->info.stencil_mean = dinfo.mean;

  m->flag |= CS_SLA_MATRIX_INFO;

}

/*----------------------------------------------------------------------------*/
/*!
 * \brief   Change matrix representation from MSR to CSR
 *
 * \param[in, out] a     matrix to transform
 */
/*----------------------------------------------------------------------------*/

void
cs_sla_matrix_msr2csr(cs_sla_matrix_t  *a)
{
  int  i, j, s, e, new_nnz;

  cs_lnum_t  shift = 0;
  cs_lnum_t  *new_index = NULL, *new_col_id = NULL;
  double  *new_val = NULL;

  if (a->type == CS_SLA_MAT_CSR) /* Nothing to do */
    return;

  if (a->type != CS_SLA_MAT_MSR)
    bft_error(__FILE__, __LINE__, 0,
              "  Incompatible matrix type.\n"
              "  Cannot convert matrix from MSR -> CSR\n");

  if (a->stride > 1) /* Should not be useful */
    bft_error(__FILE__, __LINE__, 0, _sla_err_stride);

  /* Sanity checks */
  assert(a->diag != NULL);

  /* Allocate new buffers */
  BFT_MALLOC(new_index, a->n_rows + 1, cs_lnum_t);
  new_index[0] = 0;
  new_nnz = a->idx[a->n_rows] + a->n_rows;
  BFT_MALLOC(new_col_id, new_nnz, cs_lnum_t);
  BFT_MALLOC(new_val, new_nnz, double);

  /* Fill new buffers */
  for (i = 0; i < a->n_rows; i++) {

    s = a->idx[i], e = a->idx[i+1];

    /* Diagonal term */
    new_col_id[shift] = i;
    new_val[shift] = a->diag[i];
    shift++;

    /* Extra_diagonal terms */
    for (j = s; j < e; j++) {
      new_col_id[shift] = a->col_id[j];
      new_val[shift] = a->val[j];
      shift++;
    }
    new_index[i+1] = shift;

  } /* End of loop on rows */

  /* Change elements of the matrix structure */
  BFT_FREE(a->idx);
  BFT_FREE(a->col_id);
  BFT_FREE(a->val);
  BFT_FREE(a->diag);

  a->diag = NULL;
  a->idx = new_index;
  a->col_id = new_col_id;
  a->val = new_val;
  a->type = CS_SLA_MAT_CSR;
}

/*----------------------------------------------------------------------------*/
/*!
 * \brief   Change matrix representation from CSR to MSR
 *
 * \param[in, out] a     matrix to transform
 */
/*----------------------------------------------------------------------------*/

void
cs_sla_matrix_csr2msr(cs_sla_matrix_t  *a)
{
  int  row_id, j, s, e, new_nnz;

  cs_lnum_t  shift = 0;

  if (a->type == CS_SLA_MAT_MSR) /* Nothing to do */
    return;

  /* Sanity checks */
  assert(a->diag == NULL);
  assert(a->n_rows == a->n_cols); /* Only for squared matrices */

  if (a->type != CS_SLA_MAT_CSR)
    bft_error(__FILE__, __LINE__, 0,
              "  Incompatible matrix type.\n"
              "  Cannot convert matrix from CSR -> MSR\n");

  if (a->stride > 1) /* Should not be useful */
    bft_error(__FILE__, __LINE__, 0, _sla_err_stride);

  /* Allocate new buffers */
  BFT_MALLOC(a->diag, a->n_rows, double);
  for (row_id = 0; row_id < a->n_rows; row_id++)
    a->diag[row_id] = 0;

  /* Modify existing entries and fill diag */
  s = a->idx[0];
  for (row_id = 0; row_id < a->n_rows; row_id++) {

    /* Extra_diagonal terms */
    e = a->idx[row_id+1];
    for (j = s; j < e; j++) {

      if (a->col_id[j] == row_id)  /* Diagonal entry */
        a->diag[row_id] = a->val[j];
      else {                       /* Extra diag. entry */
        a->col_id[shift] = a->col_id[j];
        a->val[shift] = a->val[j];
        shift++;
      }

    }
    a->idx[row_id+1] = shift;
    s = e;

  } /* End of loop on rows */

  /* Change elements of the matrix structure */
  new_nnz = shift;
  BFT_REALLOC(a->col_id, new_nnz, cs_lnum_t);
  BFT_REALLOC(a->val, new_nnz, double);
  a->type = CS_SLA_MAT_MSR;
}

/*----------------------------------------------------------------------------*/
/*!
 * \brief   Allocate its own pattern if shared
 *
 * \param[in, out] a     matrix to transform
 */
/*----------------------------------------------------------------------------*/

void
cs_sla_matrix_share2own(cs_sla_matrix_t  *a)
{
  int  *p = NULL;

  if (a == NULL)
    return;

  if (a->flag & CS_SLA_MATRIX_SHARED) { /* Pattern is shared */

    p = a->idx;
    BFT_MALLOC(a->idx, a->n_rows + 1, cs_lnum_t);
    memcpy(a->idx, p, (a->n_rows+1)*sizeof(cs_lnum_t));

    p = a->col_id;
    BFT_MALLOC(a->col_id, a->idx[a->n_rows], cs_lnum_t);
    memcpy(a->col_id, p, a->idx[a->n_rows]*sizeof(cs_lnum_t));

    if (a->didx != NULL) {
      p = a->didx;
      BFT_MALLOC(a->didx, a->n_rows, int);
      memcpy(a->didx, p, a->n_rows*sizeof(int));
    }

    a->flag = a->flag ^ CS_SLA_MATRIX_SHARED;
  }

}

/*----------------------------------------------------------------------------*/
/*!
 * \brief   Assemble a MSR matrix from local contributions
 *          --> We assume that the local matrices are symmetric
 *          --> We assume that the assembled matrix has its columns sorted
 *
 * \param[in]       loc        pointer to a local matrix
 * \param[in, out]  ass        pointer to a cs_sla_matrix_t struct.
 * \param[in]       only_diag  true if assembly is only for diagonal terms
 */
/*----------------------------------------------------------------------------*/

void
cs_sla_assemble_msr_sym(const cs_locmat_t   *loc,
                        cs_sla_matrix_t     *ass,
                        bool                 only_diag)
{
  int  i, j, k_ij, k_ji;

  const int  n_ent = loc->n_ent;

  assert(ass->type == CS_SLA_MAT_MSR);
  assert(ass->flag & (CS_SLA_MATRIX_SYM | CS_SLA_MATRIX_SORTED));

  /* Assemble local contributions into ass */
  for (i = 0; i < n_ent; i++) {

    const short int  pos_i = i*n_ent;
    const cs_lnum_t  i_id = loc->ids[i];

    /* Add diagonal term : loc(i,i) */
    ass->diag[i_id] += loc->val[pos_i+i];

    if (!only_diag) {

      const cs_lnum_t  start_i = ass->idx[i_id];
      const size_t  n_i_ents = ass->idx[i_id+1] - start_i; // arg. binary search

      for (j = i + 1; j < n_ent; j++) {

        double  val_ij = loc->val[pos_i+j];

        if (fabs(val_ij) > cs_math_zero_threshold) { /* Not zero */

          int  j_id = loc->ids[j];
          cs_lnum_t  start_j = ass->idx[j_id];
          size_t  n_j_ents = ass->idx[j_id+1] - start_j;

          /* First add: loc(i,j) */
          k_ij = cs_search_binary(n_i_ents, j_id, &(ass->col_id[start_i]));

#if defined(DEBUG) && !defined(NDEBUG) && CS_SLA_DBG > 0 /* Sanity check */
          if (k_ij < 0)
            bft_error(__FILE__, __LINE__, 0,
                      " Error detected while assembling a matrix.\n"
                      " An non-zero entry has not been found.");
#endif

          ass->val[start_i+k_ij] += val_ij;

          /* Second add: loc(j,i) */
          k_ji = cs_search_binary(n_j_ents, i_id, &(ass->col_id[start_j]));

#if defined(DEBUG) && !defined(NDEBUG) && CS_SLA_DBG > 0 /* Sanity check */
          if (k_ji < 0)
            bft_error(__FILE__, __LINE__, 0,
                      " Error detected while assembling a matrix.\n"
                      " An non-zero entry has not been found.");
#endif

          ass->val[start_j+k_ji] += val_ij;

        } /* loc[ij] != 0.0 */

      } /* Loop on j (Add extra-diag terms) */

    } /* Not only diagonal terms */

  } /* Loop on i (Add diagonal term) */

}

/*----------------------------------------------------------------------------*/
/*!
 * \brief   Assemble a MSR matrix from local contributions
 *          --> We assume that the assembled matrix has its columns sorted
 *
 * \param[in]       loc     pointer to a local matrix
 * \param[in, out]  ass     pointer to a cs_sla_matrix_t struct. collecting data
 */
/*----------------------------------------------------------------------------*/

void
cs_sla_assemble_msr(const cs_locmat_t   *loc,
                    cs_sla_matrix_t     *ass)
{
  int  i, j, k_ij, k_ji;

  const int  n_ent = loc->n_ent;

  assert(ass->type == CS_SLA_MAT_MSR);
  assert(ass->flag & CS_SLA_MATRIX_SORTED);

  /* Assemble local contributions into ass */
  for (i = 0; i < n_ent; i++) {

    short int  pos_i = i*n_ent;
    cs_lnum_t  i_id = loc->ids[i];
    cs_lnum_t  start_i = ass->idx[i_id];
    size_t  n_i_ents = ass->idx[i_id+1] - start_i; // arg. binary search

    /* Add diagonal term : loc(i,i) */
    ass->diag[i_id] += loc->val[pos_i+i];

    /* Add extra-diagonal terms */
    for (j = i+1; j < n_ent; j++) {

      int  j_id = loc->ids[j];
      double  val_ij = loc->val[pos_i+j];

      if (fabs(val_ij) > cs_math_zero_threshold) { /* Not zero */

        /* First add: loc(i,j) */
        k_ij = cs_search_binary(n_i_ents, j_id, &(ass->col_id[start_i]));

#if defined(DEBUG) && !defined(NDEBUG) && CS_SLA_DBG > 0 /* Sanity check */
        if (k_ij < 0)
          bft_error(__FILE__, __LINE__, 0,
                    " Error detected while assembling a matrix.\n"
                    " An non-zero entry has not been found.");
#endif
        ass->val[start_i+k_ij] += val_ij;

      } /* loc[ij] != 0.0 */

      double  val_ji = loc->val[j*n_ent+i];

      if (fabs(val_ji) > cs_math_zero_threshold) { /* Not zero */

        cs_lnum_t  start_j = ass->idx[j_id];
        size_t  n_j_ents = ass->idx[j_id+1] - start_j;

        /* Second add: loc(j,i) */
        k_ji = cs_search_binary(n_j_ents, i_id, &(ass->col_id[start_j]));

#if defined(DEBUG) && !defined(NDEBUG) && CS_SLA_DBG > 0 /* Sanity check */
        if (k_ji < 0)
          bft_error(__FILE__, __LINE__, 0,
                    " Error detected while assembling a matrix.\n"
                    " An non-zero entry has not been found.");
#endif

        ass->val[start_j+k_ji] += val_ji;

      } /* loc[ji] != 0.0 */

    } /* Loop on j (Add extra-diag terms) */

  } /* Loop on i (Add diagonal term) */

}

/*----------------------------------------------------------------------------*/
/*!
 * \brief   Build a new matrix resulting from the extraction of some listed
 *          rows and columns. The output is a new matrix packed (or zipped)
 *          w.r.t the initial matrix.
 *
 * \param[in]  n_final_rows   number of rows to extract
 * \param[in]  n_final_cols   number of columns to extract
 * \param[in]  init           init matrix to work with
 * \param[in]  row_z2i_ids    zipped -> initial ids for rows
 * \param[in]  col_i2z_ids    initial-> zipped ids for columns (-1 ==> remove)
 * \param[in]  keep_sym       true or false
 *
 * \return a pointer to the new (packed) matrix structure
 */
/*----------------------------------------------------------------------------*/

cs_sla_matrix_t *
cs_sla_matrix_pack(cs_lnum_t                n_final_rows,
                   cs_lnum_t                n_final_cols,
                   const cs_sla_matrix_t   *init,
                   const cs_lnum_t         *row_z2i_ids,
                   const cs_lnum_t         *col_i2z_ids,
                   _Bool                    keep_sym)
{
  int  j, nnz, n_entries, zrow_id, irow_id;
  cs_sla_matrix_type_t  final_type;

  _Bool  msr2csr = false;
  cs_sla_matrix_t  *final = NULL;

  if (init == NULL)
    return final;

  /* Create a block matrix extracted from an initial (full) matrix */
  final_type = init->type;
  if (init->type == CS_SLA_MAT_MSR && n_final_rows != n_final_cols) {
    final_type = CS_SLA_MAT_CSR;
    msr2csr = true;
  }

  if (keep_sym && init->flag & CS_SLA_MATRIX_SYM)
    final = cs_sla_matrix_create(n_final_rows, n_final_cols, 1,
                                 final_type, true);
  else
    final = cs_sla_matrix_create(n_final_rows, n_final_cols, 1,
                                 final_type, false);

  if (init->type == CS_SLA_MAT_NONE)
    return final;

  /* Build index */
  if (!msr2csr) {

    if (n_final_cols == init->n_cols) { /* No size reduction for columns.
                                           Extract only rows */
      for (zrow_id = 0; zrow_id < final->n_rows; zrow_id++) {
        irow_id = row_z2i_ids[zrow_id];
        n_entries = init->idx[irow_id+1] - init->idx[irow_id];
        final->idx[zrow_id+1] = final->idx[zrow_id] + n_entries;
      }

    }
    else {

      /* Sanity check */
      assert(col_i2z_ids != NULL);

      for (zrow_id = 0; zrow_id < final->n_rows; zrow_id++) {
        irow_id = row_z2i_ids[zrow_id];
        n_entries = 0;
        for (j = init->idx[irow_id]; j < init->idx[irow_id+1]; j++)
          if (col_i2z_ids[init->col_id[j]] > -1) /* Not removed */
            n_entries++;
        final->idx[zrow_id+1] = final->idx[zrow_id] + n_entries;

      } /* End of loop on final rows */

    } /* Columns reduction */

  }
  else { /* msr2csr = true */

    if (n_final_cols == init->n_cols) { /* No size reduction for columns.
                                           Extract only rows */
      for (zrow_id = 0; zrow_id < final->n_rows; zrow_id++) {
        irow_id = row_z2i_ids[zrow_id];
        n_entries = init->idx[irow_id+1] - init->idx[irow_id];
        if (zrow_id < n_final_cols) // Add diagonal term
          n_entries += 1;
        final->idx[zrow_id+1] = final->idx[zrow_id] + n_entries;
      }

    }
    else {

      /* Sanity check */
      assert(col_i2z_ids != NULL);

      for (zrow_id = 0; zrow_id < final->n_rows; zrow_id++) {
        irow_id = row_z2i_ids[zrow_id];
        n_entries = 0;
        if (zrow_id < n_final_cols)
          n_entries = 1;
        for (j = init->idx[irow_id]; j < init->idx[irow_id+1]; j++)
          if (col_i2z_ids[init->col_id[j]] > -1) /* Not removed */
            n_entries++;
        final->idx[zrow_id+1] = final->idx[zrow_id] + n_entries;

      } /* End of loop on final rows */

    } /* Columns reduction */

  } /* test msr2csr */

  /* Allocate arrays */
  nnz = final->idx[final->n_rows];
  BFT_MALLOC(final->col_id, nnz, int);

  if (init->type == CS_SLA_MAT_DEC) {

    BFT_MALLOC(final->sgn, nnz, short int);
    _pack_dec(final, init, row_z2i_ids, col_i2z_ids);

  }
  else { /* Not DEC */

    BFT_MALLOC(final->val, nnz, double);
    if (init->type == CS_SLA_MAT_CSR)
      _pack_csr(final, init, row_z2i_ids, col_i2z_ids);
    else if (init->type == CS_SLA_MAT_MSR)
      _pack_msr(final, init, row_z2i_ids, col_i2z_ids, msr2csr);

  } /* End test matrix type */

  return final;
}

/*----------------------------------------------------------------------------*/
/*!
 * \brief   Add two sparse matrices a and b. c = alpha*a + beta*b
 *
 * \param[in]  alpha   first coef.
 * \param[in]  a       first matrix to add
 * \param[in]  beta    second coef.
 * \param[in]  b       second matrix to add
 *
 * \return  a pointer to the resulting matrix
 */
/*----------------------------------------------------------------------------*/

cs_sla_matrix_t *
cs_sla_matrix_add(double                  alpha,
                  const cs_sla_matrix_t  *a,
                  double                  beta,
                  const cs_sla_matrix_t  *b)
{
  int  ii, j, jj;
  size_t  annz, bnnz;

  cs_sla_matrix_type_t  c_type = CS_SLA_MAT_CSR;
  size_t  idx = 0, n_entries = 0, size_max = 0, lst_max = 0;
  _spa_t  *spa = NULL;
  cs_sla_matrix_t  *c = NULL;

  const char errmsg[] =
    "  Incompatible matrix type.\n  This combination is not available yet.\n"
    "  Matrices addition is aborted.\n";

  /* Sanity check */
  assert(a != NULL && b != NULL);
  assert(a->n_rows == b->n_rows);
  assert(a->n_cols == b->n_cols);

  if (a->stride > 1 || b->stride > 1)
    bft_error(__FILE__, __LINE__, 0, _sla_err_stride);

  /* Estimate sizes and allocate structures */
  annz = a->idx[a->n_rows];
  bnnz = b->idx[b->n_rows];
  size_max = CS_MAX((annz+bnnz)/2, (size_t)a->n_rows);

  if (a->type == CS_SLA_MAT_MSR && b->type == CS_SLA_MAT_MSR)
    c_type = CS_SLA_MAT_MSR;
  c = _init_mat(a, b, c_type, size_max);

  lst_max = CS_MAX(5, (annz + bnnz)/(2*a->n_rows));
  spa = _spa_init(b->n_cols, lst_max);

  if (a->type == b->type) {

    if (a->type == CS_SLA_MAT_DEC) {  /* DEC-DEC */

      /* Compute c = alpha*a + beta*b row by row */
      for (ii = 0; ii < a->n_rows; ii++) {

        /* Contribution of matrix a */
        for (j = a->idx[ii]; j < a->idx[ii+1]; j++)
          jj = a->col_id[j], _spa_add(spa, alpha*a->sgn[j], jj, ii);

        /* Contribution of matrix b */
        for (j = b->idx[ii]; j < b->idx[ii+1]; j++)
          jj = b->col_id[j], _spa_add(spa, beta*b->sgn[j], jj, ii);

        /* Fill a new row in c and prepare next step */
        if (spa->nnz + idx > size_max)
          _resize_mat(c, spa->nnz + idx, &size_max);
        n_entries = _spa_gather(spa, idx, c->col_id, c->val);
        c->idx[ii+1] = idx + n_entries;
        idx = c->idx[ii+1];

      } /* Loop on non-empty entry of row  */

    } /* a = b = DEC */
    else if (a->type == CS_SLA_MAT_CSR || a->type == CS_SLA_MAT_MSR) {

      if (a->type == CS_SLA_MAT_MSR)  /* Diagonal entries */
        for (ii = 0; ii < a->n_rows; ii++)
          c->diag[ii] = alpha*a->diag[ii] + beta*b->diag[ii];

      /* Compute c = alpha*a + beta*b row by row */
      for (ii = 0; ii < a->n_rows; ii++) {

        /* Contribution of matrix a */
        for (j = a->idx[ii]; j < a->idx[ii+1]; j++)
          jj = a->col_id[j], _spa_add(spa, alpha*a->val[j], jj, ii);

        /* Contribution of matrix b */
        for (j = b->idx[ii]; j < b->idx[ii+1]; j++)
          jj = b->col_id[j], _spa_add(spa, beta*b->val[j], jj, ii);

        /* Fill a new row in c and prepare next step */
        if (spa->nnz + idx > size_max)
          _resize_mat(c, spa->nnz + idx, &size_max);
        n_entries = _spa_gather(spa, idx, c->col_id, c->val);
        c->idx[ii+1] = idx + n_entries;
        idx = c->idx[ii+1];

      } /* Loop on non-empty entry of row  */

    }
    else
      bft_error(__FILE__, __LINE__, 0, errmsg);

  }
  else { /* a->type != b->type */

    if (a->type == CS_SLA_MAT_MSR && b->type == CS_SLA_MAT_CSR) {

      /* Compute c = alpha*a + beta*b row by row */
      for (ii = 0; ii < a->n_rows; ii++) {

        /* Contribution of matrix a */
        _spa_add(spa, alpha*a->diag[ii], ii, ii);
        for (j = a->idx[ii]; j < a->idx[ii+1]; j++)
          jj = a->col_id[j], _spa_add(spa, alpha*a->val[j], jj, ii);

        /* Contribution of matrix b */
        for (j = b->idx[ii]; j < b->idx[ii+1]; j++)
          jj = b->col_id[j], _spa_add(spa, beta*b->val[j], jj, ii);

        /* Fill a new row in c and prepare next step */
        if (spa->nnz + idx > size_max)
          _resize_mat(c, spa->nnz + idx, &size_max);
        n_entries = _spa_gather(spa, idx, c->col_id, c->val);
        c->idx[ii+1] = idx + n_entries;
        idx = c->idx[ii+1];

      } /* Loop on non-empty entry of row  */

    }
    else
      bft_error(__FILE__, __LINE__, 0, errmsg);

  }

  /* Memory management */
  BFT_REALLOC(c->col_id, c->idx[c->n_rows], cs_lnum_t);
  BFT_REALLOC(c->val, c->idx[c->n_rows], double);
  spa = _spa_free(spa);

  return c;
}

/*----------------------------------------------------------------------------*/
/*!
 * \brief  Compute a matrix vector product.
 *         If inout is not allocated, allocation is done inside this function
 *         If reset is set to true, initialization inout to 0
 *
 * \param[in]       m        pointer to a cs_sla_matrix_t structure
 * \param[in]       v        pointer to an array of double
 * \param[in, out]  inout    pointer to a pointer of double
 * \param[in]       reset    if true, first initialize inout to zero
 */
/*----------------------------------------------------------------------------*/

void
cs_sla_matvec(const cs_sla_matrix_t  *m,
              const double            v[],
              double                 *inout[],
              bool                    reset)
{
  double  *out = *inout;

  if (m == NULL)
    return;

  if (m->stride > 1)
    bft_error(__FILE__, __LINE__, 0, _sla_err_stride);

  if (out == NULL) {
    BFT_MALLOC(out, m->n_rows, double);
    reset = true;
  }

  if (reset == true)
# pragma omp parallel for if (m->n_rows > CS_THR_MIN)
    for (cs_lnum_t i = 0; i < m->n_rows; i++)
      out[i] = 0.0;

  switch (m->type) {
  case CS_SLA_MAT_DEC:
# pragma omp parallel for if (m->n_rows > CS_THR_MIN)
    for (cs_lnum_t i = 0; i < m->n_rows; i++) {
      double sum = 0.0;
      for (cs_lnum_t j = m->idx[i]; j < m->idx[i+1]; j++)
        sum += m->sgn[j] * v[m->col_id[j]];
      out[i] += sum;
    }
    break;

  case CS_SLA_MAT_CSR:
# pragma omp parallel for if (m->n_rows > CS_THR_MIN)
    for (cs_lnum_t i = 0; i < m->n_rows; i++) {
      double sum = 0.0;
      for (cs_lnum_t j = m->idx[i]; j < m->idx[i+1]; j++)
        sum += m->val[j] * v[m->col_id[j]];
      out[i] += sum;
    }
    break;

  case CS_SLA_MAT_MSR:
    assert(m->n_rows == m->n_cols); /* Should be a squared matrix */
# pragma omp parallel for if (m->n_rows > CS_THR_MIN)
    for (cs_lnum_t i = 0; i < m->n_rows; i++) {
      double sum = m->diag[i] * v[i];
      for (cs_lnum_t j = m->idx[i]; j < m->idx[i+1]; j++)
        sum += m->val[j] * v[m->col_id[j]];
      out[i] += sum;
    }
    break;

  default:
    bft_error(__FILE__, __LINE__, 0,
              "  Incompatible matrix type.\n"
              "  Cannot mulitply matrix by vector.\n");
    break;

  } // end of switch

  /* Return pointer */
  *inout = out;
}

/*----------------------------------------------------------------------------*/
/*!
 * \brief  Compute an array resulting from alpha * M(x) + beta * y
 *         If inout is not allocated, allocation is done inside this function
 *
 * \param[in]       alpha    multiplicative coefficient
 * \param[in]       m        pointer to a cs_sla_matrix_t structure
 * \param[in]       x        pointer to an array of double
 * \param[in]       beta     multiplicative coefficient
 * \param[in]       y        pointer to an array of double
 * \param[in, out]  inout    pointer to a pointer of double
 */
/*----------------------------------------------------------------------------*/

void
cs_sla_amxby(double                  alpha,
             const cs_sla_matrix_t  *m,
             const double            x[],
             double                  beta,
             const double            y[],
             double                 *inout[])
{
  double  *out = *inout;

  if (m == NULL)
    return;

  cs_sla_matvec(m, x, &out, true);

  for (cs_lnum_t  i = 0; i < m->n_rows; i++) {
    out[i] *= alpha;
    out[i] += beta*y[i];
  }

  *inout = out;
}

/*----------------------------------------------------------------------------*/
/*!
 * \brief   Main subroutine to multiply two sparse matrices a and b. c= a*b
 *
 * \param[in]  a     first matrix to multiply
 * \param[in]  b     second matrix to multiply
 *
 * \return  a pointer to the resulting matrix
 */
/*----------------------------------------------------------------------------*/

cs_sla_matrix_t *
cs_sla_matrix_multiply(const cs_sla_matrix_t   *a,
                       const cs_sla_matrix_t   *b)
{
  cs_sla_matrix_t  *c = NULL;

  const char errmsg[] =
    "  Incompatible matrix type.\n  This combination is not available yet.\n"
    "  Matrices multiplication is aborted.\n";

  /* Sanity check */
  assert(a != NULL && b != NULL);
  assert(a->n_cols == b->n_rows);

  if (a->type == CS_SLA_MAT_NONE || b->type == CS_SLA_MAT_NONE)
    bft_error(__FILE__, __LINE__, 0,
              "  Incompatible matrix type.\n   Cannot mulitply matrices\n");
  if (a->stride > 1 || b->stride > 1)
    bft_error(__FILE__, __LINE__, 0, _sla_err_stride);

  /* Switch to the right algorithm according to the kind of matrices */
  if (a->type == CS_SLA_MAT_DEC) {

    if (b->type == CS_SLA_MAT_DEC)        /* DEC-DEC */
      c = _multiply_dec_matrices(a, b);

    else if (b->type == CS_SLA_MAT_MSR)   /* DEC-MSR */
      c = _multiply_decmsr_matrices(a, b);

    else if(b->type == CS_SLA_MAT_CSR)    /* DEC-CSR */
      c = _multiply_deccsr_matrices(a, b);

    else
      bft_error(__FILE__, __LINE__, 0, errmsg);

  }
  else if (a->type == CS_SLA_MAT_CSR) {

    if (b->type == CS_SLA_MAT_CSR)       /* CSR-CSR */
      c = _multiply_csr_matrices(a, b);

    else if (b->type == CS_SLA_MAT_DEC)  /* CSR-DEC */
      c = _multiply_csrdec_matrices(a, b);

    else
      bft_error(__FILE__, __LINE__, 0, errmsg);

  }
  else if (a->type == CS_SLA_MAT_MSR) {

    if (b->type == CS_SLA_MAT_DEC)       /* MSR-DEC */
      c = _multiply_msrdec_matrices(a, b);

    else
      bft_error(__FILE__, __LINE__, 0, errmsg);

  } /* End of switch on a->type */
  else
    bft_error(__FILE__, __LINE__, 0, errmsg);

  /* Build diagonal index */
  cs_sla_matrix_diag_idx(c);

  return c;
}

/*----------------------------------------------------------------------------*/
/*!
 * \brief   Compute the product C = At * Diag * A
 *
 * \param[in]       At   pointer to a cs_sla_matrix_t struct. (DEC type)
 * \param[in]       D    array standing for a diagonal operator
 * \param[in]       A    pointer to a cs_sla_matrix_t struct. (DEC type)
 * \param[in, out]  w    work buffer
 *
 * \return a pointer to a new cs_sla_matrix_t
 */
/*----------------------------------------------------------------------------*/

cs_sla_matrix_t *
cs_sla_multiply_AtDA(const cs_sla_matrix_t  *At,
                     const double            D[],
                     const cs_sla_matrix_t  *A,
                     cs_lnum_t              *w)
{
  cs_lnum_t  i;

  int  use_work = 0;
  cs_sla_matrix_t  *C = NULL;

  /* Sanity check */
  assert(A != NULL && At != NULL && D != NULL);
  assert(At->n_cols == A->n_rows);

  if (A->stride > 1 || At->stride > 1)
    bft_error(__FILE__, __LINE__, 0, _sla_err_stride);

  C = cs_sla_matrix_create(At->n_rows, A->n_cols, 1,
                           CS_SLA_MAT_CSR,
                           true); /* Symmetric by construction */

  /* Manage temporary buffer */
  if (w == NULL) {
    BFT_MALLOC(w, A->n_cols, int);
    use_work = 1;
  }
  for (i = 0; i < A->n_cols; i++)
    w[i] = -1;

  if (A->type == CS_SLA_MAT_CSR && At->type == CS_SLA_MAT_CSR)
    _csrcsr_AtDA(At, D, A, C, w);
  else if (A->type == CS_SLA_MAT_DEC && At->type == CS_SLA_MAT_DEC)
    _decdec_AtDA(At, D, A, C, w);

  /* Memory management */
  BFT_REALLOC(C->col_id, C->idx[C->n_rows], int);
  BFT_REALLOC(C->val, C->idx[C->n_rows], double);

  if (use_work == 1)
    BFT_FREE(w);

  /* Build diagonal index */
  cs_sla_matrix_diag_idx(C);

  return C;
}

/*----------------------------------------------------------------------------*/
/*!
 * \brief   Specific matrix multiplication. Compute Bt * beta * B + alpha * A
 *          alpha and beta are scalar
 *
 * \param[in] alpha     real coefficient
 * \param[in] a         square sym. matrix
 * \param[in] beta      real coefficient
 * \param[in] b         matrix (CSR or DEC)
 * \param[in] bt        adjoint matrix of b
 *
 * \return the matrix corresponding to this operation in MSR storage
 */
/*----------------------------------------------------------------------------*/

cs_sla_matrix_t *
cs_sla_matrix_combine(double                  alpha,
                      const cs_sla_matrix_t  *a,
                      double                  beta,
                      const cs_sla_matrix_t  *bt,
                      const cs_sla_matrix_t  *b)
{
  int  ii, j, jj, k, kk;
  double  val, contrib;

  size_t  idx = 0, n_entries = 0, size_max = 0, lst_size_init = 0;
  _spa_t  *spa = NULL;
  cs_sla_matrix_t  *c = NULL;

  /* Sanity checks */
  assert(b != NULL && bt != NULL && a != NULL);
  assert(bt->n_cols == b->n_rows);
  assert(bt->n_rows == a->n_rows);
  assert(a->type == CS_SLA_MAT_MSR || a->type == CS_SLA_MAT_CSR);
  assert(bt->type == b->type);
  assert(bt->type != CS_SLA_MAT_MSR);

  if (b->stride > 1 || bt->stride > 1 || a->stride > 1)
    bft_error(__FILE__, __LINE__, 0, _sla_err_stride);

  /* Initialize matrix c = alpha*a + beta*bt*b and structures */
  size_max = a->idx[a->n_rows];
  c = _init_mat(a, a, CS_SLA_MAT_CSR, size_max);
  lst_size_init = CS_MAX(1, a->idx[a->n_rows]/a->n_rows);
  spa = _spa_init(a->n_rows, lst_size_init);

  if (c->type == CS_SLA_MAT_MSR) { /* Define diagonal entries */

    if (bt->type == CS_SLA_MAT_DEC) {

      for (ii = 0; ii < a->n_rows; ii++) {
        contrib = 0.0;
        for (j = bt->idx[ii]; j < bt->idx[ii+1]; j++)
          val = bt->sgn[j], contrib += val*val;
        c->diag[ii] = alpha*a->diag[ii] + beta*contrib;
      }

    } /* DEC */
    else {
      assert(bt->type == CS_SLA_MAT_CSR);

      for (ii = 0; ii < a->n_rows; ii++) {
        contrib = 0.0;
        for (j = bt->idx[ii]; j < bt->idx[ii+1]; j++)
          val = bt->val[j], contrib += val*val;
        c->diag[ii] = alpha*a->diag[ii] + beta*contrib;
      }

    }

  } /* MSR type: define diagonal */

  /* Compute the remaining part line by line */
  if (bt->type == CS_SLA_MAT_DEC) {

    for (ii = 0; ii < a->n_rows; ii++) {

      /* Add contribution from alpha*a */
      for (j = a->idx[ii]; j < a->idx[ii+1]; j++) {
        jj = a->col_id[j], val = alpha*a->val[j];
        _spa_add(spa, val, jj, ii);
      }
      if (a->type == CS_SLA_MAT_MSR)
        _spa_add(spa, alpha*a->diag[ii], ii, ii);

      for (j = bt->idx[ii]; j < bt->idx[ii+1]; j++) {

        jj = bt->col_id[j], val = beta*bt->sgn[j];

        for (k = b->idx[jj]; k < b->idx[jj+1]; k++) {
          kk = b->col_id[k];
          _spa_add(spa, val*b->sgn[k], kk, ii);
        }

      } /* End of loop on non-empty columns of row ii of bt */

      /* Fill a new row in c and prepare next step */
      if (spa->nnz + idx > size_max)
        _resize_mat(c, spa->nnz + idx, &size_max);
      n_entries = _spa_gather(spa, idx, c->col_id, c->val);
      c->idx[ii+1] = idx + n_entries;
      idx = c->idx[ii+1];

    } /* End of loop on rows */

  } /* DEC type */
  else  {

    for (ii = 0; ii < a->n_rows; ii++) {

      /* Add contribution from alpha*a */
      for (j = a->idx[ii]; j < a->idx[ii+1]; j++) {
        jj = a->col_id[j], val = alpha*a->val[j];
        _spa_add(spa, val, jj, ii);
      }
      if (a->type == CS_SLA_MAT_MSR)
        _spa_add(spa, alpha*a->diag[ii], ii, ii);

      for (j = bt->idx[ii]; j < bt->idx[ii+1]; j++) {

        jj = bt->col_id[j], val = beta * bt->val[j];

        for (k = b->idx[jj]; k < b->idx[jj+1]; k++)
          kk = b->col_id[k], _spa_add(spa, val*b->val[k], kk, ii);

      } /* End of loop on non-empty columns of row ii of bt */

      /* Fill a new row in c and prepare next step */
      if (spa->nnz + idx > size_max)
        _resize_mat(c, spa->nnz + idx, &size_max);
      n_entries = _spa_gather(spa, idx, c->col_id, c->val);
      c->idx[ii+1] = idx + n_entries;
      idx = c->idx[ii+1];

    } /* End of loop on rows */

  } /* CSR type */

  /* Memory management */
  BFT_REALLOC(c->col_id, c->idx[c->n_rows], cs_lnum_t);
  BFT_REALLOC(c->val, c->idx[c->n_rows], double);
  spa = _spa_free(spa);

  /* Build diagonal index */
  cs_sla_matrix_diag_idx(c);

  return c;
}

/*----------------------------------------------------------------------------*/
/*!
 * \brief   Matrix block 2x2 multiply by a vector
 *
 *              | A  B | |X| = |F|= |AX + BY|
 *              | C  D | |Y|   |G|  |CX + DY|
 *
 * \param[in]      A     pointer to a cs_sla_matrix_t block (1,1)
 * \param[in]      B     pointer to a cs_sla_matrix_t block (1,2)
 * \param[in]      C     pointer to a cs_sla_matrix_t block (2,1)
 * \param[in]      D     pointer to a cs_sla_matrix_t block (2,2)
 * \param[in]      X     upper vector
 * \param[in]      Y     lower vector
 * \param[in, out] F     upper result
 * \param[in, out] G     lower result
 * \param[in]      reset reset before computation (true/false)
 */
/*----------------------------------------------------------------------------*/

void
cs_sla_matvec_block2(const cs_sla_matrix_t  *A,
                     const cs_sla_matrix_t  *B,
                     const cs_sla_matrix_t  *C,
                     const cs_sla_matrix_t  *D,
                     const double            X[],
                     const double            Y[],
                     double                 *F[],
                     double                 *G[],
                     _Bool                   reset)
{
  int  i;

  double  *_F = *F, *_G = *G;
  int  nx = 0, ny = 0;

  assert(A != NULL || B != NULL);
  assert(C != NULL || D != NULL);
  assert(X != NULL);
  assert(Y != NULL);

  if (A->stride > 1 || B->stride > 1 || C->stride > 1 || D->stride > 1)
    bft_error(__FILE__, __LINE__, 0, _sla_err_stride);

  if (A != NULL)
    nx = A->n_rows;
  else
    nx = B->n_rows;
  if (C != NULL)
    ny = B->n_rows;
  else
    ny = D->n_rows;
  if (_F == NULL) {
    BFT_MALLOC(_F, nx, double);
    reset = true;
  }
  if (_G == NULL) {
    BFT_MALLOC(_G, ny, double);
    reset = true;
  }

  if (reset == true) {
    for (i = 0; i < nx; i++) _F[i] = 0.0;
    for (i = 0; i < ny; i++) _G[i] = 0.0;
  }

  /* Compute _F = A*X + B*Y */
  if (A != NULL)
    cs_sla_matvec(A, X, &_F, reset);
  if (B != NULL)
    cs_sla_matvec(B, Y, &_F, reset);

  /* Compute _G = A*X + B*Y */
  if (C != NULL)
    cs_sla_matvec(C, X, &_G, reset);
  if (D != NULL)
    cs_sla_matvec(D, Y, &_G, reset);

  /* Return pointers */
  *F = _F;
  *G = _G;
}

/*----------------------------------------------------------------------------*/
/*!
 * \brief  Read from a binary file a matrix in CSR format, its righ hand side
 *         and the solution. Matrix must have a stride equal to 1.
 *
 * \param[in]       name      name of the output file
 * \param[in, out]  p_mat     system to solve
 * \param[in, out]  p_rhs     right hand side
 * \param[in, out]  p_sol       solution
 */
/*----------------------------------------------------------------------------*/

void
cs_sla_bread(const char        *name,
             cs_sla_matrix_t  **p_mat,
             double            *p_rhs[],
             double            *p_sol[])
{
  int  n, n_rows, n_cols, nnz, flag;

  double  *rhs = NULL, *sol = NULL;
  cs_sla_matrix_t  *m = NULL;
  FILE *f = NULL;

  /* Sanity check */
  if (name == NULL)
    bft_error(__FILE__, __LINE__, 0,
              " No filename given. Can not read binary file!\n");

  f = fopen(name, "rb");

  /* Rhs : dim + values */
  fread(&n, sizeof(int), 1, f);
  BFT_MALLOC(rhs, n, double);
  BFT_MALLOC(sol, n, double);
  fread(rhs, n*sizeof(double), 1, f);
  fread(sol, n*sizeof(double), 1, f);

  /* Matrix flag 0 = CSR or 1 = MSR */
  fread(&flag, sizeof(int), 1, f);

  /* Matrix: dim + values */
  fread(&n_rows, sizeof(int), 1, f);
  fread(&n_cols, sizeof(int), 1, f);
  fread(&nnz, sizeof(int), 1, f);

  assert(n_rows == n_cols); /* This is not a real limitation */

  if (flag == 0)
    m = cs_sla_matrix_create(n_rows, n_cols, 1, CS_SLA_MAT_CSR, false);
  else {
    assert(flag == 1);
    m = cs_sla_matrix_create(n_rows, n_cols, 1, CS_SLA_MAT_MSR, false);

    fread(m->diag, n_rows*sizeof(double), 1, f);
  }

  /* index from 0 */
  fread(m->idx, (n_rows + 1)*sizeof(int), 1, f);

  if (nnz > 0) {

    BFT_MALLOC(m->col_id, nnz, int);
    BFT_MALLOC(m->val, nnz, double);

    /* cols from 1 to n_rows */
    fread(m->col_id, nnz*sizeof(int), 1, f);
    fread(m->val, nnz*sizeof(double), 1, f);

  }

  fclose(f);

  /* Return pointers */
  *p_mat = m;
  *p_rhs = rhs;
  *p_sol = sol;
}

/*----------------------------------------------------------------------------*/
/*!
 * \brief  Write in binary format a matrix in CSR format, its righ hand side
 *         and the solution
 *
 * \param[in]     name      name of the output file
 * \param[in]     m         system to solve
 * \param[in]     rhs       right hand side
 * \param[in]     sol       solution
 */
/*----------------------------------------------------------------------------*/

void
cs_sla_bwrite(const char              *name,
              const cs_sla_matrix_t   *m,
              const double            *rhs,
              const double            *sol)
{
  int  nnz, flag;

  FILE *f = NULL;

  /* Sanity check */
  assert(name != NULL);

  if (m == NULL) {
    fprintf(stdout, "\n SLA matrix structure: %p (%s)\n", (const void *)m, name);
    fprintf(stdout, " Stop file writing.\n");
    return;
  }
  else if (m->type == CS_SLA_MAT_NONE || m->type == CS_SLA_MAT_DEC) {
    fprintf(stdout, "\n SLA matrix structure: %p (%s)\n", (const void *)m, name);
    fprintf(stdout, "   type:   %8d\n", m->type);
    fprintf(stdout, " Stop file writing.\n");
    return;
  }
  else if (rhs == NULL) {
    fprintf(stdout, " Empty rhs array.\n");
    fprintf(stdout, " Stop file writing.\n");
    return;
  }
  else if (sol == NULL) {
    fprintf(stdout, " Empty sol array.\n");
    fprintf(stdout, " Stop file writing.\n");
    return;
  }

  if (m->stride > 1)
    bft_error(__FILE__, __LINE__, 0, _sla_err_stride);

  f = fopen(name, "wb");

  /* array size + rhs + sol */
  fwrite(&(m->n_cols), sizeof(int), 1, f);
  fwrite(rhs, sizeof(double), m->n_cols, f);
  fwrite(sol, sizeof(double), m->n_cols, f);

  /* matrix type: 0 = CSR or 1 = MSR */
  flag = 0;
  if (m->type == CS_SLA_MAT_MSR)
    flag = 1;
  fwrite(&flag, sizeof(int), 1, f);

  /* matrix size and number of non-zeros */
  fwrite(&(m->n_rows), sizeof(int), 1, f);
  fwrite(&(m->n_cols), sizeof(int), 1, f);
  nnz = m->idx[m->n_rows];
  fwrite(&nnz, sizeof(int), 1, f);

  if (flag == 1) /* Dump diagonal */
    fwrite(m->diag, sizeof(double), m->n_rows, f);

  /* write index (start from 0) */
  fwrite(m->idx, sizeof(int), m->n_rows + 1, f);

  /* write cols (start from 1 to n_rows) and values */
  fwrite(m->col_id, sizeof(int), m->idx[m->n_rows], f);
  fwrite(m->val, sizeof(double), m->idx[m->n_rows], f);

  fclose(f);
}

/*----------------------------------------------------------------------------*/
/*!
 * \brief   Synthesis of a cs_sla_matrix_t structure
 *
 * \param[in]       name    either name of the file if f is NULL or description
 * \param[in]       f       pointer to a FILE struct.
 * \param[in, out]  m       matrix to dump (info can be computed inside)
 */
/*----------------------------------------------------------------------------*/

void
cs_sla_matrix_summary(const char        *name,
                      FILE              *f,
                      cs_sla_matrix_t   *m)
{
  cs_data_info_t  dinfo;

  char  *filename = NULL;
  FILE  *_f = f;
  _Bool close_file = false;

  if (_f == NULL) {
    if (name == NULL)
      _f = stdout;

    else {

      int len = strlen(name) + strlen("-summary.log") + 1;

      BFT_MALLOC(filename, len, char);
      sprintf(filename,"%s-summary.log", name);
      _f = fopen(filename,"w");
      close_file = true;
    }
  }

  fprintf(_f, "\n");
  if (m == NULL)
    fprintf(_f, " -sla-  SLA matrix structure: %p (%s)\n",
            (const void *)m, name);

  else if (m->type == CS_SLA_MAT_NONE) {
    fprintf(_f, " -sla-  SLA matrix structure: %p (%s)\n",
            (const void *)m, name);
    fprintf(_f, " -sla-  type:        %s\n", _sla_matrix_type[m->type]);
  }
  else {

    if (!(m->flag & CS_SLA_MATRIX_INFO))
      cs_sla_matrix_set_info(m);

    fprintf(_f, " -sla-  SLA matrix structure: %p (%s)\n",
            (const void *)m, name);
    fprintf(_f, " -sla-  type          %s\n", _sla_matrix_type[m->type]);
    fprintf(_f, " -sla-  n_rows        %d\n", m->n_rows);
    fprintf(_f, " -sla-  n_cols        %d\n", m->n_cols);
    fprintf(_f, " -sla-  stride        %d\n", m->stride);
    fprintf(_f, " -sla-  nnz           %lu\n", m->info.nnz);
    fprintf(_f, " -sla-  fill-in       %5.2e %%\n", m->info.fillin);
    fprintf(_f, " -sla-  stencil_min   %d\n", m->info.stencil_min);
    fprintf(_f, " -sla-  stencil_max   %d\n", m->info.stencil_max);
    fprintf(_f, " -sla-  stencil_mean  %5.2e\n", m->info.stencil_mean);
    if (m->flag & CS_SLA_MATRIX_SYM)
      fprintf(_f, " -sla-  sym           True\n");
    else
      fprintf(_f, " -sla-  sym           False\n");

    if (m->type == CS_SLA_MAT_MSR ) {

      dinfo = cs_analysis_data(m->n_rows,    // n_elts
                               1,            // stride
                               CS_DOUBLE,    // datatype
                               m->diag,      // data
                               false);       // work also with abs ?
      cs_data_info_dump("mat->diag", _f, m->n_rows, CS_DOUBLE, dinfo);

      const cs_lnum_t  n_msr_vals = m->info.nnz - m->n_rows;

      dinfo = cs_analysis_data(n_msr_vals,   // n_elts
                               1,            // stride
                               CS_DOUBLE,    // datatype
                               m->val,       // data
                               false);       // work also with abs ?
      cs_data_info_dump("mat->val", _f, n_msr_vals, CS_DOUBLE, dinfo);
    }

    if (m->type == CS_SLA_MAT_CSR) {
      dinfo = cs_analysis_data(m->info.nnz,  // n_elts
                               1,            // stride
                               CS_DOUBLE,    // datatype
                               m->val,       // data
                               false);       // work also with abs ?
      cs_data_info_dump("mat->val", _f, m->info.nnz, CS_DOUBLE, dinfo);
    }

  } /* m neither NULL nor CS_SLA_MAT_NONE */

  if (close_file) {
    BFT_FREE(filename);
    fclose(_f);
  }

}

/*----------------------------------------------------------------------------*/
/*!
 * \brief   Dump a cs_sla_matrix_t structure
 *
 * \param[in]  name    either name of the file if f is NULL or description
 * \param[in]  f       pointer to a FILE struct.
 * \param[in]  m       matrix to dump
 */
/*----------------------------------------------------------------------------*/

void
cs_sla_matrix_dump(const char             *name,
                   FILE                   *f,
                   const cs_sla_matrix_t  *m)
{
  cs_lnum_t i, j, k;

  FILE  *_f = f;
  _Bool close_file = false;

  if (_f == NULL) {
    if (name == NULL)  _f = stdout;
    else
      _f = fopen(name,"w"), close_file = true;
  }

  if (m == NULL)
    fprintf(_f, "\n SLA matrix structure: %p (%s)\n", (const void *)m, name);

  else if (m->type == CS_SLA_MAT_NONE) {
    fprintf(_f, "\n SLA matrix structure: %p (%s)\n", (const void *)m, name);
    fprintf(_f, "   type:        %s\n", _sla_matrix_type[m->type]);
  }
  else {

    fprintf(_f, "\n SLA matrix structure: %p (%s)\n", (const void *)m, name);
    fprintf(_f, "   stride         %d\n", m->stride);
    fprintf(_f, "   type           %s\n", _sla_matrix_type[m->type]);
    if (m->flag & CS_SLA_MATRIX_SYM)
      fprintf(_f, "   symmetry       True\n\n");
    else
      fprintf(_f, "   symmetry       False\n\n");
    fprintf(_f, "   n_rows         %d\n", m->n_rows);
    fprintf(_f, "   n_cols         %d\n", m->n_cols);
    if (m->flag & CS_SLA_MATRIX_INFO) {
      fprintf(_f, "   stencil_min    %d\n", m->info.stencil_min);
      fprintf(_f, "   stencil_max    %d\n", m->info.stencil_max);
      fprintf(_f, "   nnz            %lu\n", m->info.nnz);
      fprintf(_f, "   fill-in        %.2f\n", m->info.fillin);
    }

    const cs_lnum_t  *idx = m->idx;
    const cs_lnum_t  *col_id = m->col_id;
    const short int  *sgn = m->sgn;
    const cs_real_t  *diag = m->diag;
    const cs_real_t  *val = m->val;

    for (i = 0; i < m->n_rows; i++) {

      cs_lnum_t  s = idx[i], e = idx[i+1];

      fprintf(_f, "%5d >", i+1);

      if (diag != NULL) { /* Dump diagonal */
        fprintf(_f, " %5d >>", i);
        for (k = 0; k < m->stride; k++)
          fprintf(_f, " % -8.4e", diag[i*m->stride+k]);
        fprintf(_f, " >> Extra:");
      } /* diag != NULL */

      if (m->type == CS_SLA_MAT_DEC) { // DEC matrix
        for (j = s; j < e; j++) {
          for (k = 0; k < m->stride; k++)
            fprintf(_f, " %2d", sgn[j*m->stride+k]);
          fprintf(_f, " (%5d)", col_id[j]);
        }
      }
      else if (m->type == CS_SLA_MAT_CSR || m->type == CS_SLA_MAT_MSR) {

        for (j = s; j < e; j++) {
          for (k = 0; k < m->stride; k++) {
            const double  v_ij = val[j*m->stride+k];
            if (fabs(v_ij) > 0)
              fprintf(_f, " % -8.4e (%5d)", v_ij, col_id[j]);
          }
        } // Loop on row entries

      } // MSR or CSR
      fprintf(_f, "\n");

    }

  } /* m neither NULL nor CS_SLA_MAT_NONE */

  if (close_file)
    fclose(_f);
}

/*----------------------------------------------------------------------------*/
/*!
 * \brief   Dump a cs_sla_matrix_t structure and its related right-hand side
 *
 * \param[in]  name    either name of the file if f is NULL or description
 * \param[in]  f       pointer to a FILE struct.
 * \param[in]  m       matrix to dump
 * \param[in]  rhs     right-hand side to dump
 */
/*----------------------------------------------------------------------------*/

void
cs_sla_system_dump(const char              *name,
                   FILE                    *f,
                   const cs_sla_matrix_t   *m,
                   const double            *rhs)
{
  cs_lnum_t i, j, k;

  FILE  *_f = f;
  _Bool close_file = false;

  if (_f == NULL) {
    if (name == NULL)  _f = stdout;
    else
      _f = fopen(name,"w"), close_file = true;
  }

  if (m == NULL)
    fprintf(_f, "\n SLA matrix structure: %p (%s)\n", (const void *)m, name);

  else if (m->type == CS_SLA_MAT_NONE) {
    fprintf(_f, "\n SLA matrix structure: %p (%s)\n", (const void *)m, name);
    fprintf(_f, "   type:        %s\n", _sla_matrix_type[m->type]);
  }
  else {

    fprintf(_f, "\n SLA matrix structure: %p (%s)\n", (const void *)m, name);
    fprintf(_f, "   stride         %d\n", m->stride);
    fprintf(_f, "   type           %s\n", _sla_matrix_type[m->type]);
    if (m->flag & CS_SLA_MATRIX_SYM)
      fprintf(_f, "   symmetry       True\n\n");
    else
      fprintf(_f, "   symmetry       False\n\n");
    fprintf(_f, "   n_rows         %d\n", m->n_rows);
    fprintf(_f, "   n_cols         %d\n", m->n_cols);
    if (m->flag & CS_SLA_MATRIX_INFO) {
      fprintf(_f, "   stencil_min    %d\n", m->info.stencil_min);
      fprintf(_f, "   stencil_max    %d\n", m->info.stencil_max);
      fprintf(_f, "   nnz            %lu\n", m->info.nnz);
      fprintf(_f, "   fill-in        %.2f\n", m->info.fillin);
    }

    /* Sanity check */
    assert(rhs != NULL);

    const cs_lnum_t  *idx = m->idx;
    const cs_lnum_t  *col_id = m->col_id;

    for (i = 0; i < m->n_rows; i++) {

      cs_lnum_t  s = idx[i], e = idx[i+1];

      fprintf(_f, "\nrow: %3d >> rhs: % -8.4e", i, rhs[i]);

      if (m->type == CS_SLA_MAT_DEC) { // DEC matrix

        const short int  *sgn = m->sgn;

        assert(m->diag == NULL);
        for (j = s; j < e; j++) {
          fprintf(_f, " <col: %4d;", col_id[j]);
          for (k = 0; k < m->stride; k++)
            fprintf(_f, " %2d", sgn[j*m->stride+k]);
          fprintf(_f,">");
        }

      }
      else if (m->type == CS_SLA_MAT_CSR || m->type == CS_SLA_MAT_MSR) {

        const cs_real_t  *diag = m->diag;
        const cs_real_t  *val = m->val;

        if (diag != NULL) {
          fprintf(_f, " diag:");
          for (k = 0; k < m->stride; k++)
            fprintf(_f, " % -6.3e", diag[i*m->stride+k]);
          fprintf(_f, "\t");
        }

        for (j = s; j < e; j++) {
          for (k = 0; k < m->stride; k++) {
            const double  v_ij = val[j*m->stride+k];
            if (fabs(v_ij) > 0)
              fprintf(_f, " (% -6.3e, %4d)", v_ij, col_id[j]);
          }
        }

      } // MSR or CSR

    } // Loop on rows

  } /* m neither NULL nor CS_SLA_MAT_NONE */

  if (close_file)
    fclose(_f);
}

/*----------------------------------------------------------------------------*/
/*!
 * \brief   Create a cs_sla_hmatrix_t structure
 *          This is a square matrix of size n_x+n_cells (stride = 1 up to now)
 *
 * \param[in]  n_x       number of hybrid entities
 * \param[in]  n_cells   number of cells
 * \param[in]  bktrans   block (1,0) and (0,1) are transposed: true or false
 * \param[in]  bk00sym   block (0,0) is symmetric: true or false
 * \param[in]  x2x       pointer to cs_connect_index_t struc.
 * \param[in]  c2x       pointer to cs_connect_index_t struc.
 *
 * \return  a pointer to new allocated hybrid matrix structure
 */
/*----------------------------------------------------------------------------*/

cs_sla_hmatrix_t *
cs_sla_hmatrix_create(cs_lnum_t                   n_x,
                      cs_lnum_t                   n_cells,
                      bool                        bktrans,
                      bool                        bk00sym,
                      const cs_connect_index_t   *x2x,
                      const cs_connect_index_t   *c2x)
{
  cs_sla_hmatrix_t  *hm = NULL;

  /* Sanity checks */
  if (x2x == NULL)
    bft_error(__FILE__, __LINE__, 0,
              " Stop creating a hybrid matrix: x2x connectivity index is NULL");
  if (c2x == NULL)
    bft_error(__FILE__, __LINE__, 0,
              " Stop creating a hybrid matrix: c2x connectivity index is NULL");

  BFT_MALLOC(hm, 1, cs_sla_hmatrix_t);

  /* Default initialization */
  hm->n_rows = n_x + n_cells;
  hm->n_x = n_x;
  hm->n_cells = n_cells;
  hm->flag = 0;
  if (bktrans && bk00sym) hm->flag |= CS_SLA_MATRIX_SYM;

  hm->c2x = c2x;
  BFT_MALLOC(hm->cx_vals, c2x->idx[n_cells], double);
  if (bktrans) {

    hm->xc_vals = NULL;
# pragma omp parallel for if (n_x > CS_THR_MIN)
    for (cs_lnum_t i = 0; i < c2x->idx[n_cells]; i++)
      hm->cx_vals[i] = 0;

  }
  else {

    BFT_MALLOC(hm->xc_vals, c2x->idx[n_cells], double);
# pragma omp parallel for if (n_x > CS_THR_MIN)
    for (cs_lnum_t i = 0; i < c2x->idx[n_cells]; i++)
      hm->cx_vals[i] = 0, hm->xc_vals[i] = 0;

  }

  BFT_MALLOC(hm->cc_diag, n_cells, double);
# pragma omp parallel for if (n_cells > CS_THR_MIN)
  for (cs_lnum_t i = 0; i < n_cells; i++)
    hm->cc_diag[i] = 0;

  // index, symmetric, sorted, stride
  hm->xx_block = cs_sla_matrix_create_msr_from_index(x2x, bk00sym, true, 1);

  return hm;
}

/*----------------------------------------------------------------------------*/
/*!
 * \brief   Free a cs_sla_hmatrix_t structure
 *
 * \param[in]  hm     hybrid matrix to free
 *
 * \return  a NULL pointer
 */
/*----------------------------------------------------------------------------*/

cs_sla_hmatrix_t *
cs_sla_hmatrix_free(cs_sla_hmatrix_t  *hm)
{
  if (hm == NULL)
    return NULL;

  /* Sanity check */
  assert(!(hm->flag & CS_SLA_MATRIX_SHARED));

  BFT_FREE(hm->cc_diag);
  BFT_FREE(hm->cx_vals);
  if (hm->xc_vals != NULL)
    BFT_FREE(hm->xc_vals);

  hm->xx_block = cs_sla_matrix_free(hm->xx_block);

  BFT_FREE(hm);

  return NULL;
}

/*----------------------------------------------------------------------------*/
/*!
 * \brief  Compute a matrix vector product.
 *         If inout is not allocated, allocation is done inside this function
 *         If reset is set to true, initialization inout to 0
 *
 * \param[in]       hm       pointer to a cs_sla_hmatrix_t structure
 * \param[in]       vx       pointer to an array of double (x-based values)
 * \param[in]       vc       pointer to an array of double (cell-based values)
 * \param[in, out]  iox      pointer to a pointer of double (x-based values)
 * \param[in, out]  ioc      pointer to a pointer of double (celle-based values)
 * \param[in]       reset    if true, first initialize inout to zero
 */
/*----------------------------------------------------------------------------*/

void
cs_sla_hmatvec(const cs_sla_hmatrix_t   *hm,
               const double              vx[],
               const double              vc[],
               double                   *iox[],
               double                   *ioc[],
               bool                      reset)
{
  double  *ox = *iox;
  double  *oc = *ioc;
  bool  reset_x = reset;
  bool  reset_c = reset;

  if (hm == NULL)
    return;

  /* Compute x-based part */
  if (ox == NULL) {
    BFT_MALLOC(ox, hm->n_x, double);
    reset_x = true;
  }

  if (reset_x == true)
# pragma omp parallel for if (hm->n_x > CS_THR_MIN)
    for (cs_lnum_t i = 0; i < hm->n_x; i++)
      ox[i] = 0.0;

  /* First contribution: ox += Hxx*vx */
  cs_sla_matvec(hm->xx_block, vx, &ox, false);

  /* Compute cell-based part */
  if (oc == NULL) {
    BFT_MALLOC(oc, hm->n_cells, double);
    reset_c = true;
  }

  if (reset_c == true)
# pragma omp parallel for if (hm->n_cells > CS_THR_MIN)
    for (cs_lnum_t i = 0; i < hm->n_cells; i++)
      oc[i] = 0.0;

  /* First contribution: oc += Hcc*vc */
# pragma omp parallel for if (hm->n_cells > CS_THR_MIN)
  for (cs_lnum_t i = 0; i < hm->n_cells; i++)
    oc[i] += hm->cc_diag[i]*vc[i];

  /* Second contribution for x-based and cell-based parts */
  if (hm->xc_vals == NULL) {

    for (cs_lnum_t c_id = 0; c_id < hm->n_cells; c_id++) {

      const double  c_val = vc[c_id];

      for (cs_lnum_t j = hm->c2x->idx[c_id]; j < hm->c2x->idx[c_id+1]; j++) {

        const double  xval = hm->cx_vals[j];
        const cs_lnum_t  x_id = hm->c2x->ids[j];

        oc[c_id] += xval * vx[x_id];
        ox[x_id] += xval * c_val;

      } // Loop on x entities related to this cell
    } // Loop on cells

  }
  else { // blocks (1,0) and (0,1) are not transposed

    for (cs_lnum_t c_id = 0; c_id < hm->n_cells; c_id++) {

      const double  c_val = vc[c_id];

      for (cs_lnum_t j = hm->c2x->idx[c_id]; j < hm->c2x->idx[c_id+1]; j++) {

        const cs_lnum_t  x_id = hm->c2x->ids[j];

        oc[c_id] += hm->cx_vals[j] * vx[x_id];
        ox[x_id] += hm->xc_vals[j] * c_val;

      } // Loop on x entities related to this cell
    } // Loop on cells

  }

}

/*----------------------------------------------------------------------------*/
/*!
 * \brief   Assemble a hybrid matrix from local contributions
 *          --> We assume that the local matrices are symmetric
 *          --> We assume that the (0,0) block of the assembled matrix has its
 *              columns sorted
 *
 * \param[in]       loc        pointer to a local matrix
 * \param[in, out]  ass        pointer to a cs_sla_hmatrix_t struct.
 */
/*----------------------------------------------------------------------------*/

void
cs_sla_assemble_hmat_sym(const cs_locmat_t   *loc,
                         cs_sla_hmatrix_t    *ass)
{
  const int  n_ent = loc->n_ent; // n_loc_x + 1
  const int  n_x_ent = n_ent - 1;

  cs_sla_matrix_t  *bxx = ass->xx_block;

  /* Sanity checks */
  assert(n_ent > 1);
  assert(ass->flag & CS_SLA_MATRIX_SYM);
  assert(bxx->type == CS_SLA_MAT_MSR);
  assert(bxx->flag & (CS_SLA_MATRIX_SYM | CS_SLA_MATRIX_SORTED));

  /* Assemble local contributions into bxx from x entities */
  for (int i = 0; i < n_x_ent; i++) {

    const double  *loc_i = loc->val + i*n_ent;
    const cs_lnum_t  i_id = loc->ids[i];

    /* Add diagonal term : loc(i,i) */
    bxx->diag[i_id] += loc_i[i];

    const cs_lnum_t  start_i = bxx->idx[i_id];
    const size_t  n_i_ents = bxx->idx[i_id+1] - start_i; // arg. binary search

    for (int j = i + 1; j < n_x_ent; j++) {

      double  val_ij = loc_i[j];

      if (fabs(val_ij) > cs_math_zero_threshold) { /* Not zero */

        int  j_id = loc->ids[j];
        cs_lnum_t  start_j = bxx->idx[j_id];
        size_t  n_j_ents = bxx->idx[j_id+1] - start_j;

        /* First add: loc(i,j) */
        cs_lnum_t  k_ij = cs_search_binary(n_i_ents, j_id,
                                           &(bxx->col_id[start_i]));

#if defined(DEBUG) && !defined(NDEBUG) && CS_SLA_DBG > 0 /* Sanity check */
        if (k_ij < 0)
          bft_error(__FILE__, __LINE__, 0,
                    " Error detected while assembling a matrix.\n"
                    " An non-zero entry has not been found.");
#endif

        bxx->val[start_i+k_ij] += val_ij;

        /* Second add: loc(j,i) */
        cs_lnum_t  k_ji = cs_search_binary(n_j_ents, i_id,
                                           &(bxx->col_id[start_j]));

#if defined(DEBUG) && !defined(NDEBUG) && CS_SLA_DBG > 0 /* Sanity check */
        if (k_ji < 0)
          bft_error(__FILE__, __LINE__, 0,
                    " Error detected while assembling a matrix.\n"
                    " An non-zero entry has not been found.");
#endif

        bxx->val[start_j+k_ji] += val_ij;

      } /* loc[ij] != 0.0 */

    } /* Loop on j (Add extra-diag terms) */

  } /* Loop on i */

  /* Add contribution to cell diagonal */
  const cs_lnum_t  c_id = loc->ids[n_x_ent];
  const double  *loc_c = loc->val + n_x_ent*n_ent;

  ass->cc_diag[c_id] += loc_c[n_x_ent];

  /* Add contributions to cx_vals (it's an assignment not an accumulation) */
  int shift = 0;
  for (cs_lnum_t i = ass->c2x->idx[c_id]; i < ass->c2x->idx[c_id+1]; i++)
    ass->cx_vals[i] = loc_c[shift++];

}

/*----------------------------------------------------------------------------*/

END_C_DECLS