Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
31 changes: 17 additions & 14 deletions treerec/tests/README.md
Original file line number Diff line number Diff line change
@@ -1,51 +1,55 @@
# Test suite for tree sequence output from SLiM

## Running the tests
Just do `./run_tests.sh` from within this directory to run the tests on the results of SLiM scripts listed in the `testRecipes/` directory. Alternatively, to run just one of the recipes do `./do_test.sh testRecipes/test_XXX.slim`
Just do `python3 -m pytest` from within this directory to run the tests on the results of SLiM scripts listed in the `testRecipes/` directory. Alternatively, to run just one of the recipes do e.g.
`python3 -m pytest -k test_000_sexual_nonwf`

## Adding new tests


To add a new test:

1. Put the recipe in the `testRecipes/` directory, with a filename like `test_XXX.slim`.
2. Add the additional necessary stuff:
1. Put the recipe in the `test_recipes/` directory, with a filename like `test_XXX.slim`.
2. Add a config line in `recipe_specs.py` which determines which tests to run.
3. Add the additional necessary stuff to the SLiM recipe:

* To check that haplotypes agree between SLiM and the tree sequence, just put

```
source("testing_utils.slim");
source("init.slim");
```

in `initialize()` (this calls `initializeTreeSeq()` and defines functions);
and then call
in `initialize()` (this defines functions); and then call

```
outputMutationResult();
```

at the end (well, whenever you want, really; but only once).
at the end (well, whenever you want, really;).

* To mark individuals in the initial generation with particular mutation types so we
can check *something* even with mutation recording turned off, do
can check *something* even with mutation recording turned off, instead of sourcing
"init.slim", source "init_marked_mutations.slim", i.e. place

```
source("marked_mutations_setup.slim");
source("init_marked_mutations.slim");
```

in `initialize()`, and then
in `initialize()` and then call

```
initializeMarks(n_marks);
```

in `1` (after adding the subpop), and then
in `1` (after adding the subpop), and then, as before,

```
outputMutationTypes();
outputMutationResult();
```
at the end. Note that this will only work properly if there is no new mutation.

* Make sure you call `initializeTreeSeq();` after the `source(...)` line

* Add `chooseAncestralSamples(5)` to some generations along the way
to add some individuals as "ancestral samples". This is done by "remembering" them.

Expand All @@ -62,6 +66,5 @@ To add a new test:
in the simulation.


To temporarily turn off a test, just add e.g. `dont_` to the start of its file name.
Or, add it to `failingTestRecipes/`.
To temporarily turn off a test just comment out the appropriate line in `recipe_specs.py`

205 changes: 205 additions & 0 deletions treerec/tests/conftest.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,205 @@
# Configuration for pytest
import collections
import os
import subprocess

from filelock import FileLock
import pytest
import pyslim

from recipe_specs import recipe_specs

SLiMindividual = collections.namedtuple('SLiMindividual', 'type population pos nodes')

class OutputResult:
"""
A wrapper to process the results files returned from a ts
"""
def __init__(self, out_dir):
assert os.path.isdir(out_dir)
self.dir = out_dir

def get_ts(self, include_text=False):
if include_text:
# read in from text
node_file = open(os.path.join(self.dir, "NodeTable.txt"), "r")
edge_file = open(os.path.join(self.dir, "EdgeTable.txt"), "r")
try:
site_file = open(os.path.join(self.dir, "SiteTable.txt"), "r")
except IOerror:
site_file = None
try:
mutation_file = open(os.path.join(self.dir, "MutationTable.txt"), "r")
except IOerror:
mutation_file = None
try:
individual_file = open(os.path.join(self.dir, "IndividualTable.txt"), "r")
except IOerror:
individual_file = None
try:
population_file = open(os.path.join(self.dir, "PopulationTable.txt"), "r")
except IOerror:
population_file = None
text_ts = msprime.load_text(nodes=node_file, edges=edge_file,
sites=site_file, mutations=mutation_file,
individuals=individual_file,
populations=population_file,
base64_metadata=False)

print("******* Text input.")
yield text_ts
# and binary
bin_ts = pyslim.load(os.path.join(self.dir, "test_output.trees"))
print("******** Binary input.")
yield bin_ts
# and nonsimplified binary
print("******** Unsimplified binary.")
bin_nonsip_ts = pyslim.load(
os.path.join(self.dir, "test_output.unsimplified.trees"))
yield bin_nonsip_ts

@staticmethod
def get_slim_ids(ts):
# get SLiM ID -> msprime ID map from metadata
ids = {}
for n in ts.nodes():
ids[n.metadata["slim_id"]] = n.id
return ids

def mutation_output(self):
"""
Read in the genotypes output by the SLiM function outputMutationResult(),
producing a dictionary indexed by position, whose values are dictionaries
indexed by SLiM genome ID, giving a mutation carried at that position in
that genome. Return None if no such filename exists
"""
basename = "slim_mutation_output.txt" # matches the name in init.slim
filename = os.path.join(self.dir, basename)
if not os.path.isfile(filename):
raise RuntimeError(f"No mutation file {basename} in {self.dir}")
slim_file = open(filename, "r")
slim = {}
for header in slim_file:
headstring = header.split()
assert headstring[0] == "#Genome:"
genome = int(headstring[1])
mutations = slim_file.readline().split()
assert mutations[0] == "Mutations:"
mutations = [int(u) for u in mutations[1:]]
positions = slim_file.readline().split()
assert positions[0] == "Positions:"
positions = [int(u) for u in positions[1:]]
for pos, mut in zip(positions, mutations):
if pos not in slim:
slim[pos] = {}
if genome not in slim[pos]:
slim[pos][genome] = []
slim[pos][genome].append(mut)
return slim

def marked_mutation_output(self, ts):
"""
Output from SLiM will be indexed by position,
and contain a dict indexed by mutation type giving the indivs
inheriting that mut at that position
"""
basename = "slim_no_mutation_output.txt" # matches the name in init.slim
filename = os.path.join(self.dir, basename)
if not os.path.isfile(filename):
raise RuntimeError(f"No marked mutation file {basename} in {self.dir}")
slim_file = open(filename, "r")
ids = self.get_slim_ids(ts)
slim = []
for header in slim_file:
assert header[0:12] == "MutationType"
mut, pos = header[12:].split()
pos = int(pos)
if pos == len(slim):
slim.append({})
slim_ids = [int(u) for u in slim_file.readline().split()]
for u in slim_ids:
assert u in ids
slim[pos][mut] = [ids[u] for u in slim_ids]
return slim

def individual_output(self):
# Read in the individuals output by the SLiM function addIndividuals(),
# producing a dictionary indexed by individual pedigree ID
basename = "slim_individual_output.txt" # matches the name in init.slim
filename = os.path.join(self.dir, basename)
if not os.path.isfile(filename):
raise RuntimeError(f"No individual details file {basename} in {self.dir}")
slim_file = open(filename, "r")
slim = {}
for line in slim_file:
fields = line.split()
assert fields[0].startswith("#Individual:")
store = fields[0][len("#Individual:"):]
assert store in ("remember", "retain", "output")
pedigree_id = int(fields[1])
if pedigree_id in slim and store == "retain":
# We have a duplicate: "remember"ed takes priority
continue
slim[pedigree_id] = SLiMindividual(
type=store,
population=int(fields[2]),
pos=[float(p) for p in fields[3].split(",")],
nodes=[int(p) for p in fields[4].split(",")],
)
return slim

def make_result(run_dir):
"""
SLiM recipes are expected to output their results into a set of directories
within the run_dir: return a list of results, one for each subdirectory
"""
return [
OutputResult(os.path.join(run_dir, f.name))
for f in os.scandir(run_dir)
if f.is_dir()
]

def run_slim(recipe, run_dir, recipe_dir="test_recipes"):
"""
Run the script specified by recipe (which should switch to the run_dir directory).
Recipes should dump files into subdirectories of run_dir, and we return a list of
these directories, which contain the files on which tests should be run
"""
script_dir = os.path.dirname(os.path.realpath(__file__)) # Path to this file
full_recipe = os.path.abspath(os.path.join(recipe_dir, recipe))
assert os.path.isdir(run_dir) # should have been created by caller
cmd = ["slim", "-s", "22", "-d", f"RUN_DIR=\"{run_dir}\"", full_recipe]
print(f"Running {cmd} in dir '{run_dir}', errors etc to 'SLiM_run_output.log'")
with open(os.path.join(run_dir, "SLiM_run_output.log"), "w") as out:
retval = subprocess.call(cmd, cwd=script_dir, stderr=subprocess.STDOUT, stdout=out)
if retval != 0:
raise RuntimeError(f"Could not run `{cmd}`")
return make_result(run_dir)


@pytest.fixture(scope="session", params=recipe_specs.keys())
def recipe(request, tmp_path_factory, worker_id):
"""
Return a dict containing information about the recipe results. Most logic in this
fixture is to check whether we are running as a single proc, or as a worker.
"""
recipe_name=request.param
return_val = {"name": recipe_name}
return_val.update(recipe_specs[recipe_name])

if worker_id == "master":
# not executing in with multiple workers
run_dir = tmp_path_factory.getbasetemp() / recipe_name
else:
# get the temp directory shared by all workers, so that simulation files
# are shared between workers
run_dir = tmp_path_factory.getbasetemp().parent / recipe_name
with FileLock(str(run_dir) + ".lock"):
# lock until all simulations are done
if run_dir.is_dir():
return_val["results"] = make_result(run_dir)
else:
os.makedirs(run_dir, exist_ok=True)
return_val["results"] = run_slim(recipe_name, run_dir)
return return_val

62 changes: 0 additions & 62 deletions treerec/tests/do_test.sh

This file was deleted.

Loading