├── models
├── __init__.py
├── gaussian.py
├── model_weinberg_yadage.py
├── model_weinberg.py
├── model_weinberg_yadage_full.py
├── model_gaussian.py
├── weinberg.py
├── yadage_sim_local.py
└── yadage_sim_distributed.py
├── workflows
├── localflow
│ ├── .gitignore
│ ├── fastweinberg
│ │ ├── __init__.py
│ │ ├── .gitignore
│ │ ├── main.py
│ │ └── weinberg.py
│ ├── workdir
│ │ ├── detsim
│ │ │ ├── out.np
│ │ │ └── _packtivity
│ │ │ │ └── detsim.step.log
│ │ ├── recontructiona
│ │ │ ├── out.np
│ │ │ └── _packtivity
│ │ │ │ └── recontructiona.step.log
│ │ ├── feature_extraction
│ │ │ ├── out.np
│ │ │ └── _packtivity
│ │ │ │ └── feature_extraction.step.log
│ │ ├── generate
│ │ │ ├── out.np
│ │ │ └── _packtivity
│ │ │ │ └── generate.step.log
│ │ ├── _adage
│ │ │ ├── workflow.gif
│ │ │ └── adagesnap.txt
│ │ └── _yadage
│ │ │ ├── yadage_workflow_instance.pdf
│ │ │ ├── yadage_workflow_instance.png
│ │ │ ├── yadage_snapshot_backend.json
│ │ │ ├── yadage_template.json
│ │ │ ├── yadage_workflow_instance.dot
│ │ │ └── yadage_snapshot_workflow.json
│ ├── setup.py
│ └── workflow
│ │ ├── steps.yml
│ │ ├── workflow.yml
│ │ └── workflow_delay.yml
└── codes
│ ├── simulator.py
│ ├── Dockerfile
│ ├── workflow.yml
│ ├── steps.yml
│ └── weinberg.py
├── A_fb.png
├── .dockerignore
├── flowchart.pdf
├── flowchart.png
├── .gitignore
├── requirements.txt
├── eig_widget.py
├── yadage.yml
├── bayesopt.py
├── Dockerfile
├── science_loop_widget.py
├── plots.py
├── yadage_widget.py
├── yadage.js
├── distr.py
├── README.md
├── what.ipynb
├── common.py
└── demo_weinberg_yadage_full.ipynb
/models/__init__.py:
--------------------------------------------------------------------------------
1 |
--------------------------------------------------------------------------------
/workflows/localflow/.gitignore:
--------------------------------------------------------------------------------
1 | *.egg*
2 |
--------------------------------------------------------------------------------
/workflows/localflow/fastweinberg/__init__.py:
--------------------------------------------------------------------------------
1 |
--------------------------------------------------------------------------------
/workflows/codes/simulator.py:
--------------------------------------------------------------------------------
1 | import weinberg
2 |
3 |
--------------------------------------------------------------------------------
/workflows/localflow/fastweinberg/.gitignore:
--------------------------------------------------------------------------------
1 | *.pyc
2 |
--------------------------------------------------------------------------------
/A_fb.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/cranmer/active_sciencing/master/A_fb.png
--------------------------------------------------------------------------------
/.dockerignore:
--------------------------------------------------------------------------------
1 | venv
2 | *.pyc
3 | .ipynb_checkpoints/*
4 | Untitled*.ipynb
5 | tmp*
6 |
--------------------------------------------------------------------------------
/flowchart.pdf:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/cranmer/active_sciencing/master/flowchart.pdf
--------------------------------------------------------------------------------
/flowchart.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/cranmer/active_sciencing/master/flowchart.png
--------------------------------------------------------------------------------
/workflows/codes/Dockerfile:
--------------------------------------------------------------------------------
1 | FROM python:2.7
2 | RUN pip install numpy
3 | ADD . /code
4 | WORKDIR /code
5 |
--------------------------------------------------------------------------------
/workflows/localflow/workdir/detsim/out.np:
--------------------------------------------------------------------------------
1 | /Users/lukas/Code/active_sciencing/workflows/localflow/workdir/generate/out.np
--------------------------------------------------------------------------------
/.gitignore:
--------------------------------------------------------------------------------
1 | venv
2 | *.pyc
3 | .ipynb_checkpoints/*
4 | __pycache__/prior_dist.cpython-35.pyc
5 | Untitled*.ipynb
6 | tmp*
7 |
--------------------------------------------------------------------------------
/workflows/localflow/workdir/recontructiona/out.np:
--------------------------------------------------------------------------------
1 | /Users/lukas/Code/active_sciencing/workflows/localflow/workdir/detsim/out.np
--------------------------------------------------------------------------------
/requirements.txt:
--------------------------------------------------------------------------------
1 | jupyter
2 | matplotlib
3 | scipy
4 | numpy
5 | scikit-optimize
6 | emcee
7 | yadage
8 | celery
9 | redis
10 |
--------------------------------------------------------------------------------
/workflows/localflow/workdir/feature_extraction/out.np:
--------------------------------------------------------------------------------
1 | /Users/lukas/Code/active_sciencing/workflows/localflow/workdir/recontructiona/out.np
--------------------------------------------------------------------------------
/workflows/localflow/workdir/generate/out.np:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/cranmer/active_sciencing/master/workflows/localflow/workdir/generate/out.np
--------------------------------------------------------------------------------
/workflows/localflow/workdir/_adage/workflow.gif:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/cranmer/active_sciencing/master/workflows/localflow/workdir/_adage/workflow.gif
--------------------------------------------------------------------------------
/workflows/localflow/workdir/_yadage/yadage_workflow_instance.pdf:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/cranmer/active_sciencing/master/workflows/localflow/workdir/_yadage/yadage_workflow_instance.pdf
--------------------------------------------------------------------------------
/workflows/localflow/workdir/_yadage/yadage_workflow_instance.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/cranmer/active_sciencing/master/workflows/localflow/workdir/_yadage/yadage_workflow_instance.png
--------------------------------------------------------------------------------
/eig_widget.py:
--------------------------------------------------------------------------------
1 | from ipywidgets import widgets
2 | def widget():
3 | single_progress = widgets.IntProgress(min = 0, max = 10, description = 'Calculating EIG: ')
4 | overall_progress = widgets.IntProgress(min = 0, max = 10, description = 'EIG Progress : ')
5 | return widgets.VBox([single_progress, overall_progress])
6 |
--------------------------------------------------------------------------------
/workflows/codes/workflow.yml:
--------------------------------------------------------------------------------
1 | stages:
2 | - name: generate
3 | dependencies: [init]
4 | scheduler:
5 | scheduler_type: singlestep-stage
6 | parameters:
7 | theta: {stages: init, output: theta, unwrap: true}
8 | phi: {stages: init, output: phi, unwrap: true}
9 | n_samples: {stages: init, output: n_samples, unwrap: true}
10 | outfile: '{workdir}/out.np'
11 | step: {$ref: 'steps.yml#/weinberg'}
--------------------------------------------------------------------------------
/models/gaussian.py:
--------------------------------------------------------------------------------
1 | import numpy as np
2 | import sys
3 | import time
4 | import random
5 |
6 | def simulator(theta,phi,n_samples, widget = None, delay = False):
7 | samples = np.random.normal(loc = theta, scale = 2+np.cos(phi), size = n_samples)
8 | if delay:
9 | widget.value = 0
10 | for i in range(widget.max):
11 | time.sleep(random.random())
12 | widget.value = widget.value + 1
13 | return samples
14 |
--------------------------------------------------------------------------------
/yadage.yml:
--------------------------------------------------------------------------------
1 | toplevel: github:lukasheinrich/weinberg-exp:example_yadage
2 | workflow: rootflow.yml
3 | outputs: merge/out.jsonl
4 | archive: https://raw.githubusercontent.com/lukasheinrich/weinberg-exp/master/example_yadage/input.zip
5 | pars:
6 | nevents: 10000
7 | seeds: [1,2,3,4]
8 | runcardtempl: run_card.templ
9 | proccardtempl: sm_proc_card.templ
10 | sqrtshalf: 45
11 | polbeam1: 0
12 | polbeam2: 0
13 | Gf: 1.766390e-05
14 | paramcardtempl: param_card.templ
15 |
--------------------------------------------------------------------------------
/workflows/codes/steps.yml:
--------------------------------------------------------------------------------
1 | weinberg:
2 | process:
3 | process_type: interpolated-script-cmd
4 | interpreter: python
5 | script: |
6 | import weinberg
7 | import numpy as np
8 |
9 | data = weinberg.simulator(theta = {theta}, phi = {phi}, n_samples = {n_samples})
10 | np.save(open('{outfile}','w'), data)
11 | environment:
12 | environment_type: docker-encapsulated
13 | image: lukasheinrich/ycomb_fastweinberg
14 | publisher:
15 | publisher_type: 'frompar-pub'
16 | outputmap:
17 | outfile: 'outfile'
18 |
--------------------------------------------------------------------------------
/workflows/localflow/setup.py:
--------------------------------------------------------------------------------
1 |
2 | import os
3 | from setuptools import setup, find_packages
4 |
5 | setup(
6 | name = 'fast-weinberg',
7 | version = '0.0.1',
8 | description = 'fast approximation of weinberg madgraph workflow',
9 | url = '',
10 | author = 'Lukas Heinrich',
11 | author_email = 'lukas.heinrich@cern.ch',
12 | packages = find_packages(),
13 | include_package_data = True,
14 | install_requires = [],
15 | entry_points = {
16 | 'console_scripts': [
17 | 'weinberg-fast=fastweinberg.main:main',
18 | ],
19 | }
20 | )
21 |
--------------------------------------------------------------------------------
/workflows/localflow/fastweinberg/main.py:
--------------------------------------------------------------------------------
1 | import weinberg
2 | import numpy as np
3 | import sys
4 | import time
5 |
6 | def main():
7 | theta = float(sys.argv[1])
8 | phi = float(sys.argv[2])
9 | n_samples = int(sys.argv[3])
10 |
11 |
12 | try:
13 | mean = float(sys.argv[5])
14 | if mean:
15 | random_delay = np.random.normal(mean)
16 | print 'random',random_delay
17 | time.sleep(random_delay)
18 | except IndexError:
19 | pass
20 |
21 | outfile = sys.argv[4]
22 | data = weinberg.simulator(theta = theta, phi = phi, n_samples = n_samples)
23 | np.save(open(outfile,'w'), data)
24 |
25 | if __name__ == '__main__':
26 | main()
27 |
--------------------------------------------------------------------------------
/workflows/localflow/workdir/generate/_packtivity/generate.step.log:
--------------------------------------------------------------------------------
1 | 2017-06-08 22:14:59,562 - packtivity_logger_generate.step - INFO - running local command weinberg-fast 42 1.0 100 /Users/lukas/Code/active_sciencing/workflows/localflow/workdir/generate/out.np
2 | 2017-06-08 22:14:59,562 - packtivity_logger_generate.step - INFO - changing to workdirectory /Users/lukas/Code/active_sciencing/workflows/localflow/workdir/generate
3 | 2017-06-08 22:15:00,086 - packtivity_logger_generate.step - INFO - changing back to original directory /Users/lukas/Code/active_sciencing/workflows/localflow
4 | 2017-06-08 22:15:00,092 - packtivity_logger_generate.step - INFO - publishing data: {'outfile': '/Users/lukas/Code/active_sciencing/workflows/localflow/workdir/generate/out.np'}
5 |
--------------------------------------------------------------------------------
/workflows/localflow/workdir/detsim/_packtivity/detsim.step.log:
--------------------------------------------------------------------------------
1 | 2017-06-08 22:15:00,117 - packtivity_logger_detsim.step - INFO - running local command ln -s /Users/lukas/Code/active_sciencing/workflows/localflow/workdir/generate/out.np /Users/lukas/Code/active_sciencing/workflows/localflow/workdir/detsim/out.np
2 | 2017-06-08 22:15:00,117 - packtivity_logger_detsim.step - INFO - changing to workdirectory /Users/lukas/Code/active_sciencing/workflows/localflow/workdir/detsim
3 | 2017-06-08 22:15:00,130 - packtivity_logger_detsim.step - INFO - changing back to original directory /Users/lukas/Code/active_sciencing/workflows/localflow
4 | 2017-06-08 22:15:00,136 - packtivity_logger_detsim.step - INFO - publishing data: {'outfile': '/Users/lukas/Code/active_sciencing/workflows/localflow/workdir/detsim/out.np'}
5 |
--------------------------------------------------------------------------------
/workflows/localflow/workdir/_yadage/yadage_snapshot_backend.json:
--------------------------------------------------------------------------------
1 | {"5c1139745c6f31114ecddc63a402557e9a006e67": {"status": "SUCCESS", "result": {"outfile": "/Users/lukas/Code/active_sciencing/workflows/localflow/workdir/feature_extraction/out.np"}}, "5abccf6823d64bdecc4a6c25038dd9fd30e7a8fd": {"status": "SUCCESS", "result": {"theta": 1.0, "phi": 42, "n_samples": 100}}, "1419713e4025a908173cf21991b443e58a1be4aa": {"status": "SUCCESS", "result": {"outfile": "/Users/lukas/Code/active_sciencing/workflows/localflow/workdir/generate/out.np"}}, "0483a180e42a866615a6a886257f54619f39581e": {"status": "SUCCESS", "result": {"outfile": "/Users/lukas/Code/active_sciencing/workflows/localflow/workdir/detsim/out.np"}}, "a8e8d2f9d5963831f538607a833ff6af1ba69c24": {"status": "SUCCESS", "result": {"outfile": "/Users/lukas/Code/active_sciencing/workflows/localflow/workdir/recontructiona/out.np"}}}
--------------------------------------------------------------------------------
/workflows/localflow/workdir/recontructiona/_packtivity/recontructiona.step.log:
--------------------------------------------------------------------------------
1 | 2017-06-08 22:15:00,164 - packtivity_logger_recontructiona.step - INFO - running local command ln -s /Users/lukas/Code/active_sciencing/workflows/localflow/workdir/detsim/out.np /Users/lukas/Code/active_sciencing/workflows/localflow/workdir/recontructiona/out.np
2 | 2017-06-08 22:15:00,165 - packtivity_logger_recontructiona.step - INFO - changing to workdirectory /Users/lukas/Code/active_sciencing/workflows/localflow/workdir/recontructiona
3 | 2017-06-08 22:15:00,182 - packtivity_logger_recontructiona.step - INFO - changing back to original directory /Users/lukas/Code/active_sciencing/workflows/localflow
4 | 2017-06-08 22:15:00,189 - packtivity_logger_recontructiona.step - INFO - publishing data: {'outfile': '/Users/lukas/Code/active_sciencing/workflows/localflow/workdir/recontructiona/out.np'}
5 |
--------------------------------------------------------------------------------
/models/model_weinberg_yadage.py:
--------------------------------------------------------------------------------
1 | import math
2 | import yadage_sim_local
3 | import yadage_widget
4 |
5 | name = 'weinberg_yadage'
6 |
7 | phi_range = [40.,50.]
8 | theta_range = [0.5,1.5]
9 | data_range = [-1,1]
10 | simulator = yadage_sim_local.simulator
11 |
12 | details_shifts = [-2.,2.]
13 | details_mirror = True
14 | details_lnlike_nsim = 1000
15 | details_map_bins = 20
16 | details_likelihood_settings = {
17 | 'simulator': simulator,
18 | 'simulation_kwargs': {'n_samples': 200},
19 | 'distr_kwargs': {'range': data_range},
20 | 'logpdf_kwargs': {'mirror': details_mirror, 'mirror_shifts': details_shifts}
21 | }
22 |
23 | intro_theta_nom = 1.0
24 | intro_phi_noms = 43,47
25 | intro_binning = 21
26 |
27 | example_phi = 47.
28 | example_theta = 1.0
29 | example_ndata = 100
30 |
31 | def collect_widget():
32 | return yadage_widget.WorkflowWidget(None)
33 |
--------------------------------------------------------------------------------
/models/model_weinberg.py:
--------------------------------------------------------------------------------
1 | import math
2 | import weinberg
3 | from ipywidgets import widgets
4 |
5 | name = 'weinberg'
6 |
7 | phi_range = [40.,50.]
8 | theta_range = [0.5,1.5]
9 | data_range = [-1,1]
10 | simulator = weinberg.simulator
11 |
12 | details_shifts = [-2.,2.]
13 | details_mirror = True
14 | details_lnlike_nsim = 1000
15 | details_map_bins = 20
16 | details_likelihood_settings = {
17 | 'simulator': simulator,
18 | 'simulation_kwargs': {'n_samples': 200},
19 | 'distr_kwargs': {'range': data_range},
20 | 'logpdf_kwargs': {'mirror': details_mirror, 'mirror_shifts': details_shifts}
21 | }
22 |
23 | intro_theta_nom = 1.0
24 | intro_phi_noms = 43,47
25 | intro_binning = 21
26 |
27 | example_phi = 47.
28 | example_theta = 1.0
29 | example_ndata = 100
30 |
31 | def collect_widget():
32 | return widgets.IntProgress(min = 0, max = 10, description = 'Taking Data.. ')
33 |
--------------------------------------------------------------------------------
/workflows/localflow/workdir/feature_extraction/_packtivity/feature_extraction.step.log:
--------------------------------------------------------------------------------
1 | 2017-06-08 22:15:00,213 - packtivity_logger_feature_extraction.step - INFO - running local command ln -s /Users/lukas/Code/active_sciencing/workflows/localflow/workdir/recontructiona/out.np /Users/lukas/Code/active_sciencing/workflows/localflow/workdir/feature_extraction/out.np
2 | 2017-06-08 22:15:00,214 - packtivity_logger_feature_extraction.step - INFO - changing to workdirectory /Users/lukas/Code/active_sciencing/workflows/localflow/workdir/feature_extraction
3 | 2017-06-08 22:15:00,235 - packtivity_logger_feature_extraction.step - INFO - changing back to original directory /Users/lukas/Code/active_sciencing/workflows/localflow
4 | 2017-06-08 22:15:00,248 - packtivity_logger_feature_extraction.step - INFO - publishing data: {'outfile': '/Users/lukas/Code/active_sciencing/workflows/localflow/workdir/feature_extraction/out.np'}
5 |
--------------------------------------------------------------------------------
/models/model_weinberg_yadage_full.py:
--------------------------------------------------------------------------------
1 | import math
2 | import yadage_sim_distributed
3 | import yadage_widget
4 |
5 | name = 'weinberg_yadage'
6 |
7 | phi_range = [40.,50.]
8 | theta_range = [0.5,1.5]
9 | data_range = [-1,1]
10 | simulator = yadage_sim_distributed.simulator
11 |
12 | details_shifts = [-2.,2.]
13 | details_mirror = True
14 | details_lnlike_nsim = 1000
15 | details_map_bins = 20
16 | details_likelihood_settings = {
17 | 'simulator': simulator,
18 | 'simulation_kwargs': {'n_samples': 200},
19 | 'distr_kwargs': {'range': data_range},
20 | 'logpdf_kwargs': {'mirror': details_mirror, 'mirror_shifts': details_shifts}
21 | }
22 |
23 | intro_theta_nom = 1.0
24 | intro_phi_noms = 43,47
25 | intro_binning = 21
26 |
27 | example_phi = 47.
28 | example_theta = 1.0
29 | example_ndata = 100
30 |
31 | def collect_widget():
32 | return yadage_widget.WorkflowWidget(None)
33 |
--------------------------------------------------------------------------------
/bayesopt.py:
--------------------------------------------------------------------------------
1 | import numpy as np
2 | from skopt import Optimizer
3 | from skopt.learning import GaussianProcessRegressor
4 | from skopt.learning.gaussian_process.kernels import ConstantKernel
5 | from skopt.learning.gaussian_process.kernels import Matern, WhiteKernel
6 |
7 |
8 |
9 | #cov_amplitude = ConstantKernel(1.0, (0.01, 5.0))
10 | cov_amplitude = ConstantKernel(1.0, "fixed")
11 |
12 | other_kernel = Matern(
13 | length_scale=np.ones(1),
14 | length_scale_bounds=[(0.3, 10)],
15 | nu=2.5)
16 |
17 | white_kernel = WhiteKernel()
18 |
19 | gp = GaussianProcessRegressor(
20 | kernel=cov_amplitude * other_kernel + white_kernel,
21 | normalize_y=True, alpha=0.0, noise=10e-7,
22 | n_restarts_optimizer=2)
23 |
24 |
25 | def get_optimizer(range,nrandom):
26 | return Optimizer(dimensions=[range],
27 | base_estimator=gp,
28 | n_random_starts=nrandom)
29 |
--------------------------------------------------------------------------------
/models/model_gaussian.py:
--------------------------------------------------------------------------------
1 | import math
2 | import gaussian
3 | from ipywidgets import widgets
4 |
5 | name = 'gaussian'
6 |
7 | phi_range = [ 0.,6.]
8 | theta_range = [-2.,2.]
9 | data_range = [-5.,5.]
10 | simulator = gaussian.simulator
11 |
12 | details_shifts = [-10.,10.]
13 | details_mirror = False
14 | details_lnlike_nsim = 1000
15 | details_map_bins = 20
16 | details_likelihood_settings = {
17 | 'simulator': simulator,
18 | 'simulation_kwargs': {'n_samples': 200},
19 | 'distr_kwargs': {'range': data_range},
20 | 'logpdf_kwargs': {'mirror': details_mirror, 'mirror_shifts': details_shifts}
21 | }
22 |
23 | intro_theta_nom = 0.0
24 | intro_phi_noms = math.pi,math.pi/2.
25 | intro_binning = 51
26 |
27 | example_phi = math.pi/2.
28 | example_theta = 1.
29 | example_ndata = 100
30 |
31 | def collect_widget():
32 | return widgets.IntProgress(min = 0, max = 10, description = 'Taking Data.. ')
33 |
--------------------------------------------------------------------------------
/Dockerfile:
--------------------------------------------------------------------------------
1 | FROM yadage/yadage:git-master
2 | RUN pip install matplotlib numpy scipy
3 | RUN pip install ipython==5.4.1 jupyter redis celery
4 | RUN yum install -y tkinter
5 | RUN jupyter nbextension enable --py --sys-prefix widgetsnbextension
6 | ENV PYTHONPATH /notebook
7 |
8 | # Add Tini. Tini operates as a process subreaper for jupyter. This prevents
9 | # kernel crashes.
10 | ENV TINI_VERSION v0.13.0
11 | ADD https://github.com/krallin/tini/releases/download/${TINI_VERSION}/tini /usr/bin/tini
12 | RUN chmod +x /usr/bin/tini
13 | ENTRYPOINT ["/usr/bin/tini", "--"]
14 |
15 | ADD . /notebook
16 | WORKDIR /notebook
17 |
18 | RUN cd workflows/localflow && pip install -e .
19 |
20 | RUN cd scikit-optimize && pip install -r requirements.txt && pip install -e .
21 | RUN pip install -U packtivity
22 | RUN pip install -r requirements.txt
23 | RUN mkdir -p ~/.jupyter; printf "import os\nc.NotebookApp.token = os.environ['THEJUPYTERTOKEN']\n" >> ~/.jupyter/jupyter_notebook_config.py
24 |
25 | EXPOSE 8888
26 | CMD ["jupyter", "notebook", "--port=8888", "--no-browser", "--ip=0.0.0.0", "--allow-root"]
27 |
--------------------------------------------------------------------------------
/workflows/localflow/fastweinberg/weinberg.py:
--------------------------------------------------------------------------------
1 | import numpy as np
2 | import sys
3 |
4 | def a_fb(sqrtshalf,gf):
5 | MZ = 90
6 | GFNom = 1.0
7 |
8 | sqrts = sqrtshalf*2.
9 | A_FB_EN = np.tanh((sqrts-MZ)/MZ*10)
10 | A_FB_GF = gf/GFNom
11 | return 2*A_FB_EN*A_FB_GF
12 |
13 | def diffxsec(costheta,sqrtshalf,gf):
14 | norm = 2.*((1.+1./3.))
15 | return ((1+costheta**2)+a_fb(sqrtshalf,gf)*costheta)/norm
16 |
17 | def rej_sample_costheta(nsamples,sqrtshalf,gf):
18 | ntrials = 0
19 | samples = []
20 | x = np.linspace(-1,1,num = 1000)
21 | maxval = np.max(diffxsec(x,sqrtshalf,gf))
22 | while len(samples) < nsamples:
23 | ntrials = ntrials+1
24 | xprop = np.random.uniform(-1,1)
25 | ycut = np.random.random()
26 | yprop = diffxsec(xprop,sqrtshalf,gf)/maxval
27 | if yprop/maxval < ycut:
28 | continue
29 | samples.append(xprop)
30 | return np.array(samples)
31 |
32 | def simulator(theta,phi,n_samples):
33 | samples = rej_sample_costheta(n_samples,phi,theta)
34 | return samples
35 |
36 |
37 |
--------------------------------------------------------------------------------
/workflows/codes/weinberg.py:
--------------------------------------------------------------------------------
1 | import numpy as np
2 | import sys
3 |
4 | def a_fb(sqrtshalf,gf):
5 | MZ = 90
6 | GFNom = 1.0
7 |
8 | sqrts = sqrtshalf*2.
9 | A_FB_EN = np.tanh((sqrts-MZ)/MZ*10)
10 | A_FB_GF = gf/GFNom
11 | return 2*A_FB_EN*A_FB_GF
12 |
13 | def diffxsec(costheta,sqrtshalf,gf):
14 | norm = 2.*((1.+1./3.))
15 | return ((1+costheta**2)+a_fb(sqrtshalf,gf)*costheta)/norm
16 |
17 | def rej_sample_costheta(nsamples,sqrtshalf,gf):
18 | ntrials = 0
19 | samples = []
20 | x = np.linspace(-1,1,num = 1000)
21 | maxval = np.max(diffxsec(x,sqrtshalf,gf))
22 | while len(samples) < nsamples:
23 | ntrials = ntrials+1
24 | xprop = np.random.uniform(-1,1)
25 | ycut = np.random.random()
26 | yprop = diffxsec(xprop,sqrtshalf,gf)/maxval
27 | if yprop/maxval < ycut:
28 | continue
29 | samples.append(xprop)
30 | return np.array(samples)
31 |
32 | def simulator(theta,phi,n_samples):
33 | sys.stdout.write('.')
34 | samples = rej_sample_costheta(n_samples,phi,theta)
35 | return samples
36 |
37 |
38 |
--------------------------------------------------------------------------------
/science_loop_widget.py:
--------------------------------------------------------------------------------
1 | from ipywidgets import widgets
2 |
3 | class loopwidget(object):
4 | def __init__(self):
5 | self.fontsize = 20
6 | layout = widgets.Layout(height = '50px', width = '200px')
7 | collect_data = widgets.HTML(layout = layout)
8 | calculate_posterior = widgets.HTML(layout = layout)
9 | next_exp = widgets.HTML(layout = layout)
10 | # control could be any custom control
11 | self.view = widgets.VBox([collect_data, calculate_posterior,next_exp])
12 |
13 | self.string_map = {0: 'Collect Data', 1: 'Calculate Posterior', 2: 'Design Next'}
14 |
15 | for i in range(3):
16 | self.view.children[i].value = self.html(self.string_map[i])
17 |
18 | def html(self, text, background_color = 'white'):
19 | textcolor = 'black'
20 | return '{}'.format(self.fontsize, background_color,textcolor,text)
21 |
22 | def toggle(self,active = None):
23 | for i in range(3):
24 | self.view.children[i].value = self.html(self.string_map[i],'#2196F3' if active == i else 'white')
25 |
26 |
--------------------------------------------------------------------------------
/workflows/localflow/workflow/steps.yml:
--------------------------------------------------------------------------------
1 | weinberg_delay:
2 | process:
3 | process_type: string-interpolated-cmd
4 | cmd: weinberg-fast {theta} {phi} {n_samples} {outfile} {delay}
5 | environment:
6 | environment_type: localproc-env
7 | publisher:
8 | publisher_type: 'frompar-pub'
9 | outputmap:
10 | outfile: 'outfile'
11 |
12 | weinberg:
13 | process:
14 | process_type: string-interpolated-cmd
15 | cmd: weinberg-fast {theta} {phi} {n_samples} {outfile}
16 | environment:
17 | environment_type: localproc-env
18 | publisher:
19 | publisher_type: 'frompar-pub'
20 | outputmap:
21 | outfile: 'outfile'
22 |
23 | softlink_delay:
24 | process:
25 | process_type: string-interpolated-cmd
26 | cmd: sleep {delay} && ln -s {inputfile} {outfile}
27 | environment:
28 | environment_type: localproc-env
29 | publisher:
30 | publisher_type: 'frompar-pub'
31 | outputmap:
32 | outfile: 'outfile'
33 |
34 | softlink:
35 | process:
36 | process_type: string-interpolated-cmd
37 | cmd: ln -s {inputfile} {outfile}
38 | environment:
39 | environment_type: localproc-env
40 | publisher:
41 | publisher_type: 'frompar-pub'
42 | outputmap:
43 | outfile: 'outfile'
44 |
--------------------------------------------------------------------------------
/models/weinberg.py:
--------------------------------------------------------------------------------
1 | import numpy as np
2 | import sys
3 | import time
4 | import random
5 |
6 | def a_fb(sqrtshalf,gf):
7 | MZ = 90
8 | GFNom = 1.0
9 |
10 | sqrts = sqrtshalf*2.
11 | A_FB_EN = np.tanh((sqrts-MZ)/MZ*10)
12 | A_FB_GF = gf/GFNom
13 | return 2*A_FB_EN*A_FB_GF
14 |
15 | def diffxsec(costheta,sqrtshalf,gf):
16 | norm = 2.*((1.+1./3.))
17 | return ((1+costheta**2)+a_fb(sqrtshalf,gf)*costheta)/norm
18 |
19 | def rej_sample_costheta(nsamples,sqrtshalf,gf):
20 | ntrials = 0
21 | samples = []
22 | x = np.linspace(-1,1,num = 1000)
23 | maxval = np.max(diffxsec(x,sqrtshalf,gf))
24 | while len(samples) < nsamples:
25 | ntrials = ntrials+1
26 | xprop = np.random.uniform(-1,1)
27 | ycut = np.random.random()
28 | yprop = diffxsec(xprop,sqrtshalf,gf)/maxval
29 | if yprop/maxval < ycut:
30 | continue
31 | samples.append(xprop)
32 | return np.array(samples)
33 |
34 | def simulator(theta,phi,n_samples, widget = None, delay = False):
35 | samples = rej_sample_costheta(n_samples,phi,theta)
36 | if delay:
37 | widget.value = 0
38 | for i in range(widget.max):
39 | time.sleep(random.random())
40 | widget.value = widget.value + 1
41 | return samples
42 |
--------------------------------------------------------------------------------
/workflows/localflow/workflow/workflow.yml:
--------------------------------------------------------------------------------
1 | stages:
2 | - name: generate
3 | dependencies: [init]
4 | scheduler:
5 | scheduler_type: singlestep-stage
6 | parameters:
7 | theta: {stages: init, output: theta, unwrap: true}
8 | phi: {stages: init, output: phi, unwrap: true}
9 | n_samples: {stages: init, output: n_samples, unwrap: true}
10 | outfile: '{workdir}/out.np'
11 | step: {$ref: 'steps.yml#/weinberg'}
12 | - name: detsim
13 | dependencies: [generate]
14 | scheduler:
15 | scheduler_type: singlestep-stage
16 | parameters:
17 | inputfile: {stages: generate, output: outfile, unwrap: true}
18 | outfile: '{workdir}/out.np'
19 | step: {$ref: 'steps.yml#/softlink'}
20 | - name: reconstruction
21 | dependencies: [detsim]
22 | scheduler:
23 | scheduler_type: singlestep-stage
24 | parameters:
25 | inputfile: {stages: detsim, output: outfile, unwrap: true}
26 | outfile: '{workdir}/out.np'
27 | step: {$ref: 'steps.yml#/softlink'}
28 | - name: feature_extraction
29 | dependencies: [reconstruction]
30 | scheduler:
31 | scheduler_type: singlestep-stage
32 | parameters:
33 | inputfile: {stages: reconstruction, output: outfile, unwrap: true}
34 | outfile: '{workdir}/out.np'
35 | step: {$ref: 'steps.yml#/softlink'}
36 |
--------------------------------------------------------------------------------
/models/yadage_sim_local.py:
--------------------------------------------------------------------------------
1 | import shutil
2 | import logging
3 | import os
4 | import numpy as np
5 | import sys
6 | import yadage.steering_object
7 | from yadage.clihelpers import setupbackend_fromstring
8 | import os
9 | import tempfile
10 |
11 | def simulator(theta,phi,n_samples, widget = None, delay = False):
12 | theta, phi, n_samples = float(theta), float(phi), int(n_samples)
13 |
14 | workdir = tempfile.mkdtemp(dir = os.environ.get('YCOMB_WOKRKDIR_BASE',os.path.abspath(os.curdir)))
15 |
16 | ys = yadage.steering_object.YadageSteering()
17 | ys.prepare_workdir(workdir, accept_existing_workdir = True)
18 |
19 | #initialize workflow with parameters
20 |
21 | initdata ={
22 | 'n_samples': n_samples,
23 | 'phi': phi,
24 | 'theta': theta,
25 | }
26 |
27 | ys.init_workflow(
28 | 'workflow_delay.yml' if delay else 'workflow.yml',
29 | 'workflows/localflow/workflow',
30 | initdata
31 | )
32 |
33 | backend = setupbackend_fromstring('fourgroundasync')
34 | ys.adage_argument(default_trackers = False)
35 | if widget:
36 | widget.wflow = ys.controller.adageobj
37 | ys.adage_argument(additional_trackers = [widget.adagetracker])
38 | ys.run_adage(backend)
39 |
40 | data = np.load(open(ys.controller.adageobj.view().getSteps('feature_extraction')[0].result['outfile']))
41 | shutil.rmtree(workdir)
42 | return data
--------------------------------------------------------------------------------
/plots.py:
--------------------------------------------------------------------------------
1 | import matplotlib.pyplot as plt
2 | import numpy as np
3 |
4 | def plot_bayes(res,phi_range, ax=plt):
5 | smooth_phi = np.linspace(*phi_range,num = 200).reshape(-1,1)
6 | try:
7 | y,std = res.models[-1].predict(smooth_phi, return_std = True)
8 | y,std = -y,-std
9 | ax.plot(smooth_phi[:,0],y, c = 'k',label = 'GP')
10 | ax.plot(smooth_phi[:,0],y+std, c = 'k', linestyle = 'dashed')
11 | ax.plot(smooth_phi[:,0],y-std, c = 'k', linestyle = 'dashed')
12 | ax.fill_between(smooth_phi[:,0],y-std,y+std, color = 'k', alpha = 0.2)
13 | except IndexError:
14 | pass
15 | ax.scatter(res.x_iters,-res.func_vals, marker = '.', s = 100, color = 'k')
16 | ax.axvline(res.x_iters[-1],color = 'b', label = 'last x')
17 | ax.axvline(res.x, c = 'r', label = 'opt. x')
18 | ax.set_xlim(*phi_range)
19 | ax.legend()
20 |
21 | def plot_data(data, data_range, ax = plt):
22 | bins = np.linspace(*data_range, num = 11)
23 | ax.hist(data, bins = bins, label = 'data')
24 | ax.legend()
25 |
26 | def plot_posterior(prior,posterior, best_theta, true_theta, theta_range, map_bins = 20, ax = plt):
27 | xs = np.linspace(*theta_range,num = map_bins)
28 | pri = ax.plot(xs,prior.pdf(xs), label = 'prior')
29 | pos = ax.plot(xs,posterior.pdf(xs), label = 'posterior')
30 | ax.axvline(best_theta, c = 'k', label = 'MAP')
31 | ax.axvline(true_theta, c = 'grey', label = 'truth')
32 | ax.legend()
33 |
34 |
--------------------------------------------------------------------------------
/workflows/localflow/workflow/workflow_delay.yml:
--------------------------------------------------------------------------------
1 | stages:
2 | - name: generate
3 | dependencies: [init]
4 | scheduler:
5 | scheduler_type: singlestep-stage
6 | parameters:
7 | theta: {stages: init, output: theta, unwrap: true}
8 | phi: {stages: init, output: phi, unwrap: true}
9 | n_samples: {stages: init, output: n_samples, unwrap: true}
10 | outfile: '{workdir}/out.np'
11 | delay: 5
12 | step: {$ref: 'steps.yml#/weinberg_delay'}
13 | - name: detsim
14 | dependencies: [generate]
15 | scheduler:
16 | scheduler_type: singlestep-stage
17 | parameters:
18 | inputfile: {stages: generate, output: outfile, unwrap: true}
19 | outfile: '{workdir}/out.np'
20 | delay: 5
21 | step: {$ref: 'steps.yml#/softlink_delay'}
22 | - name: recontructiona
23 | dependencies: [detsim]
24 | scheduler:
25 | scheduler_type: singlestep-stage
26 | parameters:
27 | inputfile: {stages: detsim, output: outfile, unwrap: true}
28 | outfile: '{workdir}/out.np'
29 | delay: 5
30 | step: {$ref: 'steps.yml#/softlink_delay'}
31 | - name: feature_extraction
32 | dependencies: [recontructiona]
33 | scheduler:
34 | scheduler_type: singlestep-stage
35 | parameters:
36 | inputfile: {stages: recontructiona, output: outfile, unwrap: true}
37 | outfile: '{workdir}/out.np'
38 | delay: 5
39 | step: {$ref: 'steps.yml#/softlink_delay'}
40 |
--------------------------------------------------------------------------------
/yadage_widget.py:
--------------------------------------------------------------------------------
1 | import ipywidgets as widgets
2 | from traitlets import Unicode, validate
3 | import adage.visualize
4 | import time
5 | from contextlib import contextmanager
6 | from functools import wraps
7 |
8 | def update_widget(widget,wflow):
9 | widget.dotstring = adage.visualize.colorize_graph_at_time(wflow.dag,time.time()).to_string()
10 |
11 | class WorkflowWidget(widgets.DOMWidget):
12 | _view_name = Unicode('WorkflowWidgetView').tag(sync=True)
13 | _view_module = Unicode('yadage').tag(sync=True)
14 | dotstring = Unicode('strict digraph {}').tag(sync = True)
15 |
16 | def update(self):
17 | update_widget(self,self.wflow)
18 |
19 | def __init__(self,wflow = None):
20 | super(WorkflowWidget,self).__init__()
21 | if wflow:
22 | self.wflow = wflow
23 | self.update()
24 |
25 | def reset(self,name,offset = ''):
26 | yadage.reset.reset_state(self.wflow,offset,name)
27 | self.update()
28 |
29 | @property
30 | def adagetracker(self):
31 | return ViewTracker(self)
32 |
33 | class ViewTracker(object):
34 | def __init__(self,widget):
35 | self.widget = widget
36 | def initialize(self,adageobj):
37 | pass
38 | def track(self,adageobj):
39 | self.widget.dotstring = adage.visualize.colorize_graph_at_time(adageobj.dag,time.time()).to_string()
40 | def finalize(self,adageobj):
41 | self.widget.dotstring = adage.visualize.colorize_graph_at_time(adageobj.dag,time.time()).to_string()
42 |
43 |
--------------------------------------------------------------------------------
/yadage.js:
--------------------------------------------------------------------------------
1 | define('yadage', ["jupyter-js-widgets","vis"], function(widgets,vis) {
2 |
3 | var WorkflowWidgetView = widgets.DOMWidgetView.extend({
4 |
5 | render: function() {
6 | this.value_changed();
7 | this.model.on('change:dotstring', this.value_changed, this);
8 | },
9 |
10 |
11 | value_changed: function() {
12 | var data = this.model.get('dotstring');
13 | this.el.innerHTML = ''
14 | this.container = document.createElement('div');
15 | this.container.innerHTML = 'hello'
16 | this.el.appendChild(this.container);
17 | this.container.style.height="200px";
18 | this.container.style.width="200px";
19 | var DOTstring = data;
20 | console.log('hello')
21 | console.log(DOTstring)
22 | console.log('done')
23 | console.log(data)
24 | console.log('done2')
25 | var parsedData = vis.network.convertDot(DOTstring);
26 | this.netdata = {
27 | nodes: parsedData.nodes,
28 | edges: parsedData.edges
29 | }
30 | this.net_options = parsedData.options;
31 | this.net_options.layout = {
32 | hierarchical: {
33 | direction: 'UD',
34 | sortMethod: 'directed'
35 | }
36 | }
37 | this.network = new vis.Network(this.container, this.netdata, this.net_options);
38 | console.log(this.netdata.nodes)
39 | },
40 | });
41 | return {
42 | WorkflowWidgetView : WorkflowWidgetView
43 | };
44 | });
45 |
--------------------------------------------------------------------------------
/workflows/localflow/workdir/_adage/adagesnap.txt:
--------------------------------------------------------------------------------
1 | ========== ADAGE LOG BEGIN at 2017-06-08T22:14:59.096786 ==========
2 | ---------- snapshot at 2017-06-08T22:14:59.096874
3 | ---------- snapshot at 2017-06-08T22:14:59.494143
4 | name: init obj: submitted: True
5 | name: generate obj: submitted: False
6 | name: detsim obj: submitted: False
7 | name: recontructiona obj: submitted: False
8 | name: feature_extraction obj: submitted: False
9 | ---------- snapshot at 2017-06-08T22:15:03.524418
10 | name: init obj: submitted: True
11 | name: generate obj: submitted: True
12 | name: detsim obj: submitted: True
13 | name: recontructiona obj: submitted: True
14 | name: feature_extraction obj: submitted: True
15 | ========== ADAGE LOG END at 2017-06-08T22:15:03.524925 ==========
16 |
--------------------------------------------------------------------------------
/workflows/localflow/workdir/_yadage/yadage_template.json:
--------------------------------------------------------------------------------
1 | {"stages": [{"dependencies": {"dependency_type": "jsonpath_ready", "expressions": ["init"]}, "name": "generate", "scheduler": {"step": {"process": {"cmd": "weinberg-fast {phi} {theta} {n_samples} {outfile}", "process_type": "string-interpolated-cmd"}, "environment": {"environment_type": "localproc-env"}, "publisher": {"publisher_type": "frompar-pub", "outputmap": {"outfile": "outfile"}}}, "scheduler_type": "singlestep-stage", "parameters": [{"value": "{workdir}/out.np", "key": "outfile"}, {"value": {"output": "phi", "expression_type": "stage-output-selector", "stages": "init", "unwrap": true}, "key": "phi"}, {"value": {"output": "theta", "expression_type": "stage-output-selector", "stages": "init", "unwrap": true}, "key": "theta"}, {"value": {"output": "n_samples", "expression_type": "stage-output-selector", "stages": "init", "unwrap": true}, "key": "n_samples"}]}}, {"dependencies": {"dependency_type": "jsonpath_ready", "expressions": ["generate"]}, "name": "detsim", "scheduler": {"step": {"process": {"cmd": "ln -s {inputfile} {outfile}", "process_type": "string-interpolated-cmd"}, "environment": {"environment_type": "localproc-env"}, "publisher": {"publisher_type": "frompar-pub", "outputmap": {"outfile": "outfile"}}}, "scheduler_type": "singlestep-stage", "parameters": [{"value": "{workdir}/out.np", "key": "outfile"}, {"value": {"output": "outfile", "expression_type": "stage-output-selector", "stages": "generate", "unwrap": true}, "key": "inputfile"}]}}, {"dependencies": {"dependency_type": "jsonpath_ready", "expressions": ["detsim"]}, "name": "recontructiona", "scheduler": {"step": {"process": {"cmd": "ln -s {inputfile} {outfile}", "process_type": "string-interpolated-cmd"}, "environment": {"environment_type": "localproc-env"}, "publisher": {"publisher_type": "frompar-pub", "outputmap": {"outfile": "outfile"}}}, "scheduler_type": "singlestep-stage", "parameters": [{"value": "{workdir}/out.np", "key": "outfile"}, {"value": {"output": "outfile", "expression_type": "stage-output-selector", "stages": "detsim", "unwrap": true}, "key": "inputfile"}]}}, {"dependencies": {"dependency_type": "jsonpath_ready", "expressions": ["recontructiona"]}, "name": "feature_extraction", "scheduler": {"step": {"process": {"cmd": "ln -s {inputfile} {outfile}", "process_type": "string-interpolated-cmd"}, "environment": {"environment_type": "localproc-env"}, "publisher": {"publisher_type": "frompar-pub", "outputmap": {"outfile": "outfile"}}}, "scheduler_type": "singlestep-stage", "parameters": [{"value": "{workdir}/out.np", "key": "outfile"}, {"value": {"output": "outfile", "expression_type": "stage-output-selector", "stages": "recontructiona", "unwrap": true}, "key": "inputfile"}]}}]}
--------------------------------------------------------------------------------
/distr.py:
--------------------------------------------------------------------------------
1 | from scipy.stats import entropy, gaussian_kde
2 | import numpy as np
3 | import matplotlib.pyplot as plt
4 | from scipy.optimize import fmin
5 |
6 |
7 | class Distribution:
8 | '''
9 | member vars
10 | variable names
11 | ranges (for use with george)
12 | methods
13 | density estimate (KDE or histogram) (for use with emcee)
14 | MAP (for saddle point approximation)
15 | '''
16 | def __init__(self, name, range, samples=None):
17 | self.range = range
18 | self.name = name
19 | self._approx_pdf=None
20 | if samples is None:
21 | self.samples = np.random.uniform(range[0], range[1], size=10000)
22 | else:
23 | self.samples = samples
24 |
25 | def map(self,bins = 20, use_kde=True):
26 | """Calculate maximum a posterior estimate"""
27 | if use_kde:
28 | approx_pdf = self.approx_pdf()
29 | return fmin(lambda x: -approx_pdf(x),x0=np.mean(self.samples), disp=False)[0]
30 | else:
31 | prob, edges = np.histogram(self.samples, range=self.range, bins=bins)
32 | bin_widths = edges[1:] - edges[:-1]
33 | prob = prob.clip(min=0.0000000001)
34 | max_index = np.argmax(prob)
35 | return edges[max_index]+bin_widths[max_index]/2.
36 |
37 | def entropy(self):
38 | """Compute Shannon entropy of this distribution"""
39 | approx_pdf = self.approx_pdf()
40 | prob = approx_pdf(np.linspace(self.range[0],self.range[1],100))
41 | return entropy(prob)
42 |
43 | def hist(self,ax = plt, **kwargs):
44 | """Plot distribution samples as histogram"""
45 | ax.hist(self.samples, range=self.range, **kwargs)
46 |
47 | def plot(self,ax = plt, *args,**kwargs):
48 | """Draw distribution using KDE"""
49 | xs = np.linspace(*self.range, num = 100)
50 | approx_pdf = self.approx_pdf()
51 | ax.plot(xs, approx_pdf(xs))
52 |
53 | def pdf(self, theta):
54 | approx_pdf = self.approx_pdf()
55 | return approx_pdf(theta)
56 |
57 | def approx_pdf(self,bw = 0.1, mirror = False, mirror_shifts = None):
58 | if self._approx_pdf != None:
59 | return self._approx_pdf
60 |
61 | if mirror:
62 | data = np.concatenate([
63 | (mirror_shifts[0]-self.samples),
64 | self.samples,
65 | (mirror_shifts[1]-self.samples)]
66 | )
67 | else:
68 | data = self.samples
69 |
70 | kernel = gaussian_kde(data)
71 | if mirror:
72 | return lambda x: 3*kernel.pdf(x)
73 | else:
74 | return lambda x: kernel.pdf(x)
75 |
76 | def approx_logpdf(self,bw = 0.1, mirror = False, mirror_shifts = None):
77 | approx_pdf = self.approx_pdf()
78 | return lambda x: np.log(approx_pdf(x))
79 |
--------------------------------------------------------------------------------
/workflows/localflow/workdir/_yadage/yadage_workflow_instance.dot:
--------------------------------------------------------------------------------
1 | digraph G {
2 | subgraph cluster_ {
3 | color=blue;
4 | label="";
5 | style=solid;
6 | subgraph cluster_detsim {
7 | color=grey;
8 | label=detsim;
9 | labeljust=l;
10 | style=dashed;
11 | "0483a180e42a866615a6a886257f54619f39581e" [color=blue, label="detsim[0]", shape=box];
12 | "0483a180e42a866615a6a886257f54619f39581e__outfile" [color=red, label="[outfile]"];
13 | "0483a180e42a866615a6a886257f54619f39581e" -> "0483a180e42a866615a6a886257f54619f39581e__outfile";
14 | }
15 |
16 | subgraph cluster_recontructiona {
17 | color=grey;
18 | label=recontructiona;
19 | labeljust=l;
20 | style=dashed;
21 | a8e8d2f9d5963831f538607a833ff6af1ba69c24 [color=blue, label="recontructiona[0]", shape=box];
22 | a8e8d2f9d5963831f538607a833ff6af1ba69c24__outfile [color=red, label="[outfile]"];
23 | a8e8d2f9d5963831f538607a833ff6af1ba69c24 -> a8e8d2f9d5963831f538607a833ff6af1ba69c24__outfile;
24 | }
25 |
26 | subgraph cluster_init {
27 | color=grey;
28 | label=init;
29 | labeljust=l;
30 | style=dashed;
31 | }
32 |
33 | "5abccf6823d64bdecc4a6c25038dd9fd30e7a8fd" [color=blue, fixedsize=True, height=0.2, label="", shape=diamond, width=0.2];
34 | "5abccf6823d64bdecc4a6c25038dd9fd30e7a8fd__theta" [color=red, label="[theta]"];
35 | "5abccf6823d64bdecc4a6c25038dd9fd30e7a8fd" -> "5abccf6823d64bdecc4a6c25038dd9fd30e7a8fd__theta";
36 | "5abccf6823d64bdecc4a6c25038dd9fd30e7a8fd__phi" [color=red, label="[phi]"];
37 | "5abccf6823d64bdecc4a6c25038dd9fd30e7a8fd" -> "5abccf6823d64bdecc4a6c25038dd9fd30e7a8fd__phi";
38 | "5abccf6823d64bdecc4a6c25038dd9fd30e7a8fd__n_samples" [color=red, label="[n_samples]"];
39 | "5abccf6823d64bdecc4a6c25038dd9fd30e7a8fd" -> "5abccf6823d64bdecc4a6c25038dd9fd30e7a8fd__n_samples";
40 | subgraph cluster_generate {
41 | color=grey;
42 | label=generate;
43 | labeljust=l;
44 | style=dashed;
45 | "1419713e4025a908173cf21991b443e58a1be4aa" [color=blue, label="generate[0]", shape=box];
46 | "1419713e4025a908173cf21991b443e58a1be4aa__outfile" [color=red, label="[outfile]"];
47 | "1419713e4025a908173cf21991b443e58a1be4aa" -> "1419713e4025a908173cf21991b443e58a1be4aa__outfile";
48 | }
49 |
50 | subgraph cluster_feature_extraction {
51 | color=grey;
52 | label=feature_extraction;
53 | labeljust=l;
54 | style=dashed;
55 | "5c1139745c6f31114ecddc63a402557e9a006e67" [color=blue, label="feature_extraction[0]", shape=box];
56 | "5c1139745c6f31114ecddc63a402557e9a006e67__outfile" [color=red, label="[outfile]"];
57 | "5c1139745c6f31114ecddc63a402557e9a006e67" -> "5c1139745c6f31114ecddc63a402557e9a006e67__outfile";
58 | }
59 |
60 | }
61 |
62 | a8e8d2f9d5963831f538607a833ff6af1ba69c24__outfile -> "5c1139745c6f31114ecddc63a402557e9a006e67";
63 | "5abccf6823d64bdecc4a6c25038dd9fd30e7a8fd__phi" -> "1419713e4025a908173cf21991b443e58a1be4aa";
64 | "5abccf6823d64bdecc4a6c25038dd9fd30e7a8fd__theta" -> "1419713e4025a908173cf21991b443e58a1be4aa";
65 | "5abccf6823d64bdecc4a6c25038dd9fd30e7a8fd__n_samples" -> "1419713e4025a908173cf21991b443e58a1be4aa";
66 | "1419713e4025a908173cf21991b443e58a1be4aa__outfile" -> "0483a180e42a866615a6a886257f54619f39581e";
67 | "0483a180e42a866615a6a886257f54619f39581e__outfile" -> a8e8d2f9d5963831f538607a833ff6af1ba69c24;
68 | }
69 |
--------------------------------------------------------------------------------
/models/yadage_sim_distributed.py:
--------------------------------------------------------------------------------
1 | import shutil
2 | import logging
3 | import os
4 | import uuid
5 | import json
6 | import random
7 | import numpy as np
8 | import sys
9 | import yadage.steering_object
10 | from yadage.clihelpers import setupbackend_fromstring,prepare_workdir_from_archive
11 | import os
12 | import tempfile
13 |
14 | logging.getLogger('adage').setLevel(logging.ERROR)
15 | logging.getLogger('yadage').setLevel(logging.ERROR)
16 |
17 | def pars_to_initdata(theta,phi,n_samples):
18 | theta, phi, n_samples = float(theta), float(phi), int(n_samples)
19 | nthreads = 2
20 | return {
21 | 'nevents': int(n_samples / nthreads),
22 | 'seeds': [random.randint(1000,9999) for x in range(nthreads)],
23 | 'sqrtshalf':phi,
24 | 'polbeam1': 0,
25 | 'polbeam2': 0,
26 | 'Gf': theta * 1e-05,
27 | 'runcardtempl':'run_card.templ',
28 | 'proccardtempl':'sm_proc_card.templ',
29 | 'paramcardtempl':'param_card.templ',
30 | }
31 |
32 | def workflow_config(initdata):
33 | return ['rootflow.yml','github:lukasheinrich/weinberg-exp:example_yadage',initdata]
34 |
35 | def load_data(adageobj):
36 | with open(adageobj.view().getSteps('merge')[0].result['jsonlinesfile']) as f:
37 | parsed = map(json.loads,f.readlines())
38 |
39 | costhetas = []
40 | for e in parsed:
41 | els = [p for p in e['particles'] if p['id'] == 11]
42 | mus = [p for p in e['particles'] if p['id'] == 13]
43 | assert len(mus) == 1
44 | assert len(els) == 1
45 | mu = mus[0]
46 | el = els[0]
47 | el_px, el_py, el_pz = [el[x] for x in ['px','py','pz']]
48 | mu_px, mu_py, mu_pz = [mu[x] for x in ['px','py','pz']]
49 | costheta = mu_pz/el_pz
50 | costhetas.append(costheta)
51 | return np.array(costhetas)
52 |
53 | def simulator(theta,phi,n_samples, widget = None, delay = False):
54 | theta, phi, n_samples = float(theta), float(phi), int(n_samples)
55 |
56 | uniqdir = 'work_'+''.join(str(uuid.uuid4()).split('-')[:2])
57 | workdir = os.path.join(os.environ.get('YCOMB_WOKRKDIR_BASE',os.path.abspath(os.curdir)),uniqdir)
58 |
59 |
60 | repolocation = 'https://raw.githubusercontent.com/lukasheinrich/weinberg-exp/master/example_yadage'
61 | prepare_workdir_from_archive(
62 | workdir,
63 | '{}/input.zip'.format(repolocation)
64 | )
65 |
66 | ys = yadage.steering_object.YadageSteering()
67 | ys.prepare_workdir(workdir, accept_existing_workdir = True)
68 |
69 | initdata = pars_to_initdata(theta,phi,n_samples)
70 | ys.init_workflow(
71 | *workflow_config(initdata),
72 | initdir = '{}/init'.format(workdir)
73 | )
74 |
75 | backend = setupbackend_fromstring(os.environ.get('YCOMB_BACKEND','multiproc:4'))
76 | ys.adage_argument(default_trackers = False)
77 | if widget:
78 | widget.wflow = ys.controller.adageobj
79 | ys.adage_argument(additional_trackers = [widget.adagetracker])
80 |
81 | ys.run_adage(backend)
82 |
83 |
84 | data = load_data(ys.controller.adageobj)
85 | shutil.rmtree(workdir)
86 | return data
--------------------------------------------------------------------------------
/README.md:
--------------------------------------------------------------------------------
1 | # "Active Sciencing" with Reusable Workflows
2 |
3 | By Kyle Cranmer, Lukas Heinrich, Tim Head, Gilles Louppe
4 |
5 |
6 |
7 |
8 |
9 |
10 | [](https://ycombdemo.cern.ch/submit?toplevel=github%3Alukasheinrich%2Fweinberg-exp%3Aexample_yadage&workflow=rootflow.yml&pars=%7B%22sqrtshalf%22%3A+45%2C+%22Gf%22%3A+1.76639e-05%2C+%22nevents%22%3A+10000%2C+%22seeds%22%3A+%5B1%2C+2%2C+3%2C+4%5D%2C+%22polbeam1%22%3A+0%2C+%22polbeam2%22%3A+0%2C+%22paramcardtempl%22%3A+%22param_card.templ%22%2C+%22runcardtempl%22%3A+%22run_card.templ%22%2C+%22proccardtempl%22%3A+%22sm_proc_card.templ%22%7D&archive=https%3A%2F%2Fraw.githubusercontent.com%2Flukasheinrich%2Fweinberg-exp%2Fmaster%2Fexample_yadage%2Finput.zip&outputs=merge%2Fout.jsonl) | [Notebook Server](http://ycombdemo.cern.ch:30888/tree?) | [Physics simulator workflow](https://github.com/lukasheinrich/weinberg-exp/blob/master/README.md)
11 |
12 |
13 |
14 |
15 | Based on earlier work with NYU CDS masters students Manoj Kumar, Phil Yeres, and Michele Ceru and discussions with Brenden Lake and Gilles Louppe.
16 |
17 | The point of this notebook is to explore the synergy of three powerful techniques:
18 |
19 | 1. generic likelihood-free inference engines (eg. ABC, carl, etc.) that enable statistical inference on the parameters of a theory that are implicitly defined by a simulator
20 |
21 | 2. workflows that encapsulate scientific pipelines and extend the scope from reproducibility to reusability
22 |
23 | 1. active learning and sequential design algorithms (eg. Bayesian optimization) that balance exploration and exploitation to efficiently optimize an expensive black box objective function
24 |
25 | Together, these three ideas can be combined to enable an efficient and automated loop of the scientific method -- at least, for a sufficiently well posed problem. The scientist's input to the system are:
26 |
27 | * an external workflow that implements some experimental protocol (orange **Exp** component)
28 | * an external workflow that implements a simulator for those experiments, which depends on some theoretical parameters that we would like to infer (orange **Sim** component).
29 |
30 |
31 | Interesingly, we will use the simulator not only to perform inference on the parameters, but also to design the next experiment (this is where active learning comes in).
32 |
33 | ## Examples
34 |
35 | * [demo_gaussian.ipynb](demo_gaussian.ipynb) Runs a fast demo with a simple Gaussian simulator
36 | * [demo_weinberg.ipynb](demo_weinberg.ipynb) Runs a fast demo with an approximate physics-inspired simulation locally
37 | * [demo_weinberg_yadage.ipynb](demo_weinberg_yadage_full.ipynb) Runs a slower demo with an approximate physics-inspired simulation through a workflow system. This measures the [Weinberg angle](https://en.wikipedia.org/wiki/Weinberg_angle) in the standard model of particle physics.
38 | * [demo_weinberg_yadage_full.ipynb](demo_weinberg_yadage_full.ipynb) Runs a much slower demo with a [real Physics simulator workflow](https://github.com/lukasheinrich/weinberg-exp/blob/master/README.md).
39 |
40 |
41 |
--------------------------------------------------------------------------------
/what.ipynb:
--------------------------------------------------------------------------------
1 | {
2 | "cells": [
3 | {
4 | "cell_type": "code",
5 | "execution_count": null,
6 | "metadata": {
7 | "collapsed": true
8 | },
9 | "outputs": [],
10 | "source": [
11 | "import numpy as np\n",
12 | "import matplotlib.pyplot as plt\n",
13 | "%matplotlib nbagg"
14 | ]
15 | },
16 | {
17 | "cell_type": "code",
18 | "execution_count": null,
19 | "metadata": {},
20 | "outputs": [],
21 | "source": [
22 | "def plot_bayes(res,ax = plt):\n",
23 | " x = np.linspace(-5,5,100).reshape(-1,1)\n",
24 | " try:\n",
25 | " prd,std = res.models[-1].predict(x, return_std = True)\n",
26 | " plt.plot(x[:,0],prd,linestyle = 'solid', c = 'k')\n",
27 | " plt.plot(x[:,0],prd+std,linestyle = 'dashed', c= 'k')\n",
28 | " plt.plot(x[:,0],prd-std,linestyle = 'dashed', c= 'k')\n",
29 | " plt.fill_between(x[:,0].ravel(),prd+std,prd-std, alpha = 0.2, color = 'k')\n",
30 | " except IndexError:\n",
31 | " pass #we don't havea model yet\n",
32 | "\n",
33 | " plt.scatter(res.x_iters,res.func_vals, marker = '.', s = 200, color = 'k')\n",
34 | " plt.axvline(res.x[0],color = 'r')\n",
35 | " plt.axvline(res.x_iters[-1],color = 'b')\n"
36 | ]
37 | },
38 | {
39 | "cell_type": "code",
40 | "execution_count": null,
41 | "metadata": {},
42 | "outputs": [],
43 | "source": [
44 | "fig,ax = plt.subplots(1,1)"
45 | ]
46 | },
47 | {
48 | "cell_type": "code",
49 | "execution_count": null,
50 | "metadata": {
51 | "collapsed": true
52 | },
53 | "outputs": [],
54 | "source": [
55 | "def fnew(x):\n",
56 | " return x[0]**2\n",
57 | "\n",
58 | "import bayesopt\n",
59 | "def fancy_pants_bayes(function, x_range, n_random,n_total, ax = None, fig = None, delay = None):\n",
60 | " opt = bayesopt.get_optimizer(x_range,n_random)\n",
61 | " for i in range(n_total): \n",
62 | " # ask next x\n",
63 | " next_x = opt.ask()\n",
64 | "\n",
65 | " next_f = function(next_x)\n",
66 | "\n",
67 | " # tell a pair to the optimizer\n",
68 | " res = opt.tell(next_x, next_f)\n",
69 | " if ax:\n",
70 | " import time\n",
71 | " if delay: time.sleep(delay)\n",
72 | " ax.clear()\n",
73 | " plot_bayes(res, ax = ax)\n",
74 | " fig.canvas.draw()\n",
75 | " return res"
76 | ]
77 | },
78 | {
79 | "cell_type": "code",
80 | "execution_count": null,
81 | "metadata": {},
82 | "outputs": [],
83 | "source": [
84 | "res = fancy_pants_bayes(fnew, [-5.0,5.0], 2, 10, ax = ax, fig = fig, delay = 2)"
85 | ]
86 | },
87 | {
88 | "cell_type": "code",
89 | "execution_count": null,
90 | "metadata": {
91 | "collapsed": true
92 | },
93 | "outputs": [],
94 | "source": []
95 | },
96 | {
97 | "cell_type": "code",
98 | "execution_count": null,
99 | "metadata": {
100 | "collapsed": true
101 | },
102 | "outputs": [],
103 | "source": []
104 | }
105 | ],
106 | "metadata": {
107 | "kernelspec": {
108 | "display_name": "Python 2",
109 | "language": "python",
110 | "name": "python2"
111 | },
112 | "language_info": {
113 | "codemirror_mode": {
114 | "name": "ipython",
115 | "version": 2
116 | },
117 | "file_extension": ".py",
118 | "mimetype": "text/x-python",
119 | "name": "python",
120 | "nbconvert_exporter": "python",
121 | "pygments_lexer": "ipython2",
122 | "version": "2.7.10"
123 | }
124 | },
125 | "nbformat": 4,
126 | "nbformat_minor": 2
127 | }
128 |
--------------------------------------------------------------------------------
/common.py:
--------------------------------------------------------------------------------
1 | import distr
2 | import numpy as np
3 | import emcee
4 | import datetime
5 | from multiprocessing import Pool
6 | from skopt import gp_minimize
7 | import bayesopt
8 | import plots
9 | import time
10 |
11 | import science_loop_widget
12 | import eig_widget
13 | from ipywidgets import widgets
14 |
15 | def lnprior(theta, prior):
16 | p = prior.pdf(theta)
17 | if p <= 1e-8:
18 | return -np.inf
19 | else:
20 | return np.log(p)
21 |
22 | def lnlike(theta, x, phi,simulator, simulation_kwargs = dict(n_samples = 5000), distr_kwargs = {}, logpdf_kwargs = {}):
23 | mc = simulator(theta,phi, **simulation_kwargs)
24 | p = distr.Distribution(name = '', samples = mc, **distr_kwargs)
25 | logpdf = p.approx_logpdf(**logpdf_kwargs)
26 | return np.sum(logpdf(x))
27 |
28 | def lnprob(theta, x, prior, phi, lnlike_kwargs):
29 | lp = lnprior(theta, prior)
30 | if not np.isfinite(lp):
31 | return -np.inf
32 | return lp + lnlike(theta, x, phi,**lnlike_kwargs)
33 |
34 | def calculate_posterior(prior, data, phi, n_walkers = 10, n_warmup = 10, n_chainlen = 20, lnprob_args = None):
35 | """Compute samples from the posterior"""
36 | ndim, n_walkers = 1, n_walkers
37 | # initialise walkers from the MAP + noise
38 | # XXX alternatively sample a point from the KDE without adding noise?
39 | # XXX not sure if the noise takes us into a region where the prior is zero?
40 | pos = [prior.map() + 1e-1*np.random.randn(ndim) for i in range(n_walkers)]
41 |
42 | sampler = emcee.EnsembleSampler(
43 | n_walkers, 1, lnprob,
44 | args=(data,prior,phi,lnprob_args),
45 | # threads = n_walkers
46 | )
47 | pos, prob, state = sampler.run_mcmc(pos, n_warmup)
48 |
49 | sampler.reset()
50 | pos, prob, state = sampler.run_mcmc(pos, n_chainlen)
51 | return distr.Distribution(prior.name, prior.range, sampler.flatchain[:,0])
52 |
53 |
54 | def info_gain(p1, p2):
55 | return p1.entropy() - p2.entropy()
56 |
57 | def _simulate(args):
58 | theta_map, phi, prior, sim_n_data, emcee_kwargs = args
59 | # external workflow provides simulated data
60 | sim_data = emcee_kwargs['lnprob_args']['simulator'](theta_map, phi, n_samples = 1000)
61 |
62 | #external workflow uses simulator to provide likelihood
63 | sim_posterior = calculate_posterior(prior, sim_data, phi,**emcee_kwargs)
64 | return info_gain(prior, sim_posterior)
65 |
66 | def expected_information_gain(phi, prior, emcee_kwargs, sim_n_data , map_bins, widget = None):
67 | 'calculate the expression above using workflow for simulations'
68 | n_simulations = 4
69 | n_parallel = 4
70 |
71 | phi = phi[0]
72 | #need to pass in prior through some extra arguments
73 |
74 | widget.max = n_simulations
75 | widget.value = 0
76 |
77 | # use saddle-point approximation
78 | theta_map = prior.map(bins = map_bins)
79 |
80 | print str(datetime.datetime.now()),'EIG via 4 parallel experiments with [theta,phi]',theta_map,phi
81 |
82 | # currently the MCMC sampler is the slower part, which already uses threads so we don't gain
83 | # this should change once we have a more realistic simulator that takes time to run
84 | pool = Pool(n_parallel)
85 |
86 | eig_results = [pool.apply_async(_simulate, args = ([theta_map, phi, prior,sim_n_data,emcee_kwargs],)) for i in range(n_simulations)]
87 |
88 | while not all([r.ready() for r in eig_results]):
89 | time.sleep(0.01)
90 | widget.value = [r.ready() for r in eig_results].count(True)
91 |
92 | eig = [r.get() for r in eig_results]
93 | pool.close()
94 | pool.join()
95 | return np.mean(eig)
96 |
97 | def overview_widgets(model):
98 | science_wdg = science_loop_widget.loopwidget()
99 | collect_ui = model.collect_widget()
100 | eig_wdg = eig_widget.widget()
101 | sub_widgets = [science_wdg,collect_ui,eig_wdg]
102 | return widgets.HBox([science_wdg.view,collect_ui,eig_wdg]), [science_wdg,collect_ui,eig_wdg]
103 |
104 | def eig_search_settings(model,ndata, widget, mcmc_length = 50):
105 | eig_kwargs = {'emcee_kwargs' : {
106 | 'n_chainlen': mcmc_length,
107 | 'lnprob_args': model.details_likelihood_settings},
108 | 'sim_n_data': ndata,
109 | 'map_bins': model.details_map_bins,
110 | 'widget': widget
111 | }
112 | return eig_kwargs
113 |
114 | def design_next_experiment_bayesopt(prior,phi_bounds, eig_kwargs,
115 | n_totalcalls=10, n_random_calls = 5, ax = None, fig = None, widget = None):
116 |
117 | opt = bayesopt.get_optimizer(phi_bounds,n_random_calls)
118 | func = lambda p: -expected_information_gain(p, prior,**eig_kwargs)
119 |
120 | widget.value = 0
121 | for i in range(n_totalcalls):
122 | # ask next x
123 | next_x = opt.ask()
124 |
125 | # print 'ASK',next_x
126 | next_f = func(next_x)
127 | widget.value = widget.value + 1
128 |
129 | # print 'TELL',next_f
130 | # tell a pair to the optimizer
131 | res = opt.tell(next_x, next_f)
132 | # print 'DATA',res.x_iters,res.func_vals
133 |
134 | if ax:
135 | ax.clear()
136 | plots.plot_bayes(res, phi_range = phi_bounds, ax = ax)
137 | fig.canvas.draw()
138 | return res, res.x[0], res.x_iters
139 |
140 | def design_next_experiment_simplegrid(prior,phi_bounds, eig_kwargs, n_points=6):
141 | eig_test_phis = np.linspace(*phi_bounds, num = n_points)
142 | eig = []
143 | for x in eig_test_phis.reshape(-1,1):
144 | eig.append(expected_information_gain(x,prior,**eig_kwargs))
145 | eig = np.array(eig)
146 | next_phi = eig_test_phis[np.argmax(eig)]
147 | return next_phi, eig_test_phis, eig
148 |
--------------------------------------------------------------------------------
/workflows/localflow/workdir/_yadage/yadage_snapshot_workflow.json:
--------------------------------------------------------------------------------
1 | {"rules": [], "applied": [{"type": "offset", "id": "22b14659061847a8dfd25f9283081b76a55644c5", "rule": {"info": "", "step": {"attributes": {"theta": 1.0, "phi": 42, "n_samples": 100}, "prepublished": {"theta": 1.0, "phi": 42, "n_samples": 100}, "type": "initstep", "name": "init", "inputs": []}, "dependencies": null, "name": "init", "context": {}, "type": "initStage"}, "offset": ""}, {"type": "offset", "id": "e12dbd5e7e1a8e668833cfce632e432a31213751", "rule": {"info": {"step": {"process": {"cmd": "weinberg-fast {phi} {theta} {n_samples} {outfile}", "process_type": "string-interpolated-cmd"}, "environment": {"environment_type": "localproc-env"}, "publisher": {"publisher_type": "frompar-pub", "outputmap": {"outfile": "outfile"}}}, "scheduler_type": "singlestep-stage", "parameters": [{"value": "{workdir}/out.np", "key": "outfile"}, {"value": {"output": "phi", "expression_type": "stage-output-selector", "stages": "init", "unwrap": true}, "key": "phi"}, {"value": {"output": "theta", "expression_type": "stage-output-selector", "stages": "init", "unwrap": true}, "key": "theta"}, {"value": {"output": "n_samples", "expression_type": "stage-output-selector", "stages": "init", "unwrap": true}, "key": "n_samples"}]}, "dependencies": {"dependency_type": "jsonpath_ready", "expressions": ["init"]}, "type": "jsonStage", "name": "generate", "context": {"readwrite": ["/Users/lukas/Code/active_sciencing/workflows/localflow/workdir"], "readonly": []}}, "offset": ""}, {"type": "offset", "id": "cfe03a1a2b3a87f4459c7af5a7d11b6dbbad0959", "rule": {"info": {"step": {"process": {"cmd": "ln -s {inputfile} {outfile}", "process_type": "string-interpolated-cmd"}, "environment": {"environment_type": "localproc-env"}, "publisher": {"publisher_type": "frompar-pub", "outputmap": {"outfile": "outfile"}}}, "scheduler_type": "singlestep-stage", "parameters": [{"value": "{workdir}/out.np", "key": "outfile"}, {"value": {"output": "outfile", "expression_type": "stage-output-selector", "stages": "generate", "unwrap": true}, "key": "inputfile"}]}, "dependencies": {"dependency_type": "jsonpath_ready", "expressions": ["generate"]}, "type": "jsonStage", "name": "detsim", "context": {"readwrite": ["/Users/lukas/Code/active_sciencing/workflows/localflow/workdir"], "readonly": []}}, "offset": ""}, {"type": "offset", "id": "3476922708146b6abb45e7ccd98e7adaeee0a7f1", "rule": {"info": {"step": {"process": {"cmd": "ln -s {inputfile} {outfile}", "process_type": "string-interpolated-cmd"}, "environment": {"environment_type": "localproc-env"}, "publisher": {"publisher_type": "frompar-pub", "outputmap": {"outfile": "outfile"}}}, "scheduler_type": "singlestep-stage", "parameters": [{"value": "{workdir}/out.np", "key": "outfile"}, {"value": {"output": "outfile", "expression_type": "stage-output-selector", "stages": "detsim", "unwrap": true}, "key": "inputfile"}]}, "dependencies": {"dependency_type": "jsonpath_ready", "expressions": ["detsim"]}, "type": "jsonStage", "name": "recontructiona", "context": {"readwrite": ["/Users/lukas/Code/active_sciencing/workflows/localflow/workdir"], "readonly": []}}, "offset": ""}, {"type": "offset", "id": "17c0cb65eaff57c4cb034629f923f75edfcc0e70", "rule": {"info": {"step": {"process": {"cmd": "ln -s {inputfile} {outfile}", "process_type": "string-interpolated-cmd"}, "environment": {"environment_type": "localproc-env"}, "publisher": {"publisher_type": "frompar-pub", "outputmap": {"outfile": "outfile"}}}, "scheduler_type": "singlestep-stage", "parameters": [{"value": "{workdir}/out.np", "key": "outfile"}, {"value": {"output": "outfile", "expression_type": "stage-output-selector", "stages": "recontructiona", "unwrap": true}, "key": "inputfile"}]}, "dependencies": {"dependency_type": "jsonpath_ready", "expressions": ["recontructiona"]}, "type": "jsonStage", "name": "feature_extraction", "context": {"readwrite": ["/Users/lukas/Code/active_sciencing/workflows/localflow/workdir"], "readonly": []}}, "offset": ""}], "dag": {"nodes": [{"task": {"inputs": [{"stepid": "a8e8d2f9d5963831f538607a833ff6af1ba69c24", "pointer_path": "/outfile"}], "name": "feature_extraction", "context": {"readwrite": ["/Users/lukas/Code/active_sciencing/workflows/localflow/workdir/feature_extraction"], "readonly": ["/Users/lukas/Code/active_sciencing/workflows/localflow/workdir"], "metadir": "/Users/lukas/Code/active_sciencing/workflows/localflow/workdir/feature_extraction/_packtivity", "nametag": "feature_extraction", "depwrites": ["/Users/lukas/Code/active_sciencing/workflows/localflow/workdir/recontructiona"]}, "attributes": {"outfile": "/Users/lukas/Code/active_sciencing/workflows/localflow/workdir/feature_extraction/out.np", "inputfile": "/Users/lukas/Code/active_sciencing/workflows/localflow/workdir/recontructiona/out.np"}, "prepublished": {"outfile": "/Users/lukas/Code/active_sciencing/workflows/localflow/workdir/feature_extraction/out.np"}, "type": "yadagestep", "spec": {"process": {"cmd": "ln -s {inputfile} {outfile}", "process_type": "string-interpolated-cmd"}, "environment": {"environment_type": "localproc-env"}, "publisher": {"publisher_type": "frompar-pub", "outputmap": {"outfile": "outfile"}}}}, "name": "feature_extraction", "state": "SUCCESS", "proxy": {"proxyname": "ForegroundProxy", "proxydetails": {"result": {"outfile": "/Users/lukas/Code/active_sciencing/workflows/localflow/workdir/feature_extraction/out.np"}, "success": true}}, "timestamps": {"defined": 1496952899.493768, "ready by": 1496952900.270372, "submit": 1496952900.248876}, "id": "5c1139745c6f31114ecddc63a402557e9a006e67"}, {"task": {"attributes": {"theta": 1.0, "phi": 42, "n_samples": 100}, "prepublished": {"theta": 1.0, "phi": 42, "n_samples": 100}, "type": "initstep", "name": "init", "inputs": []}, "name": "init", "state": "SUCCESS", "proxy": {"proxyname": "InitProxy", "proxydetails": {"status": "SUCCESS", "result": {"theta": 1.0, "phi": 42, "n_samples": 100}}}, "timestamps": {"defined": 1496952899.201363, "ready by": 1496952899.520412, "submit": 1496952899.493867}, "id": "5abccf6823d64bdecc4a6c25038dd9fd30e7a8fd"}, {"task": {"inputs": [{"stepid": "5abccf6823d64bdecc4a6c25038dd9fd30e7a8fd", "pointer_path": "/phi"}, {"stepid": "5abccf6823d64bdecc4a6c25038dd9fd30e7a8fd", "pointer_path": "/theta"}, {"stepid": "5abccf6823d64bdecc4a6c25038dd9fd30e7a8fd", "pointer_path": "/n_samples"}], "name": "generate", "context": {"readwrite": ["/Users/lukas/Code/active_sciencing/workflows/localflow/workdir/generate"], "readonly": ["/Users/lukas/Code/active_sciencing/workflows/localflow/workdir"], "metadir": "/Users/lukas/Code/active_sciencing/workflows/localflow/workdir/generate/_packtivity", "nametag": "generate", "depwrites": []}, "attributes": {"outfile": "/Users/lukas/Code/active_sciencing/workflows/localflow/workdir/generate/out.np", "phi": 42, "n_samples": 100, "theta": 1.0}, "prepublished": {"outfile": "/Users/lukas/Code/active_sciencing/workflows/localflow/workdir/generate/out.np"}, "type": "yadagestep", "spec": {"process": {"cmd": "weinberg-fast {phi} {theta} {n_samples} {outfile}", "process_type": "string-interpolated-cmd"}, "environment": {"environment_type": "localproc-env"}, "publisher": {"publisher_type": "frompar-pub", "outputmap": {"outfile": "outfile"}}}}, "name": "generate", "state": "SUCCESS", "proxy": {"proxyname": "ForegroundProxy", "proxydetails": {"result": {"outfile": "/Users/lukas/Code/active_sciencing/workflows/localflow/workdir/generate/out.np"}, "success": true}}, "timestamps": {"defined": 1496952899.315388, "ready by": 1496952900.115046, "submit": 1496952900.092477}, "id": "1419713e4025a908173cf21991b443e58a1be4aa"}, {"task": {"inputs": [{"stepid": "1419713e4025a908173cf21991b443e58a1be4aa", "pointer_path": "/outfile"}], "name": "detsim", "context": {"readwrite": ["/Users/lukas/Code/active_sciencing/workflows/localflow/workdir/detsim"], "readonly": ["/Users/lukas/Code/active_sciencing/workflows/localflow/workdir"], "metadir": "/Users/lukas/Code/active_sciencing/workflows/localflow/workdir/detsim/_packtivity", "nametag": "detsim", "depwrites": ["/Users/lukas/Code/active_sciencing/workflows/localflow/workdir/generate"]}, "attributes": {"outfile": "/Users/lukas/Code/active_sciencing/workflows/localflow/workdir/detsim/out.np", "inputfile": "/Users/lukas/Code/active_sciencing/workflows/localflow/workdir/generate/out.np"}, "prepublished": {"outfile": "/Users/lukas/Code/active_sciencing/workflows/localflow/workdir/detsim/out.np"}, "type": "yadagestep", "spec": {"process": {"cmd": "ln -s {inputfile} {outfile}", "process_type": "string-interpolated-cmd"}, "environment": {"environment_type": "localproc-env"}, "publisher": {"publisher_type": "frompar-pub", "outputmap": {"outfile": "outfile"}}}}, "name": "detsim", "state": "SUCCESS", "proxy": {"proxyname": "ForegroundProxy", "proxydetails": {"result": {"outfile": "/Users/lukas/Code/active_sciencing/workflows/localflow/workdir/detsim/out.np"}, "success": true}}, "timestamps": {"defined": 1496952899.384449, "ready by": 1496952900.157797, "submit": 1496952900.137143}, "id": "0483a180e42a866615a6a886257f54619f39581e"}, {"task": {"inputs": [{"stepid": "0483a180e42a866615a6a886257f54619f39581e", "pointer_path": "/outfile"}], "name": "recontructiona", "context": {"readwrite": ["/Users/lukas/Code/active_sciencing/workflows/localflow/workdir/recontructiona"], "readonly": ["/Users/lukas/Code/active_sciencing/workflows/localflow/workdir"], "metadir": "/Users/lukas/Code/active_sciencing/workflows/localflow/workdir/recontructiona/_packtivity", "nametag": "recontructiona", "depwrites": ["/Users/lukas/Code/active_sciencing/workflows/localflow/workdir/detsim"]}, "attributes": {"outfile": "/Users/lukas/Code/active_sciencing/workflows/localflow/workdir/recontructiona/out.np", "inputfile": "/Users/lukas/Code/active_sciencing/workflows/localflow/workdir/detsim/out.np"}, "prepublished": {"outfile": "/Users/lukas/Code/active_sciencing/workflows/localflow/workdir/recontructiona/out.np"}, "type": "yadagestep", "spec": {"process": {"cmd": "ln -s {inputfile} {outfile}", "process_type": "string-interpolated-cmd"}, "environment": {"environment_type": "localproc-env"}, "publisher": {"publisher_type": "frompar-pub", "outputmap": {"outfile": "outfile"}}}}, "name": "recontructiona", "state": "SUCCESS", "proxy": {"proxyname": "ForegroundProxy", "proxydetails": {"result": {"outfile": "/Users/lukas/Code/active_sciencing/workflows/localflow/workdir/recontructiona/out.np"}, "success": true}}, "timestamps": {"defined": 1496952899.442735, "ready by": 1496952900.211123, "submit": 1496952900.189669}, "id": "a8e8d2f9d5963831f538607a833ff6af1ba69c24"}], "edges": [["5abccf6823d64bdecc4a6c25038dd9fd30e7a8fd", "1419713e4025a908173cf21991b443e58a1be4aa"], ["1419713e4025a908173cf21991b443e58a1be4aa", "0483a180e42a866615a6a886257f54619f39581e"], ["0483a180e42a866615a6a886257f54619f39581e", "a8e8d2f9d5963831f538607a833ff6af1ba69c24"], ["a8e8d2f9d5963831f538607a833ff6af1ba69c24", "5c1139745c6f31114ecddc63a402557e9a006e67"]]}, "stepsbystage": {"detsim": [{"_nodeid": "0483a180e42a866615a6a886257f54619f39581e"}], "recontructiona": [{"_nodeid": "a8e8d2f9d5963831f538607a833ff6af1ba69c24"}], "init": [{"_nodeid": "5abccf6823d64bdecc4a6c25038dd9fd30e7a8fd"}], "generate": [{"_nodeid": "1419713e4025a908173cf21991b443e58a1be4aa"}], "feature_extraction": [{"_nodeid": "5c1139745c6f31114ecddc63a402557e9a006e67"}]}, "bookkeeping": {"_meta": {"rules": ["e12dbd5e7e1a8e668833cfce632e432a31213751", "cfe03a1a2b3a87f4459c7af5a7d11b6dbbad0959", "3476922708146b6abb45e7ccd98e7adaeee0a7f1", "17c0cb65eaff57c4cb034629f923f75edfcc0e70", "22b14659061847a8dfd25f9283081b76a55644c5"], "steps": ["5abccf6823d64bdecc4a6c25038dd9fd30e7a8fd", "1419713e4025a908173cf21991b443e58a1be4aa", "0483a180e42a866615a6a886257f54619f39581e", "a8e8d2f9d5963831f538607a833ff6af1ba69c24", "5c1139745c6f31114ecddc63a402557e9a006e67"]}}}
--------------------------------------------------------------------------------
/demo_weinberg_yadage_full.ipynb:
--------------------------------------------------------------------------------
1 | {
2 | "cells": [
3 | {
4 | "cell_type": "code",
5 | "execution_count": 1,
6 | "metadata": {
7 | "collapsed": true
8 | },
9 | "outputs": [],
10 | "source": [
11 | "import numpy as np\n",
12 | "import matplotlib.pyplot as plt\n",
13 | "import time\n",
14 | "%matplotlib nbagg"
15 | ]
16 | },
17 | {
18 | "cell_type": "code",
19 | "execution_count": 2,
20 | "metadata": {},
21 | "outputs": [
22 | {
23 | "data": {
24 | "application/javascript": [
25 | "require.config({paths: {\n",
26 | " vis: \"http://cdnjs.cloudflare.com/ajax/libs/vis/4.17.0/vis\",\n",
27 | " yadage: \"https://rawgit.com/cranmer/active_sciencing/yadage/yadage\"\n",
28 | " }\n",
29 | "});"
30 | ],
31 | "text/plain": [
32 | ""
33 | ]
34 | },
35 | "metadata": {},
36 | "output_type": "display_data"
37 | }
38 | ],
39 | "source": [
40 | "%%javascript\n",
41 | "require.config({paths: {\n",
42 | " vis: \"http://cdnjs.cloudflare.com/ajax/libs/vis/4.17.0/vis\",\n",
43 | " yadage: \"https://rawgit.com/cranmer/active_sciencing/yadage/yadage\"\n",
44 | " }\n",
45 | "});"
46 | ]
47 | },
48 | {
49 | "cell_type": "code",
50 | "execution_count": 3,
51 | "metadata": {
52 | "collapsed": true
53 | },
54 | "outputs": [],
55 | "source": [
56 | "import distr\n",
57 | "import common\n",
58 | "import plots"
59 | ]
60 | },
61 | {
62 | "cell_type": "code",
63 | "execution_count": 11,
64 | "metadata": {
65 | "collapsed": true
66 | },
67 | "outputs": [],
68 | "source": [
69 | "import models.model_weinberg_yadage_full as model"
70 | ]
71 | },
72 | {
73 | "cell_type": "code",
74 | "execution_count": 12,
75 | "metadata": {
76 | "collapsed": true
77 | },
78 | "outputs": [],
79 | "source": [
80 | "science_ndata = 20\n",
81 | "science_theta_nature = 1.0"
82 | ]
83 | },
84 | {
85 | "cell_type": "code",
86 | "execution_count": 13,
87 | "metadata": {
88 | "collapsed": true
89 | },
90 | "outputs": [],
91 | "source": [
92 | "def collect_data(phi,ndata, widget = None):\n",
93 | " return model.simulator(science_theta_nature,phi,ndata, widget, delay = True)"
94 | ]
95 | },
96 | {
97 | "cell_type": "code",
98 | "execution_count": 14,
99 | "metadata": {
100 | "collapsed": true
101 | },
102 | "outputs": [],
103 | "source": [
104 | "def calculate_posterior(prior,data,phi):\n",
105 | " posterior = common.calculate_posterior(\n",
106 | " prior,data,phi,\n",
107 | " lnprob_args = model.details_likelihood_settings,\n",
108 | " n_chainlen = 50\n",
109 | " )\n",
110 | " maximum_a_post = posterior.map(model.details_map_bins)\n",
111 | " \n",
112 | " print 'Best Theta: ', maximum_a_post\n",
113 | " return posterior, maximum_a_post"
114 | ]
115 | },
116 | {
117 | "cell_type": "code",
118 | "execution_count": 15,
119 | "metadata": {
120 | "collapsed": true
121 | },
122 | "outputs": [],
123 | "source": [
124 | "def design_next_experiment(prior, ax = None, fig = None, widget = None):\n",
125 | " eig_settings = common.eig_search_settings(model,science_ndata, widget.children[0])\n",
126 | " \n",
127 | " res_gp = common.design_next_experiment_bayesopt(\n",
128 | " prior,model.phi_range,eig_settings,\n",
129 | " n_random_calls = 2,n_totalcalls = 10,\n",
130 | " ax = ax, fig = fig, widget = widget.children[1]\n",
131 | " )\n",
132 | " res_next_phi = res_gp[0].x[0]\n",
133 | " \n",
134 | " print 'Next Phi: ', res_next_phi\n",
135 | " return res_gp,res_next_phi"
136 | ]
137 | },
138 | {
139 | "cell_type": "code",
140 | "execution_count": 16,
141 | "metadata": {},
142 | "outputs": [
143 | {
144 | "data": {
145 | "application/vnd.jupyter.widget-view+json": {
146 | "model_id": "8c24fae61b6840ff887e1ee7993eeabf"
147 | }
148 | },
149 | "metadata": {},
150 | "output_type": "display_data"
151 | }
152 | ],
153 | "source": [
154 | "widgets, subwidgets = common.overview_widgets(model)\n",
155 | "widgets"
156 | ]
157 | },
158 | {
159 | "cell_type": "code",
160 | "execution_count": 17,
161 | "metadata": {},
162 | "outputs": [
163 | {
164 | "data": {
165 | "application/javascript": [
166 | "/* Put everything inside the global mpl namespace */\n",
167 | "window.mpl = {};\n",
168 | "\n",
169 | "\n",
170 | "mpl.get_websocket_type = function() {\n",
171 | " if (typeof(WebSocket) !== 'undefined') {\n",
172 | " return WebSocket;\n",
173 | " } else if (typeof(MozWebSocket) !== 'undefined') {\n",
174 | " return MozWebSocket;\n",
175 | " } else {\n",
176 | " alert('Your browser does not have WebSocket support.' +\n",
177 | " 'Please try Chrome, Safari or Firefox ≥ 6. ' +\n",
178 | " 'Firefox 4 and 5 are also supported but you ' +\n",
179 | " 'have to enable WebSockets in about:config.');\n",
180 | " };\n",
181 | "}\n",
182 | "\n",
183 | "mpl.figure = function(figure_id, websocket, ondownload, parent_element) {\n",
184 | " this.id = figure_id;\n",
185 | "\n",
186 | " this.ws = websocket;\n",
187 | "\n",
188 | " this.supports_binary = (this.ws.binaryType != undefined);\n",
189 | "\n",
190 | " if (!this.supports_binary) {\n",
191 | " var warnings = document.getElementById(\"mpl-warnings\");\n",
192 | " if (warnings) {\n",
193 | " warnings.style.display = 'block';\n",
194 | " warnings.textContent = (\n",
195 | " \"This browser does not support binary websocket messages. \" +\n",
196 | " \"Performance may be slow.\");\n",
197 | " }\n",
198 | " }\n",
199 | "\n",
200 | " this.imageObj = new Image();\n",
201 | "\n",
202 | " this.context = undefined;\n",
203 | " this.message = undefined;\n",
204 | " this.canvas = undefined;\n",
205 | " this.rubberband_canvas = undefined;\n",
206 | " this.rubberband_context = undefined;\n",
207 | " this.format_dropdown = undefined;\n",
208 | "\n",
209 | " this.image_mode = 'full';\n",
210 | "\n",
211 | " this.root = $('');\n",
212 | " this._root_extra_style(this.root)\n",
213 | " this.root.attr('style', 'display: inline-block');\n",
214 | "\n",
215 | " $(parent_element).append(this.root);\n",
216 | "\n",
217 | " this._init_header(this);\n",
218 | " this._init_canvas(this);\n",
219 | " this._init_toolbar(this);\n",
220 | "\n",
221 | " var fig = this;\n",
222 | "\n",
223 | " this.waiting = false;\n",
224 | "\n",
225 | " this.ws.onopen = function () {\n",
226 | " fig.send_message(\"supports_binary\", {value: fig.supports_binary});\n",
227 | " fig.send_message(\"send_image_mode\", {});\n",
228 | " if (mpl.ratio != 1) {\n",
229 | " fig.send_message(\"set_dpi_ratio\", {'dpi_ratio': mpl.ratio});\n",
230 | " }\n",
231 | " fig.send_message(\"refresh\", {});\n",
232 | " }\n",
233 | "\n",
234 | " this.imageObj.onload = function() {\n",
235 | " if (fig.image_mode == 'full') {\n",
236 | " // Full images could contain transparency (where diff images\n",
237 | " // almost always do), so we need to clear the canvas so that\n",
238 | " // there is no ghosting.\n",
239 | " fig.context.clearRect(0, 0, fig.canvas.width, fig.canvas.height);\n",
240 | " }\n",
241 | " fig.context.drawImage(fig.imageObj, 0, 0);\n",
242 | " };\n",
243 | "\n",
244 | " this.imageObj.onunload = function() {\n",
245 | " this.ws.close();\n",
246 | " }\n",
247 | "\n",
248 | " this.ws.onmessage = this._make_on_message_function(this);\n",
249 | "\n",
250 | " this.ondownload = ondownload;\n",
251 | "}\n",
252 | "\n",
253 | "mpl.figure.prototype._init_header = function() {\n",
254 | " var titlebar = $(\n",
255 | " '');\n",
257 | " var titletext = $(\n",
258 | " '');\n",
260 | " titlebar.append(titletext)\n",
261 | " this.root.append(titlebar);\n",
262 | " this.header = titletext[0];\n",
263 | "}\n",
264 | "\n",
265 | "\n",
266 | "\n",
267 | "mpl.figure.prototype._canvas_extra_style = function(canvas_div) {\n",
268 | "\n",
269 | "}\n",
270 | "\n",
271 | "\n",
272 | "mpl.figure.prototype._root_extra_style = function(canvas_div) {\n",
273 | "\n",
274 | "}\n",
275 | "\n",
276 | "mpl.figure.prototype._init_canvas = function() {\n",
277 | " var fig = this;\n",
278 | "\n",
279 | " var canvas_div = $('');\n",
280 | "\n",
281 | " canvas_div.attr('style', 'position: relative; clear: both; outline: 0');\n",
282 | "\n",
283 | " function canvas_keyboard_event(event) {\n",
284 | " return fig.key_event(event, event['data']);\n",
285 | " }\n",
286 | "\n",
287 | " canvas_div.keydown('key_press', canvas_keyboard_event);\n",
288 | " canvas_div.keyup('key_release', canvas_keyboard_event);\n",
289 | " this.canvas_div = canvas_div\n",
290 | " this._canvas_extra_style(canvas_div)\n",
291 | " this.root.append(canvas_div);\n",
292 | "\n",
293 | " var canvas = $('');\n",
294 | " canvas.addClass('mpl-canvas');\n",
295 | " canvas.attr('style', \"left: 0; top: 0; z-index: 0; outline: 0\")\n",
296 | "\n",
297 | " this.canvas = canvas[0];\n",
298 | " this.context = canvas[0].getContext(\"2d\");\n",
299 | "\n",
300 | " var backingStore = this.context.backingStorePixelRatio ||\n",
301 | "\tthis.context.webkitBackingStorePixelRatio ||\n",
302 | "\tthis.context.mozBackingStorePixelRatio ||\n",
303 | "\tthis.context.msBackingStorePixelRatio ||\n",
304 | "\tthis.context.oBackingStorePixelRatio ||\n",
305 | "\tthis.context.backingStorePixelRatio || 1;\n",
306 | "\n",
307 | " mpl.ratio = (window.devicePixelRatio || 1) / backingStore;\n",
308 | "\n",
309 | " var rubberband = $('');\n",
310 | " rubberband.attr('style', \"position: absolute; left: 0; top: 0; z-index: 1;\")\n",
311 | "\n",
312 | " var pass_mouse_events = true;\n",
313 | "\n",
314 | " canvas_div.resizable({\n",
315 | " start: function(event, ui) {\n",
316 | " pass_mouse_events = false;\n",
317 | " },\n",
318 | " resize: function(event, ui) {\n",
319 | " fig.request_resize(ui.size.width, ui.size.height);\n",
320 | " },\n",
321 | " stop: function(event, ui) {\n",
322 | " pass_mouse_events = true;\n",
323 | " fig.request_resize(ui.size.width, ui.size.height);\n",
324 | " },\n",
325 | " });\n",
326 | "\n",
327 | " function mouse_event_fn(event) {\n",
328 | " if (pass_mouse_events)\n",
329 | " return fig.mouse_event(event, event['data']);\n",
330 | " }\n",
331 | "\n",
332 | " rubberband.mousedown('button_press', mouse_event_fn);\n",
333 | " rubberband.mouseup('button_release', mouse_event_fn);\n",
334 | " // Throttle sequential mouse events to 1 every 20ms.\n",
335 | " rubberband.mousemove('motion_notify', mouse_event_fn);\n",
336 | "\n",
337 | " rubberband.mouseenter('figure_enter', mouse_event_fn);\n",
338 | " rubberband.mouseleave('figure_leave', mouse_event_fn);\n",
339 | "\n",
340 | " canvas_div.on(\"wheel\", function (event) {\n",
341 | " event = event.originalEvent;\n",
342 | " event['data'] = 'scroll'\n",
343 | " if (event.deltaY < 0) {\n",
344 | " event.step = 1;\n",
345 | " } else {\n",
346 | " event.step = -1;\n",
347 | " }\n",
348 | " mouse_event_fn(event);\n",
349 | " });\n",
350 | "\n",
351 | " canvas_div.append(canvas);\n",
352 | " canvas_div.append(rubberband);\n",
353 | "\n",
354 | " this.rubberband = rubberband;\n",
355 | " this.rubberband_canvas = rubberband[0];\n",
356 | " this.rubberband_context = rubberband[0].getContext(\"2d\");\n",
357 | " this.rubberband_context.strokeStyle = \"#000000\";\n",
358 | "\n",
359 | " this._resize_canvas = function(width, height) {\n",
360 | " // Keep the size of the canvas, canvas container, and rubber band\n",
361 | " // canvas in synch.\n",
362 | " canvas_div.css('width', width)\n",
363 | " canvas_div.css('height', height)\n",
364 | "\n",
365 | " canvas.attr('width', width * mpl.ratio);\n",
366 | " canvas.attr('height', height * mpl.ratio);\n",
367 | " canvas.attr('style', 'width: ' + width + 'px; height: ' + height + 'px;');\n",
368 | "\n",
369 | " rubberband.attr('width', width);\n",
370 | " rubberband.attr('height', height);\n",
371 | " }\n",
372 | "\n",
373 | " // Set the figure to an initial 600x600px, this will subsequently be updated\n",
374 | " // upon first draw.\n",
375 | " this._resize_canvas(600, 600);\n",
376 | "\n",
377 | " // Disable right mouse context menu.\n",
378 | " $(this.rubberband_canvas).bind(\"contextmenu\",function(e){\n",
379 | " return false;\n",
380 | " });\n",
381 | "\n",
382 | " function set_focus () {\n",
383 | " canvas.focus();\n",
384 | " canvas_div.focus();\n",
385 | " }\n",
386 | "\n",
387 | " window.setTimeout(set_focus, 100);\n",
388 | "}\n",
389 | "\n",
390 | "mpl.figure.prototype._init_toolbar = function() {\n",
391 | " var fig = this;\n",
392 | "\n",
393 | " var nav_element = $('')\n",
394 | " nav_element.attr('style', 'width: 100%');\n",
395 | " this.root.append(nav_element);\n",
396 | "\n",
397 | " // Define a callback function for later on.\n",
398 | " function toolbar_event(event) {\n",
399 | " return fig.toolbar_button_onclick(event['data']);\n",
400 | " }\n",
401 | " function toolbar_mouse_event(event) {\n",
402 | " return fig.toolbar_button_onmouseover(event['data']);\n",
403 | " }\n",
404 | "\n",
405 | " for(var toolbar_ind in mpl.toolbar_items) {\n",
406 | " var name = mpl.toolbar_items[toolbar_ind][0];\n",
407 | " var tooltip = mpl.toolbar_items[toolbar_ind][1];\n",
408 | " var image = mpl.toolbar_items[toolbar_ind][2];\n",
409 | " var method_name = mpl.toolbar_items[toolbar_ind][3];\n",
410 | "\n",
411 | " if (!name) {\n",
412 | " // put a spacer in here.\n",
413 | " continue;\n",
414 | " }\n",
415 | " var button = $('');\n",
416 | " button.addClass('ui-button ui-widget ui-state-default ui-corner-all ' +\n",
417 | " 'ui-button-icon-only');\n",
418 | " button.attr('role', 'button');\n",
419 | " button.attr('aria-disabled', 'false');\n",
420 | " button.click(method_name, toolbar_event);\n",
421 | " button.mouseover(tooltip, toolbar_mouse_event);\n",
422 | "\n",
423 | " var icon_img = $('');\n",
424 | " icon_img.addClass('ui-button-icon-primary ui-icon');\n",
425 | " icon_img.addClass(image);\n",
426 | " icon_img.addClass('ui-corner-all');\n",
427 | "\n",
428 | " var tooltip_span = $('');\n",
429 | " tooltip_span.addClass('ui-button-text');\n",
430 | " tooltip_span.html(tooltip);\n",
431 | "\n",
432 | " button.append(icon_img);\n",
433 | " button.append(tooltip_span);\n",
434 | "\n",
435 | " nav_element.append(button);\n",
436 | " }\n",
437 | "\n",
438 | " var fmt_picker_span = $('');\n",
439 | "\n",
440 | " var fmt_picker = $('');\n",
441 | " fmt_picker.addClass('mpl-toolbar-option ui-widget ui-widget-content');\n",
442 | " fmt_picker_span.append(fmt_picker);\n",
443 | " nav_element.append(fmt_picker_span);\n",
444 | " this.format_dropdown = fmt_picker[0];\n",
445 | "\n",
446 | " for (var ind in mpl.extensions) {\n",
447 | " var fmt = mpl.extensions[ind];\n",
448 | " var option = $(\n",
449 | " '', {selected: fmt === mpl.default_extension}).html(fmt);\n",
450 | " fmt_picker.append(option)\n",
451 | " }\n",
452 | "\n",
453 | " // Add hover states to the ui-buttons\n",
454 | " $( \".ui-button\" ).hover(\n",
455 | " function() { $(this).addClass(\"ui-state-hover\");},\n",
456 | " function() { $(this).removeClass(\"ui-state-hover\");}\n",
457 | " );\n",
458 | "\n",
459 | " var status_bar = $('');\n",
460 | " nav_element.append(status_bar);\n",
461 | " this.message = status_bar[0];\n",
462 | "}\n",
463 | "\n",
464 | "mpl.figure.prototype.request_resize = function(x_pixels, y_pixels) {\n",
465 | " // Request matplotlib to resize the figure. Matplotlib will then trigger a resize in the client,\n",
466 | " // which will in turn request a refresh of the image.\n",
467 | " this.send_message('resize', {'width': x_pixels, 'height': y_pixels});\n",
468 | "}\n",
469 | "\n",
470 | "mpl.figure.prototype.send_message = function(type, properties) {\n",
471 | " properties['type'] = type;\n",
472 | " properties['figure_id'] = this.id;\n",
473 | " this.ws.send(JSON.stringify(properties));\n",
474 | "}\n",
475 | "\n",
476 | "mpl.figure.prototype.send_draw_message = function() {\n",
477 | " if (!this.waiting) {\n",
478 | " this.waiting = true;\n",
479 | " this.ws.send(JSON.stringify({type: \"draw\", figure_id: this.id}));\n",
480 | " }\n",
481 | "}\n",
482 | "\n",
483 | "\n",
484 | "mpl.figure.prototype.handle_save = function(fig, msg) {\n",
485 | " var format_dropdown = fig.format_dropdown;\n",
486 | " var format = format_dropdown.options[format_dropdown.selectedIndex].value;\n",
487 | " fig.ondownload(fig, format);\n",
488 | "}\n",
489 | "\n",
490 | "\n",
491 | "mpl.figure.prototype.handle_resize = function(fig, msg) {\n",
492 | " var size = msg['size'];\n",
493 | " if (size[0] != fig.canvas.width || size[1] != fig.canvas.height) {\n",
494 | " fig._resize_canvas(size[0], size[1]);\n",
495 | " fig.send_message(\"refresh\", {});\n",
496 | " };\n",
497 | "}\n",
498 | "\n",
499 | "mpl.figure.prototype.handle_rubberband = function(fig, msg) {\n",
500 | " var x0 = msg['x0'] / mpl.ratio;\n",
501 | " var y0 = (fig.canvas.height - msg['y0']) / mpl.ratio;\n",
502 | " var x1 = msg['x1'] / mpl.ratio;\n",
503 | " var y1 = (fig.canvas.height - msg['y1']) / mpl.ratio;\n",
504 | " x0 = Math.floor(x0) + 0.5;\n",
505 | " y0 = Math.floor(y0) + 0.5;\n",
506 | " x1 = Math.floor(x1) + 0.5;\n",
507 | " y1 = Math.floor(y1) + 0.5;\n",
508 | " var min_x = Math.min(x0, x1);\n",
509 | " var min_y = Math.min(y0, y1);\n",
510 | " var width = Math.abs(x1 - x0);\n",
511 | " var height = Math.abs(y1 - y0);\n",
512 | "\n",
513 | " fig.rubberband_context.clearRect(\n",
514 | " 0, 0, fig.canvas.width, fig.canvas.height);\n",
515 | "\n",
516 | " fig.rubberband_context.strokeRect(min_x, min_y, width, height);\n",
517 | "}\n",
518 | "\n",
519 | "mpl.figure.prototype.handle_figure_label = function(fig, msg) {\n",
520 | " // Updates the figure title.\n",
521 | " fig.header.textContent = msg['label'];\n",
522 | "}\n",
523 | "\n",
524 | "mpl.figure.prototype.handle_cursor = function(fig, msg) {\n",
525 | " var cursor = msg['cursor'];\n",
526 | " switch(cursor)\n",
527 | " {\n",
528 | " case 0:\n",
529 | " cursor = 'pointer';\n",
530 | " break;\n",
531 | " case 1:\n",
532 | " cursor = 'default';\n",
533 | " break;\n",
534 | " case 2:\n",
535 | " cursor = 'crosshair';\n",
536 | " break;\n",
537 | " case 3:\n",
538 | " cursor = 'move';\n",
539 | " break;\n",
540 | " }\n",
541 | " fig.rubberband_canvas.style.cursor = cursor;\n",
542 | "}\n",
543 | "\n",
544 | "mpl.figure.prototype.handle_message = function(fig, msg) {\n",
545 | " fig.message.textContent = msg['message'];\n",
546 | "}\n",
547 | "\n",
548 | "mpl.figure.prototype.handle_draw = function(fig, msg) {\n",
549 | " // Request the server to send over a new figure.\n",
550 | " fig.send_draw_message();\n",
551 | "}\n",
552 | "\n",
553 | "mpl.figure.prototype.handle_image_mode = function(fig, msg) {\n",
554 | " fig.image_mode = msg['mode'];\n",
555 | "}\n",
556 | "\n",
557 | "mpl.figure.prototype.updated_canvas_event = function() {\n",
558 | " // Called whenever the canvas gets updated.\n",
559 | " this.send_message(\"ack\", {});\n",
560 | "}\n",
561 | "\n",
562 | "// A function to construct a web socket function for onmessage handling.\n",
563 | "// Called in the figure constructor.\n",
564 | "mpl.figure.prototype._make_on_message_function = function(fig) {\n",
565 | " return function socket_on_message(evt) {\n",
566 | " if (evt.data instanceof Blob) {\n",
567 | " /* FIXME: We get \"Resource interpreted as Image but\n",
568 | " * transferred with MIME type text/plain:\" errors on\n",
569 | " * Chrome. But how to set the MIME type? It doesn't seem\n",
570 | " * to be part of the websocket stream */\n",
571 | " evt.data.type = \"image/png\";\n",
572 | "\n",
573 | " /* Free the memory for the previous frames */\n",
574 | " if (fig.imageObj.src) {\n",
575 | " (window.URL || window.webkitURL).revokeObjectURL(\n",
576 | " fig.imageObj.src);\n",
577 | " }\n",
578 | "\n",
579 | " fig.imageObj.src = (window.URL || window.webkitURL).createObjectURL(\n",
580 | " evt.data);\n",
581 | " fig.updated_canvas_event();\n",
582 | " fig.waiting = false;\n",
583 | " return;\n",
584 | " }\n",
585 | " else if (typeof evt.data === 'string' && evt.data.slice(0, 21) == \"data:image/png;base64\") {\n",
586 | " fig.imageObj.src = evt.data;\n",
587 | " fig.updated_canvas_event();\n",
588 | " fig.waiting = false;\n",
589 | " return;\n",
590 | " }\n",
591 | "\n",
592 | " var msg = JSON.parse(evt.data);\n",
593 | " var msg_type = msg['type'];\n",
594 | "\n",
595 | " // Call the \"handle_{type}\" callback, which takes\n",
596 | " // the figure and JSON message as its only arguments.\n",
597 | " try {\n",
598 | " var callback = fig[\"handle_\" + msg_type];\n",
599 | " } catch (e) {\n",
600 | " console.log(\"No handler for the '\" + msg_type + \"' message type: \", msg);\n",
601 | " return;\n",
602 | " }\n",
603 | "\n",
604 | " if (callback) {\n",
605 | " try {\n",
606 | " // console.log(\"Handling '\" + msg_type + \"' message: \", msg);\n",
607 | " callback(fig, msg);\n",
608 | " } catch (e) {\n",
609 | " console.log(\"Exception inside the 'handler_\" + msg_type + \"' callback:\", e, e.stack, msg);\n",
610 | " }\n",
611 | " }\n",
612 | " };\n",
613 | "}\n",
614 | "\n",
615 | "// from http://stackoverflow.com/questions/1114465/getting-mouse-location-in-canvas\n",
616 | "mpl.findpos = function(e) {\n",
617 | " //this section is from http://www.quirksmode.org/js/events_properties.html\n",
618 | " var targ;\n",
619 | " if (!e)\n",
620 | " e = window.event;\n",
621 | " if (e.target)\n",
622 | " targ = e.target;\n",
623 | " else if (e.srcElement)\n",
624 | " targ = e.srcElement;\n",
625 | " if (targ.nodeType == 3) // defeat Safari bug\n",
626 | " targ = targ.parentNode;\n",
627 | "\n",
628 | " // jQuery normalizes the pageX and pageY\n",
629 | " // pageX,Y are the mouse positions relative to the document\n",
630 | " // offset() returns the position of the element relative to the document\n",
631 | " var x = e.pageX - $(targ).offset().left;\n",
632 | " var y = e.pageY - $(targ).offset().top;\n",
633 | "\n",
634 | " return {\"x\": x, \"y\": y};\n",
635 | "};\n",
636 | "\n",
637 | "/*\n",
638 | " * return a copy of an object with only non-object keys\n",
639 | " * we need this to avoid circular references\n",
640 | " * http://stackoverflow.com/a/24161582/3208463\n",
641 | " */\n",
642 | "function simpleKeys (original) {\n",
643 | " return Object.keys(original).reduce(function (obj, key) {\n",
644 | " if (typeof original[key] !== 'object')\n",
645 | " obj[key] = original[key]\n",
646 | " return obj;\n",
647 | " }, {});\n",
648 | "}\n",
649 | "\n",
650 | "mpl.figure.prototype.mouse_event = function(event, name) {\n",
651 | " var canvas_pos = mpl.findpos(event)\n",
652 | "\n",
653 | " if (name === 'button_press')\n",
654 | " {\n",
655 | " this.canvas.focus();\n",
656 | " this.canvas_div.focus();\n",
657 | " }\n",
658 | "\n",
659 | " var x = canvas_pos.x * mpl.ratio;\n",
660 | " var y = canvas_pos.y * mpl.ratio;\n",
661 | "\n",
662 | " this.send_message(name, {x: x, y: y, button: event.button,\n",
663 | " step: event.step,\n",
664 | " guiEvent: simpleKeys(event)});\n",
665 | "\n",
666 | " /* This prevents the web browser from automatically changing to\n",
667 | " * the text insertion cursor when the button is pressed. We want\n",
668 | " * to control all of the cursor setting manually through the\n",
669 | " * 'cursor' event from matplotlib */\n",
670 | " event.preventDefault();\n",
671 | " return false;\n",
672 | "}\n",
673 | "\n",
674 | "mpl.figure.prototype._key_event_extra = function(event, name) {\n",
675 | " // Handle any extra behaviour associated with a key event\n",
676 | "}\n",
677 | "\n",
678 | "mpl.figure.prototype.key_event = function(event, name) {\n",
679 | "\n",
680 | " // Prevent repeat events\n",
681 | " if (name == 'key_press')\n",
682 | " {\n",
683 | " if (event.which === this._key)\n",
684 | " return;\n",
685 | " else\n",
686 | " this._key = event.which;\n",
687 | " }\n",
688 | " if (name == 'key_release')\n",
689 | " this._key = null;\n",
690 | "\n",
691 | " var value = '';\n",
692 | " if (event.ctrlKey && event.which != 17)\n",
693 | " value += \"ctrl+\";\n",
694 | " if (event.altKey && event.which != 18)\n",
695 | " value += \"alt+\";\n",
696 | " if (event.shiftKey && event.which != 16)\n",
697 | " value += \"shift+\";\n",
698 | "\n",
699 | " value += 'k';\n",
700 | " value += event.which.toString();\n",
701 | "\n",
702 | " this._key_event_extra(event, name);\n",
703 | "\n",
704 | " this.send_message(name, {key: value,\n",
705 | " guiEvent: simpleKeys(event)});\n",
706 | " return false;\n",
707 | "}\n",
708 | "\n",
709 | "mpl.figure.prototype.toolbar_button_onclick = function(name) {\n",
710 | " if (name == 'download') {\n",
711 | " this.handle_save(this, null);\n",
712 | " } else {\n",
713 | " this.send_message(\"toolbar_button\", {name: name});\n",
714 | " }\n",
715 | "};\n",
716 | "\n",
717 | "mpl.figure.prototype.toolbar_button_onmouseover = function(tooltip) {\n",
718 | " this.message.textContent = tooltip;\n",
719 | "};\n",
720 | "mpl.toolbar_items = [[\"Home\", \"Reset original view\", \"fa fa-home icon-home\", \"home\"], [\"Back\", \"Back to previous view\", \"fa fa-arrow-left icon-arrow-left\", \"back\"], [\"Forward\", \"Forward to next view\", \"fa fa-arrow-right icon-arrow-right\", \"forward\"], [\"\", \"\", \"\", \"\"], [\"Pan\", \"Pan axes with left mouse, zoom with right\", \"fa fa-arrows icon-move\", \"pan\"], [\"Zoom\", \"Zoom to rectangle\", \"fa fa-square-o icon-check-empty\", \"zoom\"], [\"\", \"\", \"\", \"\"], [\"Download\", \"Download plot\", \"fa fa-floppy-o icon-save\", \"download\"]];\n",
721 | "\n",
722 | "mpl.extensions = [\"eps\", \"pdf\", \"png\", \"ps\", \"raw\", \"svg\"];\n",
723 | "\n",
724 | "mpl.default_extension = \"png\";var comm_websocket_adapter = function(comm) {\n",
725 | " // Create a \"websocket\"-like object which calls the given IPython comm\n",
726 | " // object with the appropriate methods. Currently this is a non binary\n",
727 | " // socket, so there is still some room for performance tuning.\n",
728 | " var ws = {};\n",
729 | "\n",
730 | " ws.close = function() {\n",
731 | " comm.close()\n",
732 | " };\n",
733 | " ws.send = function(m) {\n",
734 | " //console.log('sending', m);\n",
735 | " comm.send(m);\n",
736 | " };\n",
737 | " // Register the callback with on_msg.\n",
738 | " comm.on_msg(function(msg) {\n",
739 | " //console.log('receiving', msg['content']['data'], msg);\n",
740 | " // Pass the mpl event to the overriden (by mpl) onmessage function.\n",
741 | " ws.onmessage(msg['content']['data'])\n",
742 | " });\n",
743 | " return ws;\n",
744 | "}\n",
745 | "\n",
746 | "mpl.mpl_figure_comm = function(comm, msg) {\n",
747 | " // This is the function which gets called when the mpl process\n",
748 | " // starts-up an IPython Comm through the \"matplotlib\" channel.\n",
749 | "\n",
750 | " var id = msg.content.data.id;\n",
751 | " // Get hold of the div created by the display call when the Comm\n",
752 | " // socket was opened in Python.\n",
753 | " var element = $(\"#\" + id);\n",
754 | " var ws_proxy = comm_websocket_adapter(comm)\n",
755 | "\n",
756 | " function ondownload(figure, format) {\n",
757 | " window.open(figure.imageObj.src);\n",
758 | " }\n",
759 | "\n",
760 | " var fig = new mpl.figure(id, ws_proxy,\n",
761 | " ondownload,\n",
762 | " element.get(0));\n",
763 | "\n",
764 | " // Call onopen now - mpl needs it, as it is assuming we've passed it a real\n",
765 | " // web socket which is closed, not our websocket->open comm proxy.\n",
766 | " ws_proxy.onopen();\n",
767 | "\n",
768 | " fig.parent_element = element.get(0);\n",
769 | " fig.cell_info = mpl.find_output_cell(\"\");\n",
770 | " if (!fig.cell_info) {\n",
771 | " console.error(\"Failed to find cell for figure\", id, fig);\n",
772 | " return;\n",
773 | " }\n",
774 | "\n",
775 | " var output_index = fig.cell_info[2]\n",
776 | " var cell = fig.cell_info[0];\n",
777 | "\n",
778 | "};\n",
779 | "\n",
780 | "mpl.figure.prototype.handle_close = function(fig, msg) {\n",
781 | " var width = fig.canvas.width/mpl.ratio\n",
782 | " fig.root.unbind('remove')\n",
783 | "\n",
784 | " // Update the output cell to use the data from the current canvas.\n",
785 | " fig.push_to_output();\n",
786 | " var dataURL = fig.canvas.toDataURL();\n",
787 | " // Re-enable the keyboard manager in IPython - without this line, in FF,\n",
788 | " // the notebook keyboard shortcuts fail.\n",
789 | " IPython.keyboard_manager.enable()\n",
790 | " $(fig.parent_element).html('
');\n",
791 | " fig.close_ws(fig, msg);\n",
792 | "}\n",
793 | "\n",
794 | "mpl.figure.prototype.close_ws = function(fig, msg){\n",
795 | " fig.send_message('closing', msg);\n",
796 | " // fig.ws.close()\n",
797 | "}\n",
798 | "\n",
799 | "mpl.figure.prototype.push_to_output = function(remove_interactive) {\n",
800 | " // Turn the data on the canvas into data in the output cell.\n",
801 | " var width = this.canvas.width/mpl.ratio\n",
802 | " var dataURL = this.canvas.toDataURL();\n",
803 | " this.cell_info[1]['text/html'] = '
';\n",
804 | "}\n",
805 | "\n",
806 | "mpl.figure.prototype.updated_canvas_event = function() {\n",
807 | " // Tell IPython that the notebook contents must change.\n",
808 | " IPython.notebook.set_dirty(true);\n",
809 | " this.send_message(\"ack\", {});\n",
810 | " var fig = this;\n",
811 | " // Wait a second, then push the new image to the DOM so\n",
812 | " // that it is saved nicely (might be nice to debounce this).\n",
813 | " setTimeout(function () { fig.push_to_output() }, 1000);\n",
814 | "}\n",
815 | "\n",
816 | "mpl.figure.prototype._init_toolbar = function() {\n",
817 | " var fig = this;\n",
818 | "\n",
819 | " var nav_element = $('')\n",
820 | " nav_element.attr('style', 'width: 100%');\n",
821 | " this.root.append(nav_element);\n",
822 | "\n",
823 | " // Define a callback function for later on.\n",
824 | " function toolbar_event(event) {\n",
825 | " return fig.toolbar_button_onclick(event['data']);\n",
826 | " }\n",
827 | " function toolbar_mouse_event(event) {\n",
828 | " return fig.toolbar_button_onmouseover(event['data']);\n",
829 | " }\n",
830 | "\n",
831 | " for(var toolbar_ind in mpl.toolbar_items){\n",
832 | " var name = mpl.toolbar_items[toolbar_ind][0];\n",
833 | " var tooltip = mpl.toolbar_items[toolbar_ind][1];\n",
834 | " var image = mpl.toolbar_items[toolbar_ind][2];\n",
835 | " var method_name = mpl.toolbar_items[toolbar_ind][3];\n",
836 | "\n",
837 | " if (!name) { continue; };\n",
838 | "\n",
839 | " var button = $('');\n",
840 | " button.click(method_name, toolbar_event);\n",
841 | " button.mouseover(tooltip, toolbar_mouse_event);\n",
842 | " nav_element.append(button);\n",
843 | " }\n",
844 | "\n",
845 | " // Add the status bar.\n",
846 | " var status_bar = $('');\n",
847 | " nav_element.append(status_bar);\n",
848 | " this.message = status_bar[0];\n",
849 | "\n",
850 | " // Add the close button to the window.\n",
851 | " var buttongrp = $('');\n",
852 | " var button = $('');\n",
853 | " button.click(function (evt) { fig.handle_close(fig, {}); } );\n",
854 | " button.mouseover('Stop Interaction', toolbar_mouse_event);\n",
855 | " buttongrp.append(button);\n",
856 | " var titlebar = this.root.find($('.ui-dialog-titlebar'));\n",
857 | " titlebar.prepend(buttongrp);\n",
858 | "}\n",
859 | "\n",
860 | "mpl.figure.prototype._root_extra_style = function(el){\n",
861 | " var fig = this\n",
862 | " el.on(\"remove\", function(){\n",
863 | "\tfig.close_ws(fig, {});\n",
864 | " });\n",
865 | "}\n",
866 | "\n",
867 | "mpl.figure.prototype._canvas_extra_style = function(el){\n",
868 | " // this is important to make the div 'focusable\n",
869 | " el.attr('tabindex', 0)\n",
870 | " // reach out to IPython and tell the keyboard manager to turn it's self\n",
871 | " // off when our div gets focus\n",
872 | "\n",
873 | " // location in version 3\n",
874 | " if (IPython.notebook.keyboard_manager) {\n",
875 | " IPython.notebook.keyboard_manager.register_events(el);\n",
876 | " }\n",
877 | " else {\n",
878 | " // location in version 2\n",
879 | " IPython.keyboard_manager.register_events(el);\n",
880 | " }\n",
881 | "\n",
882 | "}\n",
883 | "\n",
884 | "mpl.figure.prototype._key_event_extra = function(event, name) {\n",
885 | " var manager = IPython.notebook.keyboard_manager;\n",
886 | " if (!manager)\n",
887 | " manager = IPython.keyboard_manager;\n",
888 | "\n",
889 | " // Check for shift+enter\n",
890 | " if (event.shiftKey && event.which == 13) {\n",
891 | " this.canvas_div.blur();\n",
892 | " // select the cell after this one\n",
893 | " var index = IPython.notebook.find_cell_index(this.cell_info[0]);\n",
894 | " IPython.notebook.select(index + 1);\n",
895 | " }\n",
896 | "}\n",
897 | "\n",
898 | "mpl.figure.prototype.handle_save = function(fig, msg) {\n",
899 | " fig.ondownload(fig, null);\n",
900 | "}\n",
901 | "\n",
902 | "\n",
903 | "mpl.find_output_cell = function(html_output) {\n",
904 | " // Return the cell and output element which can be found *uniquely* in the notebook.\n",
905 | " // Note - this is a bit hacky, but it is done because the \"notebook_saving.Notebook\"\n",
906 | " // IPython event is triggered only after the cells have been serialised, which for\n",
907 | " // our purposes (turning an active figure into a static one), is too late.\n",
908 | " var cells = IPython.notebook.get_cells();\n",
909 | " var ncells = cells.length;\n",
910 | " for (var i=0; i= 3 moved mimebundle to data attribute of output\n",
917 | " data = data.data;\n",
918 | " }\n",
919 | " if (data['text/html'] == html_output) {\n",
920 | " return [cell, data, j];\n",
921 | " }\n",
922 | " }\n",
923 | " }\n",
924 | " }\n",
925 | "}\n",
926 | "\n",
927 | "// Register the function which deals with the matplotlib target/channel.\n",
928 | "// The kernel may be null if the page has been refreshed.\n",
929 | "if (IPython.notebook.kernel != null) {\n",
930 | " IPython.notebook.kernel.comm_manager.register_target('matplotlib', mpl.mpl_figure_comm);\n",
931 | "}\n"
932 | ],
933 | "text/plain": [
934 | ""
935 | ]
936 | },
937 | "metadata": {},
938 | "output_type": "display_data"
939 | },
940 | {
941 | "data": {
942 | "text/html": [
943 | "
"
944 | ],
945 | "text/plain": [
946 | ""
947 | ]
948 | },
949 | "metadata": {},
950 | "output_type": "display_data"
951 | }
952 | ],
953 | "source": [
954 | "n_science_iterations = 2\n",
955 | "fig,axarr = plt.subplots(n_science_iterations,3)\n",
956 | "fig.set_size_inches(9,4)"
957 | ]
958 | },
959 | {
960 | "cell_type": "markdown",
961 | "metadata": {},
962 | "source": [
963 | "# Running the Science Loop"
964 | ]
965 | },
966 | {
967 | "cell_type": "code",
968 | "execution_count": 18,
969 | "metadata": {
970 | "collapsed": true
971 | },
972 | "outputs": [],
973 | "source": [
974 | "# initial experimental settings and uninformative prior\n",
975 | "loop_phi = 47\n",
976 | "loop_prior = distr.Distribution('prior',range = model.theta_range)"
977 | ]
978 | },
979 | {
980 | "cell_type": "code",
981 | "execution_count": null,
982 | "metadata": {
983 | "scrolled": false
984 | },
985 | "outputs": [
986 | {
987 | "name": "stdout",
988 | "output_type": "stream",
989 | "text": [
990 | "................................"
991 | ]
992 | }
993 | ],
994 | "source": [
995 | "science_history = []\n",
996 | "for i in range(n_science_iterations):\n",
997 | " ## 1. Perform Experiment\n",
998 | " subwidgets[0].toggle(0)\n",
999 | " loop_data = collect_data(loop_phi,science_ndata, widget = subwidgets[1])\n",
1000 | " plots.plot_data(loop_data,model.data_range, ax = axarr[i][0])\n",
1001 | " fig.canvas.draw()\n",
1002 | "\n",
1003 | " ## 2. Calculate the Posterior\n",
1004 | " subwidgets[0].toggle(1)\n",
1005 | " loop_posterior, loop_best_theta = calculate_posterior(loop_prior,loop_data,loop_phi)\n",
1006 | " plots.plot_posterior(loop_prior,loop_posterior,loop_best_theta,science_theta_nature, model.theta_range, ax = axarr[i][1])\n",
1007 | " fig.canvas.draw()\n",
1008 | "\n",
1009 | " ## 3. Design Next Experiment\n",
1010 | " subwidgets[0].toggle(2)\n",
1011 | " loop_res_gp, loop_next_phi = design_next_experiment(loop_posterior,ax = axarr[i][2], fig = fig, widget = subwidgets[2])\n",
1012 | "\n",
1013 | " science_history.append([loop_data,loop_prior,loop_posterior,loop_best_theta,science_theta_nature,loop_res_gp])\n",
1014 | " \n",
1015 | " ## 5. Update our Prior and experimental settings\n",
1016 | " loop_prior = loop_posterior\n",
1017 | " loop_phi = loop_next_phi\n",
1018 | " time.sleep(5) # appreciate plots!"
1019 | ]
1020 | },
1021 | {
1022 | "cell_type": "code",
1023 | "execution_count": null,
1024 | "metadata": {
1025 | "collapsed": true
1026 | },
1027 | "outputs": [],
1028 | "source": []
1029 | },
1030 | {
1031 | "cell_type": "code",
1032 | "execution_count": null,
1033 | "metadata": {
1034 | "collapsed": true
1035 | },
1036 | "outputs": [],
1037 | "source": []
1038 | }
1039 | ],
1040 | "metadata": {
1041 | "kernelspec": {
1042 | "display_name": "Python 2",
1043 | "language": "python",
1044 | "name": "python2"
1045 | },
1046 | "language_info": {
1047 | "codemirror_mode": {
1048 | "name": "ipython",
1049 | "version": 2
1050 | },
1051 | "file_extension": ".py",
1052 | "mimetype": "text/x-python",
1053 | "name": "python",
1054 | "nbconvert_exporter": "python",
1055 | "pygments_lexer": "ipython2",
1056 | "version": "2.7.10"
1057 | },
1058 | "widgets": {
1059 | "application/vnd.jupyter.widget-state+json": {
1060 | "state": {
1061 | "01a366cf61424432b8d9a468272b102b": {
1062 | "model_module": "jupyter-js-widgets",
1063 | "model_module_version": "~2.1.4",
1064 | "model_name": "LayoutModel",
1065 | "state": {
1066 | "_model_module_version": "~2.1.4",
1067 | "_view_module_version": "~2.1.4"
1068 | }
1069 | },
1070 | "1b4c4e3f0d4a43c3987f23dbd962e070": {
1071 | "model_module": "jupyter-js-widgets",
1072 | "model_module_version": "~2.1.4",
1073 | "model_name": "ProgressStyleModel",
1074 | "state": {
1075 | "_model_module_version": "~2.1.4",
1076 | "_view_module_version": "~2.1.4"
1077 | }
1078 | },
1079 | "1c888353367247b6ba94a90833c4f306": {
1080 | "model_module": "jupyter-js-widgets",
1081 | "model_module_version": "~2.1.4",
1082 | "model_name": "HTMLModel",
1083 | "state": {
1084 | "_model_module_version": "~2.1.4",
1085 | "_view_module_version": "~2.1.4",
1086 | "layout": "IPY_MODEL_b2fdce7813f9493abac5ab26ad15f903",
1087 | "value": "Calculate Posterior"
1088 | }
1089 | },
1090 | "1fc632efe336487ab2c5c9e7c838038c": {
1091 | "model_module": "jupyter-js-widgets",
1092 | "model_module_version": "*",
1093 | "model_name": "DOMWidgetModel",
1094 | "state": {
1095 | "_model_name": "DOMWidgetModel",
1096 | "_view_module": "yadage",
1097 | "_view_name": "WorkflowWidgetView",
1098 | "dotstring": "strict digraph \"\" {\nlabel=\"2017-06-10 00:18:44\";\n\"116a090760f82b249a50cbf4d9417441128109c1\" [color=grey, label=\"detsim \", style=filled];\n\"39c07ba58542605f58c21f9e8eec90386c4354a2\" [color=green, label=\"init \", style=filled];\nc33642a93bc2c90be3b3043ac4063d5c7126c908 [color=grey, label=\"recontructiona \", style=filled];\n\"9c25f77a6deaf75a1f5022d0237029e7ce460798\" [color=grey, label=\"feature_extraction \", style=filled];\nd6f2191579ca80eae1486473198911cad93e53bf [color=green, label=\"generate \", style=filled];\n\"116a090760f82b249a50cbf4d9417441128109c1\" -> c33642a93bc2c90be3b3043ac4063d5c7126c908;\n\"39c07ba58542605f58c21f9e8eec90386c4354a2\" -> d6f2191579ca80eae1486473198911cad93e53bf;\nc33642a93bc2c90be3b3043ac4063d5c7126c908 -> \"9c25f77a6deaf75a1f5022d0237029e7ce460798\";\nd6f2191579ca80eae1486473198911cad93e53bf -> \"116a090760f82b249a50cbf4d9417441128109c1\";\n}\n",
1099 | "layout": "IPY_MODEL_01a366cf61424432b8d9a468272b102b"
1100 | }
1101 | },
1102 | "326cdd39903243bdbed5069203f2b5b6": {
1103 | "model_module": "jupyter-js-widgets",
1104 | "model_module_version": "~2.1.4",
1105 | "model_name": "HBoxModel",
1106 | "state": {
1107 | "_model_module_version": "~2.1.4",
1108 | "_view_module_version": "~2.1.4",
1109 | "children": [
1110 | "IPY_MODEL_d58d28691c024df5a20b84ac2ae43d0a",
1111 | "IPY_MODEL_1fc632efe336487ab2c5c9e7c838038c",
1112 | "IPY_MODEL_9dbd3b093ac34c1993b01f04163fd080"
1113 | ],
1114 | "layout": "IPY_MODEL_a865804e637445b5acc4d414106662e1"
1115 | }
1116 | },
1117 | "8641c534b6ce4b5485b9ee5509d9c36c": {
1118 | "model_module": "jupyter-js-widgets",
1119 | "model_module_version": "~2.1.4",
1120 | "model_name": "LayoutModel",
1121 | "state": {
1122 | "_model_module_version": "~2.1.4",
1123 | "_view_module_version": "~2.1.4"
1124 | }
1125 | },
1126 | "8744542628b54c0b9ccec7ca51060ce9": {
1127 | "model_module": "jupyter-js-widgets",
1128 | "model_module_version": "~2.1.4",
1129 | "model_name": "LayoutModel",
1130 | "state": {
1131 | "_model_module_version": "~2.1.4",
1132 | "_view_module_version": "~2.1.4"
1133 | }
1134 | },
1135 | "89ad3a7ba84c4b0c80ae00477757cd73": {
1136 | "model_module": "jupyter-js-widgets",
1137 | "model_module_version": "~2.1.4",
1138 | "model_name": "HTMLModel",
1139 | "state": {
1140 | "_model_module_version": "~2.1.4",
1141 | "_view_module_version": "~2.1.4",
1142 | "layout": "IPY_MODEL_b2fdce7813f9493abac5ab26ad15f903",
1143 | "value": "Design Next"
1144 | }
1145 | },
1146 | "9dbd3b093ac34c1993b01f04163fd080": {
1147 | "model_module": "jupyter-js-widgets",
1148 | "model_module_version": "~2.1.4",
1149 | "model_name": "ProgressModel",
1150 | "state": {
1151 | "_model_module_version": "~2.1.4",
1152 | "_view_module_version": "~2.1.4",
1153 | "description": "Calculating EIG: ",
1154 | "layout": "IPY_MODEL_8744542628b54c0b9ccec7ca51060ce9",
1155 | "max": 10,
1156 | "style": "IPY_MODEL_1b4c4e3f0d4a43c3987f23dbd962e070"
1157 | }
1158 | },
1159 | "a865804e637445b5acc4d414106662e1": {
1160 | "model_module": "jupyter-js-widgets",
1161 | "model_module_version": "~2.1.4",
1162 | "model_name": "LayoutModel",
1163 | "state": {
1164 | "_model_module_version": "~2.1.4",
1165 | "_view_module_version": "~2.1.4"
1166 | }
1167 | },
1168 | "b2fdce7813f9493abac5ab26ad15f903": {
1169 | "model_module": "jupyter-js-widgets",
1170 | "model_module_version": "~2.1.4",
1171 | "model_name": "LayoutModel",
1172 | "state": {
1173 | "_model_module_version": "~2.1.4",
1174 | "_view_module_version": "~2.1.4",
1175 | "height": "50px",
1176 | "width": "200px"
1177 | }
1178 | },
1179 | "d58d28691c024df5a20b84ac2ae43d0a": {
1180 | "model_module": "jupyter-js-widgets",
1181 | "model_module_version": "~2.1.4",
1182 | "model_name": "VBoxModel",
1183 | "state": {
1184 | "_model_module_version": "~2.1.4",
1185 | "_view_module_version": "~2.1.4",
1186 | "children": [
1187 | "IPY_MODEL_e01fe6d07fbd42539ca030c32393531f",
1188 | "IPY_MODEL_1c888353367247b6ba94a90833c4f306",
1189 | "IPY_MODEL_89ad3a7ba84c4b0c80ae00477757cd73"
1190 | ],
1191 | "layout": "IPY_MODEL_8641c534b6ce4b5485b9ee5509d9c36c"
1192 | }
1193 | },
1194 | "e01fe6d07fbd42539ca030c32393531f": {
1195 | "model_module": "jupyter-js-widgets",
1196 | "model_module_version": "~2.1.4",
1197 | "model_name": "HTMLModel",
1198 | "state": {
1199 | "_model_module_version": "~2.1.4",
1200 | "_view_module_version": "~2.1.4",
1201 | "layout": "IPY_MODEL_b2fdce7813f9493abac5ab26ad15f903",
1202 | "value": "Collect Data"
1203 | }
1204 | }
1205 | },
1206 | "version_major": 1,
1207 | "version_minor": 0
1208 | }
1209 | }
1210 | },
1211 | "nbformat": 4,
1212 | "nbformat_minor": 2
1213 | }
1214 |
--------------------------------------------------------------------------------