Skip to content

Commit

Permalink
Merge pull request #11 from joezuntz/fix-sampler-chain
Browse files Browse the repository at this point in the history
Fix bug in sampler chaining and add test
  • Loading branch information
joezuntz authored Apr 27, 2022
2 parents 55efc1b + 7fc9eb4 commit 679af03
Show file tree
Hide file tree
Showing 4 changed files with 77 additions and 15 deletions.
30 changes: 17 additions & 13 deletions cosmosis/main.py
Original file line number Diff line number Diff line change
Expand Up @@ -148,7 +148,7 @@ def setup_output(sampler_class, sampler_number, ini, pool, number_samplers, samp
if ("filename" in output_options) and (sampler_number<number_samplers-1):
filename = output_options['filename']
filename, ext = os.path.splitext(filename)
filename += '.' + sampler_name
filename += '.' + sampler_class.name
filename += ext
output_options['filename'] = filename

Expand Down Expand Up @@ -349,20 +349,24 @@ def make_graph(inifile, dotfile, params=None, variables=None):
data = pipeline.run_parameters(pipeline.start_vector())
pipeline.make_graph(data, dotfile)


# Make this global because it is useful for testing
parser = argparse.ArgumentParser(description="Run a pipeline with a single set of parameters", add_help=True)
parser.add_argument("inifile", help="Input ini file of parameters")
parser.add_argument("--mpi",action='store_true',help="Run in MPI mode.")
parser.add_argument("--smp",type=int,default=0,help="Run with the given number of processes in shared memory multiprocessing (this is experimental and does not work for multinest).")
parser.add_argument("--pdb",action='store_true',help="Start the python debugger on an uncaught error. Only in serial mode.")
parser.add_argument("--segfaults", "--experimental-fault-handling", action='store_true',help="Activate a mode that gives more info on segfault")
parser.add_argument("--mem", type=int, default=0, help="Print out memory usage every this many seconds from root process")
parser.add_argument("-p", "--params", nargs="*", action=ParseExtraParameters, help="Override parameters in inifile, with format section.name1=value1 section.name2=value2...")
parser.add_argument("-v", "--variables", nargs="*", action=ParseExtraParameters, help="Override variables in values file, with format section.name1=value1 section.name2=value2...")
parser.add_argument("--only", nargs="*", help="Fix all parameters except the ones listed")
parser.add_argument("--graph", type=str, default='', help="Do not run a sampler; instead make a graphviz dot file of the pipeline")
parser.add_argument('--version', action='version', version=__version__, help="Print out a version number")


def main():
try:
parser = argparse.ArgumentParser(description="Run a pipeline with a single set of parameters", add_help=True)
parser.add_argument("inifile", help="Input ini file of parameters")
parser.add_argument("--mpi",action='store_true',help="Run in MPI mode.")
parser.add_argument("--smp",type=int,default=0,help="Run with the given number of processes in shared memory multiprocessing (this is experimental and does not work for multinest).")
parser.add_argument("--pdb",action='store_true',help="Start the python debugger on an uncaught error. Only in serial mode.")
parser.add_argument("--segfaults", "--experimental-fault-handling", action='store_true',help="Activate a mode that gives more info on segfault")
parser.add_argument("--mem", type=int, default=0, help="Print out memory usage every this many seconds from root process")
parser.add_argument("-p", "--params", nargs="*", action=ParseExtraParameters, help="Override parameters in inifile, with format section.name1=value1 section.name2=value2...")
parser.add_argument("-v", "--variables", nargs="*", action=ParseExtraParameters, help="Override variables in values file, with format section.name1=value1 section.name2=value2...")
parser.add_argument("--only", nargs="*", help="Fix all parameters except the ones listed")
parser.add_argument("--graph", type=str, default='', help="Do not run a sampler; instead make a graphviz dot file of the pipeline")
parser.add_argument('--version', action='version', version=__version__, help="Print out a version number")
args = parser.parse_args(sys.argv[1:])

if args.graph:
Expand Down
2 changes: 1 addition & 1 deletion cosmosis/samplers/sampler.py
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,7 @@ def __new__(meta, name, bases, class_dict):
meta.registry = {name : cls for name, cls in meta.registry.items() if cls not in bases}
config_name = name[:-len("Sampler")].lower()
cls = type.__new__(meta, name, bases, class_dict)
cls.name = config_name
meta.registry[config_name] = cls
return cls
else:
Expand Down Expand Up @@ -51,7 +52,6 @@ def __init__(self, ini, pipeline, output=None):
self.output = output
self.attribution = PipelineAttribution(self.pipeline.modules)
self.distribution_hints = Hints()
self.name = self.__class__.__name__[:-len("Sampler")].lower()
self.write_header()

def write_header(self):
Expand Down
58 changes: 58 additions & 0 deletions cosmosis/test/test_chaining.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,58 @@
from cosmosis.runtime.config import Inifile
from cosmosis.main import run_cosmosis, parser
import tempfile
import os
import sys
import pytest
import numpy as np


def test_sampler_chain():


with tempfile.TemporaryDirectory() as dirname:
values_file = f"{dirname}/values.txt"
maxlike_file = f"{dirname}/chain.maxlike.txt"
fisher_file = f"{dirname}/chain.fisher.txt"
emcee_file = f"{dirname}/chain.txt"
with open(values_file, "w") as values:
values.write(
"[parameters]\n"
"p1=-3.0 0.0 3.0\n"
"p2=-3.0 0.0 3.0\n")

params = {
('runtime', 'root'): os.path.split(os.path.abspath(__file__))[0],
('runtime', 'sampler'): "maxlike fisher emcee",
("pipeline", "debug"): "T",
("pipeline", "quiet"): "F",
("pipeline", "modules"): "test1",
("pipeline", "extra_output"): "parameters/p3",
("pipeline", "values"): values_file,
("test1", "file"): "test_module.py",
("output", "filename"): emcee_file,
("emcee", "walkers"): "8",
("emcee", "samples"): "100",
("maxlike", "tolerance"): "0.05",
("fisher", "step_size"): "0.01"
}


args = parser.parse_args(["not_a_real_file"])
ini = Inifile(None, override=params)

status = run_cosmosis(args, ini=ini)

data = np.loadtxt(fisher_file)
print(data.shape)

data = np.loadtxt(maxlike_file)
print(data.shape)

data = np.loadtxt(emcee_file)
print(data.shape)



assert status == 0

2 changes: 1 addition & 1 deletion cosmosis/version.py
Original file line number Diff line number Diff line change
@@ -1 +1 @@
__version__ = '2.0.1'
__version__ = '2.0.2'

0 comments on commit 679af03

Please sign in to comment.