Skip to content

Commit

Permalink
manual linting with flake8
Browse files Browse the repository at this point in the history
  • Loading branch information
mathematicalmichael committed Apr 25, 2021
1 parent 94a9491 commit 314857c
Show file tree
Hide file tree
Showing 11 changed files with 129 additions and 134 deletions.
128 changes: 61 additions & 67 deletions src/mud_examples/linear/lin.py

Large diffs are not rendered by default.

2 changes: 1 addition & 1 deletion src/mud_examples/linear/models.py
Original file line number Diff line number Diff line change
Expand Up @@ -108,7 +108,7 @@ def randA_list_svd(dim_output, dim_input=None, seed=None) -> List:
_A = randA_gauss(dim_output, dim_input, seed=seed)
u, s, v = np.linalg.svd(_A)
for i in range(dim_output):
_a = s[i]*(u[:, i].reshape(-1, 1))@v[:, i].reshape(1, -1)
_a = s[i] * (u[:, i].reshape(-1, 1)) @ v[:, i].reshape(1, -1)
A.append(_a)
return A

Expand Down
38 changes: 19 additions & 19 deletions src/mud_examples/monomial.py
Original file line number Diff line number Diff line change
Expand Up @@ -9,12 +9,12 @@
import matplotlib.pyplot as plt
import numpy as np
# from matplotlib import cm
from mud import __version__ as __mud_version__
# from mud import __version__ as __mud_version__
from scipy.stats import \
gaussian_kde as kde # A standard kernel density estimator
from scipy.stats import norm, uniform # The standard Normal distribution

from mud_examples import __version__
# from mud_examples import __version__
from mud_examples.parsers import parse_args
from mud_examples.utils import check_dir

Expand Down Expand Up @@ -104,34 +104,34 @@ def main(args):

# compute normalizing constants
C_nonlinear = np.mean(likelihood_vals)
data_like_normalized = likelihood_vals/C_nonlinear
data_like_normalized = likelihood_vals / C_nonlinear

posterior_kde = kde(lam, weights=data_like_normalized)

# Construct push-forward of statistical Bayesian posterior
pf_posterior_kde = kde(qvals_predict, weights=data_like_normalized)

fig = plt.figure() # Plot the initial and posterior
fig, ax = plt.subplots(figsize=(10, 10)) # Plot the initial and posterior
lam_plot = np.linspace(-1, 1, num=1000)
plt.plot(lam_plot, uniform.pdf(lam_plot, loc=-1, scale=2), 'b--',
linewidth=4, label="Initial/Prior")
plt.plot(lam_plot, update_kde(lam_plot), 'k-.',
linewidth=4, label="Update")
plt.plot(lam_plot, posterior_kde(lam_plot), 'g:',
linewidth=4, label='Posterior')
plt.xlim([-1, 1])
ax.plot(lam_plot, uniform.pdf(lam_plot, loc=-1, scale=2), 'b--',
linewidth=4, label="Initial/Prior")
ax.plot(lam_plot, update_kde(lam_plot), 'k-.',
linewidth=4, label="Update")
ax.plot(lam_plot, posterior_kde(lam_plot), 'g:',
linewidth=4, label='Posterior')
ax.set_xlim([-1, 1])
if num_data > 1:
plt.annotate(f'$N={num_data}$', (-0.75, 5), fontsize=legend_fsize)
plt.ylim([0, 28]) # fix axis height for comparisons
ax.set_ylim([0, 28]) # fix axis height for comparisons

plt.xticks(fontsize=tick_fsize)
plt.yticks(fontsize=tick_fsize)
plt.xlabel("$\\Lambda$", fontsize=1.25*tick_fsize)
ax.set_xticklabels(ax.get_xticklabels(), fontsize=tick_fsize)
ax.set_yticklabels(ax.get_yticklabels(), fontsize=tick_fsize)
ax.set_xlabel("$\\Lambda$", fontsize=1.25 * tick_fsize)
plt.legend(fontsize=legend_fsize, loc='upper left')
if save:
plt.savefig(f'{fdir}/bip-vs-sip-{num_data}.png',
fig.savefig(f'{fdir}/bip-vs-sip-{num_data}.png',
bbox_inches='tight')
plt.close()
plt.close(fig)
# plt.show()

# Plot the push-forward of the initial, observed density,
Expand All @@ -153,7 +153,7 @@ def main(args):
plt.ylim([0, 20]) # fix axis height for comparisons
plt.xticks(fontsize=tick_fsize)
plt.yticks(fontsize=tick_fsize)
plt.xlabel("$\\mathcal{D}$", fontsize=1.25*tick_fsize)
plt.xlabel("$\\mathcal{D}$", fontsize=1.25 * tick_fsize)
plt.legend(fontsize=legend_fsize, loc='upper left')
if save:
plt.savefig(f'{fdir}/bip-vs-sip-pf-{num_data}.png',
Expand All @@ -180,7 +180,7 @@ def QoI(lam, p):
def data_likelihood(qvals, data, num_data, sigma):
v = 1.0
for i in range(num_data):
v *= norm.pdf(qvals-data[i], loc=0, scale=sigma)
v *= norm.pdf(qvals - data[i], loc=0, scale=sigma)
return v


Expand Down
19 changes: 9 additions & 10 deletions src/mud_examples/ode.py
Original file line number Diff line number Diff line change
Expand Up @@ -20,25 +20,24 @@
_logger = logging.getLogger(__name__)



matplotlib.rcParams['mathtext.fontset'] = 'stix'
matplotlib.rcParams['font.family'] = 'STIXGeneral'
matplotlib.backend = 'Agg'
matplotlib.rcParams['figure.figsize'] = 10,10
matplotlib.rcParams['figure.figsize'] = 10, 10
matplotlib.rcParams['font.size'] = 16


def main_ode(num_trials=20,
fsize=32,
seed=21,
lam_true=0.5,
domain=[[0,1]],
domain=[[0, 1]],
tolerances=[0.1],
time_ratios=[0.01, 1],
alt=False, bayes=True):
"""
>>> from mud_examples.ode import main_ode
>>> res = main_ode(num_trials=5, time_ratios=[0.01, 0.1, 1])
Will run simulations for %T=[0.01, 0.1, 1]
Expand All @@ -51,10 +50,10 @@ def main_ode(num_trials=20,
"""
res = []
print(f"Will run simulations for %T={time_ratios}")
sd_vals = [ std_from_equipment(tolerance=tol, probability=0.99) for tol in tolerances ]
sigma = sd_vals[-1] # sorted, pick largest
sd_vals = [std_from_equipment(tolerance=tol, probability=0.99) for tol in tolerances]
sigma = sd_vals[-1] # sorted, pick largest
t_min, t_max = 1, 3
example_list = [ 'mud' ]
example_list = ['mud']
if alt:
example_list.append('mud-alt')

Expand All @@ -68,15 +67,15 @@ def main_ode(num_trials=20,
else:
sensors = generate_sensors_ode(measurement_hertz=100, start_time=t_min, end_time=t_max)

measurements = [ int(np.floor(len(sensors)*r)) for r in time_ratios ]
measurements = [int(np.floor(len(sensors) * r)) for r in time_ratios]
print(f"Measurements: {measurements}")
# times = [ sensors[m-1] for m in measurements ]
num_measure = max(measurements)

model = generate_decay_model(sensors, lam_true)
qoi_true = model() # no args evaluates true param
np.random.seed(seed)
lam = np.random.rand(int(1E3)).reshape(-1,1)
lam = np.random.rand(int(1E3)).reshape(-1, 1)
qoi = model(lam)

if example == 'map':
Expand Down
1 change: 0 additions & 1 deletion src/mud_examples/parsers.py
Original file line number Diff line number Diff line change
Expand Up @@ -191,5 +191,4 @@ def parse_args(args):
help="Save all results (including) `mud` objects to `./results.pkl`.",
)


return parser.parse_args(args)
12 changes: 6 additions & 6 deletions src/mud_examples/pde.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,27 +2,26 @@
# -*- coding: utf-8 -*-

import logging
import os

import matplotlib
import numpy as np
from scipy.stats import distributions as ds

import mud_examples.poisson as ps # lazy loads fenics
from mud.funs import map_problem, mud_problem
# from mud.funs import map_problem, mud_problem
from mud.util import std_from_equipment
from mud_examples.experiments import (experiment_equipment,
experiment_measurements)
from mud_examples.summary import extract_statistics, fit_log_linear_regression
from mud_examples.utils import check_dir
# from mud_examples.utils import check_dir

_logger = logging.getLogger(__name__)


matplotlib.rcParams['mathtext.fontset'] = 'stix'
matplotlib.rcParams['font.family'] = 'STIXGeneral'
matplotlib.backend = 'Agg'
matplotlib.rcParams['figure.figsize'] = 10,10
matplotlib.rcParams['figure.figsize'] = 10, 10
matplotlib.rcParams['font.size'] = 16


Expand Down Expand Up @@ -91,7 +90,7 @@ def main_pde(
sd_vals = [std_from_equipment(tolerance=tol, probability=0.99) for tol in tolerances]
sigma = sd_vals[-1] # sorted, pick largest
_logger.info(f'Using std. dev {sigma}')
example_list = [ 'mud' ]
example_list = ['mud']
if alt:
example_list.append('mud-alt')
if bayes:
Expand Down Expand Up @@ -231,7 +230,8 @@ def main_pde(
P.plot_initial()
if len(measurements) > 1: # FIXME: make plots reflect level of std.
for m in measurements:
P.plot_solutions(solutions, m, example=example) # assumes keys = num_measurements. broken for tolerance comparison.
# assumes keys = num_measurements. broken for tolerance comparison.
P.plot_solutions(solutions, m, example=example)
# P.plot_solutions(solutions, 100, example=example, save=True)
return res

Expand Down
56 changes: 29 additions & 27 deletions src/mud_examples/plotting.py
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,7 @@
# matplotlib.backend = 'Agg'


_logger = logging.getLogger(__name__) # TODO: make use of this instead of print
_logger = logging.getLogger(__name__) # TODO: make use of this instead of print
_mpl_logger = logging.getLogger('matplotlib')
_mpl_logger.setLevel(logging.WARNING)

Expand Down Expand Up @@ -92,37 +92,40 @@ def plot_decay_solution(solutions, model_generator, sigma, prefix,
# plt.show()



def plot_scalar_poisson_summary(res, measurements, prefix, lam_true, fsize=32, save=False):
from fenics import plot as _plot
from mud_examples.poisson import poissonModel # function evaluation (full response surface)
from mud_examples.poisson import poissonModel # function evaluation (full response surface)

_logger.info("Fenics plotting for 1D example: Plotting surface...")
for _res in res:
_example, _in, _rm, _re, _fname = _res
lam, qoi, sensors, qoi_true, experiments, solutions = _in
gamma = lam
plot_num_measure = min(100, max(measurements))
raveled_input = np.repeat(gamma, qoi.shape[1])
raveled_output = qoi.reshape(-1)
x = raveled_input
y = raveled_output
# raveled_input = np.repeat(gamma, qoi.shape[1])
# raveled_output = qoi.reshape(-1)
# x = raveled_input
# y = raveled_output

fig = plt.figure(figsize=(10,8))
gs = gridspec.GridSpec(3, 3)
ax_main = plt.subplot(gs[1:3, :2])
# ax_xDist = plt.subplot(gs[0, :2],sharex=ax_main)
ax_yDist = plt.subplot(gs[1:3, 2],sharey=ax_main)
ax_main = plt.subplot(gs[1:3, :2], figsize=(10, 8))
# ax_xDist = plt.subplot(gs[0, :2], sharex=ax_main)
ax_yDist = plt.subplot(gs[1:3, 2], sharey=ax_main)

a = np.argsort(gamma)
slopes = []

# ax_main.plot(x,y,marker='.')
for idx in range(plot_num_measure):
ax_main.plot(gamma[a], qoi[a,idx], c='k',
label=f'sensor {idx}: (%.2f, %.2f)'%(sensors[idx,0], sensors[idx,1]),
lw=1, alpha=0.1)
slopes.append(qoi[a[-1],idx] - qoi[a[0],idx])
ax_main.plot(
gamma[a],
qoi[a, idx],
c='k',
label=f'sensor {idx}: ({sensors[idx, 0]:1.2f}, {sensors[idx, 1]:1.2f})',
lw=1,
alpha=0.1,
)
slopes.append(qoi[a[-1], idx] - qoi[a[0], idx])
sa = np.argsort(slopes)
slopes = np.array(slopes)
ranked_slopes = slopes[sa]
Expand All @@ -132,20 +135,20 @@ def plot_scalar_poisson_summary(res, measurements, prefix, lam_true, fsize=32, s
ylabel_text = "Measurement\nResponse"
ax_main.axes.set_xlabel(xlabel_text, fontsize=fsize)
ax_main.axes.set_ylabel(ylabel_text, fontsize=fsize)
ax_main.axes.set_ylim((-1.25,0.5))
ax_main.axes.set_ylim((-1.25, 0.5))
# ax_main.axes.set_title('Sensitivity of Measurements', fontsize=1.25*fsize)
ax_main.axvline(3)

ax_yDist.hist(qoi_true, bins=np.linspace(-1.25,0.5,35), orientation='horizontal', align='mid')
ax_yDist.hist(qoi_true, bins=np.linspace(-1.25, 0.5, 35), orientation='horizontal', align='mid')
# ax_yDist.set(xlabel='count')
ax_yDist.tick_params(labelleft=False, labelbottom=False)
if save:
plt.savefig(f'{_example}_qoi_response.png', bbox_inches='tight')
#plt.show()
# plt.show()

plt.figure(figsize=(10,10))
plt.title("Sensitivity of\nMeasurement Locations", fontsize=1.25*fsize)
plt.hist(ranked_slopes, bins=np.linspace(-1.25,0,25), density=True)
plt.figure(figsize=(10, 10))
plt.title("Sensitivity of\nMeasurement Locations", fontsize=1.25 * fsize)
plt.hist(ranked_slopes, bins=np.linspace(-1.25, 0, 25), density=True)
plt.xlabel("Slope", fontsize=fsize)
if save:
plt.savefig(f'{_example}_sensitivity_qoi.png', bbox_inches='tight')
Expand All @@ -154,17 +157,17 @@ def plot_scalar_poisson_summary(res, measurements, prefix, lam_true, fsize=32, s

##########

plt.figure(figsize=(10,10))
plt.figure(figsize=(10, 10))
num_sensitive = 20
most_sensitive = sa[sa < 100][0:num_sensitive]
_logger.info(f"{num_sensitive} most sensitive sensors in first 100: {most_sensitive}")
_plot(poissonModel(lam_true))
for i in range(min(100, max(measurements))):
plt.scatter(sensors[i,0], sensors[i,1], c='w', s=200)
plt.scatter(sensors[i, 0], sensors[i, 1], c='w', s=200)
if i in most_sensitive:
plt.scatter(sensors[i,0], sensors[i,1], c='y', s=100)
# plt.annotate(f"{i+1:02d}", (sensors[i,0]-0.0125, sensors[i,1]-0.01), alpha=1, fontsize=0.35*fsize)
# plt.title('Reference solution', fontsize=1.25*fsize)
plt.scatter(sensors[i, 0], sensors[i, 1], c='y', s=100)
# plt.annotate(f"{i + 1:02d}", (sensors[i, 0] - 0.0125, sensors[i, 1] - 0.01), alpha=1, fontsize=0.35*fsize)
# plt.title('Reference solution', fontsize=1.25 * fsize)
plt.xlabel('$x_1$', fontsize=fsize)
plt.ylabel('$x_2$', fontsize=fsize)
if save:
Expand Down Expand Up @@ -201,4 +204,3 @@ def plot_contours(A, ref_param, subset=None,
yloc = [ref_param[0] - w * AA[i, 1], ref_param[1] + w * AA[i, 1]]
plt.plot(xloc, yloc, c=color, ls=ls, lw=lw, **kwds)
plt.annotate('%d' % (contour + 1), (xloc[0], yloc[0]), fontsize=fs)

2 changes: 1 addition & 1 deletion src/mud_examples/poisson.py
Original file line number Diff line number Diff line change
Expand Up @@ -811,7 +811,7 @@ def evaluate_and_save_poisson(sample, save_prefix):

# define fixed mesh to avoid re-instantiation on each call to model (how it handles mesh=None)
nx, ny = 36, 36
mesh = fin.RectangleMesh(fin.Point(0,0), fin.Point(1,1), nx, ny)
mesh = fin.RectangleMesh(fin.Point(0,0), fin.Point(1, 1), nx, ny)
u = poissonModel(gamma=g, mesh=mesh, nx=nx, ny=ny)

# Save solution as XML mesh
Expand Down
1 change: 1 addition & 0 deletions src/mud_examples/runner.py
Original file line number Diff line number Diff line change
Expand Up @@ -191,6 +191,7 @@ def run_pde():
def run_ode():
"""Recreates Poisson figures in MUD paper.
>>> run_ode()
Will run simulations for %T=[0.125, 0.25, 0.5, 1.0]
Running example: mud
Expand Down
2 changes: 1 addition & 1 deletion src/mud_examples/utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -65,7 +65,7 @@ def __init__(self, module_name='utensor_cgen', submod_name=None):
self._module_name = '{}{}'.format(
module_name,
submod_name and '.{}'.format(submod_name) or ''
)
)
self._mod = None
super(LazyLoader, self).__init__(self._module_name)

Expand Down
2 changes: 1 addition & 1 deletion tests/test_random.py
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
# -*- coding: utf-8 -*-

import unittest
import mud_examples.random as mdr
import mud_examples.linear.models as mdr
import numpy as np

__author__ = "Mathematical Michael"
Expand Down

0 comments on commit 314857c

Please sign in to comment.