Dataset Viewer
Auto-converted to Parquet
repo
stringclasses
140 values
pull_number
int64
6
32.7k
instance_id
stringlengths
14
45
issue_numbers
sequencelengths
1
4
base_commit
stringlengths
40
40
patch
stringlengths
186
106k
test_patch
stringlengths
128
7.54M
problem_statement
stringlengths
10
256k
hints_text
stringlengths
0
294k
created_at
timestamp[s]date
2013-01-01 17:21:42
2024-06-28 23:53:55
version
stringclasses
1 value
scikit-hep/pyhf
119
scikit-hep__pyhf-119
[ "66" ]
25bfff7f3f1779c6df98e5aafa132df88ae5bc75
diff --git a/pyhf/__init__.py b/pyhf/__init__.py --- a/pyhf/__init__.py +++ b/pyhf/__init__.py @@ -24,9 +24,10 @@ def get_backend(): return tensorlib, optimizer # modifiers need access to tensorlib -# make sure import is below get_backend() +# make sure import is below get_backend() from . import modifiers + def set_backend(backend): """ Set the backend and the associated optimizer @@ -39,7 +40,9 @@ def set_backend(backend): None Example: - pyhf.set_backend(tensorflow_backend(session=tf.Session())) + import pyhf.tensor as tensor + import tensorflow as tf + pyhf.set_backend(tensor.tensorflow_backend(session=tf.Session())) """ global tensorlib global optimizer @@ -47,10 +50,10 @@ def set_backend(backend): tensorlib = backend if isinstance(tensorlib, tensor.tensorflow_backend): optimizer = optimize.tflow_optimizer(tensorlib) - elif isinstance(tensorlib,tensor.pytorch_backend): + elif isinstance(tensorlib, tensor.pytorch_backend): optimizer = optimize.pytorch_optimizer(tensorlib=tensorlib) # TODO: Add support for mxnet_optimizer() - # elif isinstance(tensorlib, mxnet_backend): + # elif isinstance(tensorlib, tensor.mxnet_backend): # optimizer = mxnet_optimizer() else: optimizer = optimize.scipy_optimizer()
diff --git a/tests/benchmarks/test_benchmark.py b/tests/benchmarks/test_benchmark.py --- a/tests/benchmarks/test_benchmark.py +++ b/tests/benchmarks/test_benchmark.py @@ -85,7 +85,7 @@ def runOnePoint(pdf, data): pyhf.tensor.numpy_backend(poisson_from_normal=True), pyhf.tensor.tensorflow_backend(session=tf.Session()), pyhf.tensor.pytorch_backend(), - # mxnet_backend(), + # pyhf.tensor.mxnet_backend(), ], ids=[ 'numpy', @@ -113,10 +113,4 @@ def test_runOnePoint(benchmark, backend, n_bins): source['bindata']['bkg'], source['bindata']['bkgerr']) data = source['bindata']['data'] + pdf.config.auxdata - try: - assert benchmark(runOnePoint, pdf, data) is not None - except AssertionError: - print('benchmarking has failed for n_bins = {}'.formant(n_bins)) - assert False - - # Reset backend + assert benchmark(runOnePoint, pdf, data) diff --git a/tests/test_optim.py b/tests/test_optim.py --- a/tests/test_optim.py +++ b/tests/test_optim.py @@ -1,119 +1,25 @@ import pyhf import tensorflow as tf +import pytest -def test_optim_numpy(): [email protected](scope='module') +def source(): source = { - "binning": [2,-0.5,1.5], - "bindata": { - "data": [120.0, 180.0], - "bkg": [100.0, 150.0], - "bkgsys_up": [102, 190], - "bkgsys_dn": [98, 100], - "sig": [30.0, 95.0] - } + 'binning': [2, -0.5, 1.5], + 'bindata': { + 'data': [120.0, 180.0], + 'bkg': [100.0, 150.0], + 'bkgsys_up': [102, 190], + 'bkgsys_dn': [98, 100], + 'sig': [30.0, 95.0] + } } - spec = { - 'channels': [ - { - 'name': 'singlechannel', - 'samples': [ - { - 'name': 'signal', - 'data': source['bindata']['sig'], - 'modifiers': [ - {'name': 'mu', 'type': 'normfactor', 'data': None} - ] - }, - { - 'name': 'background', - 'data': source['bindata']['bkg'], - 'modifiers': [ - {'name': 'bkg_norm', 'type': 'histosys', 'data': {'lo_data': source['bindata']['bkgsys_dn'], 'hi_data': source['bindata']['bkgsys_up']}} - ] - } - ] - } - ] - } - pdf = pyhf.hfpdf(spec) - data = source['bindata']['data'] + pdf.config.auxdata - - init_pars = pdf.config.suggested_init() - par_bounds = pdf.config.suggested_bounds() - - pyhf.set_backend(pyhf.tensor.numpy_backend(poisson_from_normal=True)) - optim = pyhf.optimizer - - v1 = pdf.logpdf(init_pars, data) - result = optim.unconstrained_bestfit(pyhf.loglambdav, data, pdf, init_pars, par_bounds) - assert pyhf.tensorlib.tolist(result) - - result = optim.constrained_bestfit(pyhf.loglambdav, 1.0, data, pdf, init_pars, par_bounds) - assert pyhf.tensorlib.tolist(result) - - -def test_optim_pytorch(): - source = { - "binning": [2,-0.5,1.5], - "bindata": { - "data": [120.0, 180.0], - "bkg": [100.0, 150.0], - "bkgsys_up": [102, 190], - "bkgsys_dn": [98, 100], - "sig": [30.0, 95.0] - } - } - spec = { - 'channels': [ - { - 'name': 'singlechannel', - 'samples': [ - { - 'name': 'signal', - 'data': source['bindata']['sig'], - 'modifiers': [ - {'name': 'mu', 'type': 'normfactor', 'data': None} - ] - }, - { - 'name': 'background', - 'data': source['bindata']['bkg'], - 'modifiers': [ - {'name': 'bkg_norm', 'type': 'histosys', 'data': {'lo_data': source['bindata']['bkgsys_dn'], 'hi_data': source['bindata']['bkgsys_up']}} - ] - } - ] - } - ] - } - pdf = pyhf.hfpdf(spec) - data = source['bindata']['data'] + pdf.config.auxdata + return source - init_pars = pdf.config.suggested_init() - par_bounds = pdf.config.suggested_bounds() - pyhf.set_backend(pyhf.tensor.pytorch_backend(poisson_from_normal=True)) - optim = pyhf.optimizer - - result = optim.unconstrained_bestfit(pyhf.loglambdav, data, pdf, init_pars, par_bounds) - assert pyhf.tensorlib.tolist(result) - - result = optim.constrained_bestfit(pyhf.loglambdav, 1.0, data, pdf, init_pars, par_bounds) - assert pyhf.tensorlib.tolist(result) - - -def test_optim_tflow(): - source = { - "binning": [2,-0.5,1.5], - "bindata": { - "data": [120.0, 180.0], - "bkg": [100.0, 150.0], - "bkgsys_up": [102, 190], - "bkgsys_dn": [98, 100], - "sig": [30.0, 95.0] - } - } [email protected](scope='module') +def spec(source): spec = { 'channels': [ { @@ -123,32 +29,71 @@ def test_optim_tflow(): 'name': 'signal', 'data': source['bindata']['sig'], 'modifiers': [ - {'name': 'mu', 'type': 'normfactor', 'data': None} + { + 'name': 'mu', + 'type': 'normfactor', + 'data': None + } ] }, { 'name': 'background', 'data': source['bindata']['bkg'], 'modifiers': [ - {'name': 'bkg_norm', 'type': 'histosys', 'data': {'lo_data': source['bindata']['bkgsys_dn'], 'hi_data': source['bindata']['bkgsys_up']}} + { + 'name': 'bkg_norm', + 'type': 'histosys', + 'data': { + 'lo_data': source['bindata']['bkgsys_dn'], + 'hi_data': source['bindata']['bkgsys_up'] + } + } ] } ] } ] } + return spec + + [email protected]('mu', + [ + 1., + ], + ids=[ + 'mu=1', + ]) [email protected]('backend', + [ + pyhf.tensor.numpy_backend(poisson_from_normal=True), + pyhf.tensor.tensorflow_backend(session=tf.Session()), + pyhf.tensor.pytorch_backend(poisson_from_normal=True), + # pyhf.tensor.mxnet_backend(), + ], + ids=[ + 'numpy', + 'tensorflow', + 'pytorch', + # 'mxnet', + ]) +def test_optim(source, spec, mu, backend): pdf = pyhf.hfpdf(spec) data = source['bindata']['data'] + pdf.config.auxdata init_pars = pdf.config.suggested_init() par_bounds = pdf.config.suggested_bounds() - pyhf.set_backend(pyhf.tensor.tensorflow_backend()) - pyhf.tensorlib.session = tf.Session() + pyhf.set_backend(backend) optim = pyhf.optimizer + if isinstance(pyhf.tensorlib, pyhf.tensor.tensorflow_backend): + tf.reset_default_graph() + pyhf.tensorlib.session = tf.Session() - result = optim.unconstrained_bestfit(pyhf.loglambdav, data, pdf, init_pars, par_bounds) + result = optim.unconstrained_bestfit( + pyhf.loglambdav, data, pdf, init_pars, par_bounds) assert pyhf.tensorlib.tolist(result) - result = optim.constrained_bestfit(pyhf.loglambdav, 1.0, data, pdf, init_pars, par_bounds) + result = optim.constrained_bestfit( + pyhf.loglambdav, mu, data, pdf, init_pars, par_bounds) assert pyhf.tensorlib.tolist(result) diff --git a/tests/test_validation.py b/tests/test_validation.py --- a/tests/test_validation.py +++ b/tests/test_validation.py @@ -1,61 +1,17 @@ import pyhf -import pyhf.simplemodels -import numpy as np -import json -VALIDATION_TOLERANCE = 1e-5 - -def test_validation_1bin_shapesys(): - expected_result = { - 'obs': 0.4541865416107029, - 'exp': [ - 0.06371799398864626, - 0.15096503398048894, - 0.3279606950533305, - 0.6046087303039118, - 0.8662627605298466 - ] - } +import json +import jsonschema +import pytest - source = json.load(open('validation/data/1bin_example1.json')) - pdf = pyhf.simplemodels.hepdata_like(source['bindata']['sig'], source['bindata']['bkg'], source['bindata']['bkgerr']) [email protected](scope='module') +def source_1bin_example1(): + return json.load(open('validation/data/1bin_example1.json')) - data = source['bindata']['data'] + pdf.config.auxdata - muTest = 1.0 - assert len(pdf.config.suggested_init()) == 2 - assert len(pdf.config.suggested_bounds()) == 2 - init_pars = pdf.config.suggested_init() - par_bounds = pdf.config.suggested_bounds() - - clsobs, cls_exp = pyhf.runOnePoint(muTest, data,pdf,init_pars,par_bounds)[-2:] - cls_obs = 1./clsobs - cls_exp = [1./x for x in cls_exp] - assert (cls_obs - expected_result['obs'])/expected_result['obs'] < VALIDATION_TOLERANCE - for result,expected_result in zip(cls_exp, expected_result['exp']): - assert (result-expected_result)/expected_result < VALIDATION_TOLERANCE - - -def test_validation_1bin_normsys(): - expected_result = { - 'obs': 0.0007930094233140433, - 'exp': [ - 1.2529050370718884e-09, - 8.932001833559302e-08, - 5.3294967286010575e-06, - 0.00022773982308763686, - 0.0054897420571466075 - ] - } - source = { - "binning": [2,-0.5,1.5], - "bindata": { - "data": [120.0, 180.0], - "bkg": [100.0, 150.0], - "sig": [30.0, 95.0] - } - } [email protected](scope='module') +def spec_1bin_shapesys(source=source_1bin_example1()): spec = { 'channels': [ { @@ -65,52 +21,81 @@ def test_validation_1bin_normsys(): 'name': 'signal', 'data': source['bindata']['sig'], 'modifiers': [ - {'name': 'mu', 'type': 'normfactor', 'data': None} + { + 'name': 'mu', + 'type': 'normfactor', + 'data': None + } ] }, { 'name': 'background', 'data': source['bindata']['bkg'], 'modifiers': [ - {'name': 'bkg_norm', 'type': 'normsys', 'data': {'lo': 0.90, 'hi': 1.10}} + { + 'name': 'uncorr_bkguncrt', + 'type': 'shapesys', + 'data': source['bindata']['bkgerr'] + } ] } ] } ] } - pdf = pyhf.hfpdf(spec) - - data = source['bindata']['data'] + pdf.config.auxdata - - muTest = 1.0 - - assert len(pdf.config.suggested_init()) == 2 - assert len(pdf.config.suggested_bounds()) == 2 - init_pars = pdf.config.suggested_init() - par_bounds = pdf.config.suggested_bounds() + schema = json.load(open('validation/spec.json')) + jsonschema.validate(spec, schema) + return spec + + [email protected](scope='module') +def expected_result_1bin_shapesys(mu=1.): + if mu == 1: + expected_result = { + 'obs': 0.4541865416107029, + 'exp': [ + 0.06371799398864626, + 0.15096503398048894, + 0.3279606950533305, + 0.6046087303039118, + 0.8662627605298466 + ] + } + return expected_result + + [email protected](scope='module') +def setup_1bin_shapesys(source=source_1bin_example1(), + spec=spec_1bin_shapesys(source_1bin_example1()), + mu=1, + expected_result=expected_result_1bin_shapesys(1.), + config={'init_pars': 2, 'par_bounds': 2}): + return { + 'source': source, + 'spec': spec, + 'mu': mu, + 'expected': { + 'result': expected_result, + 'config': config + } + } - clsobs, cls_exp = pyhf.runOnePoint(muTest, data,pdf,init_pars,par_bounds)[-2:] - cls_obs = 1./clsobs - cls_exp = [1./x for x in cls_exp] - assert (cls_obs - expected_result['obs'])/expected_result['obs'] < VALIDATION_TOLERANCE - for result,expected_result in zip(cls_exp, expected_result['exp']): - assert (result-expected_result)/expected_result < VALIDATION_TOLERANCE [email protected](scope='module') +def source_1bin_normsys(): + source = { + 'binning': [2, -0.5, 1.5], + 'bindata': { + 'data': [120.0, 180.0], + 'bkg': [100.0, 150.0], + 'sig': [30.0, 95.0] + } + } + return source -def test_validation_2bin_histosys(): - expected_result = { - 'obs': 0.10014623469489856, - 'exp': [ - 8.131143652258812e-06, - 0.0001396307700293439, - 0.0020437905684851376, - 0.022094931468776054, - 0.14246926685789288, - ] - } - source = json.load(open('validation/data/2bin_histosys_example2.json')) [email protected](scope='module') +def spec_1bin_normsys(source=source_1bin_normsys()): spec = { 'channels': [ { @@ -120,54 +105,154 @@ def test_validation_2bin_histosys(): 'name': 'signal', 'data': source['bindata']['sig'], 'modifiers': [ - {'name': 'mu', 'type': 'normfactor', 'data': None} + { + 'name': 'mu', + 'type': 'normfactor', + 'data': None + } ] }, { 'name': 'background', 'data': source['bindata']['bkg'], 'modifiers': [ - {'name': 'bkg_norm', 'type': 'histosys', 'data': {'lo_data': source['bindata']['bkgsys_dn'], 'hi_data': source['bindata']['bkgsys_up']}} + { + 'name': 'bkg_norm', + 'type': 'normsys', + 'data': {'lo': 0.90, 'hi': 1.10} + } ] } ] } ] } - pdf = pyhf.hfpdf(spec) + schema = json.load(open('validation/spec.json')) + jsonschema.validate(spec, schema) + return spec + + [email protected](scope='module') +def expected_result_1bin_normsys(mu=1.): + if mu == 1: + expected_result = { + 'obs': 0.0007930094233140433, + 'exp': [ + 1.2529050370718884e-09, + 8.932001833559302e-08, + 5.3294967286010575e-06, + 0.00022773982308763686, + 0.0054897420571466075 + ] + } + return expected_result + + [email protected](scope='module') +def setup_1bin_normsys(source=source_1bin_normsys(), + spec=spec_1bin_normsys(source_1bin_normsys()), + mu=1, + expected_result=expected_result_1bin_normsys(1.), + config={'init_pars': 2, 'par_bounds': 2}): + return { + 'source': source, + 'spec': spec, + 'mu': mu, + 'expected': { + 'result': expected_result, + 'config': config + } + } - data = source['bindata']['data'] + pdf.config.auxdata - muTest = 1.0 [email protected](scope='module') +def source_2bin_histosys_example2(): + return json.load(open('validation/data/2bin_histosys_example2.json')) - assert len(pdf.config.suggested_init()) == 2 - assert len(pdf.config.suggested_bounds()) == 2 - init_pars = pdf.config.suggested_init() - par_bounds = pdf.config.suggested_bounds() [email protected](scope='module') +def spec_2bin_histosys(source=source_2bin_histosys_example2()): + spec = { + 'channels': [ + { + 'name': 'singlechannel', + 'samples': [ + { + 'name': 'signal', + 'data': source['bindata']['sig'], + 'modifiers': [ + { + 'name': 'mu', + 'type': 'normfactor', + 'data': None + } + ] + }, + { + 'name': 'background', + 'data': source['bindata']['bkg'], + 'modifiers': [ + { + 'name': 'bkg_norm', + 'type': 'histosys', + 'data': { + 'lo_data': source['bindata']['bkgsys_dn'], + 'hi_data': source['bindata']['bkgsys_up'] + } + } + ] + } + ] + } + ] + } + schema = json.load(open('validation/spec.json')) + jsonschema.validate(spec, schema) + return spec + + [email protected](scope='module') +def expected_result_2bin_histosys(mu=1): + if mu == 1: + expected_result = { + 'obs': 0.10014623469489856, + 'exp': [ + 8.131143652258812e-06, + 0.0001396307700293439, + 0.0020437905684851376, + 0.022094931468776054, + 0.14246926685789288, + ] + } + return expected_result + + [email protected](scope='module') +def setup_2bin_histosys(source=source_2bin_histosys_example2(), + spec=spec_2bin_histosys( + source_2bin_histosys_example2()), + mu=1, + expected_result=expected_result_2bin_histosys(1.), + config={'init_pars': 2, 'par_bounds': 2}): + return { + 'source': source, + 'spec': spec, + 'mu': mu, + 'expected': { + 'result': expected_result, + 'config': config + } + } - clsobs, cls_exp = pyhf.runOnePoint(muTest, data,pdf,init_pars,par_bounds)[-2:] - cls_obs = 1./clsobs - cls_exp = [1./x for x in cls_exp] - assert (cls_obs - expected_result['obs'])/expected_result['obs'] < VALIDATION_TOLERANCE - for result,expected_result in zip(cls_exp, expected_result['exp']): - assert (result-expected_result)/expected_result < VALIDATION_TOLERANCE [email protected](scope='module') +def source_2bin_2channel_example1(): + return json.load(open('validation/data/2bin_2channel_example1.json')) -def test_validation_2bin_2channel(): - expected_result = { - 'obs': 0.05691881515460979, - 'exp': [ - 0.0004448774256747925, - 0.0034839534635069816, - 0.023684793938725246, - 0.12294326553585197, - 0.4058143629613449 - ] - } - source = json.load(open('validation/data/2bin_2channel_example1.json')) - spec = { [email protected](scope='module') +def spec_2bin_2channel(source=source_2bin_2channel_example1()): + spec = { 'channels': [ { 'name': 'signal', @@ -176,14 +261,22 @@ def test_validation_2bin_2channel(): 'name': 'signal', 'data': source['channels']['signal']['bindata']['sig'], 'modifiers': [ - {'name': 'mu', 'type': 'normfactor', 'data': None} + { + 'name': 'mu', + 'type': 'normfactor', + 'data': None + } ] }, { 'name': 'background', 'data': source['channels']['signal']['bindata']['bkg'], 'modifiers': [ - {'name': 'uncorr_bkguncrt_signal', 'type': 'shapesys', 'data': source['channels']['signal']['bindata']['bkgerr']} + { + 'name': 'uncorr_bkguncrt_signal', + 'type': 'shapesys', + 'data': source['channels']['signal']['bindata']['bkgerr'] + } ] } ] @@ -195,47 +288,65 @@ def test_validation_2bin_2channel(): 'name': 'background', 'data': source['channels']['control']['bindata']['bkg'], 'modifiers': [ - {'name': 'uncorr_bkguncrt_control', 'type': 'shapesys', 'data': source['channels']['control']['bindata']['bkgerr']} + { + 'name': 'uncorr_bkguncrt_control', + 'type': 'shapesys', + 'data': source['channels']['control']['bindata']['bkgerr'] + } ] } ] } ] } - pdf = pyhf.hfpdf(spec) - data = [] - for c in pdf.spec['channels']: - data += source['channels'][c['name']]['bindata']['data'] - data = data + pdf.config.auxdata - - muTest = 1.0 - - assert len(pdf.config.suggested_init()) == 5 # 1 mu + 2 gammas for 2 channels each - assert len(pdf.config.suggested_bounds()) == 5 - init_pars = pdf.config.suggested_init() - par_bounds = pdf.config.suggested_bounds() + schema = json.load(open('validation/spec.json')) + jsonschema.validate(spec, schema) + return spec + + [email protected](scope='module') +def expected_result_2bin_2channel(mu=1.): + if mu == 1: + expected_result = { + 'obs': 0.05691881515460979, + 'exp': [ + 0.0004448774256747925, + 0.0034839534635069816, + 0.023684793938725246, + 0.12294326553585197, + 0.4058143629613449 + ] + } + return expected_result + + [email protected](scope='module') +def setup_2bin_2channel(source=source_2bin_2channel_example1(), + spec=spec_2bin_2channel( + source_2bin_2channel_example1()), + mu=1, + expected_result=expected_result_2bin_2channel(1.), + config={'init_pars': 5, 'par_bounds': 5}): + # 1 mu + 2 gammas for 2 channels each + return { + 'source': source, + 'spec': spec, + 'mu': mu, + 'expected': { + 'result': expected_result, + 'config': config + } + } - clsobs, cls_exp = pyhf.runOnePoint(muTest, data,pdf,init_pars,par_bounds)[-2:] - cls_obs = 1./clsobs - cls_exp = [1./x for x in cls_exp] - assert (cls_obs - expected_result['obs'])/expected_result['obs'] < VALIDATION_TOLERANCE - for result,expected_result in zip(cls_exp, expected_result['exp']): - assert (result-expected_result)/expected_result < VALIDATION_TOLERANCE [email protected](scope='module') +def source_2bin_2channel_couplednorm(): + return json.load(open('validation/data/2bin_2channel_couplednorm.json')) -def test_validation_2bin_2channel_couplednorm(): - expected_result = { - 'obs': 0.5999662863185762, - 'exp': [0.06596134134354742, - 0.15477912571478988, - 0.33323967895587736, - 0.6096429330789306, - 0.8688213053042003 - ] - } - source = json.load(open('validation/data/2bin_2channel_couplednorm.json')) - spec = { [email protected](scope='module') +def spec_2bin_2channel_couplednorm(source=source_2bin_2channel_couplednorm()): + spec = { 'channels': [ { 'name': 'signal', @@ -244,21 +355,33 @@ def test_validation_2bin_2channel_couplednorm(): 'name': 'signal', 'data': source['channels']['signal']['bindata']['sig'], 'modifiers': [ - {'name': 'mu', 'type': 'normfactor', 'data': None} + { + 'name': 'mu', + 'type': 'normfactor', + 'data': None + } ] }, { 'name': 'bkg1', 'data': source['channels']['signal']['bindata']['bkg1'], 'modifiers': [ - {'name': 'coupled_normsys', 'type': 'normsys', 'data': {'lo': 0.9, 'hi': 1.1}} + { + 'name': 'coupled_normsys', + 'type': 'normsys', + 'data': {'lo': 0.9, 'hi': 1.1} + } ] }, { 'name': 'bkg2', 'data': source['channels']['signal']['bindata']['bkg2'], 'modifiers': [ - {'name': 'coupled_normsys', 'type': 'normsys', 'data': {'lo': 0.5, 'hi': 1.5}} + { + 'name': 'coupled_normsys', + 'type': 'normsys', + 'data': {'lo': 0.5, 'hi': 1.5} + } ] } ] @@ -270,48 +393,66 @@ def test_validation_2bin_2channel_couplednorm(): 'name': 'background', 'data': source['channels']['control']['bindata']['bkg1'], 'modifiers': [ - {'name': 'coupled_normsys', 'type': 'normsys', 'data': {'lo': 0.9, 'hi': 1.1}} + { + 'name': 'coupled_normsys', + 'type': 'normsys', + 'data': {'lo': 0.9, 'hi': 1.1} + } ] } ] } ] } - pdf = pyhf.hfpdf(spec) - data = [] - for c in pdf.spec['channels']: - data += source['channels'][c['name']]['bindata']['data'] - data = data + pdf.config.auxdata + schema = json.load(open('validation/spec.json')) + jsonschema.validate(spec, schema) + return spec + + [email protected](scope='module') +def expected_result_2bin_2channel_couplednorm(mu=1.): + if mu == 1: + expected_result = { + 'obs': 0.5999662863185762, + 'exp': [ + 0.06596134134354742, + 0.15477912571478988, + 0.33323967895587736, + 0.6096429330789306, + 0.8688213053042003 + ] + } + return expected_result + + [email protected](scope='module') +def setup_2bin_2channel_couplednorm( + source=source_2bin_2channel_couplednorm(), + spec=spec_2bin_2channel_couplednorm( + source_2bin_2channel_couplednorm()), + mu=1, + expected_result=expected_result_2bin_2channel_couplednorm(1.), + config={'init_pars': 2, 'par_bounds': 2}): + # 1 mu + 1 alpha + return { + 'source': source, + 'spec': spec, + 'mu': mu, + 'expected': { + 'result': expected_result, + 'config': config + } + } - muTest = 1.0 - assert len(pdf.config.suggested_init()) == 2 # 1 mu + 1 alpha - assert len(pdf.config.suggested_bounds()) == 2 # 1 mu + 1 alpha - init_pars = pdf.config.suggested_init() - par_bounds = pdf.config.suggested_bounds() [email protected](scope='module') +def source_2bin_2channel_coupledhisto(): + return json.load(open('validation/data/2bin_2channel_coupledhisto.json')) - clsobs, cls_exp = pyhf.runOnePoint(muTest, data,pdf,init_pars,par_bounds)[-2:] - cls_obs = 1./clsobs - cls_exp = [1./x for x in cls_exp] - assert (cls_obs - expected_result['obs'])/expected_result['obs'] < VALIDATION_TOLERANCE - for result,expected_result in zip(cls_exp, expected_result['exp']): - assert (result-expected_result)/expected_result < VALIDATION_TOLERANCE - - - -def test_validation_2bin_2channel_coupledhistosys(): - expected_result = { - 'obs': 0.0796739833305826, - 'exp': [ - 1.765372502072074e-05, - 0.00026265618793683054, - 0.003340033567379219, - 0.03152233566143051, - 0.17907736639946248 - ] - } - source = json.load(open('validation/data/2bin_2channel_coupledhisto.json')) - spec = { + [email protected](scope='module') +def spec_2bin_2channel_coupledhistosys(source=source_2bin_2channel_coupledhisto()): + spec = { 'channels': [ { 'name': 'signal', @@ -320,21 +461,39 @@ def test_validation_2bin_2channel_coupledhistosys(): 'name': 'signal', 'data': source['channels']['signal']['bindata']['sig'], 'modifiers': [ - {'name': 'mu', 'type': 'normfactor', 'data': None} + { + 'name': 'mu', + 'type': 'normfactor', + 'data': None + } ] }, { 'name': 'bkg1', 'data': source['channels']['signal']['bindata']['bkg1'], 'modifiers': [ - {'name': 'coupled_histosys','type': 'histosys', 'data': {'lo_data': source['channels']['signal']['bindata']['bkg1_dn'], 'hi_data': source['channels']['signal']['bindata']['bkg1_up']}} + { + 'name': 'coupled_histosys', + 'type': 'histosys', + 'data': { + 'lo_data': source['channels']['signal']['bindata']['bkg1_dn'], + 'hi_data': source['channels']['signal']['bindata']['bkg1_up'] + } + } ] }, { 'name': 'bkg2', 'data': source['channels']['signal']['bindata']['bkg2'], 'modifiers': [ - {'name': 'coupled_histosys', 'type': 'histosys', 'data': {'lo_data': source['channels']['signal']['bindata']['bkg2_dn'], 'hi_data': source['channels']['signal']['bindata']['bkg2_up']}} + { + 'name': 'coupled_histosys', + 'type': 'histosys', + 'data': { + 'lo_data': source['channels']['signal']['bindata']['bkg2_dn'], + 'hi_data': source['channels']['signal']['bindata']['bkg2_up'] + } + } ] } ] @@ -346,48 +505,69 @@ def test_validation_2bin_2channel_coupledhistosys(): 'name': 'background', 'data': source['channels']['control']['bindata']['bkg1'], 'modifiers': [ - {'name': 'coupled_histosys', 'type': 'histosys', 'data': {'lo_data': source['channels']['control']['bindata']['bkg1_dn'], 'hi_data': source['channels']['control']['bindata']['bkg1_up']}} + { + 'name': 'coupled_histosys', + 'type': 'histosys', + 'data': { + 'lo_data': source['channels']['control']['bindata']['bkg1_dn'], + 'hi_data': source['channels']['control']['bindata']['bkg1_up'] + } + } ] } ] } ] } - pdf = pyhf.hfpdf(spec) - data = [] - for c in pdf.spec['channels']: - data += source['channels'][c['name']]['bindata']['data'] - data = data + pdf.config.auxdata + schema = json.load(open('validation/spec.json')) + jsonschema.validate(spec, schema) + return spec + + [email protected](scope='module') +def expected_result_2bin_2channel_coupledhistosys(mu=1.): + if mu == 1: + expected_result = { + 'obs': 0.0796739833305826, + 'exp': [ + 1.765372502072074e-05, + 0.00026265618793683054, + 0.003340033567379219, + 0.03152233566143051, + 0.17907736639946248 + ] + } + return expected_result + + [email protected](scope='module') +def setup_2bin_2channel_coupledhistosys( + source=source_2bin_2channel_coupledhisto(), + spec=spec_2bin_2channel_coupledhistosys( + source_2bin_2channel_coupledhisto()), + mu=1, + expected_result=expected_result_2bin_2channel_coupledhistosys(1.), + config={'auxdata': 1, 'init_pars': 2, 'par_bounds': 2}): + # 1 mu 1 shared histosys + return { + 'source': source, + 'spec': spec, + 'mu': mu, + 'expected': { + 'result': expected_result, + 'config': config + } + } - init_pars = pdf.config.suggested_init() - par_bounds = pdf.config.suggested_bounds() - assert len(pdf.config.auxdata) == 1 - assert len(init_pars) == 2 #1 mu 1 shared histosys - assert len(par_bounds) == 2 - - muTest = 1.0 - clsobs, cls_exp = pyhf.runOnePoint(muTest, data,pdf,init_pars,par_bounds)[-2:] - cls_obs = 1./clsobs - cls_exp = [1./x for x in cls_exp] - assert (cls_obs - expected_result['obs'])/expected_result['obs'] < VALIDATION_TOLERANCE - for result,expected_result in zip(cls_exp, expected_result['exp']): - assert (result-expected_result)/expected_result < VALIDATION_TOLERANCE - - -def test_validation_2bin_2channel_coupledshapefactor(): - expected_result = { - 'obs': 0.5421679124909312, - 'exp': [ - 0.013753299929451691, - 0.048887400056355966, - 0.15555296253957684, - 0.4007561343326305, - 0.7357169630955912 - ] - } - source = json.load(open('validation/data/2bin_2channel_coupledshapefactor.json')) - spec = { [email protected](scope='module') +def source_2bin_2channel_coupledshapefactor(): + return json.load(open('validation/data/2bin_2channel_coupledshapefactor.json')) + + [email protected](scope='module') +def spec_2bin_2channel_coupledshapefactor(source=source_2bin_2channel_coupledshapefactor()): + spec = { 'channels': [ { 'name': 'signal', @@ -396,14 +576,22 @@ def test_validation_2bin_2channel_coupledshapefactor(): 'name': 'signal', 'data': source['channels']['signal']['bindata']['sig'], 'modifiers': [ - {'name': 'mu', 'type': 'normfactor', 'data': None} + { + 'name': 'mu', + 'type': 'normfactor', + 'data': None + } ] }, { 'name': 'bkg1', 'data': source['channels']['signal']['bindata']['bkg1'], 'modifiers': [ - {'name': 'coupled_shapefactor', 'type': 'shapefactor', 'data': None} + { + 'name': 'coupled_shapefactor', + 'type': 'shapefactor', + 'data': None + } ] } ] @@ -415,30 +603,109 @@ def test_validation_2bin_2channel_coupledshapefactor(): 'name': 'background', 'data': source['channels']['control']['bindata']['bkg1'], 'modifiers': [ - {'name': 'coupled_shapefactor', 'type': 'shapefactor', 'data': None} + { + 'name': 'coupled_shapefactor', + 'type': 'shapefactor', + 'data': None + } ] } ] } ] } - pdf = pyhf.hfpdf(spec) - data = [] - for c in pdf.spec['channels']: - data += source['channels'][c['name']]['bindata']['data'] - data = data + pdf.config.auxdata + schema = json.load(open('validation/spec.json')) + jsonschema.validate(spec, schema) + return spec + + [email protected](scope='module') +def expected_result_2bin_2channel_coupledshapefactor(mu=1.): + if mu == 1: + expected_result = { + 'obs': 0.5421679124909312, + 'exp': [ + 0.013753299929451691, + 0.048887400056355966, + 0.15555296253957684, + 0.4007561343326305, + 0.7357169630955912 + ] + } + return expected_result + + [email protected](scope='module') +def setup_2bin_2channel_coupledshapefactor( + source=source_2bin_2channel_coupledshapefactor(), + spec=spec_2bin_2channel_coupledshapefactor( + source_2bin_2channel_coupledshapefactor()), + mu=1, + expected_result=expected_result_2bin_2channel_coupledshapefactor(1.), + config={'auxdata': 0, 'init_pars': 3, 'par_bounds': 3}): + # 1 mu 2 shared shapefactors + return { + 'source': source, + 'spec': spec, + 'mu': mu, + 'expected': { + 'result': expected_result, + 'config': config + } + } + +def validate_runOnePoint(pdf, data, mu_test, expected_result, tolerance=1e-5): init_pars = pdf.config.suggested_init() par_bounds = pdf.config.suggested_bounds() - assert len(pdf.config.auxdata) == 0 - assert len(init_pars) == 3 #1 mu 2 shared shapefactors - assert len(par_bounds) == 3 - - muTest = 1.0 - clsobs, cls_exp = pyhf.runOnePoint(muTest, data,pdf,init_pars,par_bounds)[-2:] - cls_obs = 1./clsobs - cls_exp = [1./x for x in cls_exp] - assert (cls_obs - expected_result['obs'])/expected_result['obs'] < VALIDATION_TOLERANCE - for result,expected_result in zip(cls_exp, expected_result['exp']): - assert (result-expected_result)/expected_result < VALIDATION_TOLERANCE + CLs_obs, CLs_exp = pyhf.runOnePoint( + mu_test, data, pdf, init_pars, par_bounds)[-2:] + CLs_obs = 1. / CLs_obs + CLs_exp = [1. / x for x in CLs_exp] + assert (CLs_obs - expected_result['obs']) / \ + expected_result['obs'] < tolerance + for result, expected_result in zip(CLs_exp, expected_result['exp']): + assert (result - expected_result) / \ + expected_result < tolerance + + [email protected]('setup', [ + setup_1bin_shapesys(), + setup_1bin_normsys(), + setup_2bin_histosys(), + setup_2bin_2channel(), + setup_2bin_2channel_couplednorm(), + setup_2bin_2channel_coupledhistosys(), + setup_2bin_2channel_coupledshapefactor() +], + ids=[ + '1bin_shapesys_mu1', + '1bin_normsys_mu1', + '2bin_histosys_mu1', + '2bin_2channel_mu1', + '2bin_2channel_couplednorm_mu1', + '2bin_2channel_coupledhistosys_mu1', + '2bin_2channel_coupledshapefactor_mu1' +]) +def test_validation(setup): + source = setup['source'] + pdf = pyhf.hfpdf(setup['spec']) + + if 'channels' in source: + data = [] + for c in pdf.spec['channels']: + data += source['channels'][c['name']]['bindata']['data'] + data = data + pdf.config.auxdata + else: + data = source['bindata']['data'] + pdf.config.auxdata + + if 'auxdata' in setup['expected']['config']: + assert len(pdf.config.auxdata) == \ + setup['expected']['config']['auxdata'] + assert len(pdf.config.suggested_init()) == \ + setup['expected']['config']['init_pars'] + assert len(pdf.config.suggested_bounds()) == \ + setup['expected']['config']['par_bounds'] + + validate_runOnePoint(pdf, data, setup['mu'], setup['expected']['result'])
create proper test fixtures Many of the tests have large blocks of setup code that could be shared as proper `@pytest.fixtures` https://docs.pytest.org/en/latest/fixture.html
2018-04-14T23:04:32
-1.0
scikit-hep/pyhf
126
scikit-hep__pyhf-126
[ "125" ]
f8106a2946d499943339ee642f354396a7a478f7
diff --git a/pyhf/__init__.py b/pyhf/__init__.py --- a/pyhf/__init__.py +++ b/pyhf/__init__.py @@ -5,7 +5,9 @@ log = logging.getLogger(__name__) tensorlib = tensor.numpy_backend() +default_backend = tensorlib optimizer = optimize.scipy_optimizer() +default_optimizer = optimizer def set_backend(backend): """
diff --git a/tests/benchmarks/test_benchmark.py b/tests/benchmarks/test_benchmark.py --- a/tests/benchmarks/test_benchmark.py +++ b/tests/benchmarks/test_benchmark.py @@ -106,7 +106,6 @@ def test_runOnePoint(benchmark, backend, n_bins): Returns: None """ - default_backend = pyhf.tensorlib pyhf.set_backend(backend) source = generate_source_static(n_bins) @@ -118,8 +117,6 @@ def test_runOnePoint(benchmark, backend, n_bins): assert benchmark(runOnePoint, pdf, data) is not None except AssertionError: print('benchmarking has failed for n_bins = {}'.formant(n_bins)) - pyhf.set_backend(default_backend) assert False # Reset backend - pyhf.set_backend(default_backend) diff --git a/tests/conftest.py b/tests/conftest.py new file mode 100644 --- /dev/null +++ b/tests/conftest.py @@ -0,0 +1,7 @@ +import pytest +import pyhf + [email protected](scope='function', autouse=True) +def reset_backend(): + yield reset_backend + pyhf.set_backend(pyhf.default_backend) diff --git a/tests/test_backend_consistency.py b/tests/test_backend_consistency.py --- a/tests/test_backend_consistency.py +++ b/tests/test_backend_consistency.py @@ -4,7 +4,6 @@ import numpy as np import pytest - def generate_source_static(n_bins): """ Create the source structure for the given number of bins. @@ -86,7 +85,6 @@ def test_runOnePoint_q_mu(n_bins, Returns: None """ - default_backend = pyhf.tensorlib source = generate_source_static(n_bins) pdf = hepdata_like(source['bindata']['sig'], @@ -128,15 +126,10 @@ def test_runOnePoint_q_mu(n_bins, except AssertionError: print('Ratio to NumPy+SciPy exceeded tolerance of {}: {}'.format( tolerance['numpy'], numpy_ratio_delta_unity.tolist())) - pyhf.set_backend(default_backend) assert False try: assert (tensors_ratio_delta_unity < tolerance['tensors']).all() except AssertionError: print('Ratio between tensor backends exceeded tolerance of {}: {}'.format( tolerance['tensors'], tensors_ratio_delta_unity.tolist())) - pyhf.set_backend(default_backend) assert False - - # Reset backend - pyhf.set_backend(default_backend) diff --git a/tests/test_optim.py b/tests/test_optim.py --- a/tests/test_optim.py +++ b/tests/test_optim.py @@ -42,7 +42,6 @@ def test_optim_numpy(): init_pars = pdf.config.suggested_init() par_bounds = pdf.config.suggested_bounds() - oldlib = pyhf.tensorlib pyhf.set_backend(pyhf.tensor.numpy_backend(poisson_from_normal=True)) optim = pyhf.optimizer @@ -53,8 +52,6 @@ def test_optim_numpy(): result = optim.constrained_bestfit(pyhf.loglambdav, 1.0, data, pdf, init_pars, par_bounds) assert pyhf.tensorlib.tolist(result) - pyhf.set_backend(oldlib) - def test_optim_pytorch(): source = { @@ -96,8 +93,6 @@ def test_optim_pytorch(): init_pars = pdf.config.suggested_init() par_bounds = pdf.config.suggested_bounds() - oldlib = pyhf.tensorlib - pyhf.set_backend(pyhf.tensor.pytorch_backend(poisson_from_normal=True)) optim = pyhf.optimizer @@ -107,8 +102,6 @@ def test_optim_pytorch(): result = optim.constrained_bestfit(pyhf.loglambdav, 1.0, data, pdf, init_pars, par_bounds) assert pyhf.tensorlib.tolist(result) - pyhf.set_backend(oldlib) - def test_optim_tflow(): source = { @@ -150,8 +143,6 @@ def test_optim_tflow(): init_pars = pdf.config.suggested_init() par_bounds = pdf.config.suggested_bounds() - oldlib = pyhf.tensorlib - pyhf.set_backend(pyhf.tensor.tensorflow_backend()) pyhf.tensorlib.session = tf.Session() optim = pyhf.optimizer @@ -161,5 +152,3 @@ def test_optim_tflow(): result = optim.constrained_bestfit(pyhf.loglambdav, 1.0, data, pdf, init_pars, par_bounds) assert pyhf.tensorlib.tolist(result) - - pyhf.set_backend(oldlib) diff --git a/tests/test_tensor.py b/tests/test_tensor.py --- a/tests/test_tensor.py +++ b/tests/test_tensor.py @@ -41,8 +41,6 @@ def test_common_tensor_backends(): def test_pdf_eval(): - oldlib = pyhf.tensorlib - tf_sess = tf.Session() backends = [numpy_backend(poisson_from_normal=True), pytorch_backend(), @@ -92,12 +90,8 @@ def test_pdf_eval(): assert np.std(values) < 1e-6 - pyhf.set_backend(oldlib) - def test_pdf_eval_2(): - oldlib = pyhf.tensorlib - tf_sess = tf.Session() backends = [numpy_backend(poisson_from_normal=True), pytorch_backend(), @@ -126,5 +120,3 @@ def test_pdf_eval_2(): values.append(pyhf.tensorlib.tolist(v1)[0]) assert np.std(values) < 1e-6 - - pyhf.set_backend(oldlib)
test_backend_consistency not resetting to default backend if test fails unexpectedly # Description A cascading error is observed when test_backend_consistency fails, which keeps the backend as tensorflow and causes all the other tests to erroneously fail. <img width="1550" alt="screenshot 2018-04-15 20 45 50" src="https://user-images.githubusercontent.com/761483/38786764-92380ebc-40ef-11e8-921c-fc20a2d96578.png"> Easy to reproduce, run `pytest` and see `test_pdf.py` fail. Run `pytest tests/test_pdf.py` and see that it's fine (as in screenshot).
@kratsg Does `test_backend_consistency.py` fail when run by itself? > @kratsg Does test_backend_consistency.py fail when run by itself? yes, for me. When I explicitly reset the backend, it stops failing.
2018-04-16T02:30:28
-1.0
scikit-hep/pyhf
136
scikit-hep__pyhf-136
[ "134" ]
c1b506f7a39009b0ddf491a117a4a2005dfb7f15
diff --git a/pyhf/__init__.py b/pyhf/__init__.py --- a/pyhf/__init__.py +++ b/pyhf/__init__.py @@ -1,6 +1,7 @@ import logging import pyhf.optimize as optimize import pyhf.tensor as tensor +from . import exceptions log = logging.getLogger(__name__) tensorlib = tensor.numpy_backend() @@ -147,7 +148,7 @@ def add_or_get_modifier(self, channel, sample, modifier_def): modifier_cls = modifiers.registry[modifier_def['type']] except KeyError: log.exception('Modifier type not implemented yet (processing {0:s}). Current modifier types: {1}'.format(modifier_def['type'], modifiers.registry.keys())) - raise modifiers.InvalidModifier() + raise exceptions.InvalidModifier() # if modifier is shared, check if it already exists and use it if modifier_cls.is_shared and modifier_def['name'] in self.par_map: diff --git a/pyhf/exceptions/__init__.py b/pyhf/exceptions/__init__.py new file mode 100644 --- /dev/null +++ b/pyhf/exceptions/__init__.py @@ -0,0 +1,9 @@ +""" +InvalidModifier is raised when an invalid modifier is requested. This includes: + + - creating a custom modifier with the wrong structure + - initializing a modifier that does not exist, or has not been loaded + +""" +class InvalidModifier(Exception): + pass diff --git a/pyhf/modifiers/__init__.py b/pyhf/modifiers/__init__.py --- a/pyhf/modifiers/__init__.py +++ b/pyhf/modifiers/__init__.py @@ -2,10 +2,9 @@ import logging log = logging.getLogger(__name__) -registry = {} +from .. import exceptions -class InvalidModifier(Exception): - pass +registry = {} ''' Check if given object contains the right structure for constrained and unconstrained modifiers @@ -16,7 +15,7 @@ def validate_modifier_structure(modifier, constrained): for method in required_methods + required_constrained_methods*constrained: if not hasattr(modifier, method): - raise InvalidModifier('Expected {0:s} method on {1:s}constrained modifier {2:s}'.format(method, '' if constrained else 'un', modifier.__name__)) + raise exceptions.InvalidModifier('Expected {0:s} method on {1:s}constrained modifier {2:s}'.format(method, '' if constrained else 'un', modifier.__name__)) return True ''' @@ -51,7 +50,7 @@ def add_to_registry(cls, cls_name=None, constrained=False, shared=False): Raises: ValueError: too many keyword arguments, or too many arguments, or wrong arguments TypeError: provided name is not a string - InvalidModifier: object does not have necessary modifier structure + pyhf.exceptions.InvalidModifier: object does not have necessary modifier structure Examples: @@ -83,7 +82,7 @@ def add_to_registry(cls, cls_name=None, constrained=False, shared=False): >>> ... def __init__(self): pass >>> ... def add_sample(self): pass >>> - InvalidModifier: Expected alphas method on constrained modifier myCustomModifier + pyhf.exceptions.InvalidModifier: Expected alphas method on constrained modifier myCustomModifier ''' def modifier(*args, **kwargs): name = kwargs.pop('name', None)
diff --git a/tests/test_modifiers.py b/tests/test_modifiers.py --- a/tests/test_modifiers.py +++ b/tests/test_modifiers.py @@ -19,7 +19,7 @@ def test_import_default_modifiers(test_modifier): # we make sure modifiers have right structure def test_modifiers_structure(): - from pyhf.modifiers import modifier, InvalidModifier + from pyhf.modifiers import modifier @modifier(name='myUnconstrainedModifier') class myCustomModifier(object): @@ -59,17 +59,17 @@ def expected_data(self): pass assert pyhf.modifiers.registry['myConstrainedModifier'].is_shared == False del pyhf.modifiers.registry['myConstrainedModifier'] - with pytest.raises(InvalidModifier): + with pytest.raises(pyhf.exceptions.InvalidModifier): @modifier class myCustomModifier(object): pass - with pytest.raises(InvalidModifier): + with pytest.raises(pyhf.exceptions.InvalidModifier): @modifier(constrained=True) class myCustomModifier(object): pass - with pytest.raises(InvalidModifier): + with pytest.raises(pyhf.exceptions.InvalidModifier): @modifier(name='myConstrainedModifier', constrained=True) class myCustomModifier(object): def __init__(self): pass diff --git a/tests/test_pdf.py b/tests/test_pdf.py --- a/tests/test_pdf.py +++ b/tests/test_pdf.py @@ -1,7 +1,6 @@ import pyhf import pytest import pyhf.simplemodels -import pyhf.modifiers import numpy as np import json import jsonschema @@ -92,7 +91,7 @@ def test_add_unknown_modifier(): } ] } - with pytest.raises(pyhf.modifiers.InvalidModifier): + with pytest.raises(pyhf.exceptions.InvalidModifier): pyhf.hfpdf(spec)
Add exceptions module for common semantic exceptions # Description Need to have `pyhf/exceptions` which contains various exception classes such as `InvalidModifier` and so on.
2018-04-18T21:59:11
-1.0
scikit-hep/pyhf
164
scikit-hep__pyhf-164
[ "140" ]
6fe8e1d6d930d2bbf008f963a7896526042801fc
diff --git a/pyhf/__init__.py b/pyhf/__init__.py --- a/pyhf/__init__.py +++ b/pyhf/__init__.py @@ -10,6 +10,7 @@ optimizer = optimize.scipy_optimizer() default_optimizer = optimizer + def get_backend(): """ Get the current backend and the associated optimizer @@ -62,6 +63,7 @@ def set_backend(backend): else: optimizer = optimize.scipy_optimizer() + class modelconfig(object): @classmethod def from_spec(cls,spec,poiname = 'mu'): @@ -311,9 +313,11 @@ def loglambdav(pars, data, pdf): def qmu(mu, data, pdf, init_pars, par_bounds): r""" - The test statistic, q_mu, for establishing an upper - limit on the strength parameter, mu, as defiend in - Equation (14) in arXiv:1007.1727 + The test statistic, :math:`q_{\mu}`, for establishing an upper + limit on the strength parameter, :math:`\mu`, as defiend in + Equation (14) in `arXiv:1007.1727`_ . + + .. _`arXiv:1007.1727`: https://arxiv.org/abs/1007.1727 .. math:: :nowrap: @@ -334,7 +338,7 @@ def qmu(mu, data, pdf, init_pars, par_bounds): par_bounds(Tensor): The bounds on the paramter values Returns: - Float: The calculated test statistic, q_mu + Float: The calculated test statistic, :math:`q_{\mu}` """ mubhathat = optimizer.constrained_bestfit( loglambdav, mu, data, pdf, init_pars, par_bounds) @@ -346,13 +350,35 @@ def qmu(mu, data, pdf, init_pars, par_bounds): def pvals_from_teststat(sqrtqmu_v, sqrtqmuA_v): - # these pvals are from formula - # (59) in arxiv:1007.1727 p_mu = 1-F(q_mu|mu') = 1- \Phi(q_mu - (mu-mu')/sigma) - # and (mu-mu')/sigma = sqrt(Lambda)= sqrt(q_mu_A) + r""" + The :math:`p`-values for signal strength :math:`\mu` and Asimov strength :math:`\mu'` + as defined in Equations (59) and (57) of `arXiv:1007.1727`_ + + .. _`arXiv:1007.1727`: https://arxiv.org/abs/1007.1727 + + .. math:: + + p_{\mu} = 1-F\left(q_{\mu}\middle|\mu'\right) = 1- \Phi\left(q_{\mu} - \frac{\left(\mu-\mu'\right)}{\sigma}\right) + + with Equation (29) + + .. math:: + + \frac{(\mu-\mu')}{\sigma} = \sqrt{\Lambda}= \sqrt{q_{\mu,A}} + + given the observed test statistics :math:`q_{\mu}` and :math:`q_{\mu,A}`. + + Args: + sqrtqmu_v (Number or Tensor): The root of the calculated test statistic, :math:`\sqrt{q_{\mu}}` + sqrtqmuA_v (Number or Tensor): The root of the calculated test statistic given the Asimov data, :math:`\sqrt{q_{\mu,A}}` + + Returns: + Tuple of Floats: The :math:`p`-values for the signal + background, background only, and signal only hypotheses respectivley + """ CLsb = 1 - tensorlib.normal_cdf(sqrtqmu_v) CLb = 1 - tensorlib.normal_cdf(sqrtqmu_v - sqrtqmuA_v) - oneOverCLs = CLb / CLsb - return CLsb, CLb, oneOverCLs + CLs = CLsb / CLb + return CLsb, CLb, CLs def runOnePoint(muTest, data, pdf, init_pars, par_bounds): @@ -368,12 +394,12 @@ def runOnePoint(muTest, data, pdf, init_pars, par_bounds): qmu(muTest, asimov_data, pdf, init_pars, par_bounds), 0, max=None) sqrtqmuA_v = tensorlib.sqrt(qmuA_v) - CLsb, CLb, oneOverCLs = pvals_from_teststat(sqrtqmu_v, sqrtqmuA_v) + CLsb, CLb, CLs = pvals_from_teststat(sqrtqmu_v, sqrtqmuA_v) - oneOverCLs_exp = [] + CLs_exp = [] for nsigma in [-2, -1, 0, 1, 2]: sqrtqmu_v_sigma = sqrtqmuA_v - nsigma - oneOverCLs_exp.append( + CLs_exp.append( pvals_from_teststat(sqrtqmu_v_sigma, sqrtqmuA_v)[-1]) - oneOverCLs_exp = tensorlib.astensor(oneOverCLs_exp) - return qmu_v, qmuA_v, CLsb, CLb, oneOverCLs, oneOverCLs_exp + CLs_exp = tensorlib.astensor(CLs_exp) + return qmu_v, qmuA_v, CLsb, CLb, CLs, CLs_exp
diff --git a/tests/test_validation.py b/tests/test_validation.py --- a/tests/test_validation.py +++ b/tests/test_validation.py @@ -661,8 +661,6 @@ def validate_runOnePoint(pdf, data, mu_test, expected_result, tolerance=1e-5): CLs_obs, CLs_exp = pyhf.runOnePoint( mu_test, data, pdf, init_pars, par_bounds)[-2:] - CLs_obs = 1. / CLs_obs - CLs_exp = [1. / x for x in CLs_exp] assert (CLs_obs - expected_result['obs']) / \ expected_result['obs'] < tolerance for result, expected_result in zip(CLs_exp, expected_result['exp']):
figure out why we do `CLb / CLsb` # Description we have this snippet: ```python from scipy.stats import norm def pvals_from_teststat(sqrtqmu_v, sqrtqmuA_v): CLsb = 1 - norm.cdf(sqrtqmu_v) CLb = norm.cdf(sqrtqmuA_v - sqrtqmu_v) CLs = CLb / CLsb return CLsb, CLb, CLs ``` as @matthewfeickert correctly observed this seems off at first sight. But I seem to remember there was a specific reason I did it this way (perhaps while keeping around wrong variable names) i think it has something to do with this line in ROOT ```c++ virtual Double_t CLb() const { return !fBackgroundIsAlt ? NullPValue() : AlternatePValue(); } ``` https://root.cern.ch/doc/v606/HypoTestResult_8h_source.html#l00138
I suspect the variable names are backwards --- I remember the `cdf` functions confused me based on which direction the value is reporting. I think `cdf(x)` is from -infinity to x. https://cds.cern.ch/record/1099994, LHC Statistics for Pedestrians <img width="698" alt="screenshot 2018-04-20 07 17 25" src="https://user-images.githubusercontent.com/761483/39050435-f0aef9a0-446a-11e8-88dc-5250f5e03220.png"> I think the issue is that in ROOT, it's setup genericall as a Hypothesis test between a Null Hypothesis and an Alternate Hypothesis, one will be "background-only" while the other one will not, and this assignment is not fixed. It's a choice set by the HypoTestInverter, and relates to whether we do an exclusion or a discovery fit https://root.cern.ch/doc/v608/HypoTestInverter_8cxx_source.html#l00500 e.g. see this https://github.com/dguest/HistFitter/blob/master/src/StatTools.cxx#L843 From PR #141: > Arguably we should just return CLs instead of 1/CLs, but I didn't want to change all the other pieces that might rely on the output of runOnePoint @lukasheinrich Are there any objections to in another PR going through and checking all of this and moving to the CLs return structure? no, not at all. I think that's what we should do Unless someone beats me to it I'll work on this once I catch up on sleep.
2018-05-12T13:48:31
-1.0
scikit-hep/pyhf
241
scikit-hep__pyhf-241
[ "240" ]
4eb6490aaaed5a8b5a3bd5824bb4c059cbca53f8
diff --git a/pyhf/exceptions/__init__.py b/pyhf/exceptions/__init__.py --- a/pyhf/exceptions/__init__.py +++ b/pyhf/exceptions/__init__.py @@ -1,8 +1,8 @@ import sys class InvalidNameReuse(Exception): - pass - + pass + class InvalidSpecification(Exception): """ InvalidSpecification is raised when a specification does not validate against the given schema. @@ -22,6 +22,13 @@ def __init__(self, ValidationError): # Call the base class constructor with the parameters it needs super(InvalidSpecification, self).__init__(message) +class InvalidModel(Exception): + """ + InvalidModel is raised when a given model does not have the right configuration, even though it validates correctly against the schema. + + This can occur, for example, when the provided parameter of interest to fit against does not get declared in the specification provided. + """ + pass class InvalidModifier(Exception): """ diff --git a/pyhf/pdf.py b/pyhf/pdf.py --- a/pyhf/pdf.py +++ b/pyhf/pdf.py @@ -30,8 +30,11 @@ def from_spec(cls,spec,poiname = 'mu', qualify_names = False): modifier = instance.add_or_get_modifier(channel, sample, modifier_def) modifier.add_sample(channel, sample, modifier_def) modifiers.append(modifier_def['name']) + instance.channels = list(set(channels)) + instance.samples = list(set(samples)) + instance.modifiers = list(set(modifiers)) instance.set_poi(poiname) - return (instance, (list(set(channels)), list(set(samples)), list(set(modifiers)))) + return instance def __init__(self): # set up all other bookkeeping variables @@ -61,6 +64,8 @@ def modifier(self, name): return self.par_map[name]['modifier'] def set_poi(self,name): + if name not in self.modifiers: + raise exceptions.InvalidModel("The paramter of interest '{0:s}' cannot be fit as it is not declared in the model specification.".format(name)) s = self.par_slice(name) assert s.stop-s.start == 1 self.poi_index = s.start @@ -119,7 +124,7 @@ def __init__(self, spec, **config_kwargs): log.info("Validating spec against schema: {0:s}".format(self.schema)) utils.validate(self.spec, self.schema) # build up our representation of the specification - self.config, (self.channels, self.samples, self.modifiers) = _ModelConfig.from_spec(self.spec,**config_kwargs) + self.config = _ModelConfig.from_spec(self.spec,**config_kwargs) def expected_sample(self, channel, sample, pars): """
diff --git a/tests/test_schema.py b/tests/test_schema.py --- a/tests/test_schema.py +++ b/tests/test_schema.py @@ -1,7 +1,37 @@ import pyhf import pytest -def test_missing_sample_name(): +def test_no_samples(): + spec = { + 'channels': [ + { + 'name': 'channel', + 'samples': [] + }, + ] + } + with pytest.raises(pyhf.exceptions.InvalidSpecification): + pyhf.Model(spec) + +def test_sample_missing_data(): + spec = { + 'channels': [ + { + 'name': 'channel', + 'samples': [ + { + 'name': 'sample', + 'data': [], + 'modifiers': [] + } + ] + }, + ] + } + with pytest.raises(pyhf.exceptions.InvalidSpecification): + pyhf.Model(spec) + +def test_sample_missing_name(): spec = { 'channels': [ { @@ -18,6 +48,47 @@ def test_missing_sample_name(): with pytest.raises(pyhf.exceptions.InvalidSpecification): pyhf.Model(spec) +def test_sample_missing_all_modifiers(): + spec = { + 'channels': [ + { + 'name': 'channel', + 'samples': [ + { + 'name': 'sample', + 'data': [10.], + 'modifiers': [] + } + ] + }, + ] + } + with pytest.raises(pyhf.exceptions.InvalidModel): + pyhf.Model(spec) + +def test_one_sample_missing_modifiers(): + spec = { + 'channels': [ + { + 'name': 'channel', + 'samples': [ + { + 'name': 'sample', + 'data': [10.], + 'modifiers': [] + }, + { + 'name': 'another_sample', + 'data': [5.], + 'modifiers': [{'name': 'mypoi', 'type': 'normfactor', 'data': None}] + } + ] + }, + ] + } + pyhf.Model(spec, poiname='mypoi') + + def test_add_unknown_modifier(): spec = { 'channels': [ @@ -37,3 +108,63 @@ def test_add_unknown_modifier(): } with pytest.raises(pyhf.exceptions.InvalidSpecification): pyhf.Model(spec) + +def test_empty_staterror(): + spec = { + 'channels': [ + { + 'name': 'channel', + 'samples': [ + { + 'name': 'sample', + 'data': [10.], + 'modifiers': [ + {'name': 'staterror_channel', 'type': 'staterror', 'data': []} + ] + } + ] + }, + ] + } + with pytest.raises(pyhf.exceptions.InvalidSpecification): + pyhf.Model(spec) + +def test_empty_shapesys(): + spec = { + 'channels': [ + { + 'name': 'channel', + 'samples': [ + { + 'name': 'sample', + 'data': [10.], + 'modifiers': [ + {'name': 'sample_norm', 'type': 'shapesys','data': []} + ] + } + ] + }, + ] + } + with pytest.raises(pyhf.exceptions.InvalidSpecification): + pyhf.Model(spec) + +def test_empty_histosys(): + spec = { + 'channels': [ + { + 'name': 'channel', + 'samples': [ + { + 'name': 'sample', + 'data': [10.], + 'modifiers': [ + {'name': 'modifier', 'type': 'histosys', 'data': {'lo_data': [], 'hi_data': []}} + ] + } + ] + }, + ] + } + with pytest.raises(pyhf.exceptions.InvalidSpecification): + pyhf.Model(spec)
Safeguard invalid modifiers definition for stat errors # Description right now the spec reading allows the `data` field in staterrors to be empty which is invalid, since we need to be able to compute the stat. uncertainty for it. This can probably be caught in the JSON schema validation. The only modifiers who do not need additional data are the factor modifiers (the unconstrained ones) i.e. `normfactor` and `shapefactor` this showed up in #231 when processing mbj ```json {"data":[0.20280006527900696],"modifiers":[{"data":[],"name":"staterror_SR0L_Lnj_Imeff_cuts","type":"staterror"},{"data":{"hi":2,"lo":0.01},"name":"QCDHundred","type":"normsys"}],"name":"QCD"} {"data":[0.4424484670162201],"modifiers":[{"data":[],"name":"staterror_SR0L_Inj_Imeff_cuts","type":"staterror"},{"data":{"hi":2,"lo":0.01},"name":"QCDHundred","type":"normsys"}],"name":"QCD"} {"data":[0.0742708146572113],"modifiers":[{"data":[],"name":"staterror_SR0L_Hnj_Imeff_cuts","type":"staterror"},{"data":{"hi":2,"lo":0.01},"name":"QCDHundred","type":"normsys"}],"name":"QCD"} {"data":[0.047470349818468094],"modifiers":[{"data":[],"name":"staterror_SR0L_Hnj_Lmeff_cuts","type":"staterror"},{"data":{"hi":2,"lo":0.01},"name":"QCDHundred","type":"normsys"}],"name":"QCD"} {"data":[0.3601486086845398],"modifiers":[{"data":[],"name":"staterror_SR0L_Lnj_Hmeff_cuts","type":"staterror"},{"data":{"hi":2,"lo":0.01},"name":"QCDHundred","type":"normsys"}],"name":"QCD"} {"data":[0.03753824904561043],"modifiers":[{"data":[],"name":"staterror_SR0L_Lnj_Lmeff_cuts","type":"staterror"},{"data":{"hi":2,"lo":0.01},"name":"QCDHundred","type":"normsys"}],"name":"QCD"} {"data":[0.052878595888614655],"modifiers":[{"data":[],"name":"staterror_SR0L_Hnj_Hmeff_cuts","type":"staterror"},{"data":{"hi":2,"lo":0.01},"name":"QCDHundred","type":"normsys"}],"name":"QCD"} {"data":[0.028282178565859795],"modifiers":[{"data":[],"name":"staterror_SR0L_IStR_cuts","type":"staterror"},{"data":{"hi":2,"lo":0.01},"name":"QCDHundred","type":"normsys"}],"name":"QCD"} ```
2018-09-07T15:49:22
-1.0
scikit-hep/pyhf
284
scikit-hep__pyhf-284
[ "274" ]
e4031e01f35412dbc6c4a3bf97dacf99a9bb281a
diff --git a/binder/trigger_binder.py b/binder/trigger_binder.py new file mode 100644 --- /dev/null +++ b/binder/trigger_binder.py @@ -0,0 +1,35 @@ +#!/usr/bin/env python + +import argparse +import time +from selenium import webdriver +from selenium.webdriver.chrome.options import Options + + +def main(args): + options = Options() + options.set_headless() + options.add_argument('--no-sandbox') + if args.chromedriver_path is not None: + driver = webdriver.Chrome(args.chromedriver_path, chrome_options=options) + else: + driver = webdriver.Chrome(chrome_options=options) + if args.is_verbose: + print('Chrome Headless Browser Invoked') + driver.get(args.url) + time.sleep(10) + driver.close() + + +if __name__ == '__main__': + parser = argparse.ArgumentParser() + parser.add_argument('-v', '--verbose', dest='is_verbose', + action='store_true', + help='Print out more information') + parser.add_argument('--chromedriver-path', dest='chromedriver_path', + type=str, default=None, help='System path to ChromeDriver') + parser.add_argument('--url', dest='url', + type=str, default=None, help='URL for Selinium to open') + args = parser.parse_args() + + main(args) diff --git a/setup.py b/setup.py --- a/setup.py +++ b/setup.py @@ -37,6 +37,7 @@ 'coverage>=4.0', # coveralls 'matplotlib', 'jupyter', + 'nbdime', 'uproot>=3.0.0', 'papermill', 'graphviz',
diff --git a/tests/test_notebooks.py b/tests/test_notebooks.py --- a/tests/test_notebooks.py +++ b/tests/test_notebooks.py @@ -1,4 +1,5 @@ import sys +import os import papermill as pm @@ -12,6 +13,13 @@ def test_notebooks(tmpdir): pm.execute_notebook( 'docs/examples/notebooks/hello-world.ipynb', **common_kwargs) + if sys.version_info.major > 2: + # The Binder example uses specific relative paths + cwd = os.getcwd() + os.chdir(os.path.join(cwd, 'docs/examples/notebooks/binderexample')) + pm.execute_notebook('StatisticalAnalysis.ipynb', **common_kwargs) + os.chdir(cwd) + pm.execute_notebook( 'docs/examples/notebooks/learn/InterpolationCodes.ipynb', **common_kwargs)
Binder master build and Example Notebook breaks # Description the spec must be build as `Model({'channels': parsed['channels']})` we should fix this and add a test so we are protected against future regressions
2018-09-21T12:41:50
-1.0
scikit-hep/pyhf
341
scikit-hep__pyhf-341
[ "220" ]
5f6e2817686c3c1a5fd5befe811c4ce1e6d7d672
diff --git a/pyhf/commandline.py b/pyhf/commandline.py --- a/pyhf/commandline.py +++ b/pyhf/commandline.py @@ -8,7 +8,7 @@ from . import readxml from . import writexml -from .utils import runOnePoint +from .utils import hypotest from .pdf import Model from .version import __version__ @@ -111,9 +111,9 @@ def cls(workspace, output_file, measurement, qualify_names, patch): qualify_names=qualify_names, ) observed = sum((d['data'][c] for c in p.config.channels), []) + p.config.auxdata - result = runOnePoint(1.0, observed, p) + result = hypotest(1.0, observed, p, return_expected_set=True) result = { - 'CLs_obs': result[-2].tolist()[0], + 'CLs_obs': result[0].tolist()[0], 'CLs_exp': result[-1].ravel().tolist(), } if output_file is None: diff --git a/pyhf/utils.py b/pyhf/utils.py --- a/pyhf/utils.py +++ b/pyhf/utils.py @@ -67,10 +67,13 @@ def qmu(mu, data, pdf, init_pars, par_bounds): Args: mu (Number or Tensor): The signal strength parameter data (Tensor): The data to be considered - pdf (Tensor): The model used in the likelihood ratio calculation + pdf (|pyhf.pdf.Model|_): The HistFactory statistical model used in the likelihood ratio calculation init_pars (Tensor): The initial parameters par_bounds(Tensor): The bounds on the paramter values + .. |pyhf.pdf.Model| replace:: ``pyhf.pdf.Model`` + .. _pyhf.pdf.Model: https://diana-hep.org/pyhf/_generated/pyhf.pdf.Model.html + Returns: Float: The calculated test statistic, :math:`q_{\mu}` """ @@ -96,8 +99,7 @@ def generate_asimov_data(asimov_mu, data, pdf, init_pars, par_bounds): def pvals_from_teststat(sqrtqmu_v, sqrtqmuA_v): r""" - The :math:`p`-values for signal strength :math:`\mu` and Asimov strength :math:`\mu'` - as defined in Equations (59) and (57) of `arXiv:1007.1727`_ + The :math:`p`-values for signal strength :math:`\mu` and Asimov strength :math:`\mu'` as defined in Equations (59) and (57) of `arXiv:1007.1727`_ .. _`arXiv:1007.1727`: https://arxiv.org/abs/1007.1727 @@ -127,27 +129,74 @@ def pvals_from_teststat(sqrtqmu_v, sqrtqmuA_v): return CLsb, CLb, CLs -def runOnePoint(muTest, data, pdf, init_pars=None, par_bounds=None): +def hypotest(poi_test, data, pdf, init_pars=None, par_bounds=None, **kwargs): r""" - Computes test statistics (and expected statistics) for a single value - of the parameter of interest + Computes :math:`p`-values and test statistics for a single value of the parameter of interest Args: - muTest (Number or Tensor): The value of the parameter of interest (POI) + poi_test (Number or Tensor): The value of the parameter of interest (POI) data (Number or Tensor): The root of the calculated test statistic given the Asimov data, :math:`\sqrt{q_{\mu,A}}` - init_pars (Array or Tensor): the initial parameter values to be used for minimization - par_bounds (Array or Tensor): the parameter value bounds to be used for minimization + pdf (|pyhf.pdf.Model|_): The HistFactory statistical model + init_pars (Array or Tensor): The initial parameter values to be used for minimization + par_bounds (Array or Tensor): The parameter value bounds to be used for minimization + + .. |pyhf.pdf.Model| replace:: ``pyhf.pdf.Model`` + .. _pyhf.pdf.Model: https://diana-hep.org/pyhf/_generated/pyhf.pdf.Model.html + + Keyword Args: + return_tail_probs (bool): Bool for returning :math:`\textrm{CL}_{s+b}` and :math:`\textrm{CL}_{b}` + return_expected (bool): Bool for returning :math:`\textrm{CL}_{\textrm{exp}}` + return_expected_set (bool): Bool for returning the :math:`(-2,-1,0,1,2)\sigma` :math:`\textrm{CL}_{\textrm{exp}}` --- the "Brazil band" + return_test_statistics (bool): Bool for returning :math:`q_{\mu}` and :math:`q_{\mu,A}` Returns: - Tuple of Floats: a tuple containing (qmu, qmu_A, CLsb, CLb, CLs, CLs_exp) - where qmu and qmu_A are the test statistics for the - observed and Asimov datasets respectively. - CLsb, CLb are the signal + background and background-only p-values - CLs is the modified p-value - CLs_exp is a 5-tuple of expected CLs values at percentiles - of the background-only test-statistics corresponding to - percentiles of the normal distribution for - (-2,-1,0,1,2) :math:`\sigma` + Tuple of Floats and lists of Floats: + + - :math:`\textrm{CL}_{s}`: The :math:`p`-value compared to the given threshold :math:`\alpha`, typically taken to be :math:`0.05`, defined in `arXiv:1007.1727`_ as + + .. _`arXiv:1007.1727`: https://arxiv.org/abs/1007.1727 + + .. math:: + + \textrm{CL}_{s} = \frac{\textrm{CL}_{s+b}}{\textrm{CL}_{b}} = \frac{p_{s+b}}{1-p_{b}} + + to protect against excluding signal models in which there is little sensitivity. In the case that :math:`\textrm{CL}_{s} \leq \alpha` the given signal model is excluded. + + - :math:`\left[\textrm{CL}_{s+b}, \textrm{CL}_{b}\right]`: The signal + background :math:`p`-value and 1 minus the background only :math:`p`-value as defined in Equations (75) and (76) of `arXiv:1007.1727`_ + + .. math:: + + \textrm{CL}_{s+b} = p_{s+b} = \int\limits_{q_{\textrm{obs}}}^{\infty} f\left(q\,\middle|s+b\right)\,dq = 1 - \Phi\left(\frac{q_{\textrm{obs}} + 1/\sigma_{s+b}^{2}}{2/\sigma_{s+b}}\right) + + .. math:: + + \textrm{CL}_{b} = 1- p_{b} = 1 - \int\limits_{-\infty}^{q_{\textrm{obs}}} f\left(q\,\middle|b\right)\,dq = 1 - \Phi\left(\frac{q_{\textrm{obs}} - 1/\sigma_{b}^{2}}{2/\sigma_{b}}\right) + + with Equations (73) and (74) for the mean + + .. math:: + + E\left[q\right] = \frac{1 - 2\mu}{\sigma^{2}} + + and variance + + .. math:: + + V\left[q\right] = \frac{4}{\sigma^{2}} + + of the test statistic :math:`q` under the background only and and signal + background hypotheses. Only returned when ``return_tail_probs`` is ``True``. + + - :math:`\textrm{CL}_{s,\textrm{exp}}`: The expected :math:`\textrm{CL}_{s}` value corresponding to the test statistic under the background only hypothesis :math:`\left(\mu=0\right)`. Only returned when ``return_expected`` is ``True``. + + - :math:`\textrm{CL}_{s,\textrm{exp}}` band: The set of expected :math:`\textrm{CL}_{s}` values corresponding to the median significance of variations of the signal strength from the background only hypothesis :math:`\left(\mu=0\right)` at :math:`(-2,-1,0,1,2)\sigma`. That is, the :math:`p`-values that satisfy Equation (89) of `arXiv:1007.1727`_ + + .. math:: + + \textrm{band}_{N\sigma} = \mu' + \sigma\,\Phi^{-1}\left(1-\alpha\right) \pm N\sigma + + for :math:`\mu'=0` and :math:`N \in \left\{-2, -1, 0, 1, 2\right\}`. These values define the boundaries of an uncertainty band sometimes referred to as the "Brazil band". Only returned when ``return_expected_set`` is ``True``. + + - :math:`\left[q_{\mu}, q_{\mu,A}\right]`: The test statistics for the observed and Asimov datasets respectively. Only returned when ``return_test_statistics`` is ``True``. """ init_pars = init_pars or pdf.config.suggested_init() @@ -157,19 +206,32 @@ def runOnePoint(muTest, data, pdf, init_pars=None, par_bounds=None): asimov_mu = 0.0 asimov_data = generate_asimov_data(asimov_mu, data, pdf, init_pars, par_bounds) - qmu_v = tensorlib.clip(qmu(muTest, data, pdf, init_pars, par_bounds), 0, max=None) + qmu_v = tensorlib.clip(qmu(poi_test, data, pdf, init_pars, par_bounds), 0, max=None) sqrtqmu_v = tensorlib.sqrt(qmu_v) qmuA_v = tensorlib.clip( - qmu(muTest, asimov_data, pdf, init_pars, par_bounds), 0, max=None + qmu(poi_test, asimov_data, pdf, init_pars, par_bounds), 0, max=None ) sqrtqmuA_v = tensorlib.sqrt(qmuA_v) CLsb, CLb, CLs = pvals_from_teststat(sqrtqmu_v, sqrtqmuA_v) - CLs_exp = [] - for nsigma in [-2, -1, 0, 1, 2]: - sqrtqmu_v_sigma = sqrtqmuA_v - nsigma - CLs_exp.append(pvals_from_teststat(sqrtqmu_v_sigma, sqrtqmuA_v)[-1]) - CLs_exp = tensorlib.astensor(CLs_exp) - return qmu_v, qmuA_v, CLsb, CLb, CLs, CLs_exp + _returns = [CLs] + if kwargs.get('return_tail_probs'): + _returns.append([CLsb, CLb]) + if kwargs.get('return_expected_set'): + CLs_exp = [] + for n_sigma in [-2, -1, 0, 1, 2]: + sqrtqmu_v_sigma = sqrtqmuA_v - n_sigma + CLs_exp.append(pvals_from_teststat(sqrtqmu_v_sigma, sqrtqmuA_v)[-1]) + CLs_exp = tensorlib.astensor(CLs_exp) + if kwargs.get('return_expected'): + _returns.append(CLs_exp[2]) + _returns.append(CLs_exp) + elif kwargs.get('return_expected'): + _returns.append(pvals_from_teststat(sqrtqmuA_v, sqrtqmuA_v)[-1]) + if kwargs.get('return_test_statistics'): + _returns.append([qmu_v, qmuA_v]) + + # Enforce a consistent return type of the observed CLs + return tuple(_returns) if len(_returns) > 1 else _returns[0]
diff --git a/tests/benchmarks/test_benchmark.py b/tests/benchmarks/test_benchmark.py --- a/tests/benchmarks/test_benchmark.py +++ b/tests/benchmarks/test_benchmark.py @@ -52,9 +52,17 @@ def generate_source_poisson(n_bins): return source -def runOnePoint(pdf, data): - return pyhf.utils.runOnePoint( - 1.0, data, pdf, pdf.config.suggested_init(), pdf.config.suggested_bounds() +def hypotest(pdf, data): + return pyhf.utils.hypotest( + 1.0, + data, + pdf, + pdf.config.suggested_init(), + pdf.config.suggested_bounds(), + return_tail_probs=True, + return_expected=True, + return_expected_set=True, + return_test_statistics=True, ) @@ -65,9 +73,9 @@ def runOnePoint(pdf, data): @pytest.mark.parametrize('n_bins', bins, ids=bin_ids) @pytest.mark.skip_mxnet -def test_runOnePoint(benchmark, backend, n_bins): +def test_hypotest(benchmark, backend, n_bins): """ - Benchmark the performance of pyhf.runOnePoint() + Benchmark the performance of pyhf.utils.hypotest() for various numbers of bins and different backends Args: @@ -83,4 +91,4 @@ def test_runOnePoint(benchmark, backend, n_bins): source['bindata']['sig'], source['bindata']['bkg'], source['bindata']['bkgerr'] ) data = source['bindata']['data'] + pdf.config.auxdata - assert benchmark(runOnePoint, pdf, data) + assert benchmark(hypotest, pdf, data) diff --git a/tests/test_backend_consistency.py b/tests/test_backend_consistency.py --- a/tests/test_backend_consistency.py +++ b/tests/test_backend_consistency.py @@ -59,7 +59,7 @@ def generate_source_poisson(n_bins): @pytest.mark.parametrize('n_bins', bins, ids=bin_ids) @pytest.mark.parametrize('invert_order', [False, True], ids=['normal', 'inverted']) -def test_runOnePoint_q_mu( +def test_hypotest_q_mu( n_bins, invert_order, tolerance={'numpy': 1e-02, 'tensors': 5e-03} ): """ @@ -118,9 +118,14 @@ def test_runOnePoint_q_mu( backend.session = tf.Session() pyhf.set_backend(backend) - q_mu = pyhf.utils.runOnePoint( - 1.0, data, pdf, pdf.config.suggested_init(), pdf.config.suggested_bounds() - )[0] + q_mu = pyhf.utils.hypotest( + 1.0, + data, + pdf, + pdf.config.suggested_init(), + pdf.config.suggested_bounds(), + return_test_statistics=True, + )[-1][0] test_statistic.append(pyhf.tensorlib.tolist(q_mu)) # compare to NumPy/SciPy diff --git a/tests/test_utils.py b/tests/test_utils.py --- a/tests/test_utils.py +++ b/tests/test_utils.py @@ -1,6 +1,9 @@ -import pyhf -import pytest import os +import pytest + +import pyhf +import pyhf.simplemodels +import pyhf.utils def test_get_default_schema(): @@ -20,3 +23,114 @@ def test_load_custom_schema(tmpdir): temp = tmpdir.join("custom_schema.json") temp.write('{"foo": "bar"}') assert pyhf.utils.load_schema(temp.strpath) + + [email protected](scope='module') +def hypotest_args(): + pdf = pyhf.simplemodels.hepdata_like( + signal_data=[12.0, 11.0], bkg_data=[50.0, 52.0], bkg_uncerts=[3.0, 7.0] + ) + mu_test = 1.0 + data = [51, 48] + pdf.config.auxdata + return mu_test, data, pdf + + +def check_uniform_type(in_list): + return all( + [isinstance(item, type(pyhf.tensorlib.astensor(item))) for item in in_list] + ) + + +def test_hypotest_default(tmpdir, hypotest_args): + """ + Check that the default return structure of pyhf.utils.hypotest is as expected + """ + tb = pyhf.tensorlib + + kwargs = {} + result = pyhf.utils.hypotest(*hypotest_args, **kwargs) + # CLs_obs + assert len(list(result)) == 1 + assert isinstance(result, type(tb.astensor(result))) + + +def test_hypotest_return_tail_probs(tmpdir, hypotest_args): + """ + Check that the return structure of pyhf.utils.hypotest with the + return_tail_probs keyword arg is as expected + """ + tb = pyhf.tensorlib + + kwargs = {'return_tail_probs': True} + result = pyhf.utils.hypotest(*hypotest_args, **kwargs) + # CLs_obs, [CL_sb, CL_b] + assert len(list(result)) == 2 + assert isinstance(result[0], type(tb.astensor(result[0]))) + assert len(result[1]) == 2 + assert check_uniform_type(result[1]) + + +def test_hypotest_return_expected(tmpdir, hypotest_args): + """ + Check that the return structure of pyhf.utils.hypotest with the + additon of the return_expected keyword arg is as expected + """ + tb = pyhf.tensorlib + + kwargs = {'return_tail_probs': True, 'return_expected': True} + result = pyhf.utils.hypotest(*hypotest_args, **kwargs) + # CLs_obs, [CLsb, CLb], CLs_exp + assert len(list(result)) == 3 + assert isinstance(result[0], type(tb.astensor(result[0]))) + assert len(result[1]) == 2 + assert check_uniform_type(result[1]) + assert isinstance(result[2], type(tb.astensor(result[2]))) + + +def test_hypotest_return_expected_set(tmpdir, hypotest_args): + """ + Check that the return structure of pyhf.utils.hypotest with the + additon of the return_expected_set keyword arg is as expected + """ + tb = pyhf.tensorlib + + kwargs = { + 'return_tail_probs': True, + 'return_expected': True, + 'return_expected_set': True, + } + result = pyhf.utils.hypotest(*hypotest_args, **kwargs) + # CLs_obs, [CLsb, CLb], CLs_exp, CLs_exp @[-2, -1, 0, +1, +2]sigma + assert len(list(result)) == 4 + assert isinstance(result[0], type(tb.astensor(result[0]))) + assert len(result[1]) == 2 + assert check_uniform_type(result[1]) + assert isinstance(result[2], type(tb.astensor(result[2]))) + assert len(result[3]) == 5 + assert check_uniform_type(result[3]) + + +def test_hypotest_return_test_statistics(tmpdir, hypotest_args): + """ + Check that the return structure of pyhf.utils.hypotest with the + additon of the return_test_statistics keyword arg is as expected + """ + tb = pyhf.tensorlib + + kwargs = { + 'return_tail_probs': True, + 'return_expected': True, + 'return_expected_set': True, + 'return_test_statistics': True, + } + result = pyhf.utils.hypotest(*hypotest_args, **kwargs) + # CLs_obs, [CLsb, CLb], CLs_exp, CLs_exp @[-2, -1, 0, +1, +2]sigma, [q_mu, q_mu_Asimov] + assert len(list(result)) == 5 + assert isinstance(result[0], type(tb.astensor(result[0]))) + assert len(result[1]) == 2 + assert check_uniform_type(result[1]) + assert isinstance(result[2], type(tb.astensor(result[2]))) + assert len(result[3]) == 5 + assert check_uniform_type(result[3]) + assert len(result[4]) == 2 + assert check_uniform_type(result[4]) diff --git a/tests/test_validation.py b/tests/test_validation.py --- a/tests/test_validation.py +++ b/tests/test_validation.py @@ -618,16 +618,16 @@ def setup_2bin_2channel_coupledshapefactor( } -def validate_runOnePoint(pdf, data, mu_test, expected_result, tolerance=1e-6): +def validate_hypotest(pdf, data, mu_test, expected_result, tolerance=1e-6): init_pars = pdf.config.suggested_init() par_bounds = pdf.config.suggested_bounds() - CLs_obs, CLs_exp = pyhf.utils.runOnePoint( - mu_test, data, pdf, init_pars, par_bounds - )[-2:] + CLs_obs, CLs_exp_set = pyhf.utils.hypotest( + mu_test, data, pdf, init_pars, par_bounds, return_expected_set=True + ) assert abs(CLs_obs - expected_result['obs']) / expected_result['obs'] < tolerance - for result, expected_result in zip(CLs_exp, expected_result['exp']): + for result, expected_result in zip(CLs_exp_set, expected_result['exp']): assert abs(result - expected_result) / expected_result < tolerance @@ -672,6 +672,6 @@ def test_validation(setup_and_tolerance): len(pdf.config.suggested_bounds()) == setup['expected']['config']['par_bounds'] ) - validate_runOnePoint( + validate_hypotest( pdf, data, setup['mu'], setup['expected']['result'], tolerance=tolerance )
clean up name/signature of `runOnePoint` # Description The signauture of `runOnePoint` is too complicated for newcomers. mostly people are only interested in CLs obs/exp. ### Describe the solution you'd like We could use the appraoch used in scikit of a signature that is *iteratively discoverable* sucht that ``` clsobs = pyhf.utils.cls(...) clsobs, clsexp = pyhf.utils.cls(..., return_exp = True) #returns only two numbers clsobs, clsexpset = pyhf.utils.cls(..., return_expset = True) #returns full 'brazil-band' clsobs, clsexpset, qvals = pyhf.utils.cls(..., return_expset = True, return_teststatistics = True) #returns full 'brazil-band' + test statistic values ```
I very much like this idea.
2018-10-23T13:54:02
-1.0
scikit-hep/pyhf
358
scikit-hep__pyhf-358
[ "357" ]
9605def1dd6a20d865d6413dfe0ea3a6b77ef9eb
diff --git a/pyhf/commandline.py b/pyhf/commandline.py --- a/pyhf/commandline.py +++ b/pyhf/commandline.py @@ -72,8 +72,7 @@ def json2xml(workspace, xmlfile, specroot, dataroot): ) @click.option('--measurement', default=None) @click.option('-p', '--patch', multiple=True) [email protected]('--qualify-names/--no-qualify-names', default=False) -def cls(workspace, output_file, measurement, qualify_names, patch): +def cls(workspace, output_file, measurement, patch): with click.open_file(workspace, 'r') as specstream: d = json.load(specstream) measurements = d['toplvl']['measurements'] @@ -105,11 +104,7 @@ def cls(workspace, output_file, measurement, qualify_names, patch): with click.open_file(p, 'r') as read_file: p = jsonpatch.JsonPatch(json.loads(read_file.read())) spec = p.apply(spec) - p = Model( - spec, - poiname=measurements[measurement_index]['config']['poi'], - qualify_names=qualify_names, - ) + p = Model(spec, poiname=measurements[measurement_index]['config']['poi']) observed = sum((d['data'][c] for c in p.config.channels), []) + p.config.auxdata result = hypotest(1.0, observed, p, return_expected_set=True) result = { diff --git a/pyhf/paramsets.py b/pyhf/paramsets.py --- a/pyhf/paramsets.py +++ b/pyhf/paramsets.py @@ -62,7 +62,7 @@ def reduce_paramset_requirements(paramset_requirements): for k in param_keys: if len(combined_param[k]) != 1 and k != 'op_code': raise exceptions.InvalidNameReuse( - "Multiple values for '{}' ({}) were found for {}. Use unique modifier names or use qualify_names=True when constructing the pdf.".format( + "Multiple values for '{}' ({}) were found for {}. Use unique modifier names when constructing the pdf.".format( k, list(combined_param[k]), param_name ) ) diff --git a/pyhf/pdf.py b/pyhf/pdf.py --- a/pyhf/pdf.py +++ b/pyhf/pdf.py @@ -12,7 +12,7 @@ class _ModelConfig(object): - def __init__(self, spec, poiname='mu', qualify_names=False): + def __init__(self, spec, poiname='mu'): self.poi_index = None self.par_map = {} self.par_order = [] @@ -37,13 +37,6 @@ def __init__(self, spec, poiname='mu', qualify_names=False): self.samples.append(sample['name']) for modifier_def in sample['modifiers']: self.parameters.append(modifier_def['name']) - if qualify_names: - fullname = '{}/{}'.format( - modifier_def['type'], modifier_def['name'] - ) - if modifier_def['name'] == poiname: - poiname = fullname - modifier_def['name'] = fullname # get the paramset requirements for the given modifier. If # modifier does not exist, we'll have a KeyError @@ -62,8 +55,8 @@ def __init__(self, spec, poiname='mu', qualify_names=False): ( modifier_def['name'], # mod name modifier_def['type'], # mod type - modifier_def['name'], - ) # parset name + modifier_def['name'], # parset name + ) ) # check the shareability (e.g. for shapesys for example)
diff --git a/tests/test_pdf.py b/tests/test_pdf.py --- a/tests/test_pdf.py +++ b/tests/test_pdf.py @@ -372,6 +372,4 @@ def test_invalid_modifier_name_resuse(): ] } with pytest.raises(pyhf.exceptions.InvalidNameReuse): - pdf = pyhf.Model(spec, poiname='reused_name') - - pdf = pyhf.Model(spec, poiname='reused_name', qualify_names=True) + pyhf.Model(spec, poiname='reused_name')
consolidation: remove --qualify-names # Description the option added in #233 is obsolete know that we handle names shared across modifier types (#354 ) so it should be removed again
2018-11-05T14:06:43
-1.0
scikit-hep/pyhf
363
scikit-hep__pyhf-363
[ "359" ]
556c7d6e071388f86df9528379a7ea763889a119
diff --git a/pyhf/__init__.py b/pyhf/__init__.py --- a/pyhf/__init__.py +++ b/pyhf/__init__.py @@ -82,5 +82,6 @@ def set_backend(backend, custom_optimizer=None): from .pdf import Model +from . import simplemodels -__all__ = ['Model', 'utils', 'modifiers', '__version__'] +__all__ = ['Model', 'utils', 'modifiers', 'simplemodels', '__version__']
diff --git a/tests/test_pdf.py b/tests/test_pdf.py --- a/tests/test_pdf.py +++ b/tests/test_pdf.py @@ -1,6 +1,5 @@ import pyhf import pytest -import pyhf.simplemodels import pyhf.exceptions import numpy as np import json diff --git a/tests/test_utils.py b/tests/test_utils.py --- a/tests/test_utils.py +++ b/tests/test_utils.py @@ -2,8 +2,6 @@ import pytest import pyhf -import pyhf.simplemodels -import pyhf.utils def test_get_default_schema():
consolidation: add simplemodls to __all__ # Description It would be nice if the snippet in the README could be shorter: right now this is needed ``` import pyhf import pyhf.simplemodels pdf = pyhf.simplemodels.hepdata_like(signal_data=[12.0], bkg_data=[50.0], bkg_uncerts=[3.0]) CLs_obs = pyhf.utils.hypotest(1.0, [51] + pdf.config.auxdata, pdf) ``` whereas if we pre-import `simplemodels` it could be ``` import pyhf pdf = pyhf.simplemodels.hepdata_like(signal_data=[12.0], bkg_data=[50.0], bkg_uncerts=[3.0]) CLs_obs = pyhf.utils.hypotest(1.0, [51] + pdf.config.auxdata, pdf) ``` since `simplemodels.py` doesn't add much code, i don't think it would slow down things a lot
> since `simplemodels.py` doesn't add much code, i don't think it would slow down things a lot We have a test that measures how long it takes to import `pyhf`. So we can make the change in a PR and see if tests pass :)
2018-11-06T02:30:54
-1.0
scikit-hep/pyhf
369
scikit-hep__pyhf-369
[ "368" ]
0be2e8c35fdb8cb7186a46be15c5599aaca09f96
diff --git a/setup.py b/setup.py --- a/setup.py +++ b/setup.py @@ -31,7 +31,7 @@ 'minuit': ['iminuit'], 'develop': [ 'pyflakes', - 'pytest>=3.5.1', + 'pytest<4.0.0,>=3.5.1', 'pytest-cov>=2.5.1', 'pytest-benchmark[histogram]', 'pytest-console-scripts', @@ -41,7 +41,7 @@ 'jupyter', 'nbdime', 'uproot>=3.0.0', - 'papermill', + 'papermill>=0.16.0', 'graphviz', 'bumpversion', 'sphinx',
diff --git a/tests/test_notebooks.py b/tests/test_notebooks.py --- a/tests/test_notebooks.py +++ b/tests/test_notebooks.py @@ -6,7 +6,7 @@ def test_notebooks(tmpdir): outputnb = tmpdir.join('output.ipynb') common_kwargs = { - 'output': str(outputnb), + 'output_path': str(outputnb), 'kernel_name': 'python{}'.format(sys.version_info.major), }
papermill seems to break? pin version? # Description In the CI for @nikoladze's PR https://github.com/diana-hep/pyhf/pull/365 it seems like papermill is breaking for unrelated reasons. Did something change upstream? Maybe we need to pin the version? Maybe @matthewfeickert knows? https://travis-ci.org/diana-hep/pyhf/jobs/454931484
2018-11-15T06:56:28
-1.0
scikit-hep/pyhf
426
scikit-hep__pyhf-426
[ "170" ]
ce34be1525e0b79e3d8e2429ef34a024ec30300b
diff --git a/pyhf/commandline.py b/pyhf/commandline.py --- a/pyhf/commandline.py +++ b/pyhf/commandline.py @@ -14,6 +14,14 @@ logging.basicConfig() log = logging.getLogger(__name__) +# This is only needed for Python 2/3 compatibility +def ensure_dirs(path): + try: + os.makedirs(path, exist_ok=True) + except TypeError: + if not os.path.exists(path): + os.makedirs(path) + @click.group(context_settings=dict(help_option_names=['-h', '--help'])) @click.version_option(version=__version__) @@ -61,16 +69,28 @@ def xml2json(entrypoint_xml, basedir, output_file, track_progress): @pyhf.command() @click.argument('workspace', default='-') [email protected]('xmlfile', default='-') [email protected]('--specroot', default=click.Path(exists=True)) [email protected]('--dataroot', default=click.Path(exists=True)) -def json2xml(workspace, xmlfile, specroot, dataroot): [email protected]('--output-dir', type=click.Path(exists=True), default='.') [email protected]('--specroot', default='config') [email protected]('--dataroot', default='data') [email protected]('--resultprefix', default='FitConfig') +def json2xml(workspace, output_dir, specroot, dataroot, resultprefix): + ensure_dirs(output_dir) with click.open_file(workspace, 'r') as specstream: d = json.load(specstream) - with click.open_file(xmlfile, 'w') as outstream: + ensure_dirs(os.path.join(output_dir, specroot)) + ensure_dirs(os.path.join(output_dir, dataroot)) + with click.open_file( + os.path.join(output_dir, '{0:s}.xml'.format(resultprefix)), 'w' + ) as outstream: outstream.write( - writexml.writexml(d, specroot, dataroot, '').decode('utf-8') + writexml.writexml( + d, + os.path.join(output_dir, specroot), + os.path.join(output_dir, dataroot), + resultprefix, + ).decode('utf-8') ) + sys.exit(0) diff --git a/pyhf/readxml.py b/pyhf/readxml.py --- a/pyhf/readxml.py +++ b/pyhf/readxml.py @@ -235,14 +235,15 @@ def process_measurements(toplvl): overall_param_obj['value'] = param.attrib['Val'] # might be specifying multiple parameters in the same ParamSetting - for param_name in param.text.split(' '): - # lumi will always be the first parameter - if param_name == 'Lumi': - result['config']['parameters'][0].update(overall_param_obj) - else: - param_obj = {'name': param_name} - param_obj.update(overall_param_obj) - result['config']['parameters'].append(param_obj) + if param.text: + for param_name in param.text.split(' '): + # lumi will always be the first parameter + if param_name == 'Lumi': + result['config']['parameters'][0].update(overall_param_obj) + else: + param_obj = {'name': param_name} + param_obj.update(overall_param_obj) + result['config']['parameters'].append(param_obj) results.append(result) return results diff --git a/pyhf/writexml.py b/pyhf/writexml.py --- a/pyhf/writexml.py +++ b/pyhf/writexml.py @@ -1,45 +1,210 @@ +import logging + import os import xml.etree.cElementTree as ET +import numpy as np +import uproot +from uproot_methods.classes import TH1 + +_ROOT_DATA_FILE = None + +log = logging.getLogger(__name__) + + +def _make_hist_name(channel, sample, modifier='', prefix='hist', suffix=''): + return "{prefix}{middle}{suffix}".format( + prefix=prefix, + suffix=suffix, + middle='_'.join(filter(lambda x: x, [channel, sample, modifier])), + ) -def measurement(lumi, lumierr, poi, param_settings=None, name='Meas1'): - param_settings = param_settings or [] +def _export_root_histogram(histname, data): + h = TH1.from_numpy((np.asarray(data), np.arange(len(data) + 1))) + h._fName = histname + # NB: uproot crashes for some reason, figure out why later + # if histname in _ROOT_DATA_FILE: + # raise KeyError('Duplicate key {0} being written.'.format(histname)) + _ROOT_DATA_FILE[histname] = h + +# https://stackoverflow.com/a/4590052 +def indent(elem, level=0): + i = "\n" + level * " " + if elem: + if not elem.text or not elem.text.strip(): + elem.text = i + " " + if not elem.tail or not elem.tail.strip(): + elem.tail = i + for elem in elem: + indent(elem, level + 1) + if not elem.tail or not elem.tail.strip(): + elem.tail = i + else: + if level and (not elem.tail or not elem.tail.strip()): + elem.tail = i + + +def build_measurement(measurementspec): + config = measurementspec['config'] + name = measurementspec['name'] + poi = config['poi'] + + # we want to know which parameters are fixed (constant) + # and to additionally extract the luminosity information + fixed_params = [] + lumi = 1.0 + lumierr = 0.0 + for parameter in config['parameters']: + if parameter.get('fixed', False): + pname = parameter['name'] + if pname == 'lumi': + fixed_params.append('Lumi') + else: + fixed_params.append(pname) + # we found luminosity, so handle it + if parameter['name'] == 'lumi': + lumi = parameter['auxdata'][0] + lumierr = parameter['sigmas'][0] + + # define measurement meas = ET.Element("Measurement", Name=name, Lumi=str(lumi), LumiRelErr=str(lumierr)) poiel = ET.Element('POI') poiel.text = poi meas.append(poiel) - for s in param_settings: - se = ET.Element('ParamSetting', **s['attrs']) - se.text = ' '.join(s['params']) + + # add fixed parameters (constant) + if fixed_params: + se = ET.Element('ParamSetting', Const='True') + se.text = ' '.join(fixed_params) meas.append(se) return meas -def write_channel(channelspec, filename, data_rootdir): - # need to write channelfile here - with open(filename, 'w') as f: - channel = ET.Element('Channel', Name=channelspec['name']) - channel = ET.Element('Channel', Name=channelspec['name']) - f.write(ET.tostring(channel, encoding='utf-8').decode('utf-8')) - pass +def build_modifier(modifierspec, channelname, samplename, sampledata): + if modifierspec['name'] == 'lumi': + return None + mod_map = { + 'histosys': 'HistoSys', + 'staterror': 'StatError', + 'normsys': 'OverallSys', + 'shapesys': 'ShapeSys', + 'normfactor': 'NormFactor', + 'shapefactor': 'ShapeFactor', + } + attrs = {'Name': modifierspec['name']} + if modifierspec['type'] == 'histosys': + attrs['HistoNameLow'] = _make_hist_name( + channelname, samplename, modifierspec['name'], suffix='Low' + ) + attrs['HistoNameHigh'] = _make_hist_name( + channelname, samplename, modifierspec['name'], suffix='High' + ) + _export_root_histogram(attrs['HistoNameLow'], modifierspec['data']['lo_data']) + _export_root_histogram(attrs['HistoNameHigh'], modifierspec['data']['hi_data']) + elif modifierspec['type'] == 'normsys': + attrs['High'] = str(modifierspec['data']['hi']) + attrs['Low'] = str(modifierspec['data']['lo']) + elif modifierspec['type'] == 'normfactor': + attrs['Val'] = '1' + attrs['High'] = '10' + attrs['Low'] = '0' + elif modifierspec['type'] == 'staterror': + attrs['Activate'] = 'True' + attrs['HistoName'] = _make_hist_name( + channelname, samplename, modifierspec['name'] + ) + # need to make this a relative uncertainty stored in ROOT file + _export_root_histogram( + attrs['HistoName'], np.divide(modifierspec['data'], sampledata).tolist() + ) + elif modifierspec['type'] == 'shapesys': + attrs['ConstraintType'] = 'Poisson' + attrs['HistoName'] = _make_hist_name( + channelname, samplename, modifierspec['name'] + ) + # need to make this a relative uncertainty stored in ROOT file + _export_root_histogram( + attrs['HistoName'], + [np.divide(a, b) for a, b in zip(modifierspec['data'], sampledata)], + ) + else: + log.warning( + 'Skipping {0}({1}) for now'.format( + modifierspec['name'], modifierspec['type'] + ) + ) -def writexml(spec, specdir, data_rootdir, result_outputprefix): - combination = ET.Element("Combination", OutputFilePrefix=result_outputprefix) + modifier = ET.Element(mod_map[modifierspec['type']], **attrs) + return modifier - for c in spec['channels']: - channelfilename = os.path.join(specdir, 'channel_{}.xml'.format(c['name'])) - write_channel(c, channelfilename, data_rootdir) - inp = ET.Element("Input") - inp.text = channelfilename - combination.append(inp) - m = measurement( - 1, - 0.1, - 'SigXsecOverSM', - [{'attrs': {'Const': 'True'}, 'params': ['Lumi' 'alpha_syst1']}], +def build_sample(samplespec, channelname): + histname = _make_hist_name(channelname, samplespec['name']) + attrs = { + 'Name': samplespec['name'], + 'HistoName': histname, + 'InputFile': _ROOT_DATA_FILE._path, + 'NormalizeByTheory': 'False', + } + sample = ET.Element('Sample', **attrs) + for modspec in samplespec['modifiers']: + # if lumi modifier added for this sample, need to set NormalizeByTheory + if modspec['type'] == 'lumi': + sample.attrib.update({'NormalizeByTheory': 'True'}) + modifier = build_modifier( + modspec, channelname, samplespec['name'], samplespec['data'] + ) + if modifier is not None: + sample.append(modifier) + _export_root_histogram(histname, samplespec['data']) + return sample + + +def build_data(dataspec, channelname): + histname = _make_hist_name(channelname, 'data') + data = ET.Element('Data', HistoName=histname, InputFile=_ROOT_DATA_FILE._path) + _export_root_histogram(histname, dataspec[channelname]) + return data + + +def build_channel(channelspec, dataspec): + channel = ET.Element( + 'Channel', Name=channelspec['name'], InputFile=_ROOT_DATA_FILE._path ) - combination.append(m) + if dataspec: + data = build_data(dataspec, channelspec['name']) + channel.append(data) + for samplespec in channelspec['samples']: + channel.append(build_sample(samplespec, channelspec['name'])) + return channel + + +def writexml(spec, specdir, data_rootdir, resultprefix): + global _ROOT_DATA_FILE + + combination = ET.Element( + "Combination", OutputFilePrefix=os.path.join('.', specdir, resultprefix) + ) + + with uproot.recreate(os.path.join(data_rootdir, 'data.root')) as _ROOT_DATA_FILE: + for channelspec in spec['channels']: + channelfilename = os.path.join( + specdir, '{0:s}_{1:s}.xml'.format(resultprefix, channelspec['name']) + ) + with open(channelfilename, 'w') as channelfile: + channel = build_channel(channelspec, spec.get('data')) + indent(channel) + channelfile.write( + ET.tostring(channel, encoding='utf-8').decode('utf-8') + ) + + inp = ET.Element("Input") + inp.text = channelfilename + combination.append(inp) + + for measurement in spec['toplvl']['measurements']: + combination.append(build_measurement(measurement)) + indent(combination) return ET.tostring(combination, encoding='utf-8')
diff --git a/tests/test_export.py b/tests/test_export.py new file mode 100644 --- /dev/null +++ b/tests/test_export.py @@ -0,0 +1,256 @@ +import pyhf +import pyhf.writexml +import pytest +import json +import xml.etree.cElementTree as ET + + +def spec_staterror(): + spec = { + 'channels': [ + { + 'name': 'firstchannel', + 'samples': [ + { + 'name': 'mu', + 'data': [10.0, 10.0], + 'modifiers': [ + {'name': 'mu', 'type': 'normfactor', 'data': None} + ], + }, + { + 'name': 'bkg1', + 'data': [50.0, 70.0], + 'modifiers': [ + { + 'name': 'stat_firstchannel', + 'type': 'staterror', + 'data': [12.0, 12.0], + } + ], + }, + { + 'name': 'bkg2', + 'data': [30.0, 20.0], + 'modifiers': [ + { + 'name': 'stat_firstchannel', + 'type': 'staterror', + 'data': [5.0, 5.0], + } + ], + }, + {'name': 'bkg3', 'data': [20.0, 15.0], 'modifiers': []}, + ], + } + ] + } + return spec + + +def spec_histosys(): + source = json.load(open('validation/data/2bin_histosys_example2.json')) + spec = { + 'channels': [ + { + 'name': 'singlechannel', + 'samples': [ + { + 'name': 'signal', + 'data': source['bindata']['sig'], + 'modifiers': [ + {'name': 'mu', 'type': 'normfactor', 'data': None} + ], + }, + { + 'name': 'background', + 'data': source['bindata']['bkg'], + 'modifiers': [ + { + 'name': 'bkg_norm', + 'type': 'histosys', + 'data': { + 'lo_data': source['bindata']['bkgsys_dn'], + 'hi_data': source['bindata']['bkgsys_up'], + }, + } + ], + }, + ], + } + ] + } + return spec + + +def spec_normsys(): + source = json.load(open('validation/data/2bin_histosys_example2.json')) + spec = { + 'channels': [ + { + 'name': 'singlechannel', + 'samples': [ + { + 'name': 'signal', + 'data': source['bindata']['sig'], + 'modifiers': [ + {'name': 'mu', 'type': 'normfactor', 'data': None} + ], + }, + { + 'name': 'background', + 'data': source['bindata']['bkg'], + 'modifiers': [ + { + 'name': 'bkg_norm', + 'type': 'normsys', + 'data': {'lo': 0.9, 'hi': 1.1}, + } + ], + }, + ], + } + ] + } + return spec + + +def spec_shapesys(): + source = json.load(open('validation/data/2bin_histosys_example2.json')) + spec = { + 'channels': [ + { + 'name': 'singlechannel', + 'samples': [ + { + 'name': 'signal', + 'data': source['bindata']['sig'], + 'modifiers': [ + {'name': 'mu', 'type': 'normfactor', 'data': None} + ], + }, + { + 'name': 'background', + 'data': source['bindata']['bkg'], + 'modifiers': [ + {'name': 'bkg_norm', 'type': 'shapesys', 'data': [10, 10]} + ], + }, + ], + } + ] + } + return spec + + +def test_export_measurement(): + measurementspec = { + "config": { + "parameters": [ + { + "auxdata": [1.0], + "bounds": [[0.855, 1.145]], + "inits": [1.0], + "name": "lumi", + "sigmas": [0.029], + } + ], + "poi": "mu", + }, + "name": "NormalMeasurement", + } + m = pyhf.writexml.build_measurement(measurementspec) + assert m is not None + assert m.attrib['Name'] == measurementspec['name'] + assert m.attrib['Lumi'] == str( + measurementspec['config']['parameters'][0]['auxdata'][0] + ) + assert m.attrib['LumiRelErr'] == str( + measurementspec['config']['parameters'][0]['sigmas'][0] + ) + poi = m.find('POI') + assert poi is not None + assert poi.text == measurementspec['config']['poi'] + paramsetting = m.find('ParamSetting') + assert paramsetting is None + + [email protected]( + "spec, has_root_data, attrs", + [ + (spec_staterror(), True, ['Activate', 'HistoName']), + (spec_histosys(), True, ['HistoNameHigh', 'HistoNameLow']), + (spec_normsys(), False, ['High', 'Low']), + (spec_shapesys(), True, ['ConstraintType', 'HistoName']), + ], + ids=['staterror', 'histosys', 'normsys', 'shapesys'], +) +def test_export_modifier(mocker, spec, has_root_data, attrs): + channelspec = spec['channels'][0] + channelname = channelspec['name'] + samplespec = channelspec['samples'][1] + samplename = samplespec['name'] + sampledata = samplespec['data'] + modifierspec = samplespec['modifiers'][0] + + mocker.patch('pyhf.writexml._ROOT_DATA_FILE') + modifier = pyhf.writexml.build_modifier( + modifierspec, channelname, samplename, sampledata + ) + assert modifier.attrib['Name'] == modifierspec['name'] + assert all(attr in modifier.attrib for attr in attrs) + assert pyhf.writexml._ROOT_DATA_FILE.__setitem__.called == has_root_data + + [email protected]( + "spec", + [spec_staterror(), spec_histosys(), spec_normsys(), spec_shapesys()], + ids=['staterror', 'histosys', 'normsys', 'shapesys'], +) +def test_export_sample(mocker, spec): + channelspec = spec['channels'][0] + channelname = channelspec['name'] + samplespec = channelspec['samples'][1] + samplename = samplespec['name'] + sampledata = samplespec['data'] + + mocker.patch('pyhf.writexml.build_modifier', return_value=ET.Element("Modifier")) + mocker.patch('pyhf.writexml._ROOT_DATA_FILE') + sample = pyhf.writexml.build_sample(samplespec, channelname) + assert sample.attrib['Name'] == samplespec['name'] + assert sample.attrib['HistoName'] + assert sample.attrib['InputFile'] + assert sample.attrib['NormalizeByTheory'] == str(False) + assert pyhf.writexml.build_modifier.called + assert pyhf.writexml._ROOT_DATA_FILE.__setitem__.called + + [email protected]( + "spec", + [spec_staterror(), spec_histosys(), spec_normsys(), spec_shapesys()], + ids=['staterror', 'histosys', 'normsys', 'shapesys'], +) +def test_export_channel(mocker, spec): + channelspec = spec['channels'][0] + channelname = channelspec['name'] + + mocker.patch('pyhf.writexml.build_data', return_value=ET.Element("Data")) + mocker.patch('pyhf.writexml.build_sample', return_value=ET.Element("Sample")) + mocker.patch('pyhf.writexml._ROOT_DATA_FILE') + channel = pyhf.writexml.build_channel(channelspec, {}) + assert channel.attrib['Name'] == channelspec['name'] + assert channel.attrib['InputFile'] + assert pyhf.writexml.build_data.called is False + assert pyhf.writexml.build_sample.called + assert pyhf.writexml._ROOT_DATA_FILE.__setitem__.called is False + + +def test_export_data(mocker): + channelname = 'channel' + dataspec = {channelname: [0, 1, 2, 3]} + + mocker.patch('pyhf.writexml._ROOT_DATA_FILE') + data = pyhf.writexml.build_data(dataspec, channelname) + assert data.attrib['HistoName'] + assert data.attrib['InputFile'] + assert pyhf.writexml._ROOT_DATA_FILE.__setitem__.called diff --git a/tests/test_scripts.py b/tests/test_scripts.py --- a/tests/test_scripts.py +++ b/tests/test_scripts.py @@ -106,8 +106,8 @@ def test_import_and_export(tmpdir, script_runner): ) ret = script_runner.run(*shlex.split(command)) - command = 'pyhf json2xml {0:s} --specroot {1:s} --dataroot {1:s}'.format( - temp.strpath, str(tmpdir) + command = 'pyhf json2xml {0:s} --output-dir {1:s}'.format( + temp.strpath, tmpdir.mkdir('output').strpath ) ret = script_runner.run(*shlex.split(command)) assert ret.success diff --git a/tests/test_validation.py b/tests/test_validation.py --- a/tests/test_validation.py +++ b/tests/test_validation.py @@ -1,6 +1,8 @@ import pyhf +import pyhf.writexml, pyhf.readxml import json import pytest +import os @pytest.fixture(scope='module') @@ -723,6 +725,7 @@ def validate_hypotest(pdf, data, mu_test, expected_result, tolerance=1e-6): def test_validation(setup_and_tolerance): setup, tolerance = setup_and_tolerance source = setup['source'] + pdf = pyhf.Model(setup['spec']) if 'channels' in source: @@ -743,3 +746,96 @@ def test_validation(setup_and_tolerance): validate_hypotest( pdf, data, setup['mu'], setup['expected']['result'], tolerance=tolerance ) + + [email protected]( + 'toplvl, basedir', + [ + ( + 'validation/xmlimport_input/config/example.xml', + 'validation/xmlimport_input/', + ), + ( + 'validation/xmlimport_input2/config/example.xml', + 'validation/xmlimport_input2', + ), + ( + 'validation/xmlimport_input3/config/examples/example_ShapeSys.xml', + 'validation/xmlimport_input3', + ), + ], + ids=['example-one', 'example-two', 'example-three'], +) +def test_import_roundtrip(tmpdir, toplvl, basedir): + parsed_xml_before = pyhf.readxml.parse(toplvl, basedir) + spec = { + 'channels': parsed_xml_before['channels'], + 'parameters': parsed_xml_before['toplvl']['measurements'][0]['config'][ + 'parameters' + ], + } + pdf_before = pyhf.Model(spec, poiname='SigXsecOverSM') + + tmpconfig = tmpdir.mkdir('config') + tmpdata = tmpdir.mkdir('data') + tmpxml = tmpdir.join('FitConfig.xml') + tmpxml.write( + pyhf.writexml.writexml( + parsed_xml_before, + tmpconfig.strpath, + tmpdata.strpath, + os.path.join(tmpdir.strpath, 'FitConfig'), + ).decode('utf-8') + ) + parsed_xml_after = pyhf.readxml.parse(tmpxml.strpath, tmpdir.strpath) + spec = { + 'channels': parsed_xml_after['channels'], + 'parameters': parsed_xml_after['toplvl']['measurements'][0]['config'][ + 'parameters' + ], + } + pdf_after = pyhf.Model(spec, poiname='SigXsecOverSM') + + data_before = [ + binvalue + for k in pdf_before.spec['channels'] + for binvalue in parsed_xml_before['data'][k['name']] + ] + pdf_before.config.auxdata + + data_after = [ + binvalue + for k in pdf_after.spec['channels'] + for binvalue in parsed_xml_after['data'][k['name']] + ] + pdf_after.config.auxdata + + assert data_before == data_after + + init_pars_before = pdf_before.config.suggested_init() + init_pars_after = pdf_after.config.suggested_init() + assert init_pars_before == init_pars_after + + par_bounds_before = pdf_before.config.suggested_bounds() + par_bounds_after = pdf_after.config.suggested_bounds() + assert par_bounds_before == par_bounds_after + + CLs_obs_before, CLs_exp_set_before = pyhf.utils.hypotest( + 1, + data_before, + pdf_before, + init_pars_before, + par_bounds_before, + return_expected_set=True, + ) + CLs_obs_after, CLs_exp_set_after = pyhf.utils.hypotest( + 1, + data_after, + pdf_after, + init_pars_after, + par_bounds_after, + return_expected_set=True, + ) + + tolerance = 1e-6 + assert abs(CLs_obs_after - CLs_obs_before) / CLs_obs_before < tolerance + for result, expected_result in zip(CLs_exp_set_after, CLs_exp_set_before): + assert abs(result - expected_result) / expected_result < tolerance
XML ROOT Export # Description Given that we observe that some models still scale better in ROOT, it's reasonable to have some an companion tools to `readxml`, namely `writexml` that writes XML + ROOT files corresponding to a model given as JSON.
@kratsg this might be useful to comput published hf JSON in ROOT (e..g MBJ) Yeah, this is going to be much harder to build unfortunately, but it's still possible. It's a lower priority for now. uproot 3.0 is released that allows us to write XML+ROOT out now!
2019-04-08T10:47:24
-1.0
scikit-hep/pyhf
430
scikit-hep__pyhf-430
[ "398" ]
604ff0aa5f39803815b88c9c2e62e37bd4beb410
diff --git a/pyhf/commandline.py b/pyhf/commandline.py --- a/pyhf/commandline.py +++ b/pyhf/commandline.py @@ -52,7 +52,7 @@ def xml2json(entrypoint_xml, basedir, output_file, track_progress): except ImportError: log.error( "xml2json requires uproot, please install pyhf using the " - "xmlimport extra: pip install pyhf[xmlimport] or install uproot " + "xmlio extra: pip install pyhf[xmlio] or install uproot " "manually: pip install uproot" ) from . import readxml @@ -74,6 +74,17 @@ def xml2json(entrypoint_xml, basedir, output_file, track_progress): @click.option('--dataroot', default='data') @click.option('--resultprefix', default='FitConfig') def json2xml(workspace, output_dir, specroot, dataroot, resultprefix): + try: + import uproot + + assert uproot + except ImportError: + log.error( + "json2xml requires uproot, please install pyhf using the " + "xmlio extra: pip install pyhf[xmlio] or install uproot " + "manually: pip install uproot" + ) + ensure_dirs(output_dir) with click.open_file(workspace, 'r') as specstream: d = json.load(specstream) diff --git a/setup.py b/setup.py --- a/setup.py +++ b/setup.py @@ -22,7 +22,7 @@ # 'dask': [ # 'dask[array]' # ], - 'xmlimport': ['uproot'], + 'xmlio': ['uproot'], 'minuit': ['iminuit'], 'develop': [ 'pyflakes',
diff --git a/tests/test_notebooks.py b/tests/test_notebooks.py --- a/tests/test_notebooks.py +++ b/tests/test_notebooks.py @@ -12,6 +12,10 @@ def test_notebooks(tmpdir): pm.execute_notebook('docs/examples/notebooks/hello-world.ipynb', **common_kwargs) + pm.execute_notebook( + 'docs/examples/notebooks/XML_ImportExport.ipynb', **common_kwargs + ) + if sys.version_info.major > 2: # The Binder example uses specific relative paths cwd = os.getcwd()
Add FAQ RE: how to use xml2json CLI tool # Description Add a section to the FAQ RE: how to install the `xmlimport` optional dependencies and how to use the `xml2json` CLI tool. This could also be an entire example Jupyter notebook on using the CLI and then have the FAQ be just on how to install the `xmlimport` dependencies.
2019-04-09T07:41:39
-1.0
scikit-hep/pyhf
435
scikit-hep__pyhf-435
[ "433" ]
f537fe773d72726322e37b469ef1809220beff59
diff --git a/pyhf/writexml.py b/pyhf/writexml.py --- a/pyhf/writexml.py +++ b/pyhf/writexml.py @@ -1,6 +1,8 @@ import logging import os +import shutil +import pkg_resources import xml.etree.cElementTree as ET import numpy as np import uproot @@ -68,7 +70,13 @@ def build_measurement(measurementspec): lumierr = parameter['sigmas'][0] # define measurement - meas = ET.Element("Measurement", Name=name, Lumi=str(lumi), LumiRelErr=str(lumierr)) + meas = ET.Element( + "Measurement", + Name=name, + Lumi=str(lumi), + LumiRelErr=str(lumierr), + ExportOnly=str(True), + ) poiel = ET.Element('POI') poiel.text = poi meas.append(poiel) @@ -115,6 +123,7 @@ def build_modifier(modifierspec, channelname, samplename, sampledata): attrs['HistoName'] = _make_hist_name( channelname, samplename, modifierspec['name'] ) + del attrs['Name'] # need to make this a relative uncertainty stored in ROOT file _export_root_histogram( attrs['HistoName'], np.divide(modifierspec['data'], sampledata).tolist() @@ -184,6 +193,10 @@ def build_channel(channelspec, dataspec): def writexml(spec, specdir, data_rootdir, resultprefix): global _ROOT_DATA_FILE + shutil.copyfile( + pkg_resources.resource_filename(__name__, 'data/HistFactorySchema.dtd'), + os.path.join(os.path.dirname(specdir), 'HistFactorySchema.dtd'), + ) combination = ET.Element( "Combination", OutputFilePrefix=os.path.join('.', specdir, resultprefix) ) @@ -196,6 +209,9 @@ def writexml(spec, specdir, data_rootdir, resultprefix): with open(channelfilename, 'w') as channelfile: channel = build_channel(channelspec, spec.get('data')) indent(channel) + channelfile.write( + "<!DOCTYPE Channel SYSTEM '../HistFactorySchema.dtd'>\n\n" + ) channelfile.write( ET.tostring(channel, encoding='utf-8').decode('utf-8') ) @@ -207,4 +223,6 @@ def writexml(spec, specdir, data_rootdir, resultprefix): for measurement in spec['toplvl']['measurements']: combination.append(build_measurement(measurement)) indent(combination) - return ET.tostring(combination, encoding='utf-8') + return "<!DOCTYPE Combination SYSTEM 'HistFactorySchema.dtd'>\n\n".encode( + "utf-8" + ) + ET.tostring(combination, encoding='utf-8')
diff --git a/tests/test_export.py b/tests/test_export.py --- a/tests/test_export.py +++ b/tests/test_export.py @@ -197,7 +197,9 @@ def test_export_modifier(mocker, spec, has_root_data, attrs): modifier = pyhf.writexml.build_modifier( modifierspec, channelname, samplename, sampledata ) - assert modifier.attrib['Name'] == modifierspec['name'] + # if the modifier is a staterror, it has no Name + if 'Name' in modifier.attrib: + assert modifier.attrib['Name'] == modifierspec['name'] assert all(attr in modifier.attrib for attr in attrs) assert pyhf.writexml._ROOT_DATA_FILE.__setitem__.called == has_root_data
json2xml needs to add support for the HiFa DTD # Description json2xml does not include the DTD statement in the XML outputs that it generates. # Expected Behavior Should include DTD statement. # Actual Behavior Does not include DTD statement. # Checklist - [x] Run `git fetch` to get the most up to date version of `master` - [x] Searched through existing Issues to confirm this is not a duplicate issue - [x] Filled out the Description, Expected Behavior, Actual Behavior, and Steps to Reproduce sections above or have edited/removed them in a way that fully describes the issue
2019-04-09T19:23:00
-1.0
scikit-hep/pyhf
752
scikit-hep__pyhf-752
[ "695" ]
aa167874538ccb2c2ae1fee321f48027ad13b9dd
diff --git a/src/pyhf/cli/spec.py b/src/pyhf/cli/spec.py --- a/src/pyhf/cli/spec.py +++ b/src/pyhf/cli/spec.py @@ -238,12 +238,19 @@ def rename(workspace, output_file, channel, sample, modifier, measurement): @cli.command() @click.argument('workspace-one', default='-') @click.argument('workspace-two', default='-') [email protected]( + '-j', + '--join', + default='none', + type=click.Choice(Workspace.valid_joins), + help='The join operation to apply when combining the two workspaces.', +) @click.option( '--output-file', help='The location of the output json file. If not specified, prints to screen.', default=None, ) -def combine(workspace_one, workspace_two, output_file): +def combine(workspace_one, workspace_two, join, output_file): """ Combine two workspaces into a single workspace. @@ -257,7 +264,7 @@ def combine(workspace_one, workspace_two, output_file): ws_one = Workspace(spec_one) ws_two = Workspace(spec_two) - combined_ws = Workspace.combine(ws_one, ws_two) + combined_ws = Workspace.combine(ws_one, ws_two, join=join) if output_file is None: click.echo(json.dumps(combined_ws, indent=4, sort_keys=True)) diff --git a/src/pyhf/workspace.py b/src/pyhf/workspace.py --- a/src/pyhf/workspace.py +++ b/src/pyhf/workspace.py @@ -7,6 +7,8 @@ """ import logging import jsonpatch +import copy +import collections from . import exceptions from . import utils from .pdf import Model @@ -16,11 +18,251 @@ log = logging.getLogger(__name__) +def _join_items(join, left_items, right_items, key='name'): + """ + Join two lists of dictionaries along the given key. + + This is meant to be as generic as possible for any pairs of lists of dictionaries for many join operations. + + Args: + join (`str`): The join operation to apply. See ~pyhf.workspace.Workspace for valid join operations. + left_items (`list`): A list of dictionaries to join on the left + right_items (`list`): A list of dictionaries to join on the right + + Returns: + :obj:`list`: A joined list of dictionaries. + + """ + if join == 'right outer': + primary_items, secondary_items = right_items, left_items + else: + primary_items, secondary_items = left_items, right_items + joined_items = copy.deepcopy(primary_items) + for secondary_item in secondary_items: + # outer join: merge primary and secondary, matching where possible + if join == 'outer' and secondary_item in primary_items: + continue + # left/right outer join: only add secondary if existing item (by key value) is not in primary + # NB: this will be slow for large numbers of items + elif join in ['left outer', 'right outer'] and secondary_item[key] in [ + item[key] for item in joined_items + ]: + continue + joined_items.append(copy.deepcopy(secondary_item)) + return joined_items + + +def _join_versions(join, left_version, right_version): + """ + Join two workspace versions. + + Raises: + ~pyhf.exceptions.InvalidWorkspaceOperation: Versions are incompatible. + + Args: + join (`str`): The join operation to apply. See ~pyhf.workspace.Workspace for valid join operations. + left_version (`str`): The left workspace version. + right_version (`str`): The right workspace version. + + Returns: + :obj:`str`: The workspace version. + + """ + if left_version != right_version: + raise exceptions.InvalidWorkspaceOperation( + f"Workspaces of different versions cannot be combined: {left_version} != {right_version}" + ) + return left_version + + +def _join_channels(join, left_channels, right_channels): + """ + Join two workspace channel specifications. + + Raises: + ~pyhf.exceptions.InvalidWorkspaceOperation: Channel specifications are incompatible. + + Args: + join (`str`): The join operation to apply. See ~pyhf.workspace.Workspace for valid join operations. + left_channels (`list`): The left channel specification. + right_channels (`list`): The right channel specification. + + Returns: + :obj:`list`: A joined list of channels. Each channel follows the :obj:`defs.json#channel` `schema <https://scikit-hep.org/pyhf/likelihood.html#channel>`__ + + """ + + joined_channels = _join_items(join, left_channels, right_channels) + if join == 'none': + common_channels = set(c['name'] for c in left_channels).intersection( + c['name'] for c in right_channels + ) + if common_channels: + raise exceptions.InvalidWorkspaceOperation( + f"Workspaces cannot have any channels in common with the same name: {common_channels}. You can also try a different join operation: {Workspace.valid_joins}." + ) + + elif join == 'outer': + counted_channels = collections.Counter( + channel['name'] for channel in joined_channels + ) + incompatible_channels = [ + channel for channel, count in counted_channels.items() if count > 1 + ] + if incompatible_channels: + raise exceptions.InvalidWorkspaceOperation( + f"Workspaces cannot have channels in common with incompatible structure: {incompatible_channels}. You can also try a different join operation: {Workspace.valid_joins}." + ) + return joined_channels + + +def _join_observations(join, left_observations, right_observations): + """ + Join two workspace observation specifications. + + Raises: + ~pyhf.exceptions.InvalidWorkspaceOperation: Observation specifications are incompatible. + + Args: + join (`str`): The join operation to apply. See ~pyhf.workspace.Workspace for valid join operations. + left_observations (`list`): The left observation specification. + right_observations (`list`): The right observation specification. + + Returns: + :obj:`list`: A joined list of observations. Each observation follows the :obj:`defs.json#observation` `schema <https://scikit-hep.org/pyhf/likelihood.html#observations>`__ + + """ + joined_observations = _join_items(join, left_observations, right_observations) + if join == 'none': + common_observations = set( + obs['name'] for obs in left_observations + ).intersection(obs['name'] for obs in right_observations) + if common_observations: + raise exceptions.InvalidWorkspaceOperation( + f"Workspaces cannot have any observations in common with the same name: {common_observations}. You can also try a different join operation: {Workspace.valid_joins}." + ) + + elif join == 'outer': + counted_observations = collections.Counter( + observation['name'] for observation in joined_observations + ) + incompatible_observations = [ + observation + for observation, count in counted_observations.items() + if count > 1 + ] + if incompatible_observations: + raise exceptions.InvalidWorkspaceOperation( + f"Workspaces cannot have observations in common with incompatible structure: {incompatible_observations}. You can also try a different join operation: {Workspace.valid_joins}." + ) + return joined_observations + + +def _join_parameter_configs(measurement_name, left_parameters, right_parameters): + """ + Join two measurement parameter config specifications. + + Only uses by :method:`_join_measurements` when join='outer'. + + Raises: + ~pyhf.exceptions.InvalidWorkspaceOperation: Parameter configuration specifications are incompatible. + + Args: + measurement_name (`str`): The name of the measurement being joined (a detail for raising exceptions correctly) + left_parameters (`list`): The left parameter configuration specification. + right_parameters (`list`): The right parameter configuration specification. + + Returns: + :obj:`list`: A joined list of parameter configurations. Each parameter configuration follows the :obj:`defs.json#config` schema + + """ + joined_parameter_configs = _join_items('outer', left_parameters, right_parameters) + counted_parameter_configs = collections.Counter( + parameter['name'] for parameter in joined_parameter_configs + ) + incompatible_parameter_configs = [ + parameter for parameter, count in counted_parameter_configs.items() if count > 1 + ] + if incompatible_parameter_configs: + raise exceptions.InvalidWorkspaceOperation( + f"Workspaces cannot have a measurement ({measurement_name}) with incompatible parameter configs: {incompatible_parameter_configs}. You can also try a different join operation: {Workspace.valid_joins}." + ) + return joined_parameter_configs + + +def _join_measurements(join, left_measurements, right_measurements): + """ + Join two workspace measurement specifications. + + Raises: + ~pyhf.exceptions.InvalidWorkspaceOperation: Measurement specifications are incompatible. + + Args: + join (`str`): The join operation to apply. See ~pyhf.workspace.Workspace for valid join operations. + left_measurements (`list`): The left measurement specification. + right_measurements (`list`): The right measurement specification. + + Returns: + :obj:`list`: A joined list of measurements. Each measurement follows the :obj:`defs.json#measurement` `schema <https://scikit-hep.org/pyhf/likelihood.html#measurements>`__ + + """ + joined_measurements = _join_items(join, left_measurements, right_measurements) + if join == 'none': + common_measurements = set( + meas['name'] for meas in left_measurements + ).intersection(meas['name'] for meas in right_measurements) + if common_measurements: + raise exceptions.InvalidWorkspaceOperation( + f"Workspaces cannot have any measurements in common with the same name: {common_measurements}. You can also try a different join operation: {Workspace.valid_joins}." + ) + + elif join == 'outer': + # need to store a mapping of measurement name to all measurement objects with that name + _measurement_mapping = {} + for measurement in joined_measurements: + _measurement_mapping.setdefault(measurement['name'], []).append(measurement) + # first check for incompatible POI + # then merge parameter configs + incompatible_poi = [ + measurement_name + for measurement_name, measurements in _measurement_mapping.items() + if len(set(measurement['config']['poi'] for measurement in measurements)) + > 1 + ] + if incompatible_poi: + raise exceptions.InvalidWorkspaceOperation( + f"Workspaces cannot have the same measurements with incompatible POI: {incompatible_poi}." + ) + + joined_measurements = [] + for measurement_name, measurements in _measurement_mapping.items(): + if len(measurements) != 1: + new_measurement = { + 'name': measurement_name, + 'config': { + 'poi': measurements[0]['config']['poi'], + 'parameters': _join_parameter_configs( + measurement_name, + *[ + measurement['config']['parameters'] + for measurement in measurements + ], + ), + }, + } + else: + new_measurement = measurements[0] + joined_measurements.append(new_measurement) + return joined_measurements + + class Workspace(_ChannelSummaryMixin, dict): """ A JSON-serializable object that is built from an object that follows the :obj:`workspace.json` `schema <https://scikit-hep.org/pyhf/likelihood.html#workspace>`__. """ + valid_joins = ['none', 'outer', 'left outer', 'right outer'] + def __init__(self, spec, **config_kwargs): """Workspaces hold the model, data and measurements.""" super(Workspace, self).__init__(spec, channels=spec['channels']) @@ -68,9 +310,9 @@ def get_measurement(self, **config_kwargs): ~pyhf.exceptions.InvalidMeasurement: If the measurement was not found Args: - poi_name (str): The name of the parameter of interest to create a new measurement from - measurement_name (str): The name of the measurement to use - measurement_index (int): The index of the measurement to use + poi_name (`str`): The name of the parameter of interest to create a new measurement from + measurement_name (`str`): The name of the measurement to use + measurement_index (`int`): The index of the measurement to use Returns: :obj:`dict`: A measurement object adhering to the schema defs.json#/definitions/measurement @@ -275,7 +517,7 @@ def _prune_and_rename( ], 'observations': [ dict( - observation, + copy.deepcopy(observation), name=rename_channels.get(observation['name'], observation['name']), ) for observation in self['observations'] @@ -337,7 +579,7 @@ def rename(self, modifiers={}, samples={}, channels={}, measurements={}): ) @classmethod - def combine(cls, left, right): + def combine(cls, left, right, join='none'): """ Return a new workspace specification that is the combination of the two workspaces. @@ -362,74 +604,34 @@ def combine(cls, left, right): Args: left (~pyhf.workspace.Workspace): A workspace right (~pyhf.workspace.Workspace): Another workspace + join (:obj:`str`): How to join the two workspaces. Pick from "none", "outer", "left outer", or "right outer". Returns: ~pyhf.workspace.Workspace: A new combined workspace object """ - common_channels = set(left.channels).intersection(right.channels) - if common_channels: - raise exceptions.InvalidWorkspaceOperation( - "Workspaces cannot have any channels in common: {}".format( - common_channels - ) - ) - - common_measurements = set(left.measurement_names).intersection( - right.measurement_names - ) - incompatible_poi = [ - left.get_measurement(measurement_name=m)['config']['poi'] - != right.get_measurement(measurement_name=m)['config']['poi'] - for m in common_measurements - ] - if any(incompatible_poi): - raise exceptions.InvalidWorkspaceOperation( - "Workspaces cannot have any measurements with incompatible POI: {}".format( - [ - m - for m, i in zip(common_measurements, incompatible_poi) - if incompatible_poi - ] - ) + if join not in Workspace.valid_joins: + raise ValueError( + f"Workspaces must be joined using one of the valid join operations ({Workspace.valid_joins}); not {join}" ) - if left.version != right.version: - raise exceptions.InvalidWorkspaceOperation( - "Workspaces of different versions cannot be combined: {} != {}".format( - left.version, right.version - ) + if join in ['left outer', 'right outer']: + log.warning( + "You are using an unsafe join operation. This will silence exceptions that might be raised during a normal 'outer' operation." ) - left_measurements = [ - left.get_measurement(measurement_name=m) - for m in set(left.measurement_names) - set(common_measurements) - ] - right_measurements = [ - right.get_measurement(measurement_name=m) - for m in set(right.measurement_names) - set(common_measurements) - ] - merged_measurements = [ - dict( - name=m, - config=dict( - poi=left.get_measurement(measurement_name=m)['config']['poi'], - parameters=( - left.get_measurement(measurement_name=m)['config']['parameters'] - + right.get_measurement(measurement_name=m)['config'][ - 'parameters' - ] - ), - ), - ) - for m in common_measurements - ] + new_version = _join_versions(join, left['version'], right['version']) + new_channels = _join_channels(join, left['channels'], right['channels']) + new_observations = _join_observations( + join, left['observations'], right['observations'] + ) + new_measurements = _join_measurements( + join, left['measurements'], right['measurements'] + ) newspec = { - 'channels': left['channels'] + right['channels'], - 'measurements': ( - left_measurements + right_measurements + merged_measurements - ), - 'observations': left['observations'] + right['observations'], - 'version': left['version'], + 'channels': new_channels, + 'measurements': new_measurements, + 'observations': new_observations, + 'version': new_version, } return Workspace(newspec)
diff --git a/tests/test_workspace.py b/tests/test_workspace.py --- a/tests/test_workspace.py +++ b/tests/test_workspace.py @@ -67,8 +67,9 @@ def test_get_measurement_fake(workspace_factory): def test_get_measurement_nonexist(workspace_factory): w = workspace_factory() - with pytest.raises(pyhf.exceptions.InvalidMeasurement): + with pytest.raises(pyhf.exceptions.InvalidMeasurement) as excinfo: w.get_measurement(measurement_name='nonexistent_measurement') + assert 'nonexistent_measurement' in str(excinfo.value) def test_get_workspace_measurement_priority(workspace_factory): @@ -275,28 +276,334 @@ def test_rename_measurement(workspace_factory): assert renamed in new_ws.measurement_names -def test_combine_workspace_same_channels(workspace_factory): [email protected](scope='session') +def join_items(): + left = [{'name': 'left', 'key': 'value'}, {'name': 'common', 'key': 'left'}] + right = [{'name': 'right', 'key': 'value'}, {'name': 'common', 'key': 'right'}] + return (left, right) + + +def test_join_items_none(join_items): + left_items, right_items = join_items + joined = pyhf.workspace._join_items('none', left_items, right_items, key='name') + assert all(left in joined for left in left_items) + assert all(right in joined for right in right_items) + + +def test_join_items_outer(join_items): + left_items, right_items = join_items + joined = pyhf.workspace._join_items('outer', left_items, right_items, key='name') + assert all(left in joined for left in left_items) + assert all(right in joined for right in right_items) + + +def test_join_items_left_outer(join_items): + left_items, right_items = join_items + joined = pyhf.workspace._join_items( + 'left outer', left_items, right_items, key='name' + ) + assert all(left in joined for left in left_items) + assert not all(right in joined for right in right_items) + + +def test_join_items_right_outer(join_items): + left_items, right_items = join_items + joined = pyhf.workspace._join_items( + 'right outer', left_items, right_items, key='name' + ) + assert not all(left in joined for left in left_items) + assert all(right in joined for right in right_items) + + [email protected]("join", ['none', 'outer']) +def test_combine_workspace_same_channels_incompatible_structure( + workspace_factory, join +): ws = workspace_factory() - new_ws = ws.rename(channels={'channel2': 'channel3'}) + new_ws = ws.rename( + channels={'channel2': 'channel3'}, + samples={'signal': 'signal_other'}, + measurements={'GaussExample': 'GaussExample2'}, + ).prune(measurements=['GammaExample', 'ConstExample', 'LogNormExample']) with pytest.raises(pyhf.exceptions.InvalidWorkspaceOperation) as excinfo: - pyhf.Workspace.combine(ws, new_ws) + pyhf.Workspace.combine(ws, new_ws, join=join) assert 'channel1' in str(excinfo.value) assert 'channel2' not in str(excinfo.value) -def test_combine_workspace_incompatible_poi(workspace_factory): [email protected]("join", ['outer', 'left outer', 'right outer']) +def test_combine_workspace_same_channels_outer_join(workspace_factory, join): + ws = workspace_factory() + new_ws = ws.rename(channels={'channel2': 'channel3'}) + combined = pyhf.Workspace.combine(ws, new_ws, join=join) + assert 'channel1' in combined.channels + + [email protected]("join", ['left outer', 'right outer']) +def test_combine_workspace_same_channels_outer_join_unsafe( + workspace_factory, join, caplog +): + ws = workspace_factory() + new_ws = ws.rename(channels={'channel2': 'channel3'}) + pyhf.Workspace.combine(ws, new_ws, join=join) + assert 'using an unsafe join operation' in caplog.text + + [email protected]("join", ['none', 'outer']) +def test_combine_workspace_incompatible_poi(workspace_factory, join): ws = workspace_factory() new_ws = ws.rename(channels={'channel1': 'channel3', 'channel2': 'channel4'}).prune( measurements=['GammaExample', 'ConstExample', 'LogNormExample'] ) - new_ws = ws.rename( + new_ws = new_ws.rename( modifiers={new_ws.get_measurement()['config']['poi']: 'renamedPOI'} ) - with pytest.raises(pyhf.exceptions.InvalidWorkspaceOperation): - pyhf.Workspace.combine(ws, new_ws) + with pytest.raises(pyhf.exceptions.InvalidWorkspaceOperation) as excinfo: + pyhf.Workspace.combine(ws, new_ws, join=join) + assert 'GaussExample' in str(excinfo.value) + + [email protected]("join", ['none', 'outer', 'left outer', 'right outer']) +def test_combine_workspace_diff_version(workspace_factory, join): + ws = workspace_factory() + ws.version = '1.0.0' + new_ws = ws.rename( + channels={'channel1': 'channel3', 'channel2': 'channel4'}, + samples={ + 'background1': 'background3', + 'background2': 'background4', + 'signal': 'signal2', + }, + modifiers={ + 'syst1': 'syst4', + 'bkg1Shape': 'bkg3Shape', + 'bkg2Shape': 'bkg4Shape', + }, + measurements={ + 'ConstExample': 'OtherConstExample', + 'LogNormExample': 'OtherLogNormExample', + 'GaussExample': 'OtherGaussExample', + 'GammaExample': 'OtherGammaExample', + }, + ) + new_ws['version'] = '1.2.0' + with pytest.raises(pyhf.exceptions.InvalidWorkspaceOperation) as excinfo: + pyhf.Workspace.combine(ws, new_ws, join=join) + assert '1.0.0' in str(excinfo.value) + assert '1.2.0' in str(excinfo.value) + + [email protected]("join", ['none']) +def test_combine_workspace_duplicate_parameter_configs(workspace_factory, join): + ws = workspace_factory() + new_ws = ws.rename(channels={'channel1': 'channel3', 'channel2': 'channel4'}).prune( + measurements=['GammaExample', 'ConstExample', 'LogNormExample'] + ) + with pytest.raises(pyhf.exceptions.InvalidWorkspaceOperation) as excinfo: + pyhf.Workspace.combine(ws, new_ws, join=join) + assert 'GaussExample' in str(excinfo.value) + + [email protected]("join", ['outer', 'left outer', 'right outer']) +def test_combine_workspace_duplicate_parameter_configs_outer_join( + workspace_factory, join +): + ws = workspace_factory() + new_ws = ws.rename(channels={'channel1': 'channel3', 'channel2': 'channel4'}).prune( + measurements=['GammaExample', 'ConstExample', 'LogNormExample'] + ) + combined = pyhf.Workspace.combine(ws, new_ws, join=join) + + poi = ws.get_measurement(measurement_name='GaussExample')['config']['poi'] + ws_parameter_configs = [ + parameter['name'] + for parameter in ws.get_measurement(measurement_name='GaussExample')['config'][ + 'parameters' + ] + ] + new_ws_parameter_configs = [ + parameter['name'] + for parameter in new_ws.get_measurement(measurement_name='GaussExample')[ + 'config' + ]['parameters'] + ] + combined_parameter_configs = [ + parameter['name'] + for parameter in combined.get_measurement(measurement_name='GaussExample')[ + 'config' + ]['parameters'] + ] + + assert poi in ws_parameter_configs + assert poi in new_ws_parameter_configs + assert poi in combined_parameter_configs + assert 'lumi' in ws_parameter_configs + assert 'lumi' in new_ws_parameter_configs + assert 'lumi' in combined_parameter_configs + assert len(combined_parameter_configs) == len(set(combined_parameter_configs)) + + +def test_combine_workspace_parameter_configs_ordering(workspace_factory): + ws = workspace_factory() + new_ws = ws.rename(channels={'channel1': 'channel3', 'channel2': 'channel4'}).prune( + measurements=['GammaExample', 'ConstExample', 'LogNormExample'] + ) + assert ( + ws.get_measurement(measurement_name='GaussExample')['config']['parameters'] + == new_ws.get_measurement(measurement_name='GaussExample')['config'][ + 'parameters' + ] + ) + + +def test_combine_workspace_observation_ordering(workspace_factory): + ws = workspace_factory() + new_ws = ws.rename(channels={'channel1': 'channel3', 'channel2': 'channel4'}).prune( + measurements=['GammaExample', 'ConstExample', 'LogNormExample'] + ) + assert ws['observations'][0]['data'] == new_ws['observations'][0]['data'] + + +def test_combine_workspace_deepcopied(workspace_factory): + ws = workspace_factory() + new_ws = ws.rename(channels={'channel1': 'channel3', 'channel2': 'channel4'}).prune( + measurements=['GammaExample', 'ConstExample', 'LogNormExample'] + ) + new_ws.get_measurement(measurement_name='GaussExample')['config']['parameters'][0][ + 'bounds' + ] = [[0.0, 1.0]] + new_ws['observations'][0]['data'][0] = -10.0 + assert ( + ws.get_measurement(measurement_name='GaussExample')['config']['parameters'][0][ + 'bounds' + ] + != new_ws.get_measurement(measurement_name='GaussExample')['config'][ + 'parameters' + ][0]['bounds'] + ) + assert ws['observations'][0]['data'] != new_ws['observations'][0]['data'] + + [email protected]("join", ['fake join operation']) +def test_combine_workspace_invalid_join_operation(workspace_factory, join): + ws = workspace_factory() + new_ws = ws.rename(channels={'channel1': 'channel3', 'channel2': 'channel4'}).prune( + measurements=['GammaExample', 'ConstExample', 'LogNormExample'] + ) + with pytest.raises(ValueError) as excinfo: + pyhf.Workspace.combine(ws, new_ws, join=join) + assert join in str(excinfo.value) + + [email protected]("join", ['none']) +def test_combine_workspace_incompatible_parameter_configs(workspace_factory, join): + ws = workspace_factory() + new_ws = ws.rename(channels={'channel1': 'channel3', 'channel2': 'channel4'}).prune( + measurements=['GammaExample', 'ConstExample', 'LogNormExample'] + ) + new_ws.get_measurement(measurement_name='GaussExample')['config']['parameters'][0][ + 'bounds' + ] = [[0.0, 1.0]] + with pytest.raises(pyhf.exceptions.InvalidWorkspaceOperation) as excinfo: + pyhf.Workspace.combine(ws, new_ws, join=join) + assert 'GaussExample' in str(excinfo.value) + + [email protected]("join", ['outer']) +def test_combine_workspace_incompatible_parameter_configs_outer_join( + workspace_factory, join +): + ws = workspace_factory() + new_ws = ws.rename(channels={'channel1': 'channel3', 'channel2': 'channel4'}).prune( + measurements=['GammaExample', 'ConstExample', 'LogNormExample'] + ) + new_ws.get_measurement(measurement_name='GaussExample')['config']['parameters'][0][ + 'bounds' + ] = [[0.0, 1.0]] + with pytest.raises(pyhf.exceptions.InvalidWorkspaceOperation) as excinfo: + pyhf.Workspace.combine(ws, new_ws, join=join) + assert 'GaussExample' in str(excinfo.value) + assert ws.get_measurement(measurement_name='GaussExample')['config']['parameters'][ + 0 + ]['name'] in str(excinfo.value) + assert new_ws.get_measurement(measurement_name='GaussExample')['config'][ + 'parameters' + ][0]['name'] in str(excinfo.value) + + +def test_combine_workspace_incompatible_parameter_configs_left_outer_join( + workspace_factory, +): + ws = workspace_factory() + new_ws = ws.rename(channels={'channel1': 'channel3', 'channel2': 'channel4'}).prune( + measurements=['GammaExample', 'ConstExample', 'LogNormExample'] + ) + new_ws.get_measurement(measurement_name='GaussExample')['config']['parameters'][0][ + 'bounds' + ] = [[0.0, 1.0]] + combined = pyhf.Workspace.combine(ws, new_ws, join='left outer') + assert ( + combined.get_measurement(measurement_name='GaussExample')['config'][ + 'parameters' + ][0] + == ws.get_measurement(measurement_name='GaussExample')['config']['parameters'][ + 0 + ] + ) + + +def test_combine_workspace_incompatible_parameter_configs_right_outer_join( + workspace_factory, +): + ws = workspace_factory() + new_ws = ws.rename(channels={'channel1': 'channel3', 'channel2': 'channel4'}).prune( + measurements=['GammaExample', 'ConstExample', 'LogNormExample'] + ) + new_ws.get_measurement(measurement_name='GaussExample')['config']['parameters'][0][ + 'bounds' + ] = [[0.0, 1.0]] + combined = pyhf.Workspace.combine(ws, new_ws, join='right outer') + assert ( + combined.get_measurement(measurement_name='GaussExample')['config'][ + 'parameters' + ][0] + == new_ws.get_measurement(measurement_name='GaussExample')['config'][ + 'parameters' + ][0] + ) + + [email protected]("join", ['none', 'outer']) +def test_combine_workspace_incompatible_observations(workspace_factory, join): + ws = workspace_factory() + new_ws = ws.rename( + channels={'channel1': 'channel3', 'channel2': 'channel4'}, + samples={ + 'background1': 'background3', + 'background2': 'background4', + 'signal': 'signal2', + }, + modifiers={ + 'syst1': 'syst4', + 'bkg1Shape': 'bkg3Shape', + 'bkg2Shape': 'bkg4Shape', + }, + measurements={ + 'GaussExample': 'OtherGaussExample', + 'GammaExample': 'OtherGammaExample', + 'ConstExample': 'OtherConstExample', + 'LogNormExample': 'OtherLogNormExample', + }, + ) + new_ws['observations'][0]['name'] = ws['observations'][0]['name'] + new_ws['observations'][0]['data'][0] = -10.0 + with pytest.raises(pyhf.exceptions.InvalidWorkspaceOperation) as excinfo: + pyhf.Workspace.combine(ws, new_ws, join=join) + assert ws['observations'][0]['name'] in str(excinfo.value) + assert 'observations' in str(excinfo.value) -def test_combine_workspace_diff_version(workspace_factory): +def test_combine_workspace_incompatible_observations_left_outer(workspace_factory): ws = workspace_factory() new_ws = ws.rename( channels={'channel1': 'channel3', 'channel2': 'channel4'}, @@ -311,18 +618,53 @@ def test_combine_workspace_diff_version(workspace_factory): 'bkg2Shape': 'bkg4Shape', }, measurements={ + 'GaussExample': 'OtherGaussExample', + 'GammaExample': 'OtherGammaExample', 'ConstExample': 'OtherConstExample', 'LogNormExample': 'OtherLogNormExample', + }, + ) + new_ws['observations'][0]['name'] = ws['observations'][0]['name'] + new_ws['observations'][0]['data'][0] = -10.0 + combined = pyhf.Workspace.combine(ws, new_ws, join='left outer') + assert ( + combined.observations[ws['observations'][0]['name']] + == ws['observations'][0]['data'] + ) + + +def test_combine_workspace_incompatible_observations_right_outer(workspace_factory): + ws = workspace_factory() + new_ws = ws.rename( + channels={'channel1': 'channel3', 'channel2': 'channel4'}, + samples={ + 'background1': 'background3', + 'background2': 'background4', + 'signal': 'signal2', + }, + modifiers={ + 'syst1': 'syst4', + 'bkg1Shape': 'bkg3Shape', + 'bkg2Shape': 'bkg4Shape', + }, + measurements={ 'GaussExample': 'OtherGaussExample', 'GammaExample': 'OtherGammaExample', + 'ConstExample': 'OtherConstExample', + 'LogNormExample': 'OtherLogNormExample', }, ) - new_ws.version = '0.0.0' - with pytest.raises(pyhf.exceptions.InvalidWorkspaceOperation): - pyhf.Workspace.combine(ws, new_ws) + new_ws['observations'][0]['name'] = ws['observations'][0]['name'] + new_ws['observations'][0]['data'][0] = -10.0 + combined = pyhf.Workspace.combine(ws, new_ws, join='right outer') + assert ( + combined.observations[ws['observations'][0]['name']] + == new_ws['observations'][0]['data'] + ) -def test_combine_workspace(workspace_factory): [email protected]("join", pyhf.Workspace.valid_joins) +def test_combine_workspace(workspace_factory, join): ws = workspace_factory() new_ws = ws.rename( channels={'channel1': 'channel3', 'channel2': 'channel4'}, @@ -337,17 +679,13 @@ def test_combine_workspace(workspace_factory): 'bkg2Shape': 'bkg4Shape', }, measurements={ + 'GaussExample': 'OtherGaussExample', + 'GammaExample': 'OtherGammaExample', 'ConstExample': 'OtherConstExample', 'LogNormExample': 'OtherLogNormExample', }, ) - combined = pyhf.Workspace.combine(ws, new_ws) + combined = pyhf.Workspace.combine(ws, new_ws, join=join) assert set(combined.channels) == set(ws.channels + new_ws.channels) assert set(combined.samples) == set(ws.samples + new_ws.samples) assert set(combined.parameters) == set(ws.parameters + new_ws.parameters) - combined_measurement = combined.get_measurement(measurement_name='GaussExample') - assert len(combined_measurement['config']['parameters']) == len( - ws.get_measurement(measurement_name='GaussExample')['config']['parameters'] - ) + len( - new_ws.get_measurement(measurement_name='GaussExample')['config']['parameters'] - )
Combined workspaces have duplicated lumi/POI param configurations # Description When combining two workspaces with the same measurement name that has the same POI, the lumi and the POI param config are repeated twice. They should usually be compatible so we should just drop the extra copies. # Expected Behavior A single instance of the lumi and POI parameter configuration. # Actual Behavior Duplicated/extra instances of the lumi and POI parameter configuratoin. # Steps to Reproduce `pyhf combine a.json b.json` # Checklist - [x] Run `git fetch` to get the most up to date version of `master` - [x] Searched through existing Issues to confirm this is not a duplicate issue - [x] Filled out the Description, Expected Behavior, Actual Behavior, and Steps to Reproduce sections above or have edited/removed them in a way that fully describes the issue
2020-01-26T04:46:23
-1.0
scikit-hep/pyhf
802
scikit-hep__pyhf-802
[ "801" ]
021dd117d235ab62afd997652b3273d2491724e0
diff --git a/src/pyhf/workspace.py b/src/pyhf/workspace.py --- a/src/pyhf/workspace.py +++ b/src/pyhf/workspace.py @@ -267,9 +267,10 @@ def __init__(self, spec, **config_kwargs): """Workspaces hold the model, data and measurements.""" super(Workspace, self).__init__(spec, channels=spec['channels']) self.schema = config_kwargs.pop('schema', 'workspace.json') - self.version = config_kwargs.pop('version', None) + self.version = config_kwargs.pop('version', spec.get('version', None)) + # run jsonschema validation of input specification against the (provided) schema - log.info("Validating spec against schema: {0:s}".format(self.schema)) + log.info(f"Validating spec against schema: {self.schema}") utils.validate(self, self.schema, version=self.version) self.measurement_names = []
diff --git a/tests/test_workspace.py b/tests/test_workspace.py --- a/tests/test_workspace.py +++ b/tests/test_workspace.py @@ -38,6 +38,11 @@ def test_build_workspace(workspace_factory): assert w +def test_version_workspace(workspace_factory): + ws = workspace_factory() + assert ws.version is not None + + def test_build_model(workspace_factory): w = workspace_factory() assert w.model()
Workspace.version is not set when loading in a workspace with a version # Description See the title. # Expected Behavior `Workspace.version is not None` # Actual Behavior `Workspace.version is None` # Steps to Reproduce ```python import pyhf, json ws = pyhf.Workspace(json.load(open('workspace.json'))) assert ws.version is not None assert ws.version == ws['version'] ``` # Checklist - [x] Run `git fetch` to get the most up to date version of `master` - [x] Searched through existing Issues to confirm this is not a duplicate issue - [x] Filled out the Description, Expected Behavior, Actual Behavior, and Steps to Reproduce sections above or have edited/removed them in a way that fully describes the issue
I am now moving on to this issue but I'm unable to reproduce the error due to the following exception raised in the workspace.py file ``` KeyError: 'channels' ``` which is due to as per the workspace.json file ``` Unable to load schema from 'http://json-schema.org/draft-06/schema'. No schema request service available(768) ``` I am afraid that I couldn't find a solution to the above problem. @kanishk16 , not sure how you're getting that error... ``` >>> import pyhf, json >>> ws = pyhf.Workspace(json.load(open('my-workspace.json'))) >>> ws.version >>> ws['version'] '1.0.0' ``` works for me just fine. Are you trying to load in the `pyhf/schemas/1.0.0/workspace.json` file as a workspace? It's a schema describing a workspace, not a workspace itself. Sorry for the late reply @kratsg ...Yes, I was trying to load `pyhf/schemas/1.0.0/workspace.json`. Since I am using Google Colab, I am not sure if there already exists a workspace.json. I might not be well versed about it. From what I know, not sure if you are talking about this, there exists a workspace.json corresponding to the workspace of each user. But, what if the workspace.json doesn't exist only (never really thought of)? Could you point me to some resources if I am heading in the wrong direction? There are published likelihoods available for usage here: https://scikit-hep.org/pyhf/citations.html#published-likelihoods - e.g. ``` curl -s -- https://www.hepdata.net/record/resource/1165724?view=true |tar -O -xzvf - - --include patch.ERJR_350p0_0p0.json > patch.ERJR_350p0_0p0.json curl -s -- https://www.hepdata.net/record/resource/1165724?view=true |tar -O -xzvf - - --include BkgOnly.json > BkgOnly.json jsonpatch BkgOnly.json patch.ERJR_350p0_0p0.json > my_workspace.json ``` to get an example workspace in practice. The `workspace.json` is just a schema. You should understand the difference between a JSON schema specification and a JSON document that follows the schema.
2020-03-14T11:48:23
-1.0
scikit-hep/pyhf
813
scikit-hep__pyhf-813
[ "668" ]
f79a74b2c575ca35bcf3229abdcfb902b95b11d6
diff --git a/src/pyhf/pdf.py b/src/pyhf/pdf.py --- a/src/pyhf/pdf.py +++ b/src/pyhf/pdf.py @@ -222,12 +222,22 @@ def __init__(self, spec, **config_kwargs): spec, self.channel_nbins ) - poiname = config_kwargs.get('poiname', 'mu') + # measurement_name is passed in via Workspace::model and this is a bug. We'll remove it here for now + # but needs to be fixed upstream. #836 is filed to keep track. + config_kwargs.pop('measurement_name', None) + + poiname = config_kwargs.pop('poiname', 'mu') + default_modifier_settings = {'normsys': {'interpcode': 'code1'}} - self.modifier_settings = ( - config_kwargs.get('modifier_settings') or default_modifier_settings + self.modifier_settings = config_kwargs.pop( + 'modifier_settings', default_modifier_settings ) + if config_kwargs: + raise KeyError( + f"""Unexpected keyword argument(s): '{"', '".join(config_kwargs.keys())}'""" + ) + self.par_map = {} self.par_order = [] self.poi_name = None diff --git a/src/pyhf/workspace.py b/src/pyhf/workspace.py --- a/src/pyhf/workspace.py +++ b/src/pyhf/workspace.py @@ -325,7 +325,7 @@ def get_measurement(self, **config_kwargs): def _get_measurement(self, **config_kwargs): """See `Workspace::get_measurement`.""" - poi_name = config_kwargs.get('poi_name') + poi_name = config_kwargs.pop('poi_name', None) if poi_name: return { 'name': 'NormalMeasurement', @@ -333,7 +333,7 @@ def _get_measurement(self, **config_kwargs): } if self.measurement_names: - measurement_name = config_kwargs.get('measurement_name') + measurement_name = config_kwargs.pop('measurement_name', None) if measurement_name: if measurement_name not in self.measurement_names: log.debug( @@ -350,7 +350,7 @@ def _get_measurement(self, **config_kwargs): self.measurement_names.index(measurement_name) ] - measurement_index = config_kwargs.get('measurement_index') + measurement_index = config_kwargs.pop('measurement_index', None) if measurement_index: return self['measurements'][measurement_index] @@ -380,7 +380,7 @@ def model(self, **config_kwargs): 'model being created for measurement {0:s}'.format(measurement['name']) ) - patches = config_kwargs.get('patches', []) + patches = config_kwargs.pop('patches', []) modelspec = { 'channels': self['channels'],
diff --git a/tests/test_pdf.py b/tests/test_pdf.py --- a/tests/test_pdf.py +++ b/tests/test_pdf.py @@ -650,3 +650,46 @@ def test_sample_wrong_bins(): } with pytest.raises(pyhf.exceptions.InvalidModel): pyhf.Model(spec) + + [email protected]( + 'measurements, msettings', + [ + ( + None, + {'normsys': {'interpcode': 'code4'}, 'histosys': {'interpcode': 'code4p'},}, + ) + ], +) +def test_unexpected_keyword_argument(measurements, msettings): + spec = { + "channels": [ + { + "name": "singlechannel", + "samples": [ + { + "name": "signal", + "data": [5.0, 10.0], + "modifiers": [ + {"name": "mu", "type": "normfactor", "data": None} + ], + }, + { + "name": "background", + "data": [50.0, 60.0], + "modifiers": [ + { + "name": "uncorr_bkguncrt", + "type": "shapesys", + "data": [5.0, 12.0], + } + ], + }, + ], + } + ] + } + with pytest.raises(KeyError): + pyhf.pdf._ModelConfig( + spec, measurement_name=measurements, modifiers_settings=msettings + )
Catch unspecified/unknown kwargs # Description Came up in #620. The "bug" there is that the line had a typo: ``` p = w.model(measurement_name=None, patches=patches, modifiers_settings=msettings) ^ ``` instead of ``` p = w.model(measurement_name=None, patches=patches, modifier_settings=msettings) ``` We should probably catch unknown kwargs (e.g. pop them all off and make sure there's no unconsumed kwargs). ## Is your feature request related to a problem? Please describe. Typos happen and we should probably help identify the typos. ### Describe the solution you'd like Check if all kwargs are used up and raise an error if not. ### Describe alternatives you've considered None. # Relevant Issues and Pull Requests - #620
2020-03-21T07:58:43
-1.0
scikit-hep/pyhf
819
scikit-hep__pyhf-819
[ "818" ]
58120805ee945f9c02446032942586611b6445bf
diff --git a/docs/conf.py b/docs/conf.py --- a/docs/conf.py +++ b/docs/conf.py @@ -51,7 +51,6 @@ def setup(app): 'sphinx.ext.napoleon', 'sphinx_click.ext', 'nbsphinx', - 'm2r', 'sphinx_issues', 'sphinx_copybutton', 'xref', diff --git a/setup.py b/setup.py --- a/setup.py +++ b/setup.py @@ -2,8 +2,8 @@ from pathlib import Path this_directory = Path(__file__).parent.resolve() -with open(Path(this_directory).joinpath('README.md'), encoding='utf-8') as readme_md: - long_description = readme_md.read() +with open(Path(this_directory).joinpath('README.rst'), encoding='utf-8') as readme_rst: + long_description = readme_rst.read() extras_require = { 'tensorflow': ['tensorflow~=2.0', 'tensorflow-probability~=0.8'], @@ -60,7 +60,6 @@ 'ipywidgets', 'sphinx-issues', 'sphinx-copybutton>0.2.9', - 'm2r', ] ) ) @@ -79,7 +78,7 @@ version='0.4.1', description='(partial) pure python histfactory implementation', long_description=long_description, - long_description_content_type='text/markdown', + long_description_content_type='text/x-rst', url='https://github.com/scikit-hep/pyhf', author='Lukas Heinrich, Matthew Feickert, Giordon Stark', author_email='[email protected], [email protected], [email protected]',
diff --git a/.github/workflows/release_tests.yml b/.github/workflows/release_tests.yml --- a/.github/workflows/release_tests.yml +++ b/.github/workflows/release_tests.yml @@ -22,6 +22,12 @@ jobs: uses: actions/setup-python@v1 with: python-version: ${{ matrix.python-version }} + - name: Free disk space + # WARNING: Needed due to GitHub Actions disk space regression on Linux runners + if: matrix.os == 'ubuntu-latest' + run: | + sudo apt-get clean + df -h - name: Install from PyPI run: | python -m pip install --upgrade pip setuptools wheel diff --git a/tests/test_scripts.py b/tests/test_scripts.py --- a/tests/test_scripts.py +++ b/tests/test_scripts.py @@ -46,10 +46,7 @@ def test_import_prepHistFactory_withProgress(tmpdir, script_runner): def test_import_prepHistFactory_stdout(tmpdir, script_runner): - temp = tmpdir.join("parsed_output.json") - command = 'pyhf xml2json validation/xmlimport_input/config/example.xml --basedir validation/xmlimport_input/'.format( - temp.strpath - ) + command = 'pyhf xml2json validation/xmlimport_input/config/example.xml --basedir validation/xmlimport_input/' ret = script_runner.run(*shlex.split(command)) assert ret.success assert ret.stdout != '' @@ -158,14 +155,12 @@ def test_patch(tmpdir, script_runner): ret = script_runner.run(*shlex.split(command)) assert ret.success - command = 'pyhf cls {0:s} --patch -'.format(temp.strpath, patch.strpath) + command = f'pyhf cls {temp.strpath:s} --patch -' ret = script_runner.run(*shlex.split(command), stdin=patch) assert ret.success - command = 'pyhf json2xml {0:s} --output-dir {1:s} --patch -'.format( - temp.strpath, tmpdir.mkdir('output_2').strpath, patch.strpath - ) + command = f"pyhf json2xml {temp.strpath:s} --output-dir {tmpdir.mkdir('output_2').strpath:s} --patch -" ret = script_runner.run(*shlex.split(command), stdin=patch) assert ret.success
Bug Report: Sphinx v3.0.0 breaks docs build # Description The release of Sphinx [`v3.0.0`](https://github.com/sphinx-doc/sphinx/releases/tag/v3.0.0) [breaks the build of the docs with](https://github.com/scikit-hep/pyhf/runs/562901637?check_suite_focus=true#step:6:11) ```pytb Exception occurred: File "/opt/hostedtoolcache/Python/3.7.6/x64/lib/python3.7/site-packages/sphinx/application.py", line 1069, in add_source_parser self.registry.add_source_parser(*args, **kwargs) TypeError: add_source_parser() takes 2 positional arguments but 3 were given The full traceback has been saved in /tmp/sphinx-err-gu866l6p.log, if you want to report the issue to the developers. Please also report this if it was a user error, so that a better error message can be provided next time. A bug report can be filed in the tracker at <https://github.com/sphinx-doc/sphinx/issues>. Thanks! ``` which when run locally the generated log is ``` $ cat /tmp/sphinx-err-blah.log # Sphinx version: 3.0.0 # Python version: 3.7.5 (CPython) # Docutils version: 0.16 release # Jinja2 version: 2.11.1 # Last messages: # Loaded extensions: Traceback (most recent call last): File "/home/feickert/.venvs/pyhf-dev/lib/python3.7/site-packages/sphinx/cmd/build.py", line 279, in build_main args.tags, args.verbosity, args.jobs, args.keep_going) File "/home/feickert/.venvs/pyhf-dev/lib/python3.7/site-packages/sphinx/application.py", line 244, in __init__ self.setup_extension(extension) File "/home/feickert/.venvs/pyhf-dev/lib/python3.7/site-packages/sphinx/application.py", line 398, in setup_extension self.registry.load_extension(self, extname) File "/home/feickert/.venvs/pyhf-dev/lib/python3.7/site-packages/sphinx/registry.py", line 414, in load_extension metadata = setup(app) File "/home/feickert/.venvs/pyhf-dev/lib/python3.7/site-packages/m2r.py", line 652, in setup app.add_source_parser('.md', M2RParser) File "/home/feickert/.venvs/pyhf-dev/lib/python3.7/site-packages/sphinx/application.py", line 1069, in add_source_parser self.registry.add_source_parser(*args, **kwargs) TypeError: add_source_parser() takes 2 positional arguments but 3 were given ``` # Steps to Reproduce Try to build the docs with Sphinx `v3.0.0` or check the nightly CI builds. # Checklist - [x] Run `git fetch` to get the most up to date version of `master` - [x] Searched through existing Issues to confirm this is not a duplicate issue - [x] Filled out the Description, Expected Behavior, Actual Behavior, and Steps to Reproduce sections above or have edited/removed them in a way that fully describes the issue
This will get fixed if https://github.com/miyakogi/m2r/pull/55 gets merged and a new release gets cut, but `m2r` hasn't had a release since 2018, so the project is probably in archive mode and we might need to find a new extension to use.
2020-04-06T16:32:47
-1.0
End of preview. Expand in Data Studio

No dataset card yet

Downloads last month
92