-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathmcl_sparse.py
20221 lines (16638 loc) · 563 KB
/
mcl_sparse.py
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
#!usr/bin/env python
#import scipy as np
import scipy as sp
import numpy as np
from scipy import sparse
from scipy.sparse import csgraph
from scipy import stats
import sys
from time import time
import os
import gc
from struct import pack, unpack
from math import sqrt
import mimetypes
import gzip
import bz2 as bzip2
import bz2
#import numpy as np
from scipy import sparse as sps
import tempfile
import pickle
from collections import Counter
from threading import Thread
#from sklearn.externals.joblib import Parallel, delayed
import mmap
try:
from _numpypy import multiarray as npy
except:
npy = np
try:
import sharedmem as sm
except:
sm = np
# try:
# import cupy as cp
# has_cupy = has_gpu = True
# except:
# cp = np
# has_cupy = has_gpu = False
try:
import pyculib
has_gpu = True
except:
has_gpu = False
import multiprocessing as mp
from multiprocessing import Manager, Array
try:
from numba import jit, njit, cuda
except:
njit = jit = lambda x: x
try:
from numba import prange
except:
prange = xrange
# the sparse matrix add matrix on gpu
if has_gpu:
# if 1:
def csrgeam_ez(matA, matB, alpha=1, beta=1, transA='N', transB='N', descrA=None,
descrB=None, descrC=None, clf=None):
if type(clf) == type(None):
clf = pyculib.sparse.Sparse()
tmpdescr = pyculib.sparse.Sparse().matdescr()
descrA = descrA or tmpdescr
descrB = descrB or tmpdescr
descrC = descrC or tmpdescr
dtype = matA.dtype
m, ka = matA.shape
kb, n = matB.shape
if ka != kb:
raise ValueError("incompatible matrices")
k = ka
indptrC = pyculib.cuda.device_array(m + 1, dtype='int32')
nnz = clf.XcsrgeamNnz(m, n, descrA, matA.nnz,
matA.indptr, matA.indices, descrB, matB.nnz,
matB.indptr, matB.indices, descrC, indptrC)
if nnz == 0:
raise ValueError("result is entirely zero")
dataC = pyculib.cuda.device_array(nnz, dtype=dtype)
indicesC = pyculib.cuda.device_array(nnz, dtype='int32')
clf.csrgeam(m, n, alpha, descrA, matA.nnz, matA.data,
matA.indptr, matA.indices, beta, descrB, matB.nnz, matB.data,
matB.indptr, matB.indices, descrC, dataC, indptrC,
indicesC)
return pyculib.sparse.CudaCSRMatrix().from_attributes(data=dataC, indices=indicesC,
indptr=indptrC, shape=(
m, n),
dtype=dtype, nnz=nnz)
#csrgemm_ez = pyculib.sparse.Sparse().csrgemm_ez
else:
def csrgeam_ez(x, y, clf=None):
return x + y
# mmap based array
class darray:
def __init__(self, fn, size, dtype='float32'):
self.fn = fn
self.size = int(size)
self.dtype = dtype
if self.dtype == 'float8' or self.dtype == 'int8':
self.stride = 1
elif self.dtype == 'float16' or self.dtype == 'int16':
self.stride = 2
elif self.dtype == 'float32' or self.dtype == 'int32':
self.stride = 4
else:
self.stride = 8
self.size = size
self.f = open(self.fn, "w+b")
self.f.seek(self.stride * self.size - 1)
self.f.write('\x00')
self.f.flush()
self.buf = mmap.mmap(self.f.fileno(), self.stride *
self.size, prot=mmap.ACCESS_WRITE)
self.dat = npy.frombuffer(self.buf, self.dtype)
# resize the array
def resize(self, size=-1):
L = size > 0 and size * self.stride - \
1 or self.stride * (self.dat.size + 10**6) - 1
L = int(L)
self.f.seek(L)
self.f.write('\x00')
self.f.close()
self.f = open(self.fn, "r+b")
L += 1
self.buf = mmap.mmap(self.f.fileno(), L, prot=mmap.ACCESS_WRITE)
self.dat = npy.frombuffer(self.buf, self.dtype)
# worker of thread
class worker(Thread):
def __init__(self, func, args=()):
super(worker, self).__init__()
self.func = func
self.args = args
def run(self):
self.result = self.func(*self.args)
def get_result(self):
try:
return self.result
except Exception:
return None
# normalization of matrix
# @njit(nogil=True, cache=True, parallel=True)
@njit(fastmath=True, nogil=True, cache=True, parallel=True)
def inflate_norm_p(xr, xc, x, I=1.5, cpu=1, mem=4):
R = xr.size
#chk = mem > 0 and mem * (1<<30) // cpu or R // cpu
#cpu = max(1, xc.size // (1<<26))
cpu = max(1, cpu)
chk = max(1, R // cpu)
idxs = np.arange(0, R, chk)
block = idxs.size
starts = np.empty(block+1, np.int64)
starts[:block] = idxs
starts[-1] = R
row_sums = np.zeros((block, R), dtype=np.float32)
# print 'zptr', block, data.shape, starts
# print 'Rp is', starts[-1], xr[starts[-1]]
End = 0
for idx in prange(block):
Le, Rt = starts[idx: idx+2]
r = Le // chk
r = idx
# print 'current_r', r, block
# print 'L, R', Le, Rt, starts, chk, block, r
# print 'L_R', xr[Le], xr[Rt-1]
# print 'L, R', Le, Rt, xr[Le], xr[Rt]
Rt = min(R-1, Rt)
for i in range(Le, Rt):
# get ith row of a
kst, ked = xr[i], xr[i+1]
if kst == ked:
continue
for k in range(kst, ked):
x_col, x_val = xc[k], x[k]
# inflation
x_val = np.power(x_val, I)
#x[k] = x_val
row_sums[r, x_col] += x_val
End = max(End, x_col)
End += 1
row_sum = np.zeros(R, dtype=np.float32)
for i in range(block):
# for j in xrange(R):
for j in range(End):
row_sum[j] += row_sums[i, j]
#row_sums_sqs = np.zeros((block, R), dtype=np.float32)
row_sums_sqs = np.zeros((block, End), dtype=np.float32)
#row_maxs = np.zeros((block, R), dtype=np.float32)
row_maxs = np.zeros((block, End), dtype=np.float32)
# normalization and get the chaos
for idx in prange(block):
Le, Rt = starts[idx: idx+2]
r = Le // chk
Rt = min(R-1, Rt)
for i in range(Le, Rt):
# get ith row of a
kst, ked = xr[i], xr[i+1]
if kst == ked:
continue
for k in range(kst, ked):
x_col, x_val = xc[k], x[k]
x_val = np.power(x_val, I)
rsum = row_sum[x_col]
#x[k] = rsum != 0 and x_val / rsum or x_val
if rsum != 0:
x[k] = x_val / rsum
else:
x[k] = 0
row_sums_sqs[r, x_col] += x[k] * x[k]
row_maxs[r, x_col] = max(row_maxs[r, x_col], x[k])
return row_maxs, row_sums_sqs
@njit(fastmath=True, nogil=True, cache=True, parallel=True)
def inflate_norm_p_fast(xr, xc, x, I=1.5, cpu=1, mem=4):
R = xr.size
cpu = max(1, cpu)
#chk = max(1, R // cpu)
#chk = mem > 0 and mem * (1<<30) // cpu or R // cpu
#chk = max(1<<26, chk)
#chk = 10000
cache = mem * (1 << 29) // cpu
cache = int(cache) + 1
chk = max(cache, R // cpu + 1)
idxs = np.arange(0, R, chk)
block = idxs.size
blocks = idxs.size
starts = np.empty(block+1, np.int64)
starts[:block] = idxs
starts[-1] = R
row_sums = np.zeros((cpu, R), dtype=np.float32)
End = 0
for bst in range(0, blocks, cpu):
bed = min(bst + cpu, blocks)
# for idx in prange(block):
for idx in prange(bst, bed):
Le, Rt = starts[idx: idx+2]
r = Le // chk
r = idx
r = idx - bst
Rt = min(R-1, Rt)
for i in range(Le, Rt):
# get ith row of a
kst, ked = xr[i], xr[i+1]
if kst == ked:
continue
for k in range(kst, ked):
x_col, x_val = xc[k], x[k]
# inflation
x_val = np.power(x_val, I)
#x[k] = x_val
row_sums[r, x_col] += x_val
End = max(End, x_col)
End += 1
row_sum = np.zeros(R, dtype=np.float32)
# for i in xrange(block):
for i in range(cpu):
# for j in xrange(R):
for j in range(End):
row_sum[j] += row_sums[i, j]
#row_sums_sqs = np.zeros((block, R), dtype=np.float32)
row_sums_sqs = np.zeros((cpu, End), dtype=np.float32)
#row_maxs = np.zeros((block, R), dtype=np.float32)
row_maxs = np.zeros((cpu, End), dtype=np.float32)
for bst in range(0, blocks, cpu):
bed = min(bst + cpu, blocks)
# normalization and get the chaos
# for idx in prange(block):
for idx in prange(bst, bed):
Le, Rt = starts[idx: idx+2]
r = Le // chk
r = idx - bst
Rt = min(R-1, Rt)
for i in range(Le, Rt):
# get ith row of a
kst, ked = xr[i], xr[i+1]
if kst == ked:
continue
for k in range(kst, ked):
x_col, x_val = xc[k], x[k]
x_val = np.power(x_val, I)
rsum = row_sum[x_col]
#x[k] = rsum != 0 and x_val / rsum or x_val
if rsum != 0:
x[k] = x_val / rsum
else:
x[k] = 0
row_sums_sqs[r, x_col] += x[k] * x[k]
row_maxs[r, x_col] = max(row_maxs[r, x_col], x[k])
return row_maxs, row_sums_sqs
# normalization of row
@njit(fastmath=True, nogil=True, cache=True, parallel=True)
def inflate_norm_p0(xr, xc, x, I=1.5, cpu=1, mem=4):
R = xr.size
row_sums = np.zeros(R, dtype=np.float32)
row_sums_sqs = row_sums.copy()
row_maxs = row_sums.copy()
for i in prange(R-1):
# get ith row of a
jst, jed = xr[i], xr[i+1]
if jst == jed:
continue
for j in range(jst, jed):
x[j] = np.power(x[j], I)
row_sums[i] += x[j]
for j in range(jst, jed):
x[j] /= row_sums[i]
row_sums_sqs[i] += x[j] * x[j]
row_maxs[i] = max(row_maxs[i], x[j])
return row_maxs, row_sums_sqs
# inflation and normalization
def inflate_norm_p_ez(x, I=1.5, cpu=1, mem=4):
#row_maxs, row_sums_sqs = inflate_norm_p(x.indptr, x.indices, x.data, I=I, cpu=cpu, mem=mem)
row_maxs, row_sums_sqs = inflate_norm_p_fast(
x.indptr, x.indices, x.data, I=I, cpu=cpu, mem=mem)
chaos = np.nanmax(row_maxs, 0) - np.nansum(row_sums_sqs, 0)
return chaos.max()
# inflate and get row sum
@njit(fastmath=True, nogil=True, cache=True, parallel=True)
def inflate_t(xr, xc, x, row_sums, Le, Rt, r, I=1.5):
print('inflate_t_r', r)
R = xr.size
Rt = min(R-1, Rt)
for i in range(Le, Rt):
# get ith row of a
kst, ked = xr[i], xr[i+1]
if kst == ked:
continue
for k in range(kst, ked):
x_col, x_val = xc[k], x[k]
# inflation
x_val = np.power(x_val, I)
x[k] = x_val
row_sums[r, x_col] += x_val
# normalization
@njit(fastmath=True, nogil=True, cache=True, parallel=True)
def norm_t(xr, xc, x, row_sum, row_sums_sqs, row_maxs, Le, Rt, r, I=1.5):
print('inflate_t_r', r)
R = xr.size
Rt = min(R-1, Rt)
# normalization and get the chaos
for i in range(Le, Rt):
# get ith row of a
kst, ked = xr[i], xr[i+1]
if kst == ked:
continue
for k in range(kst, ked):
x_col, x_val = xc[k], x[k]
rsum = row_sum[x_col]
x[k] = rsum != 0 and x_val / rsum or x_val
row_sums_sqs[r, x_col] += x[k] * x[k]
row_maxs[r, x_col] = max(row_maxs[r, x_col], x[k])
# inflation and normalization
def inflate_norm_t_ez(x, I=1.5, cpu=1):
xr, xc, x = x.indptr, x.indices, x.data
R = xr.size
chk = R // cpu
idxs = np.arange(0, R, chk)
block = idxs.size
starts = np.empty(block+1, np.int64)
starts[:block] = idxs
starts[-1] = R
row_sums = np.zeros((block, R), dtype=np.float32)
fn = x.filename
xs = [load_npz_disk(fn) for elem in range(block)]
threads = []
for idx in prange(block):
Le, Rt = starts[idx: idx+2]
r = Le // chk
xr, xc, x = xs[idx].indptr, xs[idx].indices, xs[idx].data
t = worker(inflate_t, (xr, xc, x, row_sums, Le, Rt, r, I))
t.start()
threads.append(t)
for t in threads:
t.join()
row_sum = row_sums.sum(0)
del threads
gc.collect()
row_sums_sqs = np.zeros((block, R), dtype=np.float32)
row_maxs = np.zeros((block, R), dtype=np.float32)
threads = []
for idx in prange(block):
Le, Rt = starts[idx: idx+2]
r = Le // chk
xr, xc, x = xs[idx].indptr, xs[idx].indices, xs[idx].data
t = worker(norm_t, (xr, xc, x, row_sum,
row_sums_sqs, row_maxs, Le, Rt, r, I))
t.start()
threads.append(t)
for t in threads:
t.join()
# close xs
for xcsr in xs:
csr_close(xcsr)
#row_maxs, row_sums_sqs = inflate_norm_t(x.indptr, x.indices, x.data, Le, Rt, I=I, cpu=cpu)
#chaos = row_maxs.max(0) - row_sums_sqs.sum(0)
chaos = np.nanmax(row_maxs, 0) - np.nanmax(row_sums_sqs, 0)
return chaos.max()
# return threads
# return chaos
# a + b
@njit(fastmath=True, nogil=True, cache=True)
def csram_ms(xr, xc, x, yr, yc, y, zr, zc, z):
R = xr.size
D = yr.size
nnz = z.size
data = np.zeros(D-1, dtype=x.dtype)
visit = np.zeros(D, dtype=np.int8)
index = np.zeros(D, yr.dtype)
zptr = 0
for i in range(R - 1):
ks = 0
# get ith row of a
ast, aed = xr[i], xr[i+1]
bst, bed = yr[i], yr[i+1]
for j in range(ast, aed):
col, val = xc[j], x[j]
if val != 0:
pass
else:
continue
data[col] += val
if visit[col] == 0:
index[ks] = col
ks += 1
visit[col] = 1
else:
continue
for j in range(bst, bed):
col, val = yc[j], y[j]
if val != 0:
pass
else:
continue
data[col] += val
if visit[col] == 0:
index[ks] = col
ks += 1
visit[col] = 1
else:
continue
for pt in range(ks):
col = index[pt]
visit[col] = 0
val = data[col]
if val != 0:
zc[zptr], z[zptr] = col, val
zptr += 1
data[col] = 0
zr[i+1] = zptr
# print 'the zptr hello', zptr
flag = zptr
return zptr, flag
# a + b
def csram_ez_ms0(a, b, cpu=1, prefix=None, tmp_path=None, disk=False):
assert a.shape == b.shape
np.nan_to_num(a.data, False)
np.nan_to_num(b.data, False)
xr, xc, x = a.indptr, a.indices, a.data
yr, yc, y = b.indptr, b.indices, b.data
R = xr.shape[0]
nnz = a.nnz + b.nnz
if prefix == None:
tmpfn = tempfile.mktemp('tmp', dir=tmp_path)
else:
tmpfn = prefix
zr = np.zeros(R, xr.dtype)
if disk:
#zr = np.memmap(tmpfn + '_zr_ms.npy', mode='w+', shape=R, dtype=xr.dtype)
zc = np.memmap(tmpfn + '_zc_ms.npy', mode='w+',
shape=nnz, dtype=xc.dtype)
z = np.memmap(tmpfn + '_z_ms.npy', mode='w+', shape=nnz, dtype=x.dtype)
else:
#zr = np.zeros(R, xr.dtype)
zc = np.empty(nnz, dtype=xc.dtype)
z = np.empty(nnz, dtype=x.dtype)
zptr, flag = csram_ms(xr, xc, x, yr, yc, y, zr, zc, z)
# truncate
if disk:
print('before truncate', zc.size, zptr)
zc.flush()
N = zptr * zc.strides[0]
fn = zc.filename
_dtype = zc.dtype
del zc
f = open(fn, 'r+')
f.truncate(N)
f.close()
zc = np.memmap(fn, mode='r+', dtype=_dtype)
print('after truncate', zc.size, zptr)
z.flush()
N = zptr * z.strides[0]
fn = z.filename
_dtype = z.dtype
del z
f = open(fn, 'r+')
f.truncate(N)
f.close()
z = np.memmap(fn, mode='r+', dtype=_dtype)
shape = a.shape
if disk:
zmtx = sparse.csr_matrix(shape, dtype=z.dtype)
zmtx.indptr, zmtx.indices, zmtx.data = zr, zc, z
save_npz_disk(zmtx, tmpfn + '.npy')
del zmtx
os.system('rm %s_z*_ms.npy' % tmpfn)
zmtx = load_npz_disk(tmpfn + '.npy')
else:
indptr = zr
indices = zc
data = z
zmtx = sparse.csr_matrix(
(data, indices, indptr), shape=shape, dtype=z.dtype)
gc.collect()
return zmtx
def csram_ez_ms(a, b, cpu=1, prefix=None, tmp_path=None, disk=False):
assert a.shape == b.shape
np.nan_to_num(a.data, False)
np.nan_to_num(b.data, False)
xr, xc, x = a.indptr, a.indices, a.data
yr, yc, y = b.indptr, b.indices, b.data
shape = a.shape
R = xr.shape[0]
nnz = a.nnz + b.nnz
if prefix == None:
tmpfn = tempfile.mktemp('tmp', dir=tmp_path)
else:
tmpfn = prefix
if not tmpfn.endswith('.npy'):
tmpfn += '.npy'
if disk:
ac = R
bc = nnz
Nc = 5 + ac * 2 + bc * 2
fp = np.memmap(tmpfn, mode='w+', shape=Nc, dtype='int32')
Rc, Cc = shape
fp[:3] = [Rc, Cc, ac]
Bc = np.asarray([bc], 'int64')
Bc.dtype = 'int32'
fp[3:5] = Bc[:2]
start = 5
end = start + ac * 2
zr = fp[start: end]
zr.dtype = 'int64'
start = end
end = bc + start
zc = fp[start:end]
start = end
end = bc + start
z = fp[start:end]
z.dtype = 'float32'
else:
zr = np.zeros(R, xr.dtype)
zc = np.empty(nnz, dtype=xc.dtype)
z = np.empty(nnz, dtype=x.dtype)
zptr, flag = csram_ms(xr, xc, x, yr, yc, y, zr, zc, z)
if disk:
zmtx = load_npz_disk(tmpfn)
else:
indptr = zr
indices = zc
data = z
zmtx = sparse.csr_matrix(
(data, indices, indptr), shape=shape, dtype=z.dtype)
gc.collect()
return zmtx
@njit
def resize(a, new_size):
new = np.empty(new_size, a.dtype)
new[:a.size] = a
return new
@njit
def resize_mmp(a, new_size):
new = np.asarray(np.memmap('tmp.npy', mode='w+',
shape=new_size, dtype=a.dtype), dtype=a.dtype)
new[:a.size] = a
return new
# csr matrix by matrix
# original version
@njit(fastmath=True, nogil=True, cache=True)
def csrmm_ori(xr, xc, x, yr, yc, y, visit):
R = xr.shape[0]
D = yr.shape[0]
nnz = int(1. * x.size * y.size / (D - 1))
#nnz = x.size + y.size
print('nnz size', nnz)
# zr, zc, z = np.zeros(R, 'int32'), np.empty(nnz*5, 'int32'), np.empty(nnz*5, dtype=x.dtype)
n_size = nnz
zr, zc, z = np.zeros(R, xr.dtype), np.empty(
n_size, xc.dtype), np.empty(n_size, dtype=x.dtype)
data = np.zeros(D - 1, dtype=x.dtype)
# print 'zr init', zr[:5]
# hash table
#visit = np.zeros(yr.size, 'int8')
index = np.zeros(yr.size, yr.dtype)
flag = 0
zptr = 0
for i in range(R - 1):
# get ith row of a
kst, ked = xr[i], xr[i + 1]
if kst == ked:
zr[i + 1] = zr[i]
continue
ks = 0
nz = 0
for k in range(kst, ked):
x_col, x_val = xc[k], x[k]
# get row of b
jst, jed = yr[x_col], yr[x_col + 1]
if jst == jed:
continue
nz += jed - jst
for j in range(jst, jed):
y_col, y_val = yc[j], y[j]
data[y_col] += x_val * y_val
if visit[y_col] == 0:
visit[y_col] = 1
index[ks] = y_col
ks += 1
flag += 3
#nz += 1
flag += 3
flag += 2
zend = zr[i] + nz
if zend > n_size:
n_size += nnz
print('resize sparse matrix', n_size)
zc = resize(zc, n_size)
z = resize(z, n_size)
flag += 2
for pt in range(ks):
idx = index[pt]
#mx_col = max(mx_col, idx)
val = data[idx]
visit[idx] = 0
if val > 0:
zc[zptr], z[zptr] = idx, val
zptr += 1
data[idx] = 0
flag += 5
flag += 1
zr[i + 1] = zptr
return zr, zc[:zptr], z[:zptr], flag
#zmtx = sps.csr_matrix((z[:zptr], zc[:zptr], zr), shape=(a.shape[0], b.shape[1]))
# return zmtx
# memory save version
@njit(fastmath=True, nogil=True, cache=True)
def csrmm_msav(xr, xc, x, yr, yc, y, visit):
R = xr.shape[0]
D = yr.shape[0]
chk = x.size + y.size
#nnz = chk
nnz = min(max(int(1. * x.size * y.size / (D - 1)), chk * 33), chk * 50)
print('nnz size', chk, nnz)
# zr, zc, z = np.zeros(R, 'int32'), np.empty(nnz*5, 'int32'), np.empty(nnz*5, dtype=x.dtype)
zr, zc, z = np.zeros(R, xr.dtype), np.empty(
nnz, xc.dtype), np.empty(nnz, dtype=x.dtype)
data = np.zeros(D - 1, dtype=x.dtype)
# print 'zr init', zr[:5], zc[:5], z[:5]
# hash table
#visit = np.zeros(yr.size, 'int8')
#index = np.zeros(yr.size, yr.dtype)
index = np.zeros(yr.size, yr.dtype)
flag = 0
zptr = 0
for i in range(R - 1):
# get ith row of a
kst, ked = xr[i], xr[i + 1]
if kst == ked:
zr[i + 1] = zr[i]
continue
i_sz = index.size
ks = 0
nz = 0
for k in range(kst, ked):
x_col, x_val = xc[k], x[k]
# get row of b
jst, jed = yr[x_col], yr[x_col + 1]
if jst == jed:
continue
nz += jed - jst
flag += 2
for j in range(jst, jed):
# for j in prange(jst, jed):
y_col, y_val = yc[j], y[j]
# print 'before', ks, len(index), i_sz
y_col_val = data[y_col] + x_val * y_val
if y_col_val != 0:
if ks < i_sz:
index[ks] = y_col
else:
i_sz += (jed - jst) * 2
index = resize(index, i_sz)
index[ks] = y_col
ks += 1
flag += 2
data[y_col] = y_col_val
flag += 3
# print 'end', ks, len(index), i_sz
#print(k, jst, jed, len(yr))
zend = zr[i] + nz
if zend > nnz:
print('resize estimate', nnz, nnz + chk * 15, nnz * R / i)
#nnz = max(chk+nnz, R/i*nnz)
nnz += chk * 15
#print('resize sparse matrix', n_size)
zc = resize(zc, nnz)
z = resize(z, nnz)
flag += 2
for pt in range(ks):
# for pt in prange(ks):
y_col = index[pt]
#mx_col = max(mx_col, idx)
y_col_val = data[y_col]
if y_col_val != 0:
zc[zptr], z[zptr] = y_col, y_col_val
zptr += 1
data[y_col] = 0
flag += 3
flag += 1
zr[i + 1] = zptr
print('the zptr', zptr)
return zr, zc[:zptr], z[:zptr], flag
@njit(fastmath=True, nogil=True, cache=True)
def csrmm_msav1(xr, xc, x, yr, yc, y):
R = xr.shape[0]
D = yr.shape[0]
chk = x.size + y.size
nnz = chk
print('nnz size', nnz)
# zr, zc, z = np.zeros(R, 'int32'), np.empty(nnz*5, 'int32'), np.empty(nnz*5, dtype=x.dtype)
zr, zc, z = np.zeros(R, xr.dtype), np.empty(
nnz, xc.dtype), np.empty(nnz, dtype=x.dtype)
data = np.zeros(D - 1, dtype=x.dtype)
print('zr init', zr[:5], zc[:5], z[:5])
# hash table
#visit = np.zeros(yr.size, 'int8')
#index = np.zeros(yr.size, yr.dtype)
index = np.zeros(yr.size, yr.dtype)
index_tmp = np.zeros(yr.size, yr.dtype)
index_mg = np.zeros(yr.size, yr.dtype)
flag = 0
zptr = 0
for i in range(R - 1):
# get ith row of a
kst, ked = xr[i], xr[i + 1]
if kst == ked:
zr[i + 1] = zr[i]
continue
index[0], index_tmp[0] = -1, -1
nz = 0
ks = 0
for k in range(kst, ked):
x_col, x_val = xc[k], x[k]
# get row of b
jst, jed = yr[x_col], yr[x_col + 1]
if jst == jed:
continue
nz += jed - jst
flag += 2
ks_tmp = 0
for j in range(jst, jed):
y_col, y_val = yc[j], y[j]
y_col_val = data[y_col] + x_val * y_val
if y_col_val != 0:
index_tmp[ks_tmp] = y_col
ks_tmp += 1
flag += 2
data[y_col] = y_col_val
flag += 3
# print 'end', ks, len(index), i_sz
if index[0] == -1:
index, index_tmp = index_tmp, index
ks = ks_tmp
if index_tmp[0] != -1:
#ks = merge_index(index, index_tmp)
ks_mg = p0 = p1 = 0
while p0 < ks and p1 < ks_tmp:
idx0 = index[p0]
idx1 = index_tmp[p1]
if idx0 < idx1:
index_mg[ks_mg] = idx0
p0 += 1
else:
p1 += 1
index_mg[ks_mg] = idx1
if ks_mg <= 0 or index_mg[ks_mg - 1] != index_mg[ks_mg]:
ks_mg += 1
else:
continue
index, index_mg = index_mg, index
ks, ks_mg = ks_mg, ks
#print(k, jst, jed, len(yr))
print(index[:ks + 1])
zend = zr[i] + nz
if zend > nnz:
nnz += chk
#print('resize sparse matrix', n_size)
zc = resize(zc, nnz)
z = resize(z, nnz)
flag += 2
for pt in range(ks):
# for pt in prange(ks):
y_col = index[pt]
#mx_col = max(mx_col, idx)