σμimplied vol · KKmax(S−K,0)udβρᵢⱼfat tailsPnL · drawdownyield · TdSₜ = μSₜ dt + σSₜ dWₜC = S·N(d₁) − K·e⁻ʳᵀ·N(d₂)σₚ² = wᵀΣwd₁ = [ln(S/K) + (r + σ²⁄2)T] ⁄ σ√T∂V/∂t + ½σ²S²·∂²V/∂S² + rS·∂V/∂S − rV = 0Sharpe = (Rₚ − R_f) ⁄ σₚVaR₉₉ = μ − 2.33σρ = Cov(X,Y) ⁄ σₓσᵧE[Rₚ] = Σ wᵢ·E[Rᵢ]φ(x) = e^(−x²/2) ⁄ √2πE[Rᵢ] = R_f + βᵢ(E[Rₘ] − R_f)dXₜ = θ(μ − Xₜ)dt + σ dWₜσ²ₜ = ω + α·ε²ₜ₋₁ + β·σ²ₜ₋₁C − P = S − K·e⁻ʳᵀΔ = ∂V/∂S Γ = ∂²V/∂S²p = (e^(rΔt) − d) ⁄ (u − d)rₜ = ln(Pₜ ⁄ Pₜ₋₁)E[Xₜ₊₁ | ℱₜ] = Xₜf* = (bp − q) ⁄ bz = (x − μ) ⁄ σP(N=k) = λᵏe^(−λ) ⁄ k!Θ = −∂V/∂Tν = S·φ(d₁)·√Tmin wᵀΣw s.t. wᵀμ = μ*∫Σ∂∞λ
uantCraft AcademyRoadmapsSkills
Ctrl K
AO
+1.2k Learners
LoginJoin ↗
RoadmapsSkills
AO
+1.2k Learners
Login
  • English
  • Français
  • Español
  • العربية
  • Português
  • Deutsch
  • 日本語
  • 中文
σμimplied vol · KKmax(S−K,0)udβρᵢⱼfat tailsPnL · drawdownyield · TdSₜ = μSₜ dt + σSₜ dWₜC = S·N(d₁) − K·e⁻ʳᵀ·N(d₂)σₚ² = wᵀΣwd₁ = [ln(S/K) + (r + σ²⁄2)T] ⁄ σ√T∂V/∂t + ½σ²S²·∂²V/∂S² + rS·∂V/∂S − rV = 0Sharpe = (Rₚ − R_f) ⁄ σₚVaR₉₉ = μ − 2.33σρ = Cov(X,Y) ⁄ σₓσᵧE[Rₚ] = Σ wᵢ·E[Rᵢ]φ(x) = e^(−x²/2) ⁄ √2πE[Rᵢ] = R_f + βᵢ(E[Rₘ] − R_f)dXₜ = θ(μ − Xₜ)dt + σ dWₜσ²ₜ = ω + α·ε²ₜ₋₁ + β·σ²ₜ₋₁C − P = S − K·e⁻ʳᵀΔ = ∂V/∂S Γ = ∂²V/∂S²p = (e^(rΔt) − d) ⁄ (u − d)rₜ = ln(Pₜ ⁄ Pₜ₋₁)E[Xₜ₊₁ | ℱₜ] = Xₜf* = (bp − q) ⁄ bz = (x − μ) ⁄ σP(N=k) = λᵏe^(−λ) ⁄ k!Θ = −∂V/∂Tν = S·φ(d₁)·√Tmin wᵀΣw s.t. wᵀμ = μ*∫Σ∂∞λ
uantCraft AcademyRoadmapsSkills
Ctrl K
AO
+1.2k Learners
LoginJoin ↗
RoadmapsSkills
AO
+1.2k Learners
Login
  • English
  • Français
  • Español
  • العربية
  • Português
  • Deutsch
  • 日本語
  • 中文
BLAS and LAPACK skill›Module 2 · Solving and decomposing›Topic 2.2·~45 minAdvanced

Calling LAPACK routines and reading info

Skill positionModule 2 of 4 · Topic 2 of 3
2.2 Calling LAPACK routines and reading info
—Lab score— / 100Total XP—Streak—
Lecture0% read

4 min readCode examples: 4

  1. 01The idea in plain words
  2. 02A duplicated stock
  3. 03Pivots count from 1
  4. 04Factor once, solve many times
  5. 05Workspace and the lower triangle
  6. 06What the tasks ask

Add the same stock twice to a portfolio and its covariance matrix is singular. LAPACK does not raise an error: it returns the answer anyway, together with the number 6. What does that number say, and who has to read it?

01

The idea in plain words

Where we are. In the last topic you wrote the recipes behind LU, least squares and eigenvalues. This topic is about calling such routines the way production code does, and it is mostly about conventions that look odd to a Python programmer because LAPACK was written in Fortran in the 1970s and kept its habits. The next topic asks the question those habits cannot answer: when is a returned answer actually good?

Four habits matter. First, a routine returns an integer info instead of raising an exception. Second, counting starts at 1, as in Fortran: the pivot row numbers it returns are 1-based. Third, some routines need a work area whose size you must request, and refuse to run if it is too small. Fourth, a routine reads only the part of the matrix it needs: dsyev looks at the lower triangle and trusts that the upper one matches.

  • infoWhat it tells you
  • info == 0The call rannot a promise the answer is good
  • info < 0Argument number -info was illegala bug in the caller
  • info > 0The numbers caused troublesingular matrix or no convergence
02

A duplicated stock

Here cov is the 5 by 5 covariance matrix of the stocks from the earlier topics. We add JPM a second time as a sixth column. Its twin is perfectly correlated with it, so the six rows cannot all be independent and dgetrf stops at the sixth pivot.

main.pyPython
# JPM twice: the sixth column repeats the secondtwin = covariance([row + [row[1]] for row in X])lu, piv, info = dgetrf(Blas(), twin)print("info:", info, "| pivots (1-based):", piv)1try:    check_info("dgetrf", info)except LinAlgError as error:    print("LinAlgError:", error)
info: 6 | pivots (1-based): [1, 2, 3, 4, 5, 6]
LinAlgError: dgetrf: U(6,6) is exactly zero, the matrix is singular
  1. 1info 6 says: the sixth diagonal entry of U is exactly zero.
info 0 does not mean the answer is good

LAPACK reports a zero pivot only when it is exactly zero. If the sixth column is the sum of the first two instead of a copy, rounding leaves a pivot of about −5·10⁻²⁰, info is 0, and the solution is meaningless. The next topic measures how much to trust a solution.

03

Pivots count from 1

piv[k] is the row swapped with row k + 1, and the swaps happen one after another, so the list is not itself a permutation. piv_to_perm replays the swaps to give the order of the rows. To see real swaps we hand over the rows in reverse order; the pivot search puts the largest entry of each column back on top.

main.pyPython
# Hand over the rows in reverse order so that the pivot search has work to dobackwards = [cov[i] for i in (4, 3, 2, 1, 0)]lu, piv, info = dgetrf(Blas(), backwards)print("info", info, "| piv (1-based):", piv)print("perm (0-based):", piv_to_perm(piv))1
info 0 | piv (1-based): [5, 4, 3, 4, 5]
perm (0-based): [4, 3, 2, 1, 0]
  1. 1The rows come back in the order 4, 3, 2, 1, 0: row 0 of P A is row 4 of what we handed over, and so on.
04

Factor once, solve many times

dgesv is convenient, but it factors on every call. When the same matrix meets several right-hand sides, call dgetrf once and dgetrs for each one. Here two questions are put to the same covariance matrix: the minimum-variance mix, and the mix that hedges a position in the first stock.

main.pyPython
# Two right-hand sides against one covariance matrix: factor once with solve_manyquestions = [[1.0] * 5, [1.0, 0.0, 0.0, 0.0, 0.0]]shared = Blas()answers = solve_many(shared, cov, questions)print("solve_many: flops", shared.flops, "words", shared.words)separate = Blas()for b in questions:    dgesv(separate, cov, b)print("two dgesv calls: flops", separate.flops, "words", separate.words)1print("same first answer from dgesv?", all(abs(x - y) < 1e-6 * abs(y) for x, y in zip(answers[0], dgesv(Blas(), cov, questions[0])[2])))
solve_many: flops 160 words 120
two dgesv calls: flops 230 words 170
same first answer from dgesv? True
  1. 1Factor once (70 flops) plus two solves (45 each) is 160; calling dgesv twice factors twice and costs 230.
05

Workspace and the lower triangle

main.pyPython
# dsyev needs a work area; ask how big, and see what happens when it is too smallprint("minimum lwork for 5 stocks:", lwork_dsyev(5))w, v, info = dsyev(Blas(), cov, 4)print("lwork 4 ->", "info", info)1w, v = eigh(Blas(), cov)print("eigh ->", [round(x * 1e4, 2) for x in w])messy = [[row[j] if j <= i else 99.0 for j in range(5)] for i, row in enumerate(cov)]print("garbage above the diagonal, same eigenvalues?", [round(x * 1e4, 2) for x in eigh(Blas(), messy)[0]] == [round(x * 1e4, 2) for x in w])
minimum lwork for 5 stocks: 14
lwork 4 -> info -8
eigh -> [0.81, 1.6, 1.94, 2.51, 2.99]
garbage above the diagonal, same eigenvalues? True
  1. 1info −8 says argument 8, the workspace size, was illegal: a bug in the caller, not in the numbers.
06

What the tasks ask

  1. 1
    `check_info`Turn info into the exception Python code expects: nothing for 0, ValueError for a negative value, LinAlgError for a positive one, with the exact messages in the README.
  2. 2
    `piv_to_perm`Replay the 1-based swaps on [0, 1, ..., n-1].
  3. 3
    `solve_many` and `eigh`Two wrappers in the style of production code: one factorisation for many solves, and a workspace query before the eigen call, each call followed by check_info.

Key takeaways

  • Read info after every call LAPACK reports trouble only through info. Skipping the check turns a bug into a wrong answer.
  • Mind the conventions Pivots count from 1, workspace sizes are requested, and some routines read only one triangle. None of these raises an error when you get it wrong.
  • Factor once Use dgetrf plus dgetrs when a matrix meets many right-hand sides. Next: when is a solution that came back with info 0 still wrong?
Quick check
dgetrf returns info = 3 for a 6 by 6 covariance matrix. What does it tell you?
Pick an answer.

Lab · what's graded

4 tasks · 100 pts
  • Read the code with check_info25 pts
  • Read 1-based pivots with piv_to_perm25 pts
  • Factor once with solve_many25 pts
  • Ask for workspace with eigh25 pts
Explorer · lab-5-1
▾ lab-5-1
…
bash · in-browser
learner@quantcraft:~/lab-5-1$
Python not loaded yetPythonLn 1, Col 1Spaces: 4UTF-8

Reset this topic?

Everything in lab-5-1 goes back to the starter files and the terminal is cleared. Your current solution will be lost — this can't be undone.

Will be reset
  • main.py → starter code
  • Terminal history and test output
  • Unsubmitted changes
Will be kept
  • Best lab score
  • Your XP and streak
  • Lecture progress and notes