markdown stringlengths 0 37k | code stringlengths 1 33.3k | path stringlengths 8 215 | repo_name stringlengths 6 77 | license stringclasses 15
values |
|---|---|---|---|---|
We now create a different simulation from a snapshot in the SimulationArchive halfway through: | sim2, rebx = sa[500]
sim2.t | ipython_examples/SimulationArchive.ipynb | dtamayo/reboundx | gpl-3.0 |
We now integrate our loaded simulation to the same time as above (1.e6): | sim2.integrate(1.e6) | ipython_examples/SimulationArchive.ipynb | dtamayo/reboundx | gpl-3.0 |
and see that we obtain exactly the same particle positions in the original and reloaded simulations: | sim.status()
sim2.status() | ipython_examples/SimulationArchive.ipynb | dtamayo/reboundx | gpl-3.0 |
Using interact for animation with data
A soliton is a constant velocity wave that maintains its shape as it propagates. They arise from non-linear wave equations, such has the Korteweg–de Vries equation, which has the following analytical solution:
$$
\phi(x,t) = \frac{1}{2} c \mathrm{sech}^2 \left[ \frac{\sqrt{c}}{2} ... | def soliton(x, t, c, a):
"""Return phi(x, t) for a soliton wave with constants c and a."""
return 0.5*c*(1/(np.cosh((c**(1/2)/2)*(x-c*t-a))**2))
assert np.allclose(soliton(np.array([0]),0.0,1.0,0.0), np.array([0.5])) | assignments/assignment05/InteractEx03.ipynb | jegibbs/phys202-2015-work | mit |
Compute a 2d NumPy array called phi:
It should have a dtype of float.
It should have a shape of (xpoints, tpoints).
phi[i,j] should contain the value $\phi(x[i],t[j])$. | assert phi.shape==(xpoints, tpoints)
assert phi.ndim==2
assert phi.dtype==np.dtype(float)
assert phi[0,0]==soliton(x[0],t[0],c,a) | assignments/assignment05/InteractEx03.ipynb | jegibbs/phys202-2015-work | mit |
Write a plot_soliton_data(i) function that plots the soliton wave $\phi(x, t[i])$. Customize your plot to make it effective and beautiful. | def plot_soliton_data(i=0):
plot_soliton_data(0)
assert True # leave this for grading the plot_soliton_data function | assignments/assignment05/InteractEx03.ipynb | jegibbs/phys202-2015-work | mit |
variables
ATL-COM-PHYS-2017-079 (table 8, page 46)
|variable |type |n-tuple name |description |region >= 6j|region 5j|
|----------------------------------... | variables = [
"nElectrons",
"nMuons",
"nJets",
"nBTags_70",
"dRbb_avg_Sort4",
"dRbb_MaxPt_Sort4",
"dEtajj_MaxdEta",
"Mbb_MindR_Sort4",
"Mjj_MindR",
"nHiggsbb30_Sort4",
"HT_jets",
"dRlepbb_MindR_Sort4",
"Aplanarity_jets",
"H1_all",
"TTHReco_best_TTHReco",
"... | ttHbb_variables_preparation.ipynb | wdbm/abstraction | gpl-3.0 |
read | filenames_ttH = ["ttH_group.phys-higgs.11468583._000005.out.root"]
filenames_ttbb = ["ttbb_group.phys-higgs.11468624._000005.out.root"]
ttH = root_pandas.read_root(filenames_ttH, "nominal_Loose", columns = variables)
ttH["target"] = 1
ttH.head()
ttbb = root_pandas.read_root(filenames_ttbb, "nominal_Loose", columns... | ttHbb_variables_preparation.ipynb | wdbm/abstraction | gpl-3.0 |
characteristics | rows = []
for variable in df.columns.values:
rows.append({
"name": variable,
"maximum": df[variable].max(),
"minimum": df[variable].min(),
"mean": df[variable].mean(),
"median": df[variable].median(),
"std": df[variable].std()
})
_df = pd.DataFrame(rows... | ttHbb_variables_preparation.ipynb | wdbm/abstraction | gpl-3.0 |
imputation | df["TTHReco_best_TTHReco"].replace( -9, -1, inplace = True)
df["TTHReco_best_Higgs_mass"].replace( -9, -1, inplace = True)
df["TTHReco_best_Higgsbleptop_mass"].replace( -9, -1, inplace = True)
df["TTHReco_best_bbHiggs_dR"].replace( -9, -1, inplace = True)
df["TTHReco_withH_best_Higgsttbar_dR... | ttHbb_variables_preparation.ipynb | wdbm/abstraction | gpl-3.0 |
histograms | plt.rcParams["figure.figsize"] = (17, 14)
df.hist(); | ttHbb_variables_preparation.ipynb | wdbm/abstraction | gpl-3.0 |
correlations
correlations ${t\bar{t}H}$ | sns.heatmap(df.query("target == 1").drop("target", axis = 1).corr()); | ttHbb_variables_preparation.ipynb | wdbm/abstraction | gpl-3.0 |
correlations ${t\bar{t}b\bar{b}}$ | sns.heatmap(df.query("target == 0").drop("target", axis = 1).corr()); | ttHbb_variables_preparation.ipynb | wdbm/abstraction | gpl-3.0 |
ratio of correlations of ${t\bar{t}H}$ and ${t\bar{t}b\bar{b}}$ | _df = df.query("target == 1").drop("target", axis = 1).corr() / df.query("target == 0").drop("target", axis = 1).corr()
sns.heatmap(_df); | ttHbb_variables_preparation.ipynb | wdbm/abstraction | gpl-3.0 |
## clustered correlations | plot = sns.clustermap(df.corr())
plt.setp(plot.ax_heatmap.get_yticklabels(), rotation = 0); | ttHbb_variables_preparation.ipynb | wdbm/abstraction | gpl-3.0 |
strongest correlations and anticorrelations for discrimination of ${t\bar{t}H}$ and ${t\bar{t}b\bar{b}}$ | df.corr()["target"].sort_values(ascending = False).to_frame()[1:] | ttHbb_variables_preparation.ipynb | wdbm/abstraction | gpl-3.0 |
strongest absolute correlations for discrimination of ${t\bar{t}H}$ and ${t\bar{t}b\bar{b}}$ | df.corr()["target"].abs().sort_values(ascending = False).to_frame()[1:]
_df = df.corr()["target"].abs().sort_values(ascending = False).to_frame()[1:]
_df.plot(kind = "barh", legend = "False"); | ttHbb_variables_preparation.ipynb | wdbm/abstraction | gpl-3.0 |
clustered correlations of 10 strongest absolute correlations | names = df.corr()["target"].abs().sort_values(ascending = False)[1:11].index.values
plot = sns.clustermap(df[names].corr())
plt.setp(plot.ax_heatmap.get_yticklabels(), rotation = 0); | ttHbb_variables_preparation.ipynb | wdbm/abstraction | gpl-3.0 |
rescale | variables_rescale = [variable for variable in list(df.columns) if variable != "target"]
scaler = MinMaxScaler()
df[variables_rescale] = scaler.fit_transform(df[variables_rescale])
df.head() | ttHbb_variables_preparation.ipynb | wdbm/abstraction | gpl-3.0 |
save | df.to_csv("ttHbb_data.csv", index = False) | ttHbb_variables_preparation.ipynb | wdbm/abstraction | gpl-3.0 |
Start by finding structures using online databases (or cached local results). This uses an InChI for ethane to seed the molecule collection. | mol = oc.find_structure('InChI=1S/C2H6/c1-2/h1-2H3')
mol.structure.show() | girder/notebooks/notebooks/notebooks/NWChem.ipynb | OpenChemistry/mongochemserver | bsd-3-clause |
Set up the calculation, by specifying the name of the Docker image that will be used, and by providing input parameters that are known to the specific image | image_name = 'openchemistry/nwchem:6.6'
input_parameters = {
'theory': 'dft',
'functional': 'b3lyp',
'basis': '6-31g'
} | girder/notebooks/notebooks/notebooks/NWChem.ipynb | OpenChemistry/mongochemserver | bsd-3-clause |
Geometry Optimization Calculation
The mol.optimize() method is a specialized helper function that adds 'task': 'optimize' to the input_parameters dictionary,
and then calls the generic mol.calculate() method internally. | result = mol.optimize(image_name, input_parameters)
result.orbitals.show(mo='lumo', iso=0.005) | girder/notebooks/notebooks/notebooks/NWChem.ipynb | OpenChemistry/mongochemserver | bsd-3-clause |
Single Point Energy Calculation
The mol.energy() method is a specialized helper function that adds 'task': 'energy' to the input_parameters dictionary,
and then calls the generic mol.calculate() method internally. | result = mol.energy(image_name, input_parameters)
result.orbitals.show(mo='homo', iso=0.005) | girder/notebooks/notebooks/notebooks/NWChem.ipynb | OpenChemistry/mongochemserver | bsd-3-clause |
Lecture 11. Going fast: the Barnes-Hut algorithm
Previous lecture
Discretization of the integral equations, Galerkin methods
Computation of singular integrals
Idea of the Barnes-Hut method
Todays lecture
Barnes-Hut in details
The road to the FMM
Algebraic versions of the FMM/Fast Multipole
The discretization of the... | import numpy as np
import math
from numba import jit
N = 10000
x = np.random.randn(N, 2);
y = np.random.randn(N, 2);
charges = np.ones(N)
res = np.zeros(N)
@jit
def compute_nbody_direct(N, x, y, charges, res):
for i in xrange(N):
res[i] = 0.0
for j in xrange(N):
dist = (x[i, 0] - y[i, ... | lecture-11.ipynb | oseledets/fastpde | cc0-1.0 |
Question
What is the typical size of particle system?
Millenium run
One of the most famous N-body computations is the Millenium run
More than 10 billions particles ($2000^3$)
$>$ 1 month of computations, 25 Terabytes of storage
Each "particle" represents approximately a billion solar masses of dark matter
Study, how t... | from IPython.display import YouTubeVideo
YouTubeVideo('UC5pDPY5Nz4') | lecture-11.ipynb | oseledets/fastpde | cc0-1.0 |
Smoothed particle hydrodynamics
The particle systems can be used to model a lot of things.
For nice examples, see the website of Ron Fedkiw | from IPython.display import YouTubeVideo
YouTubeVideo('6bdIHFTfTdU') | lecture-11.ipynb | oseledets/fastpde | cc0-1.0 |
Applications
Where the N-body problem arises in different problems with long-range interactions`
- Cosmology (interacting masses)
- Electrostatics (interacting charges)
- Molecular dynamics (more complicated interactions, maybe even 3-4 body terms).
- Particle modelling (smoothed particle hydrodynamics)
Fast computatio... | from IPython.core.display import HTML
def css_styling():
styles = open("./styles/alex.css", "r").read()
return HTML(styles)
css_styling() | lecture-11.ipynb | oseledets/fastpde | cc0-1.0 |
I used 3 as the generator for this field. For a field defined with the polynomial x^8 + x^4 + x^3 + x + 1, there may be other generators (I can't remember) | generator = ff.GF2int(3)
generator | Generating the exponent and log tables.ipynb | lrq3000/unireedsolomon | mit |
We can enumerate the entire field by repeatedly multiplying by the generator. (The first element is 1 because generator^0 is 1). This becomes our exponent table. | exptable = [ff.GF2int(1), generator]
for _ in range(254): # minus 2 because the first 2 elements are hardcoded
exptable.append(exptable[-1].multiply(generator))
# Turn back to ints for a more compact print representation
print([int(x) for x in exptable]) | Generating the exponent and log tables.ipynb | lrq3000/unireedsolomon | mit |
That's now our exponent table. We can look up the nth element in this list to get generator^n | exptable[5] == generator**5
all(exptable[n] == generator**n for n in range(256))
[int(x) for x in exptable] == [int(x) for x in ff.GF2int_exptable] | Generating the exponent and log tables.ipynb | lrq3000/unireedsolomon | mit |
The log table is the inverse function of the exponent table | logtable = [None for _ in range(256)]
# Ignore the last element of the field because fields wrap back around.
# The log of 1 could be 0 (g^0=1) or it could be 255 (g^255=1)
for i, x in enumerate(exptable[:-1]):
logtable[x] = i
print([int(x) if x is not None else None for x in logtable])
[int(x) if x is not None el... | Generating the exponent and log tables.ipynb | lrq3000/unireedsolomon | mit |
Using the Metatab Package
The second way to access a package is to use the metatab package. This method requires installing the metatab python package, but has some important advantages: it gives you direct access to package and dataset documentation. You can load any type of metatab package with the open_package() fun... | import metatab
doc = metatab.open_package('http://s3.amazonaws.com/library.metatab.org/sandiegocounty.gov-adod-2012-sra-3.csv')
doc | users/eric/Metatab Package Example.ipynb | sandiegodata/age-friendly-communities | mit |
The .resource() method will return one of the resoruces. Displaying it shows the resoruce documentation. | r = doc.resource('adod-prevalence')
r | users/eric/Metatab Package Example.ipynb | sandiegodata/age-friendly-communities | mit |
Once you have a resource, use the .dataframe() method to get a Pandas dataframe. | df = r.dataframe()
df.head() | users/eric/Metatab Package Example.ipynb | sandiegodata/age-friendly-communities | mit |
24 Single-Source Shortest Paths
In a shortest-paths problem,
Given: a weighted, directed graph $G = (V, E)$, with weight function $w : E \to \mathcal{R}$.
path $p = < v_0, v_1, \dotsc, v_k >$, so
$$w(p) = \displaystyle \sum_{i=1}^k w(v_{i-1}, v_i)$$.
we define the shortest-path weight $\delta(u, v)$ from $u$ t... | plt.imshow(plt.imread('./res/bellman_ford.png'))
plt.imshow(plt.imread('./res/fig24_4.png')) | Introduction_to_Algorithms/24_Single-Source_Shortest_Paths/note.ipynb | facaiy/book_notes | cc0-1.0 |
24.2 Single-source shortest paths in directed acyclic graphs
By relaxing the edges of a weighted dag (directed acyclic graph) $G = (V, E)$ according to a topological sort of its vertices, we can compute shortest paths from a single source in $O(V + E)$ time. | plt.imshow(plt.imread('./res/dag.png'))
plt.imshow(plt.imread('./res/fig24_5.png')) | Introduction_to_Algorithms/24_Single-Source_Shortest_Paths/note.ipynb | facaiy/book_notes | cc0-1.0 |
interesting application: to determine critical paths in PERT chart analysis.
24.3 Dijkstra's algorithm (greedy strategy)
weighted, directed graph $G = (V, E)$ and all $w(u, v) \geq 0$.
Dijkstra's algorithm maintains a set $S$ of vertices whose final shortest-path weights from the source $s$ have already been determined... | plt.imshow(plt.imread('./res/dijkstra.png'))
plt.imshow(plt.imread('./res/fig24_6.png')) | Introduction_to_Algorithms/24_Single-Source_Shortest_Paths/note.ipynb | facaiy/book_notes | cc0-1.0 |
24.4 Difference constraints and shortest paths
Linear programming
Systems of difference constraints
In a system of difference constraints, each row of the linear-programming matrix $A$ contains one 1 and one -1, and all other entries of $A$ are 0. $\to$ the form $x_j - x_i \leq b_k$. | plt.imshow(plt.imread('./res/inequ.png')) | Introduction_to_Algorithms/24_Single-Source_Shortest_Paths/note.ipynb | facaiy/book_notes | cc0-1.0 |
Constraint graphs | plt.imshow(plt.imread('./res/fig24_8.png')) | Introduction_to_Algorithms/24_Single-Source_Shortest_Paths/note.ipynb | facaiy/book_notes | cc0-1.0 |
Compute statistic
To use an algorithm optimized for spatio-temporal clustering, we
just pass the spatial adjacency matrix (instead of spatio-temporal) | print('Computing adjacency.')
adjacency = spatial_src_adjacency(src)
# Note that X needs to be a list of multi-dimensional array of shape
# samples (subjects_k) × time × space, so we permute dimensions
X1 = np.transpose(X1, [2, 1, 0])
X2 = np.transpose(X2, [2, 1, 0])
X = [X1, X2]
# Now let's actually do the clu... | dev/_downloads/cfbef36033f8d33f28c4fe2cfa35314a/30_cluster_ftest_spatiotemporal.ipynb | mne-tools/mne-tools.github.io | bsd-3-clause |
Log posterior function
The log posterior function is the workhorse of the analysis. I implement it as a class that stores the observation data and the priors, contains the methods to calculate the model and evaluate the log posterior probability density, and encapsulates the optimisation and MCMC sampling routines. | class LPFunction:
def __init__(self, name: str, times: ndarray = None, fluxes: ndarray = None):
self.tm = QuadraticModel(klims=(0.05, 0.25), nk=512, nz=512)
# LPF name
# --------
self.name = name
# Declare high-level objects
# --------------------------
... | notebooks/01_broadband_parameter_estimation.ipynb | hpparvi/PyTransit | gpl-2.0 |
Priors
The priors are contained in a ParameterSet object from pytransit.param.parameter. ParameterSet is a utility class containing a function for calculating the joint prior, etc. We're using only two basic priors: a normal prior NP, for which $x \sim N(\mu,\sigma)$, a uniform prior UP, for which $x \sim U(a,b)$.
We c... | dfile = Path('data').joinpath('obs_data.fits')
data = pf.getdata(dfile, ext=1)
flux_keys = [n for n in data.names if 'f_wn' in n]
filter_names = [k.split('_')[-1] for k in flux_keys]
time = data['time'].astype('d')
fluxes = [data[k].astype('d') for k in flux_keys]
print ('Filter names: ' + ', '.join(filter_names)) | notebooks/01_broadband_parameter_estimation.ipynb | hpparvi/PyTransit | gpl-2.0 |
First, let's have a quick look at our data, and plot the blue- and redmost passbands. | with sb.axes_style('white'):
fig, axs = subplots(1,2, figsize=(13,5), sharey=True)
axs[0].plot(time,fluxes[0], drawstyle='steps-mid', c=cp[0])
axs[1].plot(time,fluxes[-1], drawstyle='steps-mid', c=cp[2])
setp(axs, xlim=time[[0,-1]])
fig.tight_layout() | notebooks/01_broadband_parameter_estimation.ipynb | hpparvi/PyTransit | gpl-2.0 |
Here we see what we'd expect to see. The stronger limb darkening in blue makes the bluemost transit round, while we can spot the end of ingress and the beginning of egress directly by eye from the redmost light curve. Also, the transit is deeper in u' than in Ks, which tells that the impact parameter b is smallish (the... | npop, de_iter, mc_reps, mc_iter, thin = 100, 200, 3, 500, 10
lpf = LPFunction('Ks', time, fluxes[-1])
lpf.optimize(de_iter, npop)
lpf.plot_light_curve();
for i in range(mc_reps):
lpf.sample(mc_iter, thin=thin, reset=True, label='MCMC sampling')
lpf.plot_light_curve('mc'); | notebooks/01_broadband_parameter_estimation.ipynb | hpparvi/PyTransit | gpl-2.0 |
Analysis: overview
The MCMC chains are now stored in lpf.sampler.chain. Let's first have a look into how the chain populations evolved to see if we have any problems with our setup, whether we have converged to sample the true posterior distribution, and, if so, what was the burn-in time. | with sb.axes_style('white'):
fig, axs = subplots(2,4, figsize=(13,5), sharex=True)
ls, lc = ['-','--','--'], ['k', '0.5', '0.5']
percs = [percentile(lpf.sampler.chain[:,:,i], [50,16,84], 0) for i in range(8)]
[axs.flat[i].plot(lpf.sampler.chain[:,:,i].T, 'k', alpha=0.01) for i in range(8)]
[[axs.fla... | notebooks/01_broadband_parameter_estimation.ipynb | hpparvi/PyTransit | gpl-2.0 |
Ok, everything looks good. The 16th, 50th and 84th percentiles of the parameter vector population are stable and don't show any significant long-term trends. Now we can flatten the individual chains into one long chain fc and calculate the median parameter vector. | fc = lpf.sampler.chain.reshape([-1,lpf.sampler.chain.shape[-1]])
mp = median(fc, 0) | notebooks/01_broadband_parameter_estimation.ipynb | hpparvi/PyTransit | gpl-2.0 |
Let's also plot the model and the data to see if this all makes sense. To do this, we calculate the conditional distribution of flux using the posterior samples (here, we're using a random subset of samples, although this isn't really necessary), and plot the distribution median and it's median-centred 68%, 95%, and 99... | flux_pr = lpf.flux_model(fc[permutation(fc.shape[0])[:1000]])
flux_pc = array(percentile(flux_pr, [50, 0.15,99.85, 2.5,97.5, 16,84], 0))
with sb.axes_style('white'):
zx1,zx2,zy1,zy2 = 0.958,0.98, 0.9892, 0.992
fig, ax = subplots(1,1, figsize=(13,4))
cp = sb.color_palette()
ax.errorbar(lpf.times, lpf.fl... | notebooks/01_broadband_parameter_estimation.ipynb | hpparvi/PyTransit | gpl-2.0 |
We could (should) also plot the residuals, but I've left them out from the plot for clarity. The plot looks fine, and we can continue to have a look at the parameter estimates.
Analysis
We start the analysis by making a Pandas data frame df, using the df.describe to gen an overview of the estimates, and plotting the po... | pd.set_option('display.precision',4)
df = pd.DataFrame(data=fc.copy(), columns=lpf.ps.names)
df['k'] = sqrt(df.k2)
df['u'] = 2*sqrt(df.q1)*df.q2
df['v'] = sqrt(df.q1)*(1-2*df.q2)
df = df.drop('k2', axis=1)
df.describe()
with sb.axes_style('white'):
fig, axs = subplots(2,3, figsize=(13,5))
pars = 'tc rho b k u ... | notebooks/01_broadband_parameter_estimation.ipynb | hpparvi/PyTransit | gpl-2.0 |
While we're at it, let's plot some correlation plots. The limb darkening coefficients are correlated, and we'd also expect to see a correlation between the impact parameter and radius ratio. | corner(df[['k', 'rho', 'b', 'q1', 'q2']]); | notebooks/01_broadband_parameter_estimation.ipynb | hpparvi/PyTransit | gpl-2.0 |
Calculating the parameter estimates for all the filters
Ok, now, let's do the parameter estimation for all the filters. We wouldn't be doing separate per-filter parameter estimation in real life, since it's much better use of the data to do a simultaneous joint modelling of all the data together (this is something that... | chains = []
npop, de_iter, mc_iter, mc_burn, thin = 100, 200, 1500, 1000, 10
for flux, pb in zip(fluxes, filter_names):
lpf = LPFunction(pb, time, flux)
lpf.optimize(de_iter, npop)
lpf.sample(mc_burn, thin=thin)
lpf.sample(mc_iter, thin=thin, reset=True)
chains.append(lpf.sampler.chain.reshape([-1,l... | notebooks/01_broadband_parameter_estimation.ipynb | hpparvi/PyTransit | gpl-2.0 |
The dataframe creation can probably be done in a nicer way, but we don't need to bother with that. The results are now in a multi-index dataframe, from where we can easily get the per-filter point estimates. | dft.loc['u'].describe()
with sb.axes_style('white'):
fig, axs = subplots(2,3, figsize=(13,6), sharex=True)
pars = 'tc rho u b k v'.split()
for i,p in enumerate(pars):
sb.violinplot(data=dft[p].unstack().T, inner='quartile', scale='width',
ax=axs.flat[i], order=filter_names)
... | notebooks/01_broadband_parameter_estimation.ipynb | hpparvi/PyTransit | gpl-2.0 |
As it is, the posterior distributions for different filters agree well with each other. However, the uncertainty in the radius ratio estimate decreases towards redder wavelengths. This is due to the reduced limb darkening, which allows us to estimate the true geometric radius ratio more accurately.
Finally, let's print... | def ms(df,p,f):
p = array(percentile(df[p][f], [50,16,84]))
return p[0], abs(p[1:]-p[0]).mean()
def create_row(df,f,pars):
return ('<tr><td>{:}</td>'.format(f)+
''.join(['<td>{:5.4f} ± {:5.4f}</td>'.format(*ms(dft,p,f)) for p in pars])+
'</tr>')
def create_table(df):
... | notebooks/01_broadband_parameter_estimation.ipynb | hpparvi/PyTransit | gpl-2.0 |
2-D Gaussian Shells
To demonstrate more of the functionality afforded by our different sampling/bounding options we will demonstrate how these various features work using a set of 2-D Gaussian shells with a uniform prior over $[-6, 6]$. | # defining constants
r = 2. # radius
w = 0.1 # width
c1 = np.array([-3.5, 0.]) # center of shell 1
c2 = np.array([3.5, 0.]) # center of shell 2
const = math.log(1. / math.sqrt(2. * math.pi * w**2)) # normalization constant
# log-likelihood of a single shell
def logcirc(theta, c):
d = np.sqrt(np.sum((theta - c... | demos/Examples -- Gaussian Shells.ipynb | joshspeagle/dynesty | mit |
Default Run
Let's first run with just the default set of dynesty options. | # run with all defaults
sampler = dynesty.DynamicNestedSampler(loglike, prior_transform, ndim=2, rstate=rstate)
sampler.run_nested()
res = sampler.results
from dynesty import plotting as dyplot
dyplot.cornerplot(sampler.results, span=([-6, 6], [-6, 6]), fig=plt.subplots(2, 2, figsize=(10, 10))); | demos/Examples -- Gaussian Shells.ipynb | joshspeagle/dynesty | mit |
Bounding Options
Let's test out the bounding options available in dynesty (with uniform sampling) on these 2-D shells. To illustrate their baseline effectiveness, we will also disable the initial delay before our first update. | # bounding methods
bounds = ['none', 'single', 'multi', 'balls', 'cubes']
# run over each method and collect our results
bounds_res = []
for b in bounds:
sampler = dynesty.NestedSampler(loglike, prior_transform, ndim=2,
bound=b, sample='unif', nlive=500,
... | demos/Examples -- Gaussian Shells.ipynb | joshspeagle/dynesty | mit |
We can see the amount of overhead associated with 'balls' and 'cubes' is non-trivial in this case. This mainly comes from sampling from our bouding distributions, since accepting or rejecting a point requires counting all neighbors within some radius $r$, leading to frequent nearest-neighbor searches.
Runtime aside, we... | from dynesty import plotting as dyplot
# initialize figure
fig, axes = plt.subplots(1, 1, figsize=(6, 6))
# plot proposals in corner format for 'none'
fg, ax = dyplot.cornerbound(bounds_res[0], it=2000, prior_transform=prior_transform,
show_live=True, fig=(fig, axes))
ax[0, 0].set_title('N... | demos/Examples -- Gaussian Shells.ipynb | joshspeagle/dynesty | mit |
Now let's examine the single and multi-ellipsoidal cases. | # initialize figure
fig, axes = plt.subplots(1, 3, figsize=(18, 6))
axes = axes.reshape((1, 3))
[a.set_frame_on(False) for a in axes[:, 1]]
[a.set_xticks([]) for a in axes[:, 1]]
[a.set_yticks([]) for a in axes[:, 1]]
# plot proposals in corner format for 'single'
fg, ax = dyplot.cornerbound(bounds_res[1], it=2000, pr... | demos/Examples -- Gaussian Shells.ipynb | joshspeagle/dynesty | mit |
Finally, let's take a look at our overlapping set of balls and cubes. | # initialize figure
fig, axes = plt.subplots(1, 3, figsize=(18, 6))
axes = axes.reshape((1, 3))
[a.set_frame_on(False) for a in axes[:, 1]]
[a.set_xticks([]) for a in axes[:, 1]]
[a.set_yticks([]) for a in axes[:, 1]]
# plot proposals in corner format for 'balls'
fg, ax = dyplot.cornerbound(bounds_res[3], it=1500, pri... | demos/Examples -- Gaussian Shells.ipynb | joshspeagle/dynesty | mit |
Bounding Objects
By default, the nested samplers in dynesty save all bounding distributions used throughout the course of a run, which can be accessed within the results dictionary. More information on these distributions can be found in bounding.py. | # the proposals associated with our 'multi' bounds
bounds_res[2].bound | demos/Examples -- Gaussian Shells.ipynb | joshspeagle/dynesty | mit |
Each bounding object has a host of additional functionality that the user can experiment with. For instance, the volume contained by the union of ellipsoids within MultiEllipsoid can be estimated using Monte Carlo integration (but otherwise are not computed by default). These volume estimates, combined with what fracti... | # compute effective 'single' volumes
single_logvols = [0.] # unit cube
for bound in bounds_res[1].bound[1:]:
logvol = bound.logvol # volume
funit = bound.unitcube_overlap(rstate=rstate) # fractional overlap with unit cube
single_logvols.append(logvol +np.log(funit))
single_logvols = np.array(single_logvol... | demos/Examples -- Gaussian Shells.ipynb | joshspeagle/dynesty | mit |
We see that in the beginning, only a single ellipsoid is used. After some bounding updates have been made, there is enough of an incentive to split the proposal into several ellipsoids. Although the initial ellipsoid decompositions can be somewhat unstable (i.e. bootstrapping can give relatively large volume expansion ... | # bounding methods
sampling = ['unif', 'rwalk', 'slice', 'rslice', 'hslice']
# run over each method and collect our results
sampling_res = []
for s in sampling:
sampler = dynesty.NestedSampler(loglike, prior_transform, ndim=2,
bound='multi', sample=s, nlive=1000,
... | demos/Examples -- Gaussian Shells.ipynb | joshspeagle/dynesty | mit |
As expected, uniform sampling in 2-D is substantially more efficient that other more complex alternatives (especially 'hslice', which is computing numerical gradients!). Regardless of runtime, however, we see that each method runs for a similar number of iterations and gives similar logz values (with comparable errors)... | # setup for running tests over gaussian shells in arbitrary dimensions
def run(ndim, bootstrap, bound, method, nlive):
"""Convenience function for running in any dimension."""
c1 = np.zeros(ndim)
c1[0] = -3.5
c2 = np.zeros(ndim)
c2[0] = 3.5
f = lambda theta: np.logaddexp(logcirc(theta, c1), log... | demos/Examples -- Gaussian Shells.ipynb | joshspeagle/dynesty | mit |
While our results are comparable between both cases, in higher dimensions multi-ellipsoid bounding distributions can sometimes be over-constrained, leading to biased results. Other sampling methods mitigate this problem by sampling conditioned on the ellipsoid axes, and so only depends on ellipsoid shapes, not sizes. '... | # adding on slice sampling
results3 = []
times3 = []
for ndim in ndims:
t0 = time.time()
sys.stderr.flush()
sys.stderr.write('{} dimensions:\n'.format(ndim))
sys.stderr.flush()
res = run(ndim, 0, 'multi', 'rslice', 2000)
sys.stderr.flush()
curdt = time.time() - t0
times3.append(curdt)
... | demos/Examples -- Gaussian Shells.ipynb | joshspeagle/dynesty | mit |
Refining the dataset
In this section, we add some additional time-based information to the DataFrame to accomplish our tasks.
Adding weekdays
First, we add the information about the weekdays based on the weekday_name information of the timestamp_local column. Because we want to preserve the order of the weekdays, we co... | import calendar
git_authors['weekday'] = git_authors["timestamp_local"].dt.weekday_name
git_authors['weekday'] = pd.Categorical(
git_authors['weekday'],
categories=calendar.day_name,
ordered=True)
git_authors.head() | notebooks/Developers' Habits (Linux Edition).ipynb | feststelltaste/software-analytics | gpl-3.0 |
Adding working hours
For the working hour analysis, we extract the hour information from the timestamp_local column.
Note: Again, we assume that every hour is in the dataset. | git_authors['hour'] = git_authors['timestamp_local'].dt.hour
git_authors.head() | notebooks/Developers' Habits (Linux Edition).ipynb | feststelltaste/software-analytics | gpl-3.0 |
Analyzing the data
With the prepared git_authors DataFrame, we are now able to deliver insights into the past years of development.
Developers' timezones
First, we want to know where the developers roughly live. For this, we plot the values of the timezone columns as a pie chart. | %matplotlib inline
timezones = git_authors['timezone'].value_counts()
timezones.plot(
kind='pie',
figsize=(7,7),
title="Developers' timezones",
label="") | notebooks/Developers' Habits (Linux Edition).ipynb | feststelltaste/software-analytics | gpl-3.0 |
Result
The majority of the developers' commits come from the time zones +0100, +0200 and -0700. With most commits coming probably from the West Coast of the USA, this might just be an indicator that Linus Torvalds lives there ;-) . But there are also many commits from developers within Western Europe.
Weekdays with the... | ax = git_authors['weekday'].\
value_counts(sort=False).\
plot(
kind='bar',
title="Commits per weekday")
ax.set_xlabel('weekday')
ax.set_ylabel('# commits') | notebooks/Developers' Habits (Linux Edition).ipynb | feststelltaste/software-analytics | gpl-3.0 |
Result
Most of the commits occur during normal working days with a slight peak on Wednesday. There are relatively few commits happening on weekends.
Working behavior of the main contributor
It would be very interesting and easy to see when Linus Torvalds (the main contributor to Linux) is working. But we won't do that... | ax = git_authors\
.groupby(['hour'])['author']\
.count().plot(kind='bar')
ax.set_title("Distribution of working hours")
ax.yaxis.set_label_text("# commits")
ax.xaxis.set_label_text("hour") | notebooks/Developers' Habits (Linux Edition).ipynb | feststelltaste/software-analytics | gpl-3.0 |
Result
The distribution of the working hours is interesting:
- First, we can clearly see that there is a dent around 12:00. So this might be an indicator that developers have lunch at regular times (which is a good thing IMHO).
- Another not so typical result is the slight rise after 20:00. This could be interpreted as... | latest_hour_per_week = git_authors.groupby(
[
pd.Grouper( key='timestamp_local', freq='1w'),
'author'
]
)[['hour']].max()
latest_hour_per_week.head() | notebooks/Developers' Habits (Linux Edition).ipynb | feststelltaste/software-analytics | gpl-3.0 |
Next, we want to know if there were any stressful time periods that forced the developers to work overtime over a longer period of time. We calculate the mean of all late stays of all authors for each week. | mean_latest_hours_per_week = \
latest_hour_per_week \
.reset_index().groupby('timestamp_local').mean()
mean_latest_hours_per_week.head() | notebooks/Developers' Habits (Linux Edition).ipynb | feststelltaste/software-analytics | gpl-3.0 |
We also create a trend line that shows how the contributors are working over the span of the past years. We use the polyfit function from numpy for this which needs a numeric index to calculate the polynomial coefficients later on. We then calculate the coefficients with a three-dimensional polynomial based on the hour... | import numpy as np
numeric_index = range(0, len(mean_latest_hours_per_week))
coefficients = np.polyfit(numeric_index, mean_latest_hours_per_week.hour, 3)
polynomial = np.poly1d(coefficients)
ys = polynomial(numeric_index)
mean_latest_hours_per_week['trend'] = ys
mean_latest_hours_per_week.head() | notebooks/Developers' Habits (Linux Edition).ipynb | feststelltaste/software-analytics | gpl-3.0 |
At last, we plot the hour results of the mean_latest_hours_per_week DataFrame as well as the trend data in one line plot. | ax = mean_latest_hours_per_week[['hour', 'trend']].plot(
figsize=(10, 6),
color=['grey','blue'],
title="Late hours per weeks")
ax.set_xlabel("time")
ax.set_ylabel("hour") | notebooks/Developers' Habits (Linux Edition).ipynb | feststelltaste/software-analytics | gpl-3.0 |
FLE
In this script the CONDENSATION is done for rightward and leftward motion of a dot stimulus, at different levels of noise. also for flashing stimuli needed for simulation of flash initiated and flash_terminated FLEs.
The aim is to generate generate (Berry et al 99)'s figure 2: shifting RF position in the direction... | %%writefile experiment_SI_controls.py
"""
A bunch of control runs
"""
import MotionParticlesFLE as mp
gen_dot = mp.generate_dot
import numpy as np
import os
from default_param import *
image = {}
experiment = 'SI'
N_scan = 5
base = 10.
#mp.N_trials = 4
for stimulus_tag, im_arg in zip(stim_labels, stim_args):
#for st... | notebooks/SI_controls.ipynb | laurentperrinet/Khoei_2017_PLoSCB | mit |
TODO : show results with a widget | !git commit -m' SI controls ' ../notebooks/SI_controls* ../scripts/experiment_SI_controls* | notebooks/SI_controls.ipynb | laurentperrinet/Khoei_2017_PLoSCB | mit |
Multi-layered perceptron (feed forward network)
Each hiden layer is formed by neurons called perceptrons
A perceptron is a binary linear classifier
inputs: a flat array $x_i$
one output per neuron j: $y_j$
a transformation of input into output (activation function):
linear separator
sigmoid function
$z_j= \sum_i ... | from IPython.display import Image
Image(url= "../img/perceptron.png", width=400, height=400) | day3/DL1_FFN.ipynb | grokkaine/biopycourse | cc0-1.0 |
input layer: sequential (flattened) image
hidden layers: perceptrons
output layer: softmax | from IPython.display import Image
Image(url= "../img/ffn.png", width=400, height=400)
from tensorflow.keras import models
from tensorflow.keras import layers
# defining the NN structure
network = models.Sequential()
network.add(layers.Dense(512, activation='sigmoid', input_shape=(28 * 28,)))
network.add(layers.Dense(... | day3/DL1_FFN.ipynb | grokkaine/biopycourse | cc0-1.0 |
Learning process
NNs are supervised learning structures!
- forward propagation: all training data is fed to the network and y is predicted
- estimate the loss: difference between prediction and label
- backpropagation: the loss information is propagated backwards layer by layer, and the neuron weights are adjusted
- gl... | from IPython.display import Image
Image(url= "../img/NN_learning.png", width=400, height=400) | day3/DL1_FFN.ipynb | grokkaine/biopycourse | cc0-1.0 |
Gradient descent (main optimization technique)
The weights in small increments with the help of the calculation of the derivative (or gradient) of the loss function, which allows us to see in which direction “to descend” towards the global minimum. Most optimizers are based on gradient descent, an algorithm that is ver... | network.fit(train_images, train_labels, epochs=5, batch_size=128)
test_loss, test_acc = network.evaluate(test_images, test_labels)
print(test_loss, test_acc) | day3/DL1_FFN.ipynb | grokkaine/biopycourse | cc0-1.0 |
Observations:
- slightly smaller accuracy on the test data compared to training data (model overfits on the training data)
Questions:
- Why do we need several epochs?
- What is the main computer limitation when it comes to batches?
- How many epochs are needed, and what is the danger associated with using too many or t... | import matplotlib.pyplot as plt
import numpy as np
prediction=network.predict(test_images[0:9])
y_true_cls = np.argmax(test_labels[0:9], axis=1)
y_pred_cls = np.argmax(prediction, axis=1)
fig, axes = plt.subplots(3, 3, figsize=(8,8))
fig.subplots_adjust(hspace=0.5, wspace=0.5)
for i, ax in enumerate(axes.flat):
ax... | day3/DL1_FFN.ipynb | grokkaine/biopycourse | cc0-1.0 |
Historical essentials
Deep learning, from an algorithmic perspective, is the application of advanced multi-layered filters to learn hidden features in data representation.
Many of the methods that are used today in DL, such as most neural network types (and not only), went through a 20 years long pause due to the fac... | import numpy as np
from keras.datasets import imdb
from keras import models
from keras import layers
from keras import optimizers
from keras import losses
from keras import metrics
(train_data, train_labels), (test_data, test_labels) = imdb.load_data(num_words=10000)
print(max([max(sequence) for sequence in train_data... | day3/DL1_FFN.ipynb | grokkaine/biopycourse | cc0-1.0 |
Let us set up the problem, discretization and solver details. The number of divisions along each dimension is given as a power of two function of the number of levels. In principle this is not required, but having it makes the inter-grid transfers easy.
The coarsest problem is going to have a 2-by-2 grid. | #input
max_cycles = 30
nlevels = 6
NX = 2*2**(nlevels-1)
NY = 2*2**(nlevels-1)
tol = 1e-15
#the grid has one layer of ghost cellss
uann=np.zeros([NX+2,NY+2])#analytical solution
u =np.zeros([NX+2,NY+2])#approximation
f =np.zeros([NX+2,NY+2])#RHS
#calcualte the RHS and exact solut... | .ipynb_checkpoints/Making_a_Preconditioner-vectorized-checkpoint.ipynb | AbhilashReddyM/GeometricMultigrid | mit |
Lets look at what happens with and without the preconditioner. | A = Laplace(NX,NY)
#Exact solution and RHS
uex=np.random.rand(NX*NY,1)
b=A*uex
#Multigrid Preconditioner
M=MGVP(NX,NY,nlevels)
u,info,iters=solve_sparse(bicgstab,A,b,tol=1e-10,maxiter=500)
print('Without preconditioning. status:',info,', Iters: ',iters)
error=uex-u
print('error :',np.max(np.abs(error)))
u,info,iters... | .ipynb_checkpoints/Making_a_Preconditioner-vectorized-checkpoint.ipynb | AbhilashReddyM/GeometricMultigrid | mit |
Without the preconditioner ~150 iterations were needed, where as with the V-cycle preconditioner the solution was obtained in far fewer iterations. Let's try with CG: | u,info,iters=solve_sparse(cg,A,b,tol=1e-10,maxiter=500)
print('Without preconditioning. status:',info,', Iters: ',iters)
error=uex-u
print('error :',np.max(np.abs(error)))
u,info,iters=solve_sparse(cg,A,b,tol=1e-10,maxiter=500,M=M)
print('With preconditioning. status:',info,', Iters: ',iters)
error=uex-u
print('error ... | .ipynb_checkpoints/Making_a_Preconditioner-vectorized-checkpoint.ipynb | AbhilashReddyM/GeometricMultigrid | mit |
Load raw data | df = pd.read_stata('/gh/data/hcmst/1.dta')
# df2 = pd.read_stata('/gh/data/hcmst/2.dta')
# df3 = pd.read_stata('/gh/data/hcmst/3.dta')
# df = df1.merge(df2, on='caseid_new')
# df = df.merge(df3, on='caseid_new')
df.head(2) | hcmst/process_raw_data.ipynb | srcole/qwm | mit |
Select and rename columns | rename_cols_dict = {'ppage': 'age', 'ppeducat': 'education',
'ppethm': 'race', 'ppgender': 'sex',
'pphouseholdsize': 'household_size', 'pphouse': 'house_type',
'hhinc': 'income', 'ppmarit': 'marital_status',
'ppmsacat': 'in_metro', 'ppreg4': 'u... | hcmst/process_raw_data.ipynb | srcole/qwm | mit |
Distributions | for c in df.columns:
print(df[c].value_counts())
# Countplot if categorical; distplot if numeric
from pandas.api.types import is_numeric_dtype
plt.figure(figsize=(40,40))
for i, c in enumerate(df.columns):
plt.subplot(7,7,i+1)
if is_numeric_dtype(df[c]):
sns.distplot(df[c].dropna(), kde=False)
... | hcmst/process_raw_data.ipynb | srcole/qwm | mit |
Since Series and DataFrame are used frequently, they should be imported directly by name.
Panda Data Structures
Series
A Series is basically a one-dimensional array with indices.
You create a simplest Series like this: | ps = Series([4,2,1,3])
print ps | pandas/Learn-Pandas-Completely.ipynb | minhhh/charts | mit |
Get values and indeces like this: | print ps.values
print ps.index
ps[0] | pandas/Learn-Pandas-Completely.ipynb | minhhh/charts | mit |
To use a custom index, do this: | ps2 = Series([4, 7, -1, 8], ['a','b','c','d'])
ps2 | pandas/Learn-Pandas-Completely.ipynb | minhhh/charts | mit |
Often, you want to create Series from python dict | ps3 = {'Ohio': 35000, 'Texas': 71000, 'Oregon': 16000, 'Utah': 5000}
ps3 | pandas/Learn-Pandas-Completely.ipynb | minhhh/charts | mit |
DataFrame
A DataFrame represents a tabular structure. It can be thought of as a dict of Series.
A DataFrame can be constructed from a dict of equal-length lists | data = {'state': ['Ohio', 'Ohio', 'Ohio', 'Nevada', 'Nevada'], 'year': [2000, 2001, 2002, 2001, 2002],
'pop': [1.5, 1.7, 3.6, 2.4, 2.9]}
df = DataFrame(data)
df | pandas/Learn-Pandas-Completely.ipynb | minhhh/charts | mit |
You can specify a sequence of columns like so: | DataFrame(data, columns=['year', 'state', 'pop']) | pandas/Learn-Pandas-Completely.ipynb | minhhh/charts | mit |
In addition to index and values, DataFrame has columns | print df.index
print
print df.values
print
print df.columns | pandas/Learn-Pandas-Completely.ipynb | minhhh/charts | mit |
You can get a specific column like this: | df['state'] | pandas/Learn-Pandas-Completely.ipynb | minhhh/charts | mit |
Rows can be retrieved using the ix method: | df.ix[0] | pandas/Learn-Pandas-Completely.ipynb | minhhh/charts | mit |
Another common form of data to create DataFrame is a nested dict of dicts OR nested dict of Series: | pop = {'Nevada': {2001: 2.4, 2002: 2.9}, 'Ohio': {2000: 1.5, 2001: 1.7, 2002: 3.6}}
df2 = DataFrame(pop)
df2 | pandas/Learn-Pandas-Completely.ipynb | minhhh/charts | mit |
You can pass explicit index when creating DataFrame: | df3=DataFrame(pop, index=[2001, 2002, 2003])
df3 | pandas/Learn-Pandas-Completely.ipynb | minhhh/charts | mit |
If a DataFrame’s index and columns have their name attributes set, these will also be displayed: | df2.index.name = 'year'
df2.columns.name = 'state'
df2 | pandas/Learn-Pandas-Completely.ipynb | minhhh/charts | mit |
The 3rd common data input structures is a list of dicts or Series: | films = [{'star': 9.3, 'title': 'The Shawshank Redemption', 'content_rating': 'R'},
{'star': 9.2, 'title': 'The Godfather', 'content_rating': 'R'},
{'star': 9.1, 'title': 'The Godfather: Part II', 'content_rating': 'R'}
]
df3 = DataFrame(f... | pandas/Learn-Pandas-Completely.ipynb | minhhh/charts | mit |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.