forked from statsmodels/statsmodels
-
Notifications
You must be signed in to change notification settings - Fork 0
/
mat2nparray.ado
50 lines (46 loc) · 1.42 KB
/
mat2nparray.ado
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
capture program drop mat2array
program define mat2array
version 11.2
syntax namelist(min=1), SAVing(str) [ Format(str) APPend REPlace ]
if "`format'"=="" local format "%16.0g"
local saving: subinstr local saving "." ".", count(local ext)
if !`ext' local saving "`saving'.py"
tempname myfile
file open `myfile' using "`saving'", write text `append' `replace'
file write `myfile' "import numpy as np" _n _n
foreach mat of local namelist {
mkarray `mat' `myfile' `format'
}
file close `myfile'
end
capture program drop mkarray
program define mkarray
args mat myfile fmt
local nrows = rowsof(`mat')
local ncols = colsof(`mat')
local i 1
local j 1
file write `myfile' "`mat' = np.array(["
local justifyn = length("`mat' = np.array([")
forvalues i=1/`nrows' {
forvalues j = 1/`ncols' {
if `i' > 1 | `j' > 1 { // then we need to indent
forvalues k=1/`justifyn' {
file write `myfile' " "
}
}
if `i' < `nrows' | `j' < `ncols' {
file write `myfile' `fmt' (`mat'[`i',`j']) ", " _n
}
else {
file write `myfile' `fmt' (`mat'[`i',`j'])
}
}
}
if `nrows' == 1 | `ncols' == 1 {
file write `myfile' "])" _n _n
}
else {
file write `myfile' "]).reshape(`nrows',`ncols')" _n _n
}
end