This code snippet adds a convergence-order column to a pandas dataframe, by providing the name of the values column, and the deltas (h-s) column. The convergence column is appended to the values column.
The rate of convergence of a discretization method is defined as
\begin{equation} c = \frac {log( \frac{e_2}{e_1} )} {log( \frac{h_2}{h_1} )} \end{equation}
where $$ e_1 $$ , $$e_2$$ are the respective old and new error, and $$h_1$$, $$h_2$$ are the respective coarser and finer discretization step.
import pandas as pd
from math import log, nan
def calc_convergences(values, deltas):
"""Compute a convergence rate for values as a function of deltas as
log(value1 / value2) / log(delta1 / delta2)."""
convergences = values.copy()
for i in range(len(values)-1):
v1 = values.iloc[i]
v2 = values.iloc[i+1]
h1 = deltas.iloc[i]
h2 = deltas.iloc[i+1]
convergences[i] = log(v1 / v2) / log(h1 / h2)
convergences.iloc[len(values)- 1] = nan
return convergences
def insert_convergences(valuesName, deltasName, dFrame):
"""Compute a convergence rate for values as a function of deltas as
log(value1 / value2) / log(delta1 / delta2). and insert them into dFrame."""
convs = calc_convergences(dFrame[valuesName], dFrame[deltasName])
fvcReconstructData.insert(dFrame.columns.get_loc(valuesName)+1, # Get the index of the values column and increment it.
"O(%s)" % valuesName, convs)