Part II - Pyro Inference¶
This is Part II of the time series tutorial https://pyro.ai/time. See also Part I and Part III.
We have already covered:
Pyro primitives -
pyro.param
,pyro.sample
.Effect handlers -
poutine.replay
,poutine.trace
.Pyro models and guides.
In this section, we will learn about automatic inference in Pyro, and how to use Pyro primitives and the effect handling library (pyro.poutine
) to build custom tools for analysis.
[1]:
%reset -sf
from collections import defaultdict
import math
import matplotlib.pyplot as plt
import numpy as np
import pandas as pd
import pyro
import pyro.distributions as dist
from pyro.infer import SVI, Trace_ELBO
import pyro.optim as optim
import pyro.poutine as poutine
import seaborn as sns
import torch
from torch.distributions import constraints
%matplotlib inline
%config InlineBackend.figure_format = 'svg'
plt.rcParams["figure.figsize"] = (8, 4)
print('pyro ver: {}'.format(pyro.__version__))
print('pytorch ver: {}'.format(torch.__version__))
pyro ver: 1.3.1
pytorch ver: 1.5.1
Problem Domain¶
We are provided with a time series dataset of the number of initial unemployment insurance claims for all of U.S. from the Department of Labor.
[2]:
unemployment = pd.read_csv('./unemployment_claims.csv')
unemployment['date'] = pd.to_datetime(unemployment['date'])
unemployment.head()
[2]:
| date | initial claim | |
|---|---|---|
| 0 | 2010-01-02 | 651215 |
| 1 | 2010-01-09 | 825891 |
| 2 | 2010-01-16 | 659173 |
| 3 | 2010-01-23 | 507651 |
| 4 | 2010-01-30 | 538617 |
[3]:
y = torch.tensor(unemployment['initial claim'].values, dtype=torch.float32)
sns.lineplot(x='date', y='initial claim', data=unemployment).set_title('Unemployment Insurance Claims');
[4]:
init_date = '2010-01-02'
time_range = pd.date_range(start=init_date, freq='7D', periods=len(y))
y_log = y.log()
fig, ax = plt.subplots()
ax.plot(time_range, y_log)
ax.set(title='Weekly Claims (Log Scale)', xlabel='date', ylabel='initial claim');
Outline¶
Build a regression model to model the global trend and seasonality - estimate parameters using ML.
Build a bayesian model for time series forecasting and infer latent parameters using:
SVI (Autoguides)
Delta Autoguide - MAP inference.
Diagonal Normal Autoguide.
MCMC with a No-U-Turn Sampler (NUTS).
Fitting a Regression Model¶
A Global Trend Model¶
For simplicity, let us assume that \(\sigma = 1\) to begin with.
[5]:
def model_global_trend(y):
slope = pyro.param('slope', torch.tensor(0.))
intercept = pyro.param('intercept', torch.tensor(13.))
for i in range(len(y)):
log_y_hat = slope * i + intercept
pyro.sample('y_{}'.format(i), dist.LogNormal(log_y_hat, 1.), obs=y[i])
pyro.param
designate model parameters that we would like to optimize.Observations are denoted by the
obs=
keyword argument topyro.sample
. This specifies the likelihood function.Instead of log transforming the data, we use a LogNormal distribution.
Vectorized Model Using pyro.plate
¶
Tensor libraries like PyTorch have highly optimized linear algebra routines that can exploit data parallelism. Let us vectorize the likelihood computation to operate over all data in parallel.
[6]:
def model_global_trend(y):
slope = pyro.param('slope', torch.tensor(0.))
intercept = pyro.param('intercept', torch.tensor(13.))
with pyro.plate('N', len(y)) as t:
log_y_hat = slope * t.type(torch.float) + intercept
pyro.sample('y', dist.LogNormal(log_y_hat, 1.), obs=y)
[7]:
?pyro.plate
Maximum Likelihood Estimate of the Parameters¶
Test-Train Split: Reserve the last 100 data-points for testing.
[8]:
N = len(y)
N_test = 100
N_train = N - N_test
y_train = y[:N_train]
[9]:
%%time
opt = optim.Adam({'lr': 0.08})
pyro.clear_param_store()
pyro.set_rng_seed(1)
empty_guide = lambda x: None
svi = SVI(model_global_trend, empty_guide, opt, loss=Trace_ELBO())
for i in range(1600):
loss = svi.step(y_train)
if i % 100 == 0:
print('ELBO loss: {}'.format(loss / len(y_train)))
print('ELBO loss: {}'.format(loss / len(y_train)))
ELBO loss: 13.695740666221734
ELBO loss: 13.63005579656093
ELBO loss: 13.627845035725503
ELBO loss: 13.627821725816583
ELBO loss: 13.627820498979272
ELBO loss: 13.627818045304648
ELBO loss: 13.62781927214196
ELBO loss: 13.62781927214196
ELBO loss: 13.62781927214196
ELBO loss: 13.62781927214196
ELBO loss: 13.62781927214196
ELBO loss: 13.627818045304648
ELBO loss: 13.627818045304648
ELBO loss: 13.627818045304648
ELBO loss: 13.627818045304648
ELBO loss: 13.62781927214196
ELBO loss: 13.62781927214196
CPU times: user 2.08 s, sys: 76.2 ms, total: 2.15 s
Wall time: 2.97 s
Important arguments to
SVI
- model, guide, loss.We pass an empty guide
lambda x: None
since the model does not have any latent parameters.The loss function is given by
Trace_ELBO
. With an empty guide and onlypyro.param
statements in the model, this simply computes the NLL- log(p(y|x))
. We minimize this using the Adam optimizer.
Plotting the Regression Fit¶
[10]:
slope = pyro.param('slope').detach()
intercept = pyro.param('intercept').detach()
slope, intercept
[10]:
(tensor(-0.0018), tensor(13.0523))
[11]:
model_fit = (slope * torch.arange(len(y)).type(torch.float) + intercept).exp()
fig, ax = plt.subplots()
ax.plot(time_range, y, label='Actual data')
ax.plot(time_range, model_fit.detach(), linewidth=2, label='Fitted data')
ax.axvline(time_range[N_train], linestyle='--', color='gray', label='train-test split')
ax.set(title='Regression Fit', xlabel='date', ylabel='initial claim')
plt.legend();
Modeling Seasonality¶
[12]:
fig, ax = plt.subplots()
ax.plot(np.arange(52), y[:52], label='2010');
ax.plot(np.arange(52), y[52:104], label='2011');
plt.legend()
ax.set(title='Weekly Claims (first 2 years)', xlabel='date', ylabel='initial claims');
A Sesonal Global Trend (SGT) Model¶
[13]:
def model_sgt(y):
slope = pyro.param('slope', torch.tensor(1.))
intercept = pyro.param('intercept', torch.tensor(13.))
seasonality = pyro.param('seasonality', torch.zeros(52))
seasonality = seasonality - seasonality.mean()
N = len(y)
with pyro.plate('N', N) as t:
seasonality_factor = seasonality.repeat(math.ceil(N / 52))[:N]
log_y_hat = slope * t.type(torch.float) + intercept + seasonality_factor
pyro.sample('y', dist.LogNormal(log_y_hat, 1.), obs=y)
In addition to the global trend, this includes a cyclic seasonality term. Note that this is a multiplier term.
We will use
SVI
to fit this model in a similar fashion.
[14]:
%%time
opt = optim.Adam({'lr': 0.08})
pyro.clear_param_store()
pyro.set_rng_seed(1)
empty_guide = lambda x: None
svi = SVI(model_sgt, empty_guide, opt, loss=Trace_ELBO())
for i in range(3000):
loss = svi.step(y_train)
if i % 500 == 0:
print('ELBO loss: {}'.format(loss / len(y_train)))
print('ELBO loss: {}'.format(loss / len(y_train)))
ELBO loss: 26399.26381909548
ELBO loss: 13.683770414572864
ELBO loss: 13.631697304883794
ELBO loss: 13.61758131477701
ELBO loss: 13.615883371937814
ELBO loss: 13.615797493326005
ELBO loss: 13.615795039651381
CPU times: user 4.15 s, sys: 86.9 ms, total: 4.24 s
Wall time: 4.44 s
[15]:
len(y_train)
[15]:
398
Plotting the Regression Fit¶
[16]:
slope = pyro.param('slope').detach()
intercept = pyro.param('intercept').detach()
slope, intercept
[16]:
(tensor(-0.0018), tensor(13.0455))
[17]:
slope = pyro.param('slope').detach()
intercept = pyro.param('intercept').detach()
seasonality = pyro.param('seasonality').detach()
seasonality = (seasonality - seasonality.mean())
seasonality_rep = seasonality.repeat(math.ceil(len(y) / 52))[:len(y)]
model_fit = (slope * torch.arange(len(y)).type(torch.float) + intercept + seasonality_rep).exp()
fig, ax = plt.subplots(2, 1, figsize=(8, 10))
ax[0].plot(time_range, y, label='Actual data')
ax[0].plot(time_range, model_fit.detach(), label='Fitted data')
ax[0].set(title='Seasonal + Global Trend Regression Model',
xlabel='year',
ylabel='initial claim')
ax[0].axvline(time_range[N_train], linestyle='--', color='gray', label='train-test split')
ax[0].legend();
ax[1].plot(range(52), seasonality.exp())
ax[1].set(title='Seasonality Component',
xlabel='week of year',
ylabel='seasonality multiplier');
A Bayesian Model for Forecasting¶
We build on our previous SGT
model.
[18]:
seasonality_mean = pyro.param('seasonality').detach()
"""
N : Number of forecast steps from the current step.
x : Index for the last observed data from which to start forecasting.
y : Value for the last observed data.
"""
def prob_sgt(N, x, y):
slope = pyro.sample('slope', dist.Normal(-0.18, 1.)) * 1e-2
obs_sd = pyro.sample('obs_sd', dist.HalfNormal(1.)) * 0.1
with pyro.plate('S', 52):
seasonality = pyro.sample('seasonality', dist.Normal(seasonality_mean, 0.1))
seasonality = seasonality - seasonality.mean()
with pyro.plate('N', N) as t:
seasonality_factor = seasonality.roll(-(x + 1) % 52).repeat(math.ceil(N / 52))[:N]
y_intercept = y.log() - seasonality[x % 52]
log_y_hat = slope * (t + 1).type(torch.float) + y_intercept + seasonality_factor
return pyro.sample('y', dist.LogNormal(log_y_hat, obs_sd))
No
intercept
parameter, we instead take the current known value fory
and forecastN
steps ahead.We need to account for which week we are in starting from the first week of Jan 2010 to apply the seasonality factor.
Priors for
slope
,seasonality
and the observation noiseobs_sd
.There is no
obs
argument. How are we going to train the model?
Are the Priors Reasonable?¶
One way to check would be to generate samples from the model and check the overlap between distribution from the training set and the prior predictive distribution.
To generate samples from the prior, we will simply call the model multiple times and stack the predictions from the prior.
[19]:
pyro.clear_param_store()
preds = []
for i in range(500):
preds.append(prob_sgt(N_train-1, 0, y[0]).detach())
preds = torch.stack(preds)
quantiles = [0.1, 0.5, 0.9]
pred_p10, pred_p50, pred_p90 = [preds.kthvalue(int(q*500), dim=0)[0] for q in quantiles]
fig, ax = plt.subplots()
ax.plot(time_range[:N_train], y_train, label='Actual data')
ax.plot(time_range[1:N_train], pred_p50, label='Prior Predictive', color='darkorange')
ax.fill_between(time_range[1:N_train], pred_p10, pred_p90, alpha=0.4,
color='darkorange')
ax.set(title='Before Training - Prior Predictive (90% CI)',
xlabel='year', ylabel='initial claim', ylim=(0, 2e6))
plt.legend();
Inference Using Stochastic Variational Inference¶
Provides a way to formulate the inference problem as an optimization problem.
Pyro provides state of the art support for VI.
Optimize the parameters of a guide program to generate samples from the approx posterior.
Autoguides¶
We will use autoguides from the pyro.infer.autoguide module.
MAP Inference Using a Delta Autoguide¶
[20]:
%%time
from pyro.contrib.autoguide import *
opt = optim.Adam({'lr': 0.05})
pyro.clear_param_store()
pyro.set_rng_seed(2)
model = poutine.condition(prob_sgt, {'y': y_train[1:]})
guide_delta = AutoDelta(model)
guide_delta(N_train-1, x=0, y=y_train[0])
svi = SVI(model, guide_delta, opt, loss=Trace_ELBO())
for i in range(5000):
loss = svi.step(N_train-1, x=0, y=y_train[0])
if i % 500 == 0:
print('ELBO loss: {}'.format(loss / len(y_train)))
print('ELBO loss: {}'.format(loss / len(y_train)))
ELBO loss: 62.88858677933563
ELBO loss: 11.126496613175426
ELBO loss: 11.12649508472064
ELBO loss: 11.126495065251786
ELBO loss: 11.126495065251786
ELBO loss: 11.126495065251786
ELBO loss: 11.126495065251786
ELBO loss: 11.126495065251786
ELBO loss: 11.126513930121858
ELBO loss: 11.128522273433868
ELBO loss: 11.127055210534053
CPU times: user 16.8 s, sys: 254 ms, total: 17 s
Wall time: 17.7 s
Note the use of the poutine.condition
handler to constrain the site y
to our training set. The advantage of using poutine.condition
is that we can use the same model for both training and forecasting!
Examining the MAP Parameters¶
[21]:
pyro.get_param_store().get_state()
[21]:
{'params': {'AutoDelta.slope': Parameter containing:
tensor(-0.1784, requires_grad=True),
'AutoDelta.obs_sd': Parameter containing:
tensor(-0.4818, requires_grad=True),
'AutoDelta.seasonality': Parameter containing:
tensor([ 0.3740, 0.5071, 0.4950, 0.2619, 0.1308, 0.1354, 0.0932, 0.0103,
-0.0235, 0.0249, -0.0222, -0.0807, -0.0836, -0.0736, 0.0259, 0.0440,
-0.0077, -0.0254, -0.0591, -0.0608, -0.0652, -0.0473, -0.0766, 0.0099,
0.0175, 0.0219, 0.0547, 0.1484, 0.2195, 0.0159, -0.0981, -0.1067,
-0.0841, -0.1222, -0.1301, -0.1290, -0.1848, -0.1527, -0.1658, -0.1799,
-0.0381, -0.0027, -0.0423, -0.0174, 0.0287, 0.1000, 0.0624, 0.1120,
0.1721, 0.2947, 0.1932, 0.2602], requires_grad=True)},
'constraints': {'AutoDelta.slope': Real(),
'AutoDelta.obs_sd': GreaterThan(lower_bound=0.0),
'AutoDelta.seasonality': Real()}}
Generating Forecasts¶
Replaying from a Trained Guide¶
[22]:
@torch.no_grad()
def get_predictive_samples(model, *args,
guide,
num_samples=500,
quantiles=[0.1, 0.5, 0.9]):
preds = defaultdict(list)
for i in range(num_samples):
guide_trace = poutine.trace(guide).get_trace(*args)
replay_model = poutine.replay(model, guide_trace)
model_trace = poutine.trace(replay_model).get_trace(*args)
preds['slope_sd'].append(model_trace.nodes['slope']['value'].detach())
preds['slope'].append(model_trace.nodes['slope']['value'].detach())
preds['obs_sd'].append(model_trace.nodes['obs_sd']['value'].detach())
preds['y'].append(model_trace.nodes['y']['value'].detach())
return {k: torch.stack(v) for k, v in preds.items()}
Model remains the same for both inference and prediction.
To generate forecasts we can simply run the guide to sample latent values from the approximate posterior distribution, and replay these values in the model.
[23]:
forecast_delta = get_predictive_samples(prob_sgt, N_test, N_train-1, y[N_train-1],
guide=guide_delta)
p10, p50, p90 = [forecast_delta['y'].kthvalue(int(q * (N_train-1)), dim=0)[0] for q in quantiles]
plt.plot(time_range[-200:], y[-200:], label='Actual data')
plt.plot(time_range[N_train:N_train+N_test], p50, label='Forecast',
color='darkorange')
plt.fill_between(time_range[398:len(y)], p10, p90, alpha=0.4,
color='darkorange')
plt.title('Forecast (Delta Autoguide)')
plt.legend();
Variational Inference Using a Normal Autoguide¶
The model and training procedure remains the same as earlier.
The Diagonal Normal Autoguide samples from a Normal distribution with diagonal covariance to generate samples from the approximate posterior distribution.
[24]:
%%time
opt = optim.ClippedAdam({'lr': 0.8 * 1e-3})
pyro.clear_param_store()
pyro.set_rng_seed(1)
model = poutine.condition(prob_sgt, {'y': y_train[1:]})
guide_diagnormal = AutoDiagonalNormal(model)
pyro.param('auto_scale', torch.ones(54).fill_(1e-2), constraint=constraints.positive)
svi = SVI(model, guide_diagnormal, opt, loss=Trace_ELBO())
for i in range(10000):
loss = svi.step(N=N_train-1, x=0, y=y_train[0])
if i % 1000 == 0:
print('ELBO loss: {}'.format(loss / len(y_train)))
print('ELBO loss: {}'.format(loss / len(y_train)))
/Users/distiller/project/conda/conda-bld/pytorch_1591914889657/work/torch/csrc/utils/python_arg_parser.cpp:756: UserWarning: This overload of add_ is deprecated:
add_(Number alpha, Tensor other)
Consider using one of the following signatures instead:
add_(Tensor other, *, Number alpha)
ELBO loss: 22.420856059163846
ELBO loss: 12.916967682203456
ELBO loss: 12.170049678889951
ELBO loss: 12.401121813920911
ELBO loss: 11.663290481172016
ELBO loss: 11.567352228802653
ELBO loss: 11.728647305288506
ELBO loss: 11.542766381897518
ELBO loss: 11.568688603951104
ELBO loss: 11.527311370899929
ELBO loss: 11.523166831863586
CPU times: user 41 s, sys: 550 ms, total: 41.6 s
Wall time: 43.2 s
Plotting the Model’s Forecast¶
[24]:
guide_diagnormal.quantiles([0.1, 0.5, 0.9])
[24]:
{'slope': [tensor(-0.1802, grad_fn=<ViewBackward>),
tensor(-0.1783, grad_fn=<ViewBackward>),
tensor(-0.1764, grad_fn=<ViewBackward>)],
'obs_sd': [tensor(0.6376, grad_fn=<AddBackward0>),
tensor(0.6669, grad_fn=<AddBackward0>),
tensor(0.6975, grad_fn=<AddBackward0>)],
'seasonality': [tensor([ 0.3664, 0.4766, 0.4672, 0.2306, 0.0946, 0.1026, 0.0633, -0.0217,
-0.0504, -0.0073, -0.0557, -0.1122, -0.1125, -0.1028, -0.0076, 0.0115,
-0.0354, -0.0569, -0.0933, -0.0898, -0.0920, -0.0783, -0.1084, -0.0260,
-0.0135, -0.0082, 0.0256, 0.1206, 0.1892, -0.0124, -0.1282, -0.1364,
-0.1188, -0.1528, -0.1567, -0.1607, -0.2177, -0.1868, -0.1951, -0.2120,
-0.0690, -0.0380, -0.0666, -0.0522, -0.0048, 0.0606, 0.0305, 0.0817,
0.1467, 0.2637, 0.1638, 0.2353], grad_fn=<ViewBackward>),
tensor([ 0.3708, 0.5058, 0.4973, 0.2595, 0.1244, 0.1326, 0.0932, 0.0076,
-0.0210, 0.0211, -0.0270, -0.0835, -0.0828, -0.0733, 0.0218, 0.0411,
-0.0069, -0.0280, -0.0643, -0.0599, -0.0635, -0.0485, -0.0785, 0.0038,
0.0152, 0.0216, 0.0542, 0.1500, 0.2188, 0.0171, -0.0988, -0.1069,
-0.0899, -0.1236, -0.1250, -0.1295, -0.1860, -0.1549, -0.1643, -0.1804,
-0.0366, -0.0064, -0.0347, -0.0202, 0.0263, 0.0908, 0.0619, 0.1122,
0.1788, 0.2950, 0.1955, 0.2668], grad_fn=<ViewBackward>),
tensor([ 0.3751, 0.5349, 0.5273, 0.2884, 0.1542, 0.1625, 0.1231, 0.0369,
0.0085, 0.0495, 0.0018, -0.0549, -0.0532, -0.0439, 0.0513, 0.0708,
0.0217, 0.0009, -0.0353, -0.0301, -0.0350, -0.0187, -0.0487, 0.0336,
0.0439, 0.0513, 0.0828, 0.1793, 0.2484, 0.0466, -0.0694, -0.0775,
-0.0611, -0.0944, -0.0933, -0.0983, -0.1543, -0.1230, -0.1336, -0.1488,
-0.0041, 0.0251, -0.0028, 0.0118, 0.0573, 0.1211, 0.0933, 0.1427,
0.2110, 0.3262, 0.2272, 0.2982], grad_fn=<ViewBackward>)]}
[25]:
forecast_diagnormal = get_predictive_samples(prob_sgt, N_test, N_train-1, y[N_train-1],
guide=guide_diagnormal)
p10, p50, p90 = [forecast_diagnormal['y'].kthvalue(int(q * (N_train-1)), dim=0)[0]
for q in quantiles]
plt.plot(time_range[-200:], y[-200:], label='Actual data')
plt.plot(time_range[N_train:N_train+N_test], p50, label='Forecast',
color='darkorange')
plt.fill_between(time_range[N_train:N_train+N_test], p10, p90, alpha=0.4,
color='darkorange')
plt.title('Forecast (Diagonal Normal Autoguide)')
plt.legend();
Inference Using MCMC¶
Pyro provides support for Hamiltonian Monte Carlo which is well suited to sample from high-dimensional continuous spaces.
In particular, we use the No-U-Turn algorithm for running HMC which adaptively sets many critical parameters for HMC.
[26]:
from pyro.infer.mcmc import NUTS
from pyro.infer.mcmc.api import MCMC
from pyro.infer.mcmc.util import predictive
from pyro.ops.stats import hpdi
from torch.distributions.transforms import AffineTransform
[27]:
model = poutine.condition(prob_sgt, {'y': y_train[1:]})
nuts_kernel = NUTS(model, jit_compile=True, ignore_jit_warnings=True)
mcmc = MCMC(nuts_kernel, num_samples=500, num_chains=4)
mcmc.run(N_train-1, x=0, y=y_train[0])
Model Summary¶
[28]:
mcmc.summary()
mean std median 5.0% 95.0% n_eff r_hat
slope -0.18 0.00 -0.18 -0.18 -0.17 4190.57 1.00
obs_sd 0.66 0.03 0.66 0.62 0.71 1640.48 1.00
seasonality[0] 0.37 0.02 0.37 0.35 0.40 130.34 1.03
seasonality[1] 0.51 0.03 0.51 0.46 0.55 296.55 1.02
seasonality[2] 0.49 0.03 0.49 0.45 0.54 366.82 1.01
seasonality[3] 0.26 0.03 0.26 0.22 0.30 404.48 1.01
seasonality[4] 0.13 0.03 0.13 0.09 0.18 413.99 1.01
seasonality[5] 0.14 0.03 0.14 0.09 0.18 445.08 1.01
seasonality[6] 0.09 0.03 0.09 0.06 0.14 409.36 1.01
seasonality[7] 0.01 0.03 0.01 -0.03 0.05 399.18 1.01
seasonality[8] -0.02 0.03 -0.02 -0.07 0.02 387.69 1.01
seasonality[9] 0.02 0.03 0.03 -0.02 0.07 339.95 1.01
seasonality[10] -0.02 0.03 -0.02 -0.06 0.02 363.41 1.01
seasonality[11] -0.08 0.03 -0.08 -0.12 -0.04 345.68 1.02
seasonality[12] -0.08 0.03 -0.08 -0.13 -0.04 342.02 1.01
seasonality[13] -0.07 0.03 -0.07 -0.12 -0.03 363.95 1.01
seasonality[14] 0.03 0.03 0.03 -0.02 0.07 369.73 1.01
seasonality[15] 0.04 0.03 0.04 -0.00 0.09 352.19 1.01
seasonality[16] -0.01 0.03 -0.01 -0.05 0.04 352.38 1.01
seasonality[17] -0.03 0.03 -0.03 -0.07 0.02 318.25 1.01
seasonality[18] -0.06 0.03 -0.06 -0.10 -0.02 347.87 1.01
seasonality[19] -0.06 0.03 -0.06 -0.10 -0.02 374.32 1.01
seasonality[20] -0.07 0.03 -0.06 -0.11 -0.03 401.81 1.01
seasonality[21] -0.05 0.03 -0.05 -0.09 -0.00 381.88 1.01
seasonality[22] -0.08 0.03 -0.08 -0.12 -0.03 352.64 1.01
seasonality[23] 0.01 0.03 0.01 -0.03 0.05 365.34 1.01
seasonality[24] 0.02 0.03 0.02 -0.03 0.06 378.86 1.01
seasonality[25] 0.02 0.03 0.02 -0.02 0.06 411.36 1.01
seasonality[26] 0.05 0.03 0.05 0.01 0.10 387.78 1.01
seasonality[27] 0.15 0.03 0.15 0.10 0.19 360.38 1.01
seasonality[28] 0.22 0.03 0.22 0.18 0.26 352.08 1.01
seasonality[29] 0.02 0.03 0.02 -0.03 0.06 374.96 1.01
seasonality[30] -0.10 0.03 -0.10 -0.14 -0.05 423.33 1.01
seasonality[31] -0.11 0.03 -0.11 -0.15 -0.06 311.62 1.02
seasonality[32] -0.08 0.03 -0.08 -0.13 -0.04 331.68 1.01
seasonality[33] -0.12 0.03 -0.12 -0.17 -0.08 381.49 1.01
seasonality[34] -0.13 0.03 -0.13 -0.18 -0.08 418.21 1.01
seasonality[35] -0.13 0.03 -0.13 -0.17 -0.08 352.13 1.01
seasonality[36] -0.18 0.03 -0.19 -0.23 -0.14 404.80 1.01
seasonality[37] -0.15 0.03 -0.15 -0.20 -0.11 367.51 1.01
seasonality[38] -0.17 0.03 -0.17 -0.21 -0.12 424.00 1.01
seasonality[39] -0.18 0.03 -0.18 -0.22 -0.13 335.00 1.01
seasonality[40] -0.04 0.03 -0.04 -0.08 0.01 447.33 1.01
seasonality[41] -0.00 0.03 -0.00 -0.05 0.04 443.58 1.01
seasonality[42] -0.04 0.03 -0.04 -0.09 0.00 370.32 1.01
seasonality[43] -0.02 0.03 -0.02 -0.06 0.03 429.21 1.01
seasonality[44] 0.03 0.03 0.03 -0.01 0.08 402.90 1.01
seasonality[45] 0.10 0.03 0.10 0.05 0.15 470.56 1.01
seasonality[46] 0.06 0.03 0.06 0.02 0.11 406.96 1.01
seasonality[47] 0.11 0.03 0.11 0.06 0.16 489.49 1.01
seasonality[48] 0.17 0.03 0.17 0.13 0.22 415.83 1.01
seasonality[49] 0.29 0.03 0.29 0.25 0.34 361.79 1.01
seasonality[50] 0.19 0.03 0.19 0.14 0.23 510.13 1.01
seasonality[51] 0.26 0.03 0.26 0.22 0.31 382.86 1.01
Plotting Model Forecast¶
[29]:
from pyro.util import ignore_experimental_warning
with ignore_experimental_warning():
forecast_mcmc = predictive(prob_sgt, mcmc.get_samples(), N_test, N_train-1, y[N_train-1])
p10, p90 = hpdi(forecast_mcmc['y'], prob=0.9)
p50 = forecast_mcmc['y'].median(dim=0)[0]
plt.plot(time_range[-200:], y[-200:], label='Actual data')
plt.plot(time_range[N_train:N_train+N_test], p50, label='Forecast',
color='darkorange')
plt.fill_between(time_range[N_train:N_train+N_test], p10, p90, alpha=0.4,
color='darkorange')
plt.title('Forecast (MCMC)')
plt.legend();
Posterior Distribution of Slope for MCMC and SVI¶
[30]:
samples = mcmc.get_samples()
fig, ax = plt.subplots()
sns.kdeplot(samples['slope'].cpu().numpy(),
ax=ax, label='NUTS')
sns.kdeplot(forecast_diagnormal['slope'].cpu().numpy(),
ax=ax, label='SVI (AutoDiagonalNormal)')
ax.set(title='Posterior distribution of `slope`',
xlabel='slope')
ax.legend();
Variational Inference Using a Multivariate Normal Autoguide¶
[31]:
%%time
opt = optim.ClippedAdam({'lr': 0.5 * 1e-3})
pyro.clear_param_store()
pyro.set_rng_seed(1)
model = poutine.condition(prob_sgt, {'y': y_train[1:]})
guide_mvn = AutoMultivariateNormal(model)
pyro.param('auto_scale_tril', torch.diag_embed(torch.full((54,), 1e-2)),
constraint=constraints.lower_cholesky)
svi = SVI(model, guide_mvn, opt, loss=Trace_ELBO())
for i in range(15000):
loss = svi.step(N=N_train-1, x=0, y=y_train[0])
if i % 1000 == 0:
print('ELBO loss: {}'.format(loss / len(y_train)))
print('ELBO loss: {}'.format(loss / len(y_train)))
ELBO loss: 19.95344287678412
ELBO loss: 11.59777264162224
ELBO loss: 11.561684518453465
ELBO loss: 11.598039866766738
ELBO loss: 11.54362484648
ELBO loss: 11.557480851160221
ELBO loss: 11.579892492623785
ELBO loss: 11.53785526437975
ELBO loss: 11.523967811585072
ELBO loss: 11.548766153990924
ELBO loss: 11.583748653755714
ELBO loss: 11.55748783553665
ELBO loss: 11.552191911780055
ELBO loss: 11.581329234056737
ELBO loss: 11.551585462524663
ELBO loss: 11.554221333945216
CPU times: user 45.3 s, sys: 267 ms, total: 45.5 s
Wall time: 45.5 s
[32]:
forecast_mvn = get_predictive_samples(prob_sgt, N_test, N_train-1, y[N_train-1],
guide=guide_mvn)
p10, p50, p90 = [forecast_mvn['y'].kthvalue(int(q * (N_train-1)), dim=0)[0]
for q in quantiles]
plt.plot(time_range[-200:], y[-200:], label='Actual data')
plt.plot(time_range[N_train:N_train+N_test], p50, label='Forecast',
color='darkorange')
plt.fill_between(time_range[N_train:N_train+N_test], p10, p90, alpha=0.4,
color='darkorange')
plt.title('Forecast (AutoMultivariateNormal)')
plt.legend();
[33]:
samples = mcmc.get_samples()
fig, ax = plt.subplots()
sns.kdeplot(samples['slope'].cpu().numpy(),
ax=ax, label='NUTS')
sns.kdeplot(forecast_mvn['slope'].cpu().numpy(),
ax=ax, label='SVI (AutoMultivariateNormal)')
ax.set(title='Posterior distribution of `slope`',
xlabel='slope')
ax.legend();
Next Steps¶
In Part III we will look into custom guides for scalable and flexible inference.
To recap: - Modeling in Pyro is for the most part distinct from inference. - Pyro an array of black-box inference algorithms to use out of the box: - ML estimation using null guides. - SVI with autoguides - AutoDelta, AutoDiagNormal, AutoMultivariateNormal, flow-based guides, etc. - MCMC using NUTS sampler.


WITNESS LIST Criminal Justice Committee April 25, 2001 - 1:00P HB 261 Registering, but not testifying: For: Hampton, Keith Law (Texas Criminal Defense Lawyers Association), Austin, TX HB 772 FOR: Roper, Helga (Self), Austin, TX ON: Gibson, Mary Lou (Texas Comptroller's Office), Austin, TX Kifowit, Dee Director (TX Council on Offenders with Mental Impairments), Austin, TX Minor, Ned (Texas Comptroller's Office), Austin, TX Registering, but not testifying: For: Green, Dana (Restful Acres Care Center), Kenedy, TX On: Gold, Marc (Texas Department of Human Services), Austin, TX HB 780 FOR: Elkin, Bill Executive Director (Houston Police Retired Officers Association), Houston, TX Sawyer, Gary President (Texas Reserve Law Officers Association), Dallas, TX Registering, but not testifying: For: Clark, Mark (Houston Police Officers' Union), Houston, TX DeLord, Ron President (CLEAT), Austin, TX Navarro, Jr., Wilfred President (Houston Police Retired Officers Association), Houston, TX Sanders, Stephen (Texas State Lodge Fraternal Order of Police), Austin, TX HB 1739 FOR: DeSoto, Dean Executive Director (Community Alliance for Training & Safety), San Antonio, TX ON: Bresnen, Steve Attorney (USA Training, Inc.), Austin, TX Warren, Elizabeth Coordinator, Occupant Safety Programs (TX DPS), Austin, TX Registering, but not testifying: For: Ybarbo, Ray (Chief of Police Al Philippus, San Antonio Police Department), San Antonio, TX On: Hackney, Clint (Driver Training Associates), Austin, TX Midence, Yuniedth (Defensive Driving.com), Austin, TX SB 455 FOR: Gildon, Gary Director, Criminal Justice Program (Community College Criminal Justice Educators of Texas), Texarkana, TX Grams, Dr. Mary Ann College Administrator (CCCJET), Hillsboro, TX Reeves, Gary Criminal Justice Program Coordinator (CCCJET), Hillsboro, TX Vanderhule, Lt. George Police Officer (Austin Police Department), Austin, TX Registering, but not testifying: For: Davis, Gloria (CCCJET), Hillsboro, TX SB 786 FOR: Espinoza, Margaret (Erica Margaret (Daughter)), San Antonio, TX Garza, Sheila (Rudolfo (Rudy) Garza, Jr.), Floresville, TX Perry, Kathryn Scott (Parents of Murdered Children), Wimberly, TX Perry, Muriel (Self), San Antonio, TX Rodriguez, Linda (Rudolfo (Rudy) Garza, Jr.), Floresville, TX Torres, Vincent (Self), Austin, TX Valadez, Rachel (Self), San Antonio, TX Registering, but not testifying: For: Carr, Verna Lee (People Against Violent Crime), Austin, TX Moore, Arlene (Self), San Antonio, TX Stober, Lonnie (People Against Violent Crime), Austin, TX SB 1312 FOR: DeLord, Ron President (CLEAT), Austin, TX Elkin, Bill Executive Director (Houston Police Retired Officers' Association), Houston, TX Navarro, Jr., Wilfred President (Houston Police Retired Officers Association), Houston, TX Registering, but not testifying: For: Campos, Jr., Charlie Constable (Justices of the Peace and Constables Association of Texas), San Antonio, TX Mann, Tom (TX Police Chiefs Association and Lubbock Police Department), Lubbock, TX Oakley, Keith Consultant (Texas Municipal Police Association), Terrell, TX Sanders, Stephen Police Officer (Texas State Lodge Fraternal Order of Police), Austin, TX Watson, Rick (Chief of Police Terrell Bolton, Dallas Police Department), Dallas, TX Ybarbo, Ray (Chief of Police Al Philippus, San Antonio Police Department), San Antonio, TX SB 1313 FOR: Willis, Joe District Attorney Investigator (Anderson County District Attorney, Palestine Police Department), Palestine, TX Registering, but not testifying: For: Granger, J.D. Assistant District Attorney (Tarrant County District Attorney's Office), Fort Worth, TX Noll, Chuck Assistant District Attorney (Harris County District Attorney's Office), Houston, TX Against: Harrell, William Lawyer (ACLU), Austin, TX SB 1347 FOR: Parker, Ray Executive Secretary, Austin TASO (Texas Association Sports Officials), Pflugerville, TX Registering, but not testifying: For: Fisher, Jon (Self), Austin, TX Rivero, Hector (Texas Association of Sports Officials - Austin Football Chapter), Austin, TX SB 1665 FOR: Dick, Sam Attorney (Texas Criminal Defense Association), Sugar Land, TX AGAINST: Granger, J.D. Assistant District Attorney (Tarrant County District Attorney's Office), Fort Worth, TX Liu, Livia Assistant District Attorney (Dallas County District Attorney's Office), Dallas, TX Noll, Chuck Assistant District Attorney (Harris County District Attorney's Office), Houston, TX Registering, but not testifying: For: Hampton, Keith (Texas Criminal Defense Lawyers Association), Austin, TX Against: Whalen, Ken Director of Legislative Affairs (TX Daily Newspaper Association, TX Press Association), Austin, TX SB 1724 FOR: Autry, Greg (Self), Dallas, TX Briscoe, Judy (Self), Austin, TX Doubet, Frederick (Responsible Pet Owners' Alliance), Hondo, TX Flynn, Clifton Professor of Sociology (University of South Carolina, Spartanburg), Spartanburg, SC French, Robert Chief Investigator (SPCA of Texas), Dallas, TX Hale, Jef Program Coordinator (The Humane Society of the United States), Dallas, TX Jeffrey, Betty (Responsible Pet Owners' Alliance), San Antonio, TX Trimble, Robert Attorney (Texas Humane Legislation Network), Dallas, TX Winder, Merceda (Self), Allen, TX AGAINST: Burkey, Robert (Self), San Antonio, TX Hagen, Walter (Responsible Pet Owners' Alliance), San Antonio, TX Registering, but not testifying: For: Campbell, Virginia (Self), Austin, TX Holloway, Cile (Texas Humane Legislation Network), Austin, TX Monroe, Richard (Self), Austin, TX Patterson, Jerry (Houston Safari Club/Houston Gun Collectors Association), Austin, TX Valls-Trelles, Pat (Self), Austin, TX SB 1807 ON: Kepple, Robert Attorney (District & County Attorneys Association), Austin, TX Registering, but not testifying: For: Granger, J.D. Assistant District Attorney (Tarrant County District Attorney's Office), Fort Worth, TX Liu, Livia Assistant District Attorney (Dallas County District Attorney's Office), Dallas, TX Noll, Chuck Assistant District Attorney (Harris County District Attorney's Office), Houston, TX Weeks, David Criminal District Attorney (Self), Huntsville, TX


--- title: pyxelstitch keywords: fastai sidebar: home_sidebar summary: "Simple, matplotlib based tool for hand-labeling the two-image correspondences" description: "Simple, matplotlib based tool for hand-labeling the two-image correspondences" nb_path: "index.ipynb" ---
pip install pixelstitch
Let's test our annotator on a sample project. It needs a list of triplets: (path_to_img1
, path_to_img2
, path_to_corrs_to_save
).
import os
rootdir = 'sample_project'
pairs = os.listdir(rootdir)
img_pairs_list = []
for p in pairs:
if p == '.DS_Store':
continue
cur_dir = os.path.join(rootdir, p)
img_pairs_list.append((os.path.join(cur_dir, '01.png'),
os.path.join(cur_dir, '02.png'),
os.path.join(cur_dir, 'corrs.txt')))
print (img_pairs_list)
Now we are ready to initialize CorrespondenceAnnotator
. Don't forget to declare magic command %matplotlib notebook
.
WITHOUT MAGIC IT WOULD NOT WORK
You also should explicitly specify, if you want to save (and possibly over-write previous better annotation) current correspondences automatically when clicking on prev and next buttons for going to the next pair.
%matplotlib notebook
from pixelstitch.core import *
CA = CorrespondenceAnnotator(img_pairs_list, save_on_next=True)
from IPython.core.display import display, HTML
display(HTML("<style>.container { width:95% !important; }</style>"))
CA.start(figsize=(12,7))
Model
. One can select between "F
" -- fundamental matrix and "H
" -- homography. The selection influences the reprojection error type, and the visualization of the models and reprojection errors, shown when clicked on NextCorrsValPoint
, NextCorrsValAll
and ShowModel
buttons.NextCorrsValPoint
. Shows the correspondence in the bottom axis. The image title shows correspondence index and the reprojection error. If Model
is F
, it will show induced epipolar line, if H
-- the position of the reprojected point from other image. The model is estimated with all other correspondences except current one.
NextCorrsValAll
. Shows the correspondences in the bottom axis. Similar to NextCorrsValPoint
button, but shows all points. The model is estimated with all correspondences except current one, which index is shown in the title.
ShowModel
. Has different behavoir depending on the Model
selected. For F
-- shows correspondences with their induced epipolar lines. Unlike NextCorrsValPoint
and NextCorrsValPoint
all correspondences are used for model estimation.
For H
, the button shows overlay of image 1 reprojected into image2 with image2. The reprojected area is defined by the convex hull of the labelled correspondences. Next click flips the order, i.e. shows the image 2 reprojected into image 1.
Save points
-- saves (overwrites) the correspondences into the text file.
Prev
-- Loads and shows previous image pair to label. If the CorrespondenceAnnotator
was initialized with save_on_next=True
, the current pair correspondences are saved before the switch. Change is not cyclical, so the button does nothing on 1st image pair
Next
-- Loads and shows next image pair to label. If the CorrespondenceAnnotator
was initialized with save_on_next=True
, the current pair correspondences are saved before the switch.Change is not cyclical, so the button does nothing on last image pair.
CLAHE
-- Images are shown with enhanced contrast with CLAHE algorithm.
Pick 4 points for homography
-- Special mode. User picks 4 points in one image, which define new fronto-parallel view. This mode helps for labeling obscure views, see example below. The order of the points: top-left -> top-right -> bottom right -> bottom left. After the 4 point picked, the mode is switched off, so user needs to click the button again if she wants to rectify another image.
ResetView
-- Resets any recifications or zoom done to images.
All points are selected and image1 is rectified to the rectangle, defined by the selected points


This theme features a flexible, UX friendly sidebar menu and stock photos from our friends at Unsplash !
What We OfferLooks great on any screen size!
Freshly redesigned for Bootstrap 5.
Millions of users Start Bootstrap!
I mustache you a question...


There are a number of introductory UNIX books that will acquaint you with sed and awk. The goal of this book is to take you much further - to help you master sed and awk and to reduce the amount of time and effort that it takes you to reach that goal.
There are four hurdles on the way to mastering sed and awk. You must learn:
How to use sed and awk. This is a relatively low hurdle to clear because, fortunately, sed and awk work in a very similar manner, based on the line editor ed. Chapter 2, Understanding Basic Operations, covers the mechanics of using sed and awk.
To apply UNIX regular expression syntax. Using UNIX regular expression syntax for pattern matching is common to both sed and awk, and many other UNIX programs. This can be a difficult hurdle for two reasons: the syntax is arcane, and though many people have some experience using regular expressions, few have persevered to master the complete syntax. The more facile you are in using this syntax, the easier sed and awk are to use. That is why we spend a good deal of time covering regular expressions in Chapter 3, Understanding Regular Expression Syntax.
How to interact with the shell. While not directly related to sed and awk themselves, managing the interaction with the command shell is often a frustrating problem, since the shell shares a number of special characters with both programs. If you can, avoid the problem by putting your script in a separate file. If not, use a Bourne-compatible shell for your scripts (the quoting rules are more straightforward), and use single quotes to contain your script. If you are using csh as your interactive shell, remember to escape any exclamation points with a backslash ("\!"). There is no other way to get csh to leave the exclamation point alone.[3]
[3] Well, you can set the
histchars
variable. See the csh man page.
The knack of script writing. This is the most difficult, rather like a series of high hurdles. Because of this, the bulk of the book is devoted to script writing. With sed, you have to learn a set of single-letter commands. With awk, you have to learn the statements of a programming language. To get the knack of script writing, though, you simply must pore over lots of examples and, of course, must try your hand at writing scripts yourself.
If you were running the high hurdles, the ability to clear the hurdles does not win the race - clearing them swiftly does. In writing scripts, learning the scripting command set or language is simply clearing the hurdle. Acquiring the ability to attack interesting problems with your scripts is running fast enough to compete.


Currently I'm studying as a information systems Student at
Faculdade de Informática e Administração Paulista.
one of my great abilities is to understand what the client want and what he need.
Being a Javascript Programmer, I love creating applications that are scalable and
efficient under the hood while providing engaging.
When I'm not in front of a computer screen
, I'm probably on the gym, watching movies, playing video Game,
or having some fun with my friends.
View My Resume!


|
||||||||
| PREV CLASS NEXT CLASS | FRAMES NO FRAMES | |||||||
| SUMMARY: NESTED | FIELD | CONSTR | METHOD | DETAIL: FIELD | CONSTR | METHOD |
java.lang.Object java.util.Calendar java.util.GregorianCalendar org.apache.xmlbeans.XmlCalendar
public class XmlCalendar
An XML Schema compatible subclass of GregorianCalendar
.
XmlCalendar modifies several key details in the behavior of
GregorianCalendar to make it more useful when dealing with XML dates.
It is easy to convert between XmlCalendar and GDate
, or to
parse or emit an XmlCalendar using a standard XML Schema
lexical representation.
GregorianCalendar
, which chooses 1970. The reason 0 is preferable
is that it is a leap year and so it permits the date --2-29 to be specified
stably. A different default year can be chosen via the static method
XmlCalendar.setDefaultYear()
, or by setting the
system property "user.defaultyear". If you do change this value, you should
pick another leap year such as 2000 and avoid non-leap years such as 1900.
TimeZone.getDefault()
if not.
For example, the XML timezone "Z" is translated to "GMT"; the XML timezone "+05:00" is translated to "GMT+05:00".
| Field Summary |
|---|
| Fields inherited from class java.util.GregorianCalendar |
|---|
AD, BC |
| Fields inherited from class java.util.Calendar |
|---|
ALL_STYLES, AM, AM_PM, APRIL, areFieldsSet, AUGUST, DATE, DAY_OF_MONTH, DAY_OF_WEEK, DAY_OF_WEEK_IN_MONTH, DAY_OF_YEAR, DECEMBER, DST_OFFSET, ERA, FEBRUARY, FIELD_COUNT, fields, FRIDAY, HOUR, HOUR_OF_DAY, isSet, isTimeSet, JANUARY, JULY, JUNE, LONG, MARCH, MAY, MILLISECOND, MINUTE, MONDAY, MONTH, NOVEMBER, OCTOBER, PM, SATURDAY, SECOND, SEPTEMBER, SHORT, SUNDAY, THURSDAY, time, TUESDAY, UNDECIMBER, WEDNESDAY, WEEK_OF_MONTH, WEEK_OF_YEAR, YEAR, ZONE_OFFSET |
| Constructor Summary | |
|---|---|
XmlCalendar()
Constructs an empty instance with no fields set. |
|
XmlCalendar(java.util.Date date)
Constructs an XmlCalendar from a Date. |
|
XmlCalendar(GDateSpecification date)
Constructs an XmlCalendar from a GDate. |
|
XmlCalendar(int year,
int month,
int day,
int hour,
int minute,
int second,
java.math.BigDecimal fraction)
Constructs an XmlCalendar with the specified year, month, day, hours, minutes, seconds, and optional fractional seconds, in the default timezone. |
|
XmlCalendar(int year,
int month,
int day,
int hour,
int minute,
int second,
java.math.BigDecimal fraction,
int tzSign,
int tzHour,
int tzMinute)
Constructs an XmlCalendar with the specified year, month, day, hours, minutes, seconds, and optional fractional seconds, in the specified timezone. |
|
XmlCalendar(java.lang.String xmlSchemaDateString)
Constructs an XmlCalendar for a standard XML schema formatted date string. |
| Method Summary | |
|---|---|
protected void |
computeTime()
Overrides GregorianCalendar.computeTime to apply a different default year. |
int |
get(int field)
Gets the value for a given time field. |
static int |
getDefaultYear()
Returns the default year that is used when no year is specified. |
static void |
setDefaultYear(int year)
Sets the default year to be used when no year is specified. |
java.lang.String |
toString()
Prints the XmlCalendar using a standard XML Schema format, as described in XmlCalendar(String s). |
| Methods inherited from class java.util.GregorianCalendar |
|---|
add, clone, computeFields, equals, getActualMaximum, getActualMinimum, getGreatestMinimum, getGregorianChange, getLeastMaximum, getMaximum, getMinimum, getTimeZone, hashCode, isLeapYear, roll, roll, setGregorianChange, setTimeZone |
| Methods inherited from class java.util.Calendar |
|---|
after, before, clear, clear, compareTo, complete, getAvailableLocales, getDisplayName, getDisplayNames, getFirstDayOfWeek, getInstance, getInstance, getInstance, getInstance, getMinimalDaysInFirstWeek, getTime, getTimeInMillis, internalGet, isLenient, isSet, set, set, set, set, setFirstDayOfWeek, setLenient, setMinimalDaysInFirstWeek, setTime, setTimeInMillis |
| Methods inherited from class java.lang.Object |
|---|
finalize, getClass, notify, notifyAll, wait, wait, wait |
| Constructor Detail |
|---|
public XmlCalendar(java.lang.String xmlSchemaDateString)
public XmlCalendar(GDateSpecification date)
public XmlCalendar(java.util.Date date)
public XmlCalendar(int year, int month, int day, int hour, int minute, int second, java.math.BigDecimal fraction)
public XmlCalendar(int year, int month, int day, int hour, int minute, int second, java.math.BigDecimal fraction, int tzSign, int tzHour, int tzMinute)
public XmlCalendar()
| Method Detail |
|---|
public int get(int field)
get
in class java.util.Calendar
public static int getDefaultYear()
public static void setDefaultYear(int year)
protected void computeTime()
computeTime
in class java.util.GregorianCalendar
public java.lang.String toString()
toString
in class java.util.Calendar
|
||||||||
| PREV CLASS NEXT CLASS | FRAMES NO FRAMES | |||||||
| SUMMARY: NESTED | FIELD | CONSTR | METHOD | DETAIL: FIELD | CONSTR | METHOD |


aiodocker: AsyncIO bindings for docker.io¶
A simple Docker HTTP API wrapper written with asyncio and aiohttp.
Installation¶
pip install aiodocker
Examples¶
import asyncio
import aiodocker
async def list_things():
docker = aiodocker.Docker()
print('== Images ==')
for image in (await docker.images.list()):
tags = image['RepoTags'][0] if image['RepoTags'] else ''
print(image['Id'], tags)
print('== Containers ==')
for container in (await docker.containers.list()):
print(f" {container._id}")
await docker.close()
async def run_container():
docker = aiodocker.Docker()
print('== Running a hello-world container ==')
container = await docker.containers.create_or_replace(
config={
'Cmd': ['/bin/ash', '-c', 'echo "hello world"'],
'Image': 'alpine:latest',
},
name='testing',
)
await container.start()
logs = await container.log(stdout=True)
print(''.join(logs))
await container.delete(force=True)
await docker.close()
if __name__ == '__main__':
loop = asyncio.get_event_loop()
loop.run_until_complete(list_things())
loop.run_until_complete(run_container())
loop.close()
Source code¶
The project is hosted on GitHub: https://github.com/aio-libs/aiodocker
Please feel free to file an issue on the bug tracker if you have found a bug or have some suggestion in order to improve the library.
Communication channels¶
aio-libs google group: https://groups.google.com/forum/#!forum/aio-libs
Feel free to post your questions and ideas here.
Gitter Chat https://gitter.im/aio-libs/Lobby
We support Stack Overflow. Please add python-asyncio tag to your question there.
Author and License¶
The aiodocker
package is written by Andrew Svetlov.
It’s Apache 2 licensed and freely available.


Last updated: April 24, 2019
These Terms and Conditions ("Terms", "Terms and Conditions") govern your relationship with https://chronicler.starchartlabs.org website (the "Service") operated by Chronicler ("us", "we", or "our").
Please read these Terms and Conditions carefully before using the Service.
Your access to and use of the Service is conditioned on your acceptance of and compliance with these Terms. These Terms apply to all visitors, users and others who access or use the Service.
By accessing or using the Service you agree to be bound by these Terms. If you disagree with any part of the terms then you may not access the Service.
Our Service may contain links to third-party web sites or services that are not owned or controlled by Chronicler.
Chronicler has no control over, and assumes no responsibility for, the content, privacy policies, or practices of any third party web sites or services. You further acknowledge and agree that Chronicler shall not be responsible or liable, directly or indirectly, for any damage or loss caused or alleged to be caused by or in connection with use of or reliance on any such content, goods or services available on or through any such web sites or services.
We strongly advise you to read the terms and conditions and privacy policies of any third-party web sites or services that you visit.
We may terminate or suspend your access immediately, without prior notice or liability, for any reason whatsoever, including without limitation if you breach the Terms.
Upon termination, your right to use the Service will immediately cease.
In no event shall Chronicler, nor its directors, employees, partners, agents, suppliers, or affiliates, be liable for any indirect, incidental, special, consequential or punitive damages, including without limitation, loss of profits, data, use, goodwill, or other intangible losses, resulting from (i) your access to or use of or inability to access or use the Service; (ii) any conduct or content of any third party on the Service; (iii) any content obtained from the Service; and (iv) unauthorized access, use or alteration of your transmissions or content, whether based on warranty, contract, tort (including negligence) or any other legal theory, whether or not we have been informed of the possibility of such damage, and even if a remedy set forth herein is found to have failed of its essential purpose.
Your use of the Service is at your sole risk. The Service is provided on an "AS IS" and "AS AVAILABLE" basis. The Service is provided without warranties of any kind, whether express or implied, including, but not limited to, implied warranties of merchantability, fitness for a particular purpose, non-infringement or course of performance.
Chronicler its subsidiaries, affiliates, and its licensors do not warrant that a) the Service will function uninterrupted, secure or available at any particular time or location; b) any errors or defects will be corrected; c) the Service is free of viruses or other harmful components; or d) the results of using the Service will meet your requirements.
These Terms shall be governed and construed in accordance with the laws of Massachusetts, United States, without regard to its conflict of law provisions.
Our failure to enforce any right or provision of these Terms will not be considered a waiver of those rights. If any provision of these Terms is held to be invalid or unenforceable by a court, the remaining provisions of these Terms will remain in effect. These Terms constitute the entire agreement between us regarding our Service, and supersede and replace any prior agreements we might have between us regarding the Service.
We reserve the right, at our sole discretion, to modify or replace these Terms at any time. If a revision is material we will try to provide at least 30 days notice prior to any new terms taking effect. What constitutes a material change will be determined at our sole discretion.
By continuing to access or use our Service after those revisions become effective, you agree to be bound by the revised terms. If you do not agree to the new terms, please stop using the Service.
If you have any questions about these Terms, please contact us.


| Package | flare.flex |
| Class | public class FlareVis |
| Inheritance | FlareVis mx.containers.Canvas |
Visualization
instance can always be
accessed using the visualization
property.
| Property | Defined by | ||
|---|---|---|---|
| axes : Axes
[read-only] Returns the axes for the backing visualization instance.
| FlareVis | ||
| controls : Array [write-only] The interactive controls used by this visualization.
| FlareVis | ||
| dataSet : * [write-only] Sets the data visualized by this instance.
| FlareVis | ||
| operators : Array [write-only] The visualization operators used by this visualization.
| FlareVis | ||
| visHeight : Number | FlareVis | ||
| visualization : Visualization
Returns the backing Flare visualization instance.
| FlareVis | ||
| visWidth : Number | FlareVis | ||
| xyAxes : CartesianAxes
[read-only] Returns the CartesianAxes for the backing visualization instance.
| FlareVis |
| Method | Defined by | ||
|---|---|---|---|
|
Creates a new FlareVis component.
| FlareVis |
| axes | property |
axes:Axes
[read-only]Returns the axes for the backing visualization instance.
Implementation public function get axes():Axes
| controls | property |
controls:Array
[write-only]The interactive controls used by this visualization. This should be an array of IControl instances.
Implementation public function set controls(value:Array):void
| dataSet | property |
dataSet:*
[write-only]Sets the data visualized by this instance. The input value can be an array of data objects, a Data instance, or a DataSet instance. Any existing data will be removed and new NodeSprite instances will be created for each object in the input arrary.
Implementation public function set dataSet(value:*):void
| operators | property |
operators:Array
[write-only]The visualization operators used by this visualization. This should be an array of IOperator instances.
Implementation public function set operators(value:Array):void
| visHeight | property |
visHeight:Number
[read-write]Implementation
public function get visHeight():Number
public function set visHeight(value:Number):void
| visualization | property |
visualization:Visualization
[read-write]Returns the backing Flare visualization instance.
Implementation public function get visualization():Visualization
public function set visualization(value:Visualization):void
| visWidth | property |
visWidth:Number
[read-write]Implementation
public function get visWidth():Number
public function set visWidth(value:Number):void
| xyAxes | property |
xyAxes:CartesianAxes
[read-only]Returns the CartesianAxes for the backing visualization instance.
Implementation public function get xyAxes():CartesianAxes
| FlareVis | () | constructor |
public function FlareVis(data:Data = null)
Creates a new FlareVis component. By default, a new visualization with an empty data set is created.
Parametersdata:Data (default = null ) — the data to visualize. If this value is null, a new
empty data instance will be used.
|


--- layout: post title: "The Week in Robots" date: 2016-06-11 08:35:00 +0000 tags: image: https://s3.amazonaws.com/audreywatters/2016-06-11-robot.jpg imagecredits: https://www.flickr.com/photos/jammind/2451193334 ---
Artificial intelligence is changing SEO faster than you think
E-Trade to Introduce Robo-Advisory Service
Stop the Bots From Killing Broadway
The amazing, shitty robots of Simone Giertz
Robots Are Invading Malls (and Sidewalks) Near You
Why I'm Not Worried About Robots (because privilege?)
NHS memo details Google/DeepMind's five year plan to bring AI to healthcare
Warning: Do not let a drone equipped with terrifying robo-scissors cut your hair
Drone Taxis? Nevada To Allow Testing Of Passenger Drone
Coder fired after 6 years for automating his job
The AI Machines Undergoing Behavioral Psychology Tests
Jobs Threatened by Machines: A Once ‘Stupid’ Concern Gains Respect
Do Robot Fireflies Dream of Electric Lights?
Voice (AI driven) – gift for teachers and learners?
Sunspring, A Sci-Fi Short Written by an Artificial Neural Network Starring Thomas Middleditch


--- layout: default title: Forks permalink: /housekeeping-abandoned-orgs ---
An organizations is considered abandoned if none of its repositories has received a push in the last year (ignoring archived repositories).
If the content still has value, then you could archive all repositories in these organizations to emphasize the fact that they are not maintained anymore. If the content is not valuable anymore, then you could delete the organization to reduce clutter on your GitHub Enterprise appliance.


Sat Dec 23, 2006
I don’t really post in here as often as in wordspace, and when I do the entries are mostly duplicated. To be honest, I’m having a little trouble posting pictures and videos in this journal, but I’d like to keep it alive. So, I’ve decided to post updates periodically, but you’re going to have to go to wordspace to read the actual entry. Sorry about that. If the entry is text only, chances are you can find it here too.
If you’re into it, here’s some permalinks to what you’ve missed this week…
Longest place name in the world
Grab some popcorn, grab your iPod
And, yay! I’ve finished my 500 page textbook. Just in time for Christmas.


HTML & CSS are like a loving couple, both partners together create a stable relationship. They share their lives with eachother - in style. They combine their passion for structure and for style. Both of them create the backend component; a static website.
JS creates the environment of excitement. It enables the fun, the movement, the adventure. It transforms the static webpage into more; into an interactive playground.
With JS in the air, both partners can create the unimagined .
With the help of control flow, everything is under control.
The JS structure guides us to the next river where a new adventure awaits.
But if we prefer a personalised adventure instead, we have the opportunity to take a loop.
The 'do/while' loop, can loop us through a block of code (exciting) for a certain number of times - "as long as the sun shines".
This can be handy when we plan to dry ourselves off, as we can interupt the js flow, the normal control flow.
Objects and Arrays have a little more complex data structure. They can be visualized as containers for other datatypes in JavaScript, thus the term: data structures.
An Object {in curly brackets} is similar to say a kayak, a gumboot, a truck. It can contain things (even other objects), and can be used for different purposes.
Arrays [in edgy brackets] don't take value pairs but can hold singular data in them.
Functions are little task descriptors. They can perform the particular task under normal "control flow", or if certain conditions are set. The great thing with functions is that we can call them repeatedly. The short descriptor saves us from rewriting the code.
The DOM (Document Object Model) is the playground where HTML and CSS surounded by the breeze of JS can come together to create. The DOM provides the main structure as it's sitting above the HTML, but below the window object. From here we can dig a little deeper.


--- layout: page title: About header-img: "img/about-bg.png" ---
I'm Emily Miles, a student at Flatiron School. I have been a project manager for over 10 years, and I am looking forward to getting my hands into some tech. Its time.


domosaics.ui.views.domainview.components
Class AngstdPolygon
java.lang.Object
java.awt.Polygon
domosaics.ui.views.domainview.components.AngstdPolygon
- All Implemented Interfaces:
- java.awt.Shape, java.io.Serializable
public class AngstdPolygon
- extends java.awt.Polygon
- See Also:
- Serialized Form
| Fields inherited from class java.awt.Polygon |
npoints, xpoints, ypoints |
|
Method Summary |
void |
init(int style)
|
void |
setPolygon(double x,
double y,
double width,
double height)
|
| Methods inherited from class java.awt.Polygon |
addPoint, contains, contains, contains, contains, contains, contains, getBoundingBox, getBounds, getBounds2D, getPathIterator, getPathIterator, inside, intersects, intersects, invalidate, reset, translate |
| Methods inherited from class java.lang.Object |
equals, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait |
TWOTRAP
public static final int TWOTRAP
- See Also:
- Constant Field Values
ARROW
public static final int ARROW
- See Also:
- Constant Field Values
RAGGED
public static final int RAGGED
- See Also:
- Constant Field Values
ZIGZAG
public static final int ZIGZAG
- See Also:
- Constant Field Values
HORSESHOE
public static final int HORSESHOE
- See Also:
- Constant Field Values
H
public static final int H
- See Also:
- Constant Field Values
MUSHROOM
public static final int MUSHROOM
- See Also:
- Constant Field Values
TETRIS
public static final int TETRIS
- See Also:
- Constant Field Values
DIAMOND
public static final int DIAMOND
- See Also:
- Constant Field Values
RHOMBOID
public static final int RHOMBOID
- See Also:
- Constant Field Values
RHOMBOID2
public static final int RHOMBOID2
- See Also:
- Constant Field Values
ARROW2
public static final int ARROW2
- See Also:
- Constant Field Values
PLUS
public static final int PLUS
- See Also:
- Constant Field Values
PENTAGON
public static final int PENTAGON
- See Also:
- Constant Field Values
HEXAGON
public static final int HEXAGON
- See Also:
- Constant Field Values
AngstdPolygon
public AngstdPolygon(int style)
setPolygon
public void setPolygon(double x,
double y,
double width,
double height)
init
public void init(int style)


PERSONA
PURPOSE:
To provide users with a shuffle of unique ideas for things to go out and
do with other individuals or as couples.
AUDIENCE:
Devices:
Phone-Samsung Note 10+, Computer-Samsung Note 9, Browser used:Chrome & Microsoft Edge
ATTITUDES/BEHAVIORS:
Works Monday-Friday has weekends off always. Has a fiance of 3 years.
Always looking for something new to do. Enjoys traveling with her partner.
shares custody with her son of 7 years old so keeping him occupied is very
important to her. She likes the outdoors. Has an artistic side. She likes
to drink wine with her fiance & friends. Loves food especially as well.
NEEDS/FRUSTRATIONS:
Kesha gets upset when she cant do something without spending too much money.
Hidden fees at locations are a bust. She likes it when other people
share deals or personal experience. Kesha becomes frustrated when she
cannot bring her son to certain locations. She likes family friendly
environments that keeps both adults and kids having fun. She is frustrated
when she does a search that gives her way too much content to read. She
wants something simple and fast that will give her just the information
she needs.
STORY
As a Date Night app user, Kesha would like all her current options at the
palm of her hand enstead of needing to google it and getting all kinds of
things to do that are not relevant to her liking nor in her city.
User Case
DATE-NIGHT
Preconditions:
Before Date Night, Kesha would google things to do on her regular samsung note 10+
browser. She would receive all these links to so many different websites. She would
have to load each page, if she had bad service, she would get frustrated and
close out and enter a new one.
Postconditions:
With Date Night, Kesha is able to simplify her search. Like and review her
previous interactions for others to see and for herself to see aswell.
She can limit all the links and just get the straight information that she needs.
She can look up ideas to spend time with her fiance or ideas to go out and do
family activities.
User Interaction Flow
- Navigate to Date-Night webpage.
- Login/sign up page comes up or proceed as guest
- User signs up with email & username
- User is directed to homepage
- Selects preference (Romantic or Friendly)
- Grant access to location
- Hit search
- Receive 1 result and its details
- Like/share it or click on try again
- If liked, share option will apear
- If re-shuffled stay on same page but brings up different result
- If user wants to view previous likes, navigates to drop-down on top right corner
- If proceed as guest
- Page directs to homepage without like/share option


Overview
Group Summary
4 Examples
#
Group
Duration
Pending
Failed
Passed
Status
1
Addition
31.10742
0
0
1
passed
2
Division
30.32206
0
0
1
passed
3
Multiplication
30.27946
0
0
1
passed
4
Subtraction
34.17462
0
1
0
failed


Contains functions to identify tree-ring borders based on X-ray micro-density profiles and a Graphical User Interface to visualize density profiles and correct tree-ring borders.
| Version: | 0.1.0 |
| Depends: | R (≥ 3.3) |
| Imports: | dplR, imager, tcltk2, tkRplotR |
| Suggests: | detrendeR |
| Published: | 2018-08-24 |
| Author: | Filipe Campelo and Konrad Mayer |
| Maintainer: | Filipe Campelo <fcampelo at ci.uc.pt> |
| License: | GPL-2 | GPL-3 [expanded from: GPL (≥ 2)] |
| NeedsCompilation: | no |
| CRAN checks: | xRing results |
| Reference manual: | xRing.pdf |
| Package source: | xRing_0.1.0.tar.gz |
| Windows binaries: | r-devel: xRing_0.1.0.zip, r-release: xRing_0.1.0.zip, r-oldrel: xRing_0.1.0.zip |
| OS X binaries: | r-release: xRing_0.1.0.tgz, r-oldrel: xRing_0.1.0.tgz |
Please use the canonical form https://CRAN.R-project.org/package=xRing to link to this page.


WITNESS LIST Nominations Committee March 21, 2005 - 2:00P Nomination to the Teacher Retirement System of Texas Board of Trustees FOR: Graham, John (Self), Frederericksburg, TX Henry, Mark Dr. (Self), Houston, TX Wiley, Dory (Self), Dallas, TX


Indicates GC causes that should not be triggered on a correctly sized application
Causes
- Metadata GC Threshold
- Ergonomics
How to resolve?
- Metadata GC Threshold: Set/Increase metaspace size with the following JVM options: -XX:MetaspaceSize=128M
- Ergonomics: Set/Increase initial heap space with the following JVM options: -Xms1G


All the following require a valid key parameter. Click on the links for an example response.
| What | URL pattern | Returns |
|---|---|---|
| Draft info: | {% url 'draftHost:api:draft' %} | Draft information, teams, picks |
| Your team: | {% url 'draftHost:api:current_team' %} | { name:"Your name", picks: [list of pick objects], players: [who you've drafted] } |
| Draft picks & selections: | {% url 'draftHost:api:picks' %} | picks & selections |
| Make a pick: | {% url 'draftHost:api:make_pick' 1623 %} | { code: pick status code, success: True or missing, message: human readable state, selection: fantasy selection object } |
| Player status in your draft: | {% url 'draftHost:api:player_status' 1623 %} | Returns the player object, including fantasy team if he's been picked. Use this if you want to check player availability before your turn! |


{% extends 'user_base.html' %} {% block user_action_title %} Password Reset Done {% endblock %} {% block user_action %} Password reset link sent {% endblock %} {% block body %}
We’ve emailed you instructions for setting your password, if an account exists with the email you entered. You should receive them shortly.
If you don’t receive an email, please make sure you’ve entered the address you registered with, and check your spam folder.


Crime Alert
menu
John Doe
<EMAIL_ADDRESS>first_page
Log Out
settings
Settings
location_on
View Map
edit
Report Crime
phone
Contact Police
Legend
Armed Robbery
Assault
Battery
Drugs
Hate Crime
Hit and Run
Homicide
Other
Rape
Theft
search
*Icon Legend in Side Menu
CMU Police have approved your crime report and updated the map.


To adjust the margin size apply one of the available divider-specific size classes. For example, simply using the class .divider-short
will reduce margin evenly above and below the divider.
| Class | Description |
|---|---|
.divider-flush
|
Remove the margin in one or both direction entirely. |
.divider-shorter
|
Reduce the margin in one or both direction to 25%. |
.divider-short
|
Reduce the margin in one or both direction to 50%. |
.divider-tall
|
Increase the margin in one or both direction to 150%. |
.divider-taller
|
Increase the margin in one or both direction to 200%. |

 …

Add -top
or -bottom
to the end of the size modifier class to adjust padding only in the direction implied by the direction modifier.
| Class | Description |
|---|---|
.divider-*-top
|
Adjust padding above the divider. |
.divider-*-bottom
|
Adjust padding below the divider. |

 …


PLOD - Brief Introduction
Enter search terms or a module, class or function name.
PLOD is a simpler and easier way to manipulate lists of dictionaries. PLOD stands for Pythonic Lists of Dictionaries.
Contents: