Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
169 changes: 168 additions & 1 deletion LAPACK/audit.py
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,8 @@
DP (d/z): h >= 1e-10 required, h >= 1e-8 recommended
4) CODE: Every test must print a numerical error value
5) CODE: Static signature audit — argument count, ndir placement,
cross-precision consistency, test CALL vs SUBROUTINE match
cross-precision consistency, type consistency, companion placement,
derivative vs primal arg count, test CALL vs SUBROUTINE match
6) CODE: Eigval prechecks — generalized eigenvalue tests have well-separation
7) CODE: z-overwrite — eigenvector tests save z before FD calls
8) CODE: COMPZ usage — tridiagonal tests with COMPZ='V' must initialize Z
Expand Down Expand Up @@ -375,6 +376,31 @@ def _preprocess_fortran(filepath):
return '\n'.join(cleaned).replace('&', ' ')


def _extract_declarations(filepath):
"""Extract variable declarations from a Fortran source file.
Returns {varname_lower: type_str} where type_str is one of
'INTEGER', 'DOUBLE PRECISION', 'REAL', 'COMPLEX*16', 'COMPLEX',
'CHARACTER', 'LOGICAL'."""
content = _preprocess_fortran(filepath)
decls = {}
type_pat = re.compile(
r'(?i)^\s*(DOUBLE\s+PRECISION|COMPLEX\s*\*\s*16|COMPLEX|REAL|INTEGER|'
r'CHARACTER|LOGICAL)\b'
r'(?:\s*\([^)]*\))?'
r'(?:\s*,\s*(?:INTENT|ALLOCATABLE|PARAMETER|DIMENSION|EXTERNAL)[^:]*)*'
r'\s*::\s*(.+)',
re.MULTILINE)
for m in type_pat.finditer(content):
type_str = re.sub(r'\s+', ' ', m.group(1)).strip().upper()
if type_str == 'COMPLEX * 16':
type_str = 'COMPLEX*16'
var_list = m.group(2)
for var in re.findall(r'(\w+)', var_list.split('!')[0]):
if var.upper() not in ('IN', 'OUT', 'INOUT'):
decls[var.lower()] = type_str
return decls


def _extract_all_sigs(filepath):
"""Extract all SUBROUTINE name + arg-list pairs from a Fortran file.
Returns [(name_lower, [arg_lower, ...])]."""
Expand Down Expand Up @@ -443,6 +469,10 @@ def audit_signatures():
S1. _dv/_bv must not have fewer args than _d/_b
S2. _dv/_bv must have 'ndir'/'nvar' somewhere in arg list
S3. Cross-precision consistency (d<->s, z<->c arg counts match)
S4. ndir/nvar must be LAST argument in _dv/_bv
S5. Type consistency (d-prefix → DOUBLE PRECISION, s → REAL, etc.)
S6. Companion placement (xd/xb immediately follows x)
S7. _d/_b must have more args than primal
T1. CALL arg count in test files matches SUBROUTINE declaration
"""
print("\n=== CODE: Signature Audit (static) ===")
Expand Down Expand Up @@ -537,6 +567,143 @@ def audit_signatures():
f"Cross-precision mismatch ({family} {base}_{mode}): {details}")
n_issues += 1

# --- S4: ndir/nvar must be last (or near-last before info/work) ---
# Some routines append mode-specific workspace after ndir; allow that.
s4_tail_ok = {'info', 'work', 'lwork', 'rwork', 'lrwork', 'iwork',
'liwork'}
for name in sorted(sigs):
args = sigs[name]
if (name.endswith('_dv') or name.endswith('_bv')) and args:
ndir_pos = None
for i, a in enumerate(args):
if a in ('ndir', 'nvar'):
ndir_pos = i
break
if ndir_pos is None:
continue # Already caught by S2
# Everything after ndir must be in s4_tail_ok
tail = args[ndir_pos + 1:]
bad_tail = [a for a in tail if a not in s4_tail_ok]
if bad_tail:
issue("SIGNATURE", f"src/{name}.f90", None,
f"{name}: unexpected args after ndir/nvar: "
f"{', '.join(bad_tail)}")
n_issues += 1

# --- S5: Type consistency (precision prefix → Fortran type) ---
# d-prefix → arrays should be DOUBLE PRECISION
# s-prefix → arrays should be REAL
# z-prefix → arrays should be COMPLEX*16
# c-prefix → arrays should be COMPLEX
# Workspace (rwork/rworkd) in complex routines can be real-typed.
s5_exclude_vars = {'info', 'lwork', 'lrwork', 'liwork', 'lwopt',
'info_sv', 'info_ev', 'info_fd', 'lsame',
'm', 'n', 'k', 'i', 'j', 'lda', 'ldu', 'ldvt',
'ldvl', 'ldvr', 'ldz', 'ldb', 'ldq', 'nrhs',
'kl', 'ku', 'kd', 'il', 'iu', 'ndir', 'nvar',
'idir', 'itype', 'nev', 'ncv', 'nfound',
'wp', 'den', 'eps_sep', 'smax2', 'sinvj',
'jobu', 'jobvt', 'jobz', 'jobvl', 'jobvr',
'uplo', 'range', 'sort', 'compz', 'sense',
'barone', 'brone', 'trans', 'diag', 'fact',
'equed', 'vl_bound', 'vu_bound', 'abstol'}
expected_types = {'d': 'DOUBLE PRECISION', 's': 'REAL',
'z': 'COMPLEX*16', 'c': 'COMPLEX'}
for sf in src_files:
base = os.path.basename(sf).replace('.f90', '').lower()
if not base or base[0] not in expected_types:
continue
prec = base[0]
exp_type = expected_types[prec]
decls = _extract_declarations(sf)
for var, vtype in decls.items():
if var in s5_exclude_vars:
continue
if vtype in ('INTEGER', 'LOGICAL', 'CHARACTER'):
continue
# rwork/rworkd/iwork/iworkd are real-typed in complex routines
if prec in ('z', 'c') and re.match(r'^(rwork|iwork)', var):
continue
# s() and sd() store real singular values in complex SVD
if prec in ('z', 'c') and var in ('s', 'sd', 'den', 'eps_sep',
'smax2', 'sinvj'):
continue
if vtype != exp_type:
# Allow DOUBLE PRECISION for DP work-precision constants in
# complex*16 routines, and REAL for SP constants in complex
if prec == 'z' and vtype == 'DOUBLE PRECISION':
continue
if prec == 'c' and vtype == 'REAL':
continue
# Real reverse-mode _b/_bv routines use complex arithmetic
# internally for eigenvalue/Schur adjoint (Giles algorithm)
if prec in ('d', 's') and '_b' in base:
if prec == 'd' and vtype == 'COMPLEX*16':
continue
if prec == 's' and vtype == 'COMPLEX':
continue
issue("SIGNATURE", sf, None,
f"{base}: variable '{var}' declared as {vtype}, "
f"expected {exp_type} for {prec}-prefix routine")
n_issues += 1

# --- S6: Companion placement (xd/xb follows x in arg list) ---
# In _d routines, for each arg ending in 'd' (companion), verify the
# primal (without the 'd' suffix) appears earlier in the arg list.
# Similarly for _b routines with 'b' suffix.
# Only check args where stripping the suffix gives a name that is also
# a declared argument — this avoids false positives on compound names
# like 'rcond', 'equed', 'ldb' (which are NOT companions).
s6_skip_args = {'workd', 'rworkd', 'iworkd', 'ndir', 'nvar',
'lworkd', 'lrworkd', 'liworkd', 'info'}
for name in sorted(sigs):
args = sigs[name]
m_name = re.match(r'^([sdcz])(\w+?)_(d|b|dv|bv)$', name)
if not m_name:
continue
mode = m_name.group(3)
if mode in ('d', 'dv'):
suffix = 'd'
elif mode in ('b', 'bv'):
suffix = 'b'
else:
continue
arg_set = set(args)
for idx, arg in enumerate(args):
if arg in s6_skip_args:
continue
if not arg.endswith(suffix) or len(arg) <= len(suffix):
continue
primal_name = arg[:-len(suffix)]
# Only treat as companion if the primal is also an argument
if primal_name not in arg_set:
continue
# Now verify the primal appears before the companion
preceding = args[:idx]
if primal_name not in preceding:
issue("SIGNATURE", f"src/{name}.f90", None,
f"{name}: companion '{arg}' appears before its "
f"primal '{primal_name}' in arg list")
n_issues += 1

# --- S7: _d/_b vs primal arg count (informational) ---
# Many derivative routines simplify the primal interface by not exposing
# all options (condition numbers, error bounds, etc.), so fewer args is
# normal. We only flag routines with EXACTLY the same arg count as the
# primal, since that likely means no companion args were added at all.
n_s7_info = 0
for name in sorted(sigs):
m_name = re.match(r'^([sdcz])(\w+?)_(d|b)$', name)
if not m_name:
continue
prec, base, mode = m_name.group(1), m_name.group(2), m_name.group(3)
primal = prec + base
if primal in primal_sigs:
n_deriv = len(sigs[name])
n_primal = len(primal_sigs[primal])
if n_deriv <= n_primal:
n_s7_info += 1

# --- T1: CALL arg count in tests vs SUBROUTINE declaration ---
test_files = sorted(glob.glob("test/test_*.f90"))
n_calls_checked = 0
Expand Down
135 changes: 67 additions & 68 deletions LAPACK/src/cgees_b.f90
Original file line number Diff line number Diff line change
Expand Up @@ -11,99 +11,98 @@ SUBROUTINE CGEES_B(jobvs, sort, select, n, a, ad, lda, sdim, w, wd, vs, vsd, ldv
LOGICAL :: bwork(*)
LOGICAL, EXTERNAL :: select

COMPLEX, ALLOCATABLE :: ac(:, :), adb(:, :), wtmp(:), wcd(:), vlc(:, :), vlcd(:, :), wk(:)
REAL, ALLOCATABLE :: rwk(:)
INTEGER :: i, j, ii, jj, info_d
COMPLEX, PARAMETER :: CZERO = (0.0E0, 0.0E0)
COMPLEX, PARAMETER :: CONE = (1.0E0, 0.0E0)
REAL, PARAMETER :: EIG_TOL = 1.0E-4

COMPLEX, ALLOCATABLE :: T(:,:), VS_local(:,:), VL(:,:), VR(:,:)
COMPLEX, ALLOCATABLE :: G_bar(:,:), temp(:,:), P_bar(:,:)
COMPLEX, ALLOCATABLE :: eig_work(:)
REAL, ALLOCATABLE :: rwork_trevc(:)
COMPLEX :: d_i, alpha_i
REAL :: trsyl_scale, diff_mag
INTEGER :: i, j, k, m_eig, info2
LOGICAL :: LSAME, use_vs
COMPLEX :: ci
REAL :: vjp_re, vjp_im
EXTERNAL :: CGEES, CGEES_D, LSAME
EXTERNAL :: CGEES, LSAME, CGEMM, CTREVC, CTRSYL

info = 0
ci = CMPLX(0.0E0, 1.0E0)
use_vs = LSAME(jobvs, 'V')

ALLOCATE(ac(n, n), adb(n, n), wtmp(n), wcd(n), vlc(n, n), vlcd(n, n), wk(lwork), rwk(n))
IF (n <= 0) THEN
sdim = 0
RETURN
END IF

ALLOCATE(T(n,n), VS_local(n,n), VL(n,n), VR(n,n), G_bar(n,n), temp(n,n), P_bar(n,n), eig_work(2*n), rwork_trevc(n))

DO j = 1, n
DO i = 1, n
ac(i, j) = a(i, j)
T(i,j) = a(i,j)
END DO
END DO

CALL CGEES(jobvs, sort, select, n, ac, n, sdim, w, vs, ldvs, wk, lwork, rwk, bwork, info)
CALL CGEES('V', sort, select, n, T, n, sdim, w, VS_local, n, work, lwork, rwork, bwork, info)
IF (info /= 0) THEN
DEALLOCATE(ac, adb, wtmp, wcd, vlc, vlcd, wk, rwk)
DEALLOCATE(T, VS_local, VL, VR, G_bar, temp, P_bar, eig_work, rwork_trevc)
RETURN
END IF

DO j = 1, n
DO i = 1, n
ad(i, j) = CMPLX(0.0E0, 0.0E0)
END DO
END DO

DO jj = 1, n
DO ii = 1, n
DO j = 1, n
DO i = 1, n
ac(i, j) = a(i, j)
adb(i, j) = CMPLX(0.0E0, 0.0E0)
END DO
IF (use_vs) THEN
DO j = 1, n
DO i = 1, n
vs(i,j) = VS_local(i,j)
END DO
adb(ii, jj) = CMPLX(1.0E0, 0.0E0)
END DO
END IF

CALL CGEES_D(jobvs, sort, select, n, ac, adb, n, sdim, wtmp, wcd, vlc, vlcd, n, &
wk, workd, lwork, rwk, rworkd, bwork, info_d)
IF (info_d /= 0) THEN
info = info_d
DEALLOCATE(ac, adb, wtmp, wcd, vlc, vlcd, wk, rwk)
DO i = 1, n-1
DO j = i+1, n
diff_mag = ABS(w(i) - w(j))
IF (diff_mag < EIG_TOL) THEN
info = -200
DEALLOCATE(T, VS_local, VL, VR, G_bar, temp, P_bar, eig_work, rwork_trevc)
RETURN
END IF
END DO
END DO

vjp_re = 0.0E0
DO i = 1, n
vjp_re = vjp_re + REAL(CONJG(wd(i)) * wcd(i))
END DO
IF (use_vs) THEN
DO j = 1, n
DO i = 1, n
vjp_re = vjp_re + REAL(CONJG(vsd(i, j)) * vlcd(i, j))
END DO
END DO
END IF
CALL CTREVC('B', 'A', bwork, n, T, n, VL, n, VR, n, n, m_eig, eig_work, rwork_trevc, info2)

DO j = 1, n
DO i = 1, n
ac(i, j) = a(i, j)
adb(i, j) = CMPLX(0.0E0, 0.0E0)
END DO
END DO
adb(ii, jj) = ci
DO i = 1, n
d_i = CZERO
DO k = 1, n
d_i = d_i + CONJG(VL(k,i)) * VR(k,i)
END DO
alpha_i = wd(i) / CONJG(d_i)
DO k = 1, n
VL(k,i) = alpha_i * VL(k,i)
END DO
END DO
CALL CGEMM('N', 'C', n, n, n, CONE, VL, n, VR, n, CZERO, G_bar, n)

CALL CGEES_D(jobvs, sort, select, n, ac, adb, n, sdim, wtmp, wcd, vlc, vlcd, n, &
wk, workd, lwork, rwk, rworkd, bwork, info_d)
IF (info_d /= 0) THEN
info = info_d
DEALLOCATE(ac, adb, wtmp, wcd, vlc, vlcd, wk, rwk)
RETURN
END IF
IF (use_vs) THEN
CALL CGEMM('C', 'N', n, n, n, CONE, VS_local, n, vsd, ldvs, CZERO, P_bar, n)

vjp_im = 0.0E0
DO i = 1, n
vjp_im = vjp_im + REAL(CONJG(wd(i)) * wcd(i))
DO j = 1, n
DO i = 1, j
temp(i,j) = CZERO
END DO
IF (use_vs) THEN
DO j = 1, n
DO i = 1, n
vjp_im = vjp_im + REAL(CONJG(vsd(i, j)) * vlcd(i, j))
END DO
END DO
END IF
DO i = j+1, n
temp(i,j) = P_bar(i,j) - CONJG(P_bar(j,i))
END DO
END DO

CALL CTRSYL('C', 'C', -1, n, n, T, n, T, n, temp, n, trsyl_scale, info2)

ad(ii, jj) = CMPLX(vjp_re, vjp_im)
DO j = 1, n
DO i = j+1, n
G_bar(i,j) = G_bar(i,j) - temp(i,j) / trsyl_scale
END DO
END DO
END DO
END IF

CALL CGEMM('N', 'N', n, n, n, CONE, VS_local, n, G_bar, n, CZERO, temp, n)
CALL CGEMM('N', 'C', n, n, n, CONE, temp, n, VS_local, n, CZERO, ad, lda)

DEALLOCATE(ac, adb, wtmp, wcd, vlc, vlcd, wk, rwk)
DEALLOCATE(T, VS_local, VL, VR, G_bar, temp, P_bar, eig_work, rwork_trevc)
END SUBROUTINE CGEES_B
Loading
Loading