- Notifications
You must be signed in to change notification settings - Fork 16
Expand file tree
/
Copy pathalg.lua
More file actions
Latest commit
832 lines (746 loc) · 21.8 KB
/
Copy pathalg.lua
File metadata and controls
832 lines (746 loc) · 21.8 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
--------------------------------------------------------------------------------
-- Matrix and vector algebra module.
--
-- Copyright (C) 2011-2016 Stefano Peluchetti. All rights reserved.
--------------------------------------------------------------------------------
-- TODO: Stack.
-- TODO: Use only the algorithms in OpenBLAS: support only the supported types.
-- TODO: Views: sub, row, col, diag
-- TODO: Custom allocator
-- TODO: Can bound checks be optimized?
-- TODO: Can access be optimized (contiguous memory + $** / no shifts) ?
-- TODO: Can access to BLAS functions be optimized?
-- TODO: For vectors: r = c = 0 or r = 1, c = n ? (totable then changes)
-- TODO: Minimize dimension and type checks in BLAS operations.
-- TODO: Can the request to the stack be optimized (is the pointer sunk?) ?
-- TODO: better dimension reporting.
-- TODO: Use column vectors: think of matrix vector ,multiplication.
-- TODO: Just mul() instead of mulmv() and mulmm().
-- TODO: Consider avoiding type checks via calls like x:_method_element_type().
-- TODO: Remove _new.
-- TODO: Think of removing _gem*.
-- Notes:
-- + BLAS requires contiguous memory and allows only for aliasing between inputs
-- + to decide faster way a reasonable number of benchmarks must be available,
-- including ones that perform allocations.
localffi=require'ffi'
localbit=require'bit'
localxsys=require'xsys'
localSTACK_BUFFER=10e6
assert(STACK_BUFFER>=0)
localSTACK_ELEMENT=ffi.typeof('double') -- TODO: Fix casting!
localJOIN_UNROLL=5
assert(JOIN_UNROLL>0)
localtype, setmetatable, rawequal=type, setmetatable, rawequal
localband=bit.band
localfloor, ceil=math.floor, math.ceil
localtemplate=xsys.template
localwidth=xsys.string.width
-- Array memory ops ------------------------------------------------------------
-- Invariant: n == r*c.
localfunctionarray_alloc(ct, n, r, c)
locala=ffi.new(ct, n) -- Default initialization of VLS, compiled.
a._n, a._r, a._c=n, r, c
a._p=a._v
returna-- VLS are automatically zero-filled for default initializer case.
end
localfunctionarray_map(ct, n, r, c, p)
locala=ffi.new(ct, 0) -- Default initialization of VLS, compiled.
a._n, a._r, a._c=n, r, c
a._p=p
returna-- VLS are automatically zero-filled for default initializer case.
end
localfunctionarray_copy_data(dest, source)
localsource_size=ffi.sizeof(source:elementct())*source._n
ffi.copy(dest._p, source._p, source_size)
end
localfunctionarray_copy_data_offset(dest, source, offset)
localsource_size=ffi.sizeof(source:elementct())*source._n
ffi.copy(dest._p+offset, source._p, source_size)
end
localfunctionarray_clear(x)
localx_size=ffi.sizeof(x:elementct())*x._n
ffi.fill(x._p, x_size)
end
-- Stack -----------------------------------------------------------------------
-- TODO: Use malloc.
-- TODO: Allow growth.
localstack_struct='struct { int32_t _max, _n; $ _p[?]; }'
localfunctionmem_stack_data(self, n)
self._n=self._n+n
returnself._p+ (self._n-n)
end
localfunctionnew_mem_stack_ct(element_ct)
localstack_mt= {
__new=function(ct, maxsize)
localo=ffi.new(ct, maxsize)
o._max=maxsize
returno
end,
clear=function(self)
array_clear(self)
self._n=0
end,
request=function(self, n)
returnself._n+n<=self._maxandmem_stack_data(self, n)
end,
elementct=function()
returnelement_ct
end,
}
stack_mt.__index=stack_mt
localstack_ct=ffi.typeof(stack_struct, element_ct)
returnffi.metatype(stack_ct, stack_mt)
end
localstack_element_size=ffi.sizeof(STACK_ELEMENT)
localstack_elements=STACK_BUFFER/stack_element_size
localstack=new_mem_stack_ct(STACK_ELEMENT)(stack_elements)
localfunctionstack_array(self, n, r, c)
localnbuff=ceil(ffi.sizeof(self:elementct())*n/stack_element_size)
localp=stack:request(nbuff)
returnpandarray_map(self, n, r, c, ffi.cast(self._p, p)) orarray_alloc(self, n, r, c)
end
localfunctionstack_clear()
stack:clear()
end
-- BLAS ------------------------------------------------------------------------
localblas_element_code=template([[
local ffi = require 'ffi'
local cblas_h = require 'sci._cblas_h'
ffi.cdef(cblas_h)
local blas = ffi.load('libopenblas')
local complex_a1 = ffi.typeof('complex[1]')
local compflo_a1 = ffi.typeof('complex float[1]')
local compfloa, compflob = compflo_a1(), compflo_a1()
local complexa, complexb = complex_a1(), complex_a1()
return {
| for ELEMENT_NAME, BLAS in pairs{
| float = { PREFIX = 's' },
| double = { PREFIX = 'd' },
| ['complex float'] = { PREFIX = 'c', ALPHA = 'compfloa', BETA = 'compflob' },
| complex = { PREFIX = 'z', ALPHA = 'complexa', BETA = 'complexb' },
| } do
[tonumber(ffi.typeof('${ELEMENT_NAME}'))] = {
gemm = function(C, A, B, At, Bt, alpha, beta)
${BLAS.ALPHA and BLAS.ALPHA..'[0] = alpha'}
${BLAS.BETA and BLAS.BETA..'[0] = beta'}
blas.cblas_${BLAS.PREFIX}gemm(
blas.CblasRowMajor,
At and blas.CblasTrans or blas.CblasNoTrans,
Bt and blas.CblasTrans or blas.CblasNoTrans,
C:nrow(),
C:ncol(),
At and A:nrow() or A:ncol(),
${BLAS.ALPHA and BLAS.ALPHA or 'alpha'},
A:data(),
A:ncol(),
B:data(),
B:ncol(),
${BLAS.BETA and BLAS.BETA or 'beta'},
C:data(),
C:ncol()
)
end,
gemv = function(y, A, x, At, alpha, beta)
${BLAS.ALPHA and BLAS.ALPHA..'[0] = alpha'}
${BLAS.BETA and BLAS.BETA..'[0] = beta'}
blas.cblas_${BLAS.PREFIX}gemv(
blas.CblasRowMajor,
At and blas.CblasTrans or blas.CblasNoTrans,
A:nrow(),
A:ncol(),
${BLAS.ALPHA and BLAS.ALPHA or 'alpha'},
A:data(),
A:ncol(),
x:data(),
1,
${BLAS.BETA and BLAS.BETA or 'beta'},
y:data(),
1
)
end,
},
| end
}
]])()
localblas_element_ct=assert(loadstring(blas_element_code))()
localfunctionsame_type_check_2(x, y)
ifx:elementct() ~=y:elementct() then
error('constant element type required')
end
end
localfunctionsame_type_check_3(x, y, z)
localct=x:elementct()
ifct~=y:elementct() orct~=z:elementct() then
error('constant element type required')
end
end
localfunctiondimensions_mat(A, At)
localAr, Ac=A:nrow(), A:ncol()
ifAtthen
Ar, Ac=Ac, Ar
end
returnAr*Ac, Ar, Ac
end
localfunctiondimensions_mat_same_check(A, At, Br, Bc)
local_, Ar, Ac=dimensions_mat(A, At)
ifAr~=BrorAc~=Bcthen
error('matrix dimensions disagree')
end
end
localfunctiondimensions_mat_square_check(Ar, Ac)
ifAr~=Acthen
error('square matrix expected')
end
end
localfunctiondimensions_mul_check_2(A, B, At, Bt)
local_, Ar, Ac=dimensions_mat(A, At)
local_, Br, Bc=dimensions_mat(B, Bt)
ifAc~=Brthen
error("incompatible dimensions in matrix-matrix multiplication")
end
returnAr*Bc, Ar, Bc
end
localfunctiondimensions_mul_check_3(C, A, B, At, Bt)
localCn, Cr, Cc=dimensions_mul_check_2(A, B, At, Bt)
dimensions_mat_same_check(C, false, Cr, Cc)
returnCn, Cr, Cc
end
localfunctiondimensions_pow_check_1(A)
localAn, Ar, Ac=dimensions_mat(A)
dimensions_mat_square_check(Ar, Ac)
returnAn, Ar, Ac
end
localfunctiondimensions_pow_check_2(B, A)
localAn, Ar, Ac=dimensions_pow_check_1(A)
dimensions_mat_same_check(B, false, Ar, Ac)
returnAn, Ar, Ac
end
localfunction__mul(C, A, B, At, Bt)
same_type_check_3(C, A, B)
localCn, Cr, Cc=dimensions_mat(C)
localalias=rawequal(C, A) orrawequal(C, B)
localT=aliasandstack_array(C, Cn, Cr, Cc) orC
ifCc==1then
T:_gemv(A, B, At, 1, 0)
else
T:_gemm(A, B, At, Bt, 1, 0)
end
ifaliasthen
array_copy_data(C, T)
end
end
localfunctionmul(C, A, B, At, Bt)
dimensions_mul_check_3(C, A, B, At, Bt)
__mul(C, A, B, At, Bt)
stack_clear()
end
-- Exponentiation by squaring algorithm:
localfunctionpow_recursive(A, s, n)
localT=stack_array(A, n*n, n, n)
ifs==1then
-- Cannot return A because could generate aliasing between R and T below.
array_copy_data(T, A)
returnT
elseifs==2then
T:_gemm(A, A, false, false, 1, 0)
returnT
elseifband(s, 1) ==0then-- Even.
T:_gemm(A, A, false, false, 1, 0)
returnpow_recursive(T, s/2, n)
else
T:_gemm(A, A, false, false, 1, 0)
localR=pow_recursive(T, (s-1)/2, n) -- R cannot alias T.
T:_gemm(R, A, false, false, 1, 0)
returnT
end
end
localfunctionpow_dispatch(B, A, s)
localn=B:nrow()
ifs==0then
array_clear(B)
fori=1,ndoB[{i,i}] =1end
elseifs==1then
array_copy_data(B, A)
else
localT=pow_recursive(A, s, n)
array_copy_data(B, T)
end
end
-- TODO: Use SVD decomposition for large s and allow positive real s.
localfunction__pow(B, A, s)
same_type_check_2(B, A)
ifs<0orfloor(s) ~=sthen
error('NYI: matrix exponentiation supported only for nonnegative integers')
end
pow_dispatch(B, A, s)
end
localfunctionpow(B, A, s)
dimensions_pow_check_2(B, A)
__pow(B, A, s)
stack_clear()
end
--------------------------------------------------------------------------------
localfunctionsum(x)
localv=0
fori=0,#x-1dov=v+x._p[i] end
returnv
end
localfunctionprod(x)
localv=1
fori=0,#x-1dov=v*x._p[i] end
returnv
end
localfunctiontrace(A)
local_, Ar, Ac=dimensions_mat(A)
dimensions_mat_square_check(Ar, Ac)
localv=0
fori=1,Ardo
v=v+A[{i,i}]
end
returnv
end
-- Join ------------------------------------------------------------------------
localfunctionrep(what, first, last, sep)
sep=sepor', '
localincrement=last>=firstand1or-1
localo= { }
fori=first,last,incrementdo
o[#o+1] =what:gsub('@', i)
end
returntable.concat(o, sep)
end
localconcat_code=template([[
local setmetatable = setmetatable
local concat_n_mt = {
_new = function(self, n, r, c)
return self[1]:_new(n, r, c)
end,
nrow = function(self)
return self[1]:nrow()
end,
ncol = function(self)
local nc = 0
for i=1,self[0] do
nc = nc + self[i]:ncol()
end
return nc
end,
elementct = function(self)
return self[1]:elementct()
end,
_concat_dispatch = function(self, lhs)
local na = self[0]
self[na + 1] = lhs
self[0] = na + 1
return self
end,
_copy_into = function(self, out, offset)
local na, nr = self[0], self[1]._r
for r=1,nr do
for a=na,1,-1 do
local nc = self[a]._c
for c=1,nc do
out._p[offset + c - 1] = self[a]._p[(r-1)*nc + c - 1]
end
offset = offset + nc
end
end
return offset
end,
}
concat_n_mt.__index = concat_n_mt
| for N=JOIN_UNROLL,2,-1 do
local concat_${N}_mt = {
_new = function(self, n, r, c)
return self[1]:_new(n, r, c)
end,
nrow = function(self)
return self[1]:nrow()
end,
ncol = function(self)
return ${R('self[@]:ncol()', 1, N, ' + ')}
end,
elementct = function(self)
return self[1]:elementct()
end,
_concat_dispatch = function(self, lhs)
| if N == JOIN_UNROLL then
self[0] = ${N + 1}
return setmetatable({ ${R('self[@]', 1, N)}, lhs }, concat_n_mt)
| else
return setmetatable({ ${R('self[@]', 1, N)}, lhs }, concat_${N + 1}_mt)
| end
end,
_copy_into = function(self, out, offset)
for r=1,self[1]:nrow() do
| for I=N,1,-1 do
local nc = self[${I}]._c
for c=1,nc do
out._p[offset + c - 1] = self[${I}]._p[(r-1)*nc + c - 1]
end
offset = offset + nc
| end
end
return offset
end,
}
concat_${N}_mt.__index = concat_${N}_mt
| end
return concat_2_mt
]])({ JOIN_UNROLL=JOIN_UNROLL, R=rep })
localconcat_2_mt=assert(loadstring(concat_code))()
localjoin_code=template([[
local select = select
local error = error
local function join_1(x1)
local nr, nc = x1:nrow(), x1:ncol()
local a = x1:_new(nr*nc, nr, nc)
x1:_copy_into(a, 0)
return a
end
| for N=2,JOIN_UNROLL do
local function join_${N}(${R('x@', 1, N)})
local nr, nc, ct = x1:nrow(), x1:ncol(), x1:elementct()
if ${R('x@:elementct() ~= ct', 2, N, ' or ')} then
error('constant element type required')
end
if ${R('x@:ncol() ~= nc', 2, N, ' or ')} then
error('constant number of columns required')
end
nr = nr + ${R('x@:nrow()', 2, N, ' + ')}
local a = x1:_new(nr*nc, nr, nc)
local offset = 0
| for I=1,N do
offset = x${I}:_copy_into(a, offset)
| end
return a
end
| end
local function join_n(n, ...)
local arg = { ... }
local nr, nc, ct = arg[1]:nrow(), arg[1]:ncol(), arg[1]:elementct()
for i=2,n do
if arg[i]:elementct() ~= ct then
error('constant element type required')
end
if arg[i]:ncol() ~= nc then
error('constant number of columns required')
end
nr = nr + arg[i]:nrow()
end
local a = arg[1]:_new(nr*nc, nr, nc)
local offset = 0
for i=1,n do
offset = arg[i]:_copy_into(a, offset)
end
return a
end
return function(...)
local n = select('#', ...)
if n == 1 then
return join_1(...)
| for I=2,JOIN_UNROLL do
elseif n == ${I} then
return join_${I}(...)
| end
else
return join_n(n, ...)
end
end
]])({ JOIN_UNROLL=JOIN_UNROLL, R=rep })
localjoin=assert(loadstring(join_code))()
-- Array -----------------------------------------------------------------------
localarray_struct='struct { int32_t _n, _r, _c; $* _p; $ _v[?]; }'
localfunctionunsupported_element_ct(self)
error('operation not supported for element type '..tostring(self:elementct()))
end
localfunctionnew_array_ct(element_ct, element_copy)
localarray_mt
array_mt= {
new=function(self)
returnarray_alloc(self, self._n, self._r, self._c)
end,
copy=function(self)
locala=self:new()
array_copy_data(a, self)
returna
end,
_new=function(self, n, r, c)
returnarray_alloc(self, n, r, c)
end,
_copy_into=function(self, out, offset)
array_copy_data_offset(out, self, offset)
returnoffset+self._n
end,
_concat_dispatch=function(self, lhs) -- Concatenating two array_ct.
returnsetmetatable({ [0] =2, self, lhs }, concat_2_mt)
end,
__concat=function(lhs, rhs)
iflhs:nrow() ~=rhs:nrow() then
error('constant number of rows required')
end
same_type_check_2(lhs, rhs)
returnrhs:_concat_dispatch(lhs)
end,
sub=function(self, f, l)
iff<1orf-1>lorl>self._nthen
error('out of bounds first: '..f..', last: '..l..', length: '..self._n)
end
ifself._n~=0andself._c~=1then
error('single-column array required')
end
locala=array_alloc(self, l-f+1, l-f+1, 1)
array_copy_data_offset(a, self, f-1)
returna
end,
__len=function(self)
returnself._n
end,
nrow=function(self)
returnself._r
end,
ncol=function(self)
returnself._c
end,
__index=element_copyandfunction(self, k)
iftype(k) =='number' then
ifk<1ork>self._nthen
error('out of bounds index: '..k..', length: '..self._n)
end
returnelement_copy(self._p[k-1])
elseiftype(k) =='table' then
localr, c=k[1], k[2]
ifr<1orr>self._rthen
error('out of bounds row: '..r..', number of rows: '..self._r)
end
ifc<1orc>self._cthen
error('out of bounds column: '..c..', number of columns: '..self._c)
end
returnelement_copy(self._p[(r-1)*self._c+ (c-1)])
else
returnarray_mt[k]
end
endorfunction(self, k)
iftype(k) =='number' then
ifk<1ork>self._nthen
error('out of bounds index: '..k..', length: '..self._n)
end
returnself._p[k-1]
elseiftype(k) =='table' then
localr, c=k[1], k[2]
ifr<1orr>self._rthen
error('out of bounds row: '..r..', number of rows: '..self._r)
end
ifc<1orc>self._cthen
error('out of bounds column: '..c..', number of columns: '..self._c)
end
returnself._p[(r-1)*self._c+ (c-1)]
else
returnarray_mt[k]
end
end,
__newindex=element_copyandfunction(self, k, v)
iftype(k) =='number' then
ifk<1ork>self._nthen
error('out of bounds index: '..k..', length: '..self._n)
end
self._p[k-1] =element_copy(v)
elseiftype(k) =='table' then
localr, c=k[1], k[2]
ifr<1orr>self._rthen
error('out of bounds row: '..r..', number of rows: '..self._r)
end
ifc<1orc>self._cthen
error('out of bounds column: '..c..', number of columns: '..self._c)
end
self._p[(r-1)*self._c+ (c-1)] =element_copy(v)
end
endorfunction(self, k, v)
iftype(k) =='number' then
ifk<1ork>self._nthen
error('out of bounds index: '..k..', length: '..self._n)
end
self._p[k-1] =v
elseiftype(k) =='table' then
localr, c=k[1], k[2]
ifr<1orr>self._rthen
error('out of bounds row: '..r..', number of rows: '..self._r)
end
ifc<1orc>self._cthen
error('out of bounds column: '..c..', number of columns: '..self._c)
end
self._p[(r-1)*self._c+ (c-1)] =v
end
end,
totable=function(self)
localo= { }
fori=1,self:nrow() do
o[i] = { }
forj=1,self:ncol() do
o[i][j] =self[{i, j}]
end
end
returno
end,
__tostring=function(self)
localo= { }
fori=1,self:nrow() do
o[i] = { }
forj=1,self:ncol() do
o[i][j] =width(self[{i, j}])
end
o[i] =table.concat(o[i], ",")
end
returntable.concat(o, "\n")
end,
elementct=function()
returnelement_ct
end,
data=function(self)
returnself._p
end,
}
localelement_ct_id=tonumber(element_ct)
localblas_algo=blas_element_ct[element_ct_id]
ifblas_algothen
array_mt._gemm=blas_algo.gemm
array_mt._gemv=blas_algo.gemv
else
array_mt._gemm=unsupported_element_ct
array_mt._gemv=unsupported_element_ct
end
localct=ffi.typeof(array_struct, element_ct, element_ct)
returnffi.metatype(ct, array_mt)
end
-- Typeof ----------------------------------------------------------------------
-- To preserve value semantics.
localallowed_element_ct= { }
localdiff=require'sci.diff'
forct_nameinpairs{
bool=true,
char=true,
int8_t=true,
int16_t=true,
int32_t=true,
int64_t=true,
uint8_t=true,
uint16_t=true,
uint32_t=true,
uint64_t=true,
float=true,
double=true,
['complex float'] =true,
complex=true,
[diff.dn] =true,
} do
localct_id=tonumber(ffi.typeof(ct_name))
allowed_element_ct[ct_id] =true
end
localalg_element_ct= { }
localfunctionalg_typeof(element_ct)
element_ct=ffi.typeof(element_ct) -- Allow for strings, now it's ctype.
localelement_ct_id=tonumber(element_ct)
ifnotallowed_element_ct[element_ct_id] then
error('element type "'..tostring(element_ct)..'" not allowed')
end
ifalg_element_ct[element_ct_id] then
returnalg_element_ct[element_ct_id]
end
localis_diff_dn=element_ct==diff.dn
localarray_ct=new_array_ct(element_ct, is_diff_dnandelement_ct)
localfunctionvec(n)
ifn<0then
error('length '..n..' is negative')
end
returnarray_alloc(array_ct, n, n, 1)
end
localfunctionmat(r, c)
ifr<0then
error('number of rows '..r..' is negative')
end
ifc<0then
error('number of columns '..c..' is negative')
end
returnarray_alloc(array_ct, r*c, r, c)
end
localfunctiontovec(t)
iftype(t) ~='table' then
error('table argument expected, got '..type(t))
end
localn=#t
locala=vec(n)
fori=1,ndo
a[i] =t[i]
end
returna
end
localfunctiontomat(t)
iftype(t) ~='table' then
error('table argument expected, got '..type(t))
end
localr, c=#t, #t>0and#t[1] or0
locala=mat(r, c)
fori=1,rdo
forj=1,cdo
if#t[i] ~=cthen
error('all rows of the table must have the same number of elements')
end
a[{i, j}] =t[i][j]
end
end
returna
end
localalg= {
vec=vec,
mat=mat,
tovec=tovec,
tomat=tomat,
arrayct=array_ct,
}
alg_element_ct[element_ct_id] =alg
returnalg_element_ct[element_ct_id]
end
--------------------------------------------------------------------------------
local__code=template([[
return {
| for NEL = 1,10 do
dim_elw_${NEL} = function(${R('__x@', 1, NEL)})
local n, r, c = __x1._n, __x1._r, __x1._c
| for N=2,NEL do
if ${R('__x@._r ~= r or __x@._c ~= c', 2, N, ' or ')} then
error('incompatible dimensions in element-wise operation')
end
| end
return n, r, c
end,
| end
}
]])({ R=rep })
local__=assert(loadstring(__code))()
__.array_alloc=array_alloc
__.stack_array=stack_array
__.stack_clear=stack_clear
__.mul=__mul
__.pow=__pow
__.dim_pow_1=dimensions_pow_check_1
__.dim_pow_2=dimensions_pow_check_2
__.dim_mul_2=dimensions_mul_check_2
__.dim_mul_3=dimensions_mul_check_3
--------------------------------------------------------------------------------
localalg_double=alg_typeof('double')
return {
typeof=alg_typeof,
vec=alg_double.vec,
mat=alg_double.mat,
tovec=alg_double.tovec,
tomat=alg_double.tomat,
arrayct=alg_double.arrayct,
join=join,
mul=mul,
pow=pow,
sum=sum,
prod=prod,
trace=trace,
__=__,
}