File: equation.py

package info (click to toggle)
lapackpp 2024.10.26-1
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid, trixie
  • size: 6,500 kB
  • sloc: cpp: 80,181; ansic: 27,660; python: 4,838; xml: 182; perl: 99; makefile: 53; sh: 23
file content (242 lines) | stat: -rwxr-xr-x 7,019 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
#!/usr/bin/env python3
#
# Attempts to find equations in Doxygen code and replace them with $...$.
# For instance:
#     /// solve A * X = B^H for matrices A, X, B.
# becomes
#     /// solve $A X = B^H$ for matrices A, X, B.
# However, patterns are heuristic and incomplete, so mistakes occur.
# Use with caution.

from __future__ import print_function

import sys
import re
import os

debug = False

operators = {
    '<=': r'\le',
    '>=': r'\ge',
}

src = '../gen'
assert( os.path.exists( src ))

dst = '../eqn'
if (not os.path.exists( dst )):
    os.mkdir( dst )

def equation( line, subexpr=False ):
    if (debug):
        print( 'equation:', line + '; subexpr:', subexpr )

    if (subexpr):
        eqn = ''
    else:
        eqn = r'$'
    begin = True
    while (line):
        # no space after $ at beginning;
        # after that, add a space before most tokens (except ^T and punctuation)
        if (begin):
            begin = False
            space = ''
        else:
            space = ' '

        if (debug):
            print( 'eqn: <' + eqn + '> line: <' + line + '>' )

        # space
        s = re.search( r'^( +)(.*)', line )
        if (s):
            line = s.group(2)
            continue

        # variable
        s = re.search( r'^([a-zA-Z]|VT)(\d*)\b(.*)', line )
        if (s):
            eqn += space + s.group(1)
            if (s.group(2)):
                eqn += '_{' + s.group(2) + '}'
            line = s.group(3)
            continue

        # number
        s = re.search( r'^(\d+)\b(.*)', line )
        if (s):
            eqn += space + s.group(1)
            line = s.group(2)
            continue

        # binary operator * becomes implicit
        s = re.search( r'^(\*)(.*)', line )
        if (s):
            line = s.group(2)
            continue

        # explicit binary operators <= >=
        s = re.search( r'^(<=|>=)(.*)', line )
        if (s):
            eqn += space + operators[ s.group(1) ]
            line = s.group(2)
            continue

        # explicit binary operators = < > + - /
        s = re.search( r'^([=<>\+\-\/])(.*)', line )
        if (s):
            eqn += space + s.group(1)
            line = s.group(2)
            continue

        # exponents, transpose
        s = re.search( r'^(\^[HT2-9])\b(.*)', line )
        if (s):
            # don't print space
            eqn += s.group(1)
            line = s.group(2)
            continue

        # Greek, functions
        s = re.search( r'^(alpha|beta|lambda|Lambda|mu|sigma|Sigma|tau|sqrt|min|max)\b(.*)', line )
        if (s):
            eqn += space + '\\' + s.group(1)
            line = s.group(2)
            continue

        # capitalized Greek, functions
        s = re.search( r'^(MIN|MAX)\b(.*)', line )
        if (s):
            eqn += space + '\\' + s.group(1).lower()
            line = s.group(2)
            continue

        # norm
        # todo: use \lVert?
        s = re.search( r'^norm\((.*)', line )
        if (s):
            (expr, line) = equation( s.group(1), True )
            eqn += space + r'|| ' + expr + ' ||'
            continue

        # abs
        # todo: use \lvert?
        s = re.search( r'^abs\((.*)', line )
        if (s):
            (expr, line) = equation( s.group(1), True )
            eqn += space + r'| ' + expr + ' |'
            continue

        # inverse
        s = re.search( r'^inv\((.*)', line )
        if (s):
            (expr, line) = equation( s.group(1), True )
            if (re.search( '^\w+$', expr )):
                # safe to skip parens
                eqn += space + expr + '^{-1}'
            else:
                eqn += space + '(' + expr + ')^{-1}'
            continue

        # non-Latex functions
        s = re.search( r'^(diag)\((.*)', line )
        if (s):
            (expr, line) = equation( s.group(2), True )
            eqn += space + r'\; \text{' + s.group(1) + '}(' + expr + ') \; '
            continue

        # open parens
        s = re.search( r'^\((.*)', line )
        if (s):
            (expr, line) = equation( s.group(1), True )
            if (expr):
                eqn += space + '(' + expr + ')'
            else:
                # sub-expr didn't parse, so put ( back on line
                line = '(' + line
                break # done
            continue

        # close parens
        if (subexpr):
            s = re.search( r'^\)(.*)', line )
            if (s):
                # finished subexpression; don't include ) in eqn
                line = s.group(1)
                if (debug):
                    print( 'finish subexpr:', eqn, '\nline:', line )
                break

        # ellipsis
        s = re.search( r'^\. ?\. ?\.(.*)', line )
        if (s):
            eqn += space + r'\dots'
            line = s.group(1)
            continue

        # punctuation
        ##s = re.search( r'^([.,;:])(.*)', line )
        s = re.search( r'^([,])(.*)', line )
        if (s):
            # don't print space
            eqn += s.group(1)
            line = s.group(2)
            continue

        # otherwise done
        break
    # end
    if (not subexpr):
        eqn += '$'
        # add space after $,
        # unless there's punctuation or already space such as \n in line.
        s = re.search( r'^[^.,;:\s]', line )
        if (s):
            eqn += ' '
    return (eqn, line)
# end

def process( arg ):
    filename = arg + '.cc'
    f_out = os.path.join( dst, filename )
    f_in  = os.path.join( src, filename )
    print( 'reading ' + f_in + '\nwriting ' + f_out )
    f_out = open( f_out, 'w' )
    f_in  = open( f_in )
    for line in f_in:
        s = re.search( r'^///', line )
        if (s):
            rest = line.rstrip()
            line = ''
            while (rest):
                #                                variable        Greek                                            operator          | functions
                s = re.search( r'^(.*?)\b((?: (?:[A-Z]\d* | VT | alpha | beta | lambda | mu | sigma | tau) \s* (?:=|\^|\+|\-|\*|\/) | norm\( | inv\( | diag\( | sqrt\( ).*)',
                               rest, re.X )
                if (s):
                    line += s.group(1)
                    (eqn, rest) = equation( s.group(2) )
                    if (debug):
                        print( 'eqn: ' + eqn + ', rest: ' + rest )
                    eqn = re.sub( r',\$( *)$', r'$,\1', eqn )  # move trailing punctuation (only commas) outside
                    line += eqn
                else:
                    break
                # end
            # end
            line += rest + '\n'
            # if the entire line is an indented equation, make it \[ ... \]
            # and put punctuation inside.
            line = re.sub( r'^///     \$(.*)\$([.,;:]?)$', r'///     \[ \1\2 \]', line )
        # end
        print( line, file=f_out, end='' )
    # end
# end

for arg in sys.argv[1:]:
    if (arg == '-d'):
        debug = True
    else:
        process( arg )
# end