Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save bsilvereagle/e34b4168bfe73fdcbe5dfb619f3297b2 to your computer and use it in GitHub Desktop.
Save bsilvereagle/e34b4168bfe73fdcbe5dfb619f3297b2 to your computer and use it in GitHub Desktop.
Symbolic Uncertainty
"""
Copyright (c) <year> <copyright holders>
Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
"""
class UncertaintyPropagation:
def __init__(self, expr, local_dict=None, second_order=None, sensitivity=True):
if isinstance(expr, str):
self._expr = sympy.parse_expr(expr, local_dict=local_dict or sympy.abc._clash1)
else:
self._expr = expr
self._symbols = self._expr.free_symbols
self._u_symbols = [sympy.Symbol(f"u_{{{symbol}}}") for symbol in self._symbols]
self.u = 0
# Build up dict of uncertainty for each term in the expression
self.components = dict()
for u, s in zip(self._u_symbols, self._symbols):
self.components[u] = (u*sympy.diff(self._expr, s))**2
self.u += self.components[u]
# Build up dict of second order uncertainty terms (can be very expensive)
self.components_second = dict()
if second_order:
for u_i, s_i in zip(self._u_symbols, self._symbols):
for u_j, s_j in zip(self._u_symbols, self._symbols):
self.components_second.update({s_i : {s_j: self._second_order(self._expr, s_i, s_j, u_i, u_j)}})
self.u += self.components_second[s_i][s_j]
# Take the final sqrt to calculate uncertainty
self.u = sympy.sqrt(self.u)
# Calculate partial derivative of uncertainty with respect to all parameters
self.sensitivity = None
if sensitivity:
self.sensitivity = {s: sympy.diff(self.u, s) for s in self.u.free_symbols}
def __str__(self):
return str(self._expr)
def __repr__(self):
return sympy.srepr(self)
def _repr_latex_(self, printer=None):
return f"$${sympy.latex(self._expr)}$$"
@staticmethod
def _second_order(expr, i, j, ui, uj):
return (0.5*sympy.diff(expr, i, j)**2 + sympy.diff(expr, i)*sympy.diff(expr, i, j, j))*ui**2*uj**2
def evaluate(self, op):
"""Evaluate unceratinty and sensitivity at an operating point."""
return u.u.subs(op), {k: u.sensitivity[k].subs(op) for k in u.sensitivity.keys()}
def gen_op(self):
"""Generate a string to be printed to fill in the operating points."""
result = "op = {\n"
for key in self.sensitivity.keys():
result += f"\tsympy.Symbol(\"{key}\"): <>,\n"
result += "}"
print(result)
def _plot_sensitivity(self, op, sensitivity, decades=1):
op = op.copy() # pop will impact the underlying dict
value = op.pop(sensitivity)
if isinstance(value, sympy.core.mul.Mul):
value = float(value.subs(op))
print(value)
print(type(value))
curve = u.u.subs(op.items())
display(curve)
f = sympy.lambdify(sensitivity, curve)
values = np.logspace(np.log10(value)-decades, np.log10(value)+decades)
uncertainty = f(values)
fig, ax = plt.subplots()
ax.set_title(f"${sympy.latex(curve)}$")
ax.set_xlabel(f"${sensitivity}$")
ax.plot(values,uncertainty, '.')
ax.plot(value, f(value), 'x')
plt.show()
return uncertainty
def plot_sensitivities(self, op):
results = {}
for key in op.keys():
results[key] = self._plot_sensitivity(op, key)
fig, ax = plt.subplots()
xs = np.logspace(-2, 1)
for k, v in results.items():
ax.plot(xs, v, label=f"${k}$")
ax.legend()
plt.show()
u = UncertaintyPropagation("(V-ΔV)*ΔV/R", second_order=False)
display(u)
display(u.u)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment