diff --git a/CHANGELOG.md b/CHANGELOG.md index 3b58d4b0..6766b7f2 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -4,6 +4,17 @@ In development +- The numerical core (the special functions, gamma approximations, expectation + propagation passes, rescaling and utilities) is now a C extension instead of + numba-compiled Python. Results are identical on x86-64 Linux; elsewhere they can + differ in the last few digits. numba is no longer a dependency, + so importing tsdate no longer takes tens of seconds to compile, and + `TSDATE_ENABLE_NUMBA_CACHE` is gone. Wheels are now tested on macOS x86_64 and + built for musllinux. + +- The inside-outside method sums likelihoods in log space with numpy, which can + change results in the last few digits. + - `preprocess_ts` now always sorts the tree sequence, which may change the order of mutations @@ -11,11 +22,24 @@ In development diagnostics are superseded by the scripts in `evaluation/`, the AFS diagnostics moved to `evaluation/afs.py`, and the polytomy test helpers to `tests/`. +- Removed the internal `tsdate.approx` and `tsdate.hypergeo` modules; the special + functions and gamma approximations are now part of the `_tsdate` C extension. + +- The state of `ExpectationPropagation` (the factors, posteriors and normalising + constants) is held by the C extension: the `factors` attribute and the + `EPFactors` class are gone, and `node_posterior`, `edge_logconst` and + `block_logconst` are copies updated by `iterate`. + `tsdate.phasing.reallocate_unphased` returns the reallocated likelihoods instead + of updating its first argument. + **Bugfixes** - Removed an assertion in `split_disjoint_nodes` that is not guarenteed to hold since table sorting changes the order of mutations in tskit 1.0.0 onwards +- `tsdate.rescaling.count_mutations` rejected sample masks of the right size and + accepted those of the wrong size. + ## [0.2.6] - 2026-03-06 Maintenance release. diff --git a/_tsdatemodule.c b/_tsdatemodule.c index 13d13df7..ea4bf2a6 100644 --- a/_tsdatemodule.c +++ b/_tsdatemodule.c @@ -26,6 +26,7 @@ #define NPY_NO_DEPRECATED_API NPY_1_7_API_VERSION #include +#include #include #include "lib/tsdate.h" @@ -74,11 +75,1834 @@ tsdate_raise_library_error(PyObject *Py_UNUSED(self), PyObject *args) return ret; } +/* + * Functions of the tree sequence (phasing, utilities, prior and rescaling). Arrays are + * converted to C-contiguous arrays of the right type and dimension; sizes of arrays + * that share a dimension are checked here (ValueError), and everything else by the + * library. + */ + +#define ARRAY_LEN(array) ((tsd_size_t) PyArray_DIM((array), 0)) +#define DOUBLES(array) ((double *) PyArray_DATA(array)) +#define IDS(array) ((tsd_id_t *) PyArray_DATA(array)) +#define FLAGS(array) ((uint8_t *) PyArray_DATA(array)) + +/* A new array of the given type and shape holding a copy of `data`. */ +static PyArrayObject * +new_array_from_data(int typenum, int ndim, npy_intp *dims, const void *data) +{ + PyArrayObject *ret = (PyArrayObject *) PyArray_SimpleNew(ndim, dims, typenum); + + if (ret != NULL) { + memcpy(PyArray_DATA(ret), data, (size_t) PyArray_NBYTES(ret)); + } + return ret; +} + +static PyObject * +tsdate_block_singletons(PyObject *Py_UNUSED(self), PyObject *args, PyObject *kwds) +{ + PyObject *ret = NULL; + static char *kwlist[] = { "individuals_unphased", "nodes_individual", + "mutations_node", "mutations_position", "edges_child", "edges_left", + "edges_right", "indexes_insert", "indexes_remove", "sequence_length", NULL }; + PyObject *individuals_unphased_obj = NULL; + PyObject *nodes_individual_obj = NULL; + PyObject *mutations_node_obj = NULL; + PyObject *mutations_position_obj = NULL; + PyObject *edges_child_obj = NULL; + PyObject *edges_left_obj = NULL; + PyObject *edges_right_obj = NULL; + PyObject *indexes_insert_obj = NULL; + PyObject *indexes_remove_obj = NULL; + PyArrayObject *individuals_unphased = NULL; + PyArrayObject *nodes_individual = NULL; + PyArrayObject *mutations_node = NULL; + PyArrayObject *mutations_position = NULL; + PyArrayObject *edges_child = NULL; + PyArrayObject *edges_left = NULL; + PyArrayObject *edges_right = NULL; + PyArrayObject *indexes_insert = NULL; + PyArrayObject *indexes_remove = NULL; + PyArrayObject *blocks_stats = NULL; + PyArrayObject *blocks_edges = NULL; + PyArrayObject *mutations_block = NULL; + double *stats = NULL; + tsd_id_t *edges = NULL; + double sequence_length; + tsd_size_t num_edges, num_mutations, num_blocks = 0; + npy_intp dims[2]; + int err; + + if (!PyArg_ParseTupleAndKeywords(args, kwds, "OOOOOOOOOd", kwlist, + &individuals_unphased_obj, &nodes_individual_obj, &mutations_node_obj, + &mutations_position_obj, &edges_child_obj, &edges_left_obj, &edges_right_obj, + &indexes_insert_obj, &indexes_remove_obj, &sequence_length)) { + goto out; + } + individuals_unphased = (PyArrayObject *) PyArray_FROMANY( + individuals_unphased_obj, NPY_BOOL, 1, 1, NPY_ARRAY_IN_ARRAY); + if (individuals_unphased == NULL) { + goto out; + } + nodes_individual = (PyArrayObject *) PyArray_FROMANY( + nodes_individual_obj, NPY_INT32, 1, 1, NPY_ARRAY_IN_ARRAY); + if (nodes_individual == NULL) { + goto out; + } + mutations_node = (PyArrayObject *) PyArray_FROMANY( + mutations_node_obj, NPY_INT32, 1, 1, NPY_ARRAY_IN_ARRAY); + if (mutations_node == NULL) { + goto out; + } + mutations_position = (PyArrayObject *) PyArray_FROMANY( + mutations_position_obj, NPY_FLOAT64, 1, 1, NPY_ARRAY_IN_ARRAY); + if (mutations_position == NULL) { + goto out; + } + edges_child = (PyArrayObject *) PyArray_FROMANY( + edges_child_obj, NPY_INT32, 1, 1, NPY_ARRAY_IN_ARRAY); + if (edges_child == NULL) { + goto out; + } + edges_left = (PyArrayObject *) PyArray_FROMANY( + edges_left_obj, NPY_FLOAT64, 1, 1, NPY_ARRAY_IN_ARRAY); + if (edges_left == NULL) { + goto out; + } + edges_right = (PyArrayObject *) PyArray_FROMANY( + edges_right_obj, NPY_FLOAT64, 1, 1, NPY_ARRAY_IN_ARRAY); + if (edges_right == NULL) { + goto out; + } + indexes_insert = (PyArrayObject *) PyArray_FROMANY( + indexes_insert_obj, NPY_INT32, 1, 1, NPY_ARRAY_IN_ARRAY); + if (indexes_insert == NULL) { + goto out; + } + indexes_remove = (PyArrayObject *) PyArray_FROMANY( + indexes_remove_obj, NPY_INT32, 1, 1, NPY_ARRAY_IN_ARRAY); + if (indexes_remove == NULL) { + goto out; + } + num_edges = ARRAY_LEN(edges_child); + num_mutations = ARRAY_LEN(mutations_node); + if (ARRAY_LEN(edges_left) != num_edges || ARRAY_LEN(edges_right) != num_edges + || ARRAY_LEN(indexes_insert) != num_edges + || ARRAY_LEN(indexes_remove) != num_edges) { + PyErr_SetString(PyExc_ValueError, "Edge arrays must have the same size"); + goto out; + } + if (ARRAY_LEN(mutations_position) != num_mutations) { + PyErr_SetString(PyExc_ValueError, "Mutation arrays must have the same size"); + goto out; + } + dims[0] = (npy_intp) num_mutations; + mutations_block = (PyArrayObject *) PyArray_SimpleNew(1, dims, NPY_INT32); + if (mutations_block == NULL) { + goto out; + } + Py_BEGIN_ALLOW_THREADS + err = tsd_block_singletons(ARRAY_LEN(nodes_individual), + ARRAY_LEN(individuals_unphased), num_edges, num_mutations, + FLAGS(individuals_unphased), IDS(nodes_individual), IDS(mutations_node), + DOUBLES(mutations_position), IDS(edges_child), DOUBLES(edges_left), + DOUBLES(edges_right), IDS(indexes_insert), IDS(indexes_remove), sequence_length, + &num_blocks, &stats, &edges, IDS(mutations_block)); + Py_END_ALLOW_THREADS + if (err != 0) { + handle_library_error(err); + goto out; + } + dims[0] = (npy_intp) num_blocks; + dims[1] = 2; + blocks_stats = new_array_from_data(NPY_FLOAT64, 2, dims, stats); + if (blocks_stats == NULL) { + goto out; + } + blocks_edges = new_array_from_data(NPY_INT32, 2, dims, edges); + if (blocks_edges == NULL) { + goto out; + } + ret = Py_BuildValue("OOO", blocks_stats, blocks_edges, mutations_block); +out: + tsd_safe_free(stats); + tsd_safe_free(edges); + Py_XDECREF(individuals_unphased); + Py_XDECREF(nodes_individual); + Py_XDECREF(mutations_node); + Py_XDECREF(mutations_position); + Py_XDECREF(edges_child); + Py_XDECREF(edges_left); + Py_XDECREF(edges_right); + Py_XDECREF(indexes_insert); + Py_XDECREF(indexes_remove); + Py_XDECREF(blocks_stats); + Py_XDECREF(blocks_edges); + Py_XDECREF(mutations_block); + return ret; +} + +static PyObject * +tsdate_reallocate_unphased(PyObject *Py_UNUSED(self), PyObject *args, PyObject *kwds) +{ + PyObject *ret = NULL; + static char *kwlist[] = { "edges_likelihood", "mutations_phase", "mutations_block", + "blocks_edges", NULL }; + PyObject *edges_likelihood_obj = NULL; + PyObject *mutations_phase_obj = NULL; + PyObject *mutations_block_obj = NULL; + PyObject *blocks_edges_obj = NULL; + PyArrayObject *edges_likelihood = NULL; + PyArrayObject *mutations_phase = NULL; + PyArrayObject *mutations_block = NULL; + PyArrayObject *blocks_edges = NULL; + PyArrayObject *new_likelihood = NULL; + int err; + + if (!PyArg_ParseTupleAndKeywords(args, kwds, "OOOO", kwlist, &edges_likelihood_obj, + &mutations_phase_obj, &mutations_block_obj, &blocks_edges_obj)) { + goto out; + } + edges_likelihood = (PyArrayObject *) PyArray_FROMANY( + edges_likelihood_obj, NPY_FLOAT64, 2, 2, NPY_ARRAY_IN_ARRAY); + if (edges_likelihood == NULL) { + goto out; + } + mutations_phase = (PyArrayObject *) PyArray_FROMANY( + mutations_phase_obj, NPY_FLOAT64, 1, 1, NPY_ARRAY_IN_ARRAY); + if (mutations_phase == NULL) { + goto out; + } + mutations_block = (PyArrayObject *) PyArray_FROMANY( + mutations_block_obj, NPY_INT32, 1, 1, NPY_ARRAY_IN_ARRAY); + if (mutations_block == NULL) { + goto out; + } + blocks_edges = (PyArrayObject *) PyArray_FROMANY( + blocks_edges_obj, NPY_INT32, 2, 2, NPY_ARRAY_IN_ARRAY); + if (blocks_edges == NULL) { + goto out; + } + if (PyArray_DIM(edges_likelihood, 1) != 2 || PyArray_DIM(blocks_edges, 1) != 2) { + PyErr_SetString( + PyExc_ValueError, "edges_likelihood and blocks_edges must have two columns"); + goto out; + } + if (ARRAY_LEN(mutations_block) != ARRAY_LEN(mutations_phase)) { + PyErr_SetString(PyExc_ValueError, "Mutation arrays must have the same size"); + goto out; + } + new_likelihood = (PyArrayObject *) PyArray_NewCopy(edges_likelihood, NPY_CORDER); + if (new_likelihood == NULL) { + goto out; + } + Py_BEGIN_ALLOW_THREADS + err = tsd_reallocate_unphased(ARRAY_LEN(new_likelihood), ARRAY_LEN(mutations_phase), + ARRAY_LEN(blocks_edges), DOUBLES(mutations_phase), IDS(mutations_block), + IDS(blocks_edges), DOUBLES(new_likelihood)); + Py_END_ALLOW_THREADS + if (err != 0) { + handle_library_error(err); + goto out; + } + ret = (PyObject *) new_likelihood; + new_likelihood = NULL; +out: + Py_XDECREF(edges_likelihood); + Py_XDECREF(mutations_phase); + Py_XDECREF(mutations_block); + Py_XDECREF(blocks_edges); + Py_XDECREF(new_likelihood); + return ret; +} + +static PyObject * +tsdate_mutation_frequency(PyObject *Py_UNUSED(self), PyObject *args, PyObject *kwds) +{ + PyObject *ret = NULL; + static char *kwlist[] = { "nodes_sample", "mutations_node", "mutations_position", + "edges_parent", "edges_child", "edges_left", "edges_right", "indexes_insert", + "indexes_remove", "sequence_length", NULL }; + PyObject *nodes_sample_obj = NULL; + PyObject *mutations_node_obj = NULL; + PyObject *mutations_position_obj = NULL; + PyObject *edges_parent_obj = NULL; + PyObject *edges_child_obj = NULL; + PyObject *edges_left_obj = NULL; + PyObject *edges_right_obj = NULL; + PyObject *indexes_insert_obj = NULL; + PyObject *indexes_remove_obj = NULL; + PyArrayObject *nodes_sample = NULL; + PyArrayObject *mutations_node = NULL; + PyArrayObject *mutations_position = NULL; + PyArrayObject *edges_parent = NULL; + PyArrayObject *edges_child = NULL; + PyArrayObject *edges_left = NULL; + PyArrayObject *edges_right = NULL; + PyArrayObject *indexes_insert = NULL; + PyArrayObject *indexes_remove = NULL; + PyArrayObject *mutations_freq = NULL; + double sequence_length; + tsd_size_t num_edges, num_mutations; + npy_intp dims[2]; + int err; + + if (!PyArg_ParseTupleAndKeywords(args, kwds, "OOOOOOOOOd", kwlist, &nodes_sample_obj, + &mutations_node_obj, &mutations_position_obj, &edges_parent_obj, + &edges_child_obj, &edges_left_obj, &edges_right_obj, &indexes_insert_obj, + &indexes_remove_obj, &sequence_length)) { + goto out; + } + nodes_sample = (PyArrayObject *) PyArray_FROMANY( + nodes_sample_obj, NPY_BOOL, 2, 2, NPY_ARRAY_IN_ARRAY); + if (nodes_sample == NULL) { + goto out; + } + mutations_node = (PyArrayObject *) PyArray_FROMANY( + mutations_node_obj, NPY_INT32, 1, 1, NPY_ARRAY_IN_ARRAY); + if (mutations_node == NULL) { + goto out; + } + mutations_position = (PyArrayObject *) PyArray_FROMANY( + mutations_position_obj, NPY_FLOAT64, 1, 1, NPY_ARRAY_IN_ARRAY); + if (mutations_position == NULL) { + goto out; + } + edges_parent = (PyArrayObject *) PyArray_FROMANY( + edges_parent_obj, NPY_INT32, 1, 1, NPY_ARRAY_IN_ARRAY); + if (edges_parent == NULL) { + goto out; + } + edges_child = (PyArrayObject *) PyArray_FROMANY( + edges_child_obj, NPY_INT32, 1, 1, NPY_ARRAY_IN_ARRAY); + if (edges_child == NULL) { + goto out; + } + edges_left = (PyArrayObject *) PyArray_FROMANY( + edges_left_obj, NPY_FLOAT64, 1, 1, NPY_ARRAY_IN_ARRAY); + if (edges_left == NULL) { + goto out; + } + edges_right = (PyArrayObject *) PyArray_FROMANY( + edges_right_obj, NPY_FLOAT64, 1, 1, NPY_ARRAY_IN_ARRAY); + if (edges_right == NULL) { + goto out; + } + indexes_insert = (PyArrayObject *) PyArray_FROMANY( + indexes_insert_obj, NPY_INT32, 1, 1, NPY_ARRAY_IN_ARRAY); + if (indexes_insert == NULL) { + goto out; + } + indexes_remove = (PyArrayObject *) PyArray_FROMANY( + indexes_remove_obj, NPY_INT32, 1, 1, NPY_ARRAY_IN_ARRAY); + if (indexes_remove == NULL) { + goto out; + } + num_edges = ARRAY_LEN(edges_parent); + num_mutations = ARRAY_LEN(mutations_node); + if (ARRAY_LEN(edges_child) != num_edges || ARRAY_LEN(edges_left) != num_edges + || ARRAY_LEN(edges_right) != num_edges || ARRAY_LEN(indexes_insert) != num_edges + || ARRAY_LEN(indexes_remove) != num_edges) { + PyErr_SetString(PyExc_ValueError, "Edge arrays must have the same size"); + goto out; + } + if (ARRAY_LEN(mutations_position) != num_mutations) { + PyErr_SetString(PyExc_ValueError, "Mutation arrays must have the same size"); + goto out; + } + dims[0] = (npy_intp) num_mutations; + dims[1] = PyArray_DIM(nodes_sample, 1); + mutations_freq = (PyArrayObject *) PyArray_SimpleNew(2, dims, NPY_INT32); + if (mutations_freq == NULL) { + goto out; + } + Py_BEGIN_ALLOW_THREADS + err = tsd_mutation_frequency(ARRAY_LEN(nodes_sample), + (tsd_size_t) PyArray_DIM(nodes_sample, 1), num_edges, num_mutations, + FLAGS(nodes_sample), IDS(mutations_node), DOUBLES(mutations_position), + IDS(edges_parent), IDS(edges_child), DOUBLES(edges_left), DOUBLES(edges_right), + IDS(indexes_insert), IDS(indexes_remove), sequence_length, + (int32_t *) PyArray_DATA(mutations_freq)); + Py_END_ALLOW_THREADS + if (err != 0) { + handle_library_error(err); + goto out; + } + ret = (PyObject *) mutations_freq; + mutations_freq = NULL; +out: + Py_XDECREF(nodes_sample); + Py_XDECREF(mutations_node); + Py_XDECREF(mutations_position); + Py_XDECREF(edges_parent); + Py_XDECREF(edges_child); + Py_XDECREF(edges_left); + Py_XDECREF(edges_right); + Py_XDECREF(indexes_insert); + Py_XDECREF(indexes_remove); + Py_XDECREF(mutations_freq); + return ret; +} + +static PyObject * +tsdate_split_disjoint_nodes(PyObject *Py_UNUSED(self), PyObject *args, PyObject *kwds) +{ + PyObject *ret = NULL; + static char *kwlist[] = { "edges_parent", "edges_child", "edges_left", "edges_right", + "nodes_excluded", NULL }; + PyObject *edges_parent_obj = NULL; + PyObject *edges_child_obj = NULL; + PyObject *edges_left_obj = NULL; + PyObject *edges_right_obj = NULL; + PyObject *nodes_excluded_obj = NULL; + PyArrayObject *edges_parent = NULL; + PyArrayObject *edges_child = NULL; + PyArrayObject *edges_left = NULL; + PyArrayObject *edges_right = NULL; + PyArrayObject *nodes_excluded = NULL; + PyArrayObject *new_parent = NULL; + PyArrayObject *new_child = NULL; + PyArrayObject *nodes_order = NULL; + PyArrayObject *split_nodes = NULL; + tsd_id_t *order = NULL; + tsd_size_t num_nodes, num_edges, num_split = 0; + npy_intp dims[1]; + int err; + + if (!PyArg_ParseTupleAndKeywords(args, kwds, "OOOOO", kwlist, &edges_parent_obj, + &edges_child_obj, &edges_left_obj, &edges_right_obj, &nodes_excluded_obj)) { + goto out; + } + edges_parent = (PyArrayObject *) PyArray_FROMANY( + edges_parent_obj, NPY_INT32, 1, 1, NPY_ARRAY_IN_ARRAY); + if (edges_parent == NULL) { + goto out; + } + edges_child = (PyArrayObject *) PyArray_FROMANY( + edges_child_obj, NPY_INT32, 1, 1, NPY_ARRAY_IN_ARRAY); + if (edges_child == NULL) { + goto out; + } + edges_left = (PyArrayObject *) PyArray_FROMANY( + edges_left_obj, NPY_FLOAT64, 1, 1, NPY_ARRAY_IN_ARRAY); + if (edges_left == NULL) { + goto out; + } + edges_right = (PyArrayObject *) PyArray_FROMANY( + edges_right_obj, NPY_FLOAT64, 1, 1, NPY_ARRAY_IN_ARRAY); + if (edges_right == NULL) { + goto out; + } + nodes_excluded = (PyArrayObject *) PyArray_FROMANY( + nodes_excluded_obj, NPY_BOOL, 1, 1, NPY_ARRAY_IN_ARRAY); + if (nodes_excluded == NULL) { + goto out; + } + num_nodes = ARRAY_LEN(nodes_excluded); + num_edges = ARRAY_LEN(edges_parent); + if (ARRAY_LEN(edges_child) != num_edges || ARRAY_LEN(edges_left) != num_edges + || ARRAY_LEN(edges_right) != num_edges) { + PyErr_SetString(PyExc_ValueError, "Edge arrays must have the same size"); + goto out; + } + dims[0] = (npy_intp) num_edges; + new_parent = (PyArrayObject *) PyArray_SimpleNew(1, dims, NPY_INT32); + if (new_parent == NULL) { + goto out; + } + new_child = (PyArrayObject *) PyArray_SimpleNew(1, dims, NPY_INT32); + if (new_child == NULL) { + goto out; + } + Py_BEGIN_ALLOW_THREADS + err = tsd_split_disjoint_nodes(num_nodes, num_edges, IDS(edges_parent), + IDS(edges_child), DOUBLES(edges_left), DOUBLES(edges_right), + FLAGS(nodes_excluded), IDS(new_parent), IDS(new_child), &num_split, &order); + Py_END_ALLOW_THREADS + if (err != 0) { + handle_library_error(err); + goto out; + } + dims[0] = (npy_intp) (num_nodes + num_split); + nodes_order = new_array_from_data(NPY_INT32, 1, dims, order); + if (nodes_order == NULL) { + goto out; + } + dims[0] = (npy_intp) num_split; + split_nodes = new_array_from_data(NPY_INT32, 1, dims, order + num_nodes); + if (split_nodes == NULL) { + goto out; + } + ret = Py_BuildValue("OOOO", new_parent, new_child, nodes_order, split_nodes); +out: + tsd_safe_free(order); + Py_XDECREF(edges_parent); + Py_XDECREF(edges_child); + Py_XDECREF(edges_left); + Py_XDECREF(edges_right); + Py_XDECREF(nodes_excluded); + Py_XDECREF(new_parent); + Py_XDECREF(new_child); + Py_XDECREF(nodes_order); + Py_XDECREF(split_nodes); + return ret; +} + +static PyObject * +tsdate_relabel_mutations_node(PyObject *Py_UNUSED(self), PyObject *args, PyObject *kwds) +{ + PyObject *ret = NULL; + static char *kwlist[] = { "mutations_node", "mutations_position", "nodes_order", + "edges_parent", "edges_child", "edges_left", "edges_right", "indexes_insert", + "indexes_remove", NULL }; + PyObject *mutations_node_obj = NULL; + PyObject *mutations_position_obj = NULL; + PyObject *nodes_order_obj = NULL; + PyObject *edges_parent_obj = NULL; + PyObject *edges_child_obj = NULL; + PyObject *edges_left_obj = NULL; + PyObject *edges_right_obj = NULL; + PyObject *indexes_insert_obj = NULL; + PyObject *indexes_remove_obj = NULL; + PyArrayObject *mutations_node = NULL; + PyArrayObject *mutations_position = NULL; + PyArrayObject *nodes_order = NULL; + PyArrayObject *edges_parent = NULL; + PyArrayObject *edges_child = NULL; + PyArrayObject *edges_left = NULL; + PyArrayObject *edges_right = NULL; + PyArrayObject *indexes_insert = NULL; + PyArrayObject *indexes_remove = NULL; + PyArrayObject *new_node = NULL; + tsd_size_t num_edges, num_mutations; + npy_intp dims[1]; + int err; + + if (!PyArg_ParseTupleAndKeywords(args, kwds, "OOOOOOOOO", kwlist, + &mutations_node_obj, &mutations_position_obj, &nodes_order_obj, + &edges_parent_obj, &edges_child_obj, &edges_left_obj, &edges_right_obj, + &indexes_insert_obj, &indexes_remove_obj)) { + goto out; + } + mutations_node = (PyArrayObject *) PyArray_FROMANY( + mutations_node_obj, NPY_INT32, 1, 1, NPY_ARRAY_IN_ARRAY); + if (mutations_node == NULL) { + goto out; + } + mutations_position = (PyArrayObject *) PyArray_FROMANY( + mutations_position_obj, NPY_FLOAT64, 1, 1, NPY_ARRAY_IN_ARRAY); + if (mutations_position == NULL) { + goto out; + } + nodes_order = (PyArrayObject *) PyArray_FROMANY( + nodes_order_obj, NPY_INT32, 1, 1, NPY_ARRAY_IN_ARRAY); + if (nodes_order == NULL) { + goto out; + } + edges_parent = (PyArrayObject *) PyArray_FROMANY( + edges_parent_obj, NPY_INT32, 1, 1, NPY_ARRAY_IN_ARRAY); + if (edges_parent == NULL) { + goto out; + } + edges_child = (PyArrayObject *) PyArray_FROMANY( + edges_child_obj, NPY_INT32, 1, 1, NPY_ARRAY_IN_ARRAY); + if (edges_child == NULL) { + goto out; + } + edges_left = (PyArrayObject *) PyArray_FROMANY( + edges_left_obj, NPY_FLOAT64, 1, 1, NPY_ARRAY_IN_ARRAY); + if (edges_left == NULL) { + goto out; + } + edges_right = (PyArrayObject *) PyArray_FROMANY( + edges_right_obj, NPY_FLOAT64, 1, 1, NPY_ARRAY_IN_ARRAY); + if (edges_right == NULL) { + goto out; + } + indexes_insert = (PyArrayObject *) PyArray_FROMANY( + indexes_insert_obj, NPY_INT32, 1, 1, NPY_ARRAY_IN_ARRAY); + if (indexes_insert == NULL) { + goto out; + } + indexes_remove = (PyArrayObject *) PyArray_FROMANY( + indexes_remove_obj, NPY_INT32, 1, 1, NPY_ARRAY_IN_ARRAY); + if (indexes_remove == NULL) { + goto out; + } + num_edges = ARRAY_LEN(edges_parent); + num_mutations = ARRAY_LEN(mutations_node); + if (ARRAY_LEN(edges_child) != num_edges || ARRAY_LEN(edges_left) != num_edges + || ARRAY_LEN(edges_right) != num_edges || ARRAY_LEN(indexes_insert) != num_edges + || ARRAY_LEN(indexes_remove) != num_edges) { + PyErr_SetString(PyExc_ValueError, "Edge arrays must have the same size"); + goto out; + } + if (ARRAY_LEN(mutations_position) != num_mutations) { + PyErr_SetString(PyExc_ValueError, "Mutation arrays must have the same size"); + goto out; + } + dims[0] = (npy_intp) num_mutations; + new_node = (PyArrayObject *) PyArray_SimpleNew(1, dims, NPY_INT32); + if (new_node == NULL) { + goto out; + } + Py_BEGIN_ALLOW_THREADS + err = tsd_relabel_mutations_node(ARRAY_LEN(nodes_order), num_edges, num_mutations, + IDS(mutations_node), DOUBLES(mutations_position), IDS(nodes_order), + IDS(edges_parent), IDS(edges_child), DOUBLES(edges_left), DOUBLES(edges_right), + IDS(indexes_insert), IDS(indexes_remove), IDS(new_node)); + Py_END_ALLOW_THREADS + if (err != 0) { + handle_library_error(err); + goto out; + } + ret = (PyObject *) new_node; + new_node = NULL; +out: + Py_XDECREF(mutations_node); + Py_XDECREF(mutations_position); + Py_XDECREF(nodes_order); + Py_XDECREF(edges_parent); + Py_XDECREF(edges_child); + Py_XDECREF(edges_left); + Py_XDECREF(edges_right); + Py_XDECREF(indexes_insert); + Py_XDECREF(indexes_remove); + Py_XDECREF(new_node); + return ret; +} + +static PyObject * +tsdate_constrain_ages(PyObject *Py_UNUSED(self), PyObject *args, PyObject *kwds) +{ + PyObject *ret = NULL; + static char *kwlist[] = { "nodes_time", "nodes_fixed", "edges_parent", "edges_child", + "epsilon", "max_iterations", NULL }; + PyObject *nodes_time_obj = NULL; + PyObject *nodes_fixed_obj = NULL; + PyObject *edges_parent_obj = NULL; + PyObject *edges_child_obj = NULL; + PyArrayObject *nodes_time = NULL; + PyArrayObject *nodes_fixed = NULL; + PyArrayObject *edges_parent = NULL; + PyArrayObject *edges_child = NULL; + PyArrayObject *new_time = NULL; + double epsilon; + long long max_iterations; + tsd_size_t num_nodes, num_edges; + npy_intp dims[1]; + int err; + + if (!PyArg_ParseTupleAndKeywords(args, kwds, "OOOOdL", kwlist, &nodes_time_obj, + &nodes_fixed_obj, &edges_parent_obj, &edges_child_obj, &epsilon, + &max_iterations)) { + goto out; + } + nodes_time = (PyArrayObject *) PyArray_FROMANY( + nodes_time_obj, NPY_FLOAT64, 1, 1, NPY_ARRAY_IN_ARRAY); + if (nodes_time == NULL) { + goto out; + } + nodes_fixed = (PyArrayObject *) PyArray_FROMANY( + nodes_fixed_obj, NPY_BOOL, 1, 1, NPY_ARRAY_IN_ARRAY); + if (nodes_fixed == NULL) { + goto out; + } + edges_parent = (PyArrayObject *) PyArray_FROMANY( + edges_parent_obj, NPY_INT32, 1, 1, NPY_ARRAY_IN_ARRAY); + if (edges_parent == NULL) { + goto out; + } + edges_child = (PyArrayObject *) PyArray_FROMANY( + edges_child_obj, NPY_INT32, 1, 1, NPY_ARRAY_IN_ARRAY); + if (edges_child == NULL) { + goto out; + } + num_nodes = ARRAY_LEN(nodes_time); + num_edges = ARRAY_LEN(edges_parent); + if (ARRAY_LEN(nodes_fixed) != num_nodes) { + PyErr_SetString(PyExc_ValueError, "Node arrays must have the same size"); + goto out; + } + if (ARRAY_LEN(edges_child) != num_edges) { + PyErr_SetString(PyExc_ValueError, "Edge arrays must have the same size"); + goto out; + } + dims[0] = (npy_intp) num_nodes; + new_time = (PyArrayObject *) PyArray_SimpleNew(1, dims, NPY_FLOAT64); + if (new_time == NULL) { + goto out; + } + Py_BEGIN_ALLOW_THREADS + err = tsd_constrain_ages(num_nodes, num_edges, DOUBLES(nodes_time), + FLAGS(nodes_fixed), IDS(edges_parent), IDS(edges_child), epsilon, + (int64_t) max_iterations, DOUBLES(new_time)); + Py_END_ALLOW_THREADS + if (err != 0) { + handle_library_error(err); + goto out; + } + ret = (PyObject *) new_time; + new_time = NULL; +out: + Py_XDECREF(nodes_time); + Py_XDECREF(nodes_fixed); + Py_XDECREF(edges_parent); + Py_XDECREF(edges_child); + Py_XDECREF(new_time); + return ret; +} + +static PyObject * +tsdate_contains_unary_nodes(PyObject *Py_UNUSED(self), PyObject *args, PyObject *kwds) +{ + PyObject *ret = NULL; + static char *kwlist[] = { "nodes_mask", "edges_parent", "edges_left", "edges_right", + "indexes_insert", "indexes_remove", "sequence_length", NULL }; + PyObject *nodes_mask_obj = NULL; + PyObject *edges_parent_obj = NULL; + PyObject *edges_left_obj = NULL; + PyObject *edges_right_obj = NULL; + PyObject *indexes_insert_obj = NULL; + PyObject *indexes_remove_obj = NULL; + PyArrayObject *nodes_mask = NULL; + PyArrayObject *edges_parent = NULL; + PyArrayObject *edges_left = NULL; + PyArrayObject *edges_right = NULL; + PyArrayObject *indexes_insert = NULL; + PyArrayObject *indexes_remove = NULL; + double sequence_length; + tsd_size_t num_edges; + int contains_unary = 0; + int err; + + if (!PyArg_ParseTupleAndKeywords(args, kwds, "OOOOOOd", kwlist, &nodes_mask_obj, + &edges_parent_obj, &edges_left_obj, &edges_right_obj, &indexes_insert_obj, + &indexes_remove_obj, &sequence_length)) { + goto out; + } + nodes_mask = (PyArrayObject *) PyArray_FROMANY( + nodes_mask_obj, NPY_BOOL, 1, 1, NPY_ARRAY_IN_ARRAY); + if (nodes_mask == NULL) { + goto out; + } + edges_parent = (PyArrayObject *) PyArray_FROMANY( + edges_parent_obj, NPY_INT32, 1, 1, NPY_ARRAY_IN_ARRAY); + if (edges_parent == NULL) { + goto out; + } + edges_left = (PyArrayObject *) PyArray_FROMANY( + edges_left_obj, NPY_FLOAT64, 1, 1, NPY_ARRAY_IN_ARRAY); + if (edges_left == NULL) { + goto out; + } + edges_right = (PyArrayObject *) PyArray_FROMANY( + edges_right_obj, NPY_FLOAT64, 1, 1, NPY_ARRAY_IN_ARRAY); + if (edges_right == NULL) { + goto out; + } + indexes_insert = (PyArrayObject *) PyArray_FROMANY( + indexes_insert_obj, NPY_INT32, 1, 1, NPY_ARRAY_IN_ARRAY); + if (indexes_insert == NULL) { + goto out; + } + indexes_remove = (PyArrayObject *) PyArray_FROMANY( + indexes_remove_obj, NPY_INT32, 1, 1, NPY_ARRAY_IN_ARRAY); + if (indexes_remove == NULL) { + goto out; + } + num_edges = ARRAY_LEN(edges_parent); + if (ARRAY_LEN(edges_left) != num_edges || ARRAY_LEN(edges_right) != num_edges + || ARRAY_LEN(indexes_insert) != num_edges + || ARRAY_LEN(indexes_remove) != num_edges) { + PyErr_SetString(PyExc_ValueError, "Edge arrays must have the same size"); + goto out; + } + Py_BEGIN_ALLOW_THREADS + err = tsd_contains_unary_nodes(ARRAY_LEN(nodes_mask), num_edges, FLAGS(nodes_mask), + IDS(edges_parent), DOUBLES(edges_left), DOUBLES(edges_right), + IDS(indexes_insert), IDS(indexes_remove), sequence_length, &contains_unary); + Py_END_ALLOW_THREADS + if (err != 0) { + handle_library_error(err); + goto out; + } + ret = PyBool_FromLong(contains_unary); +out: + Py_XDECREF(nodes_mask); + Py_XDECREF(edges_parent); + Py_XDECREF(edges_left); + Py_XDECREF(edges_right); + Py_XDECREF(indexes_insert); + Py_XDECREF(indexes_remove); + return ret; +} + +static PyObject * +tsdate_conditional_coalescent_variance( + PyObject *Py_UNUSED(self), PyObject *args, PyObject *kwds) +{ + PyObject *ret = NULL; + static char *kwlist[] = { "num_tips", NULL }; + PyArrayObject *variance = NULL; + Py_ssize_t num_tips; + npy_intp dims[1]; + int err; + + if (!PyArg_ParseTupleAndKeywords(args, kwds, "n", kwlist, &num_tips)) { + goto out; + } + if (num_tips < 0) { + PyErr_SetString(PyExc_ValueError, "The number of tips must be non-negative"); + goto out; + } + dims[0] = (npy_intp) num_tips + 1; + variance = (PyArrayObject *) PyArray_SimpleNew(1, dims, NPY_FLOAT64); + if (variance == NULL) { + goto out; + } + Py_BEGIN_ALLOW_THREADS + err = tsd_conditional_coalescent_variance((tsd_size_t) num_tips, DOUBLES(variance)); + Py_END_ALLOW_THREADS + if (err != 0) { + handle_library_error(err); + goto out; + } + ret = (PyObject *) variance; + variance = NULL; +out: + Py_XDECREF(variance); + return ret; +} + +static PyObject * +tsdate_count_mutations(PyObject *Py_UNUSED(self), PyObject *args, PyObject *kwds) +{ + PyObject *ret = NULL; + static char *kwlist[] = { "nodes_sample", "mutations_node", "mutations_position", + "edges_parent", "edges_child", "edges_left", "edges_right", "indexes_insert", + "indexes_remove", "sequence_length", "size_biased", NULL }; + PyObject *nodes_sample_obj = NULL; + PyObject *mutations_node_obj = NULL; + PyObject *mutations_position_obj = NULL; + PyObject *edges_parent_obj = NULL; + PyObject *edges_child_obj = NULL; + PyObject *edges_left_obj = NULL; + PyObject *edges_right_obj = NULL; + PyObject *indexes_insert_obj = NULL; + PyObject *indexes_remove_obj = NULL; + PyArrayObject *nodes_sample = NULL; + PyArrayObject *mutations_node = NULL; + PyArrayObject *mutations_position = NULL; + PyArrayObject *edges_parent = NULL; + PyArrayObject *edges_child = NULL; + PyArrayObject *edges_left = NULL; + PyArrayObject *edges_right = NULL; + PyArrayObject *indexes_insert = NULL; + PyArrayObject *indexes_remove = NULL; + PyArrayObject *edges_stats = NULL; + PyArrayObject *mutations_edge = NULL; + double sequence_length; + int size_biased; + tsd_size_t num_edges, num_mutations; + npy_intp dims[2]; + int err; + + if (!PyArg_ParseTupleAndKeywords(args, kwds, "OOOOOOOOOdp", kwlist, + &nodes_sample_obj, &mutations_node_obj, &mutations_position_obj, + &edges_parent_obj, &edges_child_obj, &edges_left_obj, &edges_right_obj, + &indexes_insert_obj, &indexes_remove_obj, &sequence_length, &size_biased)) { + goto out; + } + nodes_sample = (PyArrayObject *) PyArray_FROMANY( + nodes_sample_obj, NPY_BOOL, 1, 1, NPY_ARRAY_IN_ARRAY); + if (nodes_sample == NULL) { + goto out; + } + mutations_node = (PyArrayObject *) PyArray_FROMANY( + mutations_node_obj, NPY_INT32, 1, 1, NPY_ARRAY_IN_ARRAY); + if (mutations_node == NULL) { + goto out; + } + mutations_position = (PyArrayObject *) PyArray_FROMANY( + mutations_position_obj, NPY_FLOAT64, 1, 1, NPY_ARRAY_IN_ARRAY); + if (mutations_position == NULL) { + goto out; + } + edges_parent = (PyArrayObject *) PyArray_FROMANY( + edges_parent_obj, NPY_INT32, 1, 1, NPY_ARRAY_IN_ARRAY); + if (edges_parent == NULL) { + goto out; + } + edges_child = (PyArrayObject *) PyArray_FROMANY( + edges_child_obj, NPY_INT32, 1, 1, NPY_ARRAY_IN_ARRAY); + if (edges_child == NULL) { + goto out; + } + edges_left = (PyArrayObject *) PyArray_FROMANY( + edges_left_obj, NPY_FLOAT64, 1, 1, NPY_ARRAY_IN_ARRAY); + if (edges_left == NULL) { + goto out; + } + edges_right = (PyArrayObject *) PyArray_FROMANY( + edges_right_obj, NPY_FLOAT64, 1, 1, NPY_ARRAY_IN_ARRAY); + if (edges_right == NULL) { + goto out; + } + indexes_insert = (PyArrayObject *) PyArray_FROMANY( + indexes_insert_obj, NPY_INT32, 1, 1, NPY_ARRAY_IN_ARRAY); + if (indexes_insert == NULL) { + goto out; + } + indexes_remove = (PyArrayObject *) PyArray_FROMANY( + indexes_remove_obj, NPY_INT32, 1, 1, NPY_ARRAY_IN_ARRAY); + if (indexes_remove == NULL) { + goto out; + } + num_edges = ARRAY_LEN(edges_parent); + num_mutations = ARRAY_LEN(mutations_node); + if (ARRAY_LEN(edges_child) != num_edges || ARRAY_LEN(edges_left) != num_edges + || ARRAY_LEN(edges_right) != num_edges || ARRAY_LEN(indexes_insert) != num_edges + || ARRAY_LEN(indexes_remove) != num_edges) { + PyErr_SetString(PyExc_ValueError, "Edge arrays must have the same size"); + goto out; + } + if (ARRAY_LEN(mutations_position) != num_mutations) { + PyErr_SetString(PyExc_ValueError, "Mutation arrays must have the same size"); + goto out; + } + dims[0] = (npy_intp) num_edges; + dims[1] = 2; + edges_stats = (PyArrayObject *) PyArray_SimpleNew(2, dims, NPY_FLOAT64); + if (edges_stats == NULL) { + goto out; + } + dims[0] = (npy_intp) num_mutations; + mutations_edge = (PyArrayObject *) PyArray_SimpleNew(1, dims, NPY_INT32); + if (mutations_edge == NULL) { + goto out; + } + Py_BEGIN_ALLOW_THREADS + err = tsd_count_mutations(ARRAY_LEN(nodes_sample), FLAGS(nodes_sample), + num_mutations, IDS(mutations_node), DOUBLES(mutations_position), num_edges, + IDS(edges_parent), IDS(edges_child), DOUBLES(edges_left), DOUBLES(edges_right), + IDS(indexes_insert), IDS(indexes_remove), sequence_length, size_biased, + DOUBLES(edges_stats), IDS(mutations_edge)); + Py_END_ALLOW_THREADS + if (err != 0) { + handle_library_error(err); + goto out; + } + ret = Py_BuildValue("OO", edges_stats, mutations_edge); +out: + Py_XDECREF(nodes_sample); + Py_XDECREF(mutations_node); + Py_XDECREF(mutations_position); + Py_XDECREF(edges_parent); + Py_XDECREF(edges_child); + Py_XDECREF(edges_left); + Py_XDECREF(edges_right); + Py_XDECREF(indexes_insert); + Py_XDECREF(indexes_remove); + Py_XDECREF(edges_stats); + Py_XDECREF(mutations_edge); + return ret; +} + +static PyObject * +tsdate_mutational_area(PyObject *Py_UNUSED(self), PyObject *args, PyObject *kwds) +{ + PyObject *ret = NULL; + static char *kwlist[] + = { "nodes_time", "edges_likelihood", "edges_parent", "edges_child", NULL }; + PyObject *nodes_time_obj = NULL; + PyObject *edges_likelihood_obj = NULL; + PyObject *edges_parent_obj = NULL; + PyObject *edges_child_obj = NULL; + PyArrayObject *nodes_time = NULL; + PyArrayObject *edges_likelihood = NULL; + PyArrayObject *edges_parent = NULL; + PyArrayObject *edges_child = NULL; + PyArrayObject *counts = NULL; + PyArrayObject *offset = NULL; + PyArrayObject *duration = NULL; + PyArrayObject *nodes_index = NULL; + tsd_epoch_stats_t stats = { 0, NULL, NULL, NULL }; + tsd_size_t num_nodes, num_edges; + npy_intp dims[1]; + int err; + + if (!PyArg_ParseTupleAndKeywords(args, kwds, "OOOO", kwlist, &nodes_time_obj, + &edges_likelihood_obj, &edges_parent_obj, &edges_child_obj)) { + goto out; + } + nodes_time = (PyArrayObject *) PyArray_FROMANY( + nodes_time_obj, NPY_FLOAT64, 1, 1, NPY_ARRAY_IN_ARRAY); + if (nodes_time == NULL) { + goto out; + } + edges_likelihood = (PyArrayObject *) PyArray_FROMANY( + edges_likelihood_obj, NPY_FLOAT64, 2, 2, NPY_ARRAY_IN_ARRAY); + if (edges_likelihood == NULL) { + goto out; + } + edges_parent = (PyArrayObject *) PyArray_FROMANY( + edges_parent_obj, NPY_INT32, 1, 1, NPY_ARRAY_IN_ARRAY); + if (edges_parent == NULL) { + goto out; + } + edges_child = (PyArrayObject *) PyArray_FROMANY( + edges_child_obj, NPY_INT32, 1, 1, NPY_ARRAY_IN_ARRAY); + if (edges_child == NULL) { + goto out; + } + num_nodes = ARRAY_LEN(nodes_time); + num_edges = ARRAY_LEN(edges_parent); + if (ARRAY_LEN(edges_child) != num_edges) { + PyErr_SetString(PyExc_ValueError, "Edge arrays must have the same size"); + goto out; + } + if (ARRAY_LEN(edges_likelihood) != num_edges + || PyArray_DIM(edges_likelihood, 1) != 2) { + PyErr_SetString( + PyExc_ValueError, "Likelihoods must have one row of two columns per edge"); + goto out; + } + dims[0] = (npy_intp) num_nodes; + nodes_index = (PyArrayObject *) PyArray_SimpleNew(1, dims, NPY_INT32); + if (nodes_index == NULL) { + goto out; + } + Py_BEGIN_ALLOW_THREADS + err = tsd_mutational_area(num_nodes, DOUBLES(nodes_time), num_edges, + DOUBLES(edges_likelihood), IDS(edges_parent), IDS(edges_child), &stats, + IDS(nodes_index)); + Py_END_ALLOW_THREADS + if (err != 0) { + handle_library_error(err); + goto out; + } + dims[0] = (npy_intp) stats.num_epochs; + counts = new_array_from_data(NPY_FLOAT64, 1, dims, stats.counts); + if (counts == NULL) { + goto out; + } + offset = new_array_from_data(NPY_FLOAT64, 1, dims, stats.offset); + if (offset == NULL) { + goto out; + } + duration = new_array_from_data(NPY_FLOAT64, 1, dims, stats.duration); + if (duration == NULL) { + goto out; + } + ret = Py_BuildValue("OOOO", counts, offset, duration, nodes_index); +out: + tsd_epoch_stats_free(&stats); + Py_XDECREF(nodes_time); + Py_XDECREF(edges_likelihood); + Py_XDECREF(edges_parent); + Py_XDECREF(edges_child); + Py_XDECREF(counts); + Py_XDECREF(offset); + Py_XDECREF(duration); + Py_XDECREF(nodes_index); + return ret; +} + +static PyObject * +tsdate_mutational_timescale(PyObject *Py_UNUSED(self), PyObject *args, PyObject *kwds) +{ + PyObject *ret = NULL; + static char *kwlist[] = { "nodes_time", "edges_likelihood", "nodes_fixed", + "edges_parent", "edges_child", "max_intervals", NULL }; + PyObject *nodes_time_obj = NULL; + PyObject *edges_likelihood_obj = NULL; + PyObject *nodes_fixed_obj = NULL; + PyObject *edges_parent_obj = NULL; + PyObject *edges_child_obj = NULL; + PyArrayObject *nodes_time = NULL; + PyArrayObject *edges_likelihood = NULL; + PyArrayObject *nodes_fixed = NULL; + PyArrayObject *edges_parent = NULL; + PyArrayObject *edges_child = NULL; + PyArrayObject *origin = NULL; + PyArrayObject *adjust = NULL; + double *origin_data = NULL; + double *adjust_data = NULL; + long long max_intervals; + tsd_size_t num_edges, num_breaks = 0; + npy_intp dims[1]; + int err; + + if (!PyArg_ParseTupleAndKeywords(args, kwds, "OOOOOL", kwlist, &nodes_time_obj, + &edges_likelihood_obj, &nodes_fixed_obj, &edges_parent_obj, &edges_child_obj, + &max_intervals)) { + goto out; + } + nodes_time = (PyArrayObject *) PyArray_FROMANY( + nodes_time_obj, NPY_FLOAT64, 1, 1, NPY_ARRAY_IN_ARRAY); + if (nodes_time == NULL) { + goto out; + } + edges_likelihood = (PyArrayObject *) PyArray_FROMANY( + edges_likelihood_obj, NPY_FLOAT64, 2, 2, NPY_ARRAY_IN_ARRAY); + if (edges_likelihood == NULL) { + goto out; + } + nodes_fixed = (PyArrayObject *) PyArray_FROMANY( + nodes_fixed_obj, NPY_BOOL, 1, 1, NPY_ARRAY_IN_ARRAY); + if (nodes_fixed == NULL) { + goto out; + } + edges_parent = (PyArrayObject *) PyArray_FROMANY( + edges_parent_obj, NPY_INT32, 1, 1, NPY_ARRAY_IN_ARRAY); + if (edges_parent == NULL) { + goto out; + } + edges_child = (PyArrayObject *) PyArray_FROMANY( + edges_child_obj, NPY_INT32, 1, 1, NPY_ARRAY_IN_ARRAY); + if (edges_child == NULL) { + goto out; + } + num_edges = ARRAY_LEN(edges_parent); + if (ARRAY_LEN(edges_child) != num_edges) { + PyErr_SetString(PyExc_ValueError, "Edge arrays must have the same size"); + goto out; + } + if (ARRAY_LEN(edges_likelihood) != num_edges + || PyArray_DIM(edges_likelihood, 1) != 2) { + PyErr_SetString( + PyExc_ValueError, "Likelihoods must have one row of two columns per edge"); + goto out; + } + if (ARRAY_LEN(nodes_fixed) != ARRAY_LEN(nodes_time)) { + PyErr_SetString( + PyExc_ValueError, "nodes_fixed and nodes_time must have the same size"); + goto out; + } + Py_BEGIN_ALLOW_THREADS + err = tsd_mutational_timescale(ARRAY_LEN(nodes_time), DOUBLES(nodes_time), num_edges, + DOUBLES(edges_likelihood), IDS(edges_parent), IDS(edges_child), + (int64_t) max_intervals, &num_breaks, &origin_data, &adjust_data); + Py_END_ALLOW_THREADS + if (err != 0) { + handle_library_error(err); + goto out; + } + dims[0] = (npy_intp) num_breaks; + origin = new_array_from_data(NPY_FLOAT64, 1, dims, origin_data); + if (origin == NULL) { + goto out; + } + adjust = new_array_from_data(NPY_FLOAT64, 1, dims, adjust_data); + if (adjust == NULL) { + goto out; + } + ret = Py_BuildValue("OO", origin, adjust); +out: + tsd_safe_free(origin_data); + tsd_safe_free(adjust_data); + Py_XDECREF(nodes_time); + Py_XDECREF(edges_likelihood); + Py_XDECREF(nodes_fixed); + Py_XDECREF(edges_parent); + Py_XDECREF(edges_child); + Py_XDECREF(origin); + Py_XDECREF(adjust); + return ret; +} + +static PyObject * +tsdate_piecewise_scale_point_estimate( + PyObject *Py_UNUSED(self), PyObject *args, PyObject *kwds) +{ + PyObject *ret = NULL; + static char *kwlist[] = { "point_estimate", "point_fixed", "original_breaks", + "rescaled_breaks", NULL }; + PyObject *point_estimate_obj = NULL; + PyObject *point_fixed_obj = NULL; + PyObject *original_breaks_obj = NULL; + PyObject *rescaled_breaks_obj = NULL; + PyArrayObject *point_estimate = NULL; + PyArrayObject *point_fixed = NULL; + PyArrayObject *original_breaks = NULL; + PyArrayObject *rescaled_breaks = NULL; + PyArrayObject *rescaled = NULL; + tsd_size_t num_points, num_breaks; + npy_intp dims[1]; + int err; + + if (!PyArg_ParseTupleAndKeywords(args, kwds, "OOOO", kwlist, &point_estimate_obj, + &point_fixed_obj, &original_breaks_obj, &rescaled_breaks_obj)) { + goto out; + } + point_estimate = (PyArrayObject *) PyArray_FROMANY( + point_estimate_obj, NPY_FLOAT64, 1, 1, NPY_ARRAY_IN_ARRAY); + if (point_estimate == NULL) { + goto out; + } + point_fixed = (PyArrayObject *) PyArray_FROMANY( + point_fixed_obj, NPY_BOOL, 1, 1, NPY_ARRAY_IN_ARRAY); + if (point_fixed == NULL) { + goto out; + } + original_breaks = (PyArrayObject *) PyArray_FROMANY( + original_breaks_obj, NPY_FLOAT64, 1, 1, NPY_ARRAY_IN_ARRAY); + if (original_breaks == NULL) { + goto out; + } + rescaled_breaks = (PyArrayObject *) PyArray_FROMANY( + rescaled_breaks_obj, NPY_FLOAT64, 1, 1, NPY_ARRAY_IN_ARRAY); + if (rescaled_breaks == NULL) { + goto out; + } + num_points = ARRAY_LEN(point_estimate); + num_breaks = ARRAY_LEN(original_breaks); + if (ARRAY_LEN(point_fixed) != num_points) { + PyErr_SetString( + PyExc_ValueError, "point_fixed and point_estimate must have the same size"); + goto out; + } + if (ARRAY_LEN(rescaled_breaks) != num_breaks) { + PyErr_SetString(PyExc_ValueError, "Breakpoints must be of the same size"); + goto out; + } + dims[0] = (npy_intp) num_points; + rescaled = (PyArrayObject *) PyArray_SimpleNew(1, dims, NPY_FLOAT64); + if (rescaled == NULL) { + goto out; + } + Py_BEGIN_ALLOW_THREADS + err = tsd_piecewise_scale_point_estimate(num_points, DOUBLES(point_estimate), + FLAGS(point_fixed), num_breaks, DOUBLES(original_breaks), + DOUBLES(rescaled_breaks), DOUBLES(rescaled)); + Py_END_ALLOW_THREADS + if (err != 0) { + handle_library_error(err); + goto out; + } + ret = (PyObject *) rescaled; + rescaled = NULL; +out: + Py_XDECREF(point_estimate); + Py_XDECREF(point_fixed); + Py_XDECREF(original_breaks); + Py_XDECREF(rescaled_breaks); + Py_XDECREF(rescaled); + return ret; +} + +static PyObject * +tsdate_piecewise_scale_posterior( + PyObject *Py_UNUSED(self), PyObject *args, PyObject *kwds) +{ + PyObject *ret = NULL; + static char *kwlist[] = { "posteriors", "posteriors_fixed", "original_breaks", + "rescaled_breaks", "quantile_width", "max_shape", NULL }; + PyObject *posteriors_obj = NULL; + PyObject *posteriors_fixed_obj = NULL; + PyObject *original_breaks_obj = NULL; + PyObject *rescaled_breaks_obj = NULL; + PyArrayObject *posteriors = NULL; + PyArrayObject *posteriors_fixed = NULL; + PyArrayObject *original_breaks = NULL; + PyArrayObject *rescaled_breaks = NULL; + PyArrayObject *new_posteriors = NULL; + double quantile_width, max_shape; + tsd_size_t num_posteriors, num_breaks; + npy_intp dims[2]; + int err; + + if (!PyArg_ParseTupleAndKeywords(args, kwds, "OOOOdd", kwlist, &posteriors_obj, + &posteriors_fixed_obj, &original_breaks_obj, &rescaled_breaks_obj, + &quantile_width, &max_shape)) { + goto out; + } + posteriors = (PyArrayObject *) PyArray_FROMANY( + posteriors_obj, NPY_FLOAT64, 2, 2, NPY_ARRAY_IN_ARRAY); + if (posteriors == NULL) { + goto out; + } + posteriors_fixed = (PyArrayObject *) PyArray_FROMANY( + posteriors_fixed_obj, NPY_BOOL, 1, 1, NPY_ARRAY_IN_ARRAY); + if (posteriors_fixed == NULL) { + goto out; + } + original_breaks = (PyArrayObject *) PyArray_FROMANY( + original_breaks_obj, NPY_FLOAT64, 1, 1, NPY_ARRAY_IN_ARRAY); + if (original_breaks == NULL) { + goto out; + } + rescaled_breaks = (PyArrayObject *) PyArray_FROMANY( + rescaled_breaks_obj, NPY_FLOAT64, 1, 1, NPY_ARRAY_IN_ARRAY); + if (rescaled_breaks == NULL) { + goto out; + } + num_posteriors = ARRAY_LEN(posteriors); + num_breaks = ARRAY_LEN(original_breaks); + if (PyArray_DIM(posteriors, 1) != 2 + || ARRAY_LEN(posteriors_fixed) != num_posteriors) { + PyErr_SetString(PyExc_ValueError, + "Posteriors must have two columns and one row per fixed flag"); + goto out; + } + if (ARRAY_LEN(rescaled_breaks) != num_breaks) { + PyErr_SetString(PyExc_ValueError, "Breakpoints must be of the same size"); + goto out; + } + dims[0] = (npy_intp) num_posteriors; + dims[1] = 2; + new_posteriors = (PyArrayObject *) PyArray_SimpleNew(2, dims, NPY_FLOAT64); + if (new_posteriors == NULL) { + goto out; + } + Py_BEGIN_ALLOW_THREADS + err = tsd_piecewise_scale_posterior(num_posteriors, DOUBLES(posteriors), + FLAGS(posteriors_fixed), num_breaks, DOUBLES(original_breaks), + DOUBLES(rescaled_breaks), quantile_width, max_shape, DOUBLES(new_posteriors)); + Py_END_ALLOW_THREADS + if (err != 0) { + handle_library_error(err); + goto out; + } + ret = (PyObject *) new_posteriors; + new_posteriors = NULL; +out: + Py_XDECREF(posteriors); + Py_XDECREF(posteriors_fixed); + Py_XDECREF(original_breaks); + Py_XDECREF(rescaled_breaks); + Py_XDECREF(new_posteriors); + return ret; +} + +static PyObject * +tsdate_constraints_are_consistent( + PyObject *Py_UNUSED(self), PyObject *args, PyObject *kwds) +{ + PyObject *ret = NULL; + static char *kwlist[] = { "constraints", "edges_parent", "edges_child", NULL }; + PyObject *constraints_obj = NULL; + PyObject *edges_parent_obj = NULL; + PyObject *edges_child_obj = NULL; + PyArrayObject *constraints = NULL; + PyArrayObject *edges_parent = NULL; + PyArrayObject *edges_child = NULL; + tsd_size_t num_edges; + int consistent = 0; + int err; + + if (!PyArg_ParseTupleAndKeywords(args, kwds, "OOO", kwlist, &constraints_obj, + &edges_parent_obj, &edges_child_obj)) { + goto out; + } + constraints = (PyArrayObject *) PyArray_FROMANY( + constraints_obj, NPY_FLOAT64, 2, 2, NPY_ARRAY_IN_ARRAY); + if (constraints == NULL) { + goto out; + } + edges_parent = (PyArrayObject *) PyArray_FROMANY( + edges_parent_obj, NPY_INT32, 1, 1, NPY_ARRAY_IN_ARRAY); + if (edges_parent == NULL) { + goto out; + } + edges_child = (PyArrayObject *) PyArray_FROMANY( + edges_child_obj, NPY_INT32, 1, 1, NPY_ARRAY_IN_ARRAY); + if (edges_child == NULL) { + goto out; + } + num_edges = ARRAY_LEN(edges_parent); + if (PyArray_DIM(constraints, 1) != 2) { + PyErr_SetString(PyExc_ValueError, "constraints must have two columns"); + goto out; + } + if (ARRAY_LEN(edges_child) != num_edges) { + PyErr_SetString(PyExc_ValueError, "Edge arrays must have the same size"); + goto out; + } + Py_BEGIN_ALLOW_THREADS + err = tsd_constraints_are_consistent(ARRAY_LEN(constraints), num_edges, + DOUBLES(constraints), IDS(edges_parent), IDS(edges_child), &consistent); + Py_END_ALLOW_THREADS + if (err != 0) { + handle_library_error(err); + goto out; + } + ret = PyBool_FromLong(consistent); +out: + Py_XDECREF(constraints); + Py_XDECREF(edges_parent); + Py_XDECREF(edges_child); + return ret; +} + +/*=================================================================== + * ExpectationPropagation + *=================================================================== + */ + +typedef struct { + PyObject_HEAD + tsd_ep_t *ep; +} ExpectationPropagation; + +static int +ExpectationPropagation_check_state(ExpectationPropagation *self) +{ + int ret = 0; + + if (self->ep == NULL) { + PyErr_SetString(PyExc_SystemError, "ExpectationPropagation not initialised"); + ret = -1; + } + return ret; +} + +static void +ExpectationPropagation_dealloc(ExpectationPropagation *self) +{ + if (self->ep != NULL) { + tsd_ep_free(self->ep); + PyMem_Free(self->ep); + self->ep = NULL; + } + Py_TYPE(self)->tp_free((PyObject *) self); +} + +static int +ExpectationPropagation_init(ExpectationPropagation *self, PyObject *args, PyObject *kwds) +{ + int ret = -1; + static char *kwlist[] = { "constraints", "edges_parent", "edges_child", + "edges_likelihood", "blocks_left", "blocks_right", "blocks_likelihood", NULL }; + PyObject *constraints_obj = NULL; + PyObject *edges_parent_obj = NULL; + PyObject *edges_child_obj = NULL; + PyObject *edges_likelihood_obj = NULL; + PyObject *blocks_left_obj = NULL; + PyObject *blocks_right_obj = NULL; + PyObject *blocks_likelihood_obj = NULL; + PyArrayObject *constraints = NULL; + PyArrayObject *edges_parent = NULL; + PyArrayObject *edges_child = NULL; + PyArrayObject *edges_likelihood = NULL; + PyArrayObject *blocks_left = NULL; + PyArrayObject *blocks_right = NULL; + PyArrayObject *blocks_likelihood = NULL; + tsd_size_t num_edges, num_blocks; + int err; + + if (self->ep != NULL) { + tsd_ep_free(self->ep); + PyMem_Free(self->ep); + self->ep = NULL; + } + if (!PyArg_ParseTupleAndKeywords(args, kwds, "OOOOOOO", kwlist, &constraints_obj, + &edges_parent_obj, &edges_child_obj, &edges_likelihood_obj, &blocks_left_obj, + &blocks_right_obj, &blocks_likelihood_obj)) { + goto out; + } + constraints = (PyArrayObject *) PyArray_FROMANY( + constraints_obj, NPY_FLOAT64, 2, 2, NPY_ARRAY_IN_ARRAY); + if (constraints == NULL) { + goto out; + } + edges_parent = (PyArrayObject *) PyArray_FROMANY( + edges_parent_obj, NPY_INT32, 1, 1, NPY_ARRAY_IN_ARRAY); + if (edges_parent == NULL) { + goto out; + } + edges_child = (PyArrayObject *) PyArray_FROMANY( + edges_child_obj, NPY_INT32, 1, 1, NPY_ARRAY_IN_ARRAY); + if (edges_child == NULL) { + goto out; + } + edges_likelihood = (PyArrayObject *) PyArray_FROMANY( + edges_likelihood_obj, NPY_FLOAT64, 2, 2, NPY_ARRAY_IN_ARRAY); + if (edges_likelihood == NULL) { + goto out; + } + blocks_left = (PyArrayObject *) PyArray_FROMANY( + blocks_left_obj, NPY_INT32, 1, 1, NPY_ARRAY_IN_ARRAY); + if (blocks_left == NULL) { + goto out; + } + blocks_right = (PyArrayObject *) PyArray_FROMANY( + blocks_right_obj, NPY_INT32, 1, 1, NPY_ARRAY_IN_ARRAY); + if (blocks_right == NULL) { + goto out; + } + blocks_likelihood = (PyArrayObject *) PyArray_FROMANY( + blocks_likelihood_obj, NPY_FLOAT64, 2, 2, NPY_ARRAY_IN_ARRAY); + if (blocks_likelihood == NULL) { + goto out; + } + num_edges = ARRAY_LEN(edges_parent); + num_blocks = ARRAY_LEN(blocks_left); + if (PyArray_DIM(constraints, 1) != 2 || PyArray_DIM(edges_likelihood, 1) != 2 + || PyArray_DIM(blocks_likelihood, 1) != 2) { + PyErr_SetString(PyExc_ValueError, + "constraints, edges_likelihood and blocks_likelihood must have two columns"); + goto out; + } + if (ARRAY_LEN(edges_child) != num_edges + || ARRAY_LEN(edges_likelihood) != num_edges) { + PyErr_SetString(PyExc_ValueError, "Edge arrays must have the same size"); + goto out; + } + if (ARRAY_LEN(blocks_right) != num_blocks + || ARRAY_LEN(blocks_likelihood) != num_blocks) { + PyErr_SetString(PyExc_ValueError, "Block arrays must have the same size"); + goto out; + } + self->ep = PyMem_Malloc(sizeof(*self->ep)); + if (self->ep == NULL) { + PyErr_NoMemory(); + goto out; + } + err = tsd_ep_init(self->ep, ARRAY_LEN(constraints), num_edges, num_blocks, + DOUBLES(constraints), IDS(edges_parent), IDS(edges_child), + DOUBLES(edges_likelihood), IDS(blocks_left), IDS(blocks_right), + DOUBLES(blocks_likelihood)); + if (err != 0) { + handle_library_error(err); + tsd_ep_free(self->ep); + PyMem_Free(self->ep); + self->ep = NULL; + goto out; + } + ret = 0; +out: + Py_XDECREF(constraints); + Py_XDECREF(edges_parent); + Py_XDECREF(edges_child); + Py_XDECREF(edges_likelihood); + Py_XDECREF(blocks_left); + Py_XDECREF(blocks_right); + Py_XDECREF(blocks_likelihood); + return ret; +} + +static PyObject * +ExpectationPropagation_propagate_likelihood( + ExpectationPropagation *self, PyObject *args, PyObject *kwds) +{ + PyObject *ret = NULL; + static char *kwlist[] = { "order", "unphased", "max_shape", "min_step", NULL }; + PyObject *order_obj = NULL; + PyArrayObject *order = NULL; + int unphased; + double max_shape, min_step; + int err; + + if (ExpectationPropagation_check_state(self) != 0) { + goto out; + } + if (!PyArg_ParseTupleAndKeywords( + args, kwds, "Opdd", kwlist, &order_obj, &unphased, &max_shape, &min_step)) { + goto out; + } + order = (PyArrayObject *) PyArray_FROMANY( + order_obj, NPY_INT32, 1, 1, NPY_ARRAY_IN_ARRAY); + if (order == NULL) { + goto out; + } + Py_BEGIN_ALLOW_THREADS + err = tsd_ep_propagate_likelihood( + self->ep, ARRAY_LEN(order), IDS(order), unphased, max_shape, min_step); + Py_END_ALLOW_THREADS + if (err != 0) { + handle_library_error(err); + goto out; + } + ret = Py_BuildValue(""); +out: + Py_XDECREF(order); + return ret; +} + +static PyObject * +ExpectationPropagation_propagate_prior( + ExpectationPropagation *self, PyObject *args, PyObject *kwds) +{ + PyObject *ret = NULL; + static char *kwlist[] = { "free", "max_shape", "em_maxitt", "em_reltol", NULL }; + PyObject *free_obj = NULL; + PyArrayObject *free = NULL; + double max_shape, em_reltol; + long long em_maxitt; + int err; + + if (ExpectationPropagation_check_state(self) != 0) { + goto out; + } + if (!PyArg_ParseTupleAndKeywords( + args, kwds, "OdLd", kwlist, &free_obj, &max_shape, &em_maxitt, &em_reltol)) { + goto out; + } + free = (PyArrayObject *) PyArray_FROMANY( + free_obj, NPY_BOOL, 1, 1, NPY_ARRAY_IN_ARRAY); + if (free == NULL) { + goto out; + } + if (ARRAY_LEN(free) != self->ep->num_nodes) { + PyErr_SetString(PyExc_ValueError, "free must have one entry per node"); + goto out; + } + Py_BEGIN_ALLOW_THREADS + err = tsd_ep_propagate_prior( + self->ep, FLAGS(free), max_shape, (int64_t) em_maxitt, em_reltol); + Py_END_ALLOW_THREADS + if (err != 0) { + handle_library_error(err); + goto out; + } + ret = Py_BuildValue(""); +out: + Py_XDECREF(free); + return ret; +} + +static PyObject * +ExpectationPropagation_propagate_mutations( + ExpectationPropagation *self, PyObject *args, PyObject *kwds) +{ + PyObject *ret = NULL; + static char *kwlist[] = { "mutations_edge", "unphased", NULL }; + PyObject *mutations_edge_obj = NULL; + PyArrayObject *mutations_edge = NULL; + PyArrayObject *mutations_posterior = NULL; + PyArrayObject *mutations_phase = NULL; + int unphased; + npy_intp dims[2]; + int err; + + if (ExpectationPropagation_check_state(self) != 0) { + goto out; + } + if (!PyArg_ParseTupleAndKeywords( + args, kwds, "Op", kwlist, &mutations_edge_obj, &unphased)) { + goto out; + } + mutations_edge = (PyArrayObject *) PyArray_FROMANY( + mutations_edge_obj, NPY_INT32, 1, 1, NPY_ARRAY_IN_ARRAY); + if (mutations_edge == NULL) { + goto out; + } + dims[0] = PyArray_DIM(mutations_edge, 0); + dims[1] = 2; + mutations_posterior = (PyArrayObject *) PyArray_SimpleNew(2, dims, NPY_FLOAT64); + if (mutations_posterior == NULL) { + goto out; + } + mutations_phase = (PyArrayObject *) PyArray_SimpleNew(1, dims, NPY_FLOAT64); + if (mutations_phase == NULL) { + goto out; + } + Py_BEGIN_ALLOW_THREADS + err = tsd_ep_propagate_mutations(self->ep, ARRAY_LEN(mutations_edge), + IDS(mutations_edge), unphased, DOUBLES(mutations_posterior), + DOUBLES(mutations_phase)); + Py_END_ALLOW_THREADS + if (err != 0) { + handle_library_error(err); + goto out; + } + ret = Py_BuildValue("OO", mutations_posterior, mutations_phase); +out: + Py_XDECREF(mutations_edge); + Py_XDECREF(mutations_posterior); + Py_XDECREF(mutations_phase); + return ret; +} + +static PyObject * +ExpectationPropagation_rescale_factors( + ExpectationPropagation *self, PyObject *Py_UNUSED(args)) +{ + PyObject *ret = NULL; + + if (ExpectationPropagation_check_state(self) != 0) { + goto out; + } + tsd_ep_rescale_factors(self->ep); + ret = Py_BuildValue(""); +out: + return ret; +} + +static PyObject * +ExpectationPropagation_assemble_factors( + ExpectationPropagation *self, PyObject *Py_UNUSED(args)) +{ + PyObject *ret = NULL; + PyArrayObject *posterior = NULL; + npy_intp dims[2]; + + if (ExpectationPropagation_check_state(self) != 0) { + goto out; + } + dims[0] = (npy_intp) self->ep->num_nodes; + dims[1] = 2; + posterior = (PyArrayObject *) PyArray_SimpleNew(2, dims, NPY_FLOAT64); + if (posterior == NULL) { + goto out; + } + tsd_ep_assemble_factors(self->ep, DOUBLES(posterior)); + ret = (PyObject *) posterior; + posterior = NULL; +out: + Py_XDECREF(posterior); + return ret; +} + +static PyObject * +ExpectationPropagation_get_posterior( + ExpectationPropagation *self, void *Py_UNUSED(closure)) +{ + PyObject *ret = NULL; + npy_intp dims[2]; + + if (ExpectationPropagation_check_state(self) != 0) { + goto out; + } + dims[0] = (npy_intp) self->ep->num_nodes; + dims[1] = 2; + ret = (PyObject *) new_array_from_data(NPY_FLOAT64, 2, dims, self->ep->posterior); +out: + return ret; +} + +static PyObject * +ExpectationPropagation_get_edges_lognorm( + ExpectationPropagation *self, void *Py_UNUSED(closure)) +{ + PyObject *ret = NULL; + npy_intp dims[1]; + + if (ExpectationPropagation_check_state(self) != 0) { + goto out; + } + dims[0] = (npy_intp) self->ep->num_edges; + ret = (PyObject *) new_array_from_data( + NPY_FLOAT64, 1, dims, self->ep->edges_lognorm); +out: + return ret; +} + +static PyObject * +ExpectationPropagation_get_blocks_lognorm( + ExpectationPropagation *self, void *Py_UNUSED(closure)) +{ + PyObject *ret = NULL; + npy_intp dims[1]; + + if (ExpectationPropagation_check_state(self) != 0) { + goto out; + } + dims[0] = (npy_intp) self->ep->num_blocks; + ret = (PyObject *) new_array_from_data( + NPY_FLOAT64, 1, dims, self->ep->blocks_lognorm); +out: + return ret; +} + +static PyMethodDef ExpectationPropagation_methods[] = { + { "propagate_likelihood", + (PyCFunction) (void (*)(void)) ExpectationPropagation_propagate_likelihood, + METH_VARARGS | METH_KEYWORDS, + "Update the factors of the edges (blocks, if unphased) in the given order." }, + { "propagate_prior", + (PyCFunction) (void (*)(void)) ExpectationPropagation_propagate_prior, + METH_VARARGS | METH_KEYWORDS, + "Fit an exponential prior to the free nodes and update their factors." }, + { "propagate_mutations", + (PyCFunction) (void (*)(void)) ExpectationPropagation_propagate_mutations, + METH_VARARGS | METH_KEYWORDS, + "The posteriors and phases of mutations above the given edges (blocks)." }, + { "rescale_factors", (PyCFunction) ExpectationPropagation_rescale_factors, + METH_NOARGS, "Multiply the factors by the scales of their nodes." }, + { "assemble_factors", (PyCFunction) ExpectationPropagation_assemble_factors, + METH_NOARGS, "The posteriors implied by the factors." }, + { NULL } /* Sentinel */ +}; + +static PyGetSetDef ExpectationPropagation_getsetters[] = { + { "posterior", (getter) ExpectationPropagation_get_posterior, NULL, + "A copy of the posteriors of the nodes (natural parameters).", NULL }, + { "edges_lognorm", (getter) ExpectationPropagation_get_edges_lognorm, NULL, + "A copy of the log normalising constants of the edges.", NULL }, + { "blocks_lognorm", (getter) ExpectationPropagation_get_blocks_lognorm, NULL, + "A copy of the log normalising constants of the blocks.", NULL }, + { NULL } /* Sentinel */ +}; + +static PyTypeObject ExpectationPropagationType = { + // clang-format off + PyVarObject_HEAD_INIT(NULL, 0) + .tp_name = "_tsdate.ExpectationPropagation", + // clang-format on + .tp_basicsize = sizeof(ExpectationPropagation), + .tp_dealloc = (destructor) ExpectationPropagation_dealloc, + .tp_flags = Py_TPFLAGS_DEFAULT, + .tp_doc = "The state of expectation propagation.", + .tp_methods = ExpectationPropagation_methods, + .tp_getset = ExpectationPropagation_getsetters, + .tp_init = (initproc) ExpectationPropagation_init, + .tp_new = PyType_GenericNew, +}; + static PyMethodDef tsdate_methods[] = { { "strerror", (PyCFunction) tsdate_strerror, METH_VARARGS, "Return the message for a library error code." }, { "raise_library_error", (PyCFunction) tsdate_raise_library_error, METH_VARARGS, "Raise the Python exception corresponding to a library error code." }, + { "block_singletons", (PyCFunction) (void (*)(void)) tsdate_block_singletons, + METH_VARARGS | METH_KEYWORDS, + "Group the singletons of unphased individuals into blocks." }, + { "reallocate_unphased", (PyCFunction) (void (*)(void)) tsdate_reallocate_unphased, + METH_VARARGS | METH_KEYWORDS, + "The edge likelihoods with those of unphased blocks reallocated by phase." }, + { "mutation_frequency", (PyCFunction) (void (*)(void)) tsdate_mutation_frequency, + METH_VARARGS | METH_KEYWORDS, + "The number of members of each sample set below each mutation." }, + { "split_disjoint_nodes", (PyCFunction) (void (*)(void)) tsdate_split_disjoint_nodes, + METH_VARARGS | METH_KEYWORDS, + "Split disconnected regions of nodes into separate nodes." }, + { "relabel_mutations_node", + (PyCFunction) (void (*)(void)) tsdate_relabel_mutations_node, + METH_VARARGS | METH_KEYWORDS, + "The new node of each mutation, after splitting nodes." }, + { "constrain_ages", (PyCFunction) (void (*)(void)) tsdate_constrain_ages, + METH_VARARGS | METH_KEYWORDS, + "Constrain node ages to be consistent with the edges." }, + { "contains_unary_nodes", (PyCFunction) (void (*)(void)) tsdate_contains_unary_nodes, + METH_VARARGS | METH_KEYWORDS, + "Whether any unmasked node has a single child in some tree." }, + { "conditional_coalescent_variance", + (PyCFunction) (void (*)(void)) tsdate_conditional_coalescent_variance, + METH_VARARGS | METH_KEYWORDS, + "Variance of node age given the number of descendant leaves." }, + { "count_mutations", (PyCFunction) (void (*)(void)) tsdate_count_mutations, + METH_VARARGS | METH_KEYWORDS, + "Mutation counts and spans per edge, and the edge of each mutation." }, + { "mutational_area", (PyCFunction) (void (*)(void)) tsdate_mutational_area, + METH_VARARGS | METH_KEYWORDS, + "Mutation counts and area per inter-node interval." }, + { "mutational_timescale", (PyCFunction) (void (*)(void)) tsdate_mutational_timescale, + METH_VARARGS | METH_KEYWORDS, + "Breakpoints for rescaling time so that the mutation rate is constant." }, + { "piecewise_scale_point_estimate", + (PyCFunction) (void (*)(void)) tsdate_piecewise_scale_point_estimate, + METH_VARARGS | METH_KEYWORDS, "Rescale point estimates of node ages." }, + { "piecewise_scale_posterior", + (PyCFunction) (void (*)(void)) tsdate_piecewise_scale_posterior, + METH_VARARGS | METH_KEYWORDS, "Rescale gamma posteriors of node ages." }, + { "constraints_are_consistent", + (PyCFunction) (void (*)(void)) tsdate_constraints_are_consistent, + METH_VARARGS | METH_KEYWORDS, + "Whether node age constraints are consistent with the edges." }, { NULL } /* Sentinel */ }; @@ -100,5 +1924,18 @@ PyInit__tsdate(void) Py_INCREF(TsdLibraryError); PyModule_AddObject(module, "LibraryError", TsdLibraryError); + if (PyType_Ready(&ExpectationPropagationType) < 0) { + Py_DECREF(module); + return NULL; + } + Py_INCREF(&ExpectationPropagationType); + if (PyModule_AddObject( + module, "ExpectationPropagation", (PyObject *) &ExpectationPropagationType) + != 0) { + Py_DECREF(&ExpectationPropagationType); + Py_DECREF(module); + return NULL; + } + return module; } diff --git a/docs/installation.md b/docs/installation.md index 816b1a84..ad2416f7 100644 --- a/docs/installation.md +++ b/docs/installation.md @@ -49,14 +49,3 @@ Install development dependencies with `uv sync` and run the tests with: `uv sync` also (re)builds the C extension. After editing C code, run `uv sync` (or `make`) again to rebuild it. - -_Tsdate_ makes extensive use of [numba](https://numba.pydata.org)'s -"just in time" (jit) compilation to speed up time-consuming numerical functions. -Because of the need to compile these functions, loading the tsdate package can take -tens of seconds. To speed up loading time, you can set the environment variable - - TSDATE_ENABLE_NUMBA_CACHE=1 - -The compiled code is not cached by default as it can be problematic when -e.g. running the same installation on different CPU types in a cluster, -and can occassionally lead to unexpected crashes. diff --git a/docs/usage.md b/docs/usage.md index 26d6809c..dee196dd 100644 --- a/docs/usage.md +++ b/docs/usage.md @@ -320,12 +320,6 @@ As the time taken to date a tree sequence using _tsdate_ is only a fraction of t required to infer the initial tree sequence, the core _tsdate_ algorithm has not been parallelised to allow running on many CPU cores. -:::{note} -Extensive use of just-in-time compilation via [numba](https://numba.pydata.org) -means that it can take tens of seconds to load the _tsdate_ module into python. -See {ref}`here ` for a workaround if this is causing you problems. -::: - ## CLI use Computationally-intensive uses of _tsdate_ are likely to involve diff --git a/evaluation/README.md b/evaluation/README.md index 461834a9..1880a725 100644 --- a/evaluation/README.md +++ b/evaluation/README.md @@ -15,6 +15,9 @@ standard coalescent. | `accuracy.py` | Sweep a parameter (`sample_size`, `length`, `mutation_rate`, `max_iterations`) for `variational_gamma`, comparing estimated to true node times. `--modes true` dates the true topology; `inferred` dates a tsinfer topology and compares to best-matching true nodes via [tscompare](https://github.com/tskit-dev/tscompare) (see issue #301). Writes one row per node (`accuracy_*.csv`). It also compares mutation times (`mutations_*.csv`): sites with a single mutation are matched by position, and tsdate's posterior mean mutation time is compared with the midpoint of the true edge the mutation sits on (the best any method can do; the exact simulated time is also saved as `true_time_exact`). `plot.py` scores scatter, RMSE and bias against the midpoint but PIT and interval coverage against the exact time, since the posterior is for the realised mutation time; `--mutation-truth midpoint` or `exact` forces one truth everywhere. Mutation comparison needs no node matching in either mode. | | `afs.py` | Compare the observed site allele frequency spectrum with the expected one from branch lengths (branch AFS x mutation rate) in genomic windows, for the true times, the true topology dated by tsdate, and a tsinfer topology dated by tsdate. Writes `afs_*.csv`. | | `performance.py` | Wall time and peak RSS, each case in a fresh process. | +| `microbench.py` | Microbenchmarks of the functions of `_tsdate` (EP passes, rescaling, phasing, `util`, `prior`), on simulated inputs at three sizes (see below). | +| `numerical_accuracy.py` | Accuracy of the special functions and gamma approximations (the scalar functions of the C library, through `clib.py`) per function and regime: worst error against mpmath, SciPy or closed forms, and violations of properties such as symmetry, monotonicity and continuity at switch points (see below). Not to be confused with `accuracy.py`, which scores dating. | +| `clib.py` | The scalar functions of the C library, called with ctypes from the shared library that meson builds (see below). | | `compare.py` | Compares two `performance.py` CSVs case by case (see below). | | `plot.py` | Reads `results/*.csv` and writes PNGs: error/bias/interval coverage vs parameter (`accuracy_*_summary.png`: top row node times, bottom row mutation times), estimated-vs-true scatter (`accuracy_*_scatter.png`: columns are swept values, rows are node/mutation times for true/tsinferred topology), PIT calibration histograms (`accuracy_*_calibration.png`: node row, mutation row), AFS observed-vs-expected (`afs_*.png`), time and memory scaling. | | `validation.py` | Stub: numerical checks too slow for the unit tests (issue #384). | @@ -73,3 +76,51 @@ repeats (use 5 or more for a reference run). Add `--quick` to `accuracy.py` / `performance.py` for a fast smoke test. Quick runs write to separate `*_quick.csv` files (so they never overwrite full results), and `plot.py` labels their figures "quick run" and names them `*_quick*.png`. + +### Microbenchmarks of the C extension + +`microbench.py` times each function of the `_tsdate` extension on inputs built from +simulated tree sequences (small/medium/large; the large case has ~560k edges, so the +EP edge pass takes about a second). The EP state is produced by running +`ExpectationPropagation.infer` for two iterations, and the functions are called as +`iterate`/`infer`/`rescale` call them (edges with some nonzero-age samples, and +unphased singleton blocks). The EP passes update their state, so each repeat of a +pass gets a new `_tsdate.ExpectationPropagation`, iterated outside the timed region. +Scalar functions (`approx`, `hypergeo`) are timed only through the EP passes. + +``` +python evaluation/microbench.py --quick # smoke test +python evaluation/microbench.py --repeats 7 --output mb.csv # table + results/mb.csv +python evaluation/microbench.py --sizes medium --only propagate mutational +``` + +Each function is warmed up, then the median of `--repeats` timed calls is reported +(fast calls are batched so each timed block lasts a few ms; times are per call). +The CSV also records provenance. Timings are only comparable between runs on a quiet +machine. + +### Accuracy of the special functions + +`numerical_accuracy.py` measures the approximation error of the special functions of +the C library (digamma, trigamma, `betaln`, the incomplete gamma derivative and +inverse, and the Laplace approximations to U, 1F1 and 2F1, including the +unity limit of 2F1) and the gamma approximations (moment matching, gamma fits, closed forms of +the moment functions) against mpmath, SciPy and closed forms. It also reports how often +properties that the exact functions have are violated: symmetry, monotonicity, the Kummer +transformation, continuity across a switch point. One row per function and regime gives +the worst error (`rel`, `abs`, `ulp`) or a violation `count`. The unit tests check the +library only at fixed points, so the table is where inaccurate regimes show up. + +The scalar functions are not part of the `_tsdate` module: `clib.py` calls them with +ctypes from the shared library that meson builds, so build it first +(`cd lib && meson setup build && ninja -C build`). `clib.py` names each function as in +C without the `tsd_` prefix; arguments are numbers (a two-element array is given as two +numbers), and the outputs come back as a float or a tuple, for example +`clib.hyp2f1_laplace(1.0, 2.0, 3.0, 0.5)`. Its table of signatures must match +`lib/tsdate.h`. + +``` +python evaluation/numerical_accuracy.py --quick # the computation takes seconds +python evaluation/numerical_accuracy.py --only hyp2f1 gammainc # groups: polygamma betaln gammainc hyperu hyp1f1 hyp2f1 approx +python evaluation/numerical_accuracy.py --output acc.csv # also writes results/acc.csv +``` diff --git a/evaluation/accuracy.py b/evaluation/accuracy.py index ed9a5166..681adfd3 100644 --- a/evaluation/accuracy.py +++ b/evaluation/accuracy.py @@ -188,7 +188,7 @@ def run(args): mut_frames += muts progress.update() else: - # Spawn (not fork) so that numba and tsinfer state is not shared + # Spawn (not fork) so that tsinfer state is not shared ctx = multiprocessing.get_context("spawn") with concurrent.futures.ProcessPoolExecutor(args.cores, mp_context=ctx) as ex: futures = [ex.submit(run_case, args, v, s, prov) for v, s in cases] diff --git a/evaluation/clib.py b/evaluation/clib.py new file mode 100644 index 00000000..d03b5ab1 --- /dev/null +++ b/evaluation/clib.py @@ -0,0 +1,132 @@ +""" +The scalar functions of the C library (``lib/``), called with ctypes from the shared +library that meson builds (``cd lib && meson setup build && ninja -C build``), to +measure their accuracy by hand. They are not part of the ``_tsdate`` module, and the +signatures below must match ``lib/tsdate.h``: a mismatch is not detected and can +crash the interpreter. + +Each function is named as in C without the ``tsd_`` prefix and takes numbers: a +two-element array argument (natural parameters) is given as two numbers. It returns +its outputs as a float, or a tuple of floats with two-element outputs flattened, and +raises ``LibraryError`` for an error code. +""" + +import ctypes +import pathlib + +BUILD = pathlib.Path(__file__).parents[1] / "lib" / "build" + +# Arguments: "d" a double, "p" a two-element array of doubles; outputs: "o" a double, +# "O" a two-element array. Results: "error" (an error code; the outputs are the +# result), "double" or "flag" (the return value is the result; no outputs). +SIGNATURES = { + "digamma": ("d", "o", "error"), + "trigamma": ("d", "o", "error"), + "betaln": ("dd", "", "double"), + "gammainc_der": ("dd", "o", "error"), + "gammaincinv": ("dd", "", "double"), + "hyperu_laplace": ("ddd", "oo", "error"), + "hyp1f1_laplace": ("ddd", "o", "error"), + "hyp2f1_laplace": ("dddd", "o", "error"), + "approximate_log_moments": ("dd", "ooo", "error"), + "approximate_gamma_kl": ("dd", "O", "error"), + "approximate_gamma_mom": ("dd", "O", "error"), + "approximate_gamma_iqr": ("ddddd", "O", "error"), + "valid_moments": ("dd", "", "flag"), + "valid_gamma": ("dd", "", "flag"), + "valid_hyp1f1": ("ddd", "", "flag"), + "valid_hyperu": ("ddd", "", "flag"), + "valid_hyp2f1": ("dddd", "", "flag"), + "moments": ("dddddd", "ooooo", "error"), + "rootward_moments": ("ddddd", "ooo", "error"), + "leafward_moments": ("ddddd", "ooo", "error"), + "unphased_moments": ("dddddd", "ooooo", "error"), + "twin_moments": ("dddd", "ooo", "error"), + "sideways_moments": ("ddddd", "ooo", "error"), + "gamma_projection": ("ppp", "oOO", "error"), + "leafward_projection": ("dpp", "oO", "error"), + "rootward_projection": ("dpp", "oO", "error"), + "unphased_projection": ("ppp", "oOO", "error"), + "twin_projection": ("pp", "oO", "error"), + "sideways_projection": ("dpp", "oO", "error"), + "mutation_moments": ("dddddd", "oo", "error"), + "mutation_rootward_moments": ("ddddd", "oo", "error"), + "mutation_leafward_moments": ("ddddd", "oo", "error"), + "mutation_unphased_moments": ("dddddd", "ooo", "error"), + "mutation_twin_moments": ("dddd", "ooo", "error"), + "mutation_sideways_moments": ("ddddd", "ooo", "error"), + "mutation_edge_moments": ("dd", "oo", "error"), + "mutation_block_moments": ("dd", "ooo", "error"), + "mutation_gamma_projection": ("ppp", "oO", "error"), + "mutation_leafward_projection": ("dpp", "oO", "error"), + "mutation_rootward_projection": ("dpp", "oO", "error"), + "mutation_edge_projection": ("dd", "oO", "error"), + "mutation_unphased_projection": ("ppp", "oO", "error"), + "mutation_twin_projection": ("pp", "oO", "error"), + "mutation_sideways_projection": ("dpp", "oO", "error"), + "mutation_block_projection": ("dd", "oO", "error"), + "damp": ("ppd", "o", "error"), + "rescale": ("pd", "o", "error"), +} + +PAIR = ctypes.c_double * 2 +CTYPES = { + "d": ctypes.c_double, + "p": PAIR, + "o": ctypes.POINTER(ctypes.c_double), + "O": PAIR, +} +RESTYPES = {"error": ctypes.c_int, "double": ctypes.c_double, "flag": ctypes.c_int} + + +class LibraryError(Exception): + pass + + +def _load(): + for name in ["libtsdate.so", "libtsdate.dylib"]: + path = BUILD / name + if path.exists(): + return ctypes.CDLL(str(path)) + raise FileNotFoundError(f"No shared library in {BUILD}: build it with meson") + + +_lib = _load() +_lib.tsd_strerror.argtypes = [ctypes.c_int] +_lib.tsd_strerror.restype = ctypes.c_char_p + + +def _function(name, inputs, outputs, result): + func = getattr(_lib, "tsd_" + name) + func.argtypes = [CTYPES[kind] for kind in inputs + outputs] + func.restype = RESTYPES[result] + num_numbers = inputs.count("d") + 2 * inputs.count("p") + + def call(*numbers): + if len(numbers) != num_numbers: + raise TypeError(f"{name} takes {num_numbers} numbers") + numbers = [float(x) for x in numbers] + args = [] + for kind in inputs: + if kind == "d": + args.append(numbers.pop(0)) + else: + args.append(PAIR(numbers.pop(0), numbers.pop(0))) + outs = [ctypes.c_double() if kind == "o" else PAIR() for kind in outputs] + refs = [ctypes.byref(x) if kind == "o" else x for x, kind in zip(outs, outputs)] + ret = func(*args, *refs) + if result != "error": + return float(ret) + if ret != 0: + raise LibraryError(_lib.tsd_strerror(ret).decode()) + values = [] + for x, kind in zip(outs, outputs): + values.extend([x.value] if kind == "o" else list(x)) + return values[0] if len(values) == 1 else tuple(values) + + call.__name__ = name + return call + + +for _name, _signature in SIGNATURES.items(): + globals()[_name] = _function(_name, *_signature) diff --git a/evaluation/microbench.py b/evaluation/microbench.py new file mode 100644 index 00000000..d6474c35 --- /dev/null +++ b/evaluation/microbench.py @@ -0,0 +1,551 @@ +""" +Microbenchmarks of the functions of the `_tsdate` extension in tsdate. Inputs are built +from simulated tree sequences at several sizes, mirroring how the functions are called +in production. Scalar functions (approx, hypergeo) are not timed on their own: they are +exercised through the EP passes. Writes a table to stdout and, with --output, a CSV to +results/. + +Timing: each function is warmed up (one untimed call), then called `--repeats` times on +identical inputs (a new EP state for each call of an EP pass, made outside the timed +region); the median of `time.perf_counter` is reported. Very fast calls are batched, so +that a timed block lasts at least a few ms (reported times are per call). + +Example: + python evaluation/microbench.py --repeats 7 --output microbench.csv +""" + +import argparse +import dataclasses +import math +import statistics +import time + +import common +import numpy as np +import pandas as pd +import tskit + +# size name -> (diploid individuals, sequence length) +SIZES = { + "small": (20, 1e5), + "medium": (100, 1e6), + "large": (1000, 5e7), +} +QUICK_SIZES = {"small": (10, 1e5)} +MUTATION_RATE = 1e-8 +MIN_BLOCK_S = 5e-3 # batch fast calls until a timed block lasts this long +MAX_BATCH = 1000 + + +# --------------------------------------------------------------------------- +# Inputs +# --------------------------------------------------------------------------- + + +def _with_ancient_samples(ts, fraction=0.1, seed=1): + """ + Give some leaf samples nonzero ages (halfway to their youngest parent), so + that the "fixed child, free parent" branch of the EP passes is exercised. + """ + rng = np.random.default_rng(seed) + tables = ts.dump_tables() + time_ = tables.nodes.time + youngest_parent = np.full(ts.num_nodes, np.inf) + np.minimum.at(youngest_parent, ts.edges_child, ts.nodes_time[ts.edges_parent]) + is_leaf = ~np.isin(np.arange(ts.num_nodes), ts.edges_parent) + candidates = [u for u in ts.samples() if is_leaf[u] and youngest_parent[u] > 1] + chosen = rng.choice(candidates, size=int(fraction * len(candidates)), replace=False) + time_[chosen] = youngest_parent[chosen] / 2 + tables.nodes.time = time_ + tables.mutations.time = np.full(ts.num_mutations, tskit.UNKNOWN_TIME) + return tables.tree_sequence() + + +def _run_ep(ts, singletons_phased, iterations): + from tsdate.variational import ExpectationPropagation + + ep = ExpectationPropagation( + ts, mutation_rate=MUTATION_RATE, singletons_phased=singletons_phased + ) + ep.infer( + ep_iterations=iterations, + max_shape=1000, + rescale_intervals=0, # call the rescaling functions separately + rescale_iterations=0, + regularise=True, + rescale_segsites=False, + ) + return ep + + +def _iterated_state(ep, iterations, max_shape): + """ + A new ``_tsdate.ExpectationPropagation`` with the inputs of `ep` (a + ``tsdate.variational.ExpectationPropagation``), after `iterations` iterations + as in ``ExpectationPropagation.iterate`` + """ + import _tsdate + + from tsdate.variational import ( + LEAFWARD, + ROOTWARD, + USE_BLOCK_LIKELIHOOD, + USE_EDGE_LIKELIHOOD, + ) + + state = _tsdate.ExpectationPropagation( + constraints=ep.node_constraints, + edges_parent=ep.edge_parents, + edges_child=ep.edge_children, + edges_likelihood=ep.edge_likelihoods, + blocks_left=ep.block_nodes[ROOTWARD], + blocks_right=ep.block_nodes[LEAFWARD], + blocks_likelihood=ep.block_likelihoods, + ) + for _ in range(iterations): + for order, unphased in [ + (ep.block_order, USE_BLOCK_LIKELIHOOD), + (ep.edge_order, USE_EDGE_LIKELIHOOD), + ]: + state.propagate_likelihood( + order=order, unphased=unphased, max_shape=max_shape, min_step=0.1 + ) + state.propagate_prior( + free=ep.unconstrained_roots, max_shape=max_shape, em_maxitt=10, em_reltol=1e-8 + ) + state.rescale_factors() + return state + + +@dataclasses.dataclass +class Bench: + """ + One benchmark: `call(**make_kwargs())`, where `make_kwargs()` returns fresh + keyword arguments (with new copies of anything that the call changes). + """ + + name: str + call: callable + make_kwargs: callable + note: str = "" + + +def _const(**kwargs): + return lambda: kwargs + + +def _module_function(name): + import _tsdate + + return getattr(_tsdate, name) + + +def _sweep_kwargs(ts, parents=True): + """ + The edge, index and mutation arrays of `ts` as keyword arguments + """ + kwargs = dict( + mutations_node=ts.mutations_node, + mutations_position=ts.sites_position[ts.mutations_site], + edges_parent=ts.edges_parent, + edges_child=ts.edges_child, + edges_left=ts.edges_left, + edges_right=ts.edges_right, + indexes_insert=ts.indexes_edge_insertion_order, + indexes_remove=ts.indexes_edge_removal_order, + ) + if not parents: + del kwargs["edges_parent"] + return kwargs + + +def build_benchmarks(n, length, iterations): + """ + Build all benchmarks (and a dict describing the inputs) for one size. + """ + from tsdate import rescaling + from tsdate.variational import USE_BLOCK_LIKELIHOOD, USE_EDGE_LIKELIHOOD + + ts_flat = common.simulate(n, length, MUTATION_RATE, seed=1) # contemporary + ts_old = _with_ancient_samples(ts_flat) # some samples with nonzero age + ep_old = _run_ep(ts_old, True, iterations) # edges + ep_flat = _run_ep(ts_flat, False, iterations) # unphased singleton blocks + info = dict( + num_samples=ts_flat.num_samples, + num_nodes=ts_flat.num_nodes, + num_edges=ts_flat.num_edges, + num_mutations=ts_flat.num_mutations, + num_blocks=ep_flat.block_likelihoods.shape[0], + ) + benches = [] + add = benches.append + func = _module_function + + # --- variational.py, as in ExpectationPropagation.iterate/infer --- + # The passes update the state, so each call gets a new state, iterated outside + # the timed region. + max_shape, min_step = 1000, 0.1 + + def propagate_likelihood(state, **kwargs): + state.propagate_likelihood(**kwargs) + + def propagate_prior(state, **kwargs): + state.propagate_prior(**kwargs) + + def propagate_mutations(state, **kwargs): + state.propagate_mutations(**kwargs) + + for tag, ep, order, unphased in [ + ("edges", ep_old, ep_old.edge_order, USE_EDGE_LIKELIHOOD), + ("blocks", ep_flat, ep_flat.block_order, USE_BLOCK_LIKELIHOOD), + ]: + + def likelihood_kwargs(ep=ep, order=order, unphased=unphased): + return dict( + state=_iterated_state(ep, iterations, max_shape), + order=order, + unphased=unphased, + max_shape=max_shape, + min_step=min_step, + ) + + add( + Bench(f"propagate_likelihood[{tag}]", propagate_likelihood, likelihood_kwargs) + ) + + def prior_kwargs(): + return dict( + state=_iterated_state(ep_old, iterations, max_shape), + free=ep_old.unconstrained_roots, + max_shape=max_shape, + em_maxitt=10, + em_reltol=1e-8, + ) + + add(Bench("propagate_prior", propagate_prior, prior_kwargs)) + + # propagate_mutations does not change the state + for tag, ep, unphased in [ + ("edges", ep_old, USE_EDGE_LIKELIHOOD), + ("blocks", ep_flat, USE_BLOCK_LIKELIHOOD), + ]: + blocked = ep.mutation_blocks != tskit.NULL + if unphased: + mutations_edge = ep.mutation_blocks[blocked] + else: + mutations_edge = ep.mutation_edges[~blocked] + add( + Bench( + f"propagate_mutations[{tag}]", + propagate_mutations, + _const(state=ep._ep, mutations_edge=mutations_edge, unphased=unphased), + ) + ) + + # --- phasing.py --- + reallocate_kwargs = dict( + edges_likelihood=ep_flat.sizebiased_likelihoods, + mutations_phase=ep_flat.mutation_phase, + mutations_block=ep_flat.mutation_blocks, + blocks_edges=ep_flat.block_edges, + ) + add( + Bench( + "reallocate_unphased", + func("reallocate_unphased"), + _const(**reallocate_kwargs), + ) + ) + add( + Bench( + "block_singletons", + func("block_singletons"), + _const( + individuals_unphased=np.full(ts_flat.num_individuals, True), + nodes_individual=ts_flat.nodes_individual, + **_sweep_kwargs(ts_flat, parents=False), + sequence_length=ts_flat.sequence_length, + ), + ) + ) + nodes_sample = np.full(ts_flat.num_nodes, False) + nodes_sample[list(ts_flat.samples())] = True + add( + Bench( + "mutation_frequency", + func("mutation_frequency"), + _const( + nodes_sample=nodes_sample[:, np.newaxis], + **_sweep_kwargs(ts_flat), + sequence_length=ts_flat.sequence_length, + ), + ) + ) + + # --- rescaling.py, as in ExpectationPropagation.rescale --- + rescale_lik = func("reallocate_unphased")(**reallocate_kwargs) + nodes_fixed = ep_flat.node_constraints[:, 0] == ep_flat.node_constraints[:, 1] + nodes_time, _ = ep_flat.node_moments() + edges = dict(edges_parent=ep_flat.edge_parents, edges_child=ep_flat.edge_children) + intervals = 1000 + add( + Bench( + "mutational_area", + func("mutational_area"), + _const(nodes_time=nodes_time, edges_likelihood=rescale_lik, **edges), + ) + ) + timescale_kwargs = dict( + nodes_time=nodes_time, + edges_likelihood=rescale_lik, + nodes_fixed=nodes_fixed, + **edges, + max_intervals=intervals, + ) + add( + Bench( + "mutational_timescale", + func("mutational_timescale"), + _const(**timescale_kwargs), + ) + ) + original_breaks, rescaled_breaks = rescaling.mutational_timescale(**timescale_kwargs) + add( + Bench( + "piecewise_scale_point_estimate", + func("piecewise_scale_point_estimate"), + _const( + point_estimate=nodes_time, + point_fixed=nodes_fixed, + original_breaks=original_breaks, + rescaled_breaks=rescaled_breaks, + ), + ) + ) + rescaled_time = rescaling.piecewise_scale_point_estimate( + nodes_time, nodes_fixed, original_breaks, rescaled_breaks + ) + _, unique = np.unique(rescaled_time[~nodes_fixed], return_index=True) + orig = rescaling.piecewise_scale_point_estimate( + rescaled_breaks, + np.full(rescaled_breaks.size, False), + np.append(0, rescaled_time[~nodes_fixed][unique]), + np.append(0, nodes_time[~nodes_fixed][unique]), + ) + add( + Bench( + "piecewise_scale_posterior", + func("piecewise_scale_posterior"), + _const( + posteriors=ep_flat.node_posterior, + posteriors_fixed=nodes_fixed, + original_breaks=orig, + rescaled_breaks=rescaled_breaks, + quantile_width=0.5, + max_shape=max_shape, + ), + ) + ) + add( + Bench( + "count_mutations", + func("count_mutations"), + _const( + nodes_sample=nodes_sample, + **_sweep_kwargs(ts_flat), + sequence_length=ts_flat.sequence_length, + size_biased=True, + ), + ) + ) + + # --- util.py --- + tree = dict( + edges_parent=ts_flat.edges_parent, + edges_child=ts_flat.edges_child, + edges_left=ts_flat.edges_left, + edges_right=ts_flat.edges_right, + ) + split_kwargs = dict(**tree, nodes_excluded=nodes_sample) + add( + Bench( + "split_disjoint_nodes", + func("split_disjoint_nodes"), + _const(**split_kwargs), + ) + ) + new_parent, new_child, nodes_order, split_nodes = func("split_disjoint_nodes")( + **split_kwargs + ) + info["num_split_nodes"] = len(split_nodes) + sweep = _sweep_kwargs(ts_flat) + sweep.update(edges_parent=new_parent, edges_child=new_child) + add( + Bench( + "relabel_mutations_node", + func("relabel_mutations_node"), + _const(nodes_order=nodes_order, **sweep), + ) + ) + rng = np.random.default_rng(1) + noisy_time = ts_flat.nodes_time * np.exp(rng.normal(0, 0.3, ts_flat.num_nodes)) + noisy_time[nodes_sample] = ts_flat.nodes_time[nodes_sample] + add( + Bench( + "constrain_ages", + func("constrain_ages"), + _const( + nodes_time=noisy_time, + nodes_fixed=nodes_sample, + edges_parent=ts_flat.edges_parent, + edges_child=ts_flat.edges_child, + epsilon=1e-6, + max_iterations=20, + ), + note="noisy times violate constraints; 20 iterations", + ) + ) + add( + Bench( + "contains_unary_nodes", + func("contains_unary_nodes"), + _const( + nodes_mask=nodes_sample, + edges_parent=ts_flat.edges_parent, + edges_left=ts_flat.edges_left, + edges_right=ts_flat.edges_right, + indexes_insert=ts_flat.indexes_edge_insertion_order, + indexes_remove=ts_flat.indexes_edge_removal_order, + sequence_length=ts_flat.sequence_length, + ), + ) + ) + + # --- prior.py --- + add( + Bench( + "conditional_coalescent_variance", + func("conditional_coalescent_variance"), + _const(num_tips=ts_flat.num_samples), + ) + ) + + return benches, info + + +# --------------------------------------------------------------------------- +# Timing +# --------------------------------------------------------------------------- + + +def time_bench(bench, repeats): + """ + Warm up, then return per-call times (seconds) for `repeats` timed blocks. + """ + t0 = time.perf_counter() + bench.call(**bench.make_kwargs()) # warm up (also the first-call cost) + first_call = time.perf_counter() - t0 + # estimate the cost of one call to choose a batch size + kwargs = bench.make_kwargs() + t0 = time.perf_counter() + bench.call(**kwargs) + one = time.perf_counter() - t0 + batch = int(min(MAX_BATCH, max(1, math.ceil(MIN_BLOCK_S / max(one, 1e-9))))) + times = [] + for _ in range(repeats): + batch_kwargs = [bench.make_kwargs() for _ in range(batch)] + t0 = time.perf_counter() + for kwargs in batch_kwargs: + bench.call(**kwargs) + times.append((time.perf_counter() - t0) / batch) + return times, first_call, batch + + +def format_table(rows): + cols = ["function", "size", "median_s", "min_s", "max_s", "repeats"] + body = [ + [ + r["function"], + r["size"], + f"{r['median_s']:.3e}", + f"{r['min_s']:.3e}", + f"{r['max_s']:.3e}", + str(r["repeats"]), + ] + for r in rows + ] + widths = [max(len(c), *(len(b[i]) for b in body)) for i, c in enumerate(cols)] + lines = [" ".join(c.ljust(w) for c, w in zip(cols, widths))] + for b in body: + lines.append(" ".join(x.ljust(w) for x, w in zip(b, widths))) + return "\n".join(lines) + + +def main(): + p = argparse.ArgumentParser(description=__doc__.split("\n\n")[0]) + p.add_argument("--sizes", nargs="+", default=list(SIZES), choices=list(SIZES)) + p.add_argument("--repeats", type=int, default=7) + p.add_argument("--ep-iterations", type=int, default=2, help="EP iterations first") + p.add_argument( + "--only", nargs="+", default=None, help="Substrings of benchmark names to run" + ) + p.add_argument( + "--output", + help="Output CSV name in results/ (default: none, print only)", + ) + p.add_argument( + "--quick", + action="store_true", + help="Tiny smoke-test run", + ) + args = p.parse_args() + sizes = {k: SIZES[k] for k in args.sizes} + if args.quick: + sizes, args.repeats, args.ep_iterations = QUICK_SIZES, 1, 1 + + prov = common.provenance() + rows = [] + for size, (n, length) in sizes.items(): + t0 = time.perf_counter() + benches, info = build_benchmarks(n, length, args.ep_iterations) + print( + f"[{size}] n={n} L={length:g}: {info} " + f"(inputs built in {time.perf_counter() - t0:.1f} s)", + flush=True, + ) + for bench in benches: + if args.only and not any(s in bench.name for s in args.only): + continue + times, first, batch = time_bench(bench, args.repeats) + row = dict( + function=bench.name, + size=size, + median_s=statistics.median(times), + min_s=min(times), + max_s=max(times), + repeats=args.repeats, + batch=batch, + first_call_s=first, + sample_size=n, + length=length, + note=bench.note, + **info, + **prov, + ) + rows.append(row) + print( + f" {bench.name:36s} {row['median_s']:.3e} s (x{batch} per block)", + flush=True, + ) + + print() + print(format_table(rows)) + if args.output: + common.RESULTS.mkdir(exist_ok=True) + out = common.RESULTS / args.output + pd.DataFrame(rows).to_csv(out, index=False) + print("wrote", out) + + +if __name__ == "__main__": + main() diff --git a/evaluation/numerical_accuracy.py b/evaluation/numerical_accuracy.py new file mode 100644 index 00000000..c4fb5bf0 --- /dev/null +++ b/evaluation/numerical_accuracy.py @@ -0,0 +1,657 @@ +""" +Numerical accuracy of the special functions and gamma approximations in tsdate (the +scalar functions of the C library, called through ``clib``), per function and regime. +Each row of the table reports the worst error of the production function against a +reference (mpmath, SciPy, a closed form) or the violation of a property the +approximation should have (symmetry, monotonicity, continuity across a switch point). +These are measurements, not tests: the unit tests check the C library at fixed points, +so inaccuracy of the algorithms across regimes is recorded here. Behaviour that looks +wrong is a candidate for a fix. + +Errors are relative unless the metric says "abs" (log-scale quantities such as +log U, log 1F1 and log 2F1 are compared in absolute terms), "ulp" or "count". + +Example: + python evaluation/numerical_accuracy.py --quick + python evaluation/numerical_accuracy.py --only hyp2f1 gammainc --output acc.csv +""" + +import argparse +import csv +import math +import pathlib + +import clib +import mpmath +import numpy as np +import scipy.special + +INF = math.inf +RESULTS = pathlib.Path(__file__).parent / "results" + + +def try_call(func, *args): + """ + The result of ``func``, or None if it raised + """ + try: + return func(*args) + except Exception: # noqa: BLE001 + return None + + +def log_uniform(rng, lo, hi, size=None): + return 10.0 ** rng.uniform(lo, hi, size) + + +class Report: + """ + Collects rows of (group, function, regime, metric, value, points, note) + """ + + def __init__(self): + self.rows = [] + + def add(self, group, function, regime, metric, value, n=1, note=""): + self.rows.append((group, function, regime, metric, value, n, note)) + + def worst(self, group, function, regime, metric, errors, note=""): + """ + Worst of ``errors`` (None marks a call that raised) + """ + raised = sum(e is None for e in errors) + finite = [e for e in errors if e is not None and math.isfinite(e)] + value = max(finite) if finite else math.nan + nonfinite = len(errors) - raised - len(finite) + if raised or nonfinite: + note = f"{note} raised={raised} nonfinite={nonfinite}".strip() + self.add(group, function, regime, metric, value, len(errors), note) + + def print(self): + header = ("function", "regime", "metric", "value", "n", "note") + body = [(r[1], r[2], r[3], f"{r[4]:.3g}", str(r[5]), r[6]) for r in self.rows] + widths = [max(len(str(x)) for x in col) for col in zip(header, *body)] + group = None + for row, raw in zip(body, self.rows): + if raw[0] != group: + group = raw[0] + print(f"\n== {group} ==") + print(" ".join(h.ljust(w) for h, w in zip(header, widths))) + print(" ".join(x.ljust(w) for x, w in zip(row, widths)).rstrip()) + + def write(self, path): + with open(path, "w", newline="") as f: + writer = csv.writer(f) + writer.writerow(("group", *("function regime metric value n note".split()))) + writer.writerows(self.rows) + + +def rel(actual, expected): + if actual is None: + return None + if actual == expected: + return 0.0 + return abs(actual - expected) / abs(expected) + + +def ulp(actual, expected): + if actual is None: + return None + return abs(actual - expected) / np.spacing(abs(expected)) + + +# --- polygamma, betaln --- # + + +def mp_psi(n, x): + with mpmath.workdps(60): + return float(mpmath.psi(n, x)) + + +POLYGAMMA_REGIMES = { + "x <= 1e-5": [1e-10, 1e-6, 1e-5], + "1e-5 < x < 8.5 (recurrence)": [1e-3, 0.1, 1.0, 2.0, 4.9, 5.0, 8.4], + "x >= 8.5 (asymptotic)": [8.5, 100.0, 1e4, 1e8], + "x < 0 (reflection)": [-1e-5, -0.5, -1.5, -10.5, -100.3, -1e5 - 0.5], + "near a negative integer": [-1.0 + 1e-8, -1.0 - 1e-8, -3.0 - 1e-6, -2.0 + 1e-12], +} + + +def polygamma(report): + for name, order in [("_digamma", 0), ("_trigamma", 1)]: + func = getattr(clib, name.lstrip("_")) + for regime, xs in POLYGAMMA_REGIMES.items(): + errors = [rel(try_call(func, x), mp_psi(order, x)) for x in xs] + report.worst("polygamma", name, regime, "rel", errors) + # trigamma returns 1 / x**2 for x <= 1e-4, omitting pi**2 / 6 + xs = [1e-6, 1e-5, 1e-4] + errors = [rel(try_call(clib.trigamma, x), mp_psi(1, x)) for x in xs] + report.worst("polygamma", "_trigamma", "x <= 1e-4 (1/x**2)", "rel", errors) + # continuity at the switch points of the series + for x in [1e-5, 8.5]: + lo = clib.digamma(x) + hi = clib.digamma(np.nextafter(x, 2 * x)) + report.add("polygamma", "_digamma", f"jump at x={x}", "rel", rel(lo, hi)) + + +def betaln(report): + regimes = { + "balanced": [(0.5, 0.5), (1.0, 1.0), (1e5, 1e5), (1e15, 1e15), (1e300, 1e300)], + "tiny and tiny": [(1e-10, 1e-10), (1e-300, 1e-300)], + "tiny and huge (cancellation)": [(1e-10, 1e10), (1e8, 1e-8), (1e-5, 1e5)], + } + for regime, points in regimes.items(): + errors = [] + for p, q in points: + errors.append(rel(try_call(clib.betaln, p, q), scipy.special.betaln(p, q))) + report.worst("betaln", "_betaln", regime, "rel", errors) + + +# --- incomplete gamma --- # + + +def gammainc_der_reference(p, x): + with mpmath.workdps(40): + return float(mpmath.diff(lambda s: mpmath.gammainc(s, 0, x, regularized=True), p)) + + +def gammainc_der(report): + regimes = { + "series (x <= 1 or x < p)": [(1.0, 1.0), (0.5, 1.0), (1e-3, 1.0), (10.0, 0.5)] + + [(2.0, 1.5), (5.0, 3.0), (100.0, 100.0 - 1e-9)], + "continued fraction (x >= p, x > 1)": [(5.0, 5.0), (5.0, 50.0), (100.0, 100.0)] + + [(1e-3, 10.0)], + "just above x = 1 (continued fraction)": [(1.0, np.nextafter(1.0, 2))], + "gaussian (p > 1000)": [(1000.5, 900.0), (2000.0, 2000.0), (2000.0, 2300.0)], + } + for regime, points in regimes.items(): + errors = [] + for p, x in points: + ref = gammainc_der_reference(p, x) + errors.append(rel(try_call(clib.gammainc_der, p, x), ref)) + report.worst("gammainc", "_gammainc_der", regime, "rel", errors) + below = clib.gammainc_der(1000.0, 1000.0) + above = clib.gammainc_der(np.nextafter(1000.0, 2000.0), 1000.0) + report.add("gammainc", "_gammainc_der", "jump at p = 1000", "rel", rel(above, below)) + + +def exact_gammainc_inv(a, q, x0): + """ + Root of the regularised lower incomplete gamma minus q, near ``x0``; or None + """ + with mpmath.workdps(40): + + def f(t): + return mpmath.gammainc(a, 0, t, regularized=True) - q + + try: + bracket = (x0 * (1 - 1e-6), x0 * (1 + 1e-6)) + return float(mpmath.re(mpmath.findroot(f, bracket, solver="illinois"))) + except (ValueError, ZeroDivisionError): + return None + + +def gammainc_inv(report, rng, quick): + func = clib.gammaincinv + n = 10 if quick else 40 + for a in [0.1, 0.3, 1.0, 2.5, 10.0, 60.0, 1e3, 1e4]: + errors = [] + for q in log_uniform(rng, -12, -0.01, n): + x = try_call(func, a, q) + errors.append(rel(scipy.special.gammainc(a, x), q) if x else None) + report.worst("gammainc", "_gammainc_inv", f"roundtrip, a={a}", "rel", errors) + # relative to an exact inverse + bands = {"a < 0.1": (-2, -1), "0.1 <= a < 1": (-1, 0), "1 <= a < 10": (0, 1)} + bands |= {"10 <= a < 100": (1, 2), "a >= 100": (2, 4)} + n = 8 if quick else 60 + for band, (lo, hi) in bands.items(): + errors = [] + for a, q in zip(log_uniform(rng, lo, hi, n), rng.uniform(1e-8, 1.0, n)): + x = try_call(func, a, q) + exact = exact_gammainc_inv(a, q, x) + if exact is None: + continue + errors.append(ulp(x, exact)) + errors = [e for e in errors if e is not None] + if errors: + report.add( + "gammainc", + "_gammainc_inv", + band, + "ulp median", + np.median(errors), + len(errors), + ) + report.add( + "gammainc", "_gammainc_inv", band, "ulp max", max(errors), len(errors) + ) + qs = np.linspace(0.001, 0.999, 50) + violations = 0 + for a in [0.2, 1.0, 5.0, 100.0]: + x = [func(a, q) for q in qs.tolist()] + violations += int(np.sum(np.diff(x) <= 0)) + report.add("gammainc", "_gammainc_inv", "monotone in q", "count", violations, 200) + exact = [(q, func(1.0, q), -math.log1p(-q)) for q in [1e-100, 1e-3, 0.5, 0.999]] + errors = [rel(x, e) for _, x, e in exact] + report.worst("gammainc", "_gammainc_inv", "a = 1, exponential", "rel", errors) + + +# --- Laplace approximations to hypergeometric functions --- # + + +def log_hyperu(a, b, x): + with mpmath.workdps(30): + return float(mpmath.log(mpmath.hyperu(a, b, x, maxterms=10**6))) + + +def log_hyp1f1(a, b, x): + with mpmath.workdps(30): + return float(mpmath.log(mpmath.hyp1f1(a, b, x, maxterms=10**6))) + + +def log_hyp2f1(a, b, c, z): + with mpmath.workdps(30): + return float(mpmath.log(mpmath.re(mpmath.hyp2f1(a, b, c, z, maxterms=10**7)))) + + +def absolute(func, reference, points): + errors = [] + for args in points: + value = try_call(func, *args) + if isinstance(value, tuple): + value = value[0] + errors.append(None if value is None else abs(value - reference(*args))) + return errors + + +def hyperu(report): + func = clib.hyperu_laplace + regimes = { + "a >= 1 (EP: a = y + 1)": [(1.0, 2.0, 1.0), (2.0, 5.0, 0.5), (5.0, 15.0, 1.0)] + + [(10.0, 20.0, 50.0), (50.0, 60.0, 1.0), (1000.0, 1010.0, 1e4)], + "large b - a": [(1.0, 11.0, 1e-2), (1.0, 101.0, 100.0), (50.0, 1050.0, 100.0)], + "b == a": [(1.0, 1.0, 1.0)], + "a < 1 (Stirling)": [(1e-3, 10.001, 1.0), (0.1, 10.1, 1.0), (1.0, 1.001, 1e-6)], + } + for regime, points in regimes.items(): + report.worst( + "hyperu", "_hyperu_laplace", regime, "abs", absolute(func, log_hyperu, points) + ) + errors = [] + for a, b, x in [ + (1.0, 2.0, 1.0), + (2.0, 5.0, 0.5), + (1.0, 11.0, 1e-2), + (10.0, 20.0, 50.0), + ]: + step = 1e-6 * x + fd = (func(a, b, x + step)[0] - func(a, b, x - step)[0]) / (2 * step) + errors.append(rel(func(a, b, x)[1], fd)) + report.worst( + "hyperu", "_hyperu_laplace", "derivative vs finite difference", "rel", errors + ) + grid = [ + (a, a + d, x) + for a in [1.0, 50.0, 1e5] + for d in [1e-10, 1.0, 1e3] + for x in [1e-3, 1.0, 1e3] + ] + values = [try_call(func, *args) for args in grid] + positive = sum(v is not None and v[1] > 0 for v in values) + report.add( + "hyperu", + "_hyperu_laplace", + "d/dx log U > 0, a >= 1", + "count", + positive, + len(grid), + ) + d = func(1e-10, 1.0 + 1e-10, 1e-12)[1] + report.add( + "hyperu", + "_hyperu_laplace", + "d/dx log U at a = 1e-10", + "value", + d, + 1, + "should be < 0", + ) + values = [func(2.0, 2.0, x)[0] for x in [0.5, 1.0, 2.0, 4.0]] + report.add( + "hyperu", + "_hyperu_laplace", + "U(a, a, x) decreasing", + "count", + int(np.sum(np.diff(values) >= 0)), + 3, + ) + + +def hyp1f1(report): + func = clib.hyp1f1_laplace + regimes = { + "moderate": [ + (1.0, 2.0, 1.0), + (1.0, 2.0, -1.0), + (5.0, 8.0, 10.0), + (5.0, 8.0, -10.0), + ], + "large shapes": [(50.0, 1000.0, 100.0), (50.0, 1000.0, -100.0)] + + [(1000.0, 1010.0, 20.0), (1000.0, 1010.0, -20.0)], + "a -> 0": [(1e-10, 1.0 + 1e-10, 1e3), (1e-10, 2e-10, 1.0)], + } + for regime, points in regimes.items(): + report.worst( + "hyp1f1", "_hyp1f1_laplace", regime, "abs", absolute(func, log_hyp1f1, points) + ) + errors = [] + for a, b, x in [(5.0, 8.0, 10.0), (1.0, 3.0, 2.0), (30.0, 40.0, 100.0)]: + errors.append(rel(func(a, b, -x), -x + func(b - a, b, x))) + report.worst("hyp1f1", "_hyp1f1_laplace", "Kummer transformation", "rel", errors) + xs = np.linspace(-50, 50, 41).tolist() + values = [func(2.0, 5.0, x) for x in xs] + report.add( + "hyp1f1", + "_hyp1f1_laplace", + "increasing in x", + "count", + int(np.sum(np.diff(values) <= 0)), + 40, + ) + + +def hyp2f1(report, quick): + func = clib.hyp2f1_laplace + zs = [(-1e9,), (-100.0,), (-1.0,), (0.5,), (0.9,), (0.99,), (0.99998,), (0.999999,)] + abcs = { + "(1, 2, 3)": (1.0, 2.0, 3.0), + "(5, 7, 9)": (5.0, 7.0, 9.0), + "(30, 40, 35)": (30.0, 40.0, 35.0), + "(100, 200, 150)": (100.0, 200.0, 150.0), + "(0.5, 30, 1.5)": (0.5, 30.0, 1.5), + "(1, 2, 5) g > 0": (1.0, 2.0, 5.0), + "(2, 3, 5) g = 0": (2.0, 3.0, 5.0), + "(3, 2, 5)": (3.0, 2.0, 5.0), + "(2, 2, 5)": (2.0, 2.0, 5.0), + "(0.1, 0.2, 1) small": (0.1, 0.2, 1.0), + } + for label, abc in abcs.items(): + for (z,) in zs: + if abc == (100.0, 200.0, 150.0) and z > 0.9999: + continue + if quick and z not in (-100.0, 0.5, 0.99998): + continue + errors = absolute(func, log_hyp2f1, [(*abc, z)]) + regime = f"(a,b,c)={label}, z={z:g}" + report.worst("hyp2f1", "_hyp2f1_laplace", regime, "abs", errors) + # tiny z: 2F1 ~ 1 + a b z / c + errors = [] + for a, b, c in [ + (1.0, 2.0, 3.0), + (5.0, 7.0, 9.0), + (0.5, 30.0, 1.5), + (30.0, 40.0, 35.0), + ]: + for z in [1e-12, 1e-8, 1e-4, -1e-12, -1e-8, -1e-4]: + errors.append(abs(func(a, b, c, z) - a * b / c * z)) + report.worst("hyp2f1", "_hyp2f1_laplace", "|z| <= 1e-4 vs a b z / c", "abs", errors) + # the unity limit, through hugely negative z (the parameters of EP updates) + pars = [ + (202.865, 0.0153, 0.0012724, 101353547.00, 0.0, 2.404560e-05), + (999.998, 0.1041, 0.0012612, 14749022.000, 2.0, 7.830300e-05), + (73.4909, 1.0600, 0.0010028, 56254280956.0, 0.0, 0.0002302392), + (18.9981, 0.1315, 0.0015053, 23443723634.0, 1.0, 2.470348e-05), + ] + errors = [] + for a_i, b_i, a_j, b_j, y, mu in pars: + z = (mu - b_j) / (mu + b_i) + args = (a_j, a_i + a_j + y, a_j + y + 1, z) + errors.append(abs(func(*args) - log_hyp2f1(*args))) + report.worst("hyp2f1", "_hyp2f1_laplace", "unity limit, EP parameters", "abs", errors) + # discontinuity where np.isclose(z, 1) switches to the unity limit + lo, hi = 0.5, 1.0 - 1e-9 + while np.nextafter(lo, 1.0) != hi: + mid = lo + (hi - lo) / 2 + lo, hi = (lo, mid) if np.isclose(mid, 1.0) else (mid, hi) + for abc in [(1.0, 2.0, 3.0), (30.0, 40.0, 35.0)]: + jump = func(*abc, hi) - func(*abc, lo) + report.add( + "hyp2f1", + "_hyp2f1_laplace", + f"jump at switch to unity, {abc}", + "abs", + abs(jump), + ) + sym = [rel(func(2.0, 5.0, 7.0, z), func(5.0, 2.0, 7.0, z)) for z in [-3.0, 0.2, 0.9]] + report.worst("hyp2f1", "_hyp2f1_laplace", "symmetric in a, b", "rel", sym) + values = [func(3.0, 4.0, 8.0, z) for z in np.linspace(-20, 0.98, 60)] + report.add( + "hyp2f1", + "_hyp2f1_laplace", + "increasing in z", + "count", + int(np.sum(np.diff(values) <= 0)), + 59, + ) + + +# --- gamma approximations --- # + + +def gamma_quantiles(shape, rate, q1=0.25, q2=0.75): + x1, x2 = scipy.special.gammaincinv(shape, [q1, q2]) / rate + return q1, q2, float(x1), float(x2) + + +def gamma_fits(report, rng, quick): + kl = clib.approximate_gamma_kl + errors, residuals = [], [] + for x, gap in [ + (1.0, 1e-3), + (1.0, 0.5), + (1.0, 5.0), + (1e-3, 2.0), + (1e6, 0.1), + (3.0, 1e-4), + ]: + shape, rate = kl(x, math.log(x) - gap) + alpha = shape + 1.0 + errors.append(rel(alpha / rate, x)) + residuals.append(abs(scipy.special.digamma(alpha) - math.log(alpha) + gap)) + report.worst("approx", "approximate_gamma_kl", "mean matched", "rel", errors) + report.worst( + "approx", "approximate_gamma_kl", "stationarity residual", "abs", residuals + ) + below = kl(1.0, -np.nextafter(5e-5, 0.0))[0] + above = kl(1.0, -np.nextafter(5e-5, 1.0))[0] + report.add( + "approx", + "approximate_gamma_kl", + "jump at asymptotic switch", + "rel", + rel(below, above), + ) + errors = [] + for mean, variance in [(1.0, 1.0), (10.0, 4.0), (1e3, 1e-6), (1e-3, 1e-3)]: + shape, rate = clib.approximate_gamma_mom(mean, variance) + errors += [rel((shape + 1) / rate, mean), rel((shape + 1) / rate**2, variance)] + report.worst( + "approx", "approximate_gamma_mom", "mean and variance matched", "rel", errors + ) + mean, variance = 3.0, 0.5 + logx, xlogx, logx2 = clib.approximate_log_moments(mean, variance) + expected = ( + math.log(mean) - 0.5 * variance / mean**2, + mean * math.log(mean) + 0.5 * variance / mean, + math.log(mean) ** 2 + (1 - math.log(mean)) * variance / mean**2, + ) + errors = [rel(a, e) for a, e in zip((logx, xlogx, logx2), expected)] + report.worst( + "approx", "approximate_log_moments", "second order expansion", "rel", errors + ) + shapes = [0.01, 0.1, 0.5, 1.0, 2.0, 10.0, 49.0, 50.0, 51.0, 999.0, 1001.0, 1e4, 1e6] + for max_shape in [50.0, 1000.0, 1e6]: + errors = [] + for shape in shapes: + args = (*gamma_quantiles(shape, 0.001), max_shape) + result = try_call(clib.approximate_gamma_iqr, *args) + errors.append( + None if result is None else rel(result[0] + 1.0, min(shape, max_shape)) + ) + report.worst( + "approx", + "approximate_gamma_iqr", + f"shape recovered, max_shape={max_shape:g}", + "rel", + errors, + ) + + +def moment_functions(report, quick): + a_i, b_i, y, mu = 10.0, 0.01, 3.0, 1e-4 + s, r = a_i + y, b_i + 2 * mu + got = clib.twin_moments(a_i, b_i, y, mu) + expected = (math.log(2) * y + math.lgamma(s) - math.log(r) * s, s / r, s / r**2) + report.worst( + "approx", + "twin_moments", + "closed form", + "rel", + [rel(g, e) for g, e in zip(got, expected)], + ) + t_i, t_j = 7.0, 2.0 + mn, va = clib.mutation_edge_moments(t_i, t_j) + errors = [rel(mn, 4.5), rel(va, 25.0 / 12.0)] + report.worst("approx", "mutation_edge_moments", "closed form", "rel", errors) + pr, mn, va = clib.mutation_block_moments(t_i, t_j) + errors = [rel(pr, 7.0 / 9.0), rel(mn, pr * t_i / 2 + (1 - pr) * t_j / 2)] + report.worst("approx", "mutation_block_moments", "closed form", "rel", errors) + # rootward with t_j -> 0 approaches the gamma with shape a_i + y, rate b_i + mu + a_i, b_i, y, mu = 10.0, 0.01, 1.0, 1e-4 + s, r = a_i + y, b_i + mu + exact = (math.lgamma(s) - s * math.log(r), s / r, s / r**2) + for t_j in [1e-10, 1e-3]: + got = clib.rootward_moments(t_j, a_i, b_i, y, mu) + report.add( + "approx", + "rootward_moments", + f"t_j={t_j:g} vs t_j=0 closed form, log-lik", + "abs", + abs(got[0] - exact[0]), + ) + report.add( + "approx", + "rootward_moments", + f"t_j={t_j:g} vs t_j=0 closed form, mean", + "rel", + rel(got[1], exact[1]), + ) + # y = 0: U(a, a + 1, z) = z**-a + a_j, b_j, mu, t_i = 10.0, 0.01, 1e-4, 1000.0 + logl, mn, va = clib.sideways_moments(t_i, a_j, b_j, 0.0, mu) + z = t_i * (mu + b_j) + f0 = logl + mu * t_i - a_j * math.log(t_i) - math.lgamma(a_j) + report.add( + "approx", "sideways_moments", "y = 0 vs z**-a", "rel", rel(f0, -a_j * math.log(z)) + ) + # projected gammas reproduce the moments + args = (10.0, 0.01, 10.0, 0.01, 1.0, 1e-4) + _, mn_i, va_i, mn_j, va_j = clib.moments(*args) + _, *flat = clib.gamma_projection(9.0, 0.01, 9.0, 0.01, 1.0, 1e-4) + proj_i = flat[0:2] + proj_j = flat[2:4] + errors = [] + for proj, mn, va in [(proj_i, mn_i, va_i), (proj_j, mn_j, va_j)]: + errors += [ + rel((proj[0] + 1) / proj[1], mn), + rel((proj[0] + 1) / proj[1] ** 2, va), + ] + report.worst( + "approx", "gamma_projection", "projection matches moments", "rel", errors + ) + # variance by cancellation (second moment minus squared mean) + for name, args in [ + ("moments", (1e8, 1e5, 1e8, 1e5, 1, 1e-4)), + ("moments", (10, 0.01, 10, 0.01, 1, 1e-4)), + ]: + va = getattr(clib, name)(*[float(a) for a in args])[2] + regime = "shape 1e8" if args[0] == 1e8 else "typical" + report.add( + "approx", + name, + f"variance of parent age, {regime}", + "value", + va, + 1, + "negative = lost", + ) + rng = np.random.default_rng(1) + count, total = 0, 200 if quick else 2000 + for _ in range(total): + a_i, a_j = rng.uniform(0.5, 30, 2) + b_i, b_j = log_uniform(rng, -5, -2, 2) + y, mu = float(rng.integers(0, 12)), log_uniform(rng, -4, -2) + result = clib.moments(a_i, b_i, a_j, b_j, y, mu) + count += not (result[2] > 0 and result[4] > 0) + report.add( + "approx", + "moments", + "non-positive variance, typical EP range", + "count", + count, + total, + ) + count = 0 + for _ in range(total): + a_i, a_j = rng.uniform(0.5, 30, 2) + b_i, b_j = log_uniform(rng, -5, -2, 2) + y, mu = float(rng.integers(0, 12)), log_uniform(rng, -4, -2) + pr = clib.mutation_unphased_moments(a_i, b_i, a_j, b_j, y, mu)[0] + count += not (0 <= pr <= 1) + report.add( + "approx", + "mutation_unphased_moments", + "probability outside [0, 1], typical EP range", + "count", + count, + total, + ) + + +def main(): + p = argparse.ArgumentParser(description=__doc__.split("\n\n")[0]) + p.add_argument("--quick", action="store_true", help="fewer points, skip slow rows") + p.add_argument("--only", nargs="+", default=None, help="substrings of group names") + p.add_argument("--seed", type=int, default=1) + p.add_argument("--output", default=None, help="CSV file name, written to results/") + args = p.parse_args() + rng = np.random.default_rng(args.seed) + report = Report() + steps = { + "polygamma": lambda: polygamma(report), + "betaln": lambda: betaln(report), + "gammainc": lambda: ( + gammainc_der(report), + gammainc_inv(report, rng, args.quick), + ), + "hyperu": lambda: hyperu(report), + "hyp1f1": lambda: hyp1f1(report), + "hyp2f1": lambda: hyp2f1(report, args.quick), + "approx": lambda: ( + gamma_fits(report, rng, args.quick), + moment_functions(report, args.quick), + ), + } + for name, step in steps.items(): + if args.only is None or any(o in name for o in args.only): + step() + report.print() + if args.output: + RESULTS.mkdir(exist_ok=True) + path = RESULTS / args.output + report.write(path) + print("\nwrote", path) + + +if __name__ == "__main__": + main() diff --git a/evaluation/performance.py b/evaluation/performance.py index d08500ff..1d740af1 100644 --- a/evaluation/performance.py +++ b/evaluation/performance.py @@ -2,8 +2,8 @@ Time and memory of tsdate.variational_gamma. Each case runs in a fresh (spawned) process so that memory is not polluted by earlier cases. Memory is the increase in resident set size (RSS) during dating over the level just before it, sampled from -the parent process (the process itself would be starved by jitted code holding the -GIL). Writes results/performance.csv; use plot.py to make figures. +the parent process (the process itself would be starved by C code holding the GIL). +Writes results/performance.csv; use plot.py to make figures. Example: python evaluation/performance.py --sizes 10 50 100 500 1000 --lengths 1e6 1e7 @@ -11,7 +11,6 @@ import argparse import multiprocessing -import os import queue as queue_lib import time @@ -29,10 +28,6 @@ def _case(queue, n, length, mutation_rate, seed, inferred): ts = common.simulate(n, length, mutation_rate, seed) if inferred: ts = common.infer_topology(ts) - # Warm up numba compilation on a tiny case so it isn't timed - tsdate.date( - common.simulate(5, 1e4, 1e-8, 1), mutation_rate=1e-8, method="variational_gamma" - ) queue.put(("start", None)) start = time.perf_counter() tsdate.date(ts, mutation_rate=mutation_rate, method="variational_gamma") @@ -103,9 +98,6 @@ def main(): if args.quick: args.sizes, args.lengths, args.repeats = [10, 30], [1e5], 1 - # Compiled code is not part of the timing or the memory increase (it is warmed up - # first), so cache it on disk to avoid recompiling in every fresh process - os.environ.setdefault("TSDATE_ENABLE_NUMBA_CACHE", "1") prov = common.provenance() rows = [] total = len(args.sizes) * len(args.lengths) * args.repeats diff --git a/evaluation/requirements.txt b/evaluation/requirements.txt index 4a8f7d1c..0609b898 100644 --- a/evaluation/requirements.txt +++ b/evaluation/requirements.txt @@ -6,3 +6,4 @@ matplotlib pandas psutil scipy +mpmath diff --git a/lib/approx.c b/lib/approx.c new file mode 100644 index 00000000..2ef17b91 --- /dev/null +++ b/lib/approx.c @@ -0,0 +1,1324 @@ +/* + * MIT License + * + * Copyright (c) 2026 Tskit Developers + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in all + * copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE + * SOFTWARE. + */ + +/* + * Gamma approximations and the moments of the EP updates. Operation order and libm + * calls match the oracles in tests/oracle, which the tests compare exactly. + * + * A float division by zero returns TSD_ERR_ZERO_DIVISION at the divisions that the + * tests show to be reachable (where the oracle raises ZeroDivisionError). The other + * divisions follow IEEE semantics (infinity or NaN). + */ + +#include + +#include "mathutil.h" +#include "tsdate.h" + +/* The convergence tolerance of the Newton iterations: sqrt(DBL_EPSILON), exactly. */ +#define KLMIN_RELTOL 1.4901161193847656e-08 +#define KLMIN_MAXITT 100 + +/* ------------------------------------------------------------------------- * + * Helpers: gamma approximations and validity checks + * ------------------------------------------------------------------------- */ + +/* + * Approximate log moments via a second-order Taylor series expansion around the mean: + * E[f(x)] ~ f(mean) + variance * f''(mean) / 2. Returns E[log x], E[x log x] and + * E[(log x)^2]. + */ +int +tsd_approximate_log_moments( + double mean, double variance, double *logx, double *xlogx, double *logx2) +{ + int ret = 0; + double log_mean, mean_sq; + + if (!(mean > 0.0) || !(variance > 0.0)) { + ret = tsd_trace_error(TSD_ERR_NONPOSITIVE_MOMENTS); + goto out; + } + log_mean = log(mean); + mean_sq = tsd_ipow(mean, 2); + if (mean_sq == 0.0) { + ret = tsd_trace_error(TSD_ERR_ZERO_DIVISION); + goto out; + } + *logx = log_mean - 0.5 * variance / mean_sq; + *xlogx = mean * log_mean + 0.5 * variance / mean; + *logx2 = tsd_ipow(log_mean, 2) + (1 - log_mean) * variance / mean_sq; +out: + return ret; +} + +/* + * Newton root finding for the gamma natural parameters matching E[x] and E[log x], + * minimising KL divergence. The initial condition uses the upper bound + * digamma(x) <= log(x) - 1/2x. + */ +int +tsd_approximate_gamma_kl(double x, double logx, double out[2]) +{ + int ret = 0; + int itt = 0; + double log_x, alpha, delta, dg, tg, denom; + + if (x <= 0.0 || isinf(logx)) { + ret = tsd_trace_error(TSD_ERR_NONPOSITIVE_OR_NONFINITE_MOMENTS); + goto out; + } + log_x = log(x); + if (!(log_x > logx)) { + ret = tsd_trace_error(TSD_ERR_JENSEN_VIOLATION); + goto out; + } + alpha = 0.5 / (log_x - logx); /* lower bound on alpha */ + if (alpha == 0.0) { + ret = tsd_trace_error(TSD_ERR_ZERO_DIVISION); + goto out; + } + /* asymptotically the lower bound becomes sharp */ + if (1.0 / alpha < 1e-4) { + out[0] = alpha - 1.0; + out[1] = alpha / x; + goto out; + } + /* converged when the change in alpha falls below the square root of machine + * precision */ + delta = INFINITY; + while (fabs(delta) > fabs(alpha) * KLMIN_RELTOL) { + if (itt > KLMIN_MAXITT) { + ret = tsd_trace_error(TSD_ERR_KL_MAX_ITERATIONS); + goto out; + } + ret = tsd_digamma(alpha, &dg); + if (ret != 0) { + goto out; + } + delta = dg - log(alpha) + log_x - logx; + ret = tsd_trigamma(alpha, &tg); + if (ret != 0) { + goto out; + } + /* alpha is not zero (the polygamma functions would have failed) */ + denom = tg - 1 / alpha; + delta /= denom; + alpha -= delta; + itt++; + } + if (!isfinite(alpha) || alpha <= 0) { + ret = tsd_trace_error(TSD_ERR_KL_INVALID_SHAPE); + goto out; + } + out[0] = alpha - 1.0; + out[1] = alpha / x; +out: + return ret; +} + +/* + * The method of moments: natural parameters of the gamma with the given mean and + * variance. + */ +int +tsd_approximate_gamma_mom(double mean, double variance, double out[2]) +{ + int ret = 0; + double shape, rate; + + if (!(mean > 0.0 && variance > 0.0)) { + ret = tsd_trace_error(TSD_ERR_NONPOSITIVE_CENTRAL_MOMENTS); + goto out; + } + shape = tsd_ipow(mean, 2) / variance; + rate = mean / variance; + out[0] = shape - 1.0; + out[1] = rate; +out: + return ret; +} + +/* The gamma with shape `max_shape` whose q-quantile is x. */ +static int +gamma_iqr_upper_bound(double q, double x, double max_shape, double out[2]) +{ + int ret = 0; + + if (x == 0.0) { + ret = tsd_trace_error(TSD_ERR_ZERO_DIVISION); + goto out; + } + out[0] = max_shape - 1; + out[1] = tsd_gammaincinv(max_shape, q) / x; +out: + return ret; +} + +/* + * One Newton step on the shape of a gamma whose quantiles are in the given ratio. + * Updates alpha and writes the step to delta. + */ +static int +gamma_iqr_newton_step( + double q1, double q2, double x1, double x2, double *alpha, double *delta) +{ + int ret = 0; + double y1, y2, obj, inv_1, inv_2, der_1, der_2, gra_1, gra_2, y1_sq, gra; + + y1 = tsd_gammaincinv(*alpha, q1); + y2 = tsd_gammaincinv(*alpha, q2); + if (y1 == 0.0) { + ret = tsd_trace_error(TSD_ERR_ZERO_DIVISION); + goto out; + } + obj = y2 / y1 - x2 / x1; + inv_1 = -exp(y1 + log(y1) * (1 - *alpha) + lgamma(*alpha)); + inv_2 = -exp(y2 + log(y2) * (1 - *alpha) + lgamma(*alpha)); + ret = tsd_gammainc_der(*alpha, y1, &der_1); + if (ret != 0) { + goto out; + } + gra_1 = der_1 * inv_1; + ret = tsd_gammainc_der(*alpha, y2, &der_2); + if (ret != 0) { + goto out; + } + gra_2 = der_2 * inv_2; + y1_sq = tsd_ipow(y1, 2); + if (y1_sq == 0.0) { + ret = tsd_trace_error(TSD_ERR_ZERO_DIVISION); + goto out; + } + gra = (gra_2 * y1 - gra_1 * y2) / y1_sq; + if (gra == 0.0) { + ret = tsd_trace_error(TSD_ERR_ZERO_DIVISION); + goto out; + } + *delta = -obj / gra; + *alpha += *delta; +out: + return ret; +} + +/* + * Natural parameters of a gamma matching two quantiles: q1, q2 are probabilities and + * x1, x2 the corresponding quantiles. The shape is capped at max_shape. + */ +int +tsd_approximate_gamma_iqr( + double q1, double q2, double x1, double x2, double max_shape, double out[2]) +{ + int ret = 0; + int itt = 0; + double alpha, delta, ratio_q, ratio_x; + + if (x2 == x1) { + ret = gamma_iqr_upper_bound(q1, x1, max_shape, out); + goto out; + } + if (!(q2 > q1 && x2 > x1)) { + ret = tsd_trace_error(TSD_ERR_UNSORTED_QUANTILES); + goto out; + } + if (q1 == 0.0 || x1 == 0.0) { + ret = tsd_trace_error(TSD_ERR_ZERO_DIVISION); + goto out; + } + ratio_q = q2 / q1; + ratio_x = x2 / x1; + alpha = log(ratio_q) / log(ratio_x); /* lower bound */ + if (alpha > max_shape) { + ret = gamma_iqr_upper_bound(q1, x1, max_shape, out); + goto out; + } + /* refine with Newton iteration */ + delta = INFINITY; + while (fabs(delta) > fabs(alpha) * KLMIN_RELTOL) { + if (itt > KLMIN_MAXITT) { + ret = tsd_trace_error(TSD_ERR_QUANTILE_MAX_ITERATIONS); + goto out; + } + ret = gamma_iqr_newton_step(q1, q2, x1, x2, &alpha, &delta); + if (ret != 0) { + goto out; + } + itt++; + } + if (!(alpha > 0)) { + ret = tsd_trace_error(TSD_ERR_NEGATIVE_SHAPE); + goto out; + } + if (alpha > max_shape) { + ret = gamma_iqr_upper_bound(q1, x1, max_shape, out); + goto out; + } + out[0] = alpha - 1; + out[1] = tsd_gammaincinv(alpha, q1) / x1; +out: + return ret; +} + +int +tsd_valid_moments(double mn, double va) +{ + if (!(isfinite(mn) && isfinite(va))) { + return 0; + } + if (!(mn > 0.0 && va > 0.0)) { + return 0; + } + return 1; +} + +int +tsd_valid_gamma(double s, double r) +{ + if (!(isfinite(s) && isfinite(r))) { + return 0; + } + if (s <= 0.0 || r <= 0.0) { + return 0; + } + return 1; +} + +int +tsd_valid_hyp1f1(double a, double b, double z) +{ + if (!(isfinite(a) && isfinite(b) && isfinite(z))) { + return 0; + } + if (!(b >= a && a > 0.0)) { + return 0; + } + return 1; +} + +int +tsd_valid_hyperu(double a, double b, double z) +{ + if (!(isfinite(a) && isfinite(b) && isfinite(z))) { + return 0; + } + if (z <= 0.0) { + return 0; + } + if (!(b > a && a > 0.0)) { + return 0; + } + return 1; +} + +int +tsd_valid_hyp2f1(double a, double b, double c, double z) +{ + if (!(isfinite(a) && isfinite(b) && isfinite(c))) { + return 0; + } + if (!isfinite(z) || z >= 1 || z / (z - 1) >= 1) { + return 0; + } + if (!(a > 0 && b > 0 && c > 0)) { + return 0; + } + return 1; +} + +/* ------------------------------------------------------------------------- * + * Node moments + * ------------------------------------------------------------------------- */ + +/* The moments of an edge between two free nodes are unusable: all NaN. */ +static void +set_nan_two_node(double *logl, double *mn_i, double *va_i, double *mn_j, double *va_j) +{ + *logl = NAN; + *mn_i = NAN; + *va_i = NAN; + *mn_j = NAN; + *va_j = NAN; +} + +static void +set_nan_one_node(double *logl, double *mn, double *va) +{ + *logl = NAN; + *mn = NAN; + *va = NAN; +} + +/* + * log p(t_i, t_j) = log(t_i - t_j) * y_ij - mu_ij * (t_i - t_j) + * + log(t_i) * (a_i - 1) - b_i * t_i + log(t_j) * (a_j - 1) - b_j * t_j + * Writes the normalising constant, E[t_i], V[t_i], E[t_j], V[t_j]. + */ +int +tsd_moments(double a_i, double b_i, double a_j, double b_j, double y_ij, double mu_ij, + double *logl, double *mn_i, double *va_i, double *mn_j, double *va_j) +{ + int ret = 0; + double a, b, c, t, z, f0, f1, f2, s1, s2, d1, d2; + double sq_i, sq_j, mn_i_, mn_j_, va_i_, va_j_, logl_; + + a = a_j; + b = a_i + a_j + y_ij; + c = a_j + y_ij + 1; + t = mu_ij + b_i; + z = t > 0 ? (mu_ij - b_j) / t : NAN; + + if (!tsd_valid_hyp2f1(a, b, c, z)) { + set_nan_two_node(logl, mn_i, va_i, mn_j, va_j); + goto out; + } + + ret = tsd_hyp2f1_laplace(a, b, c, z, &f0); + if (ret != 0) { + goto out; + } + ret = tsd_hyp2f1_laplace(a + 1, b + 1, c + 1, z, &f1); + if (ret != 0) { + goto out; + } + ret = tsd_hyp2f1_laplace(a + 2, b + 2, c + 2, z, &f2); + if (ret != 0) { + goto out; + } + s1 = a * b / c; + s2 = s1 * (a + 1) * (b + 1) / (c + 1); + d1 = s1 * exp(f1 - f0); + d2 = s2 * exp(f2 - f0); + + logl_ = f0 + tsd_betaln(y_ij + 1, a) + lgamma(b) - b * log(t); + + mn_j_ = d1 / t; + sq_j = d2 / (t * t); + va_j_ = sq_j - mn_j_ * mn_j_; + + mn_i_ = mn_j_ * z + b / t; + sq_i = sq_j * (z * z) + (b + 1) * (mn_i_ + mn_j_ * z) / t; + va_i_ = sq_i - mn_i_ * mn_i_; + + *logl = logl_; + *mn_i = mn_i_; + *va_i = va_i_; + *mn_j = mn_j_; + *va_j = va_j_; +out: + return ret; +} + +/* + * log p(t_i) = log(t_i - t_j) * y_ij - mu_ij * (t_i - t_j) + * + log(t_i) * (a_i - 1) - b_i * t_i + * for a fixed child age t_j >= 0. Writes the normalising constant, E[t_i], V[t_i]. + */ +int +tsd_rootward_moments(double t_j, double a_i, double b_i, double y_ij, double mu_ij, + double *logl, double *mn_i, double *va_i) +{ + int ret = 0; + double s, r, a, b, z, f0, d0, f1, d1; + + if (!(t_j >= 0.0)) { + ret = tsd_trace_error(TSD_ERR_INVALID_FIXED_AGE); + goto out; + } + + s = a_i + y_ij; + r = mu_ij + b_i; + + if (!tsd_valid_gamma(s, r)) { + set_nan_one_node(logl, mn_i, va_i); + goto out; + } + + if (t_j == 0.0) { + *logl = lgamma(s) - s * log(r); + *mn_i = s / r; + *va_i = s / (r * r); + goto out; + } + + a = y_ij + 1; + b = s + 1; + z = t_j * r; + + if (!tsd_valid_hyperu(a, b, z)) { + set_nan_one_node(logl, mn_i, va_i); + goto out; + } + + ret = tsd_hyperu_laplace(a, b, z, &f0, &d0); + if (ret != 0) { + goto out; + } + ret = tsd_hyperu_laplace(a + 1, b + 1, z, &f1, &d1); + if (ret != 0) { + goto out; + } + + *logl = f0 - b_i * t_j + (b - 1) * log(t_j) + lgamma(a); + *mn_i = t_j * (1 - d0); + *va_i = (t_j * t_j) * d0 * (d1 - d0); +out: + return ret; +} + +/* + * log p(t_j) = log(t_i - t_j) * y_ij - mu_ij * (t_i - t_j) + * + log(t_j) * (a_j - 1) - b_j * t_j + * for a fixed parent age t_i > 0. Writes the normalising constant, E[t_j], V[t_j]. + */ +int +tsd_leafward_moments(double t_i, double a_j, double b_j, double y_ij, double mu_ij, + double *logl, double *mn_j, double *va_j) +{ + int ret = 0; + double a, b, z, f0, f1, f2, d1, d2, sq_j, mn_j_, logl_; + + if (!(t_i > 0.0)) { + ret = tsd_trace_error(TSD_ERR_INVALID_FIXED_AGE); + goto out; + } + + a = a_j; + b = a_j + y_ij + 1; + z = t_i * (mu_ij - b_j); + + if (!tsd_valid_hyp1f1(a, b, z)) { + set_nan_one_node(logl, mn_j, va_j); + goto out; + } + + ret = tsd_hyp1f1_laplace(a, b, z, &f0); + if (ret != 0) { + goto out; + } + ret = tsd_hyp1f1_laplace(a + 1, b + 1, z, &f1); + if (ret != 0) { + goto out; + } + ret = tsd_hyp1f1_laplace(a + 2, b + 2, z, &f2); + if (ret != 0) { + goto out; + } + d1 = a / b * exp(f1 - f0); + d2 = a / b * (a + 1) / (b + 1) * exp(f2 - f0); + + logl_ = f0 - mu_ij * t_i + (b - 1) * log(t_i) + tsd_betaln(a, b - a); + mn_j_ = t_i * d1; + sq_j = (t_i * t_i) * d2; + + *logl = logl_; + *mn_j = mn_j_; + *va_j = sq_j - mn_j_ * mn_j_; +out: + return ret; +} + +/* + * log p(t_i, t_j) = log(t_i + t_j) * y_ij - mu_ij * (t_i + t_j) + * + log(t_i) * (a_i - 1) - b_i * t_i + log(t_j) * (a_j - 1) - b_j * t_j + * Writes the normalising constant, E[t_i], V[t_i], E[t_j], V[t_j]. + */ +int +tsd_unphased_moments(double a_i, double b_i, double a_j, double b_j, double y_ij, + double mu_ij, double *logl, double *mn_i, double *va_i, double *mn_j, double *va_j) +{ + int ret = 0; + double a, b, c, t, z, f0, f1, f2, s1, s2, d1, d2; + double sq_i, sq_j, mn_i_, mn_j_, va_i_, va_j_, logl_; + + a = a_j; + b = a_i + a_j + y_ij; + c = a_j + a_i; + t = mu_ij + b_i; + z = t > 0 ? (mu_ij + b_j) / t : NAN; + + if (!tsd_valid_hyp2f1(a, b, c, 1 - z)) { + set_nan_two_node(logl, mn_i, va_i, mn_j, va_j); + goto out; + } + + ret = tsd_hyp2f1_laplace(a, b, c, 1 - z, &f0); + if (ret != 0) { + goto out; + } + ret = tsd_hyp2f1_laplace(a + 1, b + 1, c + 1, 1 - z, &f1); + if (ret != 0) { + goto out; + } + ret = tsd_hyp2f1_laplace(a + 2, b + 2, c + 2, 1 - z, &f2); + if (ret != 0) { + goto out; + } + s1 = a * b / c; + s2 = s1 * (a + 1) * (b + 1) / (c + 1); + d1 = s1 * exp(f1 - f0); + d2 = s2 * exp(f2 - f0); + + logl_ = f0 + tsd_betaln(a_j, a_i) + lgamma(b) - b * log(t); + + mn_j_ = d1 / t; + sq_j = d2 / (t * t); + va_j_ = sq_j - mn_j_ * mn_j_; + + mn_i_ = b / t - mn_j_ * z; + sq_i = sq_j * (z * z) + (b + 1) * (mn_i_ - mn_j_ * z) / t; + va_i_ = sq_i - mn_i_ * mn_i_; + + *logl = logl_; + *mn_i = mn_i_; + *va_i = va_i_; + *mn_j = mn_j_; + *va_j = va_j_; +out: + return ret; +} + +/* + * log p(t_i) = log(2 t_i) * y_ij - mu_ij * (2 t_i) + log(t_i) * (a_i - 1) - b_i * t_i + * for the two edges of an unphased individual to the same parent. Writes the + * normalising constant, E[t_i], V[t_i]. A zero rate r (or one whose square + * underflows) returns TSD_ERR_ZERO_DIVISION. + */ +int +tsd_twin_moments(double a_i, double b_i, double y_ij, double mu_ij, double *logl, + double *mn_i, double *va_i) +{ + int ret = 0; + double s, r, r_sq; + + s = a_i + y_ij; + r = b_i + 2 * mu_ij; + r_sq = r * r; + if (r == 0.0 || r_sq == 0.0) { + ret = tsd_trace_error(TSD_ERR_ZERO_DIVISION); + goto out; + } + + *logl = log(2.0) * y_ij + lgamma(s) - log(r) * s; + *mn_i = s / r; + *va_i = s / r_sq; +out: + return ret; +} + +/* + * log p(t_j) = log(t_i + t_j) * y_ij - mu_ij * (t_i + t_j) + * + log(t_j) * (a_j - 1) - b_j * t_j + * for a fixed age t_i > 0. Writes the normalising constant, E[t_j], V[t_j]. + */ +int +tsd_sideways_moments(double t_i, double a_j, double b_j, double y_ij, double mu_ij, + double *logl, double *mn_j, double *va_j) +{ + int ret = 0; + double a, b, z, f0, d0, f1, d1; + + if (!(t_i > 0.0)) { + ret = tsd_trace_error(TSD_ERR_INVALID_FIXED_AGE); + goto out; + } + + a = a_j; + b = a_j + y_ij + 1; + z = t_i * (mu_ij + b_j); + + if (!tsd_valid_hyperu(a, b, z)) { + set_nan_one_node(logl, mn_j, va_j); + goto out; + } + + ret = tsd_hyperu_laplace(a, b, z, &f0, &d0); + if (ret != 0) { + goto out; + } + ret = tsd_hyperu_laplace(a + 1, b + 1, z, &f1, &d1); + if (ret != 0) { + goto out; + } + + *logl = f0 - mu_ij * t_i + (b - 1) * log(t_i) + lgamma(a); + *mn_j = -t_i * d0; + *va_j = (t_i * t_i) * d0 * (d1 - d0); +out: + return ret; +} + +/* ------------------------------------------------------------------------- * + * Node projections + * ------------------------------------------------------------------------- */ + +/* + * Project the moments of one marginal onto a gamma, writing its natural parameters to + * `proj`; if the moments are unusable, write a copy of `pars` instead and set + * `*usable` to 0. + */ +static int +project_moments(double mn, double va, const double pars[2], double proj[2], int *usable) +{ + int ret = 0; + + *usable = tsd_valid_moments(mn, va); + if (!*usable) { + proj[0] = pars[0]; + proj[1] = pars[1]; + goto out; + } + ret = tsd_approximate_gamma_mom(mn, va, proj); +out: + return ret; +} + +/* The projection of the two marginals of a two-parameter update; both are checked + * before either is projected. */ +static int +project_pair(double mn_i, double va_i, double mn_j, double va_j, const double pars_i[2], + const double pars_j[2], double *logl, double logl_value, double proj_i[2], + double proj_j[2]) +{ + int ret = 0; + int valid_i = tsd_valid_moments(mn_i, va_i); + int valid_j = tsd_valid_moments(mn_j, va_j); + + if (!(valid_i && valid_j)) { + *logl = NAN; + proj_i[0] = pars_i[0]; + proj_i[1] = pars_i[1]; + proj_j[0] = pars_j[0]; + proj_j[1] = pars_j[1]; + goto out; + } + ret = tsd_approximate_gamma_mom(mn_i, va_i, proj_i); + if (ret != 0) { + goto out; + } + ret = tsd_approximate_gamma_mom(mn_j, va_j, proj_j); + if (ret != 0) { + goto out; + } + *logl = logl_value; +out: + return ret; +} + +/* Project a single marginal; on unusable moments `*logl` is NaN. */ +static int +project_single(double mn, double va, const double pars[2], double logl_value, + double *logl, double proj[2]) +{ + int ret = 0; + int usable; + + ret = project_moments(mn, va, pars, proj, &usable); + if (ret != 0) { + goto out; + } + *logl = usable ? logl_value : NAN; +out: + return ret; +} + +int +tsd_gamma_projection(const double pars_i[2], const double pars_j[2], + const double pars_ij[2], double *logl, double proj_i[2], double proj_j[2]) +{ + int ret = 0; + double a_i = pars_i[0] + 1; + double b_i = pars_i[1]; + double a_j = pars_j[0] + 1; + double b_j = pars_j[1]; + double y_ij = pars_ij[0]; + double mu_ij = pars_ij[1]; + double logl_value, mn_i, va_i, mn_j, va_j; + + ret = tsd_moments( + a_i, b_i, a_j, b_j, y_ij, mu_ij, &logl_value, &mn_i, &va_i, &mn_j, &va_j); + if (ret != 0) { + goto out; + } + ret = project_pair( + mn_i, va_i, mn_j, va_j, pars_i, pars_j, logl, logl_value, proj_i, proj_j); +out: + return ret; +} + +int +tsd_leafward_projection(double t_i, const double pars_j[2], const double pars_ij[2], + double *logl, double proj_j[2]) +{ + int ret = 0; + double a_j = pars_j[0] + 1; + double b_j = pars_j[1]; + double y_ij = pars_ij[0]; + double mu_ij = pars_ij[1]; + double logl_value, mn_j, va_j; + + ret = tsd_leafward_moments(t_i, a_j, b_j, y_ij, mu_ij, &logl_value, &mn_j, &va_j); + if (ret != 0) { + goto out; + } + ret = project_single(mn_j, va_j, pars_j, logl_value, logl, proj_j); +out: + return ret; +} + +int +tsd_rootward_projection(double t_j, const double pars_i[2], const double pars_ij[2], + double *logl, double proj_i[2]) +{ + int ret = 0; + double a_i = pars_i[0] + 1; + double b_i = pars_i[1]; + double y_ij = pars_ij[0]; + double mu_ij = pars_ij[1]; + double logl_value, mn_i, va_i; + + ret = tsd_rootward_moments(t_j, a_i, b_i, y_ij, mu_ij, &logl_value, &mn_i, &va_i); + if (ret != 0) { + goto out; + } + ret = project_single(mn_i, va_i, pars_i, logl_value, logl, proj_i); +out: + return ret; +} + +int +tsd_unphased_projection(const double pars_i[2], const double pars_j[2], + const double pars_ij[2], double *logl, double proj_i[2], double proj_j[2]) +{ + int ret = 0; + double a_i = pars_i[0] + 1; + double b_i = pars_i[1]; + double a_j = pars_j[0] + 1; + double b_j = pars_j[1]; + double y_ij = pars_ij[0]; + double mu_ij = pars_ij[1]; + double logl_value, mn_i, va_i, mn_j, va_j; + + ret = tsd_unphased_moments( + a_i, b_i, a_j, b_j, y_ij, mu_ij, &logl_value, &mn_i, &va_i, &mn_j, &va_j); + if (ret != 0) { + goto out; + } + ret = project_pair( + mn_i, va_i, mn_j, va_j, pars_i, pars_j, logl, logl_value, proj_i, proj_j); +out: + return ret; +} + +int +tsd_twin_projection( + const double pars_i[2], const double pars_ij[2], double *logl, double proj_i[2]) +{ + int ret = 0; + double a_i = pars_i[0] + 1; + double b_i = pars_i[1]; + double y_ij = pars_ij[0]; + double mu_ij = pars_ij[1]; + double logl_value, mn_i, va_i; + + ret = tsd_twin_moments(a_i, b_i, y_ij, mu_ij, &logl_value, &mn_i, &va_i); + if (ret != 0) { + goto out; + } + ret = project_single(mn_i, va_i, pars_i, logl_value, logl, proj_i); +out: + return ret; +} + +int +tsd_sideways_projection(double t_i, const double pars_j[2], const double pars_ij[2], + double *logl, double proj_j[2]) +{ + int ret = 0; + double a_j = pars_j[0] + 1; + double b_j = pars_j[1]; + double y_ij = pars_ij[0]; + double mu_ij = pars_ij[1]; + double logl_value, mn_j, va_j; + + ret = tsd_sideways_moments(t_i, a_j, b_j, y_ij, mu_ij, &logl_value, &mn_j, &va_j); + if (ret != 0) { + goto out; + } + ret = project_single(mn_j, va_j, pars_j, logl_value, logl, proj_j); +out: + return ret; +} + +/* ------------------------------------------------------------------------- * + * Mutation moments + * ------------------------------------------------------------------------- */ + +/* + * Moments of the mutation age t_m. Conditional on the node ages, t_m is uniform on + * (t_j, t_i) for a phased edge; the moments are those of the EP surrogate density + * integrated over the node ages, in terms of hypergeometric functions. Arguments outside + * the domain give NaN, not an error. + */ +int +tsd_mutation_moments(double a_i, double b_i, double a_j, double b_j, double y_ij, + double mu_ij, double *mn_m, double *va_m) +{ + int ret = 0; + double a, b, c, t, z, s1, d1, d2, d3, sq_m; + double f000, f020, f111, f121, f222; + + a = a_j; + b = a_i + a_j + y_ij; + c = a_j + y_ij + 1; + t = mu_ij + b_i; + z = t > 0 ? (mu_ij - b_j) / t : NAN; + + if (!tsd_valid_hyp2f1(a, b, c, z)) { + *mn_m = NAN; + *va_m = NAN; + goto out; + } + + ret = tsd_hyp2f1_laplace(a + 0, b + 0, c + 0, z, &f000); + if (ret != 0) { + goto out; + } + ret = tsd_hyp2f1_laplace(a + 0, b + 2, c + 0, z, &f020); + if (ret != 0) { + goto out; + } + ret = tsd_hyp2f1_laplace(a + 1, b + 1, c + 1, z, &f111); + if (ret != 0) { + goto out; + } + ret = tsd_hyp2f1_laplace(a + 1, b + 2, c + 1, z, &f121); + if (ret != 0) { + goto out; + } + ret = tsd_hyp2f1_laplace(a + 2, b + 2, c + 2, z, &f222); + if (ret != 0) { + goto out; + } + + s1 = a * b / c; + d1 = b * (b + 1) / tsd_ipow(t, 2); + d2 = d1 * a / c; + d3 = d2 * (a + 1) / (c + 1); + + *mn_m = s1 * exp(f111 - f000) / t / 2 * (1 + z) + b / t / 2; + sq_m = d1 * exp(f020 - f000) / 3 + d2 * exp(f121 - f000) / 3 + + d3 * exp(f222 - f000) / 3; + *va_m = sq_m - tsd_ipow(*mn_m, 2); +out: + return ret; +} + +/* Moments of t_m given a fixed child age t_j: uniform on (t_j, t_i). */ +int +tsd_mutation_rootward_moments(double t_j, double a_i, double b_i, double y_ij, + double mu_ij, double *mn_m, double *va_m) +{ + int ret = 0; + double logl, mn_i, va_i, sq_m; + + ret = tsd_rootward_moments(t_j, a_i, b_i, y_ij, mu_ij, &logl, &mn_i, &va_i); + if (ret != 0) { + goto out; + } + *mn_m = mn_i / 2 + t_j / 2; + sq_m = (va_i + tsd_ipow(mn_i, 2) + mn_i * t_j + tsd_ipow(t_j, 2)) / 3; + *va_m = sq_m - tsd_ipow(*mn_m, 2); +out: + return ret; +} + +/* Moments of t_m given a fixed parent age t_i: uniform on (t_j, t_i). */ +int +tsd_mutation_leafward_moments(double t_i, double a_j, double b_j, double y_ij, + double mu_ij, double *mn_m, double *va_m) +{ + int ret = 0; + double logl, mn_j, va_j, sq_m; + + ret = tsd_leafward_moments(t_i, a_j, b_j, y_ij, mu_ij, &logl, &mn_j, &va_j); + if (ret != 0) { + goto out; + } + *mn_m = mn_j / 2 + t_i / 2; + sq_m = (va_j + tsd_ipow(mn_j, 2) + mn_j * t_i + tsd_ipow(t_i, 2)) / 3; + *va_m = sq_m - tsd_ipow(*mn_m, 2); +out: + return ret; +} + +/* + * Unphased edge: the mutation is under node i with probability t_i / (t_i + t_j), and + * uniform on (0, t_i) or (0, t_j). Integrating over the EP surrogate density gives + * hypergeometric functions with integer perturbations of a_i, a_j and y_ij. + */ +int +tsd_mutation_unphased_moments(double a_i, double b_i, double a_j, double b_j, + double y_ij, double mu_ij, double *pr_m, double *mn_m, double *va_m) +{ + int ret = 0; + double a, b, c, t, z, s0, s1, s2, d0, d1, d2, sq_m; + double f000, f001, f012, f023, f212, f323; + + a = a_j; + b = a_j + a_i + y_ij; + c = a_j + a_i; + t = mu_ij + b_i; + z = t > 0 ? (mu_ij + b_j) / t : NAN; + + if (!tsd_valid_hyp2f1(a, b, c, 1 - z)) { + *pr_m = NAN; + *mn_m = NAN; + *va_m = NAN; + goto out; + } + + ret = tsd_hyp2f1_laplace(a + 0, b + 0, c + 0, 1 - z, &f000); + if (ret != 0) { + goto out; + } + ret = tsd_hyp2f1_laplace(a + 0, b + 0, c + 1, 1 - z, &f001); + if (ret != 0) { + goto out; + } + ret = tsd_hyp2f1_laplace(a + 0, b + 1, c + 2, 1 - z, &f012); + if (ret != 0) { + goto out; + } + ret = tsd_hyp2f1_laplace(a + 0, b + 2, c + 3, 1 - z, &f023); + if (ret != 0) { + goto out; + } + ret = tsd_hyp2f1_laplace(a + 2, b + 1, c + 2, 1 - z, &f212); + if (ret != 0) { + goto out; + } + ret = tsd_hyp2f1_laplace(a + 3, b + 2, c + 3, 1 - z, &f323); + if (ret != 0) { + goto out; + } + + s0 = b / t / c / (c + 1); + s1 = (c - a) * (c - a + 1); + s2 = a * (a + 1); + d0 = s0 * (b + 1) / t / (c + 2); + d1 = s1 * (c - a + 2); + d2 = s2 * (a + 2); + + *mn_m = s0 * s1 * exp(f012 - f000) / 2 + s0 * s2 * exp(f212 - f000) / 2; + sq_m = d0 * d1 * exp(f023 - f000) / 3 + d0 * d2 * exp(f323 - f000) / 3; + *va_m = sq_m - tsd_ipow(*mn_m, 2); + *pr_m = (c - a) / c * exp(f001 - f000); +out: + return ret; +} + +/* Twin nodes (both parents are the same node): a closed form. */ +int +tsd_mutation_twin_moments(double a_i, double b_i, double y_ij, double mu_ij, + double *pr_m, double *mn_m, double *va_m) +{ + int ret = 0; + double s, r, r_sq, sq_m; + + s = a_i + y_ij; + r = b_i + 2 * mu_ij; + r_sq = tsd_ipow(r, 2); + if (r_sq == 0.0) { + /* r is zero or its square underflows */ + ret = tsd_trace_error(TSD_ERR_ZERO_DIVISION); + goto out; + } + *pr_m = 0.5; + *mn_m = s / r / 2; + sq_m = (s + 1) * s / 3 / r_sq; + *va_m = sq_m - tsd_ipow(*mn_m, 2); +out: + return ret; +} + +/* Unphased edge with a fixed parent age t_i, in terms of Tricomi functions. */ +int +tsd_mutation_sideways_moments(double t_i, double a_j, double b_j, double y_ij, + double mu_ij, double *pr_m, double *mn_m, double *va_m) +{ + int ret = 0; + double a, b, z, sq_m; + double f00, d00, f10, d10, f21, d21, f32, d32; + + if (!(t_i > 0)) { + ret = tsd_trace_error(TSD_ERR_INVALID_FIXED_AGE); + goto out; + } + + a = a_j; + b = a_j + y_ij + 1; + z = t_i * (mu_ij + b_j); + + if (!tsd_valid_hyperu(a, b, z)) { + *pr_m = NAN; + *mn_m = NAN; + *va_m = NAN; + goto out; + } + + ret = tsd_hyperu_laplace(a + 0, b + 0, z, &f00, &d00); + if (ret != 0) { + goto out; + } + ret = tsd_hyperu_laplace(a + 1, b + 0, z, &f10, &d10); + if (ret != 0) { + goto out; + } + ret = tsd_hyperu_laplace(a + 2, b + 1, z, &f21, &d21); + if (ret != 0) { + goto out; + } + ret = tsd_hyperu_laplace(a + 3, b + 2, z, &f32, &d32); + if (ret != 0) { + goto out; + } + + *pr_m = 1.0 - exp(f10 - f00) * a; + *mn_m = *pr_m * t_i / 2 + t_i * exp(f21 - f00) * a * (a + 1) / 2; + sq_m = *pr_m * tsd_ipow(t_i, 2) / 3 + + tsd_ipow(t_i, 2) * exp(f32 - f00) * a * (a + 1) * (a + 2) / 3; + *va_m = sq_m - tsd_ipow(*mn_m, 2); +out: + return ret; +} + +/* Both node ages fixed and phased: t_m is uniform on (t_j, t_i). */ +int +tsd_mutation_edge_moments(double t_i, double t_j, double *mn_m, double *va_m) +{ + *mn_m = 1.0 / 2 * (t_i + t_j); + *va_m = 1.0 / 12 * tsd_ipow(t_i - t_j, 2); + return 0; +} + +/* Both node ages fixed and unphased: t_m is uniform on (0, t_i) or (0, t_j). */ +int +tsd_mutation_block_moments( + double t_i, double t_j, double *pr_m, double *mn_m, double *va_m) +{ + int ret = 0; + double sq_m; + + if (!(t_i > 0) || !(t_j > 0)) { + ret = tsd_trace_error(TSD_ERR_INVALID_FIXED_AGE); + goto out; + } + *pr_m = t_i / (t_i + t_j); + *mn_m = *pr_m * t_i / 2 + (1 - *pr_m) * t_j / 2; + sq_m = *pr_m * tsd_ipow(t_i, 2) / 3 + (1 - *pr_m) * tsd_ipow(t_j, 2) / 3; + *va_m = sq_m - tsd_ipow(*mn_m, 2); +out: + return ret; +} + +/* ------------------------------------------------------------------------- * + * Mutation projections + * ------------------------------------------------------------------------- */ + +/* Set the outputs of a projection whose moments are unusable: NaN, in-band. */ +static void +mutation_projection_invalid(double *pr_m, double proj_m[2]) +{ + *pr_m = NAN; + proj_m[0] = NAN; + proj_m[1] = NAN; +} + +/* + * The gamma matching the mean and variance of the mutation age, with phase + * probability `pr`; NaN outputs if the moments are not usable. Phase probabilities + * outside [0, 1] (or NaN) are unusable when `check_pr` is set. + */ +static int +mutation_project_moments( + double pr, int check_pr, double mn_m, double va_m, double *pr_m, double proj_m[2]) +{ + int ret = 0; + int usable = tsd_valid_moments(mn_m, va_m); + + if (check_pr && !(pr >= 0.0 && pr <= 1.0)) { + usable = 0; + } + if (!usable) { + mutation_projection_invalid(pr_m, proj_m); + goto out; + } + ret = tsd_approximate_gamma_mom(mn_m, va_m, proj_m); + if (ret != 0) { + goto out; + } + *pr_m = pr; +out: + return ret; +} + +int +tsd_mutation_gamma_projection(const double pars_i[2], const double pars_j[2], + const double pars_ij[2], double *pr_m, double proj_m[2]) +{ + int ret = 0; + double mn_m, va_m; + const double a_i = pars_i[0] + 1; + const double a_j = pars_j[0] + 1; + + ret = tsd_mutation_moments( + a_i, pars_i[1], a_j, pars_j[1], pars_ij[0], pars_ij[1], &mn_m, &va_m); + if (ret != 0) { + goto out; + } + ret = mutation_project_moments(1.0, 0, mn_m, va_m, pr_m, proj_m); +out: + return ret; +} + +int +tsd_mutation_leafward_projection(double t_i, const double pars_j[2], + const double pars_ij[2], double *pr_m, double proj_m[2]) +{ + int ret = 0; + double mn_m, va_m; + const double a_j = pars_j[0] + 1; + + ret = tsd_mutation_leafward_moments( + t_i, a_j, pars_j[1], pars_ij[0], pars_ij[1], &mn_m, &va_m); + if (ret != 0) { + goto out; + } + ret = mutation_project_moments(1.0, 0, mn_m, va_m, pr_m, proj_m); +out: + return ret; +} + +int +tsd_mutation_rootward_projection(double t_j, const double pars_i[2], + const double pars_ij[2], double *pr_m, double proj_m[2]) +{ + int ret = 0; + double mn_m, va_m; + const double a_i = pars_i[0] + 1; + + ret = tsd_mutation_rootward_moments( + t_j, a_i, pars_i[1], pars_ij[0], pars_ij[1], &mn_m, &va_m); + if (ret != 0) { + goto out; + } + ret = mutation_project_moments(1.0, 0, mn_m, va_m, pr_m, proj_m); +out: + return ret; +} + +int +tsd_mutation_edge_projection(double t_i, double t_j, double *pr_m, double proj_m[2]) +{ + int ret = 0; + double mn_m, va_m; + + ret = tsd_mutation_edge_moments(t_i, t_j, &mn_m, &va_m); + if (ret != 0) { + goto out; + } + ret = mutation_project_moments(1.0, 0, mn_m, va_m, pr_m, proj_m); +out: + return ret; +} + +int +tsd_mutation_unphased_projection(const double pars_i[2], const double pars_j[2], + const double pars_ij[2], double *pr_m, double proj_m[2]) +{ + int ret = 0; + double pr, mn_m, va_m; + const double a_i = pars_i[0] + 1; + const double a_j = pars_j[0] + 1; + + ret = tsd_mutation_unphased_moments( + a_i, pars_i[1], a_j, pars_j[1], pars_ij[0], pars_ij[1], &pr, &mn_m, &va_m); + if (ret != 0) { + goto out; + } + ret = mutation_project_moments(pr, 1, mn_m, va_m, pr_m, proj_m); +out: + return ret; +} + +int +tsd_mutation_twin_projection( + const double pars_i[2], const double pars_ij[2], double *pr_m, double proj_m[2]) +{ + int ret = 0; + double pr, mn_m, va_m; + const double a_i = pars_i[0] + 1; + + ret = tsd_mutation_twin_moments( + a_i, pars_i[1], pars_ij[0], pars_ij[1], &pr, &mn_m, &va_m); + if (ret != 0) { + goto out; + } + ret = mutation_project_moments(pr, 1, mn_m, va_m, pr_m, proj_m); +out: + return ret; +} + +int +tsd_mutation_sideways_projection(double t_i, const double pars_j[2], + const double pars_ij[2], double *pr_m, double proj_m[2]) +{ + int ret = 0; + double pr, mn_m, va_m; + const double a_j = pars_j[0] + 1; + + ret = tsd_mutation_sideways_moments( + t_i, a_j, pars_j[1], pars_ij[0], pars_ij[1], &pr, &mn_m, &va_m); + if (ret != 0) { + goto out; + } + ret = mutation_project_moments(pr, 1, mn_m, va_m, pr_m, proj_m); +out: + return ret; +} + +int +tsd_mutation_block_projection(double t_i, double t_j, double *pr_m, double proj_m[2]) +{ + int ret = 0; + double pr, mn_m, va_m; + + ret = tsd_mutation_block_moments(t_i, t_j, &pr, &mn_m, &va_m); + if (ret != 0) { + goto out; + } + ret = mutation_project_moments(pr, 1, mn_m, va_m, pr_m, proj_m); +out: + return ret; +} diff --git a/lib/err.c b/lib/err.c index 7d241c75..b3bc132a 100644 --- a/lib/err.c +++ b/lib/err.c @@ -44,6 +44,130 @@ tsd_strerror(int err) case TSD_ERR_BAD_PARAM: ret = "Bad parameter value provided"; break; + case TSD_ERR_ZERO_DIVISION: + ret = "Floating-point division by zero"; + break; + case TSD_ERR_INVALID_HYPERGEO: + ret = "Parameters outside the domain of the hypergeometric function"; + break; + case TSD_ERR_NONPOSITIVE_OR_NONFINITE_MOMENTS: + ret = "Nonpositive or nonfinite moments"; + break; + case TSD_ERR_JENSEN_VIOLATION: + ret = "log E[t] <= E[log t] violates Jensen's inequality"; + break; + case TSD_ERR_KL_MAX_ITERATIONS: + ret = "Maximum iterations reached in KL minimization"; + break; + case TSD_ERR_KL_INVALID_SHAPE: + ret = "Invalid shape parameter in KL minimization"; + break; + case TSD_ERR_NONPOSITIVE_CENTRAL_MOMENTS: + ret = "Nonpositive central moments"; + break; + case TSD_ERR_UNSORTED_QUANTILES: + ret = "Quantiles must be sorted"; + break; + case TSD_ERR_QUANTILE_MAX_ITERATIONS: + ret = "Maximum iterations reached in quantile matching"; + break; + case TSD_ERR_NEGATIVE_SHAPE: + ret = "Negative shape parameter"; + break; + case TSD_ERR_NONPOSITIVE_MOMENTS: + ret = "The mean and variance must be positive"; + break; + case TSD_ERR_INVALID_FIXED_AGE: + ret = "The age of a fixed node is outside the domain of the function"; + break; + case TSD_ERR_UNPHASED_INDIVIDUAL_EDGES: + ret = "An unphased individual does not have exactly two edges over each " + "of its blocks"; + break; + case TSD_ERR_BLOCK_OUT_OF_BOUNDS: + ret = "Block id, or an edge of a block, out of bounds"; + break; + case TSD_ERR_PHASE_OUT_OF_RANGE: + ret = "The phase of a mutation is not between zero and one"; + break; + case TSD_ERR_UNPHASED_LIKELIHOOD_NOT_CONSERVED: + ret = "The total likelihood of the unphased edges is not conserved"; + break; + case TSD_ERR_MUTATION_NODE_NOT_IN_TREE: + ret = "A mutation is above a node that is not in any tree before it"; + break; + case TSD_ERR_FIXED_NODES_VIOLATE_CONSTRAINT: + ret = "An edge between two fixed nodes violates the age constraint"; + break; + case TSD_ERR_NONPOSITIVE_INTERVALS: + ret = "The number of intervals must be positive"; + break; + case TSD_ERR_ZERO_EDGE_SPAN: + ret = "Zero edge span in interval"; + break; + case TSD_ERR_NON_INCREASING_BREAKPOINTS: + ret = "Rescaling produced non-increasing time breakpoints. " + "Try setting `rescaling_intervals` to a smaller value " + "(e.g. half its current value)."; + break; + case TSD_ERR_INVALID_QUANTILE_WIDTH: + ret = "The quantile width must be greater than zero and less than one"; + break; + case TSD_ERR_INVALID_POSTERIOR: + ret = "A posterior to be rescaled has shape not greater than -1 or rate " + "not greater than zero"; + break; + case TSD_ERR_TIME_BELOW_FIRST_BREAKPOINT: + ret = "A time to be rescaled is below the first time breakpoint"; + break; + case TSD_ERR_NO_POSTERIORS: + ret = "zero-size array to reduction operation minimum which has no " + "identity"; + break; + case TSD_ERR_INVALID_MAX_SHAPE: + ret = "The maximum shape must be at least one"; + break; + case TSD_ERR_INVALID_MIN_STEP: + ret = "The minimum step size must be greater than zero and less than one"; + break; + case TSD_ERR_INVALID_NODE_POSTERIOR: + ret = "A node posterior has shape not greater than -1 or rate not greater " + "than zero"; + break; + case TSD_ERR_INVALID_DAMPING: + ret = "The damping factor is not greater than zero and at most one"; + break; + case TSD_ERR_TWIN_EDGE_IN_PHASED_PASS: + ret = "An edge with the same parent and child can only be updated in an " + "unphased pass"; + break; + case TSD_ERR_NONPOSITIVE_PENALTY: + ret = "The fitted regularisation penalty is not positive"; + break; + case TSD_ERR_NODE_OUT_OF_BOUNDS: + ret = "Node id out of bounds"; + break; + case TSD_ERR_EDGE_OUT_OF_BOUNDS: + ret = "Edge id out of bounds"; + break; + case TSD_ERR_INDIVIDUAL_OUT_OF_BOUNDS: + ret = "Individual id out of bounds"; + break; + case TSD_ERR_BAD_EDGE_INTERVAL: + ret = "Edge interval is empty or outside [0, sequence_length]"; + break; + case TSD_ERR_BAD_EDGE_INDEXES: + ret = "Edge indexes must list every edge once, in order of position"; + break; + case TSD_ERR_EDGES_FORM_CYCLE: + ret = "Edges form a cycle"; + break; + case TSD_ERR_TOO_FEW_TIPS: + ret = "Too few tips"; + break; + case TSD_ERR_NO_BREAKPOINTS: + ret = "No breakpoints"; + break; default: break; } diff --git a/lib/err.h b/lib/err.h index 294c9ebf..b164fb6b 100644 --- a/lib/err.h +++ b/lib/err.h @@ -25,10 +25,6 @@ #ifndef TSD_ERR_H #define TSD_ERR_H -#ifdef __cplusplus -extern "C" { -#endif - #include #include @@ -36,17 +32,63 @@ extern "C" { #define TSD_ERR_GENERIC -1 #define TSD_ERR_NO_MEMORY -2 #define TSD_ERR_BAD_PARAM -3 -/* clang-format on */ -#ifdef __GNUC__ -#define WARN_UNUSED __attribute__((warn_unused_result)) -#define unlikely(expr) __builtin_expect(!!(expr), 0) -#define likely(expr) __builtin_expect(!!(expr), 1) -#else -#define WARN_UNUSED -#define unlikely(expr) (expr) -#define likely(expr) (expr) -#endif +/* Floating-point division by zero */ +#define TSD_ERR_ZERO_DIVISION -4 + +/* hypergeo */ +#define TSD_ERR_INVALID_HYPERGEO -5 + +/* approx: failures of the gamma approximations */ +#define TSD_ERR_NONPOSITIVE_OR_NONFINITE_MOMENTS -6 +#define TSD_ERR_JENSEN_VIOLATION -7 +#define TSD_ERR_KL_MAX_ITERATIONS -8 +#define TSD_ERR_KL_INVALID_SHAPE -9 +#define TSD_ERR_NONPOSITIVE_CENTRAL_MOMENTS -10 +#define TSD_ERR_UNSORTED_QUANTILES -11 +#define TSD_ERR_QUANTILE_MAX_ITERATIONS -12 +#define TSD_ERR_NEGATIVE_SHAPE -13 +/* approx: violated preconditions */ +#define TSD_ERR_NONPOSITIVE_MOMENTS -14 +#define TSD_ERR_INVALID_FIXED_AGE -15 + +/* phasing */ +#define TSD_ERR_UNPHASED_INDIVIDUAL_EDGES -16 +#define TSD_ERR_BLOCK_OUT_OF_BOUNDS -17 +#define TSD_ERR_PHASE_OUT_OF_RANGE -18 +#define TSD_ERR_UNPHASED_LIKELIHOOD_NOT_CONSERVED -19 + +/* util */ +#define TSD_ERR_MUTATION_NODE_NOT_IN_TREE -20 +#define TSD_ERR_FIXED_NODES_VIOLATE_CONSTRAINT -21 + +/* rescaling */ +#define TSD_ERR_NONPOSITIVE_INTERVALS -22 +#define TSD_ERR_ZERO_EDGE_SPAN -24 +#define TSD_ERR_NON_INCREASING_BREAKPOINTS -25 +#define TSD_ERR_INVALID_QUANTILE_WIDTH -26 +#define TSD_ERR_INVALID_POSTERIOR -27 +#define TSD_ERR_TIME_BELOW_FIRST_BREAKPOINT -28 +#define TSD_ERR_NO_POSTERIORS -29 + +/* variational */ +#define TSD_ERR_INVALID_MAX_SHAPE -30 +#define TSD_ERR_INVALID_MIN_STEP -31 +#define TSD_ERR_INVALID_NODE_POSTERIOR -32 +#define TSD_ERR_INVALID_DAMPING -33 +#define TSD_ERR_TWIN_EDGE_IN_PHASED_PASS -34 +#define TSD_ERR_NONPOSITIVE_PENALTY -35 + +/* Arguments that a caller can get wrong */ +#define TSD_ERR_NODE_OUT_OF_BOUNDS -36 +#define TSD_ERR_EDGE_OUT_OF_BOUNDS -37 +#define TSD_ERR_INDIVIDUAL_OUT_OF_BOUNDS -38 +#define TSD_ERR_BAD_EDGE_INTERVAL -39 +#define TSD_ERR_BAD_EDGE_INDEXES -40 +#define TSD_ERR_EDGES_FORM_CYCLE -41 +#define TSD_ERR_TOO_FEW_TIPS -42 +#define TSD_ERR_NO_BREAKPOINTS -43 +/* clang-format on */ const char *tsd_strerror(int err); @@ -82,8 +124,4 @@ _tsd_trace_error(int err, int line, const char *file) void _tsd_safe_free(void **ptr); #define tsd_safe_free(pointer) _tsd_safe_free((void **) &(pointer)) -#ifdef __cplusplus -} -#endif - #endif diff --git a/lib/gammaincinv.c b/lib/gammaincinv.c new file mode 100644 index 00000000..58de06be --- /dev/null +++ b/lib/gammaincinv.c @@ -0,0 +1,1477 @@ +/* + * The inverse of the regularised lower incomplete gamma function, tsd_gammaincinv. + * + * This is a C translation of the double precision igami() of the xsf library + * (https://github.com/scipy/xsf, commit f7b85f505a94fd398024478d2e747b01dd2d7a6d), + * which is scipy.special.gammaincinv, together with the functions it reaches, from + * include/xsf/cephes/: igami.h (igami, igamci, find_inverse_gamma, find_inverse_s, + * didonato_SN), igam.h (igam, igamc, igam_fac, igam_series, igamc_series, + * igamc_continued_fraction, asymptotic_series), igam_asymp_coeff.h, gamma.h (Gamma, + * lgam, lgam_large_x), lanczos.h (lanczos_sum_expg_scaled), unity.h (log1p, + * log1pmx, expm1, lgam1p, lgam1p_taylor), zeta.h (zeta), ndtr.h (erf, erfc), + * polevl.h (polevl, p1evl, ratevl) and const.h. The operations, constants, branches + * and iteration limits are those of xsf. Arguments outside the domain give NaN + * directly, and the helper functions keep only the branches that the arguments they + * receive can reach; error reporting (set_error, a no-op in xsf's default build) is + * dropped and the in-band return values are kept. Branches marked GCOVR_EXCL are + * kept unmodified from xsf although valid arguments do not reach them (none of 20 + * million random draws did), so the tests do not cover them. + * + * The notices of the original files and the licences they are distributed under + * follow. + * + * ---------------------------------------------------------------------------- + * + * xsf: Copyright (c) 2024, SciPy. Translated into C++ by SciPy developers in 2024. + * + * Cephes Math Library (igam, gamma, lgam, polevl, zeta, ndtr, const): + * Copyright 1984, 1985, 1987, 1988, 1989, 1992, 1995 by Stephen L. Moshier. + * Cephes is distributed under the BSD 3-Clause License below with the permission + * of the author. + * + * igami.h (the Didonato and Morris initial approximation and the Halley iteration) + * and lanczos.h: (C) Copyright John Maddock 2006. Use, modification and + * distribution are subject to the Boost Software License, Version 1.0, below. + * + * ---------------------------------------------------------------------------- + * + * BSD 3-Clause License + * + * Copyright (c) 2024, SciPy + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions are met: + * + * 1. Redistributions of source code must retain the above copyright notice, this + * list of conditions and the following disclaimer. + * + * 2. Redistributions in binary form must reproduce the above copyright notice, + * this list of conditions and the following disclaimer in the documentation + * and/or other materials provided with the distribution. + * + * 3. Neither the name of the copyright holder nor the names of its + * contributors may be used to endorse or promote products derived from + * this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE + * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE + * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL + * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR + * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER + * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, + * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE + * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + * + * ---------------------------------------------------------------------------- + * + * Boost Software License - Version 1.0 - August 17th, 2003 + * + * Permission is hereby granted, free of charge, to any person or organization + * obtaining a copy of the software and accompanying documentation covered by + * this license (the "Software") to use, reproduce, display, distribute, + * execute, and transmit the Software, and to prepare derivative works of the + * Software, and to permit third-parties to whom the Software is furnished to + * do so, all subject to the following: + * + * The copyright notices in the Software and this entire statement, including + * the above license grant, this restriction and the following disclaimer, + * must be included in all copies of the Software, in whole or in part, and + * all derivative works of the Software, unless such copies or derivative + * works are solely in the form of machine-executable object code generated by + * a source language processor. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE, TITLE AND NON-INFRINGEMENT. IN NO EVENT + * SHALL THE COPYRIGHT HOLDERS OR ANYONE DISTRIBUTING THE SOFTWARE BE LIABLE + * FOR ANY DAMAGES OR OTHER LIABILITY, WHETHER IN CONTRACT, TORT OR OTHERWISE, + * ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER + * DEALINGS IN THE SOFTWARE. + */ + +#include +#include + +#include "tsdate.h" + +/* const.h, and the constants that MSVC does not define by default. */ +#define CEPH_MAXITER 500 +#define CEPH_MACHEP 1.1102230246251565404236316680908203125E-16 +#define CEPH_MAXLOG 7.097827128933839730962063185871E2 +#define CEPH_SCIPY_EULER 0.577215664901532860606512090082402431 +#define CEPH_PI 3.14159265358979323846 +#define CEPH_SQRT2 1.41421356237309504880 +#define CEPH_SQRT1_2 0.707106781186547524401 + +/* polevl.h */ + +static double +ceph_polevl(double x, const double coef[], int N) +{ + double ans; + int i; + const double *p; + + p = coef; + ans = *p++; + i = N; + + do { + ans = ans * x + *p++; + } while (--i); + + return ans; +} + +static double +ceph_p1evl(double x, const double coef[], int N) +{ + double ans; + const double *p; + int i; + + p = coef; + ans = x + *p++; + i = N - 1; + + do { + ans = ans * x + *p++; + } while (--i); + + return ans; +} + +static double +ceph_ratevl(double x, const double num[], int M, const double denom[], int N) +{ + int i, dir; + double y, num_ans, denom_ans; + double absx = fabs(x); + const double *p; + + if (absx > 1) { + /* Evaluate as a polynomial in 1/x. */ + dir = -1; + p = num + M; + y = 1 / x; + } else { + dir = 1; + p = num; + y = x; + } + + /* Evaluate the numerator */ + num_ans = *p; + p += dir; + for (i = 1; i <= M; i++) { + num_ans = num_ans * y + *p; + p += dir; + } + + /* Evaluate the denominator */ + if (absx > 1) { + p = denom + N; + } else { + p = denom; + } + + denom_ans = *p; + p += dir; + for (i = 1; i <= N; i++) { + denom_ans = denom_ans * y + *p; + p += dir; + } + + if (absx > 1) { + i = M - N; + return pow(x, i) * num_ans / denom_ans; + } else { + return num_ans / denom_ans; + } +} + +/* gamma.h */ + +static const double gamma_P[] = { 1.60119522476751861407E-4, 1.19135147006586384913E-3, + 1.04213797561761569935E-2, 4.76367800457137231464E-2, 2.07448227648435975150E-1, + 4.94214826801497100753E-1, 9.99999999999999996796E-1 }; + +static const double gamma_Q[] = { -2.31581873324120129819E-5, 5.39605580493303397842E-4, + -4.45641913851797240494E-3, 1.18139785222060435552E-2, 3.58236398605498653373E-2, + -2.34591795718243348568E-1, 7.14304917030273074085E-2, 1.00000000000000000320E0 }; + +/* The Gamma function for 0 < x < 1, the only arguments it receives. */ +static double +ceph_Gamma(double x) +{ + double p, q, z; + + z = 1.0; + while (x < 2.0) { + if (x < 1.e-9) { + return z / ((1.0 + 0.5772156649015329 * x) * x); + } + z /= x; + x += 1.0; + } + + if (x == 2.0) { + return z; + } + + x -= 2.0; + p = ceph_polevl(x, gamma_P, 6); + q = ceph_polevl(x, gamma_Q, 7); + return z * p / q; +} + +/* A[]: Stirling's formula expansion of log Gamma + * B[], C[]: log Gamma function between 2 and 3 + */ +static const double gamma_A[] = { 8.11614167470508450300E-4, -5.95061904284301438324E-4, + 7.93650340457716943945E-4, -2.77777777730099687205E-3, 8.33333333333331927722E-2 }; + +static const double gamma_B[] = { -1.37825152569120859100E3, -3.88016315134637840924E4, + -3.31612992738871184744E5, -1.16237097492762307383E6, -1.72173700820839662146E6, + -8.53555664245765465627E5 }; + +static const double gamma_C[] = { /* 1.00000000000000000000E0, */ + -3.51815701436523470549E2, -1.70642106651881159223E4, -2.20528590553854454839E5, + -1.13933444367982507207E6, -2.53252307177582951285E6, -2.01889141433532773231E6 +}; + +/* log( sqrt( 2*pi ) ) */ +#define GAMMA_LS2PI 0.91893853320467274178 +#define GAMMA_MAXLGM 2.556348e305 + +static double +ceph_lgam_large_x(double x) +{ + double q = (x - 0.5) * log(x) - x + GAMMA_LS2PI; + double p; + + if (x > 1.0e8) { + return q; /* GCOVR_EXCL_LINE */ + } + p = 1.0 / (x * x); + p = ((7.9365079365079365079365e-4 * p - 2.7777777777777777777778e-3) * p + + 0.0833333333333333333333) + / x; + return q + p; +} + +/* Logarithm of the Gamma function for positive finite x, the only arguments it + * receives. */ +static double +ceph_lgam(double x) +{ + double p, q, u, z; + + if (x < 13.0) { + z = 1.0; + p = 0.0; + u = x; + while (u >= 3.0) { + p -= 1.0; + u = x + p; + z *= u; + } + while (u < 2.0) { + z /= u; + p += 1.0; + u = x + p; + } + if (u == 2.0) { + return log(z); + } + p -= 2.0; + x = x + p; + p = x * ceph_polevl(x, gamma_B, 5) / ceph_p1evl(x, gamma_C, 6); + return log(z) + p; + } + + if (x > GAMMA_MAXLGM) { + return INFINITY; /* GCOVR_EXCL_LINE */ + } + + if (x >= 1000.0) { + return ceph_lgam_large_x(x); + } + + q = (x - 0.5) * log(x) - x + GAMMA_LS2PI; + p = 1.0 / (x * x); + return q + ceph_polevl(p, gamma_A, 4) / x; +} + +/* lanczos.h */ + +static const double lanczos_sum_expg_scaled_num[] = { + 0.006061842346248906525783753964555936883222, + 0.5098416655656676188125178644804694509993, + 19.51992788247617482847860966235652136208, + 449.9445569063168119446858607650988409623, + 6955.999602515376140356310115515198987526, + 75999.29304014542649875303443598909137092, + 601859.6171681098786670226533699352302507, + 3481712.15498064590882071018964774556468, + 14605578.08768506808414169982791359218571, + 43338889.32467613834773723740590533316085, + 86363131.28813859145546927288977868422342, + 103794043.1163445451906271053616070238554, + 56906521.91347156388090791033559122686859, +}; + +static const double lanczos_sum_expg_scaled_denom[] = { 1, 66, 1925, 32670, 357423, + 2637558, 13339535, 45995730, 105258076, 150917976, 120543840, 39916800, 0 }; + +#define LANCZOS_G 6.024680040776729583740234375 + +static double +ceph_lanczos_sum_expg_scaled(double x) +{ + return ceph_ratevl( + x, lanczos_sum_expg_scaled_num, 12, lanczos_sum_expg_scaled_denom, 12); +} + +/* unity.h */ + +/* Coefficients for log(1+x) = x - x**2/2 + x**3 P(x)/Q(x) + * 1/sqrt(2) <= x < sqrt(2) + * Theoretical peak relative error = 2.32e-20 + */ +static const double unity_LP[] = { + 4.5270000862445199635215E-5, + 4.9854102823193375972212E-1, + 6.5787325942061044846969E0, + 2.9911919328553073277375E1, + 6.0949667980987787057556E1, + 5.7112963590585538103336E1, + 2.0039553499201281259648E1, +}; + +static const double unity_LQ[] = { + /* 1.0000000000000000000000E0, */ + 1.5062909083469192043167E1, + 8.3047565967967209469434E1, + 2.2176239823732856465394E2, + 3.0909872225312059774938E2, + 2.1642788614495947685003E2, + 6.0118660497603843919306E1, +}; + +static double +ceph_log1p(double x) +{ + double z; + + z = 1.0 + x; + if ((z < CEPH_SQRT1_2) || (z > CEPH_SQRT2)) { + return log(z); /* GCOVR_EXCL_LINE */ + } + z = x * x; + z = -0.5 * z + x * (z * ceph_polevl(x, unity_LP, 6) / ceph_p1evl(x, unity_LQ, 6)); + return x + z; +} + +/* log(1 + x) - x */ +static double +ceph_log1pmx(double x) +{ + uint64_t n; + double xfac, term, res; + + if (fabs(x) < 0.5) { + xfac = x; + res = 0; + for (n = 2; n < CEPH_MAXITER; n++) { + xfac *= -x; + term = xfac / (double) n; + res += term; + if (fabs(term) < CEPH_MACHEP * fabs(res)) { + break; + } + } + return res; + } else { + return ceph_log1p(x) - x; + } +} + +/* e^x = 1 + 2x P(x^2)/( Q(x^2) - P(x^2) ) + * -0.5 <= x <= 0.5 + */ +static const double unity_EP[3] = { + 1.2617719307481059087798E-4, + 3.0299440770744196129956E-2, + 9.9999999999999999991025E-1, +}; + +static const double unity_EQ[4] = { + 3.0019850513866445504159E-6, + 2.5244834034968410419224E-3, + 2.2726554820815502876593E-1, + 2.0000000000000000000897E0, +}; + +static double +ceph_expm1(double x) +{ + double r, xx; + + /* GCOVR_EXCL_START */ + if (!isfinite(x)) { + if (isnan(x)) { + return x; + } else if (x > 0) { + return x; + } else { + return -1.0; + } + } + /* GCOVR_EXCL_STOP */ + if ((x < -0.5) || (x > 0.5)) { + return exp(x) - 1.0; /* GCOVR_EXCL_LINE */ + } + xx = x * x; + r = x * ceph_polevl(xx, unity_EP, 2); + r = r / (ceph_polevl(xx, unity_EQ, 3) - r); + return r + r; +} + +/* zeta.h */ + +/* Expansion coefficients + * for Euler-Maclaurin summation formula + * (2k)! / B2k + * where B2k are Bernoulli numbers + */ +static const double zeta_A[] = { + 12.0, -720.0, 30240.0, -1209600.0, 47900160.0, + -1.8924375803183791606e9, /*1.307674368e12/691 */ + 7.47242496e10, -2.950130727918164224e12, /*1.067062284288e16/3617 */ + 1.1646782814350067249e14, /*5.109094217170944e18/43867 */ + -4.5979787224074726105e15, /*8.028576626982912e20/174611 */ + 1.8152105401943546773e17, /*1.5511210043330985984e23/854513 */ + -7.1661652561756670113e18 /*1.6938241367317436694528e27/236364091 */ +}; + +/* The Hurwitz zeta function. Its only caller, ceph_lgam1p_taylor, passes an integer + * x >= 2 and q = 1, so the branches of zeta() for x <= 1, q <= 0 and q > 1e8 are + * omitted. */ +static double +ceph_zeta(double x, double q) +{ + int i; + double a, b, k, s, t, w; + + /* Euler-Maclaurin summation formula */ + s = pow(q, -x); + a = q; + i = 0; + b = 0.0; + while ((i < 9) || (a <= 9.0)) { + i += 1; + a += 1.0; + b = pow(a, -x); + s += b; + if (fabs(b / s) < CEPH_MACHEP) { + goto done; + } + } + + w = a; + s += b * w / (x - 1.0); + s -= 0.5 * b; + a = 1.0; + k = 0.0; + for (i = 0; i < 12; i++) { + a *= x + k; + b /= w; + t = a * b / zeta_A[i]; + s = s + t; + t = fabs(t / s); + if (t < CEPH_MACHEP) { + goto done; + } + k += 1.0; + a *= x + k; + b /= w; + k += 1.0; + } +done: /* GCOVR_EXCL_LINE: reached, but gcov counts no execution of the label */ + return s; +} + +/* Compute lgam(x + 1) around x = 0 using its Taylor series. */ +static double +ceph_lgam1p_taylor(double x) +{ + int n; + double xfac, coeff, res; + + if (x == 0) { + return 0; + } + res = -CEPH_SCIPY_EULER * x; + xfac = -x; + for (n = 2; n < 42; n++) { + xfac *= -x; + coeff = ceph_zeta(n, 1) * xfac / n; + res += coeff; + if (fabs(coeff) < CEPH_MACHEP * fabs(res)) { + break; + } + } + + return res; +} + +/* Compute lgam(x + 1). */ +static double +ceph_lgam1p(double x) +{ + if (fabs(x) <= 0.5) { + return ceph_lgam1p_taylor(x); + } else if (fabs(x - 1) < 0.5) { + return log(x) + ceph_lgam1p_taylor(x - 1); + } else { + return ceph_lgam(x + 1); /* GCOVR_EXCL_LINE */ + } +} + +/* ndtr.h */ + +static const double ndtr_P[] + = { 2.46196981473530512524E-10, 5.64189564831068821977E-1, 7.46321056442269912687E0, + 4.86371970985681366614E1, 1.96520832956077098242E2, 5.26445194995477358631E2, + 9.34528527171957607540E2, 1.02755188689515710272E3, 5.57535335369399327526E2 }; + +static const double ndtr_Q[] = { /* 1.00000000000000000000E0, */ + 1.32281951154744992508E1, 8.67072140885989742329E1, 3.54937778887819891062E2, + 9.75708501743205489753E2, 1.82390916687909736289E3, 2.24633760818710981792E3, + 1.65666309194161350182E3, 5.57535340817727675546E2 +}; + +static const double ndtr_R[] + = { 5.64189583547755073984E-1, 1.27536670759978104416E0, 5.01905042251180477414E0, + 6.16021097993053585195E0, 7.40974269950448939160E0, 2.97886665372100240670E0 }; + +static const double ndtr_S[] = { /* 1.00000000000000000000E0, */ + 2.26052863220117276590E0, 9.39603524938001434673E0, 1.20489539808096656605E1, + 1.70814450747565897222E1, 9.60896809063285878198E0, 3.36907645100081516050E0 +}; + +static const double ndtr_T[] = { 9.60497373987051638749E0, 9.00260197203842689217E1, + 2.23200534594684319226E3, 7.00332514112805075473E3, 5.55923013010394962768E4 }; + +static const double ndtr_U[] = { /* 1.00000000000000000000E0, */ + 3.35617141647503099647E1, 5.21357949780152679795E2, 4.59432382970980127987E3, + 2.26290000613890934246E4, 4.92673942608635921086E4 +}; + +static double ceph_erf(double x); + +static double +ceph_erfc(double a) +{ + double p, q, x, y, z; + + if (isnan(a)) { + return NAN; /* GCOVR_EXCL_LINE */ + } + + if (a < 0.0) { + x = -a; + } else { + x = a; + } + + if (x < 1.0) { + return 1.0 - ceph_erf(a); + } + + z = -a * a; + + if (z < -CEPH_MAXLOG) { + goto under; /* GCOVR_EXCL_LINE */ + } + + z = exp(z); + + if (x < 8.0) { + p = ceph_polevl(x, ndtr_P, 8); + q = ceph_p1evl(x, ndtr_Q, 8); + } else { + p = ceph_polevl(x, ndtr_R, 5); /* GCOVR_EXCL_LINE */ + q = ceph_p1evl(x, ndtr_S, 6); /* GCOVR_EXCL_LINE */ + } + y = (z * p) / q; + + if (a < 0) { + y = 2.0 - y; + } + + if (y != 0.0) { + return y; + } + + /* GCOVR_EXCL_START */ +under: + if (a < 0) { + return 2.0; + } else { + return 0.0; + } + /* GCOVR_EXCL_STOP */ +} + +static double +ceph_erf(double x) +{ + double y, z; + + if (isnan(x)) { + return NAN; /* GCOVR_EXCL_LINE */ + } + + if (x < 0.0) { + return -ceph_erf(-x); + } + + if (fabs(x) > 1.0) { + return 1.0 - ceph_erfc(x); /* GCOVR_EXCL_LINE */ + } + z = x * x; + + y = x * ceph_polevl(z, ndtr_T, 4) / ceph_p1evl(z, ndtr_U, 5); + return y; +} + +/* igam_asymp_coeff.h */ + +#define IGAM_ASYMP_COEFF_K 25 +#define IGAM_ASYMP_COEFF_N 25 + +static const double igam_asymp_coeff_d[IGAM_ASYMP_COEFF_K][IGAM_ASYMP_COEFF_N] = { + { -3.3333333333333333e-1, 8.3333333333333333e-2, -1.4814814814814815e-2, + 1.1574074074074074e-3, 3.527336860670194e-4, -1.7875514403292181e-4, + 3.9192631785224378e-5, -2.1854485106799922e-6, -1.85406221071516e-6, + 8.296711340953086e-7, -1.7665952736826079e-7, 6.7078535434014986e-9, + 1.0261809784240308e-8, -4.3820360184533532e-9, 9.1476995822367902e-10, + -2.551419399494625e-11, -5.8307721325504251e-11, 2.4361948020667416e-11, + -5.0276692801141756e-12, 1.1004392031956135e-13, 3.3717632624009854e-13, + -1.3923887224181621e-13, 2.8534893807047443e-14, -5.1391118342425726e-16, + -1.9752288294349443e-15 }, + { -1.8518518518518519e-3, -3.4722222222222222e-3, 2.6455026455026455e-3, + -9.9022633744855967e-4, 2.0576131687242798e-4, -4.0187757201646091e-7, + -1.8098550334489978e-5, 7.6491609160811101e-6, -1.6120900894563446e-6, + 4.6471278028074343e-9, 1.378633446915721e-7, -5.752545603517705e-8, + 1.1951628599778147e-8, -1.7543241719747648e-11, -1.0091543710600413e-9, + 4.1627929918425826e-10, -8.5639070264929806e-11, 6.0672151016047586e-14, + 7.1624989648114854e-12, -2.9331866437714371e-12, 5.9966963656836887e-13, + -2.1671786527323314e-16, -4.9783399723692616e-14, 2.0291628823713425e-14, + -4.13125571381061e-15 }, + { 4.1335978835978836e-3, -2.6813271604938272e-3, 7.7160493827160494e-4, + 2.0093878600823045e-6, -1.0736653226365161e-4, 5.2923448829120125e-5, + -1.2760635188618728e-5, 3.4235787340961381e-8, 1.3721957309062933e-6, + -6.298992138380055e-7, 1.4280614206064242e-7, -2.0477098421990866e-10, + -1.4092529910867521e-8, 6.228974084922022e-9, -1.3670488396617113e-9, + 9.4283561590146782e-13, 1.2872252400089318e-10, -5.5645956134363321e-11, + 1.1975935546366981e-11, -4.1689782251838635e-15, -1.0940640427884594e-12, + 4.6622399463901357e-13, -9.905105763906906e-14, 1.8931876768373515e-17, + 8.8592218725911273e-15 }, + { 6.4943415637860082e-4, 2.2947209362139918e-4, -4.6918949439525571e-4, + 2.6772063206283885e-4, -7.5618016718839764e-5, -2.3965051138672967e-7, + 1.1082654115347302e-5, -5.6749528269915966e-6, 1.4230900732435884e-6, + -2.7861080291528142e-11, -1.6958404091930277e-7, 8.0994649053880824e-8, + -1.9111168485973654e-8, 2.3928620439808118e-12, 2.0620131815488798e-9, + -9.4604966618551322e-10, 2.1541049775774908e-10, -1.388823336813903e-14, + -2.1894761681963939e-11, 9.7909989511716851e-12, -2.1782191880180962e-12, + 6.2088195734079014e-17, 2.126978363279737e-13, -9.3446887915174333e-14, + 2.0453671226782849e-14 }, + { -8.618882909167117e-4, 7.8403922172006663e-4, -2.9907248030319018e-4, + -1.4638452578843418e-6, 6.6414982154651222e-5, -3.9683650471794347e-5, + 1.1375726970678419e-5, 2.5074972262375328e-10, -1.6954149536558306e-6, + 8.9075075322053097e-7, -2.2929348340008049e-7, 2.956794137544049e-11, + 2.8865829742708784e-8, -1.4189739437803219e-8, 3.4463580499464897e-9, + -2.3024517174528067e-13, -3.9409233028046405e-10, 1.8602338968504502e-10, + -4.356323005056618e-11, 1.2786001016296231e-15, 4.6792750266579195e-12, + -2.1492464706134829e-12, 4.9088156148096522e-13, -6.3385914848915603e-18, + -5.0453320690800944e-14 }, + { -3.3679855336635815e-4, -6.9728137583658578e-5, 2.7727532449593921e-4, + -1.9932570516188848e-4, 6.7977804779372078e-5, 1.419062920643967e-7, + -1.3594048189768693e-5, 8.0184702563342015e-6, -2.2914811765080952e-6, + -3.252473551298454e-10, 3.4652846491085265e-7, -1.8447187191171343e-7, + 4.8240967037894181e-8, -1.7989466721743515e-14, -6.3061945000135234e-9, + 3.1624176287745679e-9, -7.8409242536974293e-10, 5.1926791652540407e-15, + 9.3589442423067836e-11, -4.5134262161632782e-11, 1.0799129993116827e-11, + -3.661886712685252e-17, -1.210902069055155e-12, 5.6807435849905643e-13, + -1.3249659916340829e-13 }, + { 5.3130793646399222e-4, -5.9216643735369388e-4, 2.7087820967180448e-4, + 7.9023532326603279e-7, -8.1539693675619688e-5, 5.6116827531062497e-5, + -1.8329116582843376e-5, -3.0796134506033048e-9, 3.4651553688036091e-6, + -2.0291327396058604e-6, 5.7887928631490037e-7, 2.338630673826657e-13, + -8.8286007463304835e-8, 4.7435958880408128e-8, -1.2545415020710382e-8, + 8.6496488580102925e-14, 1.6846058979264063e-9, -8.5754928235775947e-10, + 2.1598224929232125e-10, -7.6132305204761539e-16, -2.6639822008536144e-11, + 1.3065700536611057e-11, -3.1799163902367977e-12, 4.7109761213674315e-18, + 3.6902800842763467e-13 }, + { 3.4436760689237767e-4, 5.1717909082605922e-5, -3.3493161081142236e-4, + 2.812695154763237e-4, -1.0976582244684731e-4, -1.2741009095484485e-7, + 2.7744451511563644e-5, -1.8263488805711333e-5, 5.7876949497350524e-6, + 4.9387589339362704e-10, -1.0595367014026043e-6, 6.1667143761104075e-7, + -1.7562973359060462e-7, -1.2974473287015439e-12, 2.695423606288966e-8, + -1.4578352908731271e-8, 3.887645959386175e-9, -3.8810022510194121e-17, + -5.3279941738772867e-10, 2.7437977643314845e-10, -6.9957960920705679e-11, + 2.5899863874868481e-17, 8.8566890996696381e-12, -4.403168815871311e-12, + 1.0865561947091654e-12 }, + { -6.5262391859530942e-4, 8.3949872067208728e-4, -4.3829709854172101e-4, + -6.969091458420552e-7, 1.6644846642067548e-4, -1.2783517679769219e-4, + 4.6299532636913043e-5, 4.5579098679227077e-9, -1.0595271125805195e-5, + 6.7833429048651666e-6, -2.1075476666258804e-6, -1.7213731432817145e-11, + 3.7735877416110979e-7, -2.1867506700122867e-7, 6.2202288040189269e-8, + 6.5977038267330006e-16, -9.5903864974256858e-9, 5.2132144922808078e-9, + -1.3991589583935709e-9, 5.382058999060575e-16, 1.9484714275467745e-10, + -1.0127287556389682e-10, 2.6077347197254926e-11, -5.0904186999932993e-18, + -3.3721464474854592e-12 }, + { -5.9676129019274625e-4, -7.2048954160200106e-5, 6.7823088376673284e-4, + -6.4014752602627585e-4, 2.7750107634328704e-4, 1.8197008380465151e-7, + -8.4795071170685032e-5, 6.105192082501531e-5, -2.1073920183404862e-5, + -8.8585890141255994e-10, 4.5284535953805377e-6, -2.8427815022504408e-6, + 8.7082341778646412e-7, 3.6886101871706965e-12, -1.5344695190702061e-7, + 8.862466778790695e-8, -2.5184812301826817e-8, -1.0225912098215092e-14, + 3.8969470758154777e-9, -2.1267304792235635e-9, 5.7370135528051385e-10, + -1.887749850169741e-19, -8.0931538694657866e-11, 4.2382723283449199e-11, + -1.1002224534207726e-11 }, + { 1.3324454494800656e-3, -1.9144384985654775e-3, 1.1089369134596637e-3, + 9.932404122642299e-7, -5.0874501293093199e-4, 4.2735056665392884e-4, + -1.6858853767910799e-4, -8.1301893922784998e-9, 4.5284402370562147e-5, + -3.127053674781734e-5, 1.044986828530338e-5, 4.8435226265680926e-11, + -2.1482565873456258e-6, 1.329369701097492e-6, -4.0295693092101029e-7, + -1.7567877666323291e-13, 7.0145043163668257e-8, -4.040787734999483e-8, + 1.1474026743371963e-8, 3.9642746853563325e-18, -1.7804938269892714e-9, + 9.7480262548731646e-10, -2.6405338676507616e-10, 5.794875163403742e-18, + 3.7647749553543836e-11 }, + { 1.579727660730835e-3, 1.6251626278391582e-4, -2.0633421035543276e-3, + 2.1389686185689098e-3, -1.0108559391263003e-3, -3.9912705529919201e-7, + 3.6235025084764691e-4, -2.8143901463712154e-4, 1.0449513336495887e-4, + 2.1211418491830297e-9, -2.5779417251947842e-5, 1.7281818956040463e-5, + -5.6413773872904282e-6, -1.1024320105776174e-11, 1.1223224418895175e-6, + -6.8693396379526735e-7, 2.0653236975414887e-7, 4.6714772409838506e-14, + -3.5609886164949055e-8, 2.0470855345905963e-8, -5.8091738633283358e-9, + -1.332821287582869e-16, 9.0354604391335133e-10, -4.9598782517330834e-10, + 1.3481607129399749e-10 }, + { -4.0725121195140166e-3, 6.4033628338080698e-3, -4.0410161081676618e-3, + -2.183732802866233e-6, 2.1740441801254639e-3, -1.9700440518418892e-3, + 8.3595469747962458e-4, 1.9445447567109655e-8, -2.5779387120421696e-4, + 1.9009987368139304e-4, -6.7696499937438965e-5, -1.4440629666426572e-10, + 1.5712512518742269e-5, -1.0304008744776893e-5, 3.304517767401387e-6, + 7.9829760242325709e-13, -6.4097794149313004e-7, 3.8894624761300056e-7, + -1.1618347644948869e-7, -2.816808630596451e-15, 1.9878012911297093e-8, + -1.1407719956357511e-8, 3.2355857064185555e-9, 4.1759468293455945e-20, + -5.0423112718105824e-10 }, + { -5.9475779383993003e-3, -5.4016476789260452e-4, 8.7910413550767898e-3, + -9.8576315587856125e-3, 5.0134695031021538e-3, 1.2807521786221875e-6, + -2.0626019342754683e-3, 1.7109128573523058e-3, -6.7695312714133799e-4, + -6.9011545676562133e-9, 1.8855128143995902e-4, -1.3395215663491969e-4, + 4.6263183033528039e-5, 4.0034230613321351e-11, -1.0255652921494033e-5, + 6.612086372797651e-6, -2.0913022027253008e-6, -2.0951775649603837e-13, + 3.9756029041993247e-7, -2.3956211978815887e-7, 7.1182883382145864e-8, + 8.925574873053455e-16, -1.2101547235064676e-8, 6.9350618248334386e-9, + -1.9661464453856102e-9 }, + { 1.7402027787522711e-2, -2.9527880945699121e-2, 2.0045875571402799e-2, + 7.0289515966903407e-6, -1.2375421071343148e-2, 1.1976293444235254e-2, + -5.4156038466518525e-3, -6.3290893396418616e-8, 1.8855118129005065e-3, + -1.473473274825001e-3, 5.5515810097708387e-4, 5.2406834412550662e-10, + -1.4357913535784836e-4, 9.9181293224943297e-5, -3.3460834749478311e-5, + -3.5755837291098993e-12, 7.1560851960630076e-6, -4.5516802628155526e-6, + 1.4236576649271475e-6, 1.8803149082089664e-14, -2.6623403898929211e-7, + 1.5950642189595716e-7, -4.7187514673841102e-8, -6.5107872958755177e-17, + 7.9795091026746235e-9 }, + { 3.0249124160905891e-2, 2.4817436002649977e-3, -4.9939134373457022e-2, + 5.9915643009307869e-2, -3.2483207601623391e-2, -5.7212968652103441e-6, + 1.5085251778569354e-2, -1.3261324005088445e-2, 5.5515262632426148e-3, + 3.0263182257030016e-8, -1.7229548406756723e-3, 1.2893570099929637e-3, + -4.6845138348319876e-4, -1.830259937893045e-10, 1.1449739014822654e-4, + -7.7378565221244477e-5, 2.5625836246985201e-5, 1.0766165333192814e-12, + -5.3246809282422621e-6, 3.349634863064464e-6, -1.0381253128684018e-6, + -5.608909920621128e-15, 1.9150821930676591e-7, -1.1418365800203486e-7, + 3.3654425209171788e-8 }, + { -9.9051020880159045e-2, 1.7954011706123486e-1, -1.2989606383463778e-1, + -3.1478872752284357e-5, 9.0510635276848131e-2, -9.2828824411184397e-2, + 4.4412112839877808e-2, 2.7779236316835888e-7, -1.7229543805449697e-2, + 1.4182925050891573e-2, -5.6214161633747336e-3, -2.39598509186381e-9, + 1.6029634366079908e-3, -1.1606784674435773e-3, 4.1001337768153873e-4, + 1.8365800754090661e-11, -9.5844256563655903e-5, 6.3643062337764708e-5, + -2.076250624489065e-5, -1.1806020912804483e-13, 4.2131808239120649e-6, + -2.6262241337012467e-6, 8.0770620494930662e-7, 6.0125912123632725e-16, + -1.4729737374018841e-7 }, + { -1.9994542198219728e-1, -1.5056113040026424e-2, 3.6470239469348489e-1, + -4.6435192311733545e-1, 2.6640934719197893e-1, 3.4038266027147191e-5, + -1.3784338709329624e-1, 1.276467178337056e-1, -5.6213828755200985e-2, + -1.753150885483011e-7, 1.9235592956768113e-2, -1.5088821281095315e-2, + 5.7401854451350123e-3, 1.0622382710310225e-9, -1.5335082692563998e-3, + 1.0819320643228214e-3, -3.7372510193945659e-4, -6.6170909729031985e-12, + 8.4263617380909628e-5, -5.5150706827483479e-5, 1.7769536448348069e-5, + 3.8827923210205533e-14, -3.53513697488768e-6, 2.1865832130045269e-6, + -6.6812849447625594e-7 }, + { 7.2438608504029431e-1, -1.3918010932653375, 1.0654143352413968, + 1.876173868950258e-4, -8.2705501176152696e-1, 8.9352433347828414e-1, + -4.4971003995291339e-1, -1.6107401567546652e-6, 1.9235590165271091e-1, + -1.6597702160042609e-1, 6.8882222681814333e-2, 1.3910091724608687e-8, + -2.146911561508663e-2, 1.6228980898865892e-2, -5.9796016172584256e-3, + -1.1287469112826745e-10, 1.5167451119784857e-3, -1.0478634293553899e-3, + 3.5539072889126421e-4, 8.1704322111801517e-13, -7.7773013442452395e-5, + 5.0291413897007722e-5, -1.6035083867000518e-5, 1.2469354315487605e-14, + 3.1369106244517615e-6 }, + { 1.6668949727276811, 1.165462765994632e-1, -3.3288393225018906, 4.4692325482864037, + -2.6977693045875807, -2.600667859891061e-4, 1.5389017615694539, + -1.4937962361134612, 6.8881964633233148e-1, 1.3077482004552385e-6, + -2.5762963325596288e-1, 2.1097676102125449e-1, -8.3714408359219882e-2, + -7.7920428881354753e-9, 2.4267923064833599e-2, -1.7813678334552311e-2, + 6.3970330388900056e-3, 4.9430807090480523e-11, -1.5554602758465635e-3, + 1.0561196919903214e-3, -3.5277184460472902e-4, 9.3002334645022459e-14, + 7.5285855026557172e-5, -4.8186515569156351e-5, 1.5227271505597605e-5 }, + { -6.6188298861372935, 1.3397985455142589e+1, -1.0789350606845146e+1, + -1.4352254537875018e-3, 9.2333694596189809, -1.0456552819547769e+1, + 5.5105526029033471, 1.2024439690716742e-5, -2.5762961164755816, + 2.3207442745387179, -1.0045728797216284, -1.0207833290021914e-7, + 3.3975092171169466e-1, -2.6720517450757468e-1, 1.0235252851562706e-1, + 8.4329730484871625e-10, -2.7998284958442595e-2, 2.0066274144976813e-2, + -7.0554368915086242e-3, 1.9402238183698188e-12, 1.6562888105449611e-3, + -1.1082898580743683e-3, 3.654545161310169e-4, -5.1290032026971794e-11, + -7.6340103696869031e-5 }, + { -1.7112706061976095e+1, -1.1208044642899116, 3.7131966511885444e+1, + -5.2298271025348962e+1, 3.3058589696624618e+1, 2.4791298976200222e-3, + -2.061089403411526e+1, 2.088672775145582e+1, -1.0045703956517752e+1, + -1.2238783449063012e-5, 4.0770134274221141, -3.473667358470195, + 1.4329352617312006, 7.1359914411879712e-8, -4.4797257159115612e-1, + 3.4112666080644461e-1, -1.2699786326594923e-1, -2.8953677269081528e-10, + 3.3125776278259863e-2, -2.3274087021036101e-2, 8.0399993503648882e-3, + -1.177805216235265e-9, -1.8321624891071668e-3, 1.2108282933588665e-3, + -3.9479941246822517e-4 }, + { 7.389033153567425e+1, -1.5680141270402273e+2, 1.322177542759164e+2, + 1.3692876877324546e-2, -1.2366496885920151e+2, 1.4620689391062729e+2, + -8.0365587724865346e+1, -1.1259851148881298e-4, 4.0770132196179938e+1, + -3.8210340013273034e+1, 1.719522294277362e+1, 9.3519707955168356e-7, + -6.2716159907747034, 5.1168999071852637, -2.0319658112299095, + -4.9507215582761543e-9, 5.9626397294332597e-1, -4.4220765337238094e-1, + 1.6079998700166273e-1, -2.4733786203223402e-8, -4.0307574759979762e-2, + 2.7849050747097869e-2, -9.4751858992054221e-3, 6.419922235909132e-6, + 2.1250180774699461e-3 }, + { 2.1216837098382522e+2, 1.3107863022633868e+1, -4.9698285932871748e+2, + 7.3121595266969204e+2, -4.8213821720890847e+2, -2.8817248692894889e-2, + 3.2616720302947102e+2, -3.4389340280087117e+2, 1.7195193870816232e+2, + 1.4038077378096158e-4, -7.52594195897599e+1, 6.651969984520934e+1, + -2.8447519748152462e+1, -7.613702615875391e-7, 9.5402237105304373, + -7.5175301113311376, 2.8943997568871961, -4.6612194999538201e-7, + -8.0615149598794088e-1, 5.8483006570631029e-1, -2.0845408972964956e-1, + 1.4765818959305817e-4, 5.1000433863753019e-2, -3.3066252141883665e-2, + 1.5109265210467774e-2 }, + { -9.8959643098322368e+2, 2.1925555360905233e+3, -1.9283586782723356e+3, + -1.5925738122215253e-1, 1.9569985945919857e+3, -2.4072514765081556e+3, + 1.3756149959336496e+3, 1.2920735237496668e-3, -7.525941715948055e+2, + 7.3171668742208716e+2, -3.4137023466220065e+2, -9.9857390260608043e-6, + 1.3356313181291573e+2, -1.1276295161252794e+2, 4.6310396098204458e+1, + -7.9237387133614756e-6, -1.4510726927018646e+1, 1.1111771248100563e+1, + -4.1690817945270892, 3.1008219800117808e-3, 1.1220095449981468, + -7.6052379926149916e-1, 3.6262236505085254e-1, 2.216867741940747e-1, + 4.8683443692930507e-1 } +}; + +/* igam.h */ + +#define IGAM_MAXITER 2000 +#define IGAM_IGAM 1 +#define IGAM_IGAMC 0 +#define IGAM_SMALL 20 +#define IGAM_LARGE 200 +#define IGAM_SMALLRATIO 0.3 +#define IGAM_LARGERATIO 4.5 +#define IGAM_BIG 4.503599627370496e15 +#define IGAM_BIGINV 2.22044604925031308085e-16 + +/* Compute + * + * x^a * exp(-x) / gamma(a) + * + * corrected from (15) and (16) in [2] by replacing exp(x - a) with + * exp(a - x). + */ +static double +ceph_igam_fac(double a, double x) +{ + double ax, fac, res, num; + + if (fabs(a - x) > 0.4 * fabs(a)) { + ax = a * log(x) - x - ceph_lgam(a); + if (ax < -CEPH_MAXLOG) { + return 0.0; + } + return exp(ax); + } + + fac = a + LANCZOS_G - 0.5; + res = sqrt(fac / exp(1)) / ceph_lanczos_sum_expg_scaled(a); + + if ((a < 200) && (x < 200)) { + res *= exp(a - x) * pow(x / fac, a); + } else { + num = x - a - LANCZOS_G + 0.5; + res *= exp(a * ceph_log1pmx(num / fac) + x * (0.5 - LANCZOS_G) / fac); + } + + return res; +} + +/* Compute igamc using DLMF 8.9.2. */ +static double +ceph_igamc_continued_fraction(double a, double x) +{ + int i; + double ans, ax, c, yc, r, t, y, z; + double pk, pkm1, pkm2, qk, qkm1, qkm2; + + ax = ceph_igam_fac(a, x); + if (ax == 0.0) { + return 0.0; /* GCOVR_EXCL_LINE */ + } + + /* continued fraction */ + y = 1.0 - a; + z = x + y + 1.0; + c = 0.0; + pkm2 = 1.0; + qkm2 = x; + pkm1 = x + 1.0; + qkm1 = z * x; + ans = pkm1 / qkm1; + + for (i = 0; i < IGAM_MAXITER; i++) { + c += 1.0; + y += 1.0; + z += 2.0; + yc = y * c; + pk = pkm1 * z - pkm2 * yc; + qk = qkm1 * z - qkm2 * yc; + if (qk != 0) { + r = pk / qk; + t = fabs((ans - r) / r); + ans = r; + } else { + t = 1.0; /* GCOVR_EXCL_LINE */ + } + pkm2 = pkm1; + pkm1 = pk; + qkm2 = qkm1; + qkm1 = qk; + if (fabs(pk) > IGAM_BIG) { + pkm2 *= IGAM_BIGINV; + pkm1 *= IGAM_BIGINV; + qkm2 *= IGAM_BIGINV; + qkm1 *= IGAM_BIGINV; + } + if (t <= CEPH_MACHEP) { + break; + } + } + + return ans * ax; +} + +/* Compute igam using DLMF 8.11.4. */ +static double +ceph_igam_series(double a, double x) +{ + int i; + double ans, ax, c, r; + + ax = ceph_igam_fac(a, x); + if (ax == 0.0) { + return 0.0; /* GCOVR_EXCL_LINE */ + } + + /* power series */ + r = a; + c = 1.0; + ans = 1.0; + + for (i = 0; i < IGAM_MAXITER; i++) { + r += 1.0; + c *= x / r; + ans += c; + if (c <= CEPH_MACHEP * ans) { + break; + } + } + + return ans * ax / a; +} + +/* Compute igamc using DLMF 8.7.3. This is related to the series in + * igam_series but extra care is taken to avoid cancellation. + */ +static double +ceph_igamc_series(double a, double x) +{ + int n; + double fac = 1; + double sum = 0; + double term, logx; + + for (n = 1; n < IGAM_MAXITER; n++) { + fac *= -x / n; + term = fac / (a + n); + sum += term; + if (fabs(term) <= CEPH_MACHEP * fabs(sum)) { + break; + } + } + + logx = log(x); + term = -ceph_expm1(a * logx - ceph_lgam1p(a)); + return term - exp(a * logx - ceph_lgam(a)) * sum; +} + +/* Compute igam/igamc using DLMF 8.12.3/8.12.4. */ +static double +ceph_asymptotic_series(double a, double x, int func) +{ + int k, n, sgn; + int maxpow = 0; + double lambda = x / a; + double sigma = (x - a) / a; + double eta, res, ck, ckterm, term, absterm; + double absoldterm = INFINITY; + double etapow[IGAM_ASYMP_COEFF_N] = { 1 }; + double sum = 0; + double afac = 1; + + if (func == IGAM_IGAM) { + sgn = -1; + } else { + sgn = 1; + } + + if (lambda > 1) { + eta = sqrt(-2 * ceph_log1pmx(sigma)); + } else if (lambda < 1) { + eta = -sqrt(-2 * ceph_log1pmx(sigma)); + } else { + eta = 0; + } + res = 0.5 * ceph_erfc(sgn * eta * sqrt(a / 2)); + + for (k = 0; k < IGAM_ASYMP_COEFF_K; k++) { + ck = igam_asymp_coeff_d[k][0]; + for (n = 1; n < IGAM_ASYMP_COEFF_N; n++) { + if (n > maxpow) { + etapow[n] = eta * etapow[n - 1]; + maxpow += 1; + } + ckterm = igam_asymp_coeff_d[k][n] * etapow[n]; + ck += ckterm; + if (fabs(ckterm) < CEPH_MACHEP * fabs(ck)) { + break; + } + } + term = ck * afac; + absterm = fabs(term); + if (absterm > absoldterm) { + break; /* GCOVR_EXCL_LINE */ + } + sum += term; + if (absterm < CEPH_MACHEP * fabs(sum)) { + break; + } + absoldterm = absterm; + afac /= a; + } + res += sgn * exp(-0.5 * a * eta * eta) * sum / sqrt(2 * CEPH_PI * a); + + return res; +} + +static double ceph_igamc(double a, double x); + +static double +ceph_igam(double a, double x) +{ + double absxma_a; + + if (isnan(x)) { + return NAN; + } + + if (x < 0) { + return NAN; /* GCOVR_EXCL_LINE */ + } else if (x == 0) { + /* Zero integration limit */ + return 0; /* GCOVR_EXCL_LINE */ + } else if (isinf(x)) { + return 1; /* GCOVR_EXCL_LINE */ + } + + /* Asymptotic regime where a ~ x; see [2]. */ + absxma_a = fabs(x - a) / a; + if ((a > IGAM_SMALL) && (a < IGAM_LARGE) && (absxma_a < IGAM_SMALLRATIO)) { + return ceph_asymptotic_series(a, x, IGAM_IGAM); + } else if ((a > IGAM_LARGE) && (absxma_a < IGAM_LARGERATIO / sqrt(a))) { + return ceph_asymptotic_series(a, x, IGAM_IGAM); + } + + if ((x > 1.0) && (x > a)) { + return 1.0 - ceph_igamc(a, x); + } + + return ceph_igam_series(a, x); +} + +static double +ceph_igamc(double a, double x) +{ + double absxma_a; + + if (isnan(x)) { + return NAN; + } + + if (x < 0) { + return NAN; /* GCOVR_EXCL_LINE */ + } else if (x == 0) { + return 1; /* GCOVR_EXCL_LINE */ + } else if (isinf(x)) { + return 0; /* GCOVR_EXCL_LINE */ + } + + /* Asymptotic regime where a ~ x; see [2]. */ + absxma_a = fabs(x - a) / a; + if ((a > IGAM_SMALL) && (a < IGAM_LARGE) && (absxma_a < IGAM_SMALLRATIO)) { + return ceph_asymptotic_series(a, x, IGAM_IGAMC); + } else if ((a > IGAM_LARGE) && (absxma_a < IGAM_LARGERATIO / sqrt(a))) { + return ceph_asymptotic_series(a, x, IGAM_IGAMC); + } + + /* Everywhere else; see [2]. */ + if (x > 1.1) { + if (x < a) { + return 1.0 - ceph_igam_series(a, x); /* GCOVR_EXCL_LINE */ + } else { + return ceph_igamc_continued_fraction(a, x); + } + } else if (x <= 0.5) { + if (-0.4 / log(x) < a) { + return 1.0 - ceph_igam_series(a, x); /* GCOVR_EXCL_LINE */ + } else { + return ceph_igamc_series(a, x); + } + } else { + if (x * 1.1 < a) { + return 1.0 - ceph_igam_series(a, x); /* GCOVR_EXCL_LINE */ + } else { + return ceph_igamc_series(a, x); + } + } +} + +/* igami.h */ + +static double +ceph_find_inverse_s(double p, double q) +{ + /* + * Computation of the Incomplete Gamma Function Ratios and their Inverse + * ARMIDO R. DIDONATO and ALFRED H. MORRIS, JR. + * ACM Transactions on Mathematical Software, Vol. 12, No. 4, + * December 1986, Pages 377-393. + * + * See equation 32. + */ + double s, t; + static const double a[4] + = { 0.213623493715853, 4.28342155967104, 11.6616720288968, 3.31125922108741 }; + static const double b[5] = { 0.3611708101884203e-1, 1.27364489782223, + 6.40691597760039, 6.61053765625462, 1 }; + + if (p < 0.5) { + t = sqrt(-2 * log(p)); + } else { + t = sqrt(-2 * log(q)); + } + s = t - ceph_polevl(t, a, 3) / ceph_polevl(t, b, 4); + if (p < 0.5) { + s = -s; + } + return s; +} + +static double +ceph_didonato_SN(double a, double x, unsigned N, double tolerance) +{ + /* + * Computation of the Incomplete Gamma Function Ratios and their Inverse + * ARMIDO R. DIDONATO and ALFRED H. MORRIS, JR. + * ACM Transactions on Mathematical Software, Vol. 12, No. 4, + * December 1986, Pages 377-393. + * + * See equation 34. + */ + double sum = 1.0; + unsigned i; + double partial; + + if (N >= 1) { + partial = x / (a + 1); + + sum += partial; + for (i = 2; i <= N; ++i) { + partial *= x / (a + i); + sum += partial; + if (partial < tolerance) { + break; + } + } + } + return sum; +} + +static double +ceph_find_inverse_gamma(double a, double p, double q) +{ + /* + * In order to understand what's going on here, you will + * need to refer to: + * + * Computation of the Incomplete Gamma Function Ratios and their Inverse + * ARMIDO R. DIDONATO and ALFRED H. MORRIS, JR. + * ACM Transactions on Mathematical Software, Vol. 12, No. 4, + * December 1986, Pages 377-393. + */ + double result; + double g, b, u, t, y, c1, c1_2, c1_3, c1_4, a_2, a_3, c2, c3, c4, c5, y_2, y_3, y_4; + double s, s_2, s_3, s_4, s_5, ra, w, D, lg, lb, z, ap1, ap2, v, ls; + + if (a == 1) { + if (q > 0.9) { + result = -log1p(-p); + } else { + result = -log(q); + } + } else if (a < 1) { + g = ceph_Gamma(a); + b = q * g; + + if ((b > 0.6) || ((b >= 0.45) && (a >= 0.3))) { + /* DiDonato & Morris Eq 21: + * + * There is a slight variation from DiDonato and Morris here: + * the first form given here is unstable when p is close to 1, + * making it impossible to compute the inverse of Q(a,x) for small + * q. Fortunately the second form works perfectly well in this case. + */ + if ((b * q > 1e-8) && (q > 1e-5)) { + u = pow(p * g * a, 1 / a); + } else { + u = exp((-q / a) - CEPH_SCIPY_EULER); + } + result = u / (1 - (u / (a + 1))); + } else if ((a < 0.3) && (b >= 0.35)) { + /* DiDonato & Morris Eq 22: */ + t = exp(-CEPH_SCIPY_EULER - b); + u = t * exp(t); + result = t * exp(u); + } else if ((b > 0.15) || (a >= 0.3)) { + /* DiDonato & Morris Eq 23: */ + y = -log(b); + u = y - (1 - a) * log(y); + result = y - (1 - a) * log(u) - log(1 + (1 - a) / (1 + u)); + } else if (b > 0.1) { + /* DiDonato & Morris Eq 24: */ + y = -log(b); + u = y - (1 - a) * log(y); + result = y - (1 - a) * log(u) + - log((u * u + 2 * (3 - a) * u + (2 - a) * (3 - a)) + / (u * u + (5 - a) * u + 2)); + } else { + /* DiDonato & Morris Eq 25: */ + y = -log(b); + c1 = (a - 1) * log(y); + c1_2 = c1 * c1; + c1_3 = c1_2 * c1; + c1_4 = c1_2 * c1_2; + a_2 = a * a; + a_3 = a_2 * a; + + c2 = (a - 1) * (1 + c1); + c3 = (a - 1) * (-(c1_2 / 2) + (a - 2) * c1 + (3 * a - 5) / 2); + c4 = (a - 1) + * ((c1_3 / 3) - (3 * a - 5) * c1_2 / 2 + (a_2 - 6 * a + 7) * c1 + + (11 * a_2 - 46 * a + 47) / 6); + c5 = (a - 1) + * (-(c1_4 / 4) + (11 * a - 17) * c1_3 / 6 + + (-3 * a_2 + 13 * a - 13) * c1_2 + + (2 * a_3 - 25 * a_2 + 72 * a - 61) * c1 / 2 + + (25 * a_3 - 195 * a_2 + 477 * a - 379) / 12); + + y_2 = y * y; + y_3 = y_2 * y; + y_4 = y_2 * y_2; + result = y + c1 + (c2 / y) + (c3 / y_2) + (c4 / y_3) + (c5 / y_4); + } + } else { + /* DiDonato and Morris Eq 31: */ + s = ceph_find_inverse_s(p, q); + + s_2 = s * s; + s_3 = s_2 * s; + s_4 = s_2 * s_2; + s_5 = s_4 * s; + ra = sqrt(a); + + w = a + s * ra + (s_2 - 1) / 3; + w += (s_3 - 7 * s) / (36 * ra); + w -= (3 * s_4 + 7 * s_2 - 16) / (810 * a); + w += (9 * s_5 + 256 * s_3 - 433 * s) / (38880 * a * ra); + + if ((a >= 500) && (fabs(1 - w / a) < 1e-6)) { + result = w; + } else if (p > 0.5) { + if (w < 3 * a) { + result = w; + } else { + D = fmax(2, a * (a - 1)); + lg = ceph_lgam(a); + lb = log(q) + lg; + if (lb < -D * 2.3) { + /* DiDonato and Morris Eq 25: */ + y = -lb; + c1 = (a - 1) * log(y); + c1_2 = c1 * c1; + c1_3 = c1_2 * c1; + c1_4 = c1_2 * c1_2; + a_2 = a * a; + a_3 = a_2 * a; + + c2 = (a - 1) * (1 + c1); + c3 = (a - 1) * (-(c1_2 / 2) + (a - 2) * c1 + (3 * a - 5) / 2); + c4 = (a - 1) + * ((c1_3 / 3) - (3 * a - 5) * c1_2 / 2 + (a_2 - 6 * a + 7) * c1 + + (11 * a_2 - 46 * a + 47) / 6); + c5 = (a - 1) + * (-(c1_4 / 4) + (11 * a - 17) * c1_3 / 6 + + (-3 * a_2 + 13 * a - 13) * c1_2 + + (2 * a_3 - 25 * a_2 + 72 * a - 61) * c1 / 2 + + (25 * a_3 - 195 * a_2 + 477 * a - 379) / 12); + + y_2 = y * y; + y_3 = y_2 * y; + y_4 = y_2 * y_2; + result = y + c1 + (c2 / y) + (c3 / y_2) + (c4 / y_3) + (c5 / y_4); + } else { + /* DiDonato and Morris Eq 33: */ + u = -lb + (a - 1) * log(w) - log(1 + (1 - a) / (1 + w)); + result = -lb + (a - 1) * log(u) - log(1 + (1 - a) / (1 + u)); + } + } + } else { + z = w; + ap1 = a + 1; + ap2 = a + 2; + if (w < 0.15 * ap1) { + /* DiDonato and Morris Eq 35: */ + v = log(p) + ceph_lgam(ap1); + z = exp((v + w) / a); + s = log1p(z / ap1 * (1 + z / ap2)); + z = exp((v + z - s) / a); + s = log1p(z / ap1 * (1 + z / ap2)); + z = exp((v + z - s) / a); + s = log1p(z / ap1 * (1 + z / ap2 * (1 + z / (a + 3)))); + z = exp((v + z - s) / a); + } + + if ((z <= 0.01 * ap1) || (z > 0.7 * ap1)) { + result = z; + } else { + /* DiDonato and Morris Eq 36: */ + ls = log(ceph_didonato_SN(a, z, 100, 1e-4)); + v = log(p) + ceph_lgam(ap1); + z = exp((v + z - ls) / a); + result = z * (1 - (a * log(z) - z - v + ls) / (a - z)); + } + } + } + return result; +} + +/* The inverse of igamc. Its only caller, tsd_gammaincinv, passes 0 < q < 0.1 and + * a >= 0, so the argument checks of igamci() are omitted. */ +static double +ceph_igamci(double a, double q) +{ + int i; + double x, fac, f_fp, fpp_fp; + + x = ceph_find_inverse_gamma(a, 1 - q, q); + for (i = 0; i < 3; i++) { + fac = ceph_igam_fac(a, x); + if (fac == 0.0) { + return x; + } + f_fp = (ceph_igamc(a, x) - q) * x / (-fac); + fpp_fp = -1.0 + (a - 1) / x; + if (isinf(fpp_fp)) { + x = x - f_fp; + } else { + x = x - f_fp / (1.0 - 0.5 * f_fp * fpp_fp); + } + } + + return x; +} + +/* igami(). NaN for `a` < 0, `p` outside [0, 1], `a` = 0 or `a` = infinity (with + * 0 < p < 1), and NaN arguments. */ +double +tsd_gammaincinv(double a, double p) +{ + int i; + double x, fac, f_fp, fpp_fp; + + if (!(a >= 0) || !(p >= 0 && p <= 1)) { + return NAN; + } + if (p == 0.0) { + return 0.0; + } + if (p == 1.0) { + return INFINITY; + } + if (a == 0 || isinf(a)) { + return NAN; + } + if (p > 0.9) { + return ceph_igamci(a, 1 - p); + } + + x = ceph_find_inverse_gamma(a, p, 1 - p); + /* Halley's method */ + for (i = 0; i < 3; i++) { + fac = ceph_igam_fac(a, x); + if (fac == 0.0) { + return x; + } + f_fp = (ceph_igam(a, x) - p) * x / fac; + /* The ratio of the first and second derivatives simplifies */ + fpp_fp = -1.0 + (a - 1) / x; + if (isinf(fpp_fp)) { + /* Resort to Newton's method in the case of overflow */ + x = x - f_fp; + } else { + x = x - f_fp / (1.0 - 0.5 * f_fp * fpp_fp); + } + } + + return x; +} diff --git a/lib/hypergeo.c b/lib/hypergeo.c new file mode 100644 index 00000000..2c6810bd --- /dev/null +++ b/lib/hypergeo.c @@ -0,0 +1,490 @@ +/* + * MIT License + * + * Copyright (c) 2026 Tskit Developers + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in all + * copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE + * SOFTWARE. + */ + +/* + * Numerically stable implementations of the Gauss hypergeometric function and related + * special functions. Operation order and libm calls match the oracles in tests/oracle, + * which the tests compare exactly. + * + * A float division by zero returns TSD_ERR_ZERO_DIVISION at the divisions that the + * tests show to be reachable (those of the poles of the polygamma functions and of the + * Laplace roots). The other divisions follow IEEE semantics (infinity or NaN). + */ + +#include + +#include "mathutil.h" +#include "tsdate.h" + +/* Digamma function for x > 0 (or NaN), by recurrence and asymptotic series. */ +static double +digamma_positive(double x) +{ + double xpm2, value; + + if (x <= 1e-5) { + return -TSD_EULER_GAMMA - (1 / x); + } + if (x < 8.5) { + return digamma_positive(1 + x) - 1 / x; + } + xpm2 = 1 / tsd_ipow(x, 2); + value = log(x); + value -= 0.5 / x; + value -= 0.083333333333333333 * xpm2; + value += 0.008333333333333333 * tsd_ipow(xpm2, 2); + value -= 0.003968253968253968 * tsd_ipow(xpm2, 3); + value += 0.004166666666666667 * tsd_ipow(xpm2, 4); + value -= 0.007575757575757576 * tsd_ipow(xpm2, 5); + value += 0.021092796092796094 * tsd_ipow(xpm2, 6); + return value; +} + +/* Digamma (psi) function, from asymptotic series expansion. */ +int +tsd_digamma(double x, double *out) +{ + int ret = 0; + double reflected, tan_pix; + + if (x <= 0.0) { + /* Reflection formula; 1 - x >= 1 */ + reflected = digamma_positive(1 - x); + tan_pix = tan(TSD_PI * x); + if (tan_pix == 0.0) { + ret = tsd_trace_error(TSD_ERR_ZERO_DIVISION); + goto out; + } + *out = reflected - TSD_PI / tan_pix; + } else { + *out = digamma_positive(x); + } +out: + return ret; +} + +/* Trigamma function for x > 1e-4 (or NaN), by recurrence and asymptotic series. */ +static double +trigamma_large(double x) +{ + double x_sq, xpm1, xpm2, value; + + x_sq = tsd_ipow(x, 2); + if (x < 5) { + return trigamma_large(1 + x) + 1 / x_sq; + } + xpm1 = 1 / x; + xpm2 = 1 / x_sq; + value = 1.000000000000000000; + value += 0.500000000000000000 * xpm1; + value += 0.166666666666666667 * pow(xpm2, 1); + value -= 0.033333333333333333 * pow(xpm2, 2); + value += 0.023809523809523808 * pow(xpm2, 3); + value -= 0.033333333333333333 * pow(xpm2, 4); + value += 0.075757575757575756 * pow(xpm2, 5); + value -= 0.253113553113553102 * pow(xpm2, 6); + value += 1.166666666666666741 * pow(xpm2, 7); + return xpm1 * value; +} + +/* Trigamma function, from asymptotic series expansion. */ +int +tsd_trigamma(double x, double *out) +{ + int ret = 0; + double reflected, sin_pix, sin_sq, x_sq; + + if (x <= 0.0) { + /* Reflection formula; 1 - x >= 1 */ + reflected = trigamma_large(1 - x); + sin_pix = sin(TSD_PI * x); + sin_sq = tsd_ipow(sin_pix, 2); + if (sin_sq == 0.0) { + ret = tsd_trace_error(TSD_ERR_ZERO_DIVISION); + goto out; + } + *out = -reflected + tsd_ipow(TSD_PI, 2) / sin_sq; + } else if (x <= 1e-4) { + x_sq = tsd_ipow(x, 2); + if (x_sq == 0.0) { + ret = tsd_trace_error(TSD_ERR_ZERO_DIVISION); + goto out; + } + *out = 1 / x_sq; + } else { + *out = trigamma_large(x); + } +out: + return ret; +} + +/* Log of the beta function. */ +double +tsd_betaln(double p, double q) +{ + return lgamma(p) + lgamma(q) - lgamma(p + q); +} + +/* + * Approximate Tricomi's confluent hypergeometric function with real arguments, using + * Laplace's method with a calibration point. Also returns the derivative wrt x. + */ +int +tsd_hyperu_laplace(double a, double b, double x, double *value, double *dvalue) +{ + int ret = 0; + double t, denom, u, r, g, w, v, dr, dg, du; + + if (!(b >= a && a > 0.0)) { + ret = tsd_trace_error(TSD_ERR_INVALID_HYPERGEO); + goto out; + } + if (!(x > 0.0)) { + ret = tsd_trace_error(TSD_ERR_INVALID_HYPERGEO); + goto out; + } + + t = b - x - 1; + denom = sqrt(tsd_ipow(t, 2) + 4 * x * a) - t; + if (denom == 0.0) { + ret = tsd_trace_error(TSD_ERR_ZERO_DIVISION); + goto out; + } + u = 2 * a / denom; + r = (b - a - 1) * tsd_ipow(u, 2) + a * tsd_ipow(1 + u, 2); + g = (b - a) * log(1 + u); + g += a * (1 + log(u)); + g -= x * u; + g -= log(a) * (a - 0.5); + + w = (b - 1) * u + a; + v = u * (1 + u); + dr = w / (w * u + a * (1 + u)); + if (v == 0.0) { + ret = tsd_trace_error(TSD_ERR_ZERO_DIVISION); + goto out; + } + dg = (w - x * v + u) / v; + du = -u * v / (w - x * u + a); + + *value = g - log(r) / 2; + *dvalue = (dg - dr) * du - u; +out: + return ret; +} + +/* + * Approximate Kummer's confluent hypergeometric function with real arguments, using + * Laplace's method with a calibration point. + */ +int +tsd_hyp1f1_laplace(double a, double b, double x, double *out) +{ + int ret = 0; + double t, denom, u, r, g; + + if (!(b > a && a > 0.0)) { + ret = tsd_trace_error(TSD_ERR_INVALID_HYPERGEO); + goto out; + } + + if (x == 0.0) { + *out = 0.0; + goto out; + } + + t = x - b; + denom = sqrt(tsd_ipow(t, 2) + 4 * x * a) - t; + if (denom == 0.0) { + ret = tsd_trace_error(TSD_ERR_ZERO_DIVISION); + goto out; + } + u = 2 * a / denom; + r = tsd_ipow(u, 2) * b / a + tsd_ipow(1 - u, 2) * b / (b - a); + g = (b - a) * log(1 - u); + g += a * log(u); + g += b * log(b); + g -= (b - a) * log(b - a); + g -= a * log(a); + g += x * u; + + *out = g - log(r) / 2; +out: + return ret; +} + +/* + * Gauss hypergeometric function when `x` is near unity. See limits in DLMF 15.4. + * + * TODO: this works in practice, but when (c - a - b) is close to zero the limits don't + * converge. A good reference is Buhring 2003 "Partial sums of hypergeometric series of + * unit argument" + */ +static int +hyp2f1_unity(double a, double b, double c, double x, double *out) +{ + int ret = 0; + double g, value; + + tsd_bug_assert(tsd_isclose(x, 1.0)); + if (!(x < 1.0)) { + ret = tsd_trace_error(TSD_ERR_INVALID_HYPERGEO); + goto out; + } + + g = c - a - b; + + if (g < 0.0) { + value = lgamma(c) + lgamma(-g) - lgamma(a) - lgamma(b) + g * log(1 - x); + } else if (g > 0.0) { + /* will only occur when a_i + a_j < 1 */ + value = lgamma(c) + lgamma(g) - lgamma(c - a) - lgamma(c - b); + } else { + /* will only occur when a_i + a_j == 1 */ + value = log(-log(1 - x)) + lgamma(a + b) - lgamma(a) - lgamma(b); + } + *out = value; +out: + return ret; +} + +/* + * Approximate a Gaussian hypergeometric function with real arguments, using Laplace's + * method with a calibration point. + */ +int +tsd_hyp2f1_laplace(double a, double b, double c, double x, double *out) +{ + int ret = 0; + double s, t, u, y, yy, my, ymy, r, f, unity, denom; + + /* TODO: simplify, we can safely assume a,b > 0? */ + if (!(c > 0.0 && a >= 0.0 && b >= 0.0 && c >= a && x < 1.0)) { + ret = tsd_trace_error(TSD_ERR_INVALID_HYPERGEO); + goto out; + } + + if (x == 0.0) { + *out = 0.0; + goto out; + } + + s = 0.0; + if (x < 0.0) { + s = -b * log(1 - x); + a = c - a; + x = x / (x - 1); + } + + if (tsd_isclose(x, 1.0)) { + ret = hyp2f1_unity(a, b, c, x, &unity); + if (ret != 0) { + goto out; + } + *out = s + unity; + goto out; + } + + t = x * (b - a) - c; + u = sqrt(tsd_ipow(t, 2) - 4 * a * x * (c - b)) - t; + if (u == 0.0) { + ret = tsd_trace_error(TSD_ERR_ZERO_DIVISION); + goto out; + } + y = 2 * a / u; + + /* Root on boundary */ + if (!(0 < y && y < 1)) { + ret = tsd_trace_error(TSD_ERR_INVALID_HYPERGEO); + goto out; + } + + yy = tsd_ipow(y, 2) / a; + denom = c - a; + if (denom == 0.0) { + ret = tsd_trace_error(TSD_ERR_ZERO_DIVISION); + goto out; + } + my = tsd_ipow(1 - y, 2) / denom; + ymy = tsd_ipow(x, 2) * b * yy * my / tsd_ipow(1 - x * y, 2); + r = yy + my - ymy; + f = (c - 0.5) * log(c); + f += a * (log(y) - log(a)); + f += (c - a) * (log(1 - y) - log(c - a)); + f -= b * log(1 - x * y); + + *out = f - log(r) / 2 + s; +out: + return ret; +} + +/* Gaussian approximation of the derivative of the lower incomplete gamma function. */ +static double +gammainc_der_gaussian(double p, double x) +{ + double pn1, grad, cbrt_ratio; + + cbrt_ratio = pow(x / p, 1.0 / 3.0); + pn1 = 3 * sqrt(p) * (cbrt_ratio + 1 / (9 * p) - 1); + grad = pn1 / (2 * p) - 1 / sqrt(p) * (cbrt_ratio + 1 / (3 * p)); + grad *= 1 / sqrt(2 * TSD_PI) * exp(-(tsd_ipow(pn1, 2)) / 2); + return grad; +} + +/* Derivative of the lower incomplete gamma function by series expansion. */ +static double +gammainc_der_series(double p, double x, double tol, double elimit) +{ + double arg, value, grad, c, dc, a, darg; + + arg = p * log(x) - x - lgamma(p + 1); + value = 1.0; + grad = 0.0; + c = 1.0; + dc = 0.0; + a = p; + while (1) { + a += 1.0; + dc = -c * x / tsd_ipow(a, 2) + dc * x / a; + c *= x / a; + value += c; + grad += dc; + if (c <= tol) { + break; + } + } + darg = exp(arg) * (log(x) - digamma_positive(p + 1)); + grad = grad * exp(arg) + value * darg; + arg += log(value); + if (!(arg >= elimit)) { + grad = 0.0; + } + return grad; +} + +/* Derivative of the upper incomplete gamma function by continued fraction. */ +static double +gammainc_der_fraction(double p, double x, double tol, double elimit, double oflo) +{ + double arg, a, b, c, an, value, grad, rn, darg; + double pn1, pn2, pn3, pn4, pn5, pn6; + double dpn1, dpn2, dpn3, dpn4, dpn5, dpn6; + + arg = p * log(x) - x - lgamma(p); + a = 1.0 - p; + b = a + x + 1.0; + c = 0.0; + pn1 = 1.0; + pn2 = x; + pn3 = x + 1.0; + pn4 = x * b; + dpn1 = 0.0; + dpn2 = 0.0; + dpn3 = 0.0; + dpn4 = -x; + value = pn3 / pn4; + grad = 0.0; + while (1) { + a += 1.0; + b += 2.0; + c += 1.0; + an = a * c; + pn5 = b * pn3 - an * pn1; + pn6 = b * pn4 - an * pn2; + dpn5 = b * dpn3 - pn3 - an * dpn1 + c * pn1; + dpn6 = b * dpn4 - pn4 - an * dpn2 + c * pn2; + if (pn6 != 0.0) { + rn = pn5 / pn6; + grad = (dpn5 * pn6 - pn5 * dpn6) / tsd_ipow(pn6, 2); + if (fabs(value - rn) <= tsd_min(tol, tol * rn)) { + break; + } + value = rn; + } + pn1 = pn3; + pn2 = pn4; + pn3 = pn5; + pn4 = pn6; + dpn1 = dpn3; + dpn2 = dpn4; + dpn3 = dpn5; + dpn4 = dpn6; + if (oflo <= fabs(pn5)) { + pn1 /= oflo; + pn2 /= oflo; + pn3 /= oflo; + pn4 /= oflo; + dpn1 /= oflo; + dpn2 /= oflo; + dpn3 /= oflo; + dpn4 /= oflo; + } + } + darg = exp(arg) * (log(x) - digamma_positive(p)); + grad = grad * exp(arg) + value * darg; + arg += log(value); + if (arg >= elimit) { + grad *= -1.0; + } else { + grad = 0.0; + } + return grad; +} + +/* + * Derivative of the lower incomplete gamma function with regards to `p`. + * + * Based on Shea B (1988) "Algorithm AS 239" Applied Statistics 37: 466-473 + * + * Adapted from https://people.math.sc.edu/Burkardt/cpp_src/asa239/asa239.cpp + */ +int +tsd_gammainc_der(double p, double x, double *out) +{ + int ret = 0; + const double elimit = -88.0; + const double oflo = 1.0e37; + const double plimit = 1.0e3; + const double tol = 1.0e-14; + const double xbig = 1.0e8; + + if (!(x >= 0.0 && p > 0.0)) { + ret = tsd_trace_error(TSD_ERR_INVALID_HYPERGEO); + goto out; + } + + if (x == 0) { + *out = 0.0; + } else if (x > xbig) { + *out = 0.0; + } else if (p > plimit) { + *out = gammainc_der_gaussian(p, x); + } else if (x <= 1 || x < p) { + *out = gammainc_der_series(p, x, tol, elimit); + } else { + *out = gammainc_der_fraction(p, x, tol, elimit, oflo); + } +out: + return ret; +} diff --git a/lib/mathutil.h b/lib/mathutil.h new file mode 100644 index 00000000..6e583a89 --- /dev/null +++ b/lib/mathutil.h @@ -0,0 +1,77 @@ +/* + * MIT License + * + * Copyright (c) 2026 Tskit Developers + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in all + * copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE + * SOFTWARE. + */ + +#ifndef TSD_MATHUTIL_H +#define TSD_MATHUTIL_H + +#include + +/* Constants that only defines as extensions (and MSVC not by default). */ +#define TSD_PI 3.141592653589793 +#define TSD_EULER_GAMMA 0.5772156649015329 + +/* + * x ** n for a small positive integer constant n, by repeated squaring (the + * multiplication order of LLVM's llvm.powi, and of the oracles' `ipow`); ipow(x, 2) is + * exactly x * x. It can differ in the last bit from pow(x, n). + */ +static inline double +tsd_ipow(double x, int n) +{ + double result = 1.0; + + while (1) { + if (n & 1) { + result *= x; + } + n >>= 1; + if (n == 0) { + return result; + } + x *= x; + } +} + +/* Python's min(a, b): b if b < a else a (so NaN handling differs from fmin). */ +static inline double +tsd_min(double a, double b) +{ + return b < a ? b : a; +} + +/* Python's max(a, b): b if b > a else a (so NaN handling differs from fmax). */ +static inline double +tsd_max(double a, double b) +{ + return b > a ? b : a; +} + +/* np.isclose(a, b) for finite or NaN arguments, with default rtol and atol. */ +static inline int +tsd_isclose(double a, double b) +{ + return fabs(a - b) <= 1e-8 + 1e-5 * fabs(b); +} + +#endif diff --git a/lib/meson.build b/lib/meson.build index bbcc384f..2ba47752 100644 --- a/lib/meson.build +++ b/lib/meson.build @@ -11,13 +11,20 @@ extra_c_args = [ '-Wcast-qual', '-Wwrite-strings', '-Wnested-externs', '-fshort-enums', '-fno-common', '-ffp-contract=off'] +test_c_args = extra_c_args if get_option('buildtype') == 'debug' - extra_c_args += ['-DTSD_TRACE_ERRORS'] + test_c_args += ['-DTSD_TRACE_ERRORS'] endif -tsdate_sources = ['err.c'] +tsdate_sources = ['err.c', 'gammaincinv.c', 'hypergeo.c', 'approx.c', 'rescaling.c', + 'phasing.c', 'util.c', 'prior.c', 'variational.c'] tsdate_lib = static_library('tsdate', + sources: tsdate_sources, dependencies: [m_dep], + c_args: test_c_args) + +# For calling the library from Python with ctypes (evaluation/clib.py) +tsdate_shared = shared_library('tsdate', sources: tsdate_sources, dependencies: [m_dep], c_args: extra_c_args) diff --git a/lib/phasing.c b/lib/phasing.c new file mode 100644 index 00000000..94a7f96a --- /dev/null +++ b/lib/phasing.c @@ -0,0 +1,482 @@ +/* + * MIT License + * + * Copyright (c) 2026 Tskit Developers + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in all + * copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE + * SOFTWARE. + */ + +/* + * Phasing of singleton mutations in unphased individuals. + */ + +#include +#include + +#include "mathutil.h" +#include "tsdate.h" + +/* The state of the sweep over trees that assigns singletons to blocks. */ +typedef struct { + const uint8_t *individuals_unphased; + const tsd_id_t *nodes_individual; + const tsd_id_t *edges_child; + tsd_id_t *individuals_edges; /* two edges per individual */ + double *individuals_position; + double *individuals_singletons; + tsd_id_t *individuals_block; + double *blocks_stats; + tsd_id_t *blocks_edges; + tsd_size_t num_blocks; + tsd_size_t num_flushed; +} block_state_t; + +/* An edge ends: if its individual then has a single edge, the block is complete. */ +static void +block_edge_out(block_state_t *state, tsd_id_t e, double left) +{ + const tsd_id_t i = state->nodes_individual[state->edges_child[e]]; + tsd_id_t *edges; + tsd_id_t s, block; + + if (i == TSD_NULL || !state->individuals_unphased[i]) { + return; + } + edges = state->individuals_edges + 2 * (tsd_size_t) i; + tsd_bug_assert(edges[0] == e || edges[1] == e); + s = edges[1] == e ? edges[0] : edges[1]; + edges[0] = s; + edges[1] = TSD_NULL; + if (s != TSD_NULL) { + block = state->individuals_block[i]; + tsd_bug_assert(block != TSD_NULL); + state->blocks_edges[2 * (tsd_size_t) block] = e; + state->blocks_edges[2 * (tsd_size_t) block + 1] = s; + state->blocks_stats[2 * (tsd_size_t) block] = state->individuals_singletons[i]; + state->blocks_stats[2 * (tsd_size_t) block + 1] + = left - state->individuals_position[i]; + state->num_flushed++; + state->individuals_position[i] = NAN; + state->individuals_block[i] = TSD_NULL; + state->individuals_singletons[i] = 0.0; + } +} + +/* An edge starts: it becomes an edge of its individual, and may start a block. */ +static int +block_edge_in(block_state_t *state, tsd_id_t e, double left) +{ + int ret = 0; + const tsd_id_t i = state->nodes_individual[state->edges_child[e]]; + tsd_id_t *edges; + tsd_id_t u, v; + + if (i == TSD_NULL || !state->individuals_unphased[i]) { + goto out; + } + edges = state->individuals_edges + 2 * (tsd_size_t) i; + u = edges[0]; + v = edges[1]; + if (u != TSD_NULL && v != TSD_NULL) { + ret = tsd_trace_error(TSD_ERR_UNPHASED_INDIVIDUAL_EDGES); + goto out; + } + edges[0] = e; + edges[1] = v > u ? v : u; + state->individuals_position[i] = left; + if (state->individuals_block[i] == TSD_NULL) { + state->individuals_block[i] = (tsd_id_t) state->num_blocks; + state->num_blocks++; + } +out: + return ret; +} + +/* + * Group the singleton mutations of unphased individuals into blocks: the regions over + * which both haplotype edges of an individual are unchanged. A mutation's block is its + * individual's block at its position, or TSD_NULL. + * + * Writes `mutations_block` (one id per mutation) and allocates `blocks_stats` (rows of + * the number of singletons and the span of each block) and `blocks_edges` (rows of + * the two edges of each block), both `*num_blocks` rows, indexed by block id. The + * caller frees them. + */ +int +tsd_block_singletons(tsd_size_t num_nodes, tsd_size_t num_individuals, + tsd_size_t num_edges, tsd_size_t num_mutations, const uint8_t *individuals_unphased, + const tsd_id_t *nodes_individual, const tsd_id_t *mutations_node, + const double *mutations_position, const tsd_id_t *edges_child, + const double *edges_left, const double *edges_right, const tsd_id_t *indexes_insert, + const tsd_id_t *indexes_remove, double sequence_length, tsd_size_t *num_blocks, + double **blocks_stats, tsd_id_t **blocks_edges, tsd_id_t *mutations_block) +{ + int ret = 0; + block_state_t state; + tsd_id_t *indexes_mutation = NULL; + tsd_id_t *individuals_edges = NULL; + tsd_id_t *individuals_block = NULL; + double *individuals_position = NULL; + double *individuals_singletons = NULL; + double *stats = NULL; + tsd_id_t *block_edges = NULL; + const tsd_size_t num_rows = num_edges > 0 ? num_edges : 1; + const tsd_size_t num_ind = num_individuals > 0 ? num_individuals : 1; + tsd_size_t a, b, d, j; + tsd_id_t m, i; + double left, right; + + ret = tsd_check_ids(num_nodes, nodes_individual, num_individuals, 1, + TSD_ERR_INDIVIDUAL_OUT_OF_BOUNDS); + if (ret != 0) { + goto out; + } + ret = tsd_check_ids( + num_edges, edges_child, num_nodes, 0, TSD_ERR_NODE_OUT_OF_BOUNDS); + if (ret != 0) { + goto out; + } + ret = tsd_check_ids( + num_mutations, mutations_node, num_nodes, 0, TSD_ERR_NODE_OUT_OF_BOUNDS); + if (ret != 0) { + goto out; + } + ret = tsd_check_edge_sweep(num_edges, edges_left, edges_right, indexes_insert, + indexes_remove, sequence_length); + if (ret != 0) { + goto out; + } + indexes_mutation + = malloc((num_mutations > 0 ? num_mutations : 1) * sizeof(tsd_id_t)); + individuals_edges = malloc(2 * num_ind * sizeof(*individuals_edges)); + individuals_block = malloc(num_ind * sizeof(*individuals_block)); + individuals_position = malloc(num_ind * sizeof(*individuals_position)); + individuals_singletons = malloc(num_ind * sizeof(*individuals_singletons)); + stats = malloc(2 * num_rows * sizeof(*stats)); + block_edges = malloc(2 * num_rows * sizeof(*block_edges)); + if (indexes_mutation == NULL || individuals_edges == NULL + || individuals_block == NULL || individuals_position == NULL + || individuals_singletons == NULL || stats == NULL || block_edges == NULL) { + ret = tsd_trace_error(TSD_ERR_NO_MEMORY); + goto out; + } + ret = tsd_argsort(num_mutations, mutations_position, indexes_mutation); + if (ret != 0) { + goto out; + } + for (j = 0; j < num_individuals; j++) { + individuals_edges[2 * j] = TSD_NULL; + individuals_edges[2 * j + 1] = TSD_NULL; + individuals_block[j] = TSD_NULL; + individuals_position[j] = NAN; + individuals_singletons[j] = 0.0; + } + for (j = 0; j < num_mutations; j++) { + mutations_block[j] = TSD_NULL; + } + + state.individuals_unphased = individuals_unphased; + state.nodes_individual = nodes_individual; + state.edges_child = edges_child; + state.individuals_edges = individuals_edges; + state.individuals_position = individuals_position; + state.individuals_singletons = individuals_singletons; + state.individuals_block = individuals_block; + state.blocks_stats = stats; + state.blocks_edges = block_edges; + state.num_blocks = 0; + state.num_flushed = 0; + + a = 0; + b = 0; + d = 0; + left = 0.0; + while (a < num_edges || b < num_edges) { + while (b < num_edges && edges_right[indexes_remove[b]] == left) { + block_edge_out(&state, indexes_remove[b], left); + b++; + } + while (a < num_edges && edges_left[indexes_insert[a]] == left) { + ret = block_edge_in(&state, indexes_insert[a], left); + if (ret != 0) { + goto out; + } + a++; + } + right = sequence_length; + if (b < num_edges) { + right = tsd_min(right, edges_right[indexes_remove[b]]); + } + if (a < num_edges) { + right = tsd_min(right, edges_left[indexes_insert[a]]); + } + left = right; + while (d < num_mutations && mutations_position[indexes_mutation[d]] < right) { + m = indexes_mutation[d]; + i = nodes_individual[mutations_node[m]]; + if (i != TSD_NULL && individuals_unphased[i]) { + mutations_block[m] = individuals_block[i]; + individuals_singletons[i] += 1.0; + } + d++; + } + } + /* Every block must have been completed */ + if (state.num_blocks != state.num_flushed) { + ret = tsd_trace_error(TSD_ERR_UNPHASED_INDIVIDUAL_EDGES); + goto out; + } + *num_blocks = state.num_blocks; + *blocks_stats = stats; + *blocks_edges = block_edges; + stats = NULL; + block_edges = NULL; +out: + tsd_safe_free(indexes_mutation); + tsd_safe_free(individuals_edges); + tsd_safe_free(individuals_block); + tsd_safe_free(individuals_position); + tsd_safe_free(individuals_singletons); + tsd_safe_free(stats); + tsd_safe_free(block_edges); + return ret; +} + +/* The sum of the first column of the likelihoods of the flagged edges. */ +static double +sum_flagged_likelihoods( + tsd_size_t num_edges, const double *edges_likelihood, const uint8_t *edges_unphased) +{ + double total = 0.0; + tsd_size_t e; + + for (e = 0; e < num_edges; e++) { + if (edges_unphased[e]) { + total += edges_likelihood[2 * e]; + } + } + return total; +} + +/* + * Reallocate the likelihood of the edges of unphased blocks: the mutations in a block + * give each edge of the block its phase probability of a mutation, and the other + * edge the remainder. `edges_likelihood` has two columns and is updated in place. + */ +int +tsd_reallocate_unphased(tsd_size_t num_edges, tsd_size_t num_mutations, + tsd_size_t num_blocks, const double *mutations_phase, + const tsd_id_t *mutations_block, const tsd_id_t *blocks_edges, + double *edges_likelihood) +{ + int ret = 0; + uint8_t *edges_unphased = NULL; + tsd_size_t m, e, j; + tsd_id_t b, i, k; + double num_unphased, phase; + + edges_unphased = calloc(num_edges > 0 ? num_edges : 1, sizeof(*edges_unphased)); + if (edges_unphased == NULL) { + ret = tsd_trace_error(TSD_ERR_NO_MEMORY); + goto out; + } + /* Edges that are not in range are caught below, if a mutation refers to them */ + for (j = 0; j < 2 * num_blocks; j++) { + e = (tsd_size_t) blocks_edges[j]; + if (blocks_edges[j] > TSD_NULL && e < num_edges) { + edges_unphased[e] = 1; + } + } + num_unphased = sum_flagged_likelihoods(num_edges, edges_likelihood, edges_unphased); + for (e = 0; e < num_edges; e++) { + if (edges_unphased[e]) { + edges_likelihood[2 * e] = 0.0; + } + } + + for (m = 0; m < num_mutations; m++) { + b = mutations_block[m]; + if (b == TSD_NULL) { + continue; + } + if (b < 0 || (tsd_size_t) b >= num_blocks) { + ret = tsd_trace_error(TSD_ERR_BLOCK_OUT_OF_BOUNDS); + goto out; + } + i = blocks_edges[2 * (tsd_size_t) b]; + k = blocks_edges[2 * (tsd_size_t) b + 1]; + if (i <= TSD_NULL || (tsd_size_t) i >= num_edges || k <= TSD_NULL + || (tsd_size_t) k >= num_edges) { + ret = tsd_trace_error(TSD_ERR_BLOCK_OUT_OF_BOUNDS); + goto out; + } + phase = mutations_phase[m]; + if (isnan(phase)) { /* TODO: fix rare numerical issue */ + continue; + } + if (!(phase >= 0.0 && phase <= 1.0)) { + ret = tsd_trace_error(TSD_ERR_PHASE_OUT_OF_RANGE); + goto out; + } + edges_likelihood[2 * (tsd_size_t) i] += phase; + edges_likelihood[2 * (tsd_size_t) k] += 1 - phase; + } + if (!tsd_isclose(num_unphased, + sum_flagged_likelihoods(num_edges, edges_likelihood, edges_unphased))) { + ret = tsd_trace_error(TSD_ERR_UNPHASED_LIKELIHOOD_NOT_CONSERVED); + goto out; + } +out: + tsd_safe_free(edges_unphased); + return ret; +} + +/* + * Add (sign = 1) or subtract (sign = -1) the sample counts of node `c` to those of + * `p` and of every ancestor of `p`. Each node has one parent in the current tree, so a + * walk of more than num_nodes steps has repeated a node: the edges form a cycle. + */ +static int +update_ancestors(tsd_size_t num_nodes, tsd_size_t num_sample_sets, tsd_id_t p, + tsd_id_t c, int32_t sign, const tsd_id_t *nodes_parent, int32_t *nodes_samples) +{ + const tsd_size_t S = num_sample_sets; + tsd_size_t k, depth = 0; + + while (p != TSD_NULL) { + if (depth == num_nodes) { + return tsd_trace_error(TSD_ERR_EDGES_FORM_CYCLE); + } + for (k = 0; k < S; k++) { + nodes_samples[(tsd_size_t) p * S + k] + += sign * nodes_samples[(tsd_size_t) c * S + k]; + } + p = nodes_parent[p]; + depth++; + } + return 0; +} + +/* + * For each mutation and each sample set, the number of members of the set below the + * mutation's node in the tree at the mutation's position. + */ +int +tsd_mutation_frequency(tsd_size_t num_nodes, tsd_size_t num_sample_sets, + tsd_size_t num_edges, tsd_size_t num_mutations, const uint8_t *nodes_sample, + const tsd_id_t *mutations_node, const double *mutations_position, + const tsd_id_t *edges_parent, const tsd_id_t *edges_child, const double *edges_left, + const double *edges_right, const tsd_id_t *indexes_insert, + const tsd_id_t *indexes_remove, double sequence_length, int32_t *mutations_freq) +{ + int ret = 0; + tsd_id_t *indexes_mutation = NULL; + tsd_id_t *nodes_parent = NULL; + int32_t *nodes_samples = NULL; + const tsd_size_t S = num_sample_sets; + tsd_size_t a, b, d, j, k; + tsd_id_t e, p, c, m; + double left, right; + + ret = tsd_check_edges(num_nodes, num_edges, edges_parent, edges_child); + if (ret != 0) { + goto out; + } + ret = tsd_check_ids( + num_mutations, mutations_node, num_nodes, 0, TSD_ERR_NODE_OUT_OF_BOUNDS); + if (ret != 0) { + goto out; + } + ret = tsd_check_edge_sweep(num_edges, edges_left, edges_right, indexes_insert, + indexes_remove, sequence_length); + if (ret != 0) { + goto out; + } + indexes_mutation + = malloc((num_mutations > 0 ? num_mutations : 1) * sizeof(tsd_id_t)); + nodes_parent = malloc((num_nodes > 0 ? num_nodes : 1) * sizeof(*nodes_parent)); + nodes_samples = malloc((num_nodes * S > 0 ? num_nodes * S : 1) * sizeof(int32_t)); + if (indexes_mutation == NULL || nodes_parent == NULL || nodes_samples == NULL) { + ret = tsd_trace_error(TSD_ERR_NO_MEMORY); + goto out; + } + ret = tsd_argsort(num_mutations, mutations_position, indexes_mutation); + if (ret != 0) { + goto out; + } + for (j = 0; j < num_nodes; j++) { + nodes_parent[j] = TSD_NULL; + for (k = 0; k < S; k++) { + nodes_samples[j * S + k] = nodes_sample[j * S + k] ? 1 : 0; + } + } + for (j = 0; j < num_mutations * S; j++) { + mutations_freq[j] = 0; + } + + a = 0; + b = 0; + d = 0; + left = 0.0; + while (a < num_edges || b < num_edges) { + while (b < num_edges && edges_right[indexes_remove[b]] == left) { /* out */ + e = indexes_remove[b]; + p = edges_parent[e]; + c = edges_child[e]; + nodes_parent[c] = TSD_NULL; + ret = update_ancestors(num_nodes, S, p, c, -1, nodes_parent, nodes_samples); + /* A cycle is found when the edge that closes it is inserted */ + tsd_bug_assert(ret == 0); + b++; + } + while (a < num_edges && edges_left[indexes_insert[a]] == left) { /* in */ + e = indexes_insert[a]; + p = edges_parent[e]; + c = edges_child[e]; + nodes_parent[c] = p; + ret = update_ancestors(num_nodes, S, p, c, 1, nodes_parent, nodes_samples); + if (ret != 0) { + goto out; + } + a++; + } + right = sequence_length; + if (b < num_edges) { + right = tsd_min(right, edges_right[indexes_remove[b]]); + } + if (a < num_edges) { + right = tsd_min(right, edges_left[indexes_insert[a]]); + } + left = right; + while (d < num_mutations && mutations_position[indexes_mutation[d]] < right) { + m = indexes_mutation[d]; + c = mutations_node[m]; + for (k = 0; k < S; k++) { + mutations_freq[(tsd_size_t) m * S + k] + = nodes_samples[(tsd_size_t) c * S + k]; + } + d++; + } + } +out: + tsd_safe_free(indexes_mutation); + tsd_safe_free(nodes_parent); + tsd_safe_free(nodes_samples); + return ret; +} diff --git a/lib/prior.c b/lib/prior.c new file mode 100644 index 00000000..e0cf61b5 --- /dev/null +++ b/lib/prior.c @@ -0,0 +1,168 @@ +/* + * MIT License + * + * Copyright (c) 2026 Tskit Developers + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in all + * copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE + * SOFTWARE. + */ + +/* + * Moments of node ages under the coalescent, conditional on the number of descendant + * leaves. Operation order and libm calls match the oracles in tests/oracle, which the + * tests compare exactly. + */ + +#include +#include + +#include "mathutil.h" +#include "tsdate.h" + +/* + * Integrate an expectation over counts of extant ancestors. In a tree with "n" tips, + * the probability that there are "a" extant ancestors when a subtree of size "k" + * coalesces is hypergeometric-ish (Wuif & Donnelly 1998), and may be calculated + * recursively over increasing "a" and decreasing "k" (e.g. using recursive + * relationships for binomial coefficients). + * + * `val` has `num_tips` (at least two) rows and `num_moments` columns; `out` has + * `num_tips + 1` rows and is written in full. + */ +int +tsd_marginalize_over_ancestors( + tsd_size_t num_tips, tsd_size_t num_moments, const double *val, double *out) +{ + int ret = 0; + double *pr_a_ln = NULL; /* log Pr(a | k, n) */ + const tsd_size_t n = num_tips; + const tsd_size_t N = num_moments; + tsd_size_t k, a, j; + double dk, dnk, dnak, weight, constant; + + if (num_tips < 2) { + ret = tsd_trace_error(TSD_ERR_TOO_FEW_TIPS); + goto out; + } + pr_a_ln = malloc((n + 1) * sizeof(*pr_a_ln)); + if (pr_a_ln == NULL) { + ret = tsd_trace_error(TSD_ERR_NO_MEMORY); + goto out; + } + for (j = 0; j < (n + 1) * N; j++) { + out[j] = 0.0; + } + pr_a_ln[0] = NAN; + pr_a_ln[1] = NAN; + pr_a_ln[2] = 0.0; + for (k = n - 1; k > 1; k--) { + dk = (double) k; + dnk = (double) (n - k); + /* log(0) at k == 2 is -infinity, and the value is unused then */ + constant = log(dnk) + log((double) (k - 2)) - log(dk + 1); + for (a = 2; a < n - k + 2; a++) { + weight = exp(pr_a_ln[a]); + for (j = 0; j < N; j++) { + out[k * N + j] += weight * val[a * N + j]; + } + if (k > 2) { /* Pr(a | k, n) to Pr(a | k - 1, n) */ + dnak = (double) (n - a - k + 2); + pr_a_ln[a] += constant - log(dnak); + } + } + if (k > 2) { /* Pr(n - k + 1 | k - 1, n) to Pr(n - k + 2 | k - 1, n) */ + pr_a_ln[n - k + 2] = pr_a_ln[n - k + 1] + log((double) (n - k + 2)) + - log(dk + 1) - constant; + } + } + for (j = 0; j < N; j++) { + out[n * N + j] = val[N + j]; + } +out: + tsd_safe_free(pr_a_ln); + return ret; +} + +/* + * Variance of node age conditional on the number of descendant leaves, under the + * standard coalescent. Writes `num_tips + 1` values, indexed by the number of + * descendant leaves. For a single tip the variances are zero. + */ +int +tsd_conditional_coalescent_variance(tsd_size_t num_tips, double *variance_out) +{ + int ret = 0; + double *mean = NULL; + double *variance = NULL; + double *val = NULL; + double *moments = NULL; + tsd_size_t i, n; + double rate; + + if (num_tips < 1) { + ret = tsd_trace_error(TSD_ERR_TOO_FEW_TIPS); + goto out; + } + n = num_tips; + if (n == 1) { + variance_out[0] = 0.0; + variance_out[1] = 0.0; + goto out; + } + mean = malloc(n * sizeof(*mean)); + variance = malloc(n * sizeof(*variance)); + val = malloc(2 * n * sizeof(*val)); + moments = malloc(2 * (n + 1) * sizeof(*moments)); + if (mean == NULL || variance == NULL || val == NULL || moments == NULL) { + ret = tsd_trace_error(TSD_ERR_NO_MEMORY); + goto out; + } + /* coalescence rates, indexed by the number of lineages minus one */ + for (i = 0; i < n; i++) { + rate = 0.0; + if (i > 0) { + rate = 2.0 / (double) ((i + 1) * i); + } + mean[i] = rate; + variance[i] = rate * rate; + } + /* hypoexponential mean and variance; e.g. conditional on the number of extant + * ancestors when the node coalesces, the expected time of coalescence is the sum + * of exponential RVs (Wuif and Donnelly 1998) */ + for (i = n - 2; i > 0; i--) { + mean[i] += mean[i + 1]; + variance[i] += variance[i + 1]; + } + for (i = 0; i < n; i++) { + val[2 * i] = mean[i]; + val[2 * i + 1] = variance[i] + mean[i] * mean[i]; + } + ret = tsd_marginalize_over_ancestors(n, 2, val, moments); + if (ret != 0) { + goto out; + } + for (i = 0; i <= n; i++) { + variance_out[i] = moments[2 * i + 1] - moments[2 * i] * moments[2 * i]; + } +out: + tsd_safe_free(mean); + tsd_safe_free(variance); + tsd_safe_free(val); + tsd_safe_free(moments); + return ret; +} diff --git a/lib/rescaling.c b/lib/rescaling.c new file mode 100644 index 00000000..99250c4c --- /dev/null +++ b/lib/rescaling.c @@ -0,0 +1,825 @@ +/* + * MIT License + * + * Copyright (c) 2026 Tskit Developers + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in all + * copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE + * SOFTWARE. + */ + +/* + * Rescaling of time so that the mutation rate is constant. Operation order and libm + * calls match the oracles in tests/oracle, which the tests compare exactly. + * + * Arrays whose size is not known beforehand are allocated with room for one more + * element than needed, so that empty inputs still give valid pointers. + */ + +#include +#include +#include + +#include "mathutil.h" +#include "tsdate.h" + +/* The null id, as tskit.NULL */ +#define NO_ID ((tsd_id_t) - 1) + +/* A value with its position, for sorting (the equivalent of np.argsort). */ +typedef struct { + double value; + tsd_id_t index; +} sort_item_t; + +/* Order by value, NaN last, ties by position. */ +static int +compare_sort_items(const void *a, const void *b) +{ + const sort_item_t *x = (const sort_item_t *) a; + const sort_item_t *y = (const sort_item_t *) b; + int x_nan = isnan(x->value); + int y_nan = isnan(y->value); + int ret; + + if (x_nan != y_nan) { + ret = x_nan ? 1 : -1; + } else if (!x_nan && x->value < y->value) { + ret = -1; + } else if (!x_nan && x->value > y->value) { + ret = 1; + } else { + ret = (x->index > y->index) - (x->index < y->index); + } + return ret; +} + +static int +compare_ids(const void *a, const void *b) +{ + tsd_id_t x = *(const tsd_id_t *) a; + tsd_id_t y = *(const tsd_id_t *) b; + + return (x > y) - (x < y); +} + +/* Whether `a` is less than or equal to `key`, where NaN `key` is above everything. */ +static int +less_equal(double a, double key) +{ + return isnan(key) || a <= key; +} + +/* + * The first index in [min_idx, max_idx] at which the sorted array `a` exceeds `key` + * (the search of np.searchsorted(a, key, "right")): the number of entries less than or + * equal to `key` if the range contains it. NaN is greater than every number. + */ +static tsd_size_t +bisect_right(const double *a, double key, tsd_size_t min_idx, tsd_size_t max_idx) +{ + tsd_size_t mid_idx; + + while (min_idx < max_idx) { + mid_idx = min_idx + ((max_idx - min_idx) >> 1); + if (less_equal(a[mid_idx], key)) { + min_idx = mid_idx + 1; + } else { + max_idx = mid_idx; + } + } + return min_idx; +} + +/* np.searchsorted(a, key, "right") for one key */ +static tsd_size_t +searchsorted_right(tsd_size_t n, const double *a, double key) +{ + return bisect_right(a, key, 0, n); +} + +/* Whether np.all(np.diff(a) > 0) */ +static int +is_increasing(tsd_size_t n, const double *a) +{ + tsd_size_t j; + double diff; + + for (j = 1; j < n; j++) { + diff = a[j] - a[j - 1]; + if (!(diff > 0)) { + return 0; + } + } + return 1; +} + +/* + * The time `x` mapped from the original to the rescaled breakpoints by the piece + * `i`, which has the slope (the last piece is flat, as it has no upper breakpoint). + */ +static double +rescale_piece(tsd_size_t n, const double *original_breaks, const double *rescaled_breaks, + tsd_size_t i, double x) +{ + double scaling = 0.0; + double offset; + + if (i + 1 < n) { + scaling = (rescaled_breaks[i + 1] - rescaled_breaks[i]) + / (original_breaks[i + 1] - original_breaks[i]); + } + offset = x - original_breaks[i]; + return rescaled_breaks[i] + scaling * offset; +} + +void +tsd_epoch_stats_free(tsd_epoch_stats_t *stats) +{ + tsd_safe_free(stats->counts); + tsd_safe_free(stats->offset); + tsd_safe_free(stats->duration); + stats->num_epochs = 0; +} + +/* ------------------------------------------------------------------------- * + * Changepoints + * ------------------------------------------------------------------------- */ + +int +tsd_fixed_changepoints(tsd_size_t num_counts, const double *counts, int64_t epochs, + tsd_id_t **breaks, tsd_size_t *num_breaks) +{ + int ret = 0; + double *cumulative = NULL; + tsd_id_t *e = NULL; + tsd_size_t j, num_e, min_idx, max_idx; + double total, step, z, last_z; + + if (epochs <= 0) { + ret = tsd_trace_error(TSD_ERR_NONPOSITIVE_INTERVALS); + goto out; + } + num_e = (tsd_size_t) epochs + 1; + cumulative = malloc((num_counts + 1) * sizeof(*cumulative)); + e = malloc(num_e * sizeof(*e)); + if (cumulative == NULL || e == NULL) { + ret = tsd_trace_error(TSD_ERR_NO_MEMORY); + goto out; + } + /* + * The cumulative counts, normalised by the total. Division by zero is not an + * error: the result is NaN, which compares as greater than every number. + * NOTE: current behaviour, possibly a bug: if all counts are zero, every + * normalised count is NaN and the breakpoints are [-1, ..., -1, num_counts]. + */ + cumulative[0] = 0.0; + for (j = 0; j < num_counts; j++) { + cumulative[j + 1] = cumulative[j] + counts[j]; + } + total = cumulative[num_counts]; + for (j = 0; j <= num_counts; j++) { + cumulative[j] = cumulative[j] / total; + } + /* + * Equally spaced quantiles, as np.linspace(0, 1, epochs + 1). The quantiles + * increase, so each search starts from the last result. + */ + step = 1.0 / (double) epochs; + last_z = 0.0; + min_idx = 0; + max_idx = num_counts + 1; + for (j = 0; j < num_e; j++) { + z = 0.0 + (double) j * step; + if (j + 1 == num_e) { + z = 1.0; + } + if (j == 0 || less_equal(last_z, z)) { + max_idx = num_counts + 1; + } else { + min_idx = 0; + max_idx = max_idx < num_counts + 1 ? max_idx + 1 : num_counts + 1; + } + last_z = z; + min_idx = bisect_right(cumulative, z, min_idx, max_idx); + e[j] = (tsd_id_t) ((int64_t) min_idx - 1); + } + if (e[0] > 0) { + e[0] = 0; + } + if (e[num_e - 1] < (int64_t) num_counts) { + e[num_e - 1] = (tsd_id_t) num_counts; + } + *breaks = e; + *num_breaks = num_e; + e = NULL; +out: + tsd_safe_free(cumulative); + tsd_safe_free(e); + return ret; +} + +/* ------------------------------------------------------------------------- * + * Counting mutations + * ------------------------------------------------------------------------- */ + +/* + * Add (sign = 1) or remove (sign = -1) the span of the edge `e`, to the parent `p` of + * its child `c`, and to every ancestor of `p`, in proportion to the number of + * samples below `c`; and update the sample counts of the ancestors. Each node has one + * parent in the current tree, so a walk of more than num_nodes steps has repeated a + * node: the edges form a cycle. + */ +static int +count_update_ancestors(tsd_size_t num_nodes, tsd_id_t e, tsd_id_t p, tsd_id_t c, + double sign, double remainder, const tsd_id_t *nodes_edge, + const tsd_id_t *nodes_parent, double *nodes_samples, double *edges_stats) +{ + tsd_id_t next_e, next_p; + tsd_size_t depth = 0; + double span; + + while (p != NO_ID) { + if (depth == num_nodes) { + return tsd_trace_error(TSD_ERR_EDGES_FORM_CYCLE); + } + span = nodes_samples[c] * remainder; + edges_stats[2 * (tsd_size_t) e + 1] += sign * span; + nodes_samples[p] += sign * nodes_samples[c]; + next_e = nodes_edge[p]; + next_p = nodes_parent[p]; + e = next_e; + p = next_p; + depth++; + } + return 0; +} + +int +tsd_count_mutations(tsd_size_t num_nodes, const uint8_t *node_is_sample, + tsd_size_t num_mutations, const tsd_id_t *mutations_node, + const double *mutations_position, tsd_size_t num_edges, const tsd_id_t *edges_parent, + const tsd_id_t *edges_child, const double *edges_left, const double *edges_right, + const tsd_id_t *indexes_insert, const tsd_id_t *indexes_remove, + double sequence_length, int size_biased, double *edges_stats, + tsd_id_t *mutations_edge) +{ + int ret = 0; + sort_item_t *mutation_order = NULL; + double *nodes_samples = NULL; + tsd_id_t *nodes_edge = NULL; + tsd_id_t *nodes_parent = NULL; + tsd_size_t j, a, b, d; + tsd_id_t e, p, c, m; + double left, right, remainder, edge_position; + + ret = tsd_check_edges(num_nodes, num_edges, edges_parent, edges_child); + if (ret != 0) { + goto out; + } + ret = tsd_check_ids( + num_mutations, mutations_node, num_nodes, 0, TSD_ERR_NODE_OUT_OF_BOUNDS); + if (ret != 0) { + goto out; + } + ret = tsd_check_edge_sweep(num_edges, edges_left, edges_right, indexes_insert, + indexes_remove, sequence_length); + if (ret != 0) { + goto out; + } + mutation_order = malloc((num_mutations + 1) * sizeof(*mutation_order)); + nodes_samples = malloc((num_nodes + 1) * sizeof(*nodes_samples)); + nodes_edge = malloc((num_nodes + 1) * sizeof(*nodes_edge)); + nodes_parent = malloc((num_nodes + 1) * sizeof(*nodes_parent)); + if (mutation_order == NULL || nodes_samples == NULL || nodes_edge == NULL + || nodes_parent == NULL) { + ret = tsd_trace_error(TSD_ERR_NO_MEMORY); + goto out; + } + for (j = 0; j < num_mutations; j++) { + mutation_order[j].value = mutations_position[j]; + mutation_order[j].index = (tsd_id_t) j; + mutations_edge[j] = NO_ID; + } + qsort(mutation_order, num_mutations, sizeof(*mutation_order), compare_sort_items); + for (j = 0; j < num_nodes; j++) { + nodes_samples[j] = node_is_sample[j] ? 1.0 : 0.0; + nodes_edge[j] = NO_ID; + nodes_parent[j] = NO_ID; + } + memset(edges_stats, 0, 2 * num_edges * sizeof(*edges_stats)); + + left = 0.0; + a = 0; + b = 0; + d = 0; + while (a < num_edges || b < num_edges) { + remainder = sequence_length - left; + + /* edges out */ + while (b < num_edges && edges_right[indexes_remove[b]] == left) { + e = indexes_remove[b]; + p = edges_parent[e]; + c = edges_child[e]; + nodes_edge[c] = NO_ID; + nodes_parent[c] = NO_ID; + if (size_biased) { + ret = count_update_ancestors(num_nodes, e, p, c, -1.0, remainder, + nodes_edge, nodes_parent, nodes_samples, edges_stats); + /* A cycle is found when the edge that closes it is inserted */ + tsd_bug_assert(ret == 0); + } else { + edges_stats[2 * (tsd_size_t) e + 1] -= remainder; + } + b++; + } + + /* edges in */ + while (a < num_edges && edges_left[indexes_insert[a]] == left) { + e = indexes_insert[a]; + p = edges_parent[e]; + c = edges_child[e]; + nodes_edge[c] = e; + nodes_parent[c] = p; + if (size_biased) { + ret = count_update_ancestors(num_nodes, e, p, c, 1.0, remainder, + nodes_edge, nodes_parent, nodes_samples, edges_stats); + if (ret != 0) { + goto out; + } + } else { + edges_stats[2 * (tsd_size_t) e + 1] += remainder; + } + a++; + } + + right = sequence_length; + if (b < num_edges) { + edge_position = edges_right[indexes_remove[b]]; + right = tsd_min(right, edge_position); + } + if (a < num_edges) { + edge_position = edges_left[indexes_insert[a]]; + right = tsd_min(right, edge_position); + } + left = right; + + while (d < num_mutations && mutation_order[d].value < right) { + m = mutation_order[d].index; + c = mutations_node[m]; + e = nodes_edge[c]; + if (e != NO_ID) { + mutations_edge[m] = e; + edges_stats[2 * (tsd_size_t) e] += size_biased ? nodes_samples[c] : 1.0; + } + d++; + } + } +out: + tsd_safe_free(mutation_order); + tsd_safe_free(nodes_samples); + tsd_safe_free(nodes_edge); + tsd_safe_free(nodes_parent); + return ret; +} + +/* ------------------------------------------------------------------------- * + * Mutational area and the time scale + * ------------------------------------------------------------------------- */ + +int +tsd_mutational_area(tsd_size_t num_nodes, const double *nodes_time, tsd_size_t num_edges, + const double *likelihoods, const tsd_id_t *edges_parent, const tsd_id_t *edges_child, + tsd_epoch_stats_t *stats, tsd_id_t *nodes_index) +{ + int ret = 0; + sort_item_t *order = NULL; + double *epoch_breaks = NULL; + double *epoch_counts = NULL; + double *counts = NULL; + double *offset = NULL; + double *duration = NULL; + tsd_size_t j, k, num_breaks, num_epochs, a, b; + tsd_id_t p, c, node, previous; + double length, edge_count, edge_span; + + ret = tsd_check_edges(num_nodes, num_edges, edges_parent, edges_child); + if (ret != 0) { + goto out; + } + order = malloc((num_nodes + 1) * sizeof(*order)); + epoch_breaks = malloc((num_nodes + 1) * sizeof(*epoch_breaks)); + if (order == NULL || epoch_breaks == NULL) { + ret = tsd_trace_error(TSD_ERR_NO_MEMORY); + goto out; + } + + /* Index the nodes by unique time breaks; the first epoch starts at zero */ + for (j = 0; j < num_nodes; j++) { + order[j].value = nodes_time[j]; + order[j].index = (tsd_id_t) j; + nodes_index[j] = 0; + } + qsort(order, num_nodes, sizeof(*order), compare_sort_items); + epoch_breaks[0] = 0.0; + num_breaks = 1; + k = 0; + for (j = 1; j < num_nodes; j++) { + node = order[j].index; + previous = order[j - 1].index; + if (nodes_time[node] > nodes_time[previous]) { + epoch_breaks[num_breaks] = nodes_time[node]; + num_breaks++; + k++; + } + nodes_index[node] = (tsd_id_t) k; + } + num_epochs = num_breaks - 1; + + epoch_counts = calloc(2 * num_epochs + 1, sizeof(*epoch_counts)); + counts = malloc((num_epochs + 1) * sizeof(*counts)); + offset = malloc((num_epochs + 1) * sizeof(*offset)); + duration = malloc((num_epochs + 1) * sizeof(*duration)); + if (epoch_counts == NULL || counts == NULL || offset == NULL || duration == NULL) { + ret = tsd_trace_error(TSD_ERR_NO_MEMORY); + goto out; + } + + /* Pass over edges, measuring overlap with each time interval, using the + * instantaneous mutation rate of each edge. */ + for (j = 0; j < num_edges; j++) { + p = edges_parent[j]; + c = edges_child[j]; + length = nodes_time[p] - nodes_time[c]; + if (!(length > 0)) { + continue; + } + edge_count = likelihoods[2 * j] / length; + edge_span = likelihoods[2 * j + 1]; + a = (tsd_size_t) nodes_index[c]; + b = (tsd_size_t) nodes_index[p]; + if (a < num_epochs) { + epoch_counts[2 * a] += edge_count; + epoch_counts[2 * a + 1] += edge_span; + } + if (b < num_epochs) { + epoch_counts[2 * b] -= edge_count; + epoch_counts[2 * b + 1] -= edge_span; + } + } + for (k = 0; k < num_epochs; k++) { + counts[k] = epoch_counts[2 * k]; + offset[k] = epoch_counts[2 * k + 1]; + if (k > 0) { + counts[k] += counts[k - 1]; + offset[k] += offset[k - 1]; + } + duration[k] = epoch_breaks[k + 1] - epoch_breaks[k]; + } + stats->num_epochs = num_epochs; + stats->counts = counts; + stats->offset = offset; + stats->duration = duration; + counts = NULL; + offset = NULL; + duration = NULL; +out: + tsd_safe_free(order); + tsd_safe_free(epoch_breaks); + tsd_safe_free(epoch_counts); + tsd_safe_free(counts); + tsd_safe_free(offset); + tsd_safe_free(duration); + return ret; +} + +/* + * The sum of x[i:j] in the sense of Python slices of an array of the given size (a + * negative `i` counts from the end), accumulated from the first element. + */ +static double +slice_sum(const double *x, tsd_size_t size, tsd_id_t i, tsd_id_t j) +{ + int64_t start = i; + int64_t stop = j; + int64_t isize = (int64_t) size; + int64_t k; + double sum; + + if (start < 0) { + start = start + isize < 0 ? 0 : start + isize; + } + if (stop < 0) { + stop = stop + isize < 0 ? 0 : stop + isize; + } + start = start > isize ? isize : start; + stop = stop > isize ? isize : stop; + if (start >= stop) { + return 0.0; + } + sum = x[start]; + for (k = start + 1; k < stop; k++) { + sum += x[k]; + } + return sum; +} + +/* Sort `ids` and remove duplicates (np.unique); returns the number that remain. */ +static tsd_size_t +unique_ids(tsd_size_t n, tsd_id_t *ids) +{ + tsd_size_t j; + tsd_size_t num_unique = 0; + + qsort(ids, n, sizeof(*ids), compare_ids); + for (j = 0; j < n; j++) { + if (j == 0 || ids[j] != ids[j - 1]) { + ids[num_unique] = ids[j]; + num_unique++; + } + } + return num_unique; +} + +int +tsd_mutational_timescale(tsd_size_t num_nodes, const double *nodes_time, + tsd_size_t num_edges, const double *likelihoods, const tsd_id_t *edges_parent, + const tsd_id_t *edges_child, int64_t max_intervals, tsd_size_t *num_breaks, + double **origin_out, double **adjust_out) +{ + int ret = 0; + tsd_epoch_stats_t stats = { 0, NULL, NULL, NULL }; + tsd_id_t *nodes_index = NULL; + tsd_id_t *changepoints = NULL; + double *epoch_breaks = NULL; + double *weight = NULL; + double *adjust = NULL; + double *origin = NULL; + tsd_size_t k, num_epochs, num_changepoints, num_unique; + tsd_id_t i, j, index; + double n, y, z; + + if (max_intervals <= 0) { + ret = tsd_trace_error(TSD_ERR_NONPOSITIVE_INTERVALS); + goto out; + } + nodes_index = malloc((num_nodes + 1) * sizeof(*nodes_index)); + if (nodes_index == NULL) { + ret = tsd_trace_error(TSD_ERR_NO_MEMORY); + goto out; + } + ret = tsd_mutational_area(num_nodes, nodes_time, num_edges, likelihoods, + edges_parent, edges_child, &stats, nodes_index); + if (ret != 0) { + goto out; + } + num_epochs = stats.num_epochs; + epoch_breaks = malloc((num_epochs + 1) * sizeof(*epoch_breaks)); + weight = malloc((num_epochs + 1) * sizeof(*weight)); + if (epoch_breaks == NULL || weight == NULL) { + ret = tsd_trace_error(TSD_ERR_NO_MEMORY); + goto out; + } + epoch_breaks[0] = 0.0; + for (k = 0; k < num_epochs; k++) { + epoch_breaks[k + 1] = epoch_breaks[k] + stats.duration[k]; + weight[k] = stats.offset[k] * stats.duration[k]; + } + + /* Rescale time such that mutation density is constant between changepoints */ + ret = tsd_fixed_changepoints( + num_epochs, weight, max_intervals, &changepoints, &num_changepoints); + if (ret != 0) { + goto out; + } + num_unique = unique_ids(num_changepoints, changepoints); + adjust = malloc((num_unique + 1) * sizeof(*adjust)); + origin = malloc((num_unique + 1) * sizeof(*origin)); + if (adjust == NULL || origin == NULL) { + ret = tsd_trace_error(TSD_ERR_NO_MEMORY); + goto out; + } + adjust[0] = 0.0; + for (k = 0; k + 1 < num_unique; k++) { + i = changepoints[k]; + j = changepoints[k + 1]; + tsd_bug_assert(j > i); + n = slice_sum(stats.offset, num_epochs, i, j); + y = slice_sum(stats.counts, num_epochs, i, j); + z = slice_sum(stats.duration, num_epochs, i, j); + if (!(n > 0)) { + ret = tsd_trace_error(TSD_ERR_ZERO_EDGE_SPAN); + goto out; + } + adjust[k + 1] = z * y / n; + } + for (k = 0; k < num_unique; k++) { + if (k > 0) { + adjust[k] += adjust[k - 1]; + } + /* a negative changepoint indexes from the end, as in numpy */ + index = changepoints[k]; + if (index < 0) { + index = (tsd_id_t) ((tsd_size_t) index + num_epochs + 1); + } + origin[k] = epoch_breaks[index]; + } + *num_breaks = num_unique; + *origin_out = origin; + *adjust_out = adjust; + origin = NULL; + adjust = NULL; +out: + tsd_epoch_stats_free(&stats); + tsd_safe_free(nodes_index); + tsd_safe_free(changepoints); + tsd_safe_free(epoch_breaks); + tsd_safe_free(weight); + tsd_safe_free(adjust); + tsd_safe_free(origin); + return ret; +} + +/* ------------------------------------------------------------------------- * + * Rescaling point estimates and posteriors + * ------------------------------------------------------------------------- */ + +int +tsd_piecewise_scale_point_estimate(tsd_size_t num_points, const double *point_estimate, + const uint8_t *point_fixed, tsd_size_t num_breaks, const double *original_breaks, + const double *rescaled_breaks, double *rescaled) +{ + int ret = 0; + tsd_size_t j; + int64_t idx; + double x; + + if (num_breaks == 0) { + ret = tsd_trace_error(TSD_ERR_NO_BREAKPOINTS); + goto out; + } + if (!is_increasing(num_breaks, rescaled_breaks) + || !is_increasing(num_breaks, original_breaks)) { + ret = tsd_trace_error(TSD_ERR_NON_INCREASING_BREAKPOINTS); + goto out; + } + for (j = 0; j < num_points; j++) { + x = point_estimate[j]; + idx = (int64_t) searchsorted_right(num_breaks, original_breaks, x) - 1; + if (idx < 0) { + /* a time before the first breakpoint wraps to the last */ + idx += (int64_t) num_breaks; + } + rescaled[j] = rescale_piece( + num_breaks, original_breaks, rescaled_breaks, (tsd_size_t) idx, x); + if (point_fixed[j]) { + rescaled[j] = x; + } + } +out: + return ret; +} + +/* Rescale `x` in place, or fail if it is below the first breakpoint. */ +static int +rescale_quantile(tsd_size_t num_breaks, const double *original_breaks, + const double *rescaled_breaks, double *x) +{ + int ret = 0; + int64_t idx; + + idx = (int64_t) searchsorted_right(num_breaks, original_breaks, *x) - 1; + if (idx < 0) { + ret = tsd_trace_error(TSD_ERR_TIME_BELOW_FIRST_BREAKPOINT); + goto out; + } + *x = rescale_piece( + num_breaks, original_breaks, rescaled_breaks, (tsd_size_t) idx, *x); +out: + return ret; +} + +int +tsd_piecewise_scale_posterior(tsd_size_t num_posteriors, const double *posteriors, + const uint8_t *posteriors_fixed, tsd_size_t num_breaks, + const double *original_breaks, const double *rescaled_breaks, double quantile_width, + double max_shape, double *new_posteriors) +{ + int ret = 0; + double *lower = NULL; + double *upper = NULL; + double *midpt = NULL; + tsd_size_t j; + double alpha, beta, quant_lower, quant_upper, new_beta; + double gamma_pars[2]; + + if (num_breaks == 0) { + ret = tsd_trace_error(TSD_ERR_NO_BREAKPOINTS); + goto out; + } + if (!(quantile_width < 1 && quantile_width > 0)) { + ret = tsd_trace_error(TSD_ERR_INVALID_QUANTILE_WIDTH); + goto out; + } + if (!is_increasing(num_breaks, rescaled_breaks) + || !is_increasing(num_breaks, original_breaks)) { + ret = tsd_trace_error(TSD_ERR_NON_INCREASING_BREAKPOINTS); + goto out; + } + quant_lower = quantile_width / 2; + quant_upper = 1 - quantile_width / 2; + for (j = 0; j < num_posteriors; j++) { + if (!posteriors_fixed[j] + && !(posteriors[2 * j] > -1 && posteriors[2 * j + 1] > 0)) { + ret = tsd_trace_error(TSD_ERR_INVALID_POSTERIOR); + goto out; + } + } + if (num_posteriors == 0) { + /* no posterior to reduce */ + ret = tsd_trace_error(TSD_ERR_NO_POSTERIORS); + goto out; + } + lower = calloc(num_posteriors, sizeof(*lower)); + upper = calloc(num_posteriors, sizeof(*upper)); + midpt = calloc(num_posteriors, sizeof(*midpt)); + if (lower == NULL || upper == NULL || midpt == NULL) { + ret = tsd_trace_error(TSD_ERR_NO_MEMORY); + goto out; + } + + /* use posterior mean as a point estimate */ + for (j = 0; j < num_posteriors; j++) { + if (!posteriors_fixed[j]) { + alpha = posteriors[2 * j]; + beta = posteriors[2 * j + 1]; + lower[j] = tsd_gammaincinv(alpha + 1, quant_lower) / beta; + upper[j] = tsd_gammaincinv(alpha + 1, quant_upper) / beta; + midpt[j] = (alpha + 1) / beta; + } + } + /* rescale the quantiles; those of fixed posteriors are zero, and are checked too */ + for (j = 0; j < num_posteriors; j++) { + ret = rescale_quantile(num_breaks, original_breaks, rescaled_breaks, &midpt[j]); + if (ret != 0) { + goto out; + } + } + for (j = 0; j < num_posteriors; j++) { + ret = rescale_quantile(num_breaks, original_breaks, rescaled_breaks, &lower[j]); + if (ret != 0) { + goto out; + } + } + for (j = 0; j < num_posteriors; j++) { + ret = rescale_quantile(num_breaks, original_breaks, rescaled_breaks, &upper[j]); + if (ret != 0) { + goto out; + } + } + + /* reproject posteriors using inter-quantile range */ + for (j = 0; j < num_posteriors; j++) { + new_posteriors[2 * j] = NAN; + new_posteriors[2 * j + 1] = NAN; + if (posteriors_fixed[j]) { + continue; + } + if (lower[j] == 0.0) { + ret = tsd_trace_error(TSD_ERR_ZERO_DIVISION); + goto out; + } + ret = tsd_approximate_gamma_iqr( + quant_lower, quant_upper, lower[j], upper[j], max_shape, gamma_pars); + if (ret != 0) { + goto out; + } + if (midpt[j] == 0.0) { + ret = tsd_trace_error(TSD_ERR_ZERO_DIVISION); + goto out; + } + /* choose rate so as to keep mean */ + new_beta = (gamma_pars[0] + 1) / midpt[j]; + new_posteriors[2 * j] = gamma_pars[0]; + new_posteriors[2 * j + 1] = new_beta; + } +out: + tsd_safe_free(lower); + tsd_safe_free(upper); + tsd_safe_free(midpt); + return ret; +} diff --git a/lib/tests/tests.c b/lib/tests/tests.c index 07c5e970..2930de94 100644 --- a/lib/tests/tests.c +++ b/lib/tests/tests.c @@ -23,10 +23,17 @@ */ /* - * Smoke tests for the low-level tsdate API. These check return codes and - * memory handling only; numerical correctness is tested from Python. + * Tests of the low-level tsdate library: return codes, error paths and memory + * handling, and the values of the numerical functions, as tables of inputs and + * expected outputs. The expected values come from the reference implementation of + * each function (compared to within a few ulps) or, for the approximations to + * special functions and moments, from independent references such as mpmath + * (compared to within the accuracy of the approximation). The tree-sweep functions + * of phasing.c and util.c are compared with their reference implementations from + * Python. */ +#include #include #include #include @@ -35,10 +42,87 @@ #include "tsdate.h" +/* Tolerance of the comparisons with the reference implementation */ +#define ULPS 4 + +/* The bits of `x` as an integer that increases with `x` (with -0 equal to 0). */ +static int64_t +ordered_bits(double x) +{ + int64_t bits; + + memcpy(&bits, &x, sizeof(bits)); + if (bits < 0) { + bits = INT64_MIN - bits; + } + return bits; +} + +/* `actual` is within `ulps` units in the last place of `expected`; NaNs are equal. */ +static void +assert_close_ulps(double actual, double expected, int ulps) +{ + int64_t a, b; + uint64_t distance; + + if (isnan(expected)) { + CU_ASSERT_TRUE(isnan(actual)); + } else if (!isfinite(expected) || !isfinite(actual)) { + CU_ASSERT_EQUAL(actual, expected); + } else { + a = ordered_bits(actual); + b = ordered_bits(expected); + distance = a > b ? (uint64_t) a - (uint64_t) b : (uint64_t) b - (uint64_t) a; + CU_ASSERT_TRUE(distance <= (uint64_t) ulps); + } +} + +/* |actual - expected| <= atol + rtol * |expected|, as numpy.isclose; NaNs are equal. */ +static void +assert_close_tol(double actual, double expected, double rtol, double atol) +{ + if (isnan(expected)) { + CU_ASSERT_TRUE(isnan(actual)); + } else if (!isfinite(expected)) { + CU_ASSERT_EQUAL(actual, expected); + } else { + CU_ASSERT_TRUE(fabs(actual - expected) <= atol + rtol * fabs(expected)); + } +} + +static void +assert_array_close(const double *actual, const double *expected, tsd_size_t n) +{ + tsd_size_t j; + + for (j = 0; j < n; j++) { + assert_close_ulps(actual[j], expected[j], ULPS); + } +} + static void test_strerror(void) { - const int codes[] = { 0, TSD_ERR_GENERIC, TSD_ERR_NO_MEMORY, TSD_ERR_BAD_PARAM }; + const int codes[] = { 0, TSD_ERR_GENERIC, TSD_ERR_NO_MEMORY, TSD_ERR_BAD_PARAM, + TSD_ERR_ZERO_DIVISION, TSD_ERR_INVALID_HYPERGEO, + TSD_ERR_NONPOSITIVE_OR_NONFINITE_MOMENTS, TSD_ERR_JENSEN_VIOLATION, + TSD_ERR_KL_MAX_ITERATIONS, TSD_ERR_KL_INVALID_SHAPE, + TSD_ERR_NONPOSITIVE_CENTRAL_MOMENTS, TSD_ERR_UNSORTED_QUANTILES, + TSD_ERR_QUANTILE_MAX_ITERATIONS, TSD_ERR_NEGATIVE_SHAPE, + TSD_ERR_NONPOSITIVE_MOMENTS, TSD_ERR_INVALID_FIXED_AGE, + TSD_ERR_UNPHASED_INDIVIDUAL_EDGES, TSD_ERR_BLOCK_OUT_OF_BOUNDS, + TSD_ERR_PHASE_OUT_OF_RANGE, TSD_ERR_UNPHASED_LIKELIHOOD_NOT_CONSERVED, + TSD_ERR_MUTATION_NODE_NOT_IN_TREE, TSD_ERR_FIXED_NODES_VIOLATE_CONSTRAINT, + TSD_ERR_NONPOSITIVE_INTERVALS, TSD_ERR_ZERO_EDGE_SPAN, + TSD_ERR_NON_INCREASING_BREAKPOINTS, TSD_ERR_INVALID_QUANTILE_WIDTH, + TSD_ERR_INVALID_POSTERIOR, TSD_ERR_TIME_BELOW_FIRST_BREAKPOINT, + TSD_ERR_NO_POSTERIORS, TSD_ERR_INVALID_MAX_SHAPE, TSD_ERR_INVALID_MIN_STEP, + TSD_ERR_INVALID_NODE_POSTERIOR, TSD_ERR_INVALID_DAMPING, + TSD_ERR_TWIN_EDGE_IN_PHASED_PASS, TSD_ERR_NONPOSITIVE_PENALTY, + TSD_ERR_NODE_OUT_OF_BOUNDS, TSD_ERR_EDGE_OUT_OF_BOUNDS, + TSD_ERR_INDIVIDUAL_OUT_OF_BOUNDS, TSD_ERR_BAD_EDGE_INTERVAL, + TSD_ERR_BAD_EDGE_INDEXES, TSD_ERR_EDGES_FORM_CYCLE, TSD_ERR_TOO_FEW_TIPS, + TSD_ERR_NO_BREAKPOINTS }; const int num_codes = (int) (sizeof(codes) / sizeof(codes[0])); const char *msg_i; const char *msg_j; @@ -89,18 +173,6051 @@ test_safe_free(void) CU_ASSERT_PTR_NULL(x); } +/* Special functions: arguments, expected values and return codes */ +typedef struct { + double x; + double expected; + int ret; +} sf_case1_t; + +typedef struct { + double p, x; + double expected; + int ret; +} sf_case2_t; + +typedef struct { + double a, b, x; + double expected; + int ret; +} sf_case3_t; + +typedef struct { + double a, b, c, x; + double expected; + int ret; +} sf_case4_t; + +typedef struct { + double a, b, x; + double value, dvalue; + int ret; +} sf_hyperu_case_t; + +/* Special functions: arguments and reference values */ +typedef struct { + double x; + double expected; +} sf_ref1_t; + +typedef struct { + double x, y; + double expected; +} sf_ref2_t; + +typedef struct { + double a, b, x; + double expected; +} sf_ref3_t; + +typedef struct { + double a, b, c, x; + double expected; +} sf_ref4_t; + +typedef struct { + double a, b, x; + double value, dvalue; +} sf_hyperu_ref_t; + +/* Tolerances of the comparisons with mpmath */ +#define POLYGAMMA_RTOL 1e-5 +#define POLYGAMMA_ATOL 1e-8 +#define LAPLACE_RTOL 2e-2 +#define LAPLACE_ATOL 1e-8 +/* The unity limit of hyp2f1 is within 1% of the exact value */ +#define UNITY_RTOL 1e-2 +/* The derivative of the Laplace approximation of hyperu is within 2.5% of the exact */ +#define HYPERU_DERIVATIVE_RTOL 2.5e-2 +/* Tolerance of the comparison with SciPy, whose results depend on its build */ +#define GAMMAINCINV_RTOL 1e-10 + +/* Expected values of the reference implementation */ +static const sf_case1_t digamma_cases[] = { + { 0.0, 0.0, TSD_ERR_ZERO_DIVISION }, + { -0.0, 0.0, TSD_ERR_ZERO_DIVISION }, + { 4.9406564584124654e-324, -INFINITY, 0 }, + { 9.9999999999999995e-07, -1000000.5772156649, 0 }, + { 1.0000000000000001e-05, -100000.57721566489, 0 }, + { 1.0000000000000003e-05, -100000.57719921565, 0 }, + { 0.5, -1.9635100260214153, 0 }, + { 4.9000000000000004, 1.483737793254901, 0 }, + { 8.4999999999999982, 2.0800908175794208, 0 }, + { 8.5, 2.0800908175794279, 0 }, + { 100.0, 4.6001618527380881, 0 }, + { 1.0000000000000001e+300, 690.77552789821368, 0 }, + { INFINITY, INFINITY, 0 }, + { NAN, NAN, 0 }, + { -0.5, 0.036489973978584861, 0 }, + { -1.0, -25653050788007548.0, 0 }, + { -1.5, 0.70315664064525185, 0 }, + { -10.5, 2.3982391295357801, 0 }, + { -1e-300, 1.0000000000000001e+300, 0 }, + { -INFINITY, NAN, 0 }, +}; + +/* Expected values of the reference implementation */ +static const sf_case1_t trigamma_cases[] = { + { 0.0, 0.0, TSD_ERR_ZERO_DIVISION }, + { -0.0, 0.0, TSD_ERR_ZERO_DIVISION }, + { -1e-300, 0.0, TSD_ERR_ZERO_DIVISION }, + { 1e-300, 0.0, TSD_ERR_ZERO_DIVISION }, + { 4.9406564584124654e-324, 0.0, TSD_ERR_ZERO_DIVISION }, + { 1e-10, 9.9999999999999984e+19, 0 }, + { 0.0001, 100000000.0, 0 }, + { 0.00010000000000000002, 100000001.64469366, 0 }, + { 0.5, 4.9348022005461569, 0 }, + { 4.9000000000000004, 0.22631146419213941, 0 }, + { 5.0, 0.22132295574429867, 0 }, + { 100.0, 0.010050166663333571, 0 }, + { 1.0000000000000001e+300, 1e-300, 0 }, + { INFINITY, 0.0, 0 }, + { NAN, NAN, 0 }, + { -0.5, 8.9348022005432011, 0 }, + { -1.5, 9.3792466449876457, 0 }, + { -10.5, 9.7787577398148109, 0 }, + { -INFINITY, NAN, 0 }, +}; + +/* Expected values of the reference implementation */ +static const sf_ref2_t betaln_cases[] = { + { 1.0, 1.0, 0.0 }, + { 0.5, 0.5, 1.1447298858494002 }, + { 2.0, 3.0, -2.4849066497880004 }, + { 1e-10, 10000000000.0, 23.025848388671875 }, + { 100000.0, 100000.0, -138633.92706134822 }, + { 1.0000000000000001e+300, 1.0000000000000001e+300, -1.3862943611198268e+300 }, + { 1e+308, 1e+308, NAN }, + { 0.0, 1.0, INFINITY }, + { -0.5, 2.0, 1.3862943611198906 }, + { NAN, 1.0, NAN }, + { 1.0, INFINITY, NAN }, +}; + +/* Expected values of the reference implementation */ +static const sf_case2_t gammainc_der_cases[] = { + { 1.0, 0.0, 0.0, 0 }, + { 5.0, 100000000.00000001, 0.0, 0 }, + { 5.0, INFINITY, 0.0, 0 }, + { 2000.0, 2000.0, -0.00892111615358839, 0 }, + { 1000.0000000000001, 1000.0, -0.012617064253050618, 0 }, + { 1000.0, 1000.0, -0.012616713994069394, 0 }, + { 0.5, 1.0, -0.3898372643285174, 0 }, + { 2.0, 1.5, -0.31348863782508085, 0 }, + { 1e-10, 1e-10, -22.448635214909299, 0 }, + { 50.0, 0.001, 0.0, 0 }, + { 0.5, 1.0000000000000002, -0.3898372643285154, 0 }, + { 5.0, 50.0, -1.3227071908086766e-16, 0 }, + { 100.0, 110.0, -0.023808656854890219, 0 }, + { 0.001, 10.0, -4.1816615862918354e-06, 0 }, + { 5.0, 800.0, 0.0, 0 }, + { -1.0, 1.0, 0.0, TSD_ERR_INVALID_HYPERGEO }, + { 0.0, 1.0, 0.0, TSD_ERR_INVALID_HYPERGEO }, + { 1.0, -4.9406564584124654e-324, 0.0, TSD_ERR_INVALID_HYPERGEO }, + { NAN, 1.0, 0.0, TSD_ERR_INVALID_HYPERGEO }, + { 1.0, NAN, 0.0, TSD_ERR_INVALID_HYPERGEO }, +}; + +/* Expected values of the reference implementation */ +static const sf_hyperu_case_t hyperu_laplace_cases[] = { + { 1.0, 2.0, 1.0, 1.1102230246251565e-16, -1.0, 0 }, + { 1.0, 1.0, 1.0, -0.5016052919180235, -0.6944271909999159, 0 }, + { 0.5, 30.0, 0.001, 267.79385089219738, -28998.983352647308, 0 }, + { 50.0, 51.0, 1000.0, -345.38776394910684, -0.049999999999999996, 0 }, + { 0.001, 1.0, 100000000.0, -0.018420680743962414, -9.9999999998999994e-12, 0 }, + { 1.0, INFINITY, 1.0, NAN, NAN, 0 }, + { 4.9406564584124654e-324, 1.0, 1.0, 0.0, -4.9406564584124654e-324, 0 }, + { 1.0, 0.99999999999999989, 1.0, 0.0, 0.0, TSD_ERR_INVALID_HYPERGEO }, + { 0.0, 1.0, 1.0, 0.0, 0.0, TSD_ERR_INVALID_HYPERGEO }, + { NAN, 2.0, 1.0, 0.0, 0.0, TSD_ERR_INVALID_HYPERGEO }, + { 1.0, 2.0, 0.0, 0.0, 0.0, TSD_ERR_INVALID_HYPERGEO }, + { 1.0, 2.0, NAN, 0.0, 0.0, TSD_ERR_INVALID_HYPERGEO }, + { 1.0, 2.0, 1.0000000000000001e+300, 0.0, 0.0, TSD_ERR_ZERO_DIVISION }, + { 1.0, 2.0, INFINITY, 0.0, 0.0, TSD_ERR_ZERO_DIVISION }, + { 1.0, 2.0, 4.9406564584124654e-324, 0.0, 0.0, TSD_ERR_ZERO_DIVISION }, + { 4.9406564584124654e-324, 1.0, 10.0, 0.0, 0.0, TSD_ERR_ZERO_DIVISION }, +}; + +/* Expected values of the reference implementation */ +static const sf_case3_t hyp1f1_laplace_cases[] = { + { 1.0, 2.0, 1.0, 0.5335775438918825, 0 }, + { 1.0, 2.0, 0.0, 0.0, 0 }, + { 1.0, 2.0, -0.0, 0.0, 0 }, + { 0.5, 30.0, -1000.0, -1.7799338025575939, 0 }, + { 50.0, 1050.0, 1000.0, 97.194122480810705, 0 }, + { 0.001, 1.0009999999999999, 1e-10, 9.9826374162340947e-14, 0 }, + { 1.0, 2.0, NAN, NAN, 0 }, + { 1.0, 2.0, INFINITY, NAN, 0 }, + { 1.0, 2.0, 1.0000000000000001e+300, -INFINITY, 0 }, + { 1.0, 1.0, 1.0, 0.0, TSD_ERR_INVALID_HYPERGEO }, + { 0.0, 1.0, 0.0, 0.0, TSD_ERR_INVALID_HYPERGEO }, + { NAN, 2.0, 1.0, 0.0, TSD_ERR_INVALID_HYPERGEO }, + { 1e-10, 2.0000000000000001e-10, 100000000.0, 0.0, TSD_ERR_ZERO_DIVISION }, +}; + +/* Expected values of the reference implementation */ +static const sf_case4_t hyp2f1_laplace_cases[] = { + { 1.0, 2.0, 3.0, 0.5, 0.43844776148964582, 0 }, + { 5.0, 7.0, 9.0, 0.90000000000000002, 8.1454130153612532, 0 }, + { 30.0, 40.0, 35.0, 1e-08, 3.4285713113035854e-07, 0 }, + { 0.0, 1.0, 1.0, 0.0, 0.0, 0 }, + { 1.0, 2.0, 3.0, -0.5, -0.27842079965849342, 0 }, + { 0.5, 30.0, 1.5, -100.0, -4.0851309087682068, 0 }, + { 2.0, 3.0, 4.0, 0.99999998999999995, 19.519293027595719, 0 }, + { 1.0, 2.0, 5.0, 0.99999998999999995, 0.69314718055994551, 0 }, + { 1.0, 2.0, 3.0, 0.99999998999999995, 3.6066211672149588, 0 }, + { 2.0, 3.0, 4.0, -100000000.0, -35.742749223159137, 0 }, + { 3.0, 2.0, 5.0, -100000000.0, -35.049602038676674, 0 }, + { 2.0, 2.0, 5.0, -100000000.0, -31.44298087085901, 0 }, + { 1.0, 2.0, 3.0, -10000000000000000.0, 0.0, TSD_ERR_INVALID_HYPERGEO }, + { 1.0, 2.0, 0.0, 0.5, 0.0, TSD_ERR_INVALID_HYPERGEO }, + { -1.0, 2.0, 3.0, 0.5, 0.0, TSD_ERR_INVALID_HYPERGEO }, + { 1.0, -1.0, 3.0, 0.5, 0.0, TSD_ERR_INVALID_HYPERGEO }, + { 2.0, 1.0, 1.0, 0.5, 0.0, TSD_ERR_INVALID_HYPERGEO }, + { 1.0, 2.0, 3.0, 1.0, 0.0, TSD_ERR_INVALID_HYPERGEO }, + { 1.0, 2.0, 3.0, NAN, 0.0, TSD_ERR_INVALID_HYPERGEO }, + { 0.0, 1.0, 1.0, 0.5, 0.0, TSD_ERR_INVALID_HYPERGEO }, + { 1.0, 2.0, 1.0, 0.5, 0.0, TSD_ERR_INVALID_HYPERGEO }, + { 0.0, 1.0, 1e-300, 0.5, 0.0, TSD_ERR_ZERO_DIVISION }, + { 1.1774154985086274, 504.40824624062162, 1.1774154985086274, 0.14271801659243741, + 0.0, TSD_ERR_ZERO_DIVISION }, +}; + +/* scipy.special.gammaincinv (SciPy 1.18.1); 0 for p = 0, infinity for p = 1 and NaN + * outside the domain */ +static const sf_ref2_t gammaincinv_cases[] = { + { 0.99999999999999989, 0.5, 0.69314718055994506 }, + { 0.0018725572425875394, 0.93432222410629528, 9.8708778280225384e-17 }, + { 1.4851015014453666e-07, 0.99989259056538193, 4.2708929514115105e-315 }, + { 9.9999999999999694e-311, 0.95988221384026817, NAN }, + { 9.9999999999999694e-311, 0.56112084484672486, NAN }, + { 1.0, 0.64358723829337949, 1.0316657767689139 }, + { 1.3693230946091463e+32, 0.84677972577643534, 1.3693230946091465e+32 }, + { 3.3463277181277915, 0.99999999999894673, 34.949768724325295 }, + { 22.041778641418698, 0.093156553752253735, 16.126803358230266 }, + { 1e-10, 0.99999999999999989, 11.214230215647511 }, + { 2.0, 4.9406564584124654e-324, 3.1434555694052403e-162 }, + { 1000.0, 1e-300, 233.92836429052818 }, + { 1000.0, 0.999, 1100.5780982933145 }, + { 0.67948734660549959, 0.7818881580083944, 1.0450131885835172 }, + { 0.024285952691655305, 0.99728941525830839, 1.4475359182943457 }, + { 0.033000366354340456, 0.98377018057938537, 0.5706929538725517 }, + { 32.69007854626318, 0.99999999999999645, 98.692064965782848 }, + { 1e-300, 0.99999999989999999, 0.0 }, + { 1.0000000000000001e+300, 4.9406564584124654e-324, 1.0000000000000001e+300 }, + { 1e-300, 0.0, 0.0 }, + { 1e-300, 1.0, INFINITY }, + { 1e-300, 1.0000000000000002, NAN }, + { 1.0, 4.9406564584124654e-324, 4.9406564584124654e-324 }, + { 1000000.0, 9.9999999999999995e-21, 990765.90325837862 }, + { INFINITY, 4.9406564584124654e-324, NAN }, + { 2907.5441489134673, 0.85784200187994619, 2965.322214703659 }, + { 64.283331812787964, 0.98660725921411685, 83.323363883964191 }, + { 0.0024060602718259248, 0.17939292031798137, 4.1575279095986522e-311 }, + { 1e-300, -0.10000000000000001, NAN }, + { 1e-10, 0.99999999989999999, 0.2647369819114741 }, + { 0.5, 0.999, 5.4137830853313664 }, + { 100.0, 1e-300, 0.038006988916941875 }, + { 1000.0, 0.99999999989999999, 1214.4995558668779 }, + { 0.0, 4.9406564584124654e-324, NAN }, + { -1.0, 0.0, NAN }, + { NAN, 0.5, NAN }, + { 2.0, NAN, NAN }, + { 0.0001, 0.25, 0.0 }, + { 0.5, 0.25, 0.050765522133810782 }, + { 3.0, 0.94999999999999996, 6.2957936218719883 }, +}; + +/* mpmath psi(0, x) at 15 digits */ +static const sf_ref1_t digamma_mpmath[] = { + { -0.29999999999999999, 2.113309779635399 }, + { 1e-10, -10000000000.577215 }, + { 9.9999999999999995e-07, -1000000.57721402 }, + { 0.01, -100.56088545786866 }, + { 10.0, 2.2517525890667209 }, + { 100.0, 4.6001618527380872 }, + { 1000.0, 6.907255195648812 }, + { 100000.0, 11.512920464961896 }, + { 10000000000.0, 23.025850929890456 }, +}; + +/* mpmath psi(1, x) at 15 digits */ +static const sf_ref1_t trigamma_mpmath[] = { + { -0.29999999999999999, 13.945160267805722 }, + { 1e-10, 1e+20 }, + { 9.9999999999999995e-07, 1000000000001.645 }, + { 0.01, 10001.621213528313 }, + { 10.0, 0.10516633568168575 }, + { 100.0, 0.010050166663333571 }, + { 1000.0, 0.0010005001666666333 }, + { 100000.0, 1.0000050000166667e-05 }, + { 10000000000.0, 1.00000000005e-10 }, +}; + +/* Real part of mpmath log(beta(p, q)) at 15 digits */ +static const sf_ref2_t betaln_mpmath[] = { + { -0.29999999999999999, -0.59999999999999998, 0.41427032493334498 }, + { 1e-10, 2.0000000000000001e-10, 23.431316038048621 }, + { 9.9999999999999995e-07, 1.9999999999999999e-06, 14.220975666069149 }, + { 0.01, 0.02, 5.0103133506979862 }, + { 10.0, 20.0, -19.115327299887046 }, + { 100.0, 200.0, -192.13419227497894 }, + { 1000.0, 2000.0, -1911.8746142144516 }, + { 100000.0, 200000.0, -190958.88527911686 }, + { 10000000000.0, 20000000000.0, -19095425059.235638 }, +}; + +/* Log of mpmath hyp2f1 at 15 digits */ +static const sf_ref4_t hyp2f1_laplace_mpmath[] = { + { 984.72000000000003, 1954.22, 985.72000000000003, -1.1392534691231597, + -1478.1738051381913 }, + { 936.02999999999997, 1834.8299999999999, 938.02999999999997, -1.0739817123857025, + -1330.0059628227482 }, + { 413.54000000000002, 451.48000000000002, 414.54000000000002, -12.853557923685116, + -1181.3138708305196 }, + { 544.64999999999998, 1292.75, 545.64999999999998, -0.71439839463641541, + -693.46877093725595 }, + { 21.898, 43.078000000000003, 22.898, -1.2310276509604619, -31.917963510674785 }, + { 1000.0, 1007.931, 1001.0, -129.62015503875969, -4904.8528786755833 }, + { 42.006999999999998, 119.15700000000001, 43.006999999999998, -0.70922612322041212, + -59.975223456559483 }, + { 130.68000000000001, 1122.1800000000001, 132.68000000000001, -0.1533946760574047, + -152.42035404495687 }, + { 121.70999999999999, 802.61000000000001, 124.70999999999999, -0.80594900849858353, + -303.45631195318833 }, +}; + +/* Log of mpmath hyp2f1 at 15 digits, for z / (z - 1) close to one */ +static const sf_ref4_t hyp2f1_laplace_unity_mpmath[] = { + { 0.0012723999999999999, 202.86627240000001, 1.0012724, -6614020190.5935307, + -0.036261751566401573 }, + { 0.0012612000000000001, 1001.9992612000001, 3.0012612000000001, -141574796.04867145, + -0.031220448825817738 }, + { 0.0011992999999999999, 157.77919929999999, 1.0011992999999999, -1146235430.4403243, + -0.031774253197474109 }, + { 0.00097179999999999999, 1000.0009718, 1.0009718000000001, -158137496.57453805, + -0.025619221224780213 }, + { 0.00097110000000000002, 405.48297110000004, 1.0009710999999999, + -276526839.68553674, -0.025266157355002965 }, + { 0.0015548999999999999, 115.7745549, 1.0015548999999999, -31061255169.177708, + -0.045842304967148521 }, + { 0.0010028000000000001, 73.491902799999991, 1.0010028, -53058551695.758659, + -0.029644174580337579 }, + { 0.0015053, 19.999605300000002, 2.0015052999999998, -178245782075.18933, + -0.042831241419712583 }, +}; + +/* Log of mpmath hyperu at 15 digits, and its derivative with respect to x */ +static const sf_hyperu_ref_t hyperu_laplace_mpmath[] = { + { 1.0, 4.3380000000000001, 0.7752291021399601, 2.6258894260525927, + -3.3991838624960096 }, + { 1.0, 4.6779999999999999, 0.76981102428276016, 3.1203053508031515, + -3.8351394948119681 }, + { 2.0, 5.9990000000000006, 5.1995955076999998, -2.202169012479116, + -0.57735145331711235 }, + { 9.0, 14.251000000000001, 2.5473150302860001, -1.5490292494382205, + -4.9021077003749038 }, + { 4.0, 18.460000000000001, 11.246026052960001, -3.7214576615414909, + -0.90331659933332087 }, + { 2.0, 2.9990000000000001, 3.7769370770299999, -2.6582253243210303, + -0.52944685391153801 }, +}; + +/* Log of mpmath hyp1f1 at 15 digits */ +static const sf_ref3_t hyp1f1_laplace_mpmath[] = { + { 132.47999999999999, 133.47999999999999, 170.98504810547999, 170.15807254764488 }, + { 997.09000000000003, 999.09000000000003, 1492.6979568568001, 1490.8690564465708 }, + { 978.24000000000001, 979.24000000000001, 1031.693903284, 1030.9740566223463 }, + { 713.51999999999998, 722.51999999999998, 739.07796118750002, 732.72108850452321 }, + { 999.99000000000001, 1003.99, 2916.7083719407506, 2911.2536982489523 }, + { 989.08000000000004, 992.08000000000004, 1125.8335771375, 1123.5567170478762 }, + { 28.545999999999999, 29.545999999999999, 38.4316856035, 37.587465253533537 }, + { 30.956, 31.956, 28.834237509375001, 28.184054387129486 }, +}; + static void -test_bug_assert_passes(void) +test_digamma(void) { - tsd_bug_assert(1 + 1 == 2); + const size_t num_cases = sizeof(digamma_cases) / sizeof(*digamma_cases); + const size_t num_refs = sizeof(digamma_mpmath) / sizeof(*digamma_mpmath); + const sf_case1_t *row; + double value; + size_t j; + int ret; + + for (j = 0; j < num_cases; j++) { + row = &digamma_cases[j]; + ret = tsd_digamma(row->x, &value); + CU_ASSERT_EQUAL(ret, row->ret); + if (ret == 0) { + assert_close_ulps(value, row->expected, ULPS); + } + } + for (j = 0; j < num_refs; j++) { + ret = tsd_digamma(digamma_mpmath[j].x, &value); + CU_ASSERT_EQUAL_FATAL(ret, 0); + assert_close_tol( + value, digamma_mpmath[j].expected, POLYGAMMA_RTOL, POLYGAMMA_ATOL); + } } static void -handle_cunit_error(void) +test_trigamma(void) { - fprintf( - stderr, "CUnit error occurred: %d: %s\n", CU_get_error(), CU_get_error_msg()); - exit(EXIT_FAILURE); + const size_t num_cases = sizeof(trigamma_cases) / sizeof(*trigamma_cases); + const size_t num_refs = sizeof(trigamma_mpmath) / sizeof(*trigamma_mpmath); + const sf_case1_t *row; + double value; + size_t j; + int ret; + + for (j = 0; j < num_cases; j++) { + row = &trigamma_cases[j]; + ret = tsd_trigamma(row->x, &value); + CU_ASSERT_EQUAL(ret, row->ret); + if (ret == 0) { + assert_close_ulps(value, row->expected, ULPS); + } + } + for (j = 0; j < num_refs; j++) { + ret = tsd_trigamma(trigamma_mpmath[j].x, &value); + CU_ASSERT_EQUAL_FATAL(ret, 0); + assert_close_tol( + value, trigamma_mpmath[j].expected, POLYGAMMA_RTOL, POLYGAMMA_ATOL); + } +} + +static void +test_betaln(void) +{ + const size_t num_cases = sizeof(betaln_cases) / sizeof(*betaln_cases); + const size_t num_refs = sizeof(betaln_mpmath) / sizeof(*betaln_mpmath); + const sf_ref2_t *row; + double value; + size_t j; + + for (j = 0; j < num_cases; j++) { + row = &betaln_cases[j]; + value = tsd_betaln(row->x, row->y); + assert_close_ulps(value, row->expected, ULPS); + } + for (j = 0; j < num_refs; j++) { + row = &betaln_mpmath[j]; + value = tsd_betaln(row->x, row->y); + assert_close_tol(value, row->expected, POLYGAMMA_RTOL, POLYGAMMA_ATOL); + } +} + +static void +test_gammainc_der(void) +{ + const size_t num_cases = sizeof(gammainc_der_cases) / sizeof(*gammainc_der_cases); + const sf_case2_t *row; + double value; + size_t j; + int ret; + + for (j = 0; j < num_cases; j++) { + row = &gammainc_der_cases[j]; + ret = tsd_gammainc_der(row->p, row->x, &value); + CU_ASSERT_EQUAL(ret, row->ret); + if (ret == 0) { + assert_close_ulps(value, row->expected, ULPS); + } + } +} + +static void +test_hyperu_laplace(void) +{ + const size_t num_cases + = sizeof(hyperu_laplace_cases) / sizeof(*hyperu_laplace_cases); + const size_t num_refs + = sizeof(hyperu_laplace_mpmath) / sizeof(*hyperu_laplace_mpmath); + const sf_hyperu_case_t *row; + const sf_hyperu_ref_t *ref; + double value, dvalue; + size_t j; + int ret; + + for (j = 0; j < num_cases; j++) { + row = &hyperu_laplace_cases[j]; + ret = tsd_hyperu_laplace(row->a, row->b, row->x, &value, &dvalue); + CU_ASSERT_EQUAL(ret, row->ret); + if (ret == 0) { + assert_close_ulps(value, row->value, ULPS); + assert_close_ulps(dvalue, row->dvalue, ULPS); + } + } + for (j = 0; j < num_refs; j++) { + ref = &hyperu_laplace_mpmath[j]; + ret = tsd_hyperu_laplace(ref->a, ref->b, ref->x, &value, &dvalue); + CU_ASSERT_EQUAL_FATAL(ret, 0); + assert_close_tol(value, ref->value, LAPLACE_RTOL, LAPLACE_ATOL); + assert_close_tol(dvalue, ref->dvalue, HYPERU_DERIVATIVE_RTOL, LAPLACE_ATOL); + } +} + +static void +test_hyp1f1_laplace(void) +{ + const size_t num_cases + = sizeof(hyp1f1_laplace_cases) / sizeof(*hyp1f1_laplace_cases); + const size_t num_refs + = sizeof(hyp1f1_laplace_mpmath) / sizeof(*hyp1f1_laplace_mpmath); + const sf_case3_t *row; + const sf_ref3_t *ref; + double value; + size_t j; + int ret; + + for (j = 0; j < num_cases; j++) { + row = &hyp1f1_laplace_cases[j]; + ret = tsd_hyp1f1_laplace(row->a, row->b, row->x, &value); + CU_ASSERT_EQUAL(ret, row->ret); + if (ret == 0) { + assert_close_ulps(value, row->expected, ULPS); + } + } + for (j = 0; j < num_refs; j++) { + ref = &hyp1f1_laplace_mpmath[j]; + ret = tsd_hyp1f1_laplace(ref->a, ref->b, ref->x, &value); + CU_ASSERT_EQUAL_FATAL(ret, 0); + assert_close_tol(value, ref->expected, LAPLACE_RTOL, LAPLACE_ATOL); + } +} + +/* Compare tsd_hyp2f1_laplace with `num_refs` mpmath values to within `rtol`. */ +static void +check_hyp2f1_laplace_mpmath(const sf_ref4_t *refs, size_t num_refs, double rtol) +{ + double value; + size_t j; + int ret; + + for (j = 0; j < num_refs; j++) { + ret = tsd_hyp2f1_laplace(refs[j].a, refs[j].b, refs[j].c, refs[j].x, &value); + CU_ASSERT_EQUAL_FATAL(ret, 0); + assert_close_tol(value, refs[j].expected, rtol, LAPLACE_ATOL); + } +} + +static void +test_hyp2f1_laplace(void) +{ + const size_t num_cases + = sizeof(hyp2f1_laplace_cases) / sizeof(*hyp2f1_laplace_cases); + const size_t num_refs + = sizeof(hyp2f1_laplace_mpmath) / sizeof(*hyp2f1_laplace_mpmath); + const size_t num_unity_refs + = sizeof(hyp2f1_laplace_unity_mpmath) / sizeof(*hyp2f1_laplace_unity_mpmath); + const sf_case4_t *row; + double value; + size_t j; + int ret; + + for (j = 0; j < num_cases; j++) { + row = &hyp2f1_laplace_cases[j]; + ret = tsd_hyp2f1_laplace(row->a, row->b, row->c, row->x, &value); + CU_ASSERT_EQUAL(ret, row->ret); + if (ret == 0) { + assert_close_ulps(value, row->expected, ULPS); + } + } + check_hyp2f1_laplace_mpmath(hyp2f1_laplace_mpmath, num_refs, LAPLACE_RTOL); + check_hyp2f1_laplace_mpmath(hyp2f1_laplace_unity_mpmath, num_unity_refs, UNITY_RTOL); +} + +static void +test_gammaincinv(void) +{ + const size_t num_cases = sizeof(gammaincinv_cases) / sizeof(*gammaincinv_cases); + const sf_ref2_t *row; + double value; + size_t j; + + for (j = 0; j < num_cases; j++) { + row = &gammaincinv_cases[j]; + value = tsd_gammaincinv(row->x, row->y); + assert_close_tol(value, row->expected, GAMMAINCINV_RTOL, 0); + } +} + +/* + * Tables for the functions of approx.c. Each function is called through an adapter + * that takes its inputs and writes its outputs as arrays; the natural parameters of + * the projections are consecutive pairs of inputs. + */ +typedef int (*approx_func_t)(const double *in, double *out); + +/* Inputs, and the expected outputs or (nonzero) return code. */ +typedef struct { + double in[6]; + double out[5]; + int ret; +} approx_row_t; + +#define NUM_ROWS(rows) (sizeof(rows) / sizeof(*(rows))) + +static void +check_rows( + approx_func_t func, const approx_row_t *rows, size_t num_rows, size_t num_outputs) +{ + size_t j, k; + int ret; + double out[5]; + + for (j = 0; j < num_rows; j++) { + ret = func(rows[j].in, out); + CU_ASSERT_EQUAL(ret, rows[j].ret); + if (ret == 0 && rows[j].ret == 0) { + for (k = 0; k < num_outputs; k++) { + assert_close_ulps(out[k], rows[j].out[k], ULPS); + } + } + } +} + +/* + * Compare with reference values to within `rtol` (and an absolute tolerance of 1e-8); + * the outputs whose bits are set in `sd_mask` are variances, compared as standard + * deviations. + */ +static void +check_reference_rows(approx_func_t func, const approx_row_t *rows, size_t num_rows, + size_t num_outputs, unsigned int sd_mask, double rtol) +{ + size_t j, k; + int ret; + double out[5]; + double actual, expected; + + for (j = 0; j < num_rows; j++) { + ret = func(rows[j].in, out); + CU_ASSERT_EQUAL_FATAL(ret, 0); + for (k = 0; k < num_outputs; k++) { + actual = out[k]; + expected = rows[j].out[k]; + if (sd_mask & (1u << k)) { + actual = sqrt(actual); + expected = sqrt(expected); + } + assert_close_tol(actual, expected, rtol, 1e-8); + } + } +} + +static int +eval_log_moments(const double *in, double *out) +{ + return tsd_approximate_log_moments(in[0], in[1], out, out + 1, out + 2); +} + +static int +eval_gamma_kl(const double *in, double *out) +{ + return tsd_approximate_gamma_kl(in[0], in[1], out); +} + +static int +eval_gamma_mom(const double *in, double *out) +{ + return tsd_approximate_gamma_mom(in[0], in[1], out); +} + +static int +eval_gamma_iqr(const double *in, double *out) +{ + return tsd_approximate_gamma_iqr(in[0], in[1], in[2], in[3], in[4], out); +} + +static int +eval_valid_moments(const double *in, double *out) +{ + out[0] = tsd_valid_moments(in[0], in[1]); + return 0; +} + +static int +eval_valid_gamma(const double *in, double *out) +{ + out[0] = tsd_valid_gamma(in[0], in[1]); + return 0; +} + +static int +eval_moments(const double *in, double *out) +{ + return tsd_moments(in[0], in[1], in[2], in[3], in[4], in[5], out, out + 1, out + 2, + out + 3, out + 4); +} + +static int +eval_unphased_moments(const double *in, double *out) +{ + return tsd_unphased_moments(in[0], in[1], in[2], in[3], in[4], in[5], out, out + 1, + out + 2, out + 3, out + 4); +} + +static int +eval_rootward_moments(const double *in, double *out) +{ + return tsd_rootward_moments( + in[0], in[1], in[2], in[3], in[4], out, out + 1, out + 2); +} + +static int +eval_leafward_moments(const double *in, double *out) +{ + return tsd_leafward_moments( + in[0], in[1], in[2], in[3], in[4], out, out + 1, out + 2); +} + +static int +eval_sideways_moments(const double *in, double *out) +{ + return tsd_sideways_moments( + in[0], in[1], in[2], in[3], in[4], out, out + 1, out + 2); +} + +static int +eval_twin_moments(const double *in, double *out) +{ + return tsd_twin_moments(in[0], in[1], in[2], in[3], out, out + 1, out + 2); +} + +static int +eval_mutation_moments(const double *in, double *out) +{ + return tsd_mutation_moments(in[0], in[1], in[2], in[3], in[4], in[5], out, out + 1); +} + +static int +eval_mutation_rootward_moments(const double *in, double *out) +{ + return tsd_mutation_rootward_moments( + in[0], in[1], in[2], in[3], in[4], out, out + 1); +} + +static int +eval_mutation_leafward_moments(const double *in, double *out) +{ + return tsd_mutation_leafward_moments( + in[0], in[1], in[2], in[3], in[4], out, out + 1); +} + +static int +eval_mutation_unphased_moments(const double *in, double *out) +{ + return tsd_mutation_unphased_moments( + in[0], in[1], in[2], in[3], in[4], in[5], out, out + 1, out + 2); +} + +static int +eval_mutation_twin_moments(const double *in, double *out) +{ + return tsd_mutation_twin_moments(in[0], in[1], in[2], in[3], out, out + 1, out + 2); +} + +static int +eval_mutation_sideways_moments(const double *in, double *out) +{ + return tsd_mutation_sideways_moments( + in[0], in[1], in[2], in[3], in[4], out, out + 1, out + 2); +} + +static int +eval_mutation_edge_moments(const double *in, double *out) +{ + return tsd_mutation_edge_moments(in[0], in[1], out, out + 1); +} + +static int +eval_mutation_block_moments(const double *in, double *out) +{ + return tsd_mutation_block_moments(in[0], in[1], out, out + 1, out + 2); +} + +static int +eval_gamma_projection(const double *in, double *out) +{ + return tsd_gamma_projection(in, in + 2, in + 4, out, out + 1, out + 3); +} + +static int +eval_leafward_projection(const double *in, double *out) +{ + return tsd_leafward_projection(in[0], in + 1, in + 3, out, out + 1); +} + +static int +eval_rootward_projection(const double *in, double *out) +{ + return tsd_rootward_projection(in[0], in + 1, in + 3, out, out + 1); +} + +static int +eval_unphased_projection(const double *in, double *out) +{ + return tsd_unphased_projection(in, in + 2, in + 4, out, out + 1, out + 3); +} + +static int +eval_twin_projection(const double *in, double *out) +{ + return tsd_twin_projection(in, in + 2, out, out + 1); +} + +static int +eval_sideways_projection(const double *in, double *out) +{ + return tsd_sideways_projection(in[0], in + 1, in + 3, out, out + 1); +} + +static int +eval_mutation_gamma_projection(const double *in, double *out) +{ + return tsd_mutation_gamma_projection(in, in + 2, in + 4, out, out + 1); +} + +static int +eval_mutation_leafward_projection(const double *in, double *out) +{ + return tsd_mutation_leafward_projection(in[0], in + 1, in + 3, out, out + 1); +} + +static int +eval_mutation_rootward_projection(const double *in, double *out) +{ + return tsd_mutation_rootward_projection(in[0], in + 1, in + 3, out, out + 1); +} + +static int +eval_mutation_edge_projection(const double *in, double *out) +{ + return tsd_mutation_edge_projection(in[0], in[1], out, out + 1); +} + +static int +eval_mutation_unphased_projection(const double *in, double *out) +{ + return tsd_mutation_unphased_projection(in, in + 2, in + 4, out, out + 1); +} + +static int +eval_mutation_twin_projection(const double *in, double *out) +{ + return tsd_mutation_twin_projection(in, in + 2, out, out + 1); +} + +static int +eval_mutation_sideways_projection(const double *in, double *out) +{ + return tsd_mutation_sideways_projection(in[0], in + 1, in + 3, out, out + 1); +} + +static int +eval_mutation_block_projection(const double *in, double *out) +{ + return tsd_mutation_block_projection(in[0], in[1], out, out + 1); +} + +/* Expected values of the reference implementation */ +static const approx_row_t log_moments_rows[] = { + { .in = { 1.0, 1.0 }, .out = { -0.5, 0.5, 1.0 } }, + { .in = { 2.0, 0.5 }, + .out = { 0.6306471805599453, 1.5112943611198906, 0.5188096163482082 } }, + { .in = { 1e+300, 1e+300 }, + .out = { 690.7755278982137, 6.907755278982137e+302, 477170.8299430558 } }, + { .in = { 1e-100, 1e-100 }, .out = { -5e+99, 0.5, 2.312585092994046e+102 } }, + { .in = { 0.0, 1.0 }, .ret = TSD_ERR_NONPOSITIVE_MOMENTS }, + { .in = { -1.0, 1.0 }, .ret = TSD_ERR_NONPOSITIVE_MOMENTS }, + { .in = { 1.0, NAN }, .ret = TSD_ERR_NONPOSITIVE_MOMENTS }, + { .in = { INFINITY, 1.0 }, .out = { INFINITY, INFINITY, NAN } }, + { .in = { 1.0, INFINITY }, .out = { -INFINITY, INFINITY, INFINITY } }, + { .in = { 1e-200, 1.0 }, .ret = TSD_ERR_ZERO_DIVISION }, + { .in = { 5e-324, 1.0 }, .ret = TSD_ERR_ZERO_DIVISION }, +}; + +/* Expected values of the reference implementation */ +static const approx_row_t gamma_kl_rows[] = { + { .in = { 2.0, 0.5 }, .out = { 1.7439641139785955, 1.3719820569892978 } }, + { .in = { 1.0, -0.5 }, .out = { 0.13772472714785322, 1.1377247271478532 } }, + { .in = { 1.0, -1.0 }, .out = { -0.3844432335204093, 0.6155567664795907 } }, + { .in = { 1.0, -10.0 }, .out = { -0.9169429520050368, 0.08305704799496319 } }, + { .in = { 1.0, -1e+160 }, .out = { -1.0, 5e-161 } }, + { .in = { 1e-300, -700.0 }, .out = { -0.9107243662191306, 8.927563378086943e+298 } }, + { .in = { 1e+308, 709.0 }, .out = { 1.7033875448561395, 2.7033875448561395e-308 } }, + { .in = { 100.0, 3.605170185988092 }, + .out = { -0.3844432335204093, 0.0061555676647959065 } }, + { .in = { 1.0, -1e-06 }, .out = { 499999.0, 500000.0 } }, + { .in = { 1.0, -5.1e-05 }, .out = { 9803.088232501696, 9804.088232501696 } }, + { .in = { 1.0, -5e-324 }, .out = { INFINITY, INFINITY } }, + { .in = { 5e-324, -745.0 }, .out = { 0.02761135468838516, INFINITY } }, + { .in = { 1.0, 0.0 }, .ret = TSD_ERR_JENSEN_VIOLATION }, + { .in = { 1.0, NAN }, .ret = TSD_ERR_JENSEN_VIOLATION }, + { .in = { 1.0, -INFINITY }, .ret = TSD_ERR_NONPOSITIVE_OR_NONFINITE_MOMENTS }, + { .in = { 1.0, INFINITY }, .ret = TSD_ERR_NONPOSITIVE_OR_NONFINITE_MOMENTS }, + { .in = { 0.0, -1.0 }, .ret = TSD_ERR_NONPOSITIVE_OR_NONFINITE_MOMENTS }, + { .in = { INFINITY, -1.0 }, .ret = TSD_ERR_ZERO_DIVISION }, + { .in = { 1.0, -1e+164 }, .ret = TSD_ERR_ZERO_DIVISION }, +}; + +/* Expected values of the reference implementation */ +static const approx_row_t gamma_mom_rows[] = { + { .in = { 1.0, 1.0 }, .out = { 0.0, 1.0 } }, + { .in = { 2.0, 4.0 }, .out = { 0.0, 0.5 } }, + { .in = { 1000.0, 1e-06 }, .out = { 999999999999.0, 1000000000.0 } }, + { .in = { 5e-324, 5e-324 }, .out = { -1.0, 1.0 } }, + { .in = { 1.0, 1e-300 }, .out = { 9.999999999999999e+299, 9.999999999999999e+299 } }, + { .in = { 1.0, 5e-324 }, .out = { INFINITY, INFINITY } }, + { .in = { INFINITY, 1.0 }, .out = { INFINITY, INFINITY } }, + { .in = { INFINITY, INFINITY }, .out = { NAN, NAN } }, + { .in = { 1e-200, 1e-200 }, .out = { -1.0, 1.0 } }, + { .in = { 1.0, 0.0 }, .ret = TSD_ERR_NONPOSITIVE_CENTRAL_MOMENTS }, + { .in = { -1.0, 1.0 }, .ret = TSD_ERR_NONPOSITIVE_CENTRAL_MOMENTS }, + { .in = { NAN, 1.0 }, .ret = TSD_ERR_NONPOSITIVE_CENTRAL_MOMENTS }, +}; + +/* Expected values of the reference implementation */ +static const approx_row_t gamma_iqr_rows[] = { + { .in = { 0.25, 0.75, 1.0, 3.0, 50.0 }, + .out = { 0.7901246810530893, 0.8091070002056516 } }, + { .in = { 0.25, 0.75, 7725.886769523864, 11913.846021515428, 50.0 }, + .out = { 9.00000000000002, 0.0010000000000000022 } }, + { .in = { 0.25, 0.75, 50.765522133810784, 661.6518484657332, 10.0 }, + .out = { -0.5000000000000002, 0.0009999999999999998 } }, + { .in = { 0.25, 0.75, 9932370.564904187, 10067266.062388988, 100000.0 }, + .out = { 9999.000000001251, 0.0010000000000001258 } }, + { .in = { 0.25, 0.75, 46018.97506946053, 55618.243378532934, 50.0 }, + .out = { 49.0, 0.0009793049455175092 } }, + { .in = { 0.25, 0.75, 3.0, 3.0, 50.0 }, .out = { 49.0, 15.022203291056554 } }, + { .in = { 0.25, 0.75, 1.0, 1.1, 2.0 }, .out = { 1.0, 0.9612787631147771 } }, + { .in = { 0.25, 0.75, 0.9612787631147771, 2.692634528889695, 0.0 }, + .out = { -1.0, NAN } }, + { .in = { 0.25, 0.75, 2.0, 1.0, 50.0 }, .ret = TSD_ERR_UNSORTED_QUANTILES }, + { .in = { NAN, 0.75, 1.0, 2.0, 50.0 }, .ret = TSD_ERR_UNSORTED_QUANTILES }, + { .in = { 0.25, 0.75, 0.0, 0.0, 50.0 }, .ret = TSD_ERR_ZERO_DIVISION }, + { .in = { 0.25, 0.75, 0.0, 1.0, 50.0 }, .ret = TSD_ERR_ZERO_DIVISION }, + { .in = { 0.0, 0.75, 1.0, 2.0, 50.0 }, .ret = TSD_ERR_ZERO_DIVISION }, + { .in = { 0.25, 1.0, 1.0, 2.0, 50.0 }, .ret = TSD_ERR_NEGATIVE_SHAPE }, + { .in = { 0.25, 0.75, 1.0, INFINITY, 50.0 }, .ret = TSD_ERR_INVALID_HYPERGEO }, + { .in = { 0.25, 1.5, 1.0, 2.0, 50.0 }, .ret = TSD_ERR_INVALID_HYPERGEO }, + { .in = { 1e-200, 0.99, 1.0, 1.2, 1e+300 }, .ret = TSD_ERR_QUANTILE_MAX_ITERATIONS }, + { .in = { 1e-300, 1e-299, 1.0, 1e+30, 50.0 }, .ret = TSD_ERR_ZERO_DIVISION }, + { .in = { 0.25, 0.75, 5.256386560310826e-218, 9.53e-42, 50.0 }, + .ret = TSD_ERR_ZERO_DIVISION }, + { .in = { 0.25, 0.75, 1.0, 1.0001, 1000000.0 }, .ret = TSD_ERR_ZERO_DIVISION }, +}; + +/* Expected values of the reference implementation */ +static const approx_row_t valid_moments_rows[] = { + { .in = { 1.0, 1.0 }, .out = { 1.0 } }, + { .in = { 5e-324, 5e-324 }, .out = { 1.0 } }, + { .in = { 1.7976931348623157e+308, 1.7976931348623157e+308 }, .out = { 1.0 } }, + { .in = { 0.0, 1.0 }, .out = { 0.0 } }, + { .in = { 1.0, 0.0 }, .out = { 0.0 } }, + { .in = { -1.0, 1.0 }, .out = { 0.0 } }, + { .in = { 1.0, -1.0 }, .out = { 0.0 } }, + { .in = { INFINITY, 1.0 }, .out = { 0.0 } }, + { .in = { 1.0, INFINITY }, .out = { 0.0 } }, + { .in = { -INFINITY, 1.0 }, .out = { 0.0 } }, + { .in = { NAN, 1.0 }, .out = { 0.0 } }, + { .in = { 1.0, NAN }, .out = { 0.0 } }, +}; + +/* Expected values of the reference implementation */ +static const approx_row_t valid_gamma_rows[] = { + { .in = { 1.0, 1.0 }, .out = { 1.0 } }, + { .in = { 5e-324, 5e-324 }, .out = { 1.0 } }, + { .in = { 1.7976931348623157e+308, 1.7976931348623157e+308 }, .out = { 1.0 } }, + { .in = { 0.0, 1.0 }, .out = { 0.0 } }, + { .in = { 1.0, 0.0 }, .out = { 0.0 } }, + { .in = { -1.0, 1.0 }, .out = { 0.0 } }, + { .in = { 1.0, -1.0 }, .out = { 0.0 } }, + { .in = { INFINITY, 1.0 }, .out = { 0.0 } }, + { .in = { 1.0, INFINITY }, .out = { 0.0 } }, + { .in = { -INFINITY, 1.0 }, .out = { 0.0 } }, + { .in = { NAN, 1.0 }, .out = { 0.0 } }, + { .in = { 1.0, NAN }, .out = { 0.0 } }, +}; + +/* Expected values of the reference implementation */ +static const approx_row_t moments_rows[] = { + { .in = { 10.0, 0.01, 10.0, 0.01, 1.0, 0.0001 }, + .out = { 122.80948170104746, 1325.342857454897, 103491.97326437547, + 769.094660576317, 48824.51252025319 } }, + { .in = { 10.0, 0.01, 10.0, 0.01, 0.0, 0.0001 }, + .out = { 116.94940823258497, 1166.8217386979982, 84456.19337045238, + 829.8081251666888, 51480.22818100476 } }, + { .in = { 10.0, 0.01, 10.0, 0.01, 10000.0, 0.001 }, + .out = { 127387.4510634497, 910499.7977042779, 82752252.49682617, + 500.247250327001, 25024.723677237344 } }, + { .in = { 10.0, 0.01, 10.0, 0.01, 0.0, 0.0 }, + .out = { 116.98310817144016, 1172.1993731606126, 85998.44190601562, + 827.8006268393875, 51558.56727389339 } }, + { .in = { 100000000.0, 100000.0, 100000000.0, 100000.0, 1.0, 0.0001 }, + .out = { 1181551036.2989483, 1000.0872852957206, -0.41215872892644256, + 999.9127247041049, -0.41216047620400786 } }, + { .in = { 0.001, 1e-05, 0.001, 1e-05, 1.0, 0.0001 }, + .out = { 16.039512161262337, 9119.186826812647, 83189097.62379722, + 12.339454993237442, 292219.6727362964 } }, + { .in = { 10.0, 100000000.0, 10.0, 100000000.0, 1.0, 100000.0 }, + .out = { -360.6830669942327, 1.3322053216930383e-07, 1.0517374989732554e-15, + 7.672297026879568e-08, 4.877419678730164e-16 } }, + { .in = { 10.0, -0.0001, 10.0, 0.01, 1.0, 0.0001 }, + .out = { NAN, NAN, NAN, NAN, NAN } }, + { .in = { 10.0, 0.01, 10.0, -0.01, 1.0, 0.0001 }, + .out = { NAN, NAN, NAN, NAN, NAN } }, + { .in = { 10.0, 0.01, 10.0, -0.02, 1.0, 0.0001 }, + .out = { NAN, NAN, NAN, NAN, NAN } }, + { .in = { 10.0, 0.01, 10.0, 1000000000.0, 1.0, 0.0001 }, + .out = { -128.77903467642818, 1089.108910901103, 107832.56543473178, + 9.99999999989986e-09, 9.999999999796698e-18 } }, + { .in = { 10.0, 0.01, 0.0, 0.01, 1.0, 0.0001 }, .out = { NAN, NAN, NAN, NAN, NAN } }, + { .in = { 10.0, 0.01, 10.0, -0.005, 1.0, 0.0001 }, + .out = { 146.80391572052676, 3936.496779205956, 768709.069610931, + 3678.160288231403, 765043.3391407449 } }, + { .in = { 10.0, 0.01, 10.0, INFINITY, 1.0, 0.0001 }, + .out = { NAN, NAN, NAN, NAN, NAN } }, + { .in = { 1210672666.2995348, 852947.3207951145, 7951733.774369938, + 595712303.1396025, -1.5, 2.8337046167584198e-14 }, + .ret = TSD_ERR_INVALID_HYPERGEO }, + { .in = { 394.178342527288, 2.415712247192439e-10, 2724.719060396573, + 0.008288652462722177, -1.0, 6.154356625573251e-06 }, + .ret = TSD_ERR_ZERO_DIVISION }, + { .in = { 5411.613776267856, 5038406234.100642, 4.2430562971178696e-09, + 0.042821205396860865, -1.0, 1163.787749187542 }, + .ret = TSD_ERR_INVALID_HYPERGEO }, + { .in = { 14401.04443044055, 18400282.490663443, 7.134225181058526e-10, + 0.005953404256099466, -1.0, 3.5941767717509845e-12 }, + .ret = TSD_ERR_INVALID_HYPERGEO }, +}; + +/* Expected values of the reference implementation */ +static const approx_row_t unphased_moments_rows[] = { + { .in = { 10.0, 0.01, 10.0, 0.01, 1.0, 0.0001 }, + .out = { 125.0990041915503, 1039.6039603960396, 105381.825311244, + 1039.6039603960396, 105381.825311244 } }, + { .in = { 10.0, 0.01, 10.0, 0.01, 0.0, 0.0001 }, + .out = { 117.5080520628614, 990.0990099009902, 98029.60494069196, + 990.0990099009902, 98029.60494069196 } }, + { .in = { 10.0, 0.01, 10.0, 0.01, 1.0, 1000000.0 }, + .out = { -261.5263346935328, 1.0499999895000001e-05, 1.0749999784999992e-11, + 1.0499999895000001e-05, 1.0749999784999992e-11 } }, + { .in = { 0.001, 1e-05, 0.001, 1e-05, 1.0, 0.0001 }, + .out = { 16.733009924901715, 4554.545454545454, 62066115.70247932, + 4554.545454545454, 62066115.70247932 } }, + { .in = { 10.0, 0.01, 10.0, 0.0001, 1.0, 0.0001 }, + .out = { 167.56758070890876, 992.1010384560702, 98428.07930575986, + 54898.897557968456, 275005184.82919836 } }, + { .in = { 10.0, 0.01, 10.0, 1000000000.0, 1.0, 0.0001 }, + .out = { -128.77903467622025, 1089.108910891121, 107832.56543475669, + 9.999999999998677e-09, 9.999999999996884e-18 } }, + { .in = { 10.0, -0.001, 10.0, 0.01, 1.0, 0.0001 }, + .out = { NAN, NAN, NAN, NAN, NAN } }, + { .in = { 10.0, 0.01, 10.0, -0.01, 1.0, 0.0001 }, + .out = { NAN, NAN, NAN, NAN, NAN } }, + { .in = { 10.0, 0.01, 0.0, 0.01, 1.0, 0.0001 }, .out = { NAN, NAN, NAN, NAN, NAN } }, + { .in = { 10.0, 0.01, 10.0, -0.005, 1.0, 0.0001 }, + .out = { NAN, NAN, NAN, NAN, NAN } }, + { .in = { 1.7660035936782157e-09, 670.7541722816065, 72.24709050049042, + 1.592021596132961e-05, 100000000.0, 627.5241160659726 }, + .ret = TSD_ERR_INVALID_HYPERGEO }, + { .in = { 2.1430622617768165e-06, 116952.43478981475, 3.3934123772179934e-07, + 9526762.492287748, 100000000.0, 1.1701319088974114 }, + .ret = TSD_ERR_INVALID_HYPERGEO }, + { .in = { 1.127136132156607e-08, 8599826.4555504, 3.892603570447169e-09, + 114569.03037514388, 100000000.0, 9.492307871836265e-08 }, + .ret = TSD_ERR_INVALID_HYPERGEO }, +}; + +/* Expected values of the reference implementation */ +static const approx_row_t rootward_moments_rows[] = { + { .in = { 1000.0, 10.0, 0.01, 1.0, 0.0001 }, + .out = { 63.61325539024935, 1455.418762370423, 74402.48694603037 } }, + { .in = { 1000.0, 10.0, 0.01, 0.0, 0.0001 }, + .out = { 58.00176214728721, 1257.0756375530668, 50989.18526668936 } }, + { .in = { 1000.0, 100000000.0, 100000.0, 1.0, 0.0001 }, + .out = { 590775516.345561, 1000.1237501242261, 0.004335264883656005 } }, + { .in = { 0.0, 10.0, 0.01, 1.0, 0.0001 }, + .out = { 65.65183097955968, 1089.1089108910892, 107832.5654347613 } }, + { .in = { -1.0, 10.0, 0.01, 1.0, 0.0001 }, .ret = TSD_ERR_INVALID_FIXED_AGE }, + { .in = { NAN, 10.0, 0.01, 1.0, 0.0001 }, .ret = TSD_ERR_INVALID_FIXED_AGE }, + { .in = { INFINITY, 10.0, 0.01, 1.0, 0.0001 }, .out = { NAN, NAN, NAN } }, + { .in = { 5e-324, 10.0, 0.01, 1.0, 0.0001 }, .out = { NAN, NAN, NAN } }, + { .in = { 1000.0, 10.0, -0.0001, 1.0, 0.0001 }, .out = { NAN, NAN, NAN } }, + { .in = { 1000.0, -1.0, 0.01, 1.0, 0.0001 }, .out = { NAN, NAN, NAN } }, + { .in = { 1000.0, 10.0, 0.01, -1.0, 0.0001 }, .out = { NAN, NAN, NAN } }, + { .in = { 8.45730940350531e-08, 17123191.868610334, 2.9302830155736855e-05, + 100000000.0, 7.326444260535366e-08 }, + .ret = TSD_ERR_ZERO_DIVISION }, + { .in = { 4.821917030411909e-10, 4.169349483790142e-07, 6.852235429528821e-10, 0.0, + 1.456098777070529e-12 }, + .ret = TSD_ERR_ZERO_DIVISION }, +}; + +/* Expected values of the reference implementation */ +static const approx_row_t leafward_moments_rows[] = { + { .in = { 1000.0, 10.0, 0.01, 1.0, 0.0001 }, + .out = { 63.63521858348348, 670.1964376749686, 22340.35255159228 } }, + { .in = { 1000.0, 10.0, 0.01, 0.0, 0.0001 }, + .out = { 58.18323329851714, 777.4330182308169, 23337.819922300754 } }, + { .in = { 5e-324, 10.0, 0.01, 1.0, 0.0001 }, + .out = { -8193.541271500986, 5e-324, 0.0 } }, + { .in = { 1000.0, 10.0, 0.01, 0.0, 0.0 }, + .out = { 58.20531612967109, 775.058535890135, 23627.901122838375 } }, + { .in = { 1000.0, 10.0, -0.001, 1.0, 0.0001 }, + .out = { 72.10770342368787, 844.497150879899, 9617.330910037155 } }, + { .in = { 0.0, 10.0, 0.01, 1.0, 0.0001 }, .ret = TSD_ERR_INVALID_FIXED_AGE }, + { .in = { NAN, 10.0, 0.01, 1.0, 0.0001 }, .ret = TSD_ERR_INVALID_FIXED_AGE }, + { .in = { INFINITY, 10.0, 0.01, 1.0, 0.0001 }, .out = { NAN, NAN, NAN } }, + { .in = { 1000.0, 0.0, 0.01, 1.0, 0.0001 }, .out = { NAN, NAN, NAN } }, + { .in = { 1000.0, 10.0, 0.01, -1.0, 0.0001 }, .ret = TSD_ERR_INVALID_HYPERGEO }, + { .in = { 330585155.6728075, 1.7609486342004178e-07, -25365.04126587679, -1.0, + 7.750515488516166e-07 }, + .ret = TSD_ERR_ZERO_DIVISION }, + { .in = { 4.74294373446301e-05, 1.4259421729061415e-08, 0.0006672649725106216, -1.0, + 6.017038390421106e-14 }, + .ret = TSD_ERR_INVALID_HYPERGEO }, + { .in = { 0.00011848982522731698, 3.0738172972482273e-07, 0.0033569587369897754, + -1.0, 0.02896515217052944 }, + .ret = TSD_ERR_INVALID_HYPERGEO }, +}; + +/* Expected values of the reference implementation */ +static const approx_row_t sideways_moments_rows[] = { + { .in = { 1000.0, 10.0, 0.01, 1.0, 0.0001 }, + .out = { 66.24960717136513, 1039.3289310811742, 105361.4400384126 } }, + { .in = { 1000.0, 10.0, 0.01, 0.0, 0.0001 }, + .out = { 58.6540260314307, 990.0990099009899, 98029.60494069227 } }, + { .in = { 10000000000.0, 10.0, 0.01, 1.0, 0.0001 }, + .out = { -999918.2201229396, 990.0990197039497, 98029.60688187221 } }, + { .in = { 1000.0, 0.001, 1e-05, 1.0, 0.0001 }, + .out = { 11.711002789755941, 6980.512954646106, 73216544.51397169 } }, + { .in = { 0.0, 10.0, 0.01, 1.0, 0.0001 }, .ret = TSD_ERR_INVALID_FIXED_AGE }, + { .in = { INFINITY, 10.0, 0.01, 1.0, 0.0001 }, .out = { NAN, NAN, NAN } }, + { .in = { 1000.0, 10.0, -0.001, 1.0, 0.0001 }, .out = { NAN, NAN, NAN } }, + { .in = { 1000.0, 0.0, 0.01, 1.0, 0.0001 }, .out = { NAN, NAN, NAN } }, + { .in = { 7951733.774369938, 2.83370461675842e-10, 2.3019958853100635e-08, + 100000000.0, 1.604270854947341e-07 }, + .ret = TSD_ERR_ZERO_DIVISION }, + { .in = { 4.821917030411909e-10, 4.169349483790142e-07, 6.852235429528821e-10, 0.0, + 1.456098777070529e-12 }, + .ret = TSD_ERR_ZERO_DIVISION }, +}; + +/* Expected values of the reference implementation */ +static const approx_row_t twin_moments_rows[] = { + { .in = { 10.0, 0.01, 1.0, 0.0001 }, + .out = { 66.23660289924649, 1078.4313725490194, 105728.56593617838 } }, + { .in = { 10.0, 0.01, 0.0, 0.0001 }, + .out = { 58.65550306700058, 980.3921568627451, 96116.87812379852 } }, + { .in = { 10.0, 0.01, 0.0, 0.0 }, .out = { 58.85352933996238, 1000.0, 100000.0 } }, + { .in = { 0.001, 1e-05, 1.0, 0.0001 }, + .out = { 9.169442217235714, 4766.666666666666, 22698412.698412694 } }, + { .in = { 10.0, -0.0002, 1.0, 0.0001 }, .ret = TSD_ERR_ZERO_DIVISION }, + { .in = { 10.0, 1e-300, 1.0, 0.0 }, .ret = TSD_ERR_ZERO_DIVISION }, + { .in = { 10.0, -0.001, 1.0, 0.0001 }, .out = { NAN, -13750.0, 17187500.0 } }, + { .in = { 0.0, 0.01, 0.0, 0.0001 }, .out = { INFINITY, 0.0, 0.0 } }, + { .in = { NAN, 0.01, 1.0, 0.0001 }, .out = { NAN, NAN, NAN } }, + { .in = { 10.0, 0.01, 1e+300, 0.0001 }, + .out + = { 6.950540426374656e+302, 9.80392156862745e+301, 9.611687812379853e+303 } }, +}; + +/* Expected values of the reference implementation */ +static const approx_row_t mutation_moments_rows[] = { + { .in = { 10.0, 0.01, 10.0, 0.01, 1.0, 0.0001 }, + .out = { 1047.218759015607, 84537.65971991606 } }, + { .in = { 10.0, 0.01, 10.0, 0.01, 0.0, 0.0001 }, + .out = { 998.3149319323435, 62090.58297391038 } }, + { .in = { 10.0, 0.01, 10.0, 0.01, 100.0, 0.001 }, + .out = { 5502.047266948612, 8593441.597390726 } }, + { .in = { 10.0, 0.01, 10.0, 0.01, 0.0, 0.0 }, .out = { 1000.0, 62985.06423178315 } }, + { .in = { 10000.0, 10.0, 10000.0, 10.0, 1.0, 0.0001 }, + .out = { 1000.0499125037055, 81.2219550292939 } }, + { .in = { 10.0, 0.01, 1e-08, 0.01, 1.0, 0.0001 }, + .out = { 544.5544559496102, 134790.70668813813 } }, + { .in = { 10.0, 0.01, 10.0, -0.005, 1.0, 0.0001 }, + .out = { 3807.328533718679, 767088.4841929078 } }, + { .in = { 10.0, -0.0001, 10.0, 0.01, 1.0, 0.0001 }, .out = { NAN, NAN } }, + { .in = { 10.0, 0.01, 10.0, -0.02, 1.0, 0.0001 }, .out = { NAN, NAN } }, + { .in = { 10.0, 0.01, 10.0, 1000.0, 1.0, 0.0001 }, + .out = { 544.3849588249741, 135333.42707343184 } }, + { .in = { 1210672666.2995348, 852947.3207951145, 7951733.774369938, + 595712303.1396025, -1.5, 2.8337046167584198e-14 }, + .ret = TSD_ERR_INVALID_HYPERGEO }, + { .in = { 1582171.4459529708, 300601562.7452449, 0.0001303504890295087, + -1852940.2349876668, -1.0, 38.337696337086264 }, + .ret = TSD_ERR_INVALID_HYPERGEO }, + { .in = { 5411.613776267856, 5038406234.100642, 4.2430562971178696e-09, + 0.042821205396860865, -1.0, 1163.787749187542 }, + .ret = TSD_ERR_INVALID_HYPERGEO }, + { .in = { 634745702.2698317, 329.06825010605945, 0.038930042876279006, + 1.3003726540202816, -0.5, 871.1707853483364 }, + .ret = TSD_ERR_INVALID_HYPERGEO }, + { .in = { 14401.04443044055, 18400282.490663443, 7.134225181058526e-10, + 0.005953404256099466, -1.0, 3.5941767717509845e-12 }, + .ret = TSD_ERR_INVALID_HYPERGEO }, +}; + +/* Expected values of the reference implementation */ +static const approx_row_t mutation_rootward_moments_rows[] = { + { .in = { 1000.0, 10.0, 0.01, 1.0, 0.0001 }, + .out = { 1227.7093811852114, 42084.6830752613 } }, + { .in = { 0.0, 10.0, 0.01, 1.0, 0.0001 }, + .out = { 544.5544554455446, 134790.70679345162 } }, + { .in = { 10000000000.0, 10.0, 0.01, 1.0, 0.0001 }, + .out = { 10000000099.00991, 0.0 } }, + { .in = { 1000.0, 10.0, 0.01, 1.0, 100000.0 }, .out = { 1000.00001, 0.0 } }, + { .in = { 1000.0, 0.001, 1e-05, 1.0, 0.0001 }, + .out = { 6236.530310629031, 38372903.84425615 } }, + { .in = { 1000.0, 10.0, 0.01, -0.5, 0.0001 }, + .out = { 1061.7041169771032, 11122.429033691995 } }, + { .in = { -1.0, 10.0, 0.01, 1.0, 0.0001 }, .ret = TSD_ERR_INVALID_FIXED_AGE }, + { .in = { 1000.0, 10.0, -0.0001, 1.0, 0.0001 }, .out = { NAN, NAN } }, + { .in = { 1000.0, 0.0, 0.01, 1.0, 0.0001 }, .out = { NAN, NAN } }, + { .in = { 8.45730940350531e-08, 17123191.868610334, 2.9302830155736855e-05, + 100000000.0, 7.326444260535366e-08 }, + .ret = TSD_ERR_ZERO_DIVISION }, +}; + +/* Expected values of the reference implementation */ +static const approx_row_t mutation_leafward_moments_rows[] = { + { .in = { 1000.0, 10.0, 0.01, 1.0, 0.0001 }, + .out = { 835.0982188374843, 16510.9833273876 } }, + { .in = { 1000.0, 10.0, 0.01, 0.0, 0.0001 }, + .out = { 888.7165091154084, 11907.278421920608 } }, + { .in = { 1e-10, 10.0, 0.01, 1.0, 0.0001 }, + .out = { 9.166666666666644e-11, 5.876068376064695e-23 } }, + { .in = { 1000.0, 10.0, 0.01, 1.0, 100000.0 }, + .out = { 999.7437094147001, 206.32833492441569 } }, + { .in = { 1000.0, 100000000.0, 100000.0, 1.0, 0.0001 }, + .out = { 999.9383327981366, -0.20729712094180286 } }, + { .in = { 1000.0, 10.0, -0.001, 1.0, 0.0001 }, + .out = { 922.2485754399495, 5220.871643718099 } }, + { .in = { 0.0, 10.0, 0.01, 1.0, 0.0001 }, .ret = TSD_ERR_INVALID_FIXED_AGE }, + { .in = { INFINITY, 10.0, 0.01, 1.0, 0.0001 }, .out = { NAN, NAN } }, + { .in = { 1000.0, -1.0, 0.01, 1.0, 0.0001 }, .out = { NAN, NAN } }, + { .in = { 1000.0, 10.0, 0.01, -1.0, 0.0001 }, .ret = TSD_ERR_INVALID_HYPERGEO }, + { .in = { 330585155.6728075, 1.7609486342004178e-07, -25365.04126587679, -1.0, + 7.750515488516166e-07 }, + .ret = TSD_ERR_ZERO_DIVISION }, +}; + +/* Expected values of the reference implementation */ +static const approx_row_t mutation_unphased_moments_rows[] = { + { .in = { 10.0, 0.01, 10.0, 0.01, 1.0, 0.0001 }, + .out = { 0.5, 544.5544554455446, 134790.70679345162 } }, + { .in = { 10.0, 0.01, 10.0, 0.01, 0.0, 0.0001 }, + .out = { 0.5, 518.6232909005187, 123148.30189828435 } }, + { .in = { 10.0, 0.01, 10.0, 0.01, 0.0, 0.0 }, + .out = { 0.5, 523.8095238095239, 125623.58276643988 } }, + { .in = { 10.0, 0.01, 10.0, 1000000000.0, 1.0, 0.0001 }, + .out = { 1.0000000000000018, 544.5527343394893, 134789.85476212116 } }, + { .in = { 10.0, 0.01, 10.0, 1000.0, 1.0, 0.0001 }, + .out = { 0.9994316225667118, 544.2449430101359, 134882.545335442 } }, + { .in = { 1289.8261024396659, 2.1161296052067344, 0.15552864791315738, + 0.0007984796762152916, 1.0, 4.811169071413665e-07 }, + .out = { 1.0305283005758967, 552.3102881259031, 250943.13466915407 } }, + { .in = { 10.0, -0.001, 10.0, 0.01, 1.0, 0.0001 }, .out = { NAN, NAN, NAN } }, + { .in = { 10.0, 0.01, 0.0, 0.01, 1.0, 0.0001 }, .out = { NAN, NAN, NAN } }, + { .in = { 1.7660035936782157e-09, 670.7541722816065, 72.24709050049042, + 1.592021596132961e-05, 100000000.0, 627.5241160659726 }, + .ret = TSD_ERR_INVALID_HYPERGEO }, + { .in = { 2.1430622617768165e-06, 116952.43478981475, 3.3934123772179934e-07, + 9526762.492287748, 100000000.0, 1.1701319088974114 }, + .ret = TSD_ERR_INVALID_HYPERGEO }, + { .in = { 0.03147408814983863, -3.572097767193457e-06, 6.968397736253467e-05, + 0.0003977607105897399, 100000000.0, 0.00014045130994169163 }, + .ret = TSD_ERR_INVALID_HYPERGEO }, + { .in = { 0.8357818401616357, 1.3209477340917621e-09, 0.002340461703952937, + 0.00025633858557600413, 100000000.0, 0.0006572496535582051 }, + .ret = TSD_ERR_INVALID_HYPERGEO }, + { .in = { 8.487509248373367e-05, 993617.5506944145, 44356376.30250234, + 12.330141147550119, 100000000.0, 1.5394974045964461e-09 }, + .ret = TSD_ERR_INVALID_HYPERGEO }, + { .in = { 8.411928444767107e-07, 5.338254701078075e-06, 7363270781.288286, + -0.012693009987637643, 2.0, 2.6034067423152516 }, + .ret = TSD_ERR_INVALID_HYPERGEO }, +}; + +/* Expected values of the reference implementation */ +static const approx_row_t mutation_twin_moments_rows[] = { + { .in = { 10.0, 0.01, 1.0, 0.0001 }, + .out = { 0.5, 539.2156862745097, 132160.70742022299 } }, + { .in = { 10.0, 0.01, 0.0, 0.0001 }, + .out = { 0.5, 490.19607843137254, 112136.35781109825 } }, + { .in = { 0.001, 1e-05, 1.0, 0.0001 }, + .out = { 0.5, 2383.333333333333, 9459563.49206349 } }, + { .in = { 10.0, -0.001, 1.0, 0.0001 }, .out = { 0.5, -6875.0, 21484375.0 } }, + { .in = { -1.0, 0.01, 0.0, 0.0001 }, + .out = { 0.5, -49.01960784313725, -2402.921953094963 } }, + { .in = { 10.0, -0.0002, 1.0, 0.0001 }, .ret = TSD_ERR_ZERO_DIVISION }, + { .in = { 10.0, 1e-300, 1.0, 0.0 }, .ret = TSD_ERR_ZERO_DIVISION }, + { .in = { NAN, 0.01, 1.0, 0.0001 }, .out = { 0.5, NAN, NAN } }, + { .in = { 10.0, 0.01, 1e+300, 0.0001 }, + .out = { 0.5, 4.901960784313725e+301, NAN } }, + { .in = { 10.0, 0.01, 1.0, 1e+300 }, .out = { 0.5, 2.75e-300, 0.0 } }, +}; + +/* Expected values of the reference implementation */ +static const approx_row_t mutation_sideways_moments_rows[] = { + { .in = { 1000.0, 10.0, 0.01, 1.0, 0.0001 }, + .out = { 0.5023091569426977, 522.1743444926516, 109439.4612022693 } }, + { .in = { 1000.0, 10.0, 0.01, 0.0, 0.0001 }, + .out = { 0.5144541526611798, 509.6511047608551, 102996.39823434927 } }, + { .in = { 1e-10, 10.0, 0.01, 1.0, 0.0001 }, + .out = { 0.0007564619471360778, 544.1407948153603, 134914.7638092785 } }, + { .in = { 0.0, 10.0, 0.01, 1.0, 0.0001 }, .ret = TSD_ERR_INVALID_FIXED_AGE }, + { .in = { INFINITY, 10.0, 0.01, 1.0, 0.0001 }, .out = { NAN, NAN, NAN } }, + { .in = { 1000.0, 10.0, -0.0001, 1.0, 0.0001 }, .out = { NAN, NAN, NAN } }, + { .in = { 1000.0, 0.0, 0.01, 1.0, 0.0001 }, .out = { NAN, NAN, NAN } }, + { .in = { 1000.0, 10.0, 0.01, -0.5, 0.0001 }, .ret = TSD_ERR_INVALID_HYPERGEO }, + { .in = { 7951733.774369938, 2.83370461675842e-10, 2.3019958853100635e-08, + 100000000.0, 1.604270854947341e-07 }, + .ret = TSD_ERR_ZERO_DIVISION }, + { .in = { 3439589.3148461175, 51334026.94161953, -8.147893520675203e-06, -0.5, + 23.460646619971012 }, + .ret = TSD_ERR_INVALID_HYPERGEO }, + { .in = { 17.77466115825119, 8.850693381150145e-07, 1.2068705882784672e-08, 0.0, + 7.490387184896008e-07 }, + .ret = TSD_ERR_INVALID_HYPERGEO }, + { .in = { 3.785982048609923e-06, 8.363428340996249, 0.0001149777112112498, 10000.0, + 9.903472470733758e-13 }, + .ret = TSD_ERR_ZERO_DIVISION }, +}; + +/* Expected values of the reference implementation */ +static const approx_row_t mutation_edge_moments_rows[] = { + { .in = { 3.0, 1.0 }, .out = { 2.0, 0.3333333333333333 } }, + { .in = { 1.0, 3.0 }, .out = { 2.0, 0.3333333333333333 } }, + { .in = { 1.0, 1.0 }, .out = { 1.0, 0.0 } }, + { .in = { 0.0, 0.0 }, .out = { 0.0, 0.0 } }, + { .in = { -1.0, 1.0 }, .out = { 0.0, 0.3333333333333333 } }, + { .in = { 1e+300, 1.0 }, .out = { 5e+299, INFINITY } }, + { .in = { 1e-200, 1e-210 }, .out = { 5.0000000005e-201, 0.0 } }, + { .in = { 1.0, 0.9999999999999999 }, .out = { 1.0, 1.0271626370065257e-33 } }, + { .in = { NAN, 1.0 }, .out = { NAN, NAN } }, + { .in = { INFINITY, INFINITY }, .out = { INFINITY, NAN } }, +}; + +/* Expected values of the reference implementation */ +static const approx_row_t mutation_block_moments_rows[] = { + { .in = { 3.0, 1.0 }, .out = { 0.75, 1.25, 0.7708333333333335 } }, + { .in = { 1.0, 3.0 }, .out = { 0.25, 1.25, 0.7708333333333335 } }, + { .in = { 1.0, 1.0 }, .out = { 0.5, 0.5, 0.08333333333333331 } }, + { .in = { 1e-160, 1e-170 }, .out = { 0.9999999999, 4.9999999995e-161, 8.35e-322 } }, + { .in = { 1e+300, 1.0 }, .out = { 1.0, 5e+299, NAN } }, + { .in = { INFINITY, 1.0 }, .out = { NAN, NAN, NAN } }, + { .in = { 0.0, 1.0 }, .ret = TSD_ERR_INVALID_FIXED_AGE }, + { .in = { 1.0, 0.0 }, .ret = TSD_ERR_INVALID_FIXED_AGE }, + { .in = { -1.0, 1.0 }, .ret = TSD_ERR_INVALID_FIXED_AGE }, + { .in = { NAN, 1.0 }, .ret = TSD_ERR_INVALID_FIXED_AGE }, +}; + +/* Expected values of the reference implementation */ +static const approx_row_t gamma_projection_rows[] = { + { .in = { 9.0, 0.01, 9.0, 0.01, 1.0, 0.0001 }, + .out = { 122.80948170104746, 15.972656278565271, 0.012806238161767791, + 11.11495141260517, 0.015752224054613635 } }, + { .in = { 9.0, 0.01, 9.0, 0.01, 0.0, 0.0001 }, + .out = { 116.94940823258497, 15.12046334987365, 0.0138157036462671, + 12.375650204416319, 0.016118967504360683 } }, + { .in = { 9.0, 0.01, 9.0, 0.01, 10000.0, 0.001 }, + .out = { 127387.4510634497, 10016.973609254037, 0.011002719203796883, + 9.000002984542515, 0.01999012084125545 } }, + { .in = { 9.0, 0.01, 9.0, 0.01, 0.0, 0.0 }, + .out = { 116.98310817144016, 14.977630989405377, 0.013630472217643944, + 12.29078587764909, 0.01605553976009227 } }, + { .in = { 99999999.0, 100000.0, 99999999.0, 100000.0, 1.0, 0.0001 }, + .out = { NAN, 99999999.0, 100000.0, 99999999.0, 100000.0 } }, + { .in = { -0.999, 1e-05, -0.999, 1e-05, 1.0, 0.0001 }, + .out = { 16.039512161262337, -0.0003549652818382043, 0.00010961997530075378, + -0.9994789462731773, 4.222664024530874e-05 } }, + { .in = { 9.0, 100000000.0, 9.0, 100000000.0, 1.0, 100000.0 }, + .out = { -360.6830669942327, 15.874657610666617, 126667093.54697211, + 11.068705493063154, 157302375.68724146 } }, + { .in = { 9.0, -0.0001, 9.0, 0.01, 1.0, 0.0001 }, + .out = { NAN, 9.0, -0.0001, 9.0, 0.01 } }, + { .in = { 9.0, 0.01, 9.0, -0.01, 1.0, 0.0001 }, + .out = { NAN, 9.0, 0.01, 9.0, -0.01 } }, + { .in = { 9.0, 0.01, 9.0, -0.02, 1.0, 0.0001 }, + .out = { NAN, 9.0, 0.01, 9.0, -0.02 } }, + { .in = { 9.0, 0.01, 9.0, 1000000000.0, 1.0, 0.0001 }, + .out = { -128.77903467642818, 10.000000000205292, 0.01010000000009563, + 9.000000000003022, 1000000000.0103163 } }, + { .in = { 9.0, 0.01, -1.0, 0.01, 1.0, 0.0001 }, + .out = { NAN, 9.0, 0.01, -1.0, 0.01 } }, + { .in = { 9.0, 0.01, 9.0, -0.005, 1.0, 0.0001 }, + .out = { 146.80391572052676, 19.158480633696577, 0.005120918868822957, + 16.68378654354066, 0.004807780291718522 } }, + { .in = { 9.0, 0.01, 9.0, INFINITY, 1.0, 0.0001 }, + .out = { NAN, 9.0, 0.01, 9.0, INFINITY } }, + { .in = { 1210672665.2995348, 852947.3207951145, 7951732.774369938, + 595712303.1396025, -1.5, 2.8337046167584198e-14 }, + .ret = TSD_ERR_INVALID_HYPERGEO }, + { .in = { 393.178342527288, 2.415712247192439e-10, 2723.719060396573, + 0.008288652462722177, -1.0, 6.154356625573251e-06 }, + .ret = TSD_ERR_ZERO_DIVISION }, + { .in = { 5410.613776267856, 5038406234.100642, -0.9999999957569436, + 0.042821205396860865, -1.0, 1163.787749187542 }, + .ret = TSD_ERR_INVALID_HYPERGEO }, + { .in = { 14400.04443044055, 18400282.490663443, -0.9999999992865775, + 0.005953404256099466, -1.0, 3.5941767717509845e-12 }, + .ret = TSD_ERR_ZERO_DIVISION }, + { .in = { 36.27758386050227, 12.719368036205545, 26317363.808861483, + 1.6898146193313483e-07, 2.0, 3.273276230928174e-07 }, + .out = { NAN, 36.27758386050227, 12.719368036205545, 26317363.808861483, + 1.6898146193313483e-07 } }, +}; + +/* Expected values of the reference implementation */ +static const approx_row_t leafward_projection_rows[] = { + { .in = { 1000.0, 9.0, 0.01, 1.0, 0.0001 }, + .out = { 63.63521858348348, 19.105468973013345, 0.029999367115054822 } }, + { .in = { 1000.0, 9.0, 0.01, 0.0, 0.0001 }, + .out = { 58.18323329851714, 24.897967327185235, 0.033312152584052235 } }, + { .in = { 5e-324, 9.0, 0.01, 1.0, 0.0001 }, .out = { NAN, 9.0, 0.01 } }, + { .in = { 1000.0, 9.0, 0.01, 0.0, 0.0 }, + .out = { 58.20531612967109, 24.42399898040528, 0.032802682382184804 } }, + { .in = { 1000.0, 9.0, -0.001, 1.0, 0.0001 }, + .out = { 72.10770342368787, 73.15523543023349, 0.08780992967586641 } }, + { .in = { 0.0, 9.0, 0.01, 1.0, 0.0001 }, .ret = TSD_ERR_INVALID_FIXED_AGE }, + { .in = { NAN, 9.0, 0.01, 1.0, 0.0001 }, .ret = TSD_ERR_INVALID_FIXED_AGE }, + { .in = { INFINITY, 9.0, 0.01, 1.0, 0.0001 }, .out = { NAN, 9.0, 0.01 } }, + { .in = { 1000.0, -1.0, 0.01, 1.0, 0.0001 }, .out = { NAN, -1.0, 0.01 } }, + { .in = { 1000.0, 9.0, 0.01, -1.0, 0.0001 }, .ret = TSD_ERR_INVALID_HYPERGEO }, + { .in = { 330585155.6728075, -0.9999998239051365, -25365.04126587679, -1.0, + 7.750515488516166e-07 }, + .ret = TSD_ERR_INVALID_HYPERGEO }, + { .in = { 4.74294373446301e-05, -0.9999999857405782, 0.0006672649725106216, -1.0, + 6.017038390421106e-14 }, + .ret = TSD_ERR_INVALID_HYPERGEO }, + { .in = { 0.00011848982522731698, -0.9999996926182703, 0.0033569587369897754, -1.0, + 0.02896515217052944 }, + .ret = TSD_ERR_INVALID_HYPERGEO }, +}; + +/* Expected values of the reference implementation */ +static const approx_row_t rootward_projection_rows[] = { + { .in = { 1000.0, 9.0, 0.01, 1.0, 0.0001 }, + .out = { 63.61325539024935, 27.47006680564822, 0.01956142626557827 } }, + { .in = { 1000.0, 9.0, 0.01, 0.0, 0.0001 }, + .out = { 58.00176214728721, 29.991653431297348, 0.024653769833312078 } }, + { .in = { 1000.0, 99999999.0, 100000.0, 1.0, 0.0001 }, + .out = { 590775516.345561, 230723505.49979642, 230694.95797008928 } }, + { .in = { 0.0, 9.0, 0.01, 1.0, 0.0001 }, + .out = { 65.65183097955968, 10.0, 0.0101 } }, + { .in = { -1.0, 9.0, 0.01, 1.0, 0.0001 }, .ret = TSD_ERR_INVALID_FIXED_AGE }, + { .in = { NAN, 9.0, 0.01, 1.0, 0.0001 }, .ret = TSD_ERR_INVALID_FIXED_AGE }, + { .in = { INFINITY, 9.0, 0.01, 1.0, 0.0001 }, .out = { NAN, 9.0, 0.01 } }, + { .in = { 5e-324, 9.0, 0.01, 1.0, 0.0001 }, .out = { NAN, 9.0, 0.01 } }, + { .in = { 1000.0, 9.0, -0.0001, 1.0, 0.0001 }, .out = { NAN, 9.0, -0.0001 } }, + { .in = { 1000.0, -2.0, 0.01, 1.0, 0.0001 }, .out = { NAN, -2.0, 0.01 } }, + { .in = { 1000.0, 9.0, 0.01, -1.0, 0.0001 }, .out = { NAN, 9.0, 0.01 } }, + { .in = { 8.45730940350531e-08, 17123190.868610334, 2.9302830155736855e-05, + 100000000.0, 7.326444260535366e-08 }, + .ret = TSD_ERR_ZERO_DIVISION }, + { .in = { 4.821917030411909e-10, -0.9999995830650517, 6.852235429528821e-10, 0.0, + 1.456098777070529e-12 }, + .ret = TSD_ERR_ZERO_DIVISION }, +}; + +/* Expected values of the reference implementation */ +static const approx_row_t unphased_projection_rows[] = { + { .in = { 9.0, 0.01, 9.0, 0.01, 1.0, 0.0001 }, + .out = { 125.0990041915503, 9.255813953488373, 0.009865116279069767, + 9.255813953488373, 0.009865116279069767 } }, + { .in = { 9.0, 0.01, 9.0, 0.01, 0.0, 0.0001 }, + .out = { 117.5080520628614, 9.000000000000014, 0.010100000000000013, + 9.000000000000014, 0.010100000000000013 } }, + { .in = { 9.0, 0.01, 9.0, 0.01, 1.0, 1000000.0 }, + .out = { -261.5263346935328, 9.255813953488383, 976744.1958139545, + 9.255813953488383, 976744.1958139545 } }, + { .in = { -0.999, 1e-05, -0.999, 1e-05, 1.0, 0.0001 }, + .out = { 16.733009924901715, -0.6657776298268974, 7.338215712383491e-05, + -0.6657776298268974, 7.338215712383491e-05 } }, + { .in = { 9.0, 0.01, 9.0, 0.0001, 1.0, 0.0001 }, + .out = { 167.56758070890876, 8.999834167728347, 0.010079451366455893, + 9.959389565517451, 0.00019962859097389507 } }, + { .in = { 9.0, 0.01, 9.0, 1000000000.0, 1.0, 0.0001 }, + .out = { -128.77903467622025, 10.000000000001114, 0.010100000000000728, + 9.000000000000469, 1000000000.0001793 } }, + { .in = { 9.0, -0.001, 9.0, 0.01, 1.0, 0.0001 }, + .out = { NAN, 9.0, -0.001, 9.0, 0.01 } }, + { .in = { 9.0, 0.01, 9.0, -0.01, 1.0, 0.0001 }, + .out = { NAN, 9.0, 0.01, 9.0, -0.01 } }, + { .in = { 9.0, 0.01, -1.0, 0.01, 1.0, 0.0001 }, + .out = { NAN, 9.0, 0.01, -1.0, 0.01 } }, + { .in = { 9.0, 0.01, 9.0, -0.005, 1.0, 0.0001 }, + .out = { NAN, 9.0, 0.01, 9.0, -0.005 } }, + { .in = { -0.9999999982339964, 670.7541722816065, 71.24709050049042, + 1.592021596132961e-05, 100000000.0, 627.5241160659726 }, + .ret = TSD_ERR_INVALID_HYPERGEO }, + { .in = { -0.9999978569377382, 116952.43478981475, -0.9999996606587622, + 9526762.492287748, 100000000.0, 1.1701319088974114 }, + .ret = TSD_ERR_INVALID_HYPERGEO }, + { .in = { -0.9999999887286387, 8599826.4555504, -0.9999999961073964, + 114569.03037514388, 100000000.0, 9.492307871836265e-08 }, + .ret = TSD_ERR_INVALID_HYPERGEO }, + { .in = { 24464916.038703892, 183.8190229856431, 15606407.365774523, + 29.436886993709617, 100.0, 0.036593097704101483 }, + .out = { NAN, 24464916.038703892, 183.8190229856431, 15606407.365774523, + 29.436886993709617 } }, +}; + +/* Expected values of the reference implementation */ +static const approx_row_t twin_projection_rows[] = { + { .in = { 9.0, 0.01, 1.0, 0.0001 }, .out = { 66.23660289924649, 10.0, 0.0102 } }, + { .in = { 9.0, 0.01, 0.0, 0.0001 }, + .out = { 58.65550306700058, 9.000000000000002, 0.0102 } }, + { .in = { 9.0, 0.01, 0.0, 0.0 }, .out = { 58.85352933996238, 9.0, 0.01 } }, + { .in = { -0.999, 1e-05, 1.0, 0.0001 }, + .out = { 9.169442217235714, 0.0009999999999998899, 0.00021 } }, + { .in = { 9.0, -0.0002, 1.0, 0.0001 }, .ret = TSD_ERR_ZERO_DIVISION }, + { .in = { 9.0, 1e-300, 1.0, 0.0 }, .ret = TSD_ERR_ZERO_DIVISION }, + { .in = { 9.0, -0.001, 1.0, 0.0001 }, .out = { NAN, 9.0, -0.001 } }, + { .in = { -1.0, 0.01, 0.0, 0.0001 }, .out = { NAN, -1.0, 0.01 } }, + { .in = { NAN, 0.01, 1.0, 0.0001 }, .out = { NAN, NAN, 0.01 } }, + { .in = { 9.0, 0.01, 1e+300, 0.0001 }, + .out = { 6.950540426374656e+302, INFINITY, 0.0102 } }, +}; + +/* Expected values of the reference implementation */ +static const approx_row_t sideways_projection_rows[] = { + { .in = { 1000.0, 9.0, 0.01, 1.0, 0.0001 }, + .out = { 66.24960717136513, 9.252371518351646, 0.009864414635015015 } }, + { .in = { 1000.0, 9.0, 0.01, 0.0, 0.0001 }, + .out = { 58.6540260314307, 8.999999999999979, 0.01009999999999998 } }, + { .in = { 10000000000.0, 9.0, 0.01, 1.0, 0.0001 }, + .out = { -999918.2201229396, 9.0, 0.01009999990000001 } }, + { .in = { 1000.0, -0.999, 1e-05, 1.0, 0.0001 }, + .out = { 11.711002789755941, -0.3344733566238761, 9.534065013562661e-05 } }, + { .in = { 0.0, 9.0, 0.01, 1.0, 0.0001 }, .ret = TSD_ERR_INVALID_FIXED_AGE }, + { .in = { INFINITY, 9.0, 0.01, 1.0, 0.0001 }, .out = { NAN, 9.0, 0.01 } }, + { .in = { 1000.0, 9.0, -0.001, 1.0, 0.0001 }, .out = { NAN, 9.0, -0.001 } }, + { .in = { 1000.0, -1.0, 0.01, 1.0, 0.0001 }, .out = { NAN, -1.0, 0.01 } }, + { .in = { 7951733.774369938, -0.9999999997166296, 2.3019958853100635e-08, + 100000000.0, 1.604270854947341e-07 }, + .ret = TSD_ERR_ZERO_DIVISION }, + { .in = { 4.821917030411909e-10, -0.9999995830650517, 6.852235429528821e-10, 0.0, + 1.456098777070529e-12 }, + .ret = TSD_ERR_ZERO_DIVISION }, +}; + +/* Expected values of the reference implementation */ +static const approx_row_t mutation_gamma_projection_rows[] = { + { .in = { 9.0, 0.01, 9.0, 0.01, 1.0, 0.0001 }, + .out = { 1.0, 11.972527662435708, 0.012387600537857034 } }, + { .in = { 9.0, 0.01, 9.0, 0.01, 0.0, 0.0001 }, + .out = { 1.0, 15.051269863867297, 0.016078362999938683 } }, + { .in = { 9.0, 0.01, 9.0, 0.01, 100.0, 0.001 }, + .out = { 1.0, 2.5227474097139964, 0.0006402612043839605 } }, + { .in = { 9.0, 0.01, 9.0, 0.01, 0.0, 0.0 }, + .out = { 1.0, 14.876779871495089, 0.01587677987149509 } }, + { .in = { 9999.0, 10.0, 9999.0, 10.0, 1.0, 0.0001 }, + .out = { 1.0, 12312.171077179419, 12.312556526656158 } }, + { .in = { 9.0, 0.01, -0.99999999, 0.01, 1.0, 0.0001 }, + .out = { 1.0, 1.2000000057917348, 0.004040000006896114 } }, + { .in = { 9.0, 0.01, 9.0, -0.005, 1.0, 0.0001 }, + .out = { 1.0, 17.89710360978777, 0.004963349877067389 } }, + { .in = { 9.0, -0.0001, 9.0, 0.01, 1.0, 0.0001 }, .out = { NAN, NAN, NAN } }, + { .in = { 9.0, 0.01, 9.0, -0.02, 1.0, 0.0001 }, .out = { NAN, NAN, NAN } }, + { .in = { 9.0, 0.01, 9.0, 1000.0, 1.0, 0.0001 }, + .out = { 1.0, 1.1898136314398267, 0.004022546170574629 } }, + { .in = { 1210672665.2995348, 852947.3207951145, 7951732.774369938, + 595712303.1396025, -1.5, 2.8337046167584198e-14 }, + .ret = TSD_ERR_INVALID_HYPERGEO }, + { .in = { 1582170.4459529708, 300601562.7452449, -0.9998696495109705, + -1852940.2349876668, -1.0, 38.337696337086264 }, + .ret = TSD_ERR_ZERO_DIVISION }, + { .in = { 5410.613776267856, 5038406234.100642, -0.9999999957569436, + 0.042821205396860865, -1.0, 1163.787749187542 }, + .ret = TSD_ERR_INVALID_HYPERGEO }, + { .in = { 634745701.2698317, 329.06825010605945, -0.961069957123721, + 1.3003726540202816, -0.5, 871.1707853483364 }, + .ret = TSD_ERR_INVALID_HYPERGEO }, + { .in = { 14400.04443044055, 18400282.490663443, -0.9999999992865775, + 0.005953404256099466, -1.0, 3.5941767717509845e-12 }, + .ret = TSD_ERR_ZERO_DIVISION }, +}; + +/* Expected values of the reference implementation */ +static const approx_row_t mutation_leafward_projection_rows[] = { + { .in = { 1000.0, 9.0, 0.01, 1.0, 0.0001 }, + .out = { 1.0, 41.23788621654923, 0.05057834547335923 } }, + { .in = { 1000.0, 9.0, 0.01, 0.0, 0.0001 }, + .out = { 1.0, 65.33060936244428, 0.074636409566046 } }, + { .in = { 1e-10, 9.0, 0.01, 1.0, 0.0001 }, + .out = { 1.0, 142.00000000008887, 1560000000000.9734 } }, + { .in = { 1000.0, 9.0, 0.01, 1.0, 100000.0 }, + .out = { 1.0, 4843.160085333926, 4.845401916227049 } }, + { .in = { 1000.0, 99999999.0, 100000.0, 1.0, 0.0001 }, .out = { NAN, NAN, NAN } }, + { .in = { 1000.0, 9.0, -0.001, 1.0, 0.0001 }, + .out = { 1.0, 161.91196048162053, 0.17664647560328842 } }, + { .in = { 0.0, 9.0, 0.01, 1.0, 0.0001 }, .ret = TSD_ERR_INVALID_FIXED_AGE }, + { .in = { INFINITY, 9.0, 0.01, 1.0, 0.0001 }, .out = { NAN, NAN, NAN } }, + { .in = { 1000.0, -2.0, 0.01, 1.0, 0.0001 }, .out = { NAN, NAN, NAN } }, + { .in = { 1000.0, 9.0, 0.01, -1.0, 0.0001 }, .ret = TSD_ERR_INVALID_HYPERGEO }, + { .in = { 330585155.6728075, -0.9999998239051365, -25365.04126587679, -1.0, + 7.750515488516166e-07 }, + .ret = TSD_ERR_INVALID_HYPERGEO }, +}; + +/* Expected values of the reference implementation */ +static const approx_row_t mutation_rootward_projection_rows[] = { + { .in = { 1000.0, 9.0, 0.01, 1.0, 0.0001 }, + .out = { 1.0, 34.81517584330332, 0.0291723565789877 } }, + { .in = { 0.0, 9.0, 0.01, 1.0, 0.0001 }, + .out = { 1.0, 1.2000000000000002, 0.00404 } }, + { .in = { 10000000000.0, 9.0, 0.01, 1.0, 0.0001 }, .out = { NAN, NAN, NAN } }, + { .in = { 1000.0, 9.0, 0.01, 1.0, 100000.0 }, .out = { NAN, NAN, NAN } }, + { .in = { 1000.0, -0.999, 1e-05, 1.0, 0.0001 }, + .out = { 1.0, 0.01358788152324153, 0.00016252432539224022 } }, + { .in = { 1000.0, 9.0, 0.01, -0.5, 0.0001 }, + .out = { 1.0, 100.34617434659063, 0.0954561376621056 } }, + { .in = { -1.0, 9.0, 0.01, 1.0, 0.0001 }, .ret = TSD_ERR_INVALID_FIXED_AGE }, + { .in = { 1000.0, 9.0, -0.0001, 1.0, 0.0001 }, .out = { NAN, NAN, NAN } }, + { .in = { 1000.0, -1.0, 0.01, 1.0, 0.0001 }, .out = { NAN, NAN, NAN } }, + { .in = { 8.45730940350531e-08, 17123190.868610334, 2.9302830155736855e-05, + 100000000.0, 7.326444260535366e-08 }, + .ret = TSD_ERR_ZERO_DIVISION }, +}; + +/* Expected values of the reference implementation */ +static const approx_row_t mutation_edge_projection_rows[] = { + { .in = { 3.0, 1.0 }, .out = { 1.0, 11.0, 6.0 } }, + { .in = { 1.0, 3.0 }, .out = { 1.0, 11.0, 6.0 } }, + { .in = { 1.0, 1.0 }, .out = { NAN, NAN, NAN } }, + { .in = { 0.0, 0.0 }, .out = { NAN, NAN, NAN } }, + { .in = { -1.0, 1.0 }, .out = { NAN, NAN, NAN } }, + { .in = { 1e+300, 1.0 }, .out = { NAN, NAN, NAN } }, + { .in = { 1e-200, 1e-210 }, .out = { NAN, NAN, NAN } }, + { .in = { 1.0, 0.9999999999999999 }, + .out = { 1.0, 9.735556609752802e+32, 9.735556609752802e+32 } }, + { .in = { NAN, 1.0 }, .out = { NAN, NAN, NAN } }, + { .in = { INFINITY, INFINITY }, .out = { NAN, NAN, NAN } }, +}; + +/* Expected values of the reference implementation */ +static const approx_row_t mutation_unphased_projection_rows[] = { + { .in = { 9.0, 0.01, 9.0, 0.01, 1.0, 0.0001 }, + .out = { 0.5, 1.2000000000000002, 0.00404 } }, + { .in = { 9.0, 0.01, 9.0, 0.01, 0.0, 0.0001 }, + .out = { 0.5, 1.1841155234657053, 0.004211371841155237 } }, + { .in = { 9.0, 0.01, 9.0, 0.01, 0.0, 0.0 }, + .out = { 0.5, 1.1841155234657048, 0.004169675090252709 } }, + { .in = { 9.0, 0.01, 9.0, 1000000000.0, 1.0, 0.0001 }, .out = { NAN, NAN, NAN } }, + { .in = { 9.0, 0.01, 9.0, 1000.0, 1.0, 0.0001 }, + .out = { 0.9994316225667118, 1.19600362119112, 0.004034954572191996 } }, + { .in = { 1288.8261024396659, 2.1161296052067344, -0.8444713520868427, + 0.0007984796762152916, 1.0, 4.811169071413665e-07 }, + .out = { NAN, NAN, NAN } }, + { .in = { 9.0, -0.001, 9.0, 0.01, 1.0, 0.0001 }, .out = { NAN, NAN, NAN } }, + { .in = { 9.0, 0.01, -1.0, 0.01, 1.0, 0.0001 }, .out = { NAN, NAN, NAN } }, + { .in = { -0.9999999982339964, 670.7541722816065, 71.24709050049042, + 1.592021596132961e-05, 100000000.0, 627.5241160659726 }, + .ret = TSD_ERR_INVALID_HYPERGEO }, + { .in = { -0.9999978569377382, 116952.43478981475, -0.9999996606587622, + 9526762.492287748, 100000000.0, 1.1701319088974114 }, + .ret = TSD_ERR_INVALID_HYPERGEO }, + { .in = { -0.9685259118501613, -3.572097767193457e-06, -0.9999303160226375, + 0.0003977607105897399, 100000000.0, 0.00014045130994169163 }, + .ret = TSD_ERR_INVALID_HYPERGEO }, + { .in = { -0.1642181598383643, 1.3209477340917621e-09, -0.997659538296047, + 0.00025633858557600413, 100000000.0, 0.0006572496535582051 }, + .ret = TSD_ERR_INVALID_HYPERGEO }, + { .in = { -0.9999151249075162, 993617.5506944145, 44356375.30250234, + 12.330141147550119, 100000000.0, 1.5394974045964461e-09 }, + .ret = TSD_ERR_INVALID_HYPERGEO }, + { .in = { -0.9999991588071555, 5.338254701078075e-06, 7363270780.288286, + -0.012693009987637643, 2.0, 2.6034067423152516 }, + .ret = TSD_ERR_INVALID_HYPERGEO }, +}; + +/* Expected values of the reference implementation */ +static const approx_row_t mutation_twin_projection_rows[] = { + { .in = { 9.0, 0.01, 1.0, 0.0001 }, + .out = { 0.5, 1.1999999999999997, 0.004079999999999999 } }, + { .in = { 9.0, 0.01, 0.0, 0.0001 }, + .out = { 0.5, 1.1428571428571437, 0.004371428571428573 } }, + { .in = { -0.999, 1e-05, 1.0, 0.0001 }, + .out = { 0.5, -0.39952009598080396, 0.0002519496100779844 } }, + { .in = { 9.0, -0.001, 1.0, 0.0001 }, .out = { NAN, NAN, NAN } }, + { .in = { -2.0, 0.01, 0.0, 0.0001 }, .out = { NAN, NAN, NAN } }, + { .in = { 9.0, -0.0002, 1.0, 0.0001 }, .ret = TSD_ERR_ZERO_DIVISION }, + { .in = { 9.0, 1e-300, 1.0, 0.0 }, .ret = TSD_ERR_ZERO_DIVISION }, + { .in = { NAN, 0.01, 1.0, 0.0001 }, .out = { NAN, NAN, NAN } }, + { .in = { 9.0, 0.01, 1e+300, 0.0001 }, .out = { NAN, NAN, NAN } }, + { .in = { 9.0, 0.01, 1.0, 1e+300 }, .out = { NAN, NAN, NAN } }, +}; + +/* Expected values of the reference implementation */ +static const approx_row_t mutation_sideways_projection_rows[] = { + { .in = { 1000.0, 9.0, 0.01, 1.0, 0.0001 }, + .out = { 0.5023091569426977, 1.4914783301279306, 0.0047713533926081126 } }, + { .in = { 1000.0, 9.0, 0.01, 0.0, 0.0001 }, + .out = { 0.5144541526611798, 1.5218770077081731, 0.004948242011349156 } }, + { .in = { 1e-10, 9.0, 0.01, 1.0, 0.0001 }, + .out = { 0.0007564619471360778, 1.1946390166820953, 0.004033219044763566 } }, + { .in = { 0.0, 9.0, 0.01, 1.0, 0.0001 }, .ret = TSD_ERR_INVALID_FIXED_AGE }, + { .in = { INFINITY, 9.0, 0.01, 1.0, 0.0001 }, .out = { NAN, NAN, NAN } }, + { .in = { 1000.0, 9.0, -0.0001, 1.0, 0.0001 }, .out = { NAN, NAN, NAN } }, + { .in = { 1000.0, -1.0, 0.01, 1.0, 0.0001 }, .out = { NAN, NAN, NAN } }, + { .in = { 1000.0, 9.0, 0.01, -0.5, 0.0001 }, .ret = TSD_ERR_INVALID_HYPERGEO }, + { .in = { 7951733.774369938, -0.9999999997166296, 2.3019958853100635e-08, + 100000000.0, 1.604270854947341e-07 }, + .ret = TSD_ERR_ZERO_DIVISION }, + { .in = { 3439589.3148461175, 51334025.94161953, -8.147893520675203e-06, -0.5, + 23.460646619971012 }, + .ret = TSD_ERR_INVALID_HYPERGEO }, + { .in = { 17.77466115825119, -0.9999991149306618, 1.2068705882784672e-08, 0.0, + 7.490387184896008e-07 }, + .out = { 0.9999721035237816, -0.9998224001070971, 1.8801875677074958e-05 } }, + { .in = { 3.785982048609923e-06, 7.363428340996249, 0.0001149777112112498, 10000.0, + 9.903472470733758e-13 }, + .ret = TSD_ERR_ZERO_DIVISION }, +}; + +/* Expected values of the reference implementation */ +static const approx_row_t mutation_block_projection_rows[] = { + { .in = { 3.0, 1.0 }, .out = { 0.75, 1.0270270270270268, 1.6216216216216213 } }, + { .in = { 1.0, 3.0 }, .out = { 0.25, 1.0270270270270268, 1.6216216216216213 } }, + { .in = { 1.0, 1.0 }, .out = { 0.5, 2.000000000000001, 6.000000000000002 } }, + { .in = { 1e-160, 1e-170 }, + .out = { 0.9999999999, 1.9940828402366866, 5.988232345771314e+160 } }, + { .in = { 1e+300, 1.0 }, .out = { NAN, NAN, NAN } }, + { .in = { INFINITY, 1.0 }, .out = { NAN, NAN, NAN } }, + { .in = { 0.0, 1.0 }, .ret = TSD_ERR_INVALID_FIXED_AGE }, + { .in = { 1.0, 0.0 }, .ret = TSD_ERR_INVALID_FIXED_AGE }, + { .in = { -1.0, 1.0 }, .ret = TSD_ERR_INVALID_FIXED_AGE }, + { .in = { NAN, 1.0 }, .ret = TSD_ERR_INVALID_FIXED_AGE }, +}; + +/* Moments with exact hypergeometric functions (mpmath) */ +static const approx_row_t moments_reference_rows[] = { + { .in = { 2.0, 0.0005, 1.5, 0.005, 0.0, 0.001 }, + .out = { 21.031253635355096, 1465.2981427174977, 867475.244355388, + 325.5131964809384, 65995.30447794562 } }, + { .in = { 2.0, 0.0005, 1.5, 0.005, 1.0, 0.001 }, + .out = { 28.069848515296044, 2190.3945111492285, 1346202.2405353924, + 303.6020583190394, 59860.71923480909 } }, + { .in = { 2.0, 0.0005, 1.5, 0.005, 2.0, 0.001 }, + .out = { 35.61248206671415, 2881.212121212121, 1802822.4058769522, + 294.5454545454545, 57044.62809917363 } }, + { .in = { 2.0, 0.0005, 1.5, 0.005, 3.0, 0.001 }, + .out = { 43.470607391223304, 3561.0746641674477, 2253426.739788929, + 289.5970009372071, 55436.63575142145 } }, +}; + +/* Moments with exact hypergeometric functions (mpmath) */ +static const approx_row_t rootward_moments_reference_rows[] = { + { .in = { 0.0, 2.0, 0.0005, 0.0, 0.001 }, + .out = { 13.004580341747944, 1333.3333333333333, 888888.8888888889 } }, + { .in = { 300.0, 2.0, 0.0005, 0.0, 0.001 }, + .out = { 13.226143898180428, 1426.4367816091954, 846082.7057735494 } }, + { .in = { 0.0, 2.0, 0.0005, 1.0, 0.001 }, + .out = { 20.20001769318186, 2000.0, 1333333.3333333333 } }, + { .in = { 300.0, 2.0, 0.0005, 1.0, 0.001 }, + .out = { 20.252958537178554, 2177.551020408163, 1318339.5807302524 } }, + { .in = { 0.0, 2.0, 0.0005, 2.0, 0.001 }, + .out = { 27.800920152723943, 2666.6666666666665, 1777777.7777777778 } }, + { .in = { 300.0, 2.0, 0.0005, 2.0, 0.001 }, + .out = { 27.7906820950991, 2879.7101449275365, 1770216.3411048136 } }, + { .in = { 0.0, 2.0, 0.0005, 3.0, 0.001 }, + .out = { 35.689504684717804, 3333.3333333333335, 2222222.222222222 } }, + { .in = { 300.0, 2.0, 0.0005, 3.0, 0.001 }, + .out = { 35.64611441977607, 3565.9176029962564, 2217677.341525332 } }, +}; + +/* Moments with exact hypergeometric functions (mpmath) */ +static const approx_row_t leafward_moments_reference_rows[] = { + { .in = { 4000.0, 1.5, 0.005, 0.0, 0.001 }, + .out = { 4.161408615811342, 374.9979682813893, 93742.12708625503 } }, + { .in = { 4000.0, 1.5, 0.005, 1.0, 0.001 }, + .out = { 12.357018743574061, 349.13808564794067, 80150.76468380277 } }, + { .in = { 4000.0, 1.5, 0.005, 2.0, 0.001 }, + .out = { 20.55973730319209, 327.1841562569884, 69769.3287114679 } }, + { .in = { 4000.0, 1.5, 0.005, 3.0, 0.001 }, + .out = { 28.7684512099228, 308.1880149638367, 61530.72786327265 } }, +}; + +/* Moments with exact hypergeometric functions (mpmath) */ +static const approx_row_t unphased_moments_reference_rows[] = { + { .in = { 2.0, 0.0005, 1.5, 0.005, 0.0, 0.001 }, + .out = { 20.557791818743823, 1333.333333333334, 888888.8888888899, + 249.99999999999991, 41666.6666666667 } }, + { .in = { 2.0, 0.0005, 1.5, 0.005, 1.0, 0.001 }, + .out = { 27.925079427104397, 1894.7368421052631, 1322253.0009233607, + 276.3157894736842, 49746.07571560478 } }, + { .in = { 2.0, 0.0005, 1.5, 0.005, 2.0, 0.001 }, + .out = { 35.60804683970079, 2496.969696969697, 1775916.7431894708, + 292.4242424242424, 55691.766146311726 } }, + { .in = { 2.0, 0.0005, 1.5, 0.005, 3.0, 0.001 }, + .out = { 43.54162646489553, 3123.6646749954734, 2233786.6546523217, + 302.4171645844649, 59861.8318883694 } }, +}; + +/* Moments with exact hypergeometric functions (mpmath) */ +static const approx_row_t twin_moments_reference_rows[] = { + { .in = { 2.0, 0.0005, 0.0, 0.001 }, + .out = { 11.982929094215963, 800.0, 320000.0 } }, + { .in = { 2.0, 0.0005, 1.0, 0.001 }, + .out = { 19.360688002443837, 1200.0, 480000.0 } }, + { .in = { 2.0, 0.0005, 2.0, 0.001 }, + .out = { 27.143912018779872, 1600.0, 640000.0 } }, + { .in = { 2.0, 0.0005, 3.0, 0.001 }, + .out = { 35.21481810756769, 2000.0, 800000.0 } }, +}; + +/* Moments with exact hypergeometric functions (mpmath) */ +static const approx_row_t sideways_moments_reference_rows[] = { + { .in = { 4000.0, 1.5, 0.005, 0.0, 0.001 }, + .out = { 3.5532114769958763, 250.00000000000006, 41666.6666666666 } }, + { .in = { 4000.0, 1.5, 0.005, 1.0, 0.001 }, + .out = { 11.907885738914343, 259.80392156862735, 44838.52364475213 } }, + { .in = { 4000.0, 1.5, 0.005, 2.0, 0.001 }, + .out = { 20.26486414931765, 270.32988108937496, 48349.64184973649 } }, + { .in = { 4000.0, 1.5, 0.005, 3.0, 0.001 }, + .out = { 28.62431050808071, 281.6521075206035, 52244.75880734118 } }, +}; + +/* Moments with exact hypergeometric functions (mpmath) */ +static const approx_row_t mutation_moments_reference_rows[] = { + { .in = { 2.0, 0.0005, 1.5, 0.005, 0.0, 0.001 }, + .out = { 895.4056695992181, 433089.7662654356 } }, + { .in = { 2.0, 0.0005, 1.5, 0.005, 1.0, 0.001 }, + .out = { 1246.998284734134, 779610.7291236585 } }, + { .in = { 2.0, 0.0005, 1.5, 0.005, 2.0, 0.001 }, + .out = { 1587.8787878787878, 1192274.2577288034 } }, + { .in = { 2.0, 0.0005, 1.5, 0.005, 3.0, 0.001 }, + .out = { 1925.3358325523272, 1676579.5131383222 } }, +}; + +/* Moments with exact hypergeometric functions (mpmath) */ +static const approx_row_t mutation_rootward_moments_reference_rows[] = { + { .in = { 0.0, 2.0, 0.0005, 0.0, 0.001 }, + .out = { 666.6666666666666, 444444.4444444445 } }, + { .in = { 300.0, 2.0, 0.0005, 0.0, 0.001 }, + .out = { 863.2183908045977, 387765.8871713566 } }, + { .in = { 0.0, 2.0, 0.0005, 1.0, 0.001 }, .out = { 1000.0, 777777.7777777778 } }, + { .in = { 300.0, 2.0, 0.0005, 1.0, 0.001 }, + .out = { 1238.7755102040815, 733213.0130963952 } }, + { .in = { 0.0, 2.0, 0.0005, 2.0, 0.001 }, + .out = { 1333.3333333333333, 1185185.1851851852 } }, + { .in = { 300.0, 2.0, 0.0005, 2.0, 0.001 }, + .out = { 1589.8550724637682, 1144647.4830217757 } }, + { .in = { 0.0, 2.0, 0.0005, 3.0, 0.001 }, + .out = { 1666.6666666666667, 1666666.666666667 } }, + { .in = { 300.0, 2.0, 0.0005, 3.0, 0.001 }, + .out = { 1932.9588014981282, 1628077.262971844 } }, +}; + +/* Moments with exact hypergeometric functions (mpmath) */ +static const approx_row_t mutation_leafward_moments_reference_rows[] = { + { .in = { 4000.0, 1.5, 0.005, 0.0, 0.001 }, + .out = { 2187.4989841406946, 1126300.6865257565 } }, + { .in = { 4000.0, 1.5, 0.005, 1.0, 0.001 }, + .out = { 2174.5690428239704, 1137449.6480334653 } }, + { .in = { 4000.0, 1.5, 0.005, 2.0, 0.001 }, + .out = { 2163.592078128494, 1147387.794741298 } }, + { .in = { 4000.0, 1.5, 0.005, 3.0, 0.001 }, + .out = { 2154.094007481918, 1156299.8870258126 } }, +}; + +/* Moments with exact hypergeometric functions (mpmath) */ +static const approx_row_t mutation_unphased_moments_reference_rows[] = { + { .in = { 2.0, 0.0005, 1.5, 0.005, 0.0, 0.001 }, + .out = { 0.8007688806687693, 613.2908705909567, 436374.30804978625 } }, + { .in = { 2.0, 0.0005, 1.5, 0.005, 1.0, 0.001 }, + .out = { 0.8421052631578948, 875.0000000000001, 744243.4210526317 } }, + { .in = { 2.0, 0.0005, 1.5, 0.005, 2.0, 0.001 }, + .out = { 0.8727272727272726, 1160.3535353535353, 1136786.7436996226 } }, + { .in = { 2.0, 0.0005, 1.5, 0.005, 3.0, 0.001 }, + .out = { 0.8951656708310697, 1461.2453980324701, 1609952.4534499124 } }, +}; + +/* Moments with exact hypergeometric functions (mpmath) */ +static const approx_row_t mutation_twin_moments_reference_rows[] = { + { .in = { 2.0, 0.0005, 0.0, 0.001 }, .out = { 0.5, 400.0, 160000.0 } }, + { .in = { 2.0, 0.0005, 1.0, 0.001 }, .out = { 0.5, 600.0, 280000.0 } }, + { .in = { 2.0, 0.0005, 2.0, 0.001 }, .out = { 0.5, 800.0, 426666.66666666674 } }, + { .in = { 2.0, 0.0005, 3.0, 0.001 }, .out = { 0.5, 1000.0, 600000.0 } }, +}; + +/* Moments with exact hypergeometric functions (mpmath) */ +static const approx_row_t mutation_sideways_moments_reference_rows[] = { + { .in = { 4000.0, 1.5, 0.005, 0.0, 0.001 }, + .out = { 0.9432066834365437, 1897.8267337461748, 1432975.9109005476 } }, + { .in = { 4000.0, 1.5, 0.005, 1.0, 0.001 }, + .out = { 0.9411764705882353, 1894.6078431372548, 1434834.7590670255 } }, + { .in = { 4000.0, 1.5, 0.005, 2.0, 0.001 }, + .out = { 0.9390103567318757, 1891.2063674721903, 1436707.9296666533 } }, + { .in = { 4000.0, 1.5, 0.005, 3.0, 0.001 }, + .out = { 0.9366957849587928, 1887.609193595473, 1438586.278385757 } }, +}; + +/* Moments with exact hypergeometric functions (mpmath) */ +static const approx_row_t mutation_edge_moments_reference_rows[] = { + { .in = { 4000.0, 300.0 }, .out = { 2150.0, 1140833.3333333333 } }, +}; + +/* Moments with exact hypergeometric functions (mpmath) */ +static const approx_row_t mutation_block_moments_reference_rows[] = { + { .in = { 4000.0, 300.0 }, + .out = { 0.9302325581395349, 1870.9302325581393, 1462953.3982332796 } }, +}; + +/* E[x] and E[log x] of gammas, to be matched by the fitted gamma */ +static const approx_row_t gamma_kl_reference_rows[] = { + { .in = { 4000.0, 8.023686794640554 } }, + { .in = { 300.0, 5.334807340526621 } }, +}; + +/* Means and variances, to be matched by the fitted gamma */ +static const approx_row_t gamma_mom_reference_rows[] = { + { .in = { 1468.0830957704875, 872665.4081509365 } }, + { .in = { 324.4688390860673, 66202.99256425913 } }, + { .in = { 2191.550649932301, 1347335.0097574154 } }, + { .in = { 303.16850627538713, 59803.23888483012 } }, + { .in = { 2881.7094765803945, 1803178.2179688085 } }, + { .in = { 294.35894628235206, 57001.41004303977 } }, + { .in = { 3561.3208124108723, 2253566.347481519 } }, + { .in = { 289.5046953459227, 55410.11528755033 } }, +}; + +static void +test_approximate_log_moments(void) +{ + check_rows(eval_log_moments, log_moments_rows, NUM_ROWS(log_moments_rows), 3); +} + +static void +test_approximate_gamma_kl(void) +{ + size_t j; + int ret; + double x, logx, shape, rate, dg; + double out[2]; + + check_rows(eval_gamma_kl, gamma_kl_rows, NUM_ROWS(gamma_kl_rows), 2); + for (j = 0; j < NUM_ROWS(gamma_kl_reference_rows); j++) { + x = gamma_kl_reference_rows[j].in[0]; + logx = gamma_kl_reference_rows[j].in[1]; + ret = tsd_approximate_gamma_kl(x, logx, out); + CU_ASSERT_EQUAL_FATAL(ret, 0); + shape = out[0] + 1; + rate = out[1]; + ret = tsd_digamma(shape, &dg); + CU_ASSERT_EQUAL_FATAL(ret, 0); + assert_close_tol(shape / rate, x, 1e-5, 1e-8); + assert_close_tol(dg - log(rate), logx, 1e-5, 1e-8); + } +} + +static void +test_approximate_gamma_mom(void) +{ + size_t j; + int ret; + double mean, variance, shape, rate; + double out[2]; + + check_rows(eval_gamma_mom, gamma_mom_rows, NUM_ROWS(gamma_mom_rows), 2); + for (j = 0; j < NUM_ROWS(gamma_mom_reference_rows); j++) { + mean = gamma_mom_reference_rows[j].in[0]; + variance = gamma_mom_reference_rows[j].in[1]; + ret = tsd_approximate_gamma_mom(mean, variance, out); + CU_ASSERT_EQUAL_FATAL(ret, 0); + shape = out[0] + 1; + rate = out[1]; + assert_close_tol(shape / rate, mean, 1e-5, 1e-8); + assert_close_tol(shape / (rate * rate), variance, 1e-5, 1e-8); + } +} + +static void +test_approximate_gamma_iqr(void) +{ + check_rows(eval_gamma_iqr, gamma_iqr_rows, NUM_ROWS(gamma_iqr_rows), 2); +} + +static void +test_valid_moments_and_gamma(void) +{ + check_rows(eval_valid_moments, valid_moments_rows, NUM_ROWS(valid_moments_rows), 1); + check_rows(eval_valid_gamma, valid_gamma_rows, NUM_ROWS(valid_gamma_rows), 1); +} + +static void +test_valid(void) +{ + CU_ASSERT_TRUE(tsd_valid_hyp1f1(1.0, 2.0, 0.5)); + CU_ASSERT_FALSE(tsd_valid_hyp1f1(1.0, NAN, 0.5)); + CU_ASSERT_FALSE(tsd_valid_hyp1f1(2.0, 1.0, 0.5)); + CU_ASSERT_TRUE(tsd_valid_hyperu(1.0, 2.0, 0.5)); + CU_ASSERT_FALSE(tsd_valid_hyperu(1.0, 2.0, INFINITY)); + CU_ASSERT_FALSE(tsd_valid_hyperu(1.0, 2.0, 0.0)); + CU_ASSERT_FALSE(tsd_valid_hyperu(1.0, 1.0, 0.5)); + CU_ASSERT_TRUE(tsd_valid_hyp2f1(1.0, 2.0, 3.0, 0.5)); + CU_ASSERT_FALSE(tsd_valid_hyp2f1(1.0, 2.0, NAN, 0.5)); + CU_ASSERT_FALSE(tsd_valid_hyp2f1(1.0, 2.0, 3.0, NAN)); + CU_ASSERT_FALSE(tsd_valid_hyp2f1(1.0, 2.0, 3.0, 1.0)); + CU_ASSERT_FALSE(tsd_valid_hyp2f1(1.0, 2.0, 3.0, -1e16)); + CU_ASSERT_FALSE(tsd_valid_hyp2f1(0.0, 2.0, 3.0, 0.5)); +} + +static void +test_node_moments(void) +{ + check_rows(eval_moments, moments_rows, NUM_ROWS(moments_rows), 5); + check_rows(eval_unphased_moments, unphased_moments_rows, + NUM_ROWS(unphased_moments_rows), 5); + check_rows(eval_rootward_moments, rootward_moments_rows, + NUM_ROWS(rootward_moments_rows), 3); + check_rows(eval_leafward_moments, leafward_moments_rows, + NUM_ROWS(leafward_moments_rows), 3); + check_rows(eval_sideways_moments, sideways_moments_rows, + NUM_ROWS(sideways_moments_rows), 3); + check_rows(eval_twin_moments, twin_moments_rows, NUM_ROWS(twin_moments_rows), 3); +} + +/* The Laplace approximations against exact moments, with the tolerances of each. */ +static void +test_node_moments_reference(void) +{ + const unsigned int sd_two_node = (1u << 2) | (1u << 4); + const unsigned int sd_one_node = 1u << 2; + + check_reference_rows(eval_moments, moments_reference_rows, + NUM_ROWS(moments_reference_rows), 5, sd_two_node, 1e-2); + check_reference_rows(eval_rootward_moments, rootward_moments_reference_rows, + NUM_ROWS(rootward_moments_reference_rows), 3, sd_one_node, 2e-2); + check_reference_rows(eval_leafward_moments, leafward_moments_reference_rows, + NUM_ROWS(leafward_moments_reference_rows), 3, sd_one_node, 1e-2); + check_reference_rows(eval_unphased_moments, unphased_moments_reference_rows, + NUM_ROWS(unphased_moments_reference_rows), 5, sd_two_node, 1e-2); + check_reference_rows(eval_twin_moments, twin_moments_reference_rows, + NUM_ROWS(twin_moments_reference_rows), 3, sd_one_node, 1e-5); + check_reference_rows(eval_sideways_moments, sideways_moments_reference_rows, + NUM_ROWS(sideways_moments_reference_rows), 3, sd_one_node, 1e-2); +} + +static void +test_node_projections(void) +{ + check_rows(eval_gamma_projection, gamma_projection_rows, + NUM_ROWS(gamma_projection_rows), 5); + check_rows(eval_leafward_projection, leafward_projection_rows, + NUM_ROWS(leafward_projection_rows), 3); + check_rows(eval_rootward_projection, rootward_projection_rows, + NUM_ROWS(rootward_projection_rows), 3); + check_rows(eval_unphased_projection, unphased_projection_rows, + NUM_ROWS(unphased_projection_rows), 5); + check_rows( + eval_twin_projection, twin_projection_rows, NUM_ROWS(twin_projection_rows), 3); + check_rows(eval_sideways_projection, sideways_projection_rows, + NUM_ROWS(sideways_projection_rows), 3); +} + +static void +test_mutation_moments(void) +{ + check_rows(eval_mutation_moments, mutation_moments_rows, + NUM_ROWS(mutation_moments_rows), 2); + check_rows(eval_mutation_rootward_moments, mutation_rootward_moments_rows, + NUM_ROWS(mutation_rootward_moments_rows), 2); + check_rows(eval_mutation_leafward_moments, mutation_leafward_moments_rows, + NUM_ROWS(mutation_leafward_moments_rows), 2); + check_rows(eval_mutation_unphased_moments, mutation_unphased_moments_rows, + NUM_ROWS(mutation_unphased_moments_rows), 3); + check_rows(eval_mutation_twin_moments, mutation_twin_moments_rows, + NUM_ROWS(mutation_twin_moments_rows), 3); + check_rows(eval_mutation_sideways_moments, mutation_sideways_moments_rows, + NUM_ROWS(mutation_sideways_moments_rows), 3); + check_rows(eval_mutation_edge_moments, mutation_edge_moments_rows, + NUM_ROWS(mutation_edge_moments_rows), 2); + check_rows(eval_mutation_block_moments, mutation_block_moments_rows, + NUM_ROWS(mutation_block_moments_rows), 3); +} + +/* The Laplace approximations against exact moments, with the tolerances of each. */ +static void +test_mutation_moments_reference(void) +{ + check_reference_rows(eval_mutation_moments, mutation_moments_reference_rows, + NUM_ROWS(mutation_moments_reference_rows), 2, 1u << 1, 2e-2); + check_reference_rows(eval_mutation_rootward_moments, + mutation_rootward_moments_reference_rows, + NUM_ROWS(mutation_rootward_moments_reference_rows), 2, 1u << 1, 1e-2); + check_reference_rows(eval_mutation_leafward_moments, + mutation_leafward_moments_reference_rows, + NUM_ROWS(mutation_leafward_moments_reference_rows), 2, 1u << 1, 1e-2); + check_reference_rows(eval_mutation_unphased_moments, + mutation_unphased_moments_reference_rows, + NUM_ROWS(mutation_unphased_moments_reference_rows), 3, 1u << 2, 1e-2); + check_reference_rows(eval_mutation_twin_moments, + mutation_twin_moments_reference_rows, + NUM_ROWS(mutation_twin_moments_reference_rows), 3, 1u << 2, 1e-5); + check_reference_rows(eval_mutation_sideways_moments, + mutation_sideways_moments_reference_rows, + NUM_ROWS(mutation_sideways_moments_reference_rows), 3, 1u << 2, 1e-2); + check_reference_rows(eval_mutation_edge_moments, + mutation_edge_moments_reference_rows, + NUM_ROWS(mutation_edge_moments_reference_rows), 2, 1u << 1, 1e-5); + check_reference_rows(eval_mutation_block_moments, + mutation_block_moments_reference_rows, + NUM_ROWS(mutation_block_moments_reference_rows), 3, 1u << 2, 1e-5); +} + +static void +test_mutation_projections(void) +{ + check_rows(eval_mutation_gamma_projection, mutation_gamma_projection_rows, + NUM_ROWS(mutation_gamma_projection_rows), 3); + check_rows(eval_mutation_leafward_projection, mutation_leafward_projection_rows, + NUM_ROWS(mutation_leafward_projection_rows), 3); + check_rows(eval_mutation_rootward_projection, mutation_rootward_projection_rows, + NUM_ROWS(mutation_rootward_projection_rows), 3); + check_rows(eval_mutation_edge_projection, mutation_edge_projection_rows, + NUM_ROWS(mutation_edge_projection_rows), 3); + check_rows(eval_mutation_unphased_projection, mutation_unphased_projection_rows, + NUM_ROWS(mutation_unphased_projection_rows), 3); + check_rows(eval_mutation_twin_projection, mutation_twin_projection_rows, + NUM_ROWS(mutation_twin_projection_rows), 3); + check_rows(eval_mutation_sideways_projection, mutation_sideways_projection_rows, + NUM_ROWS(mutation_sideways_projection_rows), 3); + check_rows(eval_mutation_block_projection, mutation_block_projection_rows, + NUM_ROWS(mutation_block_projection_rows), 3); +} + +/* Two samples in each of two individuals below a root: 0, 1 | 2, 3 | root 4 */ +static const tsd_id_t phase_nodes_individual[] = { 0, 0, 1, 1, TSD_NULL }; +static const tsd_id_t phase_edges_parent[] = { 4, 4, 4, 4 }; +static const tsd_id_t phase_edges_child[] = { 0, 1, 2, 3 }; +static const double phase_edges_left[] = { 0, 0, 0, 0 }; +static const double phase_edges_right[] = { 10, 10, 10, 10 }; +static const tsd_id_t phase_order[] = { 0, 1, 2, 3 }; + +static void +test_block_singletons(void) +{ + const uint8_t unphased[] = { 1, 1 }; + const tsd_id_t mutations_node[] = { 0, 4, 2 }; + const double mutations_position[] = { 5, 1, 2 }; + const tsd_id_t child_missing[] = { 0, 2, 3, 3 }; + tsd_id_t mutations_block[3]; + tsd_id_t *blocks_edges = NULL; + double *blocks_stats = NULL; + tsd_size_t num_blocks = 0; + int ret; + + ret = tsd_block_singletons(5, 2, 4, 3, unphased, phase_nodes_individual, + mutations_node, mutations_position, phase_edges_child, phase_edges_left, + phase_edges_right, phase_order, phase_order, 10.0, &num_blocks, &blocks_stats, + &blocks_edges, mutations_block); + CU_ASSERT_EQUAL(ret, 0); + CU_ASSERT_EQUAL(num_blocks, 2); + CU_ASSERT_EQUAL(mutations_block[0], 0); + CU_ASSERT_EQUAL(mutations_block[1], TSD_NULL); + CU_ASSERT_EQUAL(mutations_block[2], 1); + CU_ASSERT_EQUAL(blocks_stats[0], 1.0); + CU_ASSERT_EQUAL(blocks_stats[1], 10.0); + tsd_safe_free(blocks_stats); + tsd_safe_free(blocks_edges); + + /* A haplotype edge is missing: the block is never completed */ + ret = tsd_block_singletons(5, 2, 4, 3, unphased, phase_nodes_individual, + mutations_node, mutations_position, child_missing, phase_edges_left, + phase_edges_right, phase_order, phase_order, 10.0, &num_blocks, &blocks_stats, + &blocks_edges, mutations_block); + CU_ASSERT_EQUAL(ret, TSD_ERR_UNPHASED_INDIVIDUAL_EDGES); + CU_ASSERT_PTR_NULL(blocks_stats); + + /* No edges and no individuals */ + ret = tsd_block_singletons(0, 0, 0, 0, unphased, phase_nodes_individual, + mutations_node, mutations_position, phase_edges_child, phase_edges_left, + phase_edges_right, phase_order, phase_order, 10.0, &num_blocks, &blocks_stats, + &blocks_edges, mutations_block); + CU_ASSERT_EQUAL(ret, 0); + CU_ASSERT_EQUAL(num_blocks, 0); + tsd_safe_free(blocks_stats); + tsd_safe_free(blocks_edges); +} + +static void +test_reallocate_unphased(void) +{ + const tsd_id_t blocks_edges[] = { 0, 1 }; + const tsd_id_t mutations_block[] = { 0, TSD_NULL }; + const tsd_id_t mutations_block_bad[] = { 1, 0 }; + const tsd_id_t blocks_edges_bad[] = { 0, 7 }; + const double phase[] = { 0.25, NAN }; + const double phase_bad[] = { 1.5, 0.0 }; + const double phase_nan[] = { NAN, 0.0 }; + const double initial[] = { 1.0, 5.0, 0.0, 5.0 }; + double likelihood[4]; + int ret; + + memcpy(likelihood, initial, sizeof(initial)); + ret = tsd_reallocate_unphased( + 2, 2, 1, phase, mutations_block, blocks_edges, likelihood); + CU_ASSERT_EQUAL(ret, 0); + CU_ASSERT_DOUBLE_EQUAL(likelihood[0], 0.25, 1e-12); + CU_ASSERT_DOUBLE_EQUAL(likelihood[2], 0.75, 1e-12); + memcpy(likelihood, initial, sizeof(initial)); + ret = tsd_reallocate_unphased( + 2, 2, 1, phase_bad, mutations_block, blocks_edges, likelihood); + CU_ASSERT_EQUAL(ret, TSD_ERR_PHASE_OUT_OF_RANGE); + /* The mass of the skipped mutation is not allocated */ + memcpy(likelihood, initial, sizeof(initial)); + ret = tsd_reallocate_unphased( + 2, 2, 1, phase_nan, mutations_block, blocks_edges, likelihood); + CU_ASSERT_EQUAL(ret, TSD_ERR_UNPHASED_LIKELIHOOD_NOT_CONSERVED); + memcpy(likelihood, initial, sizeof(initial)); + ret = tsd_reallocate_unphased( + 2, 2, 1, phase, mutations_block_bad, blocks_edges, likelihood); + CU_ASSERT_EQUAL(ret, TSD_ERR_BLOCK_OUT_OF_BOUNDS); + memcpy(likelihood, initial, sizeof(initial)); + ret = tsd_reallocate_unphased( + 2, 2, 1, phase, mutations_block, blocks_edges_bad, likelihood); + CU_ASSERT_EQUAL(ret, TSD_ERR_BLOCK_OUT_OF_BOUNDS); +} + +static void +test_mutation_frequency(void) +{ + const uint8_t nodes_sample[] = { 1, 1, 0, 0, 0 }; + const tsd_id_t mutations_node[] = { 4, 0 }; + const double mutations_position[] = { 5, 1 }; + int32_t freq[2]; + int ret; + + ret = tsd_mutation_frequency(5, 1, 4, 2, nodes_sample, mutations_node, + mutations_position, phase_edges_parent, phase_edges_child, phase_edges_left, + phase_edges_right, phase_order, phase_order, 10.0, freq); + CU_ASSERT_EQUAL(ret, 0); + CU_ASSERT_EQUAL(freq[0], 2); + CU_ASSERT_EQUAL(freq[1], 1); +} + +static void +test_split_and_relabel(void) +{ + /* Node 1 has edges over [0, 2) and [4, 6): split into node 1 and a copy, 3 */ + const tsd_id_t parent[] = { 2, 2, 2 }; + const tsd_id_t child[] = { 0, 1, 1 }; + const double left[] = { 0, 0, 4 }; + const double right[] = { 6, 2, 6 }; + const uint8_t excluded[] = { 1, 0, 0 }; + const tsd_id_t insert[] = { 0, 1, 2 }; + const tsd_id_t remove[] = { 1, 0, 2 }; + const tsd_id_t mutations_node[] = { 1, 1 }; + const double mutations_position[] = { 1, 5 }; + tsd_id_t new_parent[3], new_child[3], output[2]; + tsd_id_t *nodes_order = NULL; + tsd_size_t num_split = 0; + int ret; + + ret = tsd_split_disjoint_nodes(3, 3, parent, child, left, right, excluded, + new_parent, new_child, &num_split, &nodes_order); + CU_ASSERT_EQUAL(ret, 0); + CU_ASSERT_EQUAL(num_split, 1); + CU_ASSERT_EQUAL(nodes_order[3], 1); + CU_ASSERT_EQUAL(new_child[2], 3); + ret = tsd_relabel_mutations_node(4, 3, 2, mutations_node, mutations_position, + nodes_order, new_parent, new_child, left, right, insert, remove, output); + CU_ASSERT_EQUAL(ret, 0); + CU_ASSERT_EQUAL(output[0], 1); + CU_ASSERT_EQUAL(output[1], 3); + /* A mutation above a node that is not in any tree */ + { + const tsd_id_t absent[] = { 3, 3 }; + + ret = tsd_relabel_mutations_node(4, 3, 2, absent, mutations_position, + nodes_order, new_parent, new_child, left, right, insert, remove, output); + CU_ASSERT_EQUAL(ret, TSD_ERR_MUTATION_NODE_NOT_IN_TREE); + } + /* No edges: the mutations are not reached */ + ret = tsd_relabel_mutations_node(4, 0, 2, mutations_node, mutations_position, + nodes_order, new_parent, new_child, left, right, insert, remove, output); + CU_ASSERT_EQUAL(ret, 0); + CU_ASSERT_EQUAL(output[1], TSD_NULL); + tsd_safe_free(nodes_order); +} + +static void +test_constrain_ages(void) +{ + const double times[] = { 0.0, 1.0, 0.5 }; + const uint8_t fixed[] = { 1, 1, 0 }; + const uint8_t all_fixed[] = { 1, 1, 1 }; + const uint8_t free_nodes[] = { 0, 0, 0 }; + const uint8_t fixed_child[] = { 1, 0, 0 }; + const tsd_id_t parent[] = { 1, 2 }; + const tsd_id_t child[] = { 0, 1 }; + double out[3]; + int ret; + + /* Node 2 is younger than its child, node 1, which is fixed */ + ret = tsd_constrain_ages(3, 2, times, fixed, parent, child, 1e-6, 10, out); + CU_ASSERT_EQUAL(ret, 0); + CU_ASSERT(out[2] > out[1]); + /* Free nodes meet in the middle; a fixed parent or child does not move */ + ret = tsd_constrain_ages(3, 2, times, free_nodes, parent, child, 1e-6, 100, out); + CU_ASSERT_EQUAL(ret, 0); + ret = tsd_constrain_ages(3, 2, times, fixed_child, parent, child, 1e-6, 100, out); + CU_ASSERT_EQUAL(ret, 0); + /* Already consistent */ + ret = tsd_constrain_ages(3, 1, times, fixed, parent, child, 1e-6, 10, out); + CU_ASSERT_EQUAL(ret, 0); + /* Forcing without iterations */ + ret = tsd_constrain_ages(3, 2, times, fixed, parent, child, 1e-6, 0, out); + CU_ASSERT_EQUAL(ret, 0); + { + const double bad[] = { 0.0, 1.0, 0.0 }; + + ret = tsd_constrain_ages(3, 1, bad, all_fixed, child, parent, 1e-6, 10, out); + CU_ASSERT_EQUAL(ret, TSD_ERR_FIXED_NODES_VIOLATE_CONSTRAINT); + } +} + +static void +test_contains_unary_nodes(void) +{ + const uint8_t no_mask[] = { 0, 0, 0, 0, 0 }; + const uint8_t all_mask[] = { 1, 1, 1, 1, 1 }; + const tsd_id_t unary_parent[] = { 4, 3 }; + const double left[] = { 0, 0 }; + const double right[] = { 10, 10 }; + const tsd_id_t order[] = { 0, 1 }; + int contains = -1; + int ret; + + ret = tsd_contains_unary_nodes(5, 4, no_mask, phase_edges_parent, phase_edges_left, + phase_edges_right, phase_order, phase_order, 10.0, &contains); + CU_ASSERT_EQUAL(ret, 0); + CU_ASSERT_EQUAL(contains, 0); + ret = tsd_contains_unary_nodes( + 5, 2, no_mask, unary_parent, left, right, order, order, 10.0, &contains); + CU_ASSERT_EQUAL(ret, 0); + CU_ASSERT_EQUAL(contains, 1); + ret = tsd_contains_unary_nodes( + 5, 2, all_mask, unary_parent, left, right, order, order, 10.0, &contains); + CU_ASSERT_EQUAL(ret, 0); + CU_ASSERT_EQUAL(contains, 0); +} + +static void +test_check_arguments(void) +{ + const tsd_id_t ids[] = { 0, TSD_NULL, 4 }; + const double left_unsorted[] = { 5, 0, 0, 0 }; + const double right_unsorted[] = { 10, 5, 10, 10 }; + const tsd_id_t order_duplicate[] = { 0, 1, 1, 3 }; + const tsd_id_t order_bad[] = { 0, 1, 2, 4 }; + const double left_empty[] = { 0, 0, 0, 10 }; + const double right_long[] = { 10, 10, 10, 11 }; + const double left_nan[] = { 0, 0, 0, NAN }; + + CU_ASSERT_EQUAL(tsd_check_ids(3, ids, 5, 1, TSD_ERR_NODE_OUT_OF_BOUNDS), 0); + CU_ASSERT_EQUAL(tsd_check_ids(3, ids, 5, 0, TSD_ERR_NODE_OUT_OF_BOUNDS), + TSD_ERR_NODE_OUT_OF_BOUNDS); + CU_ASSERT_EQUAL(tsd_check_ids(3, ids, 4, 1, TSD_ERR_EDGE_OUT_OF_BOUNDS), + TSD_ERR_EDGE_OUT_OF_BOUNDS); + CU_ASSERT_EQUAL(tsd_check_edges(5, 4, phase_edges_parent, phase_edges_child), 0); + CU_ASSERT_EQUAL(tsd_check_edges(4, 4, phase_edges_parent, phase_edges_child), + TSD_ERR_NODE_OUT_OF_BOUNDS); + CU_ASSERT_EQUAL(tsd_check_edges(4, 4, phase_edges_child, phase_edges_parent), + TSD_ERR_NODE_OUT_OF_BOUNDS); + CU_ASSERT_EQUAL(tsd_check_edge_sweep(4, phase_edges_left, phase_edges_right, + phase_order, phase_order, 10.0), + 0); + CU_ASSERT_EQUAL(tsd_check_edge_sweep(0, NULL, NULL, NULL, NULL, 10.0), 0); + CU_ASSERT_EQUAL(tsd_check_edge_sweep(4, left_empty, phase_edges_right, phase_order, + phase_order, 10.0), + TSD_ERR_BAD_EDGE_INTERVAL); + CU_ASSERT_EQUAL(tsd_check_edge_sweep( + 4, phase_edges_left, right_long, phase_order, phase_order, 10.0), + TSD_ERR_BAD_EDGE_INTERVAL); + CU_ASSERT_EQUAL(tsd_check_edge_sweep( + 4, left_nan, phase_edges_right, phase_order, phase_order, 10.0), + TSD_ERR_BAD_EDGE_INTERVAL); + CU_ASSERT_EQUAL(tsd_check_edge_sweep(4, phase_edges_left, phase_edges_right, + order_bad, phase_order, 10.0), + TSD_ERR_EDGE_OUT_OF_BOUNDS); + CU_ASSERT_EQUAL(tsd_check_edge_sweep(4, phase_edges_left, phase_edges_right, + phase_order, order_bad, 10.0), + TSD_ERR_EDGE_OUT_OF_BOUNDS); + CU_ASSERT_EQUAL(tsd_check_edge_sweep(4, phase_edges_left, phase_edges_right, + order_duplicate, phase_order, 10.0), + TSD_ERR_BAD_EDGE_INDEXES); + CU_ASSERT_EQUAL(tsd_check_edge_sweep(4, phase_edges_left, phase_edges_right, + phase_order, order_duplicate, 10.0), + TSD_ERR_BAD_EDGE_INDEXES); + CU_ASSERT_EQUAL(tsd_check_edge_sweep(4, left_unsorted, phase_edges_right, + phase_order, phase_order, 10.0), + TSD_ERR_BAD_EDGE_INDEXES); + CU_ASSERT_EQUAL(tsd_check_edge_sweep(4, phase_edges_left, right_unsorted, + phase_order, phase_order, 10.0), + TSD_ERR_BAD_EDGE_INDEXES); +} + +/* + * Each function given an id out of bounds, edges that cannot be swept, or edges that + * form a cycle. The fixture has nodes 0-4 and edges from node 4 to nodes 0-3. + */ +static void +test_bad_tree_arguments(void) +{ + const uint8_t flags[] = { 1, 1, 1, 1, 0 }; + const double times[] = { 0, 0, 0, 0, 1 }; + const double constraints[] = { 0, 1, 0, 1, 0, 1, 0, 1, 0, 1 }; + const double likelihoods[] = { 1, 1, 1, 1, 1, 1, 1, 1 }; + const tsd_id_t identity[] = { 0, 1, 2, 3, 4 }; + const tsd_id_t bad_nodes[] = { 0, 1, 2, 5 }; + const tsd_id_t bad_individuals[] = { 0, 0, 1, 2, TSD_NULL }; + const double right_long[] = { 10, 10, 10, 11 }; + const tsd_id_t cycle_parent[] = { 1, 0 }; + const tsd_id_t cycle_child[] = { 0, 1 }; + const double cycle_left[] = { 0, 0 }; + const double cycle_right[] = { 10, 10 }; + const tsd_id_t mutation_node[] = { 0 }; + const tsd_id_t bad_mutation_node[] = { 5 }; + const double mutation_position[] = { 1 }; + tsd_id_t new_parent[4], new_child[4], output[1], mutations_edge[1], index[5]; + tsd_id_t *nodes_order = NULL; + tsd_id_t *blocks_edges = NULL; + double *blocks_stats = NULL; + double *origin = NULL; + double *adjust = NULL; + double stats[8], out[5]; + int32_t freq[5]; + tsd_size_t num_split, num_blocks, num_breaks; + tsd_epoch_stats_t epochs; + int result; + + /* tsd_split_disjoint_nodes */ + CU_ASSERT_EQUAL( + tsd_split_disjoint_nodes(5, 4, phase_edges_parent, bad_nodes, phase_edges_left, + phase_edges_right, flags, new_parent, new_child, &num_split, &nodes_order), + TSD_ERR_NODE_OUT_OF_BOUNDS); + CU_ASSERT_PTR_NULL(nodes_order); + + /* tsd_relabel_mutations_node */ + CU_ASSERT_EQUAL(tsd_relabel_mutations_node(5, 4, 1, mutation_node, mutation_position, + identity, phase_edges_parent, bad_nodes, phase_edges_left, + phase_edges_right, phase_order, phase_order, output), + TSD_ERR_NODE_OUT_OF_BOUNDS); + CU_ASSERT_EQUAL( + tsd_relabel_mutations_node(5, 4, 1, mutation_node, mutation_position, bad_nodes, + phase_edges_parent, phase_edges_child, phase_edges_left, phase_edges_right, + phase_order, phase_order, output), + TSD_ERR_NODE_OUT_OF_BOUNDS); + CU_ASSERT_EQUAL( + tsd_relabel_mutations_node(5, 4, 1, bad_mutation_node, mutation_position, + identity, phase_edges_parent, phase_edges_child, phase_edges_left, + phase_edges_right, phase_order, phase_order, output), + TSD_ERR_NODE_OUT_OF_BOUNDS); + CU_ASSERT_EQUAL( + tsd_relabel_mutations_node(5, 4, 1, mutation_node, mutation_position, identity, + phase_edges_parent, phase_edges_child, phase_edges_left, phase_edges_right, + bad_nodes, phase_order, output), + TSD_ERR_EDGE_OUT_OF_BOUNDS); + + /* tsd_constrain_ages */ + CU_ASSERT_EQUAL(tsd_constrain_ages( + 5, 4, times, flags, bad_nodes, phase_edges_child, 1e-6, 1, out), + TSD_ERR_NODE_OUT_OF_BOUNDS); + + /* tsd_contains_unary_nodes */ + CU_ASSERT_EQUAL(tsd_contains_unary_nodes(5, 4, flags, bad_nodes, phase_edges_left, + phase_edges_right, phase_order, phase_order, 10.0, &result), + TSD_ERR_NODE_OUT_OF_BOUNDS); + CU_ASSERT_EQUAL( + tsd_contains_unary_nodes(5, 4, flags, phase_edges_parent, phase_edges_left, + right_long, phase_order, phase_order, 10.0, &result), + TSD_ERR_BAD_EDGE_INTERVAL); + + /* tsd_constraints_are_consistent */ + CU_ASSERT_EQUAL(tsd_constraints_are_consistent( + 5, 4, constraints, phase_edges_parent, bad_nodes, &result), + TSD_ERR_NODE_OUT_OF_BOUNDS); + + /* tsd_count_mutations */ + CU_ASSERT_EQUAL( + tsd_count_mutations(5, flags, 1, mutation_node, mutation_position, 4, + phase_edges_parent, bad_nodes, phase_edges_left, phase_edges_right, + phase_order, phase_order, 10.0, 0, stats, mutations_edge), + TSD_ERR_NODE_OUT_OF_BOUNDS); + CU_ASSERT_EQUAL( + tsd_count_mutations(5, flags, 1, bad_mutation_node, mutation_position, 4, + phase_edges_parent, phase_edges_child, phase_edges_left, phase_edges_right, + phase_order, phase_order, 10.0, 0, stats, mutations_edge), + TSD_ERR_NODE_OUT_OF_BOUNDS); + CU_ASSERT_EQUAL( + tsd_count_mutations(5, flags, 1, mutation_node, mutation_position, 4, + phase_edges_parent, phase_edges_child, phase_edges_left, right_long, + phase_order, phase_order, 10.0, 0, stats, mutations_edge), + TSD_ERR_BAD_EDGE_INTERVAL); + CU_ASSERT_EQUAL(tsd_count_mutations(2, flags, 1, mutation_node, mutation_position, 2, + cycle_parent, cycle_child, cycle_left, cycle_right, phase_order, + phase_order, 10.0, 1, stats, mutations_edge), + TSD_ERR_EDGES_FORM_CYCLE); + + /* tsd_mutational_area and tsd_mutational_timescale */ + CU_ASSERT_EQUAL(tsd_mutational_area(5, times, 4, likelihoods, phase_edges_parent, + bad_nodes, &epochs, index), + TSD_ERR_NODE_OUT_OF_BOUNDS); + CU_ASSERT_EQUAL(tsd_mutational_timescale(5, times, 4, likelihoods, + phase_edges_parent, bad_nodes, 1, &num_breaks, &origin, &adjust), + TSD_ERR_NODE_OUT_OF_BOUNDS); + CU_ASSERT_PTR_NULL(origin); + + /* tsd_block_singletons */ + CU_ASSERT_EQUAL(tsd_block_singletons(5, 2, 4, 1, flags, bad_individuals, + mutation_node, mutation_position, phase_edges_child, + phase_edges_left, phase_edges_right, phase_order, phase_order, + 10.0, &num_blocks, &blocks_stats, &blocks_edges, output), + TSD_ERR_INDIVIDUAL_OUT_OF_BOUNDS); + CU_ASSERT_EQUAL(tsd_block_singletons(5, 2, 4, 1, flags, phase_nodes_individual, + mutation_node, mutation_position, bad_nodes, phase_edges_left, + phase_edges_right, phase_order, phase_order, 10.0, &num_blocks, + &blocks_stats, &blocks_edges, output), + TSD_ERR_NODE_OUT_OF_BOUNDS); + CU_ASSERT_EQUAL(tsd_block_singletons(5, 2, 4, 1, flags, phase_nodes_individual, + bad_mutation_node, mutation_position, phase_edges_child, + phase_edges_left, phase_edges_right, phase_order, phase_order, + 10.0, &num_blocks, &blocks_stats, &blocks_edges, output), + TSD_ERR_NODE_OUT_OF_BOUNDS); + CU_ASSERT_EQUAL(tsd_block_singletons(5, 2, 4, 1, flags, phase_nodes_individual, + mutation_node, mutation_position, phase_edges_child, + phase_edges_left, right_long, phase_order, phase_order, 10.0, + &num_blocks, &blocks_stats, &blocks_edges, output), + TSD_ERR_BAD_EDGE_INTERVAL); + CU_ASSERT_PTR_NULL(blocks_stats); + CU_ASSERT_PTR_NULL(blocks_edges); + + /* tsd_mutation_frequency */ + CU_ASSERT_EQUAL( + tsd_mutation_frequency(5, 1, 4, 1, flags, mutation_node, mutation_position, + phase_edges_parent, bad_nodes, phase_edges_left, phase_edges_right, + phase_order, phase_order, 10.0, freq), + TSD_ERR_NODE_OUT_OF_BOUNDS); + CU_ASSERT_EQUAL( + tsd_mutation_frequency(5, 1, 4, 1, flags, bad_mutation_node, mutation_position, + phase_edges_parent, phase_edges_child, phase_edges_left, phase_edges_right, + phase_order, phase_order, 10.0, freq), + TSD_ERR_NODE_OUT_OF_BOUNDS); + CU_ASSERT_EQUAL( + tsd_mutation_frequency(5, 1, 4, 1, flags, mutation_node, mutation_position, + phase_edges_parent, phase_edges_child, phase_edges_left, right_long, + phase_order, phase_order, 10.0, freq), + TSD_ERR_BAD_EDGE_INTERVAL); + CU_ASSERT_EQUAL(tsd_mutation_frequency(2, 1, 2, 1, flags, mutation_node, + mutation_position, cycle_parent, cycle_child, cycle_left, + cycle_right, phase_order, phase_order, 10.0, freq), + TSD_ERR_EDGES_FORM_CYCLE); +} + +/* ---- priors ---- */ + +#define TABLE_MAX_TIPS 20 +#define TABLE_MAX_MARGINAL_TIPS 10 +#define TABLE_MAX_MOMENTS 3 + +typedef struct { + tsd_size_t num_tips; + tsd_size_t num_moments; + double val[TABLE_MAX_MARGINAL_TIPS * TABLE_MAX_MOMENTS]; + double out[(TABLE_MAX_MARGINAL_TIPS + 1) * TABLE_MAX_MOMENTS]; + int ret; +} marginalize_row_t; + +typedef struct { + tsd_size_t num_tips; + double variance[TABLE_MAX_TIPS + 1]; + int ret; +} variance_row_t; + +/* Expected values of the reference implementation */ +static const marginalize_row_t marginalize_rows[] = { + { .num_tips = 2, + .num_moments = 2, + .val = { 1, 2, 3, 4 }, + .out = { 0, 0, 0, 0, 3, 4 }, + .ret = 0 }, + { .num_tips = 3, + .num_moments = 2, + .val = { 6.405920704482398, 2.770888466262316, 0.5056378869683275, + 0.26362359173243805, 8.151375368082697, 9.136280215049444 }, + .out = { 0, 0, 0, 0, 8.151375368082697, 9.136280215049444, 0.5056378869683275, + 0.26362359173243805 }, + .ret = 0 }, + { .num_tips = 6, + .num_moments = 1, + .val = { 6.105694180095081, 7.322015953741584, 5.481887415507686, + 9.357216995498906, 8.176950185803168, 0.12711115168446616 }, + .out = { 0, 0, 4.1943175516834055, 8.11004435562237, 7.419552205503297, + 5.481887415507686, 7.322015953741584 }, + .ret = 0 }, + { .num_tips = 5, + .num_moments = 3, + .val = { 8.588302338216936, 0.43249719552409716, 7.323588919656446, + 1.8389906439653343, 8.645471331263877, 5.4604660804660075, + 3.0671477163201097, 4.284603489856819, 0.3803647443400834, + 1.3304044373456831, 6.73918170546694, 6.507176164585076, 6.192312603664413, + 3.8984077871926464, 9.972378364313188 }, + .out = { 0, 0, 0, 0, 0, 0, 4.421223665034365, 4.789259532941353, + 7.973616342397445, 2.025101748935454, 5.757350419222893, 4.056451596487079, + 3.0671477163201097, 4.284603489856819, 0.3803647443400834, + 1.8389906439653343, 8.645471331263877, 5.4604660804660075 }, + .ret = 0 }, + { .num_tips = 10, + .num_moments = 2, + .val = { 9.810269853884678, 6.886865646358878, 6.5395468350513815, + 6.9156226326523065, 3.9503220973931277, 1.437455399721871, 7.242734567921409, + 5.301007792509686, 3.1713945680336613, 4.909770052434712, 8.905929560055103, + 9.347030807966872, 3.6421724474197954, 5.758145324224633, 3.2865069716518276, + 5.983570298976998, 3.4453211325206197, 3.9770281052287966, 8.913716084847444, + 2.3488601759804593 }, + .out = { 0, 0, 0, 0, 5.623151605758174, 4.568435971625975, 4.799050195244742, + 5.94494257642139, 5.422355848514381, 5.987743974404029, 5.5903751937122115, + 5.348623913661779, 5.40321218005653, 4.413497494215927, 5.163430081689842, + 3.4458516438653746, 4.938045838551611, 2.5965211175582152, + 3.9503220973931277, 1.437455399721871, 6.5395468350513815, + 6.9156226326523065 }, + .ret = 0 }, + { .num_tips = 8, + .num_moments = 2, + .val = { 0, 0, 1.75, 4.21937641723356, 0.75, 0.71937641723356, + 0.41666666666666663, 0.21937641723356005, 0.25, 0.08048752834467121, 0.15, + 0.0304875283446712, 0.08333333333333333, 0.0104875283446712, + 0.03571428571428571, 0.002551020408163265 }, + .out = { 0, 0, 0, 0, 0.125, 0.04243197278911563, 0.25000000000000006, + 0.12064625850340137, 0.3750000000000001, 0.23028911564625854, 0.5, + 0.3681859410430839, 0.625, 0.53187641723356, 0.75, 0.71937641723356, 1.75, + 4.21937641723356 }, + .ret = 0 }, + { .num_tips = 6, + .num_moments = 2, + .val = { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 }, + .out = { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 }, + .ret = 0 }, + { .num_tips = 6, + .num_moments = 2, + .val = { NAN, NAN, NAN, NAN, NAN, NAN, NAN, NAN, NAN, NAN, NAN, NAN }, + .out = { 0, 0, 0, 0, NAN, NAN, NAN, NAN, NAN, NAN, NAN, NAN, NAN, NAN }, + .ret = 0 }, + /* NOTE: non-finite values are propagated by the weighted sum, with no checks */ + { .num_tips = 4, + .num_moments = 2, + .val = { 1, 2, INFINITY, 1, 3, 3, 1, NAN }, + .out = { 0, 0, 0, 0, 1.5, NAN, 3, 3, INFINITY, 1 }, + .ret = 0 }, + { .num_tips = 1, .num_moments = 2, .val = { 1, 2 }, .ret = TSD_ERR_TOO_FEW_TIPS }, +}; + +/* Expected values of the reference implementation */ +static const variance_row_t variance_rows[] = { + /* a single tip has zero variance */ + { .num_tips = 1, .variance = { 0, 0 }, .ret = 0 }, + { .num_tips = 2, .variance = { 0, 0, 1 }, .ret = 0 }, + { .num_tips = 3, + .variance = { 0, 0, 0.1111111111111111, 1.1111111111111112 }, + .ret = 0 }, + { .num_tips = 4, + .variance = { 0, 0, 0.0763888888888889, 0.1388888888888889, 1.1388888888888888 }, + .ret = 0 }, + { .num_tips = 5, + .variance = { 0, 0, 0.05555555555555555, 0.10888888888888887, + 0.14888888888888885, 1.148888888888889 }, + .ret = 0 }, + { .num_tips = 7, + .variance + = { 0, 0, 0.033197278911564626, 0.07034013605442176, 0.10571428571428576, + 0.13519274376417229, 0.15560090702947849, 1.1556009070294788 }, + .ret = 0 }, + { .num_tips = 10, + .variance + = { 0, 0, 0.018567019400352734, 0.041611237087427574, 0.06639581758629377, + 0.09089317208364828, 0.11351221970269593, 0.13295666414714036, + 0.1481418493323255, 0.15814184933232545, 1.158141849332326 }, + .ret = 0 }, + { .num_tips = 15, + .variance = { 0, 0, 0.009275031033272787, 0.021737639649727542, + 0.03624521961185298, 0.051927046202770555, 0.06808446902686013, + 0.0841377367467945, 0.09959413220318991, 0.11402731806494726, + 0.1270631711007999, 0.13836964240727112, 0.1476492516868806, + 0.15463337867100768, 0.15907782311545215, 1.1590778231154522 }, + .ret = 0 }, + { .num_tips = 20, + .variance = { 0, 0, 0.005572819114451828, 0.013375800851143278, + 0.022807509758699017, 0.033400737695193194, 0.04477484272918324, + 0.05660993547639791, 0.068631190860954, 0.08059855293878618, + 0.09229959605553426, 0.10354436416820739, 0.11416151633721722, + 0.12399537093168672, 0.1329035891897501, 0.14075532637585275, + 0.1474297329805997, 0.1528147232340108, 0.15680595130418618, + 0.15930595130418657, 1.1593059513041868 }, + .ret = 0 }, + { .num_tips = 0, .ret = TSD_ERR_TOO_FEW_TIPS }, +}; + +static void +test_marginalize_over_ancestors(void) +{ + const size_t num_rows = sizeof(marginalize_rows) / sizeof(marginalize_rows[0]); + const marginalize_row_t *row; + double out[(TABLE_MAX_MARGINAL_TIPS + 1) * TABLE_MAX_MOMENTS]; + size_t j; + int ret; + + for (j = 0; j < num_rows; j++) { + row = marginalize_rows + j; + ret = tsd_marginalize_over_ancestors( + row->num_tips, row->num_moments, row->val, out); + CU_ASSERT_EQUAL(ret, row->ret); + if (ret == 0 && row->ret == 0) { + assert_array_close(out, row->out, (row->num_tips + 1) * row->num_moments); + } + } +} + +static void +test_conditional_coalescent_variance(void) +{ + const size_t num_rows = sizeof(variance_rows) / sizeof(variance_rows[0]); + const variance_row_t *row; + double variance[TABLE_MAX_TIPS + 1]; + size_t j; + int ret; + + for (j = 0; j < num_rows; j++) { + row = variance_rows + j; + ret = tsd_conditional_coalescent_variance(row->num_tips, variance); + CU_ASSERT_EQUAL(ret, row->ret); + if (ret == 0 && row->ret == 0) { + assert_array_close(variance, row->variance, row->num_tips + 1); + } + } +} + +/* ---- rescaling ---- */ + +#define TABLE_MAX_COUNTS 8 +#define TABLE_MAX_BREAKS 12 +#define TABLE_MAX_NODES 6 +#define TABLE_MAX_EDGES 4 +#define TABLE_MAX_MUTATIONS 5 +#define TABLE_MAX_POINTS 5 +#define TABLE_MAX_POSTERIORS 4 + +typedef struct { + tsd_size_t num_counts; + double counts[TABLE_MAX_COUNTS]; + int64_t epochs; + tsd_size_t num_breaks; + tsd_id_t breaks[TABLE_MAX_BREAKS]; + int ret; +} changepoints_row_t; + +typedef struct { + tsd_size_t num_nodes; + uint8_t is_sample[TABLE_MAX_NODES]; + tsd_size_t num_mutations; + tsd_id_t mutations_node[TABLE_MAX_MUTATIONS]; + double mutations_position[TABLE_MAX_MUTATIONS]; + tsd_size_t num_edges; + tsd_id_t edges_parent[TABLE_MAX_EDGES]; + tsd_id_t edges_child[TABLE_MAX_EDGES]; + double edges_left[TABLE_MAX_EDGES]; + double edges_right[TABLE_MAX_EDGES]; + tsd_id_t indexes_insert[TABLE_MAX_EDGES]; + tsd_id_t indexes_remove[TABLE_MAX_EDGES]; + double sequence_length; + int size_biased; + double edges_stats[TABLE_MAX_EDGES][2]; + tsd_id_t mutations_edge[TABLE_MAX_MUTATIONS]; +} count_mutations_row_t; + +typedef struct { + tsd_size_t num_nodes; + double nodes_time[TABLE_MAX_NODES]; + tsd_size_t num_edges; + double likelihoods[TABLE_MAX_EDGES][2]; + tsd_id_t edges_parent[TABLE_MAX_EDGES]; + tsd_id_t edges_child[TABLE_MAX_EDGES]; + tsd_size_t num_epochs; + double counts[TABLE_MAX_NODES]; + double offset[TABLE_MAX_NODES]; + double duration[TABLE_MAX_NODES]; + tsd_id_t nodes_index[TABLE_MAX_NODES]; +} area_row_t; + +typedef struct { + tsd_size_t num_nodes; + double nodes_time[TABLE_MAX_NODES]; + tsd_size_t num_edges; + double likelihoods[TABLE_MAX_EDGES][2]; + tsd_id_t edges_parent[TABLE_MAX_EDGES]; + tsd_id_t edges_child[TABLE_MAX_EDGES]; + int64_t max_intervals; + tsd_size_t num_breaks; + double origin[TABLE_MAX_NODES]; + double adjust[TABLE_MAX_NODES]; + int ret; +} timescale_row_t; + +typedef struct { + tsd_size_t num_points; + double estimate[TABLE_MAX_POINTS]; + uint8_t fixed[TABLE_MAX_POINTS]; + tsd_size_t num_breaks; + double original[TABLE_MAX_BREAKS]; + double rescaled[TABLE_MAX_BREAKS]; + double out[TABLE_MAX_POINTS]; + int ret; +} point_row_t; + +typedef struct { + tsd_size_t num_posteriors; + double posteriors[TABLE_MAX_POSTERIORS][2]; + uint8_t fixed[TABLE_MAX_POSTERIORS]; + tsd_size_t num_breaks; + double original[TABLE_MAX_BREAKS]; + double rescaled[TABLE_MAX_BREAKS]; + double quantile_width; + double max_shape; + double out[TABLE_MAX_POSTERIORS][2]; + int ret; +} posterior_row_t; + +/* Expected values of the reference implementation */ +static const changepoints_row_t changepoints_rows[] = { + { .num_counts = 3, + .counts = { 1, 2, 3 }, + .epochs = 1, + .num_breaks = 2, + .breaks = { 0, 3 }, + .ret = 0 }, + { .num_counts = 1, + .counts = { 5 }, + .epochs = 1, + .num_breaks = 2, + .breaks = { 0, 1 }, + .ret = 0 }, + { .num_counts = 4, + .counts = { 0, 0, 4, 0 }, + .epochs = 1, + .num_breaks = 2, + .breaks = { 0, 4 }, + .ret = 0 }, + { .num_counts = 3, + .counts = { 1, 2, 3 }, + .epochs = 10, + .num_breaks = 11, + .breaks = { 0, 0, 1, 1, 1, 2, 2, 2, 2, 2, 3 }, + .ret = 0 }, + { .num_counts = 4, + .counts = { 0, 0, 4, 0 }, + .epochs = 4, + .num_breaks = 5, + .breaks = { 0, 2, 2, 2, 4 }, + .ret = 0 }, + { .num_counts = 4, + .counts = { 0, 0, 5, 5 }, + .epochs = 3, + .num_breaks = 4, + .breaks = { 0, 2, 3, 4 }, + .ret = 0 }, + { .num_counts = 4, + .counts = { 5, 5, 0, 0 }, + .epochs = 3, + .num_breaks = 4, + .breaks = { 0, 0, 1, 4 }, + .ret = 0 }, + { .num_counts = 5, + .counts = { 0, 5, 0, 5, 0 }, + .epochs = 3, + .num_breaks = 4, + .breaks = { 0, 1, 3, 5 }, + .ret = 0 }, + { .num_counts = 4, + .counts = { 1, 1, 1, 1 }, + .epochs = 4, + .num_breaks = 5, + .breaks = { 0, 1, 2, 3, 4 }, + .ret = 0 }, + { .num_counts = 4, + .counts = { 1, 1, 1, 1 }, + .epochs = 2, + .num_breaks = 3, + .breaks = { 0, 2, 4 }, + .ret = 0 }, + { .num_counts = 8, + .counts = { 1.0730290263725388, 0.30845314412528435, 5.375436872608127, + 0.36642711289983193, 0.11536203910680366, 1.7997970856557877, + 0.498639097854449, 0.5514213768237073 }, + .epochs = 3, + .num_breaks = 4, + .breaks = { 0, 2, 2, 8 }, + .ret = 0 }, + { .num_counts = 8, + .counts = { 2.073029026372539, 0, 5.375436872608127, 0.36642711289983193, 0, + 1.7997970856557877, 0.498639097854449, 0.5514213768237073 }, + .epochs = 5, + .num_breaks = 6, + .breaks = { 0, 2, 2, 2, 5, 8 }, + .ret = 0 }, + /* NOTE: current behaviour, possibly a bug: with no counts the cumulative + distribution is 0 / 0 = NaN, so every breakpoint but the last is -1 */ + { .num_counts = 3, + .counts = { 0, 0, 0 }, + .epochs = 3, + .num_breaks = 4, + .breaks = { -1, -1, -1, 3 }, + .ret = 0 }, + { .num_counts = 0, + .epochs = 3, + .num_breaks = 4, + .breaks = { -1, -1, -1, 0 }, + .ret = 0 }, + { .num_counts = 2, + .counts = { 1, 2 }, + .epochs = 0, + .ret = TSD_ERR_NONPOSITIVE_INTERVALS }, + { .num_counts = 2, + .counts = { 1, 2 }, + .epochs = -1, + .ret = TSD_ERR_NONPOSITIVE_INTERVALS }, +}; + +static void +test_fixed_changepoints(void) +{ + const size_t num_rows = sizeof(changepoints_rows) / sizeof(changepoints_rows[0]); + const changepoints_row_t *row; + tsd_id_t *breaks = NULL; + tsd_size_t num_breaks, k; + size_t j; + int ret; + + for (j = 0; j < num_rows; j++) { + row = changepoints_rows + j; + ret = tsd_fixed_changepoints( + row->num_counts, row->counts, row->epochs, &breaks, &num_breaks); + CU_ASSERT_EQUAL(ret, row->ret); + if (ret == 0 && row->ret == 0) { + CU_ASSERT_EQUAL_FATAL(num_breaks, row->num_breaks); + for (k = 0; k < num_breaks; k++) { + CU_ASSERT_EQUAL(breaks[k], row->breaks[k]); + } + } + tsd_safe_free(breaks); + breaks = NULL; + } +} + +/* Expected values of the reference implementation */ +static const count_mutations_row_t count_mutations_rows[] = { + /* a mutation above the root has no edge */ + { .num_nodes = 3, + .is_sample = { 1, 1, 0 }, + .num_mutations = 4, + .mutations_node = { 0, 0, 1, 2 }, + .mutations_position = { 1, 2, 3, 5 }, + .num_edges = 2, + .edges_parent = { 2, 2 }, + .edges_child = { 0, 1 }, + .edges_left = { 0, 0 }, + .edges_right = { 10, 10 }, + .indexes_insert = { 0, 1 }, + .indexes_remove = { 1, 0 }, + .sequence_length = 10, + .size_biased = 0, + .edges_stats = { { 2, 10 }, { 1, 10 } }, + .mutations_edge = { 0, 0, 1, -1 } }, + { .num_nodes = 3, + .is_sample = { 1, 1, 0 }, + .num_mutations = 4, + .mutations_node = { 0, 0, 1, 2 }, + .mutations_position = { 1, 2, 3, 5 }, + .num_edges = 2, + .edges_parent = { 2, 2 }, + .edges_child = { 0, 1 }, + .edges_left = { 0, 0 }, + .edges_right = { 10, 10 }, + .indexes_insert = { 0, 1 }, + .indexes_remove = { 1, 0 }, + .sequence_length = 10, + .size_biased = 1, + .edges_stats = { { 2, 10 }, { 1, 10 } }, + .mutations_edge = { 0, 0, 1, -1 } }, + /* no mutations */ + { .num_nodes = 3, + .is_sample = { 1, 1, 0 }, + .num_mutations = 0, + .num_edges = 2, + .edges_parent = { 2, 2 }, + .edges_child = { 0, 1 }, + .edges_left = { 0, 0 }, + .edges_right = { 10, 10 }, + .indexes_insert = { 0, 1 }, + .indexes_remove = { 1, 0 }, + .sequence_length = 10, + .size_biased = 0, + .edges_stats = { { 0, 10 }, { 0, 10 } } }, + /* no edges */ + { .num_nodes = 3, + .is_sample = { 1, 1, 0 }, + .num_mutations = 1, + .mutations_node = { 0 }, + .mutations_position = { 1 }, + .num_edges = 0, + .sequence_length = 10, + .size_biased = 1, + .mutations_edge = { -1 } }, + /* no edges and no mutations */ + { .num_nodes = 3, + .is_sample = { 1, 1, 0 }, + .num_mutations = 0, + .num_edges = 0, + .sequence_length = 10, + .size_biased = 0 }, + /* a mutation beyond the edge */ + { .num_nodes = 2, + .is_sample = { 1, 0 }, + .num_mutations = 2, + .mutations_node = { 0, 0 }, + .mutations_position = { 1, 5 }, + .num_edges = 1, + .edges_parent = { 1 }, + .edges_child = { 0 }, + .edges_left = { 0 }, + .edges_right = { 4 }, + .indexes_insert = { 0 }, + .indexes_remove = { 0 }, + .sequence_length = 10, + .size_biased = 0, + .edges_stats = { { 1, 4 } }, + .mutations_edge = { 0, -1 } }, + { .num_nodes = 2, + .is_sample = { 1, 0 }, + .num_mutations = 2, + .mutations_node = { 0, 0 }, + .mutations_position = { 1, 5 }, + .num_edges = 1, + .edges_parent = { 1 }, + .edges_child = { 0 }, + .edges_left = { 0 }, + .edges_right = { 4 }, + .indexes_insert = { 0 }, + .indexes_remove = { 0 }, + .sequence_length = 10, + .size_biased = 1, + .edges_stats = { { 1, 4 } }, + .mutations_edge = { 0, -1 } }, + /* a mutation in a gap between the edges of a node */ + { .num_nodes = 3, + .is_sample = { 1, 1, 0 }, + .num_mutations = 2, + .mutations_node = { 0, 0 }, + .mutations_position = { 4, 5 }, + .num_edges = 3, + .edges_parent = { 2, 2, 2 }, + .edges_child = { 0, 0, 1 }, + .edges_left = { 0, 6, 0 }, + .edges_right = { 4, 10, 10 }, + .indexes_insert = { 0, 2, 1 }, + .indexes_remove = { 0, 2, 1 }, + .sequence_length = 10, + .size_biased = 0, + .edges_stats = { { 0, 4 }, { 0, 4 }, { 0, 10 } }, + .mutations_edge = { -1, -1 } }, + { .num_nodes = 3, + .is_sample = { 1, 1, 0 }, + .num_mutations = 2, + .mutations_node = { 0, 0 }, + .mutations_position = { 4, 5 }, + .num_edges = 3, + .edges_parent = { 2, 2, 2 }, + .edges_child = { 0, 0, 1 }, + .edges_left = { 0, 6, 0 }, + .edges_right = { 4, 10, 10 }, + .indexes_insert = { 0, 2, 1 }, + .indexes_remove = { 0, 2, 1 }, + .sequence_length = 10, + .size_biased = 1, + .edges_stats = { { 0, 4 }, { 0, 4 }, { 0, 10 } }, + .mutations_edge = { -1, -1 } }, + /* a mutation at a breakpoint belongs to the tree on its right */ + { .num_nodes = 3, + .is_sample = { 1, 1, 0 }, + .num_mutations = 2, + .mutations_node = { 0, 0 }, + .mutations_position = { 4.5, 5 }, + .num_edges = 3, + .edges_parent = { 2, 2, 2 }, + .edges_child = { 0, 0, 1 }, + .edges_left = { 0, 5, 0 }, + .edges_right = { 5, 10, 10 }, + .indexes_insert = { 0, 2, 1 }, + .indexes_remove = { 0, 2, 1 }, + .sequence_length = 10, + .size_biased = 0, + .edges_stats = { { 1, 5 }, { 1, 5 }, { 0, 10 } }, + .mutations_edge = { 0, 1 } }, + { .num_nodes = 3, + .is_sample = { 1, 1, 0 }, + .num_mutations = 2, + .mutations_node = { 0, 0 }, + .mutations_position = { 4.5, 5 }, + .num_edges = 3, + .edges_parent = { 2, 2, 2 }, + .edges_child = { 0, 0, 1 }, + .edges_left = { 0, 5, 0 }, + .edges_right = { 5, 10, 10 }, + .indexes_insert = { 0, 2, 1 }, + .indexes_remove = { 0, 2, 1 }, + .sequence_length = 10, + .size_biased = 1, + .edges_stats = { { 1, 5 }, { 1, 5 }, { 0, 10 } }, + .mutations_edge = { 0, 1 } }, + /* counts weighted by the samples below the edge */ + { .num_nodes = 5, + .is_sample = { 1, 1, 1, 0, 0 }, + .num_mutations = 3, + .mutations_node = { 0, 3, 3 }, + .mutations_position = { 1, 2, 3 }, + .num_edges = 4, + .edges_parent = { 3, 3, 4, 4 }, + .edges_child = { 0, 1, 2, 3 }, + .edges_left = { 0, 0, 0, 0 }, + .edges_right = { 10, 10, 10, 10 }, + .indexes_insert = { 0, 1, 2, 3 }, + .indexes_remove = { 3, 2, 1, 0 }, + .sequence_length = 10, + .size_biased = 0, + .edges_stats = { { 1, 10 }, { 0, 10 }, { 0, 10 }, { 2, 10 } }, + .mutations_edge = { 0, 3, 3 } }, + { .num_nodes = 5, + .is_sample = { 1, 1, 1, 0, 0 }, + .num_mutations = 3, + .mutations_node = { 0, 3, 3 }, + .mutations_position = { 1, 2, 3 }, + .num_edges = 4, + .edges_parent = { 3, 3, 4, 4 }, + .edges_child = { 0, 1, 2, 3 }, + .edges_left = { 0, 0, 0, 0 }, + .edges_right = { 10, 10, 10, 10 }, + .indexes_insert = { 0, 1, 2, 3 }, + .indexes_remove = { 3, 2, 1, 0 }, + .sequence_length = 10, + .size_biased = 1, + .edges_stats = { { 1, 10 }, { 0, 10 }, { 0, 10 }, { 4, 20 } }, + .mutations_edge = { 0, 3, 3 } }, + /* no samples flagged */ + { .num_nodes = 3, + .is_sample = { 0, 0, 0 }, + .num_mutations = 1, + .mutations_node = { 0 }, + .mutations_position = { 1 }, + .num_edges = 2, + .edges_parent = { 2, 2 }, + .edges_child = { 0, 1 }, + .edges_left = { 0, 0 }, + .edges_right = { 10, 10 }, + .indexes_insert = { 0, 1 }, + .indexes_remove = { 1, 0 }, + .sequence_length = 10, + .size_biased = 1, + .edges_stats = { { 0, 0 }, { 0, 0 } }, + .mutations_edge = { 0 } }, + /* mutations not in order of position */ + { .num_nodes = 3, + .is_sample = { 1, 1, 0 }, + .num_mutations = 5, + .mutations_node = { 1, 0, 2, 1, 0 }, + .mutations_position = { 8, 1, 9, 2, 6 }, + .num_edges = 3, + .edges_parent = { 2, 2, 2 }, + .edges_child = { 0, 0, 1 }, + .edges_left = { 0, 5, 0 }, + .edges_right = { 5, 10, 10 }, + .indexes_insert = { 0, 2, 1 }, + .indexes_remove = { 0, 2, 1 }, + .sequence_length = 10, + .size_biased = 0, + .edges_stats = { { 1, 5 }, { 1, 5 }, { 2, 10 } }, + .mutations_edge = { 2, 0, -1, 2, 1 } }, +}; + +static void +test_count_mutations(void) +{ + const size_t num_rows + = sizeof(count_mutations_rows) / sizeof(count_mutations_rows[0]); + const count_mutations_row_t *row; + double stats[2 * TABLE_MAX_EDGES]; + tsd_id_t mutations_edge[TABLE_MAX_MUTATIONS]; + tsd_size_t k; + size_t j; + int ret; + + for (j = 0; j < num_rows; j++) { + row = count_mutations_rows + j; + ret = tsd_count_mutations(row->num_nodes, row->is_sample, row->num_mutations, + row->mutations_node, row->mutations_position, row->num_edges, + row->edges_parent, row->edges_child, row->edges_left, row->edges_right, + row->indexes_insert, row->indexes_remove, row->sequence_length, + row->size_biased, stats, mutations_edge); + CU_ASSERT_EQUAL(ret, 0); + assert_array_close(stats, &row->edges_stats[0][0], 2 * row->num_edges); + for (k = 0; k < row->num_mutations; k++) { + CU_ASSERT_EQUAL(mutations_edge[k], row->mutations_edge[k]); + } + } +} + +/* Expected values of the reference implementation */ +static const area_row_t area_rows[] = { + /* a single epoch */ + { .num_nodes = 3, + .nodes_time = { 0, 0, 1 }, + .num_edges = 2, + .likelihoods = { { 2, 10 }, { 1, 10 } }, + .edges_parent = { 2, 2 }, + .edges_child = { 0, 1 }, + .num_epochs = 1, + .counts = { 3 }, + .offset = { 20 }, + .duration = { 1 }, + .nodes_index = { 0, 0, 1 } }, + /* all nodes at time zero: no epoch, and every edge has zero length */ + { .num_nodes = 3, + .nodes_time = { 0, 0, 0 }, + .num_edges = 2, + .likelihoods = { { 2, 10 }, { 1, 10 } }, + .edges_parent = { 2, 2 }, + .edges_child = { 0, 1 }, + .num_epochs = 0, + .nodes_index = { 0, 0, 0 } }, + /* no edges */ + { .num_nodes = 2, + .nodes_time = { 0, 1 }, + .num_edges = 0, + .num_epochs = 1, + .counts = { 0 }, + .offset = { 0 }, + .duration = { 1 }, + .nodes_index = { 0, 1 } }, + /* a single node */ + { .num_nodes = 1, + .nodes_time = { 0 }, + .num_edges = 0, + .num_epochs = 0, + .nodes_index = { 0 } }, + /* no nodes */ + { .num_nodes = 0, .num_edges = 0, .num_epochs = 0 }, + /* an edge of zero length */ + { .num_nodes = 5, + .nodes_time = { 0, 0, 1, 1, 3 }, + .num_edges = 3, + .likelihoods = { { 2, 10 }, { 1, 10 }, { 4, 5 } }, + .edges_parent = { 2, 2, 4 }, + .edges_child = { 0, 1, 3 }, + .num_epochs = 2, + .counts = { 3, 2 }, + .offset = { 20, 5 }, + .duration = { 1, 2 }, + .nodes_index = { 0, 0, 1, 1, 2 } }, + /* an edge whose parent is younger than its child is skipped */ + { .num_nodes = 3, + .nodes_time = { 0, 1, 0.5 }, + .num_edges = 2, + .likelihoods = { { 2, 10 }, { 1, 10 } }, + .edges_parent = { 1, 2 }, + .edges_child = { 0, 1 }, + .num_epochs = 2, + .counts = { 2, 2 }, + .offset = { 10, 10 }, + .duration = { 0.5, 0.5 }, + .nodes_index = { 0, 2, 1 } }, + /* two epochs */ + { .num_nodes = 4, + .nodes_time = { 0, 0, 1, 3 }, + .num_edges = 2, + .likelihoods = { { 6, 12 }, { 3, 12 } }, + .edges_parent = { 3, 2 }, + .edges_child = { 0, 1 }, + .num_epochs = 2, + .counts = { 5, 2 }, + .offset = { 24, 12 }, + .duration = { 1, 2 }, + .nodes_index = { 0, 0, 1, 2 } }, + /* NOTE: current behaviour, possibly a bug: the first epoch always starts at zero, + even if the youngest node is older */ + { .num_nodes = 2, + .nodes_time = { 1, 2 }, + .num_edges = 1, + .likelihoods = { { 2, 10 } }, + .edges_parent = { 1 }, + .edges_child = { 0 }, + .num_epochs = 1, + .counts = { 2 }, + .offset = { 10 }, + .duration = { 2 }, + .nodes_index = { 0, 1 } }, + /* tied and unsorted times */ + { .num_nodes = 6, + .nodes_time = { 3, 0, 1, 0, 1, 5 }, + .num_edges = 4, + .likelihoods = { { 2, 10 }, { 1, 10 }, { 3, 10 }, { 2, 10 } }, + .edges_parent = { 4, 2, 5, 2 }, + .edges_child = { 1, 3, 0, 1 }, + .num_epochs = 3, + .counts = { 5, 0, 1.5 }, + .offset = { 30, 0, 10 }, + .duration = { 1, 2, 2 }, + .nodes_index = { 2, 0, 1, 0, 1, 3 } }, + /* NaN times are ordered last, whichever their position */ + { .num_nodes = 5, + .nodes_time = { 0, NAN, 1, NAN, 2 }, + .num_edges = 2, + .likelihoods = { { 1, 1 }, { 1, 1 } }, + .edges_parent = { 2, 4 }, + .edges_child = { 0, 2 }, + .num_epochs = 2, + .counts = { 1, 1 }, + .offset = { 1, 1 }, + .duration = { 1, 1 }, + .nodes_index = { 0, 2, 1, 2, 2 } }, +}; + +static void +test_mutational_area(void) +{ + const size_t num_rows = sizeof(area_rows) / sizeof(area_rows[0]); + const area_row_t *row; + tsd_epoch_stats_t stats; + tsd_id_t nodes_index[TABLE_MAX_NODES]; + tsd_size_t k; + size_t j; + int ret; + + for (j = 0; j < num_rows; j++) { + row = area_rows + j; + ret = tsd_mutational_area(row->num_nodes, row->nodes_time, row->num_edges, + &row->likelihoods[0][0], row->edges_parent, row->edges_child, &stats, + nodes_index); + CU_ASSERT_EQUAL_FATAL(ret, 0); + CU_ASSERT_EQUAL_FATAL(stats.num_epochs, row->num_epochs); + assert_array_close(stats.counts, row->counts, row->num_epochs); + assert_array_close(stats.offset, row->offset, row->num_epochs); + assert_array_close(stats.duration, row->duration, row->num_epochs); + for (k = 0; k < row->num_nodes; k++) { + CU_ASSERT_EQUAL(nodes_index[k], row->nodes_index[k]); + } + tsd_epoch_stats_free(&stats); + } +} + +/* Expected values of the reference implementation */ +static const timescale_row_t timescale_rows[] = { + { .num_nodes = 4, + .nodes_time = { 0, 0, 1, 2 }, + .num_edges = 3, + .likelihoods = { { 2, 10 }, { 1, 10 }, { 3, 10 } }, + .edges_parent = { 2, 2, 3 }, + .edges_child = { 0, 1, 2 }, + .max_intervals = 1, + .num_breaks = 2, + .origin = { 0, 2 }, + .adjust = { 0, 0.4 }, + .ret = 0 }, + { .num_nodes = 4, + .nodes_time = { 0, 0, 1, 2 }, + .num_edges = 3, + .likelihoods = { { 2, 10 }, { 1, 10 }, { 3, 10 } }, + .edges_parent = { 2, 2, 3 }, + .edges_child = { 0, 1, 2 }, + .max_intervals = 2, + .num_breaks = 2, + .origin = { 0, 2 }, + .adjust = { 0, 0.4 }, + .ret = 0 }, + /* as many intervals as epochs */ + { .num_nodes = 4, + .nodes_time = { 0, 0, 1, 2 }, + .num_edges = 3, + .likelihoods = { { 2, 10 }, { 1, 10 }, { 3, 10 } }, + .edges_parent = { 2, 2, 3 }, + .edges_child = { 0, 1, 2 }, + .max_intervals = 3, + .num_breaks = 3, + .origin = { 0, 1, 2 }, + .adjust = { 0, 0.15, 0.44999999999999996 }, + .ret = 0 }, + /* more intervals than epochs */ + { .num_nodes = 4, + .nodes_time = { 0, 0, 1, 2 }, + .num_edges = 3, + .likelihoods = { { 2, 10 }, { 1, 10 }, { 3, 10 } }, + .edges_parent = { 2, 2, 3 }, + .edges_child = { 0, 1, 2 }, + .max_intervals = 10000, + .num_breaks = 3, + .origin = { 0, 1, 2 }, + .adjust = { 0, 0.15, 0.44999999999999996 }, + .ret = 0 }, + { .num_nodes = 4, + .nodes_time = { 0, 0, 1, 2 }, + .num_edges = 3, + .likelihoods = { { 2, 10 }, { 1, 10 }, { 3, 10 } }, + .edges_parent = { 2, 2, 3 }, + .edges_child = { 0, 1, 2 }, + .max_intervals = 0, + .ret = TSD_ERR_NONPOSITIVE_INTERVALS }, + { .num_nodes = 4, + .nodes_time = { 0, 0, 1, 2 }, + .num_edges = 3, + .likelihoods = { { 2, 10 }, { 1, 10 }, { 3, 10 } }, + .edges_parent = { 2, 2, 3 }, + .edges_child = { 0, 1, 2 }, + .max_intervals = -1, + .ret = TSD_ERR_NONPOSITIVE_INTERVALS }, + /* a historical sample */ + { .num_nodes = 4, + .nodes_time = { 0, 500, 100, 700 }, + .num_edges = 3, + .likelihoods = { { 2, 10 }, { 1, 10 }, { 3, 10 } }, + .edges_parent = { 2, 3, 3 }, + .edges_child = { 0, 2, 1 }, + .max_intervals = 1, + .num_breaks = 2, + .origin = { 0, 700 }, + .adjust = { 0, 0.6708333333333333 }, + .ret = 0 }, + { .num_nodes = 4, + .nodes_time = { 0, 500, 100, 700 }, + .num_edges = 3, + .likelihoods = { { 2, 10 }, { 1, 10 }, { 3, 10 } }, + .edges_parent = { 2, 3, 3 }, + .edges_child = { 0, 2, 1 }, + .max_intervals = 3, + .num_breaks = 4, + .origin = { 0, 100, 500, 700 }, + .adjust = { 0, 0.2, 0.2666666666666667, 0.4333333333333334 }, + .ret = 0 }, + { .num_nodes = 4, + .nodes_time = { 0, 500, 100, 700 }, + .num_edges = 3, + .likelihoods = { { 2, 10 }, { 1, 10 }, { 3, 10 } }, + .edges_parent = { 2, 3, 3 }, + .edges_child = { 0, 2, 1 }, + .max_intervals = 100, + .num_breaks = 4, + .origin = { 0, 100, 500, 700 }, + .adjust = { 0, 0.2, 0.2666666666666667, 0.4333333333333334 }, + .ret = 0 }, + /* the top edge has no span, so the last epoch has no weight and is merged */ + { .num_nodes = 4, + .nodes_time = { 0, 0, 1, 2 }, + .num_edges = 3, + .likelihoods = { { 2, 10 }, { 1, 10 }, { 3, 0 } }, + .edges_parent = { 2, 2, 3 }, + .edges_child = { 0, 1, 2 }, + .max_intervals = 1, + .num_breaks = 2, + .origin = { 0, 2 }, + .adjust = { 0, 0.6 }, + .ret = 0 }, + /* an edge of negative length is skipped from the totals */ + { .num_nodes = 4, + .nodes_time = { 0, 0, 2, 1 }, + .num_edges = 3, + .likelihoods = { { 2, 10 }, { 1, 10 }, { 5, 10 } }, + .edges_parent = { 2, 2, 3 }, + .edges_child = { 0, 1, 2 }, + .max_intervals = 2, + .num_breaks = 3, + .origin = { 0, 1, 2 }, + .adjust = { 0, 0.075, 0.15 }, + .ret = 0 }, + /* the total weight is zero, so the first changepoint is -1, which counts from the + end */ + { .num_nodes = 6, + .nodes_time = { 0, 0, 1, 2, 3, 4 }, + .num_edges = 4, + .likelihoods = { { 1, 1 }, { 1, 1 }, { 1, -3 }, { 1, 1 } }, + .edges_parent = { 2, 3, 4, 5 }, + .edges_child = { 0, 2, 3, 4 }, + .max_intervals = 2, + .num_breaks = 2, + .origin = { 4, 4 }, + .adjust = { 0, 1 }, + .ret = 0 }, + /* NOTE: current behaviour, possibly a bug: every edge over an interval has zero span + (a zero mutation rate) or there are no edges */ + { .num_nodes = 3, + .nodes_time = { 0, 0, 1 }, + .num_edges = 2, + .likelihoods = { { 2, 0 }, { 1, 0 } }, + .edges_parent = { 2, 2 }, + .edges_child = { 0, 1 }, + .max_intervals = 1, + .ret = TSD_ERR_ZERO_EDGE_SPAN }, + { .num_nodes = 2, + .nodes_time = { 0, 1 }, + .num_edges = 0, + .max_intervals = 1, + .ret = TSD_ERR_ZERO_EDGE_SPAN }, + /* all nodes at time zero: no epochs, and the span is zero */ + { .num_nodes = 3, + .nodes_time = { 0, 0, 0 }, + .num_edges = 2, + .likelihoods = { { 1, 10 }, { 1, 10 } }, + .edges_parent = { 2, 2 }, + .edges_child = { 0, 1 }, + .max_intervals = 1, + .ret = TSD_ERR_ZERO_EDGE_SPAN }, +}; + +static void +test_mutational_timescale(void) +{ + const size_t num_rows = sizeof(timescale_rows) / sizeof(timescale_rows[0]); + const timescale_row_t *row; + double *origin = NULL; + double *adjust = NULL; + tsd_size_t num_breaks; + size_t j; + int ret; + + for (j = 0; j < num_rows; j++) { + row = timescale_rows + j; + ret = tsd_mutational_timescale(row->num_nodes, row->nodes_time, row->num_edges, + &row->likelihoods[0][0], row->edges_parent, row->edges_child, + row->max_intervals, &num_breaks, &origin, &adjust); + CU_ASSERT_EQUAL(ret, row->ret); + if (ret == 0 && row->ret == 0) { + CU_ASSERT_EQUAL_FATAL(num_breaks, row->num_breaks); + assert_array_close(origin, row->origin, num_breaks); + assert_array_close(adjust, row->adjust, num_breaks); + } + tsd_safe_free(origin); + tsd_safe_free(adjust); + origin = NULL; + adjust = NULL; + } +} + +/* Expected values of the reference implementation */ +static const point_row_t point_rows[] = { + { .num_points = 5, + .estimate = { 0, 0.5, 1, 2, 3 }, + .fixed = { 0, 0, 0, 0, 0 }, + .num_breaks = 3, + .original = { 0, 1, 3 }, + .rescaled = { 0, 2, 3.5 }, + .out = { 0, 1, 2, 2.75, 3.5 }, + .ret = 0 }, + /* the last piece is flat, so everything beyond it maps to the last point */ + { .num_points = 5, + .estimate = { 3, 4, 10, 1e+300, INFINITY }, + .fixed = { 0, 0, 0, 0, 0 }, + .num_breaks = 3, + .original = { 0, 1, 3 }, + .rescaled = { 0, 2, 3.5 }, + .out = { 3.5, 3.5, 3.5, 3.5, NAN }, + .ret = 0 }, + /* NOTE: current behaviour, possibly a bug: a time below the first break has search + index -1, which wraps to the last breakpoint; -inf gives NaN */ + { .num_points = 4, + .estimate = { -1, -1e-09, 0, -INFINITY }, + .fixed = { 0, 0, 0, 0 }, + .num_breaks = 3, + .original = { 0, 1, 3 }, + .rescaled = { 0, 2, 3.5 }, + .out = { 3.5, 3.5, 0, NAN }, + .ret = 0 }, + /* NaN, fixed or not */ + { .num_points = 3, + .estimate = { NAN, 1, NAN }, + .fixed = { 1, 0, 0 }, + .num_breaks = 3, + .original = { 0, 1, 3 }, + .rescaled = { 0, 2, 3.5 }, + .out = { NAN, 2, NAN }, + .ret = 0 }, + /* some fixed */ + { .num_points = 4, + .estimate = { 0, 0.5, 3, 4 }, + .fixed = { 1, 0, 1, 1 }, + .num_breaks = 3, + .original = { 0, 1, 3 }, + .rescaled = { 0, 2, 3.5 }, + .out = { 0, 1, 3, 4 }, + .ret = 0 }, + { .num_points = 0, + .num_breaks = 3, + .original = { 0, 1, 3 }, + .rescaled = { 0, 2, 3.5 }, + .ret = 0 }, + /* a single breakpoint */ + { .num_points = 3, + .estimate = { 0, 0.5, 7 }, + .fixed = { 0, 0, 0 }, + .num_breaks = 1, + .original = { 0 }, + .rescaled = { 2 }, + .out = { 2, 2, 2 }, + .ret = 0 }, + { .num_points = 3, + .estimate = { 0, 0.3, 1 }, + .fixed = { 0, 0, 0 }, + .num_breaks = 2, + .original = { 0, 5 }, + .rescaled = { 0, 5 }, + .out = { 0, 0.3, 1 }, + .ret = 0 }, + { .num_points = 1, + .estimate = { 0.5 }, + .fixed = { 0 }, + .num_breaks = 0, + .ret = TSD_ERR_NO_BREAKPOINTS }, + { .num_points = 1, + .estimate = { 0.5 }, + .fixed = { 0 }, + .num_breaks = 3, + .original = { 0, 1, 3 }, + .rescaled = { 0, 2, 2 }, + .ret = TSD_ERR_NON_INCREASING_BREAKPOINTS }, + { .num_points = 1, + .estimate = { 0.5 }, + .fixed = { 0 }, + .num_breaks = 3, + .original = { 0, 1, 3 }, + .rescaled = { 0, 2, 1 }, + .ret = TSD_ERR_NON_INCREASING_BREAKPOINTS }, + { .num_points = 1, + .estimate = { 0.5 }, + .fixed = { 0 }, + .num_breaks = 3, + .original = { 0, 2, 1 }, + .rescaled = { 0, 1, 2 }, + .ret = TSD_ERR_NON_INCREASING_BREAKPOINTS }, + { .num_points = 1, + .estimate = { 0.5 }, + .fixed = { 0 }, + .num_breaks = 3, + .original = { 0, 1, NAN }, + .rescaled = { 0, 1, 2 }, + .ret = TSD_ERR_NON_INCREASING_BREAKPOINTS }, + { .num_points = 1, + .estimate = { 0.5 }, + .fixed = { 0 }, + .num_breaks = 3, + .original = { 0, 1, 2 }, + .rescaled = { 0, 1, NAN }, + .ret = TSD_ERR_NON_INCREASING_BREAKPOINTS }, +}; + +static void +test_piecewise_scale_point_estimate(void) +{ + const size_t num_rows = sizeof(point_rows) / sizeof(point_rows[0]); + const point_row_t *row; + double out[TABLE_MAX_POINTS]; + size_t j; + int ret; + + for (j = 0; j < num_rows; j++) { + row = point_rows + j; + ret = tsd_piecewise_scale_point_estimate(row->num_points, row->estimate, + row->fixed, row->num_breaks, row->original, row->rescaled, out); + CU_ASSERT_EQUAL(ret, row->ret); + if (ret == 0 && row->ret == 0) { + assert_array_close(out, row->out, row->num_points); + } + } +} + +/* Expected values of the reference implementation */ +static const posterior_row_t posterior_rows[] = { + { .num_posteriors = 4, + .posteriors = { { 1, 1 }, { 2, 3 }, { 0, 1 }, { 5, 2 } }, + .fixed = { 0, 0, 0, 0 }, + .num_breaks = 3, + .original = { 0, 1, 3 }, + .rescaled = { 0, 2, 3.5 }, + .quantile_width = 0.5, + .max_shape = 1000, + .out = { { 5.752572529118271, 2.455480919679371 }, + { 3.460836454696765, 2.2304182273483826 }, + { 0.22573432805250393, 0.612867164026252 }, + { 39.903223991686914, 11.686635426196261 } }, + .ret = 0 }, + { .num_posteriors = 4, + .posteriors = { { 1, 1 }, { 2, 3 }, { 0, 1 }, { 5, 2 } }, + .fixed = { 0, 0, 0, 0 }, + .num_breaks = 3, + .original = { 0, 1, 3 }, + .rescaled = { 0, 2, 3.5 }, + .quantile_width = 0.001, + .max_shape = 1000, + .out = { { 2.471583651492129, 1.2623940550880468 }, + { 3.210845310401922, 2.105422655200961 }, + { 0.23603088036204523, 0.6180154401810226 }, + { 26.04896064141572, 7.72827446897592 } }, + .ret = 0 }, + { .num_posteriors = 4, + .posteriors = { { 1, 1 }, { 2, 3 }, { 0, 1 }, { 5, 2 } }, + .fixed = { 0, 0, 0, 0 }, + .num_breaks = 3, + .original = { 0, 1, 3 }, + .rescaled = { 0, 2, 3.5 }, + .quantile_width = 0.999999999, + .max_shape = 1000, + .out = { { 6.175396703307324, 2.609235164839027 }, + { 1.9999982566565375, 1.4999991283282688 }, + { -2.6908024519656237e-07, 0.4999998654598774 }, + { 13.715489108570114, 4.204425459591461 } }, + .ret = 0 }, + { .num_posteriors = 4, + .posteriors = { { 1, 1 }, { 2, 3 }, { 0, 1 }, { 5, 2 } }, + .fixed = { 0, 0, 0, 0 }, + .num_breaks = 3, + .original = { 0, 1, 3 }, + .rescaled = { 0, 2, 3.5 }, + .quantile_width = 0, + .max_shape = 1000, + .ret = TSD_ERR_INVALID_QUANTILE_WIDTH }, + { .num_posteriors = 4, + .posteriors = { { 1, 1 }, { 2, 3 }, { 0, 1 }, { 5, 2 } }, + .fixed = { 0, 0, 0, 0 }, + .num_breaks = 3, + .original = { 0, 1, 3 }, + .rescaled = { 0, 2, 3.5 }, + .quantile_width = 1, + .max_shape = 1000, + .ret = TSD_ERR_INVALID_QUANTILE_WIDTH }, + { .num_posteriors = 4, + .posteriors = { { 1, 1 }, { 2, 3 }, { 0, 1 }, { 5, 2 } }, + .fixed = { 0, 0, 0, 0 }, + .num_breaks = 3, + .original = { 0, 1, 3 }, + .rescaled = { 0, 2, 3.5 }, + .quantile_width = NAN, + .max_shape = 1000, + .ret = TSD_ERR_INVALID_QUANTILE_WIDTH }, + { .num_posteriors = 4, + .posteriors = { { 1, 1 }, { 2, 3 }, { 0, 1 }, { 5, 2 } }, + .fixed = { 1, 0, 1, 0 }, + .num_breaks = 3, + .original = { 0, 1, 3 }, + .rescaled = { 0, 2, 3.5 }, + .quantile_width = 0.5, + .max_shape = 1000, + .out = { { NAN, NAN }, { 3.460836454696765, 2.2304182273483826 }, { NAN, NAN }, + { 39.903223991686914, 11.686635426196261 } }, + .ret = 0 }, + /* fixed rows are not validated */ + { .num_posteriors = 2, + .posteriors = { { NAN, NAN }, { 1, 1 } }, + .fixed = { 1, 0 }, + .num_breaks = 3, + .original = { 0, 1, 3 }, + .rescaled = { 0, 2, 3.5 }, + .quantile_width = 0.5, + .max_shape = 1000, + .out = { { NAN, NAN }, { 5.752572529118271, 2.455480919679371 } }, + .ret = 0 }, + /* NOTE: current behaviour, possibly a bug: no posteriors is an error */ + { .num_posteriors = 0, + .num_breaks = 3, + .original = { 0, 1, 3 }, + .rescaled = { 0, 2, 3.5 }, + .quantile_width = 0.5, + .max_shape = 1000, + .ret = TSD_ERR_NO_POSTERIORS }, + { .num_posteriors = 4, + .posteriors + = { { -0.99, 1 }, { 1, 1e-300 }, { 1, 1e+300 }, { 1000000, 1000000 } }, + .fixed = { 0, 0, 0, 0 }, + .num_breaks = 3, + .original = { 0, 1, 3 }, + .rescaled = { 0, 2, 3.5 }, + .quantile_width = 0.5, + .max_shape = 1000, + .out = { { -0.99, 0.5 }, { 999, 285.7142857142857 }, + { 1.000000000000004, 5.00000000000001e+299 }, { 999, 499.99981250007033 } }, + .ret = 0 }, + /* NOTE: current behaviour, possibly a bug: for a shape this close to -1 the lower + quantile underflows to zero and the division by it is an error (IEEE would give + inf), rather than a failed gamma fit */ + { .num_posteriors = 1, + .posteriors = { { -0.9999, 1 } }, + .fixed = { 0 }, + .num_breaks = 3, + .original = { 0, 1, 3 }, + .rescaled = { 0, 2, 3.5 }, + .quantile_width = 0.5, + .max_shape = 1000, + .ret = TSD_ERR_ZERO_DIVISION }, + { .num_posteriors = 1, + .posteriors = { { 1, INFINITY } }, + .fixed = { 0 }, + .num_breaks = 3, + .original = { 0, 1, 3 }, + .rescaled = { 0, 2, 3.5 }, + .quantile_width = 0.5, + .max_shape = 1000, + .ret = TSD_ERR_ZERO_DIVISION }, + /* NOTE: current behaviour, possibly a bug: the error of tsd_approximate_gamma_iqr is + passed on */ + { .num_posteriors = 1, + .posteriors = { { INFINITY, 1 } }, + .fixed = { 0 }, + .num_breaks = 3, + .original = { 0, 1, 3 }, + .rescaled = { 0, 2, 3.5 }, + .quantile_width = 0.5, + .max_shape = 1000, + .ret = TSD_ERR_UNSORTED_QUANTILES }, + { .num_posteriors = 4, + .posteriors = { { 1, 1 }, { 2, 3 }, { 0, 1 }, { -1, 2 } }, + .fixed = { 0, 0, 0, 0 }, + .num_breaks = 3, + .original = { 0, 1, 3 }, + .rescaled = { 0, 2, 3.5 }, + .quantile_width = 0.5, + .max_shape = 1000, + .ret = TSD_ERR_INVALID_POSTERIOR }, + { .num_posteriors = 1, + .posteriors = { { 1, NAN } }, + .fixed = { 0 }, + .num_breaks = 3, + .original = { 0, 1, 3 }, + .rescaled = { 0, 2, 3.5 }, + .quantile_width = 0.5, + .max_shape = 1000, + .ret = TSD_ERR_INVALID_POSTERIOR }, + /* all quantiles map to one point beyond the last break: zero interquantile range */ + { .num_posteriors = 2, + .posteriors = { { 1, 0.001 }, { 1, 1e-09 } }, + .fixed = { 0, 0 }, + .num_breaks = 3, + .original = { 0, 1, 3 }, + .rescaled = { 0, 2, 3.5 }, + .quantile_width = 0.5, + .max_shape = 1000, + .out = { { 999, 285.7142857142857 }, { 999, 285.7142857142857 } }, + .ret = 0 }, + { .num_posteriors = 4, + .posteriors = { { 1, 1 }, { 2, 3 }, { 0, 1 }, { 5, 2 } }, + .fixed = { 0, 0, 0, 0 }, + .num_breaks = 3, + .original = { 0.5, 1, 3 }, + .rescaled = { 0, 2, 3.5 }, + .quantile_width = 0.5, + .max_shape = 1000, + .ret = TSD_ERR_TIME_BELOW_FIRST_BREAKPOINT }, + /* the lower quantile is below the first breakpoint, the mean is not */ + { .num_posteriors = 1, + .posteriors = { { 1, 1 } }, + .fixed = { 0 }, + .num_breaks = 3, + .original = { 1.5, 3, 5 }, + .rescaled = { 0, 1, 2 }, + .quantile_width = 0.5, + .max_shape = 1000, + .ret = TSD_ERR_TIME_BELOW_FIRST_BREAKPOINT }, + /* the rescaled quantiles of fixed posteriors are zero, and are checked too */ + { .num_posteriors = 1, + .posteriors = { { 1, 1 } }, + .fixed = { 1 }, + .num_breaks = 3, + .original = { 0.5, 2, 5 }, + .rescaled = { 0, 1, 2 }, + .quantile_width = 0.5, + .max_shape = 1000, + .ret = TSD_ERR_TIME_BELOW_FIRST_BREAKPOINT }, + /* NOTE: current behaviour, possibly a bug: max_shape = 0 gives shape -1 (improper) + and zero rate */ + { .num_posteriors = 4, + .posteriors = { { 1, 1 }, { 2, 3 }, { 0, 1 }, { 5, 2 } }, + .fixed = { 0, 0, 0, 0 }, + .num_breaks = 3, + .original = { 0, 1, 3 }, + .rescaled = { 0, 2, 3.5 }, + .quantile_width = 0.5, + .max_shape = 0, + .out = { { -1, 0 }, { -1, 0 }, { -1, 0 }, { -1, 0 } }, + .ret = 0 }, + { .num_posteriors = 4, + .posteriors = { { 1, 1 }, { 2, 3 }, { 0, 1 }, { 5, 2 } }, + .fixed = { 0, 0, 0, 0 }, + .num_breaks = 3, + .original = { 0, 1, 3 }, + .rescaled = { 0, 2, 3.5 }, + .quantile_width = 0.5, + .max_shape = 1, + .out = { { 0, 0.36363636363636365 }, { 0, 0.5 }, { 0, 0.5 }, + { 0, 0.2857142857142857 } }, + .ret = 0 }, + { .num_posteriors = 4, + .posteriors = { { 1, 1 }, { 2, 3 }, { 0, 1 }, { 5, 2 } }, + .fixed = { 0, 0, 0, 0 }, + .num_breaks = 3, + .original = { 0, 1, 3 }, + .rescaled = { 0, 2, 3.5 }, + .quantile_width = 0.5, + .max_shape = NAN, + .out = { { 5.752572529118271, 2.455480919679371 }, + { 3.460836454696765, 2.2304182273483826 }, + { 0.22573432805250393, 0.612867164026252 }, + { 39.903223991686914, 11.686635426196261 } }, + .ret = 0 }, + { .num_posteriors = 4, + .posteriors = { { 1, 1 }, { 2, 3 }, { 0, 1 }, { 5, 2 } }, + .fixed = { 0, 0, 0, 0 }, + .num_breaks = 3, + .original = { 0, 1, 1 }, + .rescaled = { 0, 2, 3.5 }, + .quantile_width = 0.5, + .max_shape = 1000, + .ret = TSD_ERR_NON_INCREASING_BREAKPOINTS }, + { .num_posteriors = 4, + .posteriors = { { 1, 1 }, { 2, 3 }, { 0, 1 }, { 5, 2 } }, + .fixed = { 0, 0, 0, 0 }, + .num_breaks = 3, + .original = { 0, 1, 3 }, + .rescaled = { 0, 2, 2 }, + .quantile_width = 0.5, + .max_shape = 1000, + .ret = TSD_ERR_NON_INCREASING_BREAKPOINTS }, + /* the breaks are checked before the posteriors */ + { .num_posteriors = 1, + .posteriors = { { -5, 1 } }, + .fixed = { 0 }, + .num_breaks = 2, + .original = { 0, 0 }, + .rescaled = { 0, 1 }, + .quantile_width = 0.5, + .max_shape = 1000, + .ret = TSD_ERR_NON_INCREASING_BREAKPOINTS }, + /* a single breakpoint at zero: every quantile maps to zero */ + { .num_posteriors = 4, + .posteriors = { { 1, 1 }, { 2, 3 }, { 0, 1 }, { 5, 2 } }, + .fixed = { 0, 0, 0, 0 }, + .num_breaks = 1, + .original = { 0 }, + .rescaled = { 0 }, + .quantile_width = 0.5, + .max_shape = 1000, + .ret = TSD_ERR_ZERO_DIVISION }, + { .num_posteriors = 4, + .posteriors = { { 1, 1 }, { 2, 3 }, { 0, 1 }, { 5, 2 } }, + .fixed = { 0, 0, 0, 0 }, + .num_breaks = 1, + .original = { 0 }, + .rescaled = { 4 }, + .quantile_width = 0.5, + .max_shape = 1000, + .out = { { 999, 250 }, { 999, 250 }, { 999, 250 }, { 999, 250 } }, + .ret = 0 }, + { .num_posteriors = 4, + .posteriors = { { 1, 1 }, { 2, 3 }, { 0, 1 }, { 5, 2 } }, + .fixed = { 0, 0, 0, 0 }, + .num_breaks = 0, + .quantile_width = 0.5, + .max_shape = 1000, + .ret = TSD_ERR_NO_BREAKPOINTS }, +}; + +static void +test_piecewise_scale_posterior(void) +{ + const size_t num_rows = sizeof(posterior_rows) / sizeof(posterior_rows[0]); + const posterior_row_t *row; + double out[2 * TABLE_MAX_POSTERIORS]; + size_t j; + int ret; + + for (j = 0; j < num_rows; j++) { + row = posterior_rows + j; + ret = tsd_piecewise_scale_posterior(row->num_posteriors, &row->posteriors[0][0], + row->fixed, row->num_breaks, row->original, row->rescaled, + row->quantile_width, row->max_shape, out); + CU_ASSERT_EQUAL(ret, row->ret); + if (ret == 0 && row->ret == 0) { + assert_array_close(out, &row->out[0][0], 2 * row->num_posteriors); + } + } +} + +static void +handle_cunit_error(void) +{ + fprintf( + stderr, "CUnit error occurred: %d: %s\n", CU_get_error(), CU_get_error_msg()); + exit(EXIT_FAILURE); +} + +/* Nodes 0 and 1 are fixed, at ages 1 and 5; 2 and 3 are free. */ +static const double ep_constraints[8] = { 1, 1, 5, 5, 0, INFINITY, 0, INFINITY }; +static const double ep_likelihoods[8] = { 1, 0.1, 1, 0.1, 1, 0.1, 1, 0.1 }; +static const double ep_huge[8] = { 1, 1e300, 1, 1e300, 1, 1e300, 1, 1e300 }; +static const tsd_id_t ep_parent[4] = { 2, 1, 3, 1 }; +static const tsd_id_t ep_child[4] = { 0, 3, 2, 0 }; +static const tsd_id_t ep_twin_parent[4] = { 2, 1, 3, 2 }; +static const tsd_id_t ep_twin_child[4] = { 0, 3, 2, 2 }; + +/* Four nodes with four edges, and the same four as blocks, with posterior `post`. */ +static void +ep_init(tsd_ep_t *ep, const tsd_id_t *parent, const tsd_id_t *child, + const double *likelihoods, const double *post) +{ + int ret; + + ret = tsd_ep_init(ep, 4, 4, 4, ep_constraints, parent, child, likelihoods, parent, + child, likelihoods); + CU_ASSERT_FATAL(ret == 0); + memcpy(ep->posterior, post, 8 * sizeof(*post)); +} + +typedef struct { + double x[2]; + double y[2]; + double s; + double d; + int ret; +} damp_row_t; + +typedef struct { + double x[2]; + double s; + double d; + int ret; +} rescale_row_t; + +/* Expected values of the reference implementation */ +static const damp_row_t damp_rows[] = { + { .x = { 0, 0 }, .y = { 0, 0 }, .s = 0.5, .d = 1, .ret = 0 }, + /* zero x and y: s is not checked */ + { .x = { 0, 0 }, .y = { 0, 0 }, .s = 5, .d = 1, .ret = 0 }, + { .x = { 0, 1 }, .y = { 0, 0 }, .s = 0.5, .d = 1, .ret = 0 }, + { .x = { 1, 2 }, .y = { 0, 0 }, .s = 0.5, .d = 1, .ret = 0 }, + { .x = { 1, 2 }, .y = { 0.9999999999999999, 0 }, .s = 0.5, .d = 1, .ret = 0 }, + { .x = { 1, 2 }, .y = { 1, 0 }, .s = 0.5, .d = 1, .ret = 0 }, + { .x = { 1, 2 }, + .y = { 1.0000000000000002, 0 }, + .s = 0.5, + .d = 0.9999999999999998, + .ret = 0 }, + { .x = { 1, 2 }, .y = { 4, 0 }, .s = 0.5, .d = 0.25, .ret = 0 }, + { .x = { 1, 2 }, .y = { -5, 0 }, .s = 0.5, .d = 1, .ret = 0 }, + { .x = { 1, 2 }, .y = { 0, 0.9999999999999999 }, .s = 0.5, .d = 1, .ret = 0 }, + { .x = { 1, 2 }, .y = { 0, 1 }, .s = 0.5, .d = 1, .ret = 0 }, + { .x = { 1, 2 }, + .y = { 0, 1.0000000000000002 }, + .s = 0.5, + .d = 0.9999999999999998, + .ret = 0 }, + { .x = { 1, 2 }, .y = { 0, 8 }, .s = 0.5, .d = 0.125, .ret = 0 }, + { .x = { 1, 2 }, .y = { 0, -5 }, .s = 0.5, .d = 1, .ret = 0 }, + { .x = { 1, 2 }, .y = { 4, 2 }, .s = 0.5, .d = 0.25, .ret = 0 }, + { .x = { 1, 2 }, .y = { 2, 8 }, .s = 0.5, .d = 0.125, .ret = 0 }, + { .x = { 1, 2 }, .y = { -1, -1 }, .s = 0.5, .d = 1, .ret = 0 }, + { .x = { 1, 2 }, .y = { 2, 2 }, .s = 5e-324, .d = 1, .ret = 0 }, + { .x = { 1, 2 }, + .y = { 2, 2 }, + .s = 0.9999999999999999, + .d = 1.1102230246251565e-16, + .ret = 0 }, + { .x = { -0.9999999999999999, 1 }, .y = { 0, 0 }, .s = 0.5, .d = 1, .ret = 0 }, + { .x = { 1, 1e-300 }, .y = { 1, 4 }, .s = 0.5, .d = 1.25e-301, .ret = 0 }, + /* NOTE: current behaviour, possibly a bug: the minimum swallows a NaN in the second + component of y, so the damping is silently skipped */ + { .x = { 1, 1 }, .y = { 0, NAN }, .s = 0.5, .d = 1, .ret = 0 }, + { .x = { 1, 1 }, .y = { 8, NAN }, .s = 0.5, .d = 0.125, .ret = 0 }, + { .x = { 1, 1 }, .y = { -INFINITY, 0 }, .s = 0.5, .d = 1, .ret = 0 }, + { .x = { 1, 1 }, .y = { 0, -INFINITY }, .s = 0.5, .d = 1, .ret = 0 }, + { .x = { 1, 1 }, .y = { 0, 0 }, .s = 0, .ret = TSD_ERR_INVALID_MIN_STEP }, + { .x = { 1, 1 }, .y = { 0, 0 }, .s = 1, .ret = TSD_ERR_INVALID_MIN_STEP }, + { .x = { 1, 1 }, .y = { 0, 0 }, .s = NAN, .ret = TSD_ERR_INVALID_MIN_STEP }, + { .x = { -1, 1 }, .y = { 0, 0 }, .s = 0.5, .ret = TSD_ERR_INVALID_NODE_POSTERIOR }, + { .x = { NAN, 1 }, .y = { 0, 0 }, .s = 0.5, .ret = TSD_ERR_INVALID_NODE_POSTERIOR }, + { .x = { 1, 0 }, .y = { 0, 0 }, .s = 0.5, .ret = TSD_ERR_INVALID_NODE_POSTERIOR }, + { .x = { 1, NAN }, .y = { 0, 0 }, .s = 0.5, .ret = TSD_ERR_INVALID_NODE_POSTERIOR }, + { .x = { 0, 0 }, .y = { 1, 1 }, .s = 0.5, .ret = TSD_ERR_INVALID_NODE_POSTERIOR }, + /* d underflows */ + { .x = { 1, 1e-300 }, .y = { 0, 1e+300 }, .s = 0.5, .ret = TSD_ERR_INVALID_DAMPING }, + { .x = { 1, 1 }, .y = { NAN, 0 }, .s = 0.5, .ret = TSD_ERR_INVALID_DAMPING }, + /* d is rounded to just above one */ + { .x = { 24.23005039128842, 15.403466578537675 }, + .y = { 2.409458061921995, 1.471023884360475 }, + .s = 0.9045004657321672, + .ret = TSD_ERR_INVALID_DAMPING }, + /* an infinite posterior and a zero message: a division by zero */ + { .x = { INFINITY, 1 }, .y = { 0, 0 }, .s = 0.5, .ret = TSD_ERR_ZERO_DIVISION }, + /* an infinite posterior and a zero message: a division by zero */ + { .x = { 1, INFINITY }, .y = { 0, 0 }, .s = 0.5, .ret = TSD_ERR_ZERO_DIVISION }, +}; + +static void +test_damp(void) +{ + const size_t num_rows = sizeof(damp_rows) / sizeof(damp_rows[0]); + const damp_row_t *row; + double d; + size_t j; + int ret; + + for (j = 0; j < num_rows; j++) { + row = damp_rows + j; + ret = tsd_damp(row->x, row->y, row->s, &d); + CU_ASSERT_EQUAL(ret, row->ret); + if (ret == 0 && row->ret == 0) { + assert_close_ulps(d, row->d, ULPS); + } + } +} + +/* Expected values of the reference implementation */ +static const rescale_row_t rescale_rows[] = { + { .x = { 0, 0 }, .s = 10, .d = 1, .ret = 0 }, + /* zero x: s is not checked */ + { .x = { 0, 0 }, .s = 0, .d = 1, .ret = 0 }, + { .x = { 0, 1 }, .s = 10, .d = 1, .ret = 0 }, + { .x = { 5, 1 }, .s = 10, .d = 1, .ret = 0 }, + { .x = { -0.5, 1 }, .s = 2, .d = 1, .ret = 0 }, + { .x = { 8.999999999999998, 1 }, .s = 10, .d = 1, .ret = 0 }, + { .x = { 9, 1 }, .s = 10, .d = 1, .ret = 0 }, + { .x = { 9.000000000000002, 1 }, .s = 10, .d = 0.9999999999999998, .ret = 0 }, + { .x = { -0.49999999999999994, 1 }, .s = 2, .d = 1, .ret = 0 }, + { .x = { -0.5000000000000001, 1 }, .s = 2, .d = 0.9999999999999998, .ret = 0 }, + { .x = { -0.95, 1 }, .s = 10, .d = 0.9473684210526316, .ret = 0 }, + { .x = { 99, INFINITY }, .s = 10, .d = 0.09090909090909091, .ret = 0 }, + { .x = { INFINITY, 1 }, .s = 10, .d = 0, .ret = 0 }, + /* NOTE: current behaviour, possibly a bug: with max_shape = 1 the factor is 0 and + wipes out the posterior */ + { .x = { 1, 1 }, .s = 1, .d = 0, .ret = 0 }, + { .x = { -0.5, 1 }, .s = 1, .d = -0, .ret = 0 }, + { .x = { -1, 1 }, .s = 10, .ret = TSD_ERR_INVALID_NODE_POSTERIOR }, + { .x = { NAN, 1 }, .s = 10, .ret = TSD_ERR_INVALID_NODE_POSTERIOR }, + { .x = { 1, 0 }, .s = 10, .ret = TSD_ERR_INVALID_NODE_POSTERIOR }, + { .x = { 1, -1 }, .s = 10, .ret = TSD_ERR_INVALID_NODE_POSTERIOR }, + { .x = { 1, NAN }, .s = 10, .ret = TSD_ERR_INVALID_NODE_POSTERIOR }, + /* a zero shape with a cap below one: a division by zero */ + { .x = { 0, 1 }, .s = 0.5, .ret = TSD_ERR_ZERO_DIVISION }, +}; + +static void +test_rescale(void) +{ + const size_t num_rows = sizeof(rescale_rows) / sizeof(rescale_rows[0]); + const rescale_row_t *row; + double d; + size_t j; + int ret; + + for (j = 0; j < num_rows; j++) { + row = rescale_rows + j; + ret = tsd_rescale(row->x, row->s, &d); + CU_ASSERT_EQUAL(ret, row->ret); + if (ret == 0 && row->ret == 0) { + assert_close_ulps(d, row->d, ULPS); + } + } +} + +static void +test_ep_init(void) +{ + const tsd_id_t bad[4] = { 2, 1, 3, 4 }; + tsd_ep_t ep; + + CU_ASSERT_EQUAL(tsd_ep_init(&ep, 4, 4, 4, ep_constraints, ep_parent, ep_child, + ep_likelihoods, ep_parent, ep_child, ep_likelihoods), + 0); + CU_ASSERT_EQUAL(ep.scale[3], 1.0); + CU_ASSERT_EQUAL(ep.posterior[7], 0.0); + CU_ASSERT_EQUAL(ep.edges_parent[3], 1); + tsd_ep_free(&ep); + CU_ASSERT_EQUAL(tsd_ep_init(&ep, 4, 4, 4, ep_constraints, bad, ep_child, + ep_likelihoods, ep_parent, ep_child, ep_likelihoods), + TSD_ERR_NODE_OUT_OF_BOUNDS); + tsd_ep_free(&ep); + CU_ASSERT_EQUAL(tsd_ep_init(&ep, 4, 4, 4, ep_constraints, ep_parent, ep_child, + ep_likelihoods, ep_parent, bad, ep_likelihoods), + TSD_ERR_NODE_OUT_OF_BOUNDS); + tsd_ep_free(&ep); + CU_ASSERT_EQUAL( + tsd_ep_init(&ep, 0, 0, 0, NULL, NULL, NULL, NULL, NULL, NULL, NULL), 0); + tsd_ep_free(&ep); +} + +static void +test_rescale_and_assemble_factors(void) +{ + const double zero[8] = { 0 }; + tsd_ep_t ep; + double posterior[8]; + int j; + + ep_init(&ep, ep_parent, ep_child, ep_likelihoods, zero); + for (j = 0; j < 16; j++) { + ep.node[j] = 1.0 + j; + ep.edge[j] = 1.0 + j; + ep.block[j] = 0.5 * (1.0 + j); + } + for (j = 0; j < 4; j++) { + ep.scale[j] = 2.0; + } + tsd_ep_assemble_factors(&ep, posterior); + CU_ASSERT_TRUE(posterior[0] > 0); + tsd_ep_rescale_factors(&ep); + CU_ASSERT_EQUAL(ep.scale[3], 1.0); + CU_ASSERT_EQUAL(ep.node[0], 2.0); + CU_ASSERT_EQUAL(ep.edge[0], 2.0); + CU_ASSERT_EQUAL(ep.block[0], 1.0); + tsd_ep_free(&ep); +} + +typedef struct { + tsd_size_t num_nodes; + double constraints[3][2]; + tsd_size_t num_edges; + tsd_id_t edges_parent[2]; + tsd_id_t edges_child[2]; + int consistent; +} consistency_row_t; + +/* Expected values of the reference implementation */ +static const consistency_row_t consistency_rows[] = { + { .num_nodes = 0, .num_edges = 0, .consistent = 1 }, + /* no edges */ + { .num_nodes = 2, + .constraints = { { 0, 1 }, { 0, 1 } }, + .num_edges = 0, + .consistent = 1 }, + { .num_nodes = 2, + .constraints = { { 0, 0 }, { 0, INFINITY } }, + .num_edges = 1, + .edges_parent = { 1 }, + .edges_child = { 0 }, + .consistent = 1 }, + { .num_nodes = 2, + .constraints = { { 0, 5 }, { 3, 9 } }, + .num_edges = 1, + .edges_parent = { 1 }, + .edges_child = { 0 }, + .consistent = 1 }, + /* the parent's upper bound equals the child's lower bound */ + { .num_nodes = 2, + .constraints = { { 5, 5 }, { 0, 5 } }, + .num_edges = 1, + .edges_parent = { 1 }, + .edges_child = { 0 }, + .consistent = 1 }, + { .num_nodes = 2, + .constraints = { { 5.000000000000001, 6 }, { 0, 5 } }, + .num_edges = 1, + .edges_parent = { 1 }, + .edges_child = { 0 }, + .consistent = 0 }, + { .num_nodes = 2, + .constraints = { { 5, 5 }, { 0, 4.999999999999999 } }, + .num_edges = 1, + .edges_parent = { 1 }, + .edges_child = { 0 }, + .consistent = 0 }, + /* the maximum lower bound propagates up a chain */ + { .num_nodes = 3, + .constraints = { { 5, 5 }, { 0, 9 }, { 0, 9 } }, + .num_edges = 2, + .edges_parent = { 1, 2 }, + .edges_child = { 0, 1 }, + .consistent = 1 }, + { .num_nodes = 3, + .constraints = { { 5, 5 }, { 0, INFINITY }, { 0, 4 } }, + .num_edges = 2, + .edges_parent = { 1, 2 }, + .edges_child = { 0, 1 }, + .consistent = 0 }, + /* and from every child */ + { .num_nodes = 3, + .constraints = { { 0, 0 }, { 7, 7 }, { 0, 6 } }, + .num_edges = 2, + .edges_parent = { 2, 2 }, + .edges_child = { 0, 1 }, + .consistent = 0 }, + { .num_nodes = 2, + .constraints = { { 10, 10 }, { 0, 0 } }, + .num_edges = 1, + .edges_parent = { 1 }, + .edges_child = { 0 }, + .consistent = 0 }, + /* NOTE: current behaviour, possibly a bug: the check is a single pass in edge order, + so edges must be sorted children-first */ + { .num_nodes = 3, + .constraints = { { 5, 5 }, { 0, INFINITY }, { 0, 4 } }, + .num_edges = 2, + .edges_parent = { 2, 1 }, + .edges_child = { 1, 0 }, + .consistent = 1 }, + /* NaN bounds are never inconsistent */ + { .num_nodes = 2, + .constraints = { { NAN, NAN }, { 0, 5 } }, + .num_edges = 1, + .edges_parent = { 1 }, + .edges_child = { 0 }, + .consistent = 1 }, + { .num_nodes = 2, + .constraints = { { 5, 5 }, { 0, NAN } }, + .num_edges = 1, + .edges_parent = { 1 }, + .edges_child = { 0 }, + .consistent = 1 }, +}; + +static void +test_constraints_are_consistent(void) +{ + const size_t num_rows = sizeof(consistency_rows) / sizeof(consistency_rows[0]); + const consistency_row_t *row; + int consistent; + size_t j; + int ret; + + for (j = 0; j < num_rows; j++) { + row = consistency_rows + j; + consistent = -1; + ret = tsd_constraints_are_consistent(row->num_nodes, row->num_edges, + &row->constraints[0][0], row->edges_parent, row->edges_child, &consistent); + CU_ASSERT_EQUAL(ret, 0); + CU_ASSERT_EQUAL(consistent, row->consistent); + } +} + +/* The branches of an EP pass: fixed child, fixed parent, free, both fixed. */ +static void +run_likelihood_pass(int unphased) +{ + const tsd_id_t order[5] = { 0, 1, 2, 3, 2 }; + const double post[8] = { 0, 0, 0, 0, 1, 1, 1, 1 }; + double *lognorm; + tsd_ep_t ep; + int ret; + + ep_init(&ep, ep_parent, ep_child, ep_likelihoods, post); + lognorm = unphased ? ep.blocks_lognorm : ep.edges_lognorm; + ret = tsd_ep_propagate_likelihood(&ep, 5, order, unphased, 1000.0, 0.1); + CU_ASSERT_EQUAL(ret, 0); + CU_ASSERT_TRUE(isfinite(lognorm[2])); + /* a small scale triggers a rescaling of the factors in mid-pass */ + ep.scale[2] = 1e-200; + ret = tsd_ep_propagate_likelihood(&ep, 5, order, unphased, 1000.0, 0.1); + CU_ASSERT_EQUAL(ret, 0); + CU_ASSERT_EQUAL(ep.scale[0], 1.0); + tsd_ep_free(&ep); +} + +static void +test_propagate_likelihood(void) +{ + const tsd_id_t order[1] = { 3 }; + const tsd_id_t sideways[1] = { 0 }; + const tsd_id_t bad[1] = { 4 }; + const double post[8] = { 0, 0, 0, 0, 1, 1, 1, 1 }; + tsd_ep_t ep; + + run_likelihood_pass(0); + run_likelihood_pass(1); + /* a block with a single node: the twin update, only in an unphased pass */ + ep_init(&ep, ep_twin_parent, ep_twin_child, ep_likelihoods, post); + CU_ASSERT_EQUAL(tsd_ep_propagate_likelihood(&ep, 1, order, 1, 1000.0, 0.1), 0); + CU_ASSERT_EQUAL(tsd_ep_propagate_likelihood(&ep, 1, order, 0, 1000.0, 0.1), + TSD_ERR_TWIN_EDGE_IN_PHASED_PASS); + tsd_ep_free(&ep); + /* the projection of an edge with a huge mutational target divides by zero */ + ep_init(&ep, ep_parent, ep_child, ep_huge, post); + CU_ASSERT_EQUAL(tsd_ep_propagate_likelihood(&ep, 1, sideways, 1, 1000.0, 0.1), + TSD_ERR_ZERO_DIVISION); + tsd_ep_free(&ep); + /* an improper posterior, bad parameters and ids out of bounds */ + ep_init(&ep, ep_parent, ep_child, ep_likelihoods, post); + ep.posterior[4] = -5; + CU_ASSERT_EQUAL(tsd_ep_propagate_likelihood(&ep, 1, sideways, 0, 1000.0, 0.1), + TSD_ERR_INVALID_NODE_POSTERIOR); + CU_ASSERT_EQUAL(tsd_ep_propagate_likelihood(&ep, 1, order, 0, 0.5, 0.1), + TSD_ERR_INVALID_MAX_SHAPE); + CU_ASSERT_EQUAL(tsd_ep_propagate_likelihood(&ep, 1, order, 0, 1000.0, 1.0), + TSD_ERR_INVALID_MIN_STEP); + CU_ASSERT_EQUAL(tsd_ep_propagate_likelihood(&ep, 1, order, 0, 1000.0, 0.0), + TSD_ERR_INVALID_MIN_STEP); + CU_ASSERT_EQUAL(tsd_ep_propagate_likelihood(&ep, 1, bad, 0, 1000.0, 0.1), + TSD_ERR_EDGE_OUT_OF_BOUNDS); + CU_ASSERT_EQUAL(tsd_ep_propagate_likelihood(&ep, 1, bad, 1, 1000.0, 0.1), + TSD_ERR_BLOCK_OUT_OF_BOUNDS); + tsd_ep_free(&ep); +} + +static void +test_propagate_prior(void) +{ + const uint8_t free_nodes[4] = { 0, 0, 1, 1 }; + const uint8_t none[4] = { 0, 0, 0, 0 }; + const double post[8] = { 0, 0, 0, 0, 2, 1, 3, 2 }; + const double improper[8] = { 0, 0, 0, 0, 1, 0, 1, 0 }; + tsd_ep_t ep; + + ep_init(&ep, ep_parent, ep_child, ep_likelihoods, post); + CU_ASSERT_EQUAL(tsd_ep_propagate_prior(&ep, free_nodes, 1000.0, 10, 1e-8), 0); + CU_ASSERT_TRUE(ep.node[9] != 0); + CU_ASSERT_EQUAL( + tsd_ep_propagate_prior(&ep, none, 0.5, 10, 1e-8), TSD_ERR_INVALID_MAX_SHAPE); + CU_ASSERT_EQUAL(tsd_ep_propagate_prior(&ep, none, 1000.0, 10, 1e-8), 0); + /* the fit succeeds, but a posterior that is improper cannot be rescaled */ + ep.posterior[4] = -5; + ep.posterior[6] = 99; + CU_ASSERT_EQUAL(tsd_ep_propagate_prior(&ep, free_nodes, 1000.0, 10, 1e-8), + TSD_ERR_INVALID_NODE_POSTERIOR); + tsd_ep_free(&ep); + ep_init(&ep, ep_parent, ep_child, ep_likelihoods, improper); + CU_ASSERT_EQUAL(tsd_ep_propagate_prior(&ep, free_nodes, 1000.0, 10, 1e-8), + TSD_ERR_NONPOSITIVE_PENALTY); + tsd_ep_free(&ep); +} + +static void +run_mutations_pass(int unphased) +{ + const tsd_id_t edges[6] = { 0, 1, 2, 3, TSD_NULL, 3 }; + const double post[8] = { 0, 0, 0, 0, 1, 1, 1, 1 }; + double mutations_posterior[12]; + double mutations_phase[6]; + tsd_ep_t ep; + int ret; + + ep_init(&ep, ep_parent, ep_child, ep_likelihoods, post); + ret = tsd_ep_propagate_mutations( + &ep, 6, edges, unphased, mutations_posterior, mutations_phase); + CU_ASSERT_EQUAL(ret, 0); + CU_ASSERT_TRUE(isfinite(mutations_phase[2])); + CU_ASSERT_TRUE(isnan(mutations_posterior[8])); + CU_ASSERT_EQUAL(mutations_phase[4], 1.0); + tsd_ep_free(&ep); + ep_init(&ep, ep_twin_parent, ep_twin_child, ep_likelihoods, post); + ret = tsd_ep_propagate_mutations( + &ep, 6, edges, unphased, mutations_posterior, mutations_phase); + CU_ASSERT_EQUAL(ret, 0); + tsd_ep_free(&ep); +} + +static void +test_propagate_mutations(void) +{ + const tsd_id_t edge[1] = { 0 }; + const tsd_id_t bad[1] = { 4 }; + const double post[8] = { 0, 0, 0, 0, 1, 1, 1, 1 }; + double mutations_posterior[2]; + double mutations_phase[1]; + tsd_ep_t ep; + + run_mutations_pass(0); + run_mutations_pass(1); + ep_init(&ep, ep_parent, ep_child, ep_huge, post); + CU_ASSERT_EQUAL(tsd_ep_propagate_mutations( + &ep, 1, edge, 1, mutations_posterior, mutations_phase), + TSD_ERR_ZERO_DIVISION); + CU_ASSERT_EQUAL( + tsd_ep_propagate_mutations(&ep, 1, bad, 0, mutations_posterior, mutations_phase), + TSD_ERR_EDGE_OUT_OF_BOUNDS); + CU_ASSERT_EQUAL( + tsd_ep_propagate_mutations(&ep, 1, bad, 1, mutations_posterior, mutations_phase), + TSD_ERR_BLOCK_OUT_OF_BOUNDS); + tsd_ep_free(&ep); +} + +/* + * Tables of expectation propagation passes: the inputs of tsd_ep_init, the state + * that a case sets after it, and the state (or mutations) expected after the pass. + * Entries of the arrays beyond the sizes of the inputs are unused. + */ +#define EP_MAX_NODES 8 +#define EP_MAX_EDGES 8 +#define EP_MAX_ORDER 8 +#define EP_MAX_MUTATIONS 4 + +typedef struct { + tsd_size_t num_nodes; + tsd_size_t num_edges; + tsd_size_t num_blocks; + double constraints[EP_MAX_NODES][2]; + tsd_id_t edges_parent[EP_MAX_EDGES]; + tsd_id_t edges_child[EP_MAX_EDGES]; + double edges_likelihood[EP_MAX_EDGES][2]; + tsd_id_t blocks_left[EP_MAX_EDGES]; + tsd_id_t blocks_right[EP_MAX_EDGES]; + double blocks_likelihood[EP_MAX_EDGES][2]; +} ep_inputs_t; + +typedef struct { + double posterior[EP_MAX_NODES][2]; + double node[EP_MAX_NODES][2][2]; + double edge[EP_MAX_EDGES][2][2]; + double block[EP_MAX_EDGES][2][2]; + double scale[EP_MAX_NODES]; + double edges_lognorm[EP_MAX_EDGES]; + double blocks_lognorm[EP_MAX_EDGES]; +} ep_state_t; + +/* The expected state `after` is only checked if `ret` is 0. */ +typedef struct { + const ep_inputs_t *inputs; + const ep_state_t *before; + tsd_size_t num_order; + tsd_id_t order[EP_MAX_ORDER]; + int unphased; + double max_shape; + double min_step; + int ret; + ep_state_t after; +} ep_likelihood_row_t; + +typedef struct { + const ep_inputs_t *inputs; + const ep_state_t *before; + ep_state_t after; +} ep_rescale_row_t; + +typedef struct { + const ep_inputs_t *inputs; + const ep_state_t *before; + uint8_t free[EP_MAX_NODES]; + double max_shape; + int64_t em_maxitt; + double em_reltol; + int ret; + ep_state_t after; +} ep_prior_row_t; + +typedef struct { + const ep_inputs_t *inputs; + const ep_state_t *before; + tsd_size_t num_mutations; + tsd_id_t mutations_edge[EP_MAX_MUTATIONS]; + int unphased; + int ret; + double posterior[EP_MAX_MUTATIONS][2]; + double phase[EP_MAX_MUTATIONS]; +} ep_mutations_row_t; + +static void +ep_setup(tsd_ep_t *ep, const ep_inputs_t *in, const ep_state_t *state) +{ + const tsd_size_t n = in->num_nodes; + const tsd_size_t e = in->num_edges; + const tsd_size_t b = in->num_blocks; + int ret; + + ret = tsd_ep_init(ep, n, e, b, &in->constraints[0][0], in->edges_parent, + in->edges_child, &in->edges_likelihood[0][0], in->blocks_left, in->blocks_right, + &in->blocks_likelihood[0][0]); + CU_ASSERT_FATAL(ret == 0); + memcpy(ep->posterior, state->posterior, 2 * n * sizeof(double)); + memcpy(ep->node, state->node, 4 * n * sizeof(double)); + memcpy(ep->edge, state->edge, 4 * e * sizeof(double)); + memcpy(ep->block, state->block, 4 * b * sizeof(double)); + memcpy(ep->scale, state->scale, n * sizeof(double)); + memcpy(ep->edges_lognorm, state->edges_lognorm, e * sizeof(double)); + memcpy(ep->blocks_lognorm, state->blocks_lognorm, b * sizeof(double)); +} + +static void +assert_ep_state(const tsd_ep_t *ep, const ep_state_t *expected) +{ + const tsd_size_t n = ep->num_nodes; + const tsd_size_t e = ep->num_edges; + const tsd_size_t b = ep->num_blocks; + + assert_array_close(ep->posterior, &expected->posterior[0][0], 2 * n); + assert_array_close(ep->node, &expected->node[0][0][0], 4 * n); + assert_array_close(ep->edge, &expected->edge[0][0][0], 4 * e); + assert_array_close(ep->block, &expected->block[0][0][0], 4 * b); + assert_array_close(ep->scale, expected->scale, n); + assert_array_close(ep->edges_lognorm, expected->edges_lognorm, e); + assert_array_close(ep->blocks_lognorm, expected->blocks_lognorm, b); +} + +static const ep_inputs_t ep_inputs_fixed_child = { .num_nodes = 2, + .num_edges = 1, + .num_blocks = 1, + .constraints = { { 0, 0 }, { 0, INFINITY } }, + .edges_parent = { 1 }, + .edges_child = { 0 }, + .edges_likelihood = { { 3, 0.1 } }, + .blocks_left = { 1 }, + .blocks_right = { 0 }, + .blocks_likelihood = { { 3, 0.1 } } }; + +static const ep_state_t ep_state_edge2_valid = { .posterior = { { 4, 0.6 }, { 4, 0.6 } }, + .edge = { { { 1, 0.1 }, { 1, 0.1 } } }, + .scale = { 1, 1 } }; + +static const ep_state_t ep_state_edge2_damped + = { .posterior = { { 23, 2.4499999999999997 }, { 23, 2.4499999999999997 } }, + .edge = { { { 22, 2.4 }, { 22, 2.4 } } }, + .scale = { 1, 1 } }; + +static const ep_inputs_t ep_inputs_fixed_child_huge_span = { .num_nodes = 2, + .num_edges = 1, + .num_blocks = 1, + .constraints = { { 0, 0 }, { 0, INFINITY } }, + .edges_parent = { 1 }, + .edges_child = { 0 }, + .edges_likelihood = { { 1, 1e+300 } }, + .blocks_left = { 1 }, + .blocks_right = { 0 }, + .blocks_likelihood = { { 1, 1e+300 } } }; + +static const ep_inputs_t ep_inputs_fixed_parent = { .num_nodes = 2, + .num_edges = 1, + .num_blocks = 1, + .constraints = { { 0, INFINITY }, { 10, 10 } }, + .edges_parent = { 1 }, + .edges_child = { 0 }, + .edges_likelihood = { { 3, 0.1 } }, + .blocks_left = { 1 }, + .blocks_right = { 0 }, + .blocks_likelihood = { { 3, 0.1 } } }; + +static const ep_inputs_t ep_inputs_fixed_parent_huge_span = { .num_nodes = 2, + .num_edges = 1, + .num_blocks = 1, + .constraints = { { 0, INFINITY }, { 10, 10 } }, + .edges_parent = { 1 }, + .edges_child = { 0 }, + .edges_likelihood = { { 1, 1e+300 } }, + .blocks_left = { 1 }, + .blocks_right = { 0 }, + .blocks_likelihood = { { 1, 1e+300 } } }; + +static const ep_inputs_t ep_inputs_both_free = { .num_nodes = 2, + .num_edges = 1, + .num_blocks = 1, + .constraints = { { 0, INFINITY }, { 0, INFINITY } }, + .edges_parent = { 1 }, + .edges_child = { 0 }, + .edges_likelihood = { { 3, 0.1 } }, + .blocks_left = { 1 }, + .blocks_right = { 0 }, + .blocks_likelihood = { { 3, 0.1 } } }; + +static const ep_inputs_t ep_inputs_both_free_huge_span = { .num_nodes = 2, + .num_edges = 1, + .num_blocks = 1, + .constraints = { { 0, INFINITY }, { 0, INFINITY } }, + .edges_parent = { 1 }, + .edges_child = { 0 }, + .edges_likelihood = { { 1, 1e+300 } }, + .blocks_left = { 1 }, + .blocks_right = { 0 }, + .blocks_likelihood = { { 1, 1e+300 } } }; + +static const ep_inputs_t ep_inputs_both_fixed = { .num_nodes = 2, + .num_edges = 1, + .num_blocks = 1, + .constraints = { { 0, 0 }, { 10, 10 } }, + .edges_parent = { 1 }, + .edges_child = { 0 }, + .edges_likelihood = { { 3, 0.1 } }, + .blocks_left = { 1 }, + .blocks_right = { 0 }, + .blocks_likelihood = { { 3, 0.1 } } }; + +static const ep_inputs_t ep_inputs_twin = { .num_nodes = 2, + .num_edges = 1, + .num_blocks = 1, + .constraints = { { 0, INFINITY }, { 0, INFINITY } }, + .edges_parent = { 1 }, + .edges_child = { 1 }, + .edges_likelihood = { { 3, 0.1 } }, + .blocks_left = { 1 }, + .blocks_right = { 1 }, + .blocks_likelihood = { { 3, 0.1 } } }; + +static const ep_state_t ep_state_block2_valid + = { .posterior = { { 4, 0.6 }, { 4, 0.6 } }, + .block = { { { 1, 0.1 }, { 1, 0.1 } } }, + .scale = { 1, 1 } }; + +static const ep_state_t ep_state_block2_damped + = { .posterior = { { 23, 2.4499999999999997 }, { 23, 2.4499999999999997 } }, + .block = { { { 22, 2.4 }, { 22, 2.4 } } }, + .scale = { 1, 1 } }; + +static const ep_inputs_t ep_inputs_twin_huge_span = { .num_nodes = 2, + .num_edges = 1, + .num_blocks = 1, + .constraints = { { 0, INFINITY }, { 0, INFINITY } }, + .edges_parent = { 1 }, + .edges_child = { 1 }, + .edges_likelihood = { { 1, 1e+300 } }, + .blocks_left = { 1 }, + .blocks_right = { 1 }, + .blocks_likelihood = { { 1, 1e+300 } } }; + +static const ep_inputs_t ep_inputs_sideways_fixed_parent = { .num_nodes = 3, + .num_edges = 1, + .num_blocks = 1, + .constraints = { { 0, INFINITY }, { 5, 5 }, { 0, INFINITY } }, + .edges_parent = { 1 }, + .edges_child = { 2 }, + .edges_likelihood = { { 3, 0.1 } }, + .blocks_left = { 1 }, + .blocks_right = { 2 }, + .blocks_likelihood = { { 3, 0.1 } } }; + +static const ep_state_t ep_state_block3_valid + = { .posterior = { { 4, 0.6 }, { 4, 0.6 }, { 4, 0.6 } }, + .block = { { { 1, 0.1 }, { 1, 0.1 } } }, + .scale = { 1, 1, 1 } }; + +static const ep_state_t ep_state_block3_damped + = { .posterior = { { 23, 2.4499999999999997 }, { 23, 2.4499999999999997 }, + { 23, 2.4499999999999997 } }, + .block = { { { 22, 2.4 }, { 22, 2.4 } } }, + .scale = { 1, 1, 1 } }; + +static const ep_inputs_t ep_inputs_sideways_fixed_parent_huge_span = { .num_nodes = 3, + .num_edges = 1, + .num_blocks = 1, + .constraints = { { 0, INFINITY }, { 5, 5 }, { 0, INFINITY } }, + .edges_parent = { 1 }, + .edges_child = { 2 }, + .edges_likelihood = { { 1, 1e+300 } }, + .blocks_left = { 1 }, + .blocks_right = { 2 }, + .blocks_likelihood = { { 1, 1e+300 } } }; + +static const ep_inputs_t ep_inputs_sideways_fixed_child = { .num_nodes = 3, + .num_edges = 1, + .num_blocks = 1, + .constraints = { { 0, INFINITY }, { 0, INFINITY }, { 5, 5 } }, + .edges_parent = { 1 }, + .edges_child = { 2 }, + .edges_likelihood = { { 3, 0.1 } }, + .blocks_left = { 1 }, + .blocks_right = { 2 }, + .blocks_likelihood = { { 3, 0.1 } } }; + +static const ep_inputs_t ep_inputs_sideways_fixed_child_huge_span = { .num_nodes = 3, + .num_edges = 1, + .num_blocks = 1, + .constraints = { { 0, INFINITY }, { 0, INFINITY }, { 5, 5 } }, + .edges_parent = { 1 }, + .edges_child = { 2 }, + .edges_likelihood = { { 1, 1e+300 } }, + .blocks_left = { 1 }, + .blocks_right = { 2 }, + .blocks_likelihood = { { 1, 1e+300 } } }; + +static const ep_inputs_t ep_inputs_unphased_both_free = { .num_nodes = 3, + .num_edges = 1, + .num_blocks = 1, + .constraints = { { 0, INFINITY }, { 0, INFINITY }, { 0, INFINITY } }, + .edges_parent = { 1 }, + .edges_child = { 2 }, + .edges_likelihood = { { 3, 0.1 } }, + .blocks_left = { 1 }, + .blocks_right = { 2 }, + .blocks_likelihood = { { 3, 0.1 } } }; + +static const ep_inputs_t ep_inputs_unphased_both_free_huge_span = { .num_nodes = 3, + .num_edges = 1, + .num_blocks = 1, + .constraints = { { 0, INFINITY }, { 0, INFINITY }, { 0, INFINITY } }, + .edges_parent = { 1 }, + .edges_child = { 2 }, + .edges_likelihood = { { 1, 1e+300 } }, + .blocks_left = { 1 }, + .blocks_right = { 2 }, + .blocks_likelihood = { { 1, 1e+300 } } }; + +static const ep_inputs_t ep_inputs_unphased_both_fixed = { .num_nodes = 3, + .num_edges = 1, + .num_blocks = 1, + .constraints = { { 0, 0 }, { 5, 5 }, { 5, 5 } }, + .edges_parent = { 1 }, + .edges_child = { 2 }, + .edges_likelihood = { { 3, 0.1 } }, + .blocks_left = { 1 }, + .blocks_right = { 2 }, + .blocks_likelihood = { { 3, 0.1 } } }; + +static const ep_state_t ep_state_block2_improper_posterior + = { .posterior = { { 4, 0.6 }, { -2, 0.6 } }, + .block = { { { 1, 0.1 }, { 1, 0.1 } } }, + .scale = { 1, 1 } }; + +static const ep_state_t ep_state_edge2_improper_parent + = { .posterior = { { 4, 0.6 }, { -2, 0.6 } }, + .edge = { { { 1, 0.1 }, { 1, 0.1 } } }, + .scale = { 1, 1 } }; + +static const ep_state_t ep_state_edge2_improper_child + = { .posterior = { { -2, 0.6 }, { 4, 0.6 } }, + .edge = { { { 1, 0.1 }, { 1, 0.1 } } }, + .scale = { 1, 1 } }; + +static const ep_state_t ep_state_edge2_infinite_rate + = { .posterior = { { 4, 0.6 }, { 3, INFINITY } }, + .edge = { { { 1, 0 }, { 1, 0.1 } } }, + .scale = { 1, 1 } }; + +static const ep_state_t ep_state_edge2_nan_parent_message + = { .posterior = { { 4, 0.6 }, { 4, 0.6 } }, + .edge = { { { 1, NAN }, { 1, 0.1 } } }, + .scale = { 1, 1 } }; + +static const ep_inputs_t ep_inputs_both_free_huge_count = { .num_nodes = 2, + .num_edges = 1, + .num_blocks = 1, + .constraints = { { 0, INFINITY }, { 0, INFINITY } }, + .edges_parent = { 1 }, + .edges_child = { 0 }, + .edges_likelihood = { { 1e+300, 0.1 } }, + .blocks_left = { 1 }, + .blocks_right = { 0 }, + .blocks_likelihood = { { 1e+300, 0.1 } } }; + +static const ep_inputs_t ep_inputs_twin_huge_count = { .num_nodes = 2, + .num_edges = 1, + .num_blocks = 1, + .constraints = { { 0, INFINITY }, { 0, INFINITY } }, + .edges_parent = { 1 }, + .edges_child = { 1 }, + .edges_likelihood = { { 1e+300, 0.1 } }, + .blocks_left = { 1 }, + .blocks_right = { 1 }, + .blocks_likelihood = { { 1e+300, 0.1 } } }; + +static const ep_inputs_t ep_inputs_twin_negative_span = { .num_nodes = 2, + .num_edges = 1, + .num_blocks = 1, + .constraints = { { 0, INFINITY }, { 0, INFINITY } }, + .edges_parent = { 1 }, + .edges_child = { 1 }, + .edges_likelihood = { { 3, -0.25 } }, + .blocks_left = { 1 }, + .blocks_right = { 1 }, + .blocks_likelihood = { { 3, -0.25 } } }; + +static const ep_inputs_t ep_inputs_small = { .num_nodes = 8, + .num_edges = 7, + .num_blocks = 2, + .constraints = { { 0, 0 }, { 0, 0 }, { 1, 1 }, { 0, INFINITY }, { 0, INFINITY }, + { 3, 3 }, { 0, INFINITY }, { 0, 0 } }, + .edges_parent = { 5, 5, 6, 3, 3, 4, 4 }, + .edges_child = { 2, 6, 7, 0, 1, 3, 5 }, + .edges_likelihood = { { 2, 0.4 }, { 1, 0.3 }, { 3, 0.5 }, { 1, 0.2 }, { 2, 0.6 }, + { 4, 0.5 }, { 0, 0.3 } }, + .blocks_left = { 3, 3 }, + .blocks_right = { 3, 6 }, + .blocks_likelihood = { { 1, 0.1 }, { 2, 0.3 } } }; + +static const ep_state_t ep_state_small_parent_below = { + .posterior = { { 0, 0 }, { 0, 0 }, { 0, 0 }, { 2, 0.8636609034779383 }, + { 2, 0.35355763983709054 }, { 0, 0 }, { 1.9999999999999998, 0.6559293439814701 }, + { 0, 0 } }, + .node = { { { 0, 0 }, { 0, 0 } }, { { 0, 0 }, { 0, 0 } }, { { 0, 0 }, { 0, 0 } }, + { { 6.7039039649712985e+159, 3.3519519824856493e+159 }, { 0, 0 } }, + { { 1, 0.11336363853632214 }, { 0, 0 } }, { { 0, 0 }, { 0, 0 } }, + { { 1, 0.5 }, { 0, 0 } }, { { 0, 0 }, { 0, 0 } } }, + .edge + = { { { 0, 0 }, { 0, 0 } }, { { 0, 0 }, { 10.011642211321844, 6.605287307126262 } }, + { { 21.44384001098297, 3.5739733351638274 }, { 0, 0 } }, + { { 6.703903964971305e+159, 1.3407807929942595e+159 }, { 0, 0 } }, + { { 4.006486409929041e+160, 1.2019459229787126e+160 }, { 0, 0 } }, + { { 6.9437839783179705, 0.524576155586376 }, + { 6.734058618746918e+159, 1.196199483833472e+160 } }, + { { 6.297584371607302, 1.8796324968024116 }, { 0, 0 } } }, + .block = { { { 6.7039039649712985e+159, 1.3407807929942595e+159 }, { 0, 0 } }, + { { 5.135700831885259e+159, 1.0968339446850352e+159 }, + { 0.2842511293334642, 0.058215267444087004 } } }, + .scale = { 1, 1, 1, 1.4916681462400413e-160, 0.14043594343309676, 1, + 0.06108785244275427, 1 }, + .edges_lognorm = { 0, 0.9159334894862647, 1.8171156304288907, 1.6342858852166113, + 1.9098718845981875, 7.151100745299825, 3.5484528956654957 }, + .blocks_lognorm = { 2.265195274615815, -2.300107063753849 } +}; + +static const ep_state_t ep_state_small_child_below + = { .posterior = { { 0, 0 }, { 0, 0 }, { 0, 0 }, { 2, 0.8636609034779383 }, + { 2, 0.35355763983709054 }, { 0, 0 }, + { 1.9999999999999998, 0.6559293439814701 }, { 0, 0 } }, + .node = { { { 0, 0 }, { 0, 0 } }, { { 0, 0 }, { 0, 0 } }, + { { 0, 0 }, { 0, 0 } }, { { 1, 0.5 }, { 0, 0 } }, + { { 1, 0.11336363853632214 }, { 0, 0 } }, { { 0, 0 }, { 0, 0 } }, + { { 6.7039039649712985e+159, 3.3519519824856493e+159 }, { 0, 0 } }, + { { 0, 0 }, { 0, 0 } } }, + .edge = { { { 0, 0 }, { 0, 0 } }, + { { 0, 0 }, { 6.711708791635453e+160, 4.428121176801834e+160 } }, + { { 1.4375744407383892e+161, 2.395957401230648e+160 }, { 0, 0 } }, + { { 1.0000000000000009, 0.19999999999999996 }, { 0, 0 } }, + { { 5.9763481560347715, 1.7929044468104316 }, { 0, 0 } }, + { { 6.9437839783179705, 0.524576155586376 }, + { 1.0044980736497988, 1.7843326665831694 } }, + { { 6.297584371607302, 1.8796324968024116 }, { 0, 0 } } }, + .block = { { { 1, 0.19999999999999996 }, { 0, 0 } }, + { { 0.7660761339541722, 0.16361122570014786 }, + { 1.90559227298618e+159, 3.9026956224027946e+158 } } }, + .scale = { 1, 1, 1, 0.18609979046343747, 0.14043594343309676, 1, + 1.4916681462400413e-160, 1 }, + .edges_lognorm + = { 0, 0.9159334894862647, 1.8171156304288907, 1.6342858852166113, + 1.9098718845981875, 7.151100745299825, 3.5484528956654957 }, + .blocks_lognorm = { 2.265195274615815, -2.300107063753849 } }; + +static const ep_state_t ep_state_small_child_just_below + = { .posterior = { { 0, 0 }, { 0, 0 }, { 0, 0 }, { 2, 0.8636609034779383 }, + { 2, 0.35355763983709054 }, { 0, 0 }, + { 1.9999999999999998, 0.6559293439814701 }, { 0, 0 } }, + .node = { { { 0, 0 }, { 0, 0 } }, { { 0, 0 }, { 0, 0 } }, + { { 0, 0 }, { 0, 0 } }, { { 1, 0.5 }, { 0, 0 } }, + { { 1, 0.11336363853632214 }, { 0, 0 } }, { { 0, 0 }, { 0, 0 } }, + { { 6.7039039649713e+153, 3.35195198248565e+153 }, { 0, 0 } }, + { { 0, 0 }, { 0, 0 } } }, + .edge = { { { 0, 0 }, { 0, 0 } }, + { { 0, 0 }, { 6.711708791635454e+154, 4.4281211768018344e+154 } }, + { { 1.4375744407383894e+155, 2.395957401230648e+154 }, { 0, 0 } }, + { { 1.0000000000000009, 0.19999999999999996 }, { 0, 0 } }, + { { 5.9763481560347715, 1.7929044468104316 }, { 0, 0 } }, + { { 6.9437839783179705, 0.524576155586376 }, + { 1.0044980736497988, 1.7843326665831694 } }, + { { 6.297584371607302, 1.8796324968024116 }, { 0, 0 } } }, + .block = { { { 1, 0.19999999999999996 }, { 0, 0 } }, + { { 0.7660761339541722, 0.16361122570014786 }, + { 1.9055922729861804e+153, 3.9026956224027947e+152 } } }, + .scale = { 1, 1, 1, 0.18609979046343747, 0.14043594343309676, 1, + 1.4916681462400412e-154, 1 }, + .edges_lognorm + = { 0, 0.9159334894862647, 1.8171156304288907, 1.6342858852166113, + 1.9098718845981875, 7.151100745299825, 3.5484528956654957 }, + .blocks_lognorm = { 2.265195274615815, -2.300107063753849 } }; + +static const ep_state_t ep_state_small_child_at + = { .posterior = { { 0, 0 }, { 0, 0 }, { 0, 0 }, { 2, 0.8636609034779383 }, + { 2, 0.35355763983709054 }, { 0, 0 }, + { 1.9999999999999998, 0.6559293439814701 }, { 0, 0 } }, + .node = { { { 0, 0 }, { 0, 0 } }, { { 0, 0 }, { 0, 0 } }, + { { 0, 0 }, { 0, 0 } }, { { 1, 0.5 }, { 0, 0 } }, + { { 1, 0.11336363853632214 }, { 0, 0 } }, { { 0, 0 }, { 0, 0 } }, + { { 6.703903964971299e+153, 3.3519519824856493e+153 }, { 0, 0 } }, + { { 0, 0 }, { 0, 0 } } }, + .edge = { { { 0, 0 }, { 0, 0 } }, + { { 0, 0 }, { 6.711708791635453e+154, 4.428121176801834e+154 } }, + { { 1.4375744407383891e+155, 2.3959574012306478e+154 }, { 0, 0 } }, + { { 1.0000000000000009, 0.19999999999999996 }, { 0, 0 } }, + { { 5.9763481560347715, 1.7929044468104316 }, { 0, 0 } }, + { { 6.9437839783179705, 0.524576155586376 }, + { 1.0044980736497988, 1.7843326665831694 } }, + { { 6.297584371607302, 1.8796324968024116 }, { 0, 0 } } }, + .block = { { { 1, 0.19999999999999996 }, { 0, 0 } }, + { { 0.7660761339541722, 0.16361122570014786 }, + { 1.90559227298618e+153, 3.902695622402794e+152 } } }, + .scale = { 1, 1, 1, 0.18609979046343747, 0.14043594343309676, 1, + 1.4916681462400413e-154, 1 }, + .edges_lognorm + = { 0, 0.9159334894862647, 1.8171156304288907, 1.6342858852166113, + 1.9098718845981875, 7.151100745299825, 3.5484528956654957 }, + .blocks_lognorm = { 2.265195274615815, -2.300107063753849 } }; + +static const ep_state_t ep_state_small_parent_above = { + .posterior = { { 0, 0 }, { 0, 0 }, { 0, 0 }, { 2, 0.8636609034779383 }, + { 2, 0.35355763983709054 }, { 0, 0 }, { 1.9999999999999998, 0.6559293439814701 }, + { 0, 0 } }, + .node = { { { 0, 0 }, { 0, 0 } }, { { 0, 0 }, { 0, 0 } }, { { 0, 0 }, { 0, 0 } }, + { { 3.3519519824856493e+153, 1.6759759912428246e+153 }, { 0, 0 } }, + { { 1, 0.11336363853632214 }, { 0, 0 } }, { { 0, 0 }, { 0, 0 } }, + { { 1, 0.5 }, { 0, 0 } }, { { 0, 0 }, { 0, 0 } } }, + .edge + = { { { 0, 0 }, { 0, 0 } }, { { 0, 0 }, { 10.011642211321844, 6.605287307126262 } }, + { { 21.44384001098297, 3.5739733351638274 }, { 0, 0 } }, + { { 3.351951982485652e+153, 6.703903964971297e+152 }, { 0, 0 } }, + { { 2.0032432049645207e+154, 6.0097296148935625e+153 }, { 0, 0 } }, + { { 6.9437839783179705, 0.524576155586376 }, + { 3.367029309373459e+153, 5.9809974191673596e+153 } }, + { { 6.297584371607302, 1.8796324968024116 }, { 0, 0 } } }, + .block = { { { 3.3519519824856493e+153, 6.703903964971297e+152 }, { 0, 0 } }, + { { 2.5678504159426292e+153, 5.484169723425176e+152 }, + { 0.2842511293334642, 0.058215267444087004 } } }, + .scale = { 1, 1, 1, 2.983336292480083e-154, 0.14043594343309676, 1, + 0.06108785244275427, 1 }, + .edges_lognorm = { 0, 0.9159334894862647, 1.8171156304288907, 1.6342858852166113, + 1.9098718845981875, 7.151100745299825, 3.5484528956654957 }, + .blocks_lognorm = { 2.265195274615815, -2.300107063753849 } +}; + +static const ep_state_t ep_state_small_skipped_below = { + .posterior = { { 0, 0 }, { 0, 0 }, { 0, 0 }, { 2, 0.8636609034779383 }, + { 2, 0.35355763983709054 }, { 0, 0 }, { 1.9999999999999998, 0.6559293439814701 }, + { 0, 0 } }, + .node = { { { 0, 0 }, { 0, 0 } }, { { 0, 0 }, { 0, 0 } }, { { 0, 0 }, { 0, 0 } }, + { { 1, 0.5 }, { 0, 0 } }, { { 1, 0.11336363853632214 }, { 0, 0 } }, + { { 0, 0 }, { 0, 0 } }, { { 1, 0.5 }, { 0, 0 } }, { { 0, 0 }, { 0, 0 } } }, + .edge + = { { { 0, 0 }, { 0, 0 } }, { { 0, 0 }, { 10.011642211321844, 6.605287307126262 } }, + { { 21.44384001098297, 3.5739733351638274 }, { 0, 0 } }, + { { 1.0000000000000009, 0.19999999999999996 }, { 0, 0 } }, + { { 5.9763481560347715, 1.7929044468104316 }, { 0, 0 } }, + { { 6.9437839783179705, 0.524576155586376 }, + { 1.0044980736497988, 1.7843326665831694 } }, + { { 6.297584371607302, 1.8796324968024116 }, { 0, 0 } } }, + .block = { { { 1, 0.19999999999999996 }, { 0, 0 } }, + { { 0.7660761339541722, 0.16361122570014786 }, + { 0.2842511293334642, 0.058215267444087004 } } }, + .scale = { 1, 1, 1.4916681462400413e-160, 0.18609979046343747, 0.14043594343309676, + 1, 0.06108785244275427, 1 }, + .edges_lognorm = { 0, 0.9159334894862647, 1.8171156304288907, 1.6342858852166113, + 1.9098718845981875, 7.151100745299825, 3.5484528956654957 }, + .blocks_lognorm = { 2.265195274615815, -2.300107063753849 } +}; + +static const ep_state_t ep_state_small_random_scales = { + .posterior = { { 0, 0 }, { 0, 0 }, { 0, 0 }, { 2, 0.8636609034779383 }, + { 2, 0.35355763983709054 }, { 0, 0 }, { 1.9999999999999998, 0.6559293439814701 }, + { 0, 0 } }, + .node = { { { 0, 0 }, { 0, 0 } }, { { 0, 0 }, { 0, 0 } }, { { 0, 0 }, { 0, 0 } }, + { { 1, 0.5 }, { 0, 0 } }, { { 1, 0.11336363853632214 }, { 0, 0 } }, + { { 0, 0 }, { 0, 0 } }, { { 1, 0.5 }, { 0, 0 } }, { { 0, 0 }, { 0, 0 } } }, + .edge + = { { { 0, 0 }, { 0, 0 } }, { { 0, 0 }, { 10.011642211321844, 6.605287307126262 } }, + { { 21.44384001098297, 3.5739733351638274 }, { 0, 0 } }, + { { 1.0000000000000009, 0.19999999999999996 }, { 0, 0 } }, + { { 5.9763481560347715, 1.7929044468104316 }, { 0, 0 } }, + { { 6.9437839783179705, 0.524576155586376 }, + { 1.0044980736497988, 1.7843326665831694 } }, + { { 6.297584371607302, 1.8796324968024116 }, { 0, 0 } } }, + .block = { { { 1, 0.19999999999999996 }, { 0, 0 } }, + { { 0.7660761339541722, 0.16361122570014786 }, + { 0.2842511293334642, 0.058215267444087004 } } }, + .scale + = { 1.4554425309821815, 0.9046800706458055, 0.5614602859042921, 0.5247914532927936, + 1.7199053588004087, 1.8691333659165825, 1.4099536636507697, 1.5942448414759975 }, + .edges_lognorm = { 0, 0.9159334894862647, 1.8171156304288907, 1.6342858852166113, + 1.9098718845981875, 7.151100745299825, 3.5484528956654957 }, + .blocks_lognorm = { 2.265195274615815, -2.300107063753849 } +}; + +static const ep_state_t ep_state_small_scales_1em160 = { + .posterior = { { 0, 0 }, { 0, 0 }, { 0, 0 }, { 2, 0.8636609034779383 }, + { 2, 0.35355763983709054 }, { 0, 0 }, { 1.9999999999999998, 0.6559293439814701 }, + { 0, 0 } }, + .node = { { { 0, 0 }, { 0, 0 } }, { { 0, 0 }, { 0, 0 } }, { { 0, 0 }, { 0, 0 } }, + { { 1, 0.5 }, { 0, 0 } }, { { 1, 0.11336363853632214 }, { 0, 0 } }, + { { 0, 0 }, { 0, 0 } }, { { 1, 0.5 }, { 0, 0 } }, { { 0, 0 }, { 0, 0 } } }, + .edge + = { { { 0, 0 }, { 0, 0 } }, { { 0, 0 }, { 10.011642211321844, 6.605287307126262 } }, + { { 21.44384001098297, 3.5739733351638274 }, { 0, 0 } }, + { { 1.0000000000000009, 0.19999999999999996 }, { 0, 0 } }, + { { 5.9763481560347715, 1.7929044468104316 }, { 0, 0 } }, + { { 6.9437839783179705, 0.524576155586376 }, + { 1.0044980736497988, 1.7843326665831694 } }, + { { 6.297584371607302, 1.8796324968024116 }, { 0, 0 } } }, + .block = { { { 1, 0.19999999999999996 }, { 0, 0 } }, + { { 0.7660761339541722, 0.16361122570014786 }, + { 0.2842511293334642, 0.058215267444087004 } } }, + .scale = { 1e-160, 1e-160, 1e-160, 1e-160, 1e-160, 1e-160, 1e-160, 1e-160 }, + .edges_lognorm = { 0, 0.9159334894862647, 1.8171156304288907, 1.6342858852166113, + 1.9098718845981875, 7.151100745299825, 3.5484528956654957 }, + .blocks_lognorm = { 2.265195274615815, -2.300107063753849 } +}; + +static const ep_state_t ep_state_small_scales_1e100 = { + .posterior = { { 0, 0 }, { 0, 0 }, { 0, 0 }, { 2, 0.8636609034779383 }, + { 2, 0.35355763983709054 }, { 0, 0 }, { 1.9999999999999998, 0.6559293439814701 }, + { 0, 0 } }, + .node = { { { 0, 0 }, { 0, 0 } }, { { 0, 0 }, { 0, 0 } }, { { 0, 0 }, { 0, 0 } }, + { { 1, 0.5 }, { 0, 0 } }, { { 1, 0.11336363853632214 }, { 0, 0 } }, + { { 0, 0 }, { 0, 0 } }, { { 1, 0.5 }, { 0, 0 } }, { { 0, 0 }, { 0, 0 } } }, + .edge + = { { { 0, 0 }, { 0, 0 } }, { { 0, 0 }, { 10.011642211321844, 6.605287307126262 } }, + { { 21.44384001098297, 3.5739733351638274 }, { 0, 0 } }, + { { 1.0000000000000009, 0.19999999999999996 }, { 0, 0 } }, + { { 5.9763481560347715, 1.7929044468104316 }, { 0, 0 } }, + { { 6.9437839783179705, 0.524576155586376 }, + { 1.0044980736497988, 1.7843326665831694 } }, + { { 6.297584371607302, 1.8796324968024116 }, { 0, 0 } } }, + .block = { { { 1, 0.19999999999999996 }, { 0, 0 } }, + { { 0.7660761339541722, 0.16361122570014786 }, + { 0.2842511293334642, 0.058215267444087004 } } }, + .scale = { 1e+100, 1e+100, 1e+100, 1e+100, 1e+100, 1e+100, 1e+100, 1e+100 }, + .edges_lognorm = { 0, 0.9159334894862647, 1.8171156304288907, 1.6342858852166113, + 1.9098718845981875, 7.151100745299825, 3.5484528956654957 }, + .blocks_lognorm = { 2.265195274615815, -2.300107063753849 } +}; + +static const ep_state_t ep_state_small = { + .posterior = { { 0, 0 }, { 0, 0 }, { 0, 0 }, { 2, 0.8636609034779383 }, + { 2, 0.35355763983709054 }, { 0, 0 }, { 1.9999999999999998, 0.6559293439814701 }, + { 0, 0 } }, + .node = { { { 0, 0 }, { 0, 0 } }, { { 0, 0 }, { 0, 0 } }, { { 0, 0 }, { 0, 0 } }, + { { 1, 0.5 }, { 0, 0 } }, { { 1, 0.11336363853632214 }, { 0, 0 } }, + { { 0, 0 }, { 0, 0 } }, { { 1, 0.5 }, { 0, 0 } }, { { 0, 0 }, { 0, 0 } } }, + .edge + = { { { 0, 0 }, { 0, 0 } }, { { 0, 0 }, { 10.011642211321844, 6.605287307126262 } }, + { { 21.44384001098297, 3.5739733351638274 }, { 0, 0 } }, + { { 1.0000000000000009, 0.19999999999999996 }, { 0, 0 } }, + { { 5.9763481560347715, 1.7929044468104316 }, { 0, 0 } }, + { { 6.9437839783179705, 0.524576155586376 }, + { 1.0044980736497988, 1.7843326665831694 } }, + { { 6.297584371607302, 1.8796324968024116 }, { 0, 0 } } }, + .block = { { { 1, 0.19999999999999996 }, { 0, 0 } }, + { { 0.7660761339541722, 0.16361122570014786 }, + { 0.2842511293334642, 0.058215267444087004 } } }, + .scale + = { 1, 1, 1, 0.18609979046343747, 0.14043594343309676, 1, 0.06108785244275427, 1 }, + .edges_lognorm = { 0, 0.9159334894862647, 1.8171156304288907, 1.6342858852166113, + 1.9098718845981875, 7.151100745299825, 3.5484528956654957 }, + .blocks_lognorm = { 2.265195274615815, -2.300107063753849 } +}; + +static const ep_state_t ep_state_small_zero = { + .edge + = { { { 0, 0 }, { 0, 0 } }, { { 0, 0 }, { 10.011642211321844, 6.605287307126262 } }, + { { 21.44384001098297, 3.5739733351638274 }, { 0, 0 } }, + { { 1.0000000000000009, 0.19999999999999996 }, { 0, 0 } }, + { { 5.9763481560347715, 1.7929044468104316 }, { 0, 0 } }, + { { 6.9437839783179705, 0.524576155586376 }, + { 1.0044980736497988, 1.7843326665831694 } }, + { { 6.297584371607302, 1.8796324968024116 }, { 0, 0 } } }, + .block = { { { 1, 0.19999999999999996 }, { 0, 0 } }, + { { 0.7660761339541722, 0.16361122570014786 }, + { 0.2842511293334642, 0.058215267444087004 } } }, + .scale + = { 1, 1, 1, 0.18609979046343747, 0.14043594343309676, 1, 0.06108785244275427, 1 }, + .edges_lognorm = { 0, 0.9159334894862647, 1.8171156304288907, 1.6342858852166113, + 1.9098718845981875, 7.151100745299825, 3.5484528956654957 }, + .blocks_lognorm = { 2.265195274615815, -2.300107063753849 } +}; + +static const ep_state_t ep_state_small_negative_rate = { + .posterior = { { 0, 0 }, { 0, 0 }, { 0, 0 }, { 2, 0.8636609034779383 }, + { 2, 0.35355763983709054 }, { 0, 0 }, { 1.9999999999999998, 0.6559293439814701 }, + { 0, 0 } }, + .node = { { { 0, 0 }, { 0, 0 } }, { { 0, 0 }, { 0, 0 } }, { { 0, 0 }, { 0, 0 } }, + { { 1, 0.5 }, { 0, 0 } }, { { 1, 9.638256465887746 }, { 0, 0 } }, + { { 0, 0 }, { 0, 0 } }, { { 1, 0.5 }, { 0, 0 } }, { { 0, 0 }, { 0, 0 } } }, + .edge + = { { { 0, 0 }, { 0, 0 } }, { { 0, 0 }, { 10.011642211321844, 6.605287307126262 } }, + { { 21.44384001098297, 3.5739733351638274 }, { 0, 0 } }, + { { 1.0000000000000009, 0.19999999999999996 }, { 0, 0 } }, + { { 5.9763481560347715, 1.7929044468104316 }, { 0, 0 } }, + { { 6.9437839783179705, 0.524576155586376 }, + { 1.0044980736497988, 1.7843326665831694 } }, + { { 6.297584371607302, 1.8796324968024116 }, { 0, 0 } } }, + .block = { { { 1, 0.19999999999999996 }, { 0, 0 } }, + { { 0.7660761339541722, 0.16361122570014786 }, + { 0.2842511293334642, 0.058215267444087004 } } }, + .scale + = { 1, 1, 1, 0.18609979046343747, 0.14043594343309676, 1, 0.06108785244275427, 1 }, + .edges_lognorm = { 0, 0.9159334894862647, 1.8171156304288907, 1.6342858852166113, + 1.9098718845981875, 7.151100745299825, 3.5484528956654957 }, + .blocks_lognorm = { 2.265195274615815, -2.300107063753849 } +}; + +static const ep_inputs_t ep_inputs_both_fixed_equal = { .num_nodes = 2, + .num_edges = 1, + .num_blocks = 1, + .constraints = { { 5, 5 }, { 5, 5 } }, + .edges_parent = { 1 }, + .edges_child = { 0 }, + .edges_likelihood = { { 3, 0.1 } }, + .blocks_left = { 1 }, + .blocks_right = { 0 }, + .blocks_likelihood = { { 3, 0.1 } } }; + +static const ep_inputs_t ep_inputs_both_fixed_adjacent = { .num_nodes = 2, + .num_edges = 1, + .num_blocks = 1, + .constraints = { { 5, 5 }, { 5.000000000000001, 5.000000000000001 } }, + .edges_parent = { 1 }, + .edges_child = { 0 }, + .edges_likelihood = { { 3, 0.1 } }, + .blocks_left = { 1 }, + .blocks_right = { 0 }, + .blocks_likelihood = { { 3, 0.1 } } }; + +static const ep_inputs_t ep_inputs_both_fixed_inverted = { .num_nodes = 2, + .num_edges = 1, + .num_blocks = 1, + .constraints = { { 10, 10 }, { 0, 0 } }, + .edges_parent = { 1 }, + .edges_child = { 0 }, + .edges_likelihood = { { 3, 0.1 } }, + .blocks_left = { 1 }, + .blocks_right = { 0 }, + .blocks_likelihood = { { 3, 0.1 } } }; + +/* One edge (block) in each branch of the likelihood pass, with valid, damped and failing + * projections, and failures of the damping; expected values are those of the reference + * implementation, except for the divisions by zero that the library reports and the + * reference implementation computes in floating point. */ +static const ep_likelihood_row_t ep_likelihood_branch_rows[] = { + /* fixed_child, valid */ + { &ep_inputs_fixed_child, &ep_state_edge2_valid, 1, { 0 }, 0, 1e+300, 0.1, 0, + { .posterior = { { 4, 0.6 }, { 6.000000000000001, 0.6 } }, + .edge = { { { 3.000000000000001, 0.09999999999999998 }, { 1, 0.1 } } }, + .scale = { 1, 1 }, + .edges_lognorm = { 10.155030578372036 } } }, + /* fixed_child, damped */ + { &ep_inputs_fixed_child, &ep_state_edge2_damped, 1, { 0 }, 0, 1e+300, 0.1, 0, + { .posterior + = { { 23, 2.4499999999999997 }, { 5.543750000000004, 0.3368750000000001 } }, + .edge = { { { 4.543750000000002, 0.2868750000000003 }, { 22, 2.4 } } }, + .scale = { 1, 1 }, + .edges_lognorm = { 12.861044274991544 } } }, + /* fixed_child, projection_fails */ + { &ep_inputs_fixed_child_huge_span, &ep_state_edge2_valid, 1, { 0 }, 0, 1e+300, 0.1, + 0, + { .posterior = { { 4, 0.6 }, { 3, 0.5 } }, + .edge = { { { 0, 0 }, { 1, 0.1 } } }, + .scale = { 1, 1 }, + .edges_lognorm = { NAN } } }, + /* fixed_parent, valid */ + { &ep_inputs_fixed_parent, &ep_state_edge2_valid, 1, { 0 }, 0, 1e+300, 0.1, 0, + { .posterior = { { 5.237205312432989, 1.5864148365014894 }, { 4, 0.6 } }, + .edge = { { { 1, 0.1 }, { 2.237205312432989, 1.0864148365014894 } } }, + .scale = { 1, 1 }, + .edges_lognorm = { 8.392109396313824 } } }, + /* fixed_parent, damped */ + { &ep_inputs_fixed_parent, &ep_state_edge2_damped, 1, { 0 }, 0, 1e+300, 0.1, 0, + { .posterior + = { { 6.2859049125683475, 1.59224630406714 }, { 23, 2.4499999999999997 } }, + .edge = { { { 22, 2.4 }, { 5.285904912568346, 1.5422463040671401 } } }, + .scale = { 1, 1 }, + .edges_lognorm = { 8.819556344925992 } } }, + /* fixed_parent, projection_fails */ + { &ep_inputs_fixed_parent_huge_span, &ep_state_edge2_valid, 1, { 0 }, 0, 1e+300, 0.1, + 0, + { .posterior = { { 3, 0.5 }, { 4, 0.6 } }, + .edge = { { { 1, 0.1 }, { 0, 0 } } }, + .scale = { 1, 1 }, + .edges_lognorm = { NAN } } }, + /* both_free, valid */ + { &ep_inputs_both_free, &ep_state_edge2_valid, 1, { 0 }, 0, 1e+300, 0.1, 0, + { .posterior = { { 3.340990263647014, 0.8598058362787732 }, + { 9.208111413904785, 0.6820200768549769 } }, + .edge = { { { 6.208111413904785, 0.1820200768549769 }, + { 0.3409902636470141, 0.35980583627877316 } } }, + .scale = { 1, 1 }, + .edges_lognorm = { 13.088415737608075 } } }, + /* both_free, damped */ + { &ep_inputs_both_free, &ep_state_edge2_damped, 1, { 0 }, 0, 1e+300, 0.1, 0, + { .posterior = { { 3.191895535259021, 0.4211261303374999 }, + { 8.897091337020257, 0.3785701047221309 } }, + .edge = { { { 7.897091337020255, 0.3285701047221311 }, + { 2.191895535259019, 0.3711261303375002 } } }, + .scale = { 1, 1 }, + .edges_lognorm = { 18.31439947231522 } } }, + /* both_free, projection_fails */ + { &ep_inputs_both_free_huge_span, &ep_state_edge2_valid, 1, { 0 }, 0, 1e+300, 0.1, 0, + { .posterior = { { 3, 0.5 }, { 3, 0.5 } }, + .scale = { 1, 1 }, + .edges_lognorm = { NAN } } }, + /* both_fixed, valid */ + { &ep_inputs_both_fixed, &ep_state_edge2_valid, 1, { 0 }, 0, 1e+300, 0.1, 0, + { .posterior = { { 4, 0.6 }, { 4, 0.6 } }, + .edge = { { { 1, 0.1 }, { 1, 0.1 } } }, + .scale = { 1, 1 } } }, + /* twin, valid */ + { &ep_inputs_twin, &ep_state_block2_valid, 1, { 0 }, 1, 1e+300, 0.1, 0, + { .posterior = { { 4, 0.6 }, { 5.999999999999999, 0.6999999999999998 } }, + .block = { { { 2.999999999999999, 0.19999999999999984 }, { 1, 0.1 } } }, + .scale = { 1, 1 }, + .blocks_lognorm = { 11.155417361261065 } } }, + /* twin, damped */ + { &ep_inputs_twin, &ep_state_block2_damped, 1, { 0 }, 1, 1e+300, 0.1, 0, + { .posterior + = { { 23, 2.4499999999999997 }, { 5.543750000000005, 0.4287500000000001 } }, + .block = { { { 4.543750000000003, 0.37875000000000036 }, { 22, 2.4 } } }, + .scale = { 1, 1 }, + .blocks_lognorm = { 13.193426982114381 } } }, + /* twin, projection_fails */ + { &ep_inputs_twin_huge_span, &ep_state_block2_valid, 1, { 0 }, 1, 1e+300, 0.1, 0, + { .posterior = { { 4, 0.6 }, { 3, 0.5 } }, + .block = { { { 0, 0 }, { 1, 0.1 } } }, + .scale = { 1, 1 }, + .blocks_lognorm = { NAN } } }, + /* sideways_fixed_parent, valid */ + { &ep_inputs_sideways_fixed_parent, &ep_state_block3_valid, 1, { 0 }, 1, 1e+300, 0.1, + 0, + { .posterior + = { { 4, 0.6 }, { 4, 0.6 }, { 4.231122949265319, 0.5314156646872705 } }, + .block = { { { 1, 0.1 }, { 1.2311229492653188, 0.03141566468727053 } } }, + .scale = { 1, 1, 1 }, + .blocks_lognorm = { 10.937231963805417 } } }, + /* sideways_fixed_parent, damped */ + { &ep_inputs_sideways_fixed_parent, &ep_state_block3_damped, 1, { 0 }, 1, 1e+300, + 0.1, 0, + { .posterior = { { 23, 2.4499999999999997 }, { 23, 2.4499999999999997 }, + { 4.3632947068956724, 0.308279227260758 } }, + .block = { { { 22, 2.4 }, { 3.3632947068956707, 0.25827922726075825 } } }, + .scale = { 1, 1, 1 }, + .blocks_lognorm = { 13.159832686323291 } } }, + /* sideways_fixed_parent, projection_fails */ + { &ep_inputs_sideways_fixed_parent_huge_span, &ep_state_block3_valid, 1, { 0 }, 1, + 1e+300, 0.1, TSD_ERR_ZERO_DIVISION, { .scale = { 0 } } }, + /* sideways_fixed_child, valid */ + { &ep_inputs_sideways_fixed_child, &ep_state_block3_valid, 1, { 0 }, 1, 1e+300, 0.1, + 0, + { .posterior + = { { 4, 0.6 }, { 4.231122949265319, 0.5314156646872705 }, { 4, 0.6 } }, + .block = { { { 1.2311229492653188, 0.03141566468727053 }, { 1, 0.1 } } }, + .scale = { 1, 1, 1 }, + .blocks_lognorm = { 10.937231963805417 } } }, + /* sideways_fixed_child, damped */ + { &ep_inputs_sideways_fixed_child, &ep_state_block3_damped, 1, { 0 }, 1, 1e+300, 0.1, + 0, + { .posterior = { { 23, 2.4499999999999997 }, + { 4.3632947068956724, 0.308279227260758 }, { 23, 2.4499999999999997 } }, + .block = { { { 3.3632947068956707, 0.25827922726075825 }, { 22, 2.4 } } }, + .scale = { 1, 1, 1 }, + .blocks_lognorm = { 13.159832686323291 } } }, + /* sideways_fixed_child, projection_fails */ + { &ep_inputs_sideways_fixed_child_huge_span, &ep_state_block3_valid, 1, { 0 }, 1, + 1e+300, 0.1, TSD_ERR_ZERO_DIVISION, { .scale = { 0 } } }, + /* unphased_both_free, valid */ + { &ep_inputs_unphased_both_free, &ep_state_block3_valid, 1, { 0 }, 1, 1e+300, 0.1, 0, + { .posterior = { { 4, 0.6 }, { 3.7142857142857224, 0.5142857142857151 }, + { 3.7142857142857224, 0.5142857142857151 } }, + .block = { { { 0.7142857142857224, 0.014285714285715123 }, + { 0.7142857142857224, 0.014285714285715123 } } }, + .scale = { 1, 1, 1 }, + .blocks_lognorm = { 15.781852011892113 } } }, + /* unphased_both_free, damped */ + { &ep_inputs_unphased_both_free, &ep_state_block3_damped, 1, { 0 }, 1, 1e+300, 0.1, + 0, + { .posterior + = { { 23, 2.4499999999999997 }, { 3.4503846153846256, 0.2902307692307697 }, + { 3.4503846153846256, 0.2902307692307697 } }, + .block = { { { 2.450384615384624, 0.24023076923076994 }, + { 2.450384615384624, 0.24023076923076994 } } }, + .scale = { 1, 1, 1 }, + .blocks_lognorm = { 20.176250719010007 } } }, + /* unphased_both_free, projection_fails */ + { &ep_inputs_unphased_both_free_huge_span, &ep_state_block3_valid, 1, { 0 }, 1, + 1e+300, 0.1, 0, + { .posterior = { { 4, 0.6 }, { 3, 0.5 }, { 3, 0.5 } }, + .scale = { 1, 1, 1 }, + .blocks_lognorm = { NAN } } }, + /* unphased_both_fixed, valid */ + { &ep_inputs_unphased_both_fixed, &ep_state_block3_valid, 1, { 0 }, 1, 1e+300, 0.1, + 0, + { .posterior = { { 4, 0.6 }, { 4, 0.6 }, { 4, 0.6 } }, + .block = { { { 1, 0.1 }, { 1, 0.1 } } }, + .scale = { 1, 1, 1 } } }, + /* twin, in a phased pass */ + { &ep_inputs_twin, &ep_state_block2_valid, 1, { 0 }, 0, 1e+300, 0.1, + TSD_ERR_TWIN_EDGE_IN_PHASED_PASS, { .scale = { 0 } } }, + /* twin, improper posterior */ + { &ep_inputs_twin, &ep_state_block2_improper_posterior, 1, { 0 }, 1, 1e+300, 0.1, + TSD_ERR_INVALID_NODE_POSTERIOR, { .scale = { 0 } } }, + /* both_free, improper parent posterior */ + { &ep_inputs_both_free, &ep_state_edge2_improper_parent, 1, { 0 }, 0, 1e+300, 0.1, + TSD_ERR_INVALID_NODE_POSTERIOR, { .scale = { 0 } } }, + /* both_free, improper child posterior */ + { &ep_inputs_both_free, &ep_state_edge2_improper_child, 1, { 0 }, 0, 1e+300, 0.1, + TSD_ERR_INVALID_NODE_POSTERIOR, { .scale = { 0 } } }, + /* fixed_child, infinite posterior rate */ + { &ep_inputs_fixed_child, &ep_state_edge2_infinite_rate, 1, { 0 }, 0, 1e+300, 0.1, + TSD_ERR_ZERO_DIVISION, { .scale = { 0 } } }, + /* both_free, NaN rate of the parent message */ + { &ep_inputs_both_free, &ep_state_edge2_nan_parent_message, 1, { 0 }, 0, 1e+300, 0.1, + TSD_ERR_INVALID_NODE_POSTERIOR, { .scale = { 0 } } }, + /* both_free, huge mutation count */ + { &ep_inputs_both_free_huge_count, &ep_state_edge2_valid, 1, { 0 }, 0, 1e+300, 0.1, + TSD_ERR_INVALID_HYPERGEO, { .scale = { 0 } } }, + /* twin, huge mutation count */ + { &ep_inputs_twin_huge_count, &ep_state_block2_valid, 1, { 0 }, 1, 1e+300, 0.1, 0, + { .posterior = { { 4, 0.6 }, { NAN, 0 } }, + .block = { { { INFINITY, 0.19999999999999996 }, { 1, 0.1 } } }, + .scale = { 1, 0 }, + .blocks_lognorm = { 6.908253500227124e+302 } } }, + /* twin, span that cancels the cavity rate */ + { &ep_inputs_twin_negative_span, &ep_state_block2_valid, 1, { 0 }, 1, 1e+300, 0.1, + TSD_ERR_ZERO_DIVISION, { .scale = { 0 } } }, +}; + +/* A node scale below sqrt(DBL_MIN) rescales the factors mid-pass (even for a skipped + * edge); expected values are those of the reference implementation. */ +static const ep_likelihood_row_t ep_likelihood_tiny_scale_rows[] = { + /* parent 3, scale far below sqrt(DBL_MIN) */ + { &ep_inputs_small, &ep_state_small_parent_below, 7, { 6, 0, 3, 1, 2, 4, 5 }, 0, + 1000, 0.1, 0, + { .posterior + = { { 0, 0 }, { 0, 0 }, { 0, 0 }, { 0.5843090800906015, 0.4141118212927717 }, + { 4.576142402519787, 0.6250950421834373 }, { 0, 0 }, + { 7.309791285287766, 4.2876962848892894 }, { 0, 0 } }, + .node = { { { 0, 0 }, { 0, 0 } }, { { 0, 0 }, { 0, 0 } }, + { { 0, 0 }, { 0, 0 } }, { { 1, 0.5 }, { 0, 0 } }, + { { 0.14043594343309676, 0.015920329528856966 }, { 0, 0 } }, + { { 0, 0 }, { 0, 0 } }, + { { 0.06108785244275427, 0.030543926221377134 }, { 0, 0 } }, + { { 0, 0 }, { 0, 0 } } }, + .edge = { { { 0, 0 }, { 0, 0 } }, + { { 0, 0 }, { 4.231339141799602, 3.7535961130003725 } }, + { { 3.000000000000001, 0.49999999999999956 }, { 0, 0 } }, + { { 0.9999999999999996, 0.19999999999999984 }, { 0, 0 } }, + { { 4.252444351577177, 1.2757333054731532 }, { 0, 0 } }, + { { 2.587238914201411, 0.12364381294339392 }, + { 1.3127109581979957, 1.8519547257352813 } }, + { { 1.848467544885279, 0.48553089971118635 }, { 0, 0 } } }, + .block = { { { 1, 0.19999999999999996 }, { 0, 0 } }, + { { 0.7660761339541722, 0.16361122570014786 }, + { 0.01736429104540892, 0.003556245667539863 } } }, + .scale = { 1, 1, 1, 1, 1, 1, 1, 1 }, + .edges_lognorm + = { 0, 0.8096806220619701, -2.9410830709207385, 1.132872360686421, + 1.2487332284559316, 6.048304970158144, 2.570276182534273 }, + .blocks_lognorm = { 2.265195274615815, -2.300107063753849 } } }, + /* child 6, scale far below sqrt(DBL_MIN) */ + { &ep_inputs_small, &ep_state_small_child_below, 7, { 6, 0, 3, 1, 2, 4, 5 }, 0, 1000, + 0.1, 0, + { .posterior + = { { 0, 0 }, { 0, 0 }, { 0, 0 }, { 3.7958421321682865, 1.333492106759158 }, + { 10.065420818105734, 1.1253981016342018 }, { 0, 0 }, + { 0.771929388179595, 2.9935415583239657 }, { 0, 0 } }, + .node + = { { { 0, 0 }, { 0, 0 } }, { { 0, 0 }, { 0, 0 } }, { { 0, 0 }, { 0, 0 } }, + { { 0.18609979046343747, 0.09304989523171874 }, { 0, 0 } }, + { { 0.14043594343309676, 0.015920329528856966 }, { 0, 0 } }, + { { 0, 0 }, { 0, 0 } }, { { 1, 0.5 }, { 0, 0 } }, + { { 0, 0 }, { 0, 0 } } }, + .edge = { { { 0, 0 }, { 0, 0 } }, + { { 0, 0 }, { 14.85515137621622, 9.954829484254553 } }, + { { 15.37226023426819, 2.562043372378031 }, { 0, 0 } }, + { { 0.9999999999999999, 0.19999999999999973 }, { 0, 0 } }, + { { 1.9999999999999993, 0.5999999999999999 }, { 0, 0 } }, + { { 8.076517329787357, 0.6239468723941586 }, + { 0.28107594323350105, 0.3727742386144888 } }, + { { 1.848467544885279, 0.48553089971118635 }, { 0, 0 } } }, + .block = { { { 0.18609979046343747, 0.03721995809268749 }, { 0, 0 } }, + { { 0.1425666080079117, 0.030448014820263693 }, + { 0.2842511293334642, 0.05821526744408701 } } }, + .scale = { 1, 1, 1, 1, 1, 1, 1, 1 }, + .edges_lognorm + = { 0, 1.3769145175226662, -2.0216361082280465, 1.4634663891508815, + 1.5314734140184885, 8.186688217624864, 2.570276182534273 }, + .blocks_lognorm = { 2.265195274615815, -2.300107063753849 } } }, + /* child 6, scale just below sqrt(DBL_MIN) */ + { &ep_inputs_small, &ep_state_small_child_just_below, 7, { 6, 0, 3, 1, 2, 4, 5 }, 0, + 1000, 0.1, 0, + { .posterior + = { { 0, 0 }, { 0, 0 }, { 0, 0 }, { 3.7958421321682865, 1.333492106759158 }, + { 10.065420818105734, 1.1253981016342018 }, { 0, 0 }, + { 0.771929388179595, 2.9935415583239657 }, { 0, 0 } }, + .node + = { { { 0, 0 }, { 0, 0 } }, { { 0, 0 }, { 0, 0 } }, { { 0, 0 }, { 0, 0 } }, + { { 0.18609979046343747, 0.09304989523171874 }, { 0, 0 } }, + { { 0.14043594343309676, 0.015920329528856966 }, { 0, 0 } }, + { { 0, 0 }, { 0, 0 } }, { { 1, 0.5 }, { 0, 0 } }, + { { 0, 0 }, { 0, 0 } } }, + .edge = { { { 0, 0 }, { 0, 0 } }, + { { 0, 0 }, { 14.85515137621622, 9.954829484254553 } }, + { { 15.37226023426819, 2.562043372378031 }, { 0, 0 } }, + { { 0.9999999999999999, 0.19999999999999973 }, { 0, 0 } }, + { { 1.9999999999999993, 0.5999999999999999 }, { 0, 0 } }, + { { 8.076517329787357, 0.6239468723941586 }, + { 0.28107594323350105, 0.3727742386144888 } }, + { { 1.848467544885279, 0.48553089971118635 }, { 0, 0 } } }, + .block = { { { 0.18609979046343747, 0.03721995809268749 }, { 0, 0 } }, + { { 0.1425666080079117, 0.030448014820263693 }, + { 0.2842511293334642, 0.058215267444087004 } } }, + .scale = { 1, 1, 1, 1, 1, 1, 1, 1 }, + .edges_lognorm + = { 0, 1.3769145175226662, -2.0216361082280465, 1.4634663891508815, + 1.5314734140184885, 8.186688217624864, 2.570276182534273 }, + .blocks_lognorm = { 2.265195274615815, -2.300107063753849 } } }, + /* child 6, scale at sqrt(DBL_MIN) */ + { &ep_inputs_small, &ep_state_small_child_at, 7, { 6, 0, 3, 1, 2, 4, 5 }, 0, 1000, + 0.1, 0, + { .posterior + = { { 0, 0 }, { 0, 0 }, { 0, 0 }, { 3.7958421321682865, 1.333492106759158 }, + { 10.065420818105734, 1.1253981016342018 }, { 0, 0 }, + { 0.771929388179595, 2.9935415583239657 }, { 0, 0 } }, + .node = { { { 0, 0 }, { 0, 0 } }, { { 0, 0 }, { 0, 0 } }, + { { 0, 0 }, { 0, 0 } }, { { 1, 0.5 }, { 0, 0 } }, + { { 1, 0.11336363853632214 }, { 0, 0 } }, { { 0, 0 }, { 0, 0 } }, + { { 6.703903964971299e+153, 3.3519519824856493e+153 }, { 0, 0 } }, + { { 0, 0 }, { 0, 0 } } }, + .edge = { { { 0, 0 }, { 0, 0 } }, + { { 0, 0 }, { 9.958750821126476e+154, 6.673622085010729e+154 } }, + { { 1.0305415633508114e+155, 1.717569272251352e+154 }, { 0, 0 } }, + { { 5.37346118181937, 1.0746922363638727 }, { 0, 0 } }, + { { 10.746922363638738, 3.224076709091622 }, { 0, 0 } }, + { { 57.51032913902832, 4.442928620274516 }, + { 1.510350670108483, 2.003087900777227 } }, + { { 13.162353594796642, 3.457312194028815 }, { 0, 0 } } }, + .block = { { { 1, 0.19999999999999996 }, { 0, 0 } }, + { { 0.7660761339541722, 0.16361122570014786 }, + { 1.90559227298618e+153, 3.902695622402794e+152 } } }, + .scale = { 1, 1, 1, 0.18609979046343747, 0.14043594343309676, 1, + 1.4916681462400413e-154, 1 }, + .edges_lognorm + = { 0, 1.3769145175226662, -2.0216361082280465, 1.4634663891508815, + 1.5314734140184885, 8.186688217624864, 2.570276182534273 }, + .blocks_lognorm = { 2.265195274615815, -2.300107063753849 } } }, + /* parent 3, scale above sqrt(DBL_MIN) */ + { &ep_inputs_small, &ep_state_small_parent_above, 7, { 6, 0, 3, 1, 2, 4, 5 }, 0, + 1000, 0.1, 0, + { .posterior + = { { 0, 0 }, { 0, 0 }, { 0, 0 }, { 0.584309080090585, 0.41411182129276836 }, + { 4.5761424025197845, 0.6250950421834371 }, { 0, 0 }, + { 7.309791285287766, 4.2876962848892894 }, { 0, 0 } }, + .node + = { { { 0, 0 }, { 0, 0 } }, { { 0, 0 }, { 0, 0 } }, { { 0, 0 }, { 0, 0 } }, + { { 3.3519519824856493e+153, 1.6759759912428246e+153 }, { 0, 0 } }, + { { 1, 0.11336363853632214 }, { 0, 0 } }, { { 0, 0 }, { 0, 0 } }, + { { 1, 0.5 }, { 0, 0 } }, { { 0, 0 }, { 0, 0 } } }, + .edge = { { { 0, 0 }, { 0, 0 } }, + { { 0, 0 }, { 69.26645761143446, 61.445867924689054 } }, + { { 49.10960002745744, 8.184933337909563 }, { 0, 0 } }, + { { 3.3519519824856478e+153, 6.703903964971293e+152 }, { 0, 0 } }, + { { 1.425398927467902e+154, 4.276196782403706e+153 }, { 0, 0 } }, + { { 18.422911193201482, 0.8804285421580647 }, + { 4.400144098762354e+153, 6.207663314402032e+153 } }, + { { 13.162353594796642, 3.457312194028815 }, { 0, 0 } } }, + .block = { { { 3.3519519824856493e+153, 6.703903964971297e+152 }, { 0, 0 } }, + { { 2.5678504159426292e+153, 5.484169723425176e+152 }, + { 0.2842511293334642, 0.058215267444087004 } } }, + .scale = { 1, 1, 1, 2.983336292480083e-154, 0.14043594343309676, 1, + 0.06108785244275427, 1 }, + .edges_lognorm + = { 0, 0.8096806220619701, -2.9410830709207385, 1.132872360686421, + 1.2487332284559312, 6.048304970158142, 2.570276182534273 }, + .blocks_lognorm = { 2.265195274615815, -2.300107063753849 } } }, + /* child of a skipped edge between fixed nodes 2, scale far below sqrt(DBL_MIN) */ + { &ep_inputs_small, &ep_state_small_skipped_below, 7, { 6, 0, 3, 1, 2, 4, 5 }, 0, + 1000, 0.1, 0, + { .posterior + = { { 0, 0 }, { 0, 0 }, { 0, 0 }, { 3.7958421321682865, 1.333492106759158 }, + { 10.065420818105734, 1.1253981016342018 }, { 0, 0 }, + { 7.309791285287766, 4.2876962848892894 }, { 0, 0 } }, + .node + = { { { 0, 0 }, { 0, 0 } }, { { 0, 0 }, { 0, 0 } }, { { 0, 0 }, { 0, 0 } }, + { { 0.18609979046343747, 0.09304989523171874 }, { 0, 0 } }, + { { 0.14043594343309676, 0.015920329528856966 }, { 0, 0 } }, + { { 0, 0 }, { 0, 0 } }, + { { 0.06108785244275427, 0.030543926221377134 }, { 0, 0 } }, + { { 0, 0 }, { 0, 0 } } }, + .edge = { { { 0, 0 }, { 0, 0 } }, + { { 0, 0 }, { 4.231339141799602, 3.7535961130003725 } }, + { { 3.000000000000001, 0.49999999999999956 }, { 0, 0 } }, + { { 0.9999999999999998, 0.19999999999999973 }, { 0, 0 } }, + { { 1.9999999999999993, 0.5999999999999999 }, { 0, 0 } }, + { { 8.076517329787357, 0.6239468723941586 }, + { 0.28107594323350105, 0.3727742386144888 } }, + { { 1.848467544885279, 0.48553089971118635 }, { 0, 0 } } }, + .block = { { { 0.18609979046343747, 0.03721995809268749 }, { 0, 0 } }, + { { 0.1425666080079117, 0.030448014820263693 }, + { 0.01736429104540892, 0.003556245667539863 } } }, + .scale = { 1, 1, 1, 1, 1, 1, 1, 1 }, + .edges_lognorm + = { 0, 0.8096806220619701, -2.9410830709207385, 1.4634663891508815, + 1.5314734140184885, 8.186688217624864, 2.570276182534273 }, + .blocks_lognorm = { 2.265195274615815, -2.300107063753849 } } }, +}; + +/* Rescaling the factors of the small state; expected values are those of the reference + * implementation. */ +static const ep_rescale_row_t ep_rescale_rows[] = { + /* random scales */ + { &ep_inputs_small, &ep_state_small_random_scales, + { .posterior = { { 0, 0 }, { 0, 0 }, { 0, 0 }, { 2, 0.8636609034779383 }, + { 2, 0.35355763983709054 }, { 0, 0 }, + { 1.9999999999999998, 0.6559293439814701 }, { 0, 0 } }, + .node + = { { { 0, 0 }, { 0, 0 } }, { { 0, 0 }, { 0, 0 } }, { { 0, 0 }, { 0, 0 } }, + { { 0.5247914532927936, 0.2623957266463968 }, { 0, 0 } }, + { { 1.7199053588004087, 0.19497472941173297 }, { 0, 0 } }, + { { 0, 0 }, { 0, 0 } }, + { { 1.4099536636507697, 0.7049768318253848 }, { 0, 0 } }, + { { 0, 0 }, { 0, 0 } } }, + .edge = { { { 0, 0 }, { 0, 0 } }, + { { 0, 0 }, { 14.115951615013927, 9.3131490381486 } }, + { { 30.2348207862264, 5.039136797704399 }, { 0, 0 } }, + { { 0.5247914532927941, 0.1049582906585587 }, { 0, 0 } }, + { { 3.1363364341891953, 0.9409009302567586 }, { 0, 0 } }, + { { 11.942651274661499, 0.9022213410919251 }, + { 0.5271520039004896, 0.9364025332539873 } }, + { { 10.831249108225103, 3.2327900038258597 }, { 0, 0 } } }, + .block = { { { 0.5247914532927936, 0.1049582906585587 }, { 0, 0 } }, + { { 0.4020302076707349, 0.08586177291019587 }, + { 0.4007809212005866, 0.08208082961319985 } } }, + .scale = { 1, 1, 1, 1, 1, 1, 1, 1 }, + .edges_lognorm + = { 0, 0.9159334894862647, 1.8171156304288907, 1.6342858852166113, + 1.9098718845981875, 7.151100745299825, 3.5484528956654957 }, + .blocks_lognorm = { 2.265195274615815, -2.300107063753849 } } }, + /* scales 1e-160 */ + { &ep_inputs_small, &ep_state_small_scales_1em160, + { .posterior = { { 0, 0 }, { 0, 0 }, { 0, 0 }, { 2, 0.8636609034779383 }, + { 2, 0.35355763983709054 }, { 0, 0 }, + { 1.9999999999999998, 0.6559293439814701 }, { 0, 0 } }, + .node = { { { 0, 0 }, { 0, 0 } }, { { 0, 0 }, { 0, 0 } }, + { { 0, 0 }, { 0, 0 } }, { { 1e-160, 5e-161 }, { 0, 0 } }, + { { 1e-160, 1.1336363853632214e-161 }, { 0, 0 } }, + { { 0, 0 }, { 0, 0 } }, { { 1e-160, 5e-161 }, { 0, 0 } }, + { { 0, 0 }, { 0, 0 } } }, + .edge = { { { 0, 0 }, { 0, 0 } }, + { { 0, 0 }, { 1.0011642211321843e-159, 6.605287307126262e-160 } }, + { { 2.1443840010982971e-159, 3.5739733351638275e-160 }, { 0, 0 } }, + { { 1.000000000000001e-160, 1.9999999999999997e-161 }, { 0, 0 } }, + { { 5.976348156034772e-160, 1.7929044468104316e-160 }, { 0, 0 } }, + { { 6.943783978317971e-160, 5.24576155586376e-161 }, + { 1.0044980736497989e-160, 1.7843326665831694e-160 } }, + { { 6.297584371607302e-160, 1.8796324968024114e-160 }, { 0, 0 } } }, + .block = { { { 1e-160, 1.9999999999999997e-161 }, { 0, 0 } }, + { { 7.660761339541722e-161, 1.6361122570014785e-161 }, + { 2.842511293334642e-161, 5.8215267444087e-162 } } }, + .scale = { 1, 1, 1, 1, 1, 1, 1, 1 }, + .edges_lognorm + = { 0, 0.9159334894862647, 1.8171156304288907, 1.6342858852166113, + 1.9098718845981875, 7.151100745299825, 3.5484528956654957 }, + .blocks_lognorm = { 2.265195274615815, -2.300107063753849 } } }, + /* scales 1e100 */ + { &ep_inputs_small, &ep_state_small_scales_1e100, + { .posterior = { { 0, 0 }, { 0, 0 }, { 0, 0 }, { 2, 0.8636609034779383 }, + { 2, 0.35355763983709054 }, { 0, 0 }, + { 1.9999999999999998, 0.6559293439814701 }, { 0, 0 } }, + .node = { { { 0, 0 }, { 0, 0 } }, { { 0, 0 }, { 0, 0 } }, + { { 0, 0 }, { 0, 0 } }, { { 1e+100, 5e+99 }, { 0, 0 } }, + { { 1e+100, 1.1336363853632215e+99 }, { 0, 0 } }, { { 0, 0 }, { 0, 0 } }, + { { 1e+100, 5e+99 }, { 0, 0 } }, { { 0, 0 }, { 0, 0 } } }, + .edge = { { { 0, 0 }, { 0, 0 } }, + { { 0, 0 }, { 1.0011642211321844e+101, 6.605287307126262e+100 } }, + { { 2.144384001098297e+101, 3.5739733351638276e+100 }, { 0, 0 } }, + { { 1.000000000000001e+100, 1.9999999999999997e+99 }, { 0, 0 } }, + { { 5.9763481560347715e+100, 1.7929044468104318e+100 }, { 0, 0 } }, + { { 6.9437839783179705e+100, 5.24576155586376e+99 }, + { 1.0044980736497988e+100, 1.7843326665831695e+100 } }, + { { 6.297584371607302e+100, 1.8796324968024115e+100 }, { 0, 0 } } }, + .block = { { { 1e+100, 1.9999999999999997e+99 }, { 0, 0 } }, + { { 7.660761339541722e+99, 1.6361122570014786e+99 }, + { 2.842511293334642e+99, 5.8215267444087e+98 } } }, + .scale = { 1, 1, 1, 1, 1, 1, 1, 1 }, + .edges_lognorm + = { 0, 0.9159334894862647, 1.8171156304288907, 1.6342858852166113, + 1.9098718845981875, 7.151100745299825, 3.5484528956654957 }, + .blocks_lognorm = { 2.265195274615815, -2.300107063753849 } } }, +}; + +/* The prior pass on the small state, with and without EM iterations, and its failures; + * expected values are those of the reference implementation. */ +static const ep_prior_row_t ep_prior_rows[] = { + /* the root */ + { &ep_inputs_small, &ep_state_small, { 0, 0, 0, 0, 1, 0, 0, 0 }, 1000, 10, 1e-08, 0, + { .posterior = { { 0, 0 }, { 0, 0 }, { 0, 0 }, { 2, 0.8636609034779383 }, + { 2, 0.5192046941817232 }, { 0, 0 }, + { 1.9999999999999998, 0.6559293439814701 }, { 0, 0 } }, + .node = { { { 0, 0 }, { 0, 0 } }, { { 0, 0 }, { 0, 0 } }, + { { 0, 0 }, { 0, 0 } }, { { 1, 0.5 }, { 0, 0 } }, + { { 1.0000000000000007, 1.2928839970373238 }, { 0, 0 } }, + { { 0, 0 }, { 0, 0 } }, { { 1, 0.5 }, { 0, 0 } }, + { { 0, 0 }, { 0, 0 } } }, + .edge = { { { 0, 0 }, { 0, 0 } }, + { { 0, 0 }, { 10.011642211321844, 6.605287307126262 } }, + { { 21.44384001098297, 3.5739733351638274 }, { 0, 0 } }, + { { 1.0000000000000009, 0.19999999999999996 }, { 0, 0 } }, + { { 5.9763481560347715, 1.7929044468104316 }, { 0, 0 } }, + { { 6.9437839783179705, 0.524576155586376 }, + { 1.0044980736497988, 1.7843326665831694 } }, + { { 6.297584371607302, 1.8796324968024116 }, { 0, 0 } } }, + .block = { { { 1, 0.19999999999999996 }, { 0, 0 } }, + { { 0.7660761339541722, 0.16361122570014786 }, + { 0.2842511293334642, 0.058215267444087004 } } }, + .scale = { 1, 1, 1, 0.18609979046343747, 0.14043594343309676, 1, + 0.06108785244275427, 1 }, + .edges_lognorm + = { 0, 0.9159334894862647, 1.8171156304288907, 1.6342858852166113, + 1.9098718845981875, 7.151100745299825, 3.5484528956654957 }, + .blocks_lognorm = { 2.265195274615815, -2.300107063753849 } } }, + /* free internal nodes */ + { &ep_inputs_small, &ep_state_small, { 0, 0, 0, 1, 1, 0, 1, 0 }, 1000, 10, 1e-08, 0, + { .posterior = { { 0, 0 }, { 0, 0 }, { 0, 0 }, { 2, 1.057316890860762 }, + { 2, 0.624343192922776 }, { 0, 0 }, + { 1.9999999999999998, 0.9120913003746354 }, { 0, 0 } }, + .node + = { { { 0, 0 }, { 0, 0 } }, { { 0, 0 }, { 0, 0 } }, { { 0, 0 }, { 0, 0 } }, + { { 0.9999999999999996, 1.5406029308285045 }, { 0, 0 } }, + { { 1.0000000000000007, 2.041542041202067 }, { 0, 0 } }, + { { 0, 0 }, { 0, 0 } }, + { { 1.0000000000000002, 4.693337073573113 }, { 0, 0 } }, + { { 0, 0 }, { 0, 0 } } }, + .edge = { { { 0, 0 }, { 0, 0 } }, + { { 0, 0 }, { 10.011642211321844, 6.605287307126262 } }, + { { 21.44384001098297, 3.5739733351638274 }, { 0, 0 } }, + { { 1.0000000000000009, 0.19999999999999996 }, { 0, 0 } }, + { { 5.9763481560347715, 1.7929044468104316 }, { 0, 0 } }, + { { 6.9437839783179705, 0.524576155586376 }, + { 1.0044980736497988, 1.7843326665831694 } }, + { { 6.297584371607302, 1.8796324968024116 }, { 0, 0 } } }, + .block = { { { 1, 0.19999999999999996 }, { 0, 0 } }, + { { 0.7660761339541722, 0.16361122570014786 }, + { 0.2842511293334642, 0.058215267444087004 } } }, + .scale = { 1, 1, 1, 0.18609979046343747, 0.14043594343309676, 1, + 0.06108785244275427, 1 }, + .edges_lognorm + = { 0, 0.9159334894862647, 1.8171156304288907, 1.6342858852166113, + 1.9098718845981875, 7.151100745299825, 3.5484528956654957 }, + .blocks_lognorm = { 2.265195274615815, -2.300107063753849 } } }, + /* no EM iteration */ + { &ep_inputs_small, &ep_state_small, { 0, 0, 0, 1, 1, 0, 1, 0 }, 1000, -1, 1e-08, 0, + { .posterior = { { 0, 0 }, { 0, 0 }, { 0, 0 }, { 2, 0.9489678090196197 }, + { 2, 0.5159941110816337 }, { 0, 0 }, + { 1.9999999999999998, 0.803742218533493 }, { 0, 0 } }, + .node + = { { { 0, 0 }, { 0, 0 } }, { { 0, 0 }, { 0, 0 } }, { { 0, 0 }, { 0, 0 } }, + { { 0.9999999999999996, 0.9583933454693566 }, { 0, 0 } }, + { { 1.0000000000000007, 1.270022448764114 }, { 0, 0 } }, + { { 0, 0 }, { 0, 0 } }, + { { 1.0000000000000002, 2.919677049386196 }, { 0, 0 } }, + { { 0, 0 }, { 0, 0 } } }, + .edge = { { { 0, 0 }, { 0, 0 } }, + { { 0, 0 }, { 10.011642211321844, 6.605287307126262 } }, + { { 21.44384001098297, 3.5739733351638274 }, { 0, 0 } }, + { { 1.0000000000000009, 0.19999999999999996 }, { 0, 0 } }, + { { 5.9763481560347715, 1.7929044468104316 }, { 0, 0 } }, + { { 6.9437839783179705, 0.524576155586376 }, + { 1.0044980736497988, 1.7843326665831694 } }, + { { 6.297584371607302, 1.8796324968024116 }, { 0, 0 } } }, + .block = { { { 1, 0.19999999999999996 }, { 0, 0 } }, + { { 0.7660761339541722, 0.16361122570014786 }, + { 0.2842511293334642, 0.058215267444087004 } } }, + .scale = { 1, 1, 1, 0.18609979046343747, 0.14043594343309676, 1, + 0.06108785244275427, 1 }, + .edges_lognorm + = { 0, 0.9159334894862647, 1.8171156304288907, 1.6342858852166113, + 1.9098718845981875, 7.151100745299825, 3.5484528956654957 }, + .blocks_lognorm = { 2.265195274615815, -2.300107063753849 } } }, + /* EM iterations reach the maximum */ + { &ep_inputs_small, &ep_state_small, { 0, 0, 0, 1, 1, 0, 1, 0 }, 1000, 3, 0, 0, + { .posterior = { { 0, 0 }, { 0, 0 }, { 0, 0 }, { 2, 1.0553334660423712 }, + { 2, 0.6223597681043852 }, { 0, 0 }, + { 1.9999999999999998, 0.9101078755562446 }, { 0, 0 } }, + .node + = { { { 0, 0 }, { 0, 0 } }, { { 0, 0 }, { 0, 0 } }, { { 0, 0 }, { 0, 0 } }, + { { 0.9999999999999996, 1.5299450745598246 }, { 0, 0 } }, + { { 1.0000000000000007, 2.0274186994855237 }, { 0, 0 } }, + { { 0, 0 }, { 0, 0 } }, + { { 1.0000000000000002, 4.660868673734545 }, { 0, 0 } }, + { { 0, 0 }, { 0, 0 } } }, + .edge = { { { 0, 0 }, { 0, 0 } }, + { { 0, 0 }, { 10.011642211321844, 6.605287307126262 } }, + { { 21.44384001098297, 3.5739733351638274 }, { 0, 0 } }, + { { 1.0000000000000009, 0.19999999999999996 }, { 0, 0 } }, + { { 5.9763481560347715, 1.7929044468104316 }, { 0, 0 } }, + { { 6.9437839783179705, 0.524576155586376 }, + { 1.0044980736497988, 1.7843326665831694 } }, + { { 6.297584371607302, 1.8796324968024116 }, { 0, 0 } } }, + .block = { { { 1, 0.19999999999999996 }, { 0, 0 } }, + { { 0.7660761339541722, 0.16361122570014786 }, + { 0.2842511293334642, 0.058215267444087004 } } }, + .scale = { 1, 1, 1, 0.18609979046343747, 0.14043594343309676, 1, + 0.06108785244275427, 1 }, + .edges_lognorm + = { 0, 0.9159334894862647, 1.8171156304288907, 1.6342858852166113, + 1.9098718845981875, 7.151100745299825, 3.5484528956654957 }, + .blocks_lognorm = { 2.265195274615815, -2.300107063753849 } } }, + /* NaN tolerance: no EM iteration */ + { &ep_inputs_small, &ep_state_small, { 0, 0, 0, 1, 1, 0, 1, 0 }, 1000, 10, NAN, 0, + { .posterior = { { 0, 0 }, { 0, 0 }, { 0, 0 }, { 2, 0.9489678090196197 }, + { 2, 0.5159941110816337 }, { 0, 0 }, + { 1.9999999999999998, 0.803742218533493 }, { 0, 0 } }, + .node + = { { { 0, 0 }, { 0, 0 } }, { { 0, 0 }, { 0, 0 } }, { { 0, 0 }, { 0, 0 } }, + { { 0.9999999999999996, 0.9583933454693566 }, { 0, 0 } }, + { { 1.0000000000000007, 1.270022448764114 }, { 0, 0 } }, + { { 0, 0 }, { 0, 0 } }, + { { 1.0000000000000002, 2.919677049386196 }, { 0, 0 } }, + { { 0, 0 }, { 0, 0 } } }, + .edge = { { { 0, 0 }, { 0, 0 } }, + { { 0, 0 }, { 10.011642211321844, 6.605287307126262 } }, + { { 21.44384001098297, 3.5739733351638274 }, { 0, 0 } }, + { { 1.0000000000000009, 0.19999999999999996 }, { 0, 0 } }, + { { 5.9763481560347715, 1.7929044468104316 }, { 0, 0 } }, + { { 6.9437839783179705, 0.524576155586376 }, + { 1.0044980736497988, 1.7843326665831694 } }, + { { 6.297584371607302, 1.8796324968024116 }, { 0, 0 } } }, + .block = { { { 1, 0.19999999999999996 }, { 0, 0 } }, + { { 0.7660761339541722, 0.16361122570014786 }, + { 0.2842511293334642, 0.058215267444087004 } } }, + .scale = { 1, 1, 1, 0.18609979046343747, 0.14043594343309676, 1, + 0.06108785244275427, 1 }, + .edges_lognorm + = { 0, 0.9159334894862647, 1.8171156304288907, 1.6342858852166113, + 1.9098718845981875, 7.151100745299825, 3.5484528956654957 }, + .blocks_lognorm = { 2.265195274615815, -2.300107063753849 } } }, + /* the cap on the shape binds */ + { &ep_inputs_small, &ep_state_small, { 0, 0, 0, 1, 1, 0, 1, 0 }, 1.5, 10, 1e-08, 0, + { .posterior = { { 0, 0 }, { 0, 0 }, { 0, 0 }, { 0.5, 0.2643292227151905 }, + { 0.5, 0.156085798230694 }, { 0, 0 }, { 0.5, 0.2280228250936589 }, + { 0, 0 } }, + .node + = { { { 0, 0 }, { 0, 0 } }, { { 0, 0 }, { 0, 0 } }, { { 0, 0 }, { 0, 0 } }, + { { 0.9999999999999996, 1.5406029308285045 }, { 0, 0 } }, + { { 1.0000000000000007, 2.041542041202067 }, { 0, 0 } }, + { { 0, 0 }, { 0, 0 } }, + { { 1.0000000000000002, 4.693337073573113 }, { 0, 0 } }, + { { 0, 0 }, { 0, 0 } } }, + .edge = { { { 0, 0 }, { 0, 0 } }, + { { 0, 0 }, { 10.011642211321844, 6.605287307126262 } }, + { { 21.44384001098297, 3.5739733351638274 }, { 0, 0 } }, + { { 1.0000000000000009, 0.19999999999999996 }, { 0, 0 } }, + { { 5.9763481560347715, 1.7929044468104316 }, { 0, 0 } }, + { { 6.9437839783179705, 0.524576155586376 }, + { 1.0044980736497988, 1.7843326665831694 } }, + { { 6.297584371607302, 1.8796324968024116 }, { 0, 0 } } }, + .block = { { { 1, 0.19999999999999996 }, { 0, 0 } }, + { { 0.7660761339541722, 0.16361122570014786 }, + { 0.2842511293334642, 0.058215267444087004 } } }, + .scale = { 1, 1, 1, 0.04652494761585937, 0.03510898585827419, 1, + 0.01527196311068857, 1 }, + .edges_lognorm + = { 0, 0.9159334894862647, 1.8171156304288907, 1.6342858852166113, + 1.9098718845981875, 7.151100745299825, 3.5484528956654957 }, + .blocks_lognorm = { 2.265195274615815, -2.300107063753849 } } }, + /* no free nodes */ + { &ep_inputs_small, &ep_state_small, { 0, 0, 0, 0, 0, 0, 0, 0 }, 1000, 10, 1e-08, 0, + { .posterior = { { 0, 0 }, { 0, 0 }, { 0, 0 }, { 2, 0.8636609034779383 }, + { 2, 0.35355763983709054 }, { 0, 0 }, + { 1.9999999999999998, 0.6559293439814701 }, { 0, 0 } }, + .node = { { { 0, 0 }, { 0, 0 } }, { { 0, 0 }, { 0, 0 } }, + { { 0, 0 }, { 0, 0 } }, { { 1, 0.5 }, { 0, 0 } }, + { { 1, 0.11336363853632214 }, { 0, 0 } }, { { 0, 0 }, { 0, 0 } }, + { { 1, 0.5 }, { 0, 0 } }, { { 0, 0 }, { 0, 0 } } }, + .edge = { { { 0, 0 }, { 0, 0 } }, + { { 0, 0 }, { 10.011642211321844, 6.605287307126262 } }, + { { 21.44384001098297, 3.5739733351638274 }, { 0, 0 } }, + { { 1.0000000000000009, 0.19999999999999996 }, { 0, 0 } }, + { { 5.9763481560347715, 1.7929044468104316 }, { 0, 0 } }, + { { 6.9437839783179705, 0.524576155586376 }, + { 1.0044980736497988, 1.7843326665831694 } }, + { { 6.297584371607302, 1.8796324968024116 }, { 0, 0 } } }, + .block = { { { 1, 0.19999999999999996 }, { 0, 0 } }, + { { 0.7660761339541722, 0.16361122570014786 }, + { 0.2842511293334642, 0.058215267444087004 } } }, + .scale = { 1, 1, 1, 0.18609979046343747, 0.14043594343309676, 1, + 0.06108785244275427, 1 }, + .edges_lognorm + = { 0, 0.9159334894862647, 1.8171156304288907, 1.6342858852166113, + 1.9098718845981875, 7.151100745299825, 3.5484528956654957 }, + .blocks_lognorm = { 2.265195274615815, -2.300107063753849 } } }, + /* zero posteriors */ + { &ep_inputs_small, &ep_state_small_zero, { 0, 0, 0, 0, 1, 0, 0, 0 }, 1000, 10, + 1e-08, TSD_ERR_NONPOSITIVE_PENALTY, { .scale = { 0 } } }, + /* negative cavity rate */ + { &ep_inputs_small, &ep_state_small_negative_rate, { 0, 0, 0, 0, 1, 0, 0, 0 }, 1000, + 10, 1e-08, TSD_ERR_NONPOSITIVE_PENALTY, { .scale = { 0 } } }, + /* max_shape below one */ + { &ep_inputs_small, &ep_state_small, { 0, 0, 0, 0, 1, 0, 0, 0 }, 0.5, 10, 1e-08, + TSD_ERR_INVALID_MAX_SHAPE, { .scale = { 0 } } }, +}; + +/* The mutations above one edge (block) in each branch, with fixed ages, and on the small + * state; expected values are those of the reference implementation, except for the + * divisions by zero that the library reports and the reference implementation computes + * in floating point. */ +static const ep_mutations_row_t ep_mutations_rows[] = { + /* fixed_child, valid */ + { &ep_inputs_fixed_child, &ep_state_edge2_valid, 1, { 0 }, 0, 0, + { { 0.9090909090909085, 0.32727272727272716 } }, { 1 } }, + /* fixed_child, projection_fails */ + { &ep_inputs_fixed_child_huge_span, &ep_state_edge2_valid, 1, { 0 }, 0, 0, + { { NAN, NAN } }, { NAN } }, + /* fixed_parent, valid */ + { &ep_inputs_fixed_parent, &ep_state_edge2_valid, 1, { 0 }, 0, 0, + { { 11.458120369143545, 1.788464840386457 } }, { 1 } }, + /* fixed_parent, projection_fails */ + { &ep_inputs_fixed_parent_huge_span, &ep_state_edge2_valid, 1, { 0 }, 0, 0, + { { NAN, NAN } }, { NAN } }, + /* both_free, valid */ + { &ep_inputs_both_free, &ep_state_edge2_valid, 1, { 0 }, 0, 0, + { { 4.300199693233025, 0.529589210511545 } }, { 1 } }, + /* both_free, projection_fails */ + { &ep_inputs_both_free_huge_span, &ep_state_edge2_valid, 1, { 0 }, 0, 0, + { { NAN, NAN } }, { NAN } }, + /* both_fixed, valid */ + { &ep_inputs_both_fixed, &ep_state_edge2_valid, 1, { 0 }, 0, 0, + { { 2.0000000000000004, 0.6000000000000001 } }, { 1 } }, + /* twin, valid */ + { &ep_inputs_twin, &ep_state_block2_valid, 1, { 0 }, 1, 0, + { { 0.9090909090909081, 0.3818181818181816 } }, { 0.5 } }, + /* twin, projection_fails */ + { &ep_inputs_twin_huge_span, &ep_state_block2_valid, 1, { 0 }, 1, 0, + { { NAN, NAN } }, { NAN } }, + /* sideways_fixed_parent, valid */ + { &ep_inputs_sideways_fixed_parent, &ep_state_block3_valid, 1, { 0 }, 1, 0, + { { 0.4631781099265906, 0.3438769242905483 } }, { 0.36382649552564394 } }, + /* sideways_fixed_parent, projection_fails */ + { &ep_inputs_sideways_fixed_parent_huge_span, &ep_state_block3_valid, 1, { 0 }, 1, + TSD_ERR_ZERO_DIVISION, { { 0 } }, { 0 } }, + /* sideways_fixed_child, valid */ + { &ep_inputs_sideways_fixed_child, &ep_state_block3_valid, 1, { 0 }, 1, 0, + { { 0.4631781099265906, 0.3438769242905483 } }, { 0.36382649552564394 } }, + /* sideways_fixed_child, projection_fails */ + { &ep_inputs_sideways_fixed_child_huge_span, &ep_state_block3_valid, 1, { 0 }, 1, + TSD_ERR_ZERO_DIVISION, { { 0 } }, { 0 } }, + /* unphased_both_free, valid */ + { &ep_inputs_unphased_both_free, &ep_state_block3_valid, 1, { 0 }, 1, 0, + { { 0.7515923566878997, 0.3439490445859875 } }, { 0.5 } }, + /* unphased_both_free, projection_fails */ + { &ep_inputs_unphased_both_free_huge_span, &ep_state_block3_valid, 1, { 0 }, 1, 0, + { { NAN, NAN } }, { NAN } }, + /* unphased_both_fixed, valid */ + { &ep_inputs_unphased_both_fixed, &ep_state_block3_valid, 1, { 0 }, 1, 0, + { { 1.9999999999999991, 1.1999999999999997 } }, { 0.5 } }, + /* twin, in a phased pass */ + { &ep_inputs_twin, &ep_state_block2_valid, 1, { 0 }, 0, 0, + { { 1.0000000000000013, 0.40000000000000024 } }, { 0.5 } }, + /* equal fixed ages */ + { &ep_inputs_both_fixed_equal, &ep_state_edge2_valid, 1, { 0 }, 0, 0, + { { NAN, NAN } }, { NAN } }, + /* adjacent fixed ages */ + { &ep_inputs_both_fixed_adjacent, &ep_state_edge2_valid, 1, { 0 }, 0, 0, + { { 3.802951800684688e+32, 7.605903601369376e+31 } }, { 1 } }, + /* inverted fixed ages */ + { &ep_inputs_both_fixed_inverted, &ep_state_edge2_valid, 1, { 0 }, 0, 0, + { { 2.0000000000000004, 0.6000000000000001 } }, { 1 } }, + /* edges of each branch, and a root */ + { &ep_inputs_small, &ep_state_small, 4, { 3, -1, 1, 6 }, 0, 0, + { { 0.46427524306562473, 0.788165385679627 }, { NAN, NAN }, + { 17.735867699826013, 8.054195276382863 }, + { 3.653465150153581, 0.9407997952233624 } }, + { 1, 1, 1, 1 } }, + /* blocks, and a root */ + { &ep_inputs_small, &ep_state_small, 3, { 1, -1, 0 }, 1, 0, + { { 0.5085725565286765, 0.6842153617467468 }, { NAN, NAN }, + { 0.4642752430656252, 0.7881653856796274 } }, + { 0.43985052500362354, 1, 0.5 } }, +}; + +static void +run_likelihood_rows(const ep_likelihood_row_t *rows, size_t num_rows) +{ + const ep_likelihood_row_t *row; + tsd_ep_t ep; + size_t j; + int ret; + + for (j = 0; j < num_rows; j++) { + row = rows + j; + ep_setup(&ep, row->inputs, row->before); + ret = tsd_ep_propagate_likelihood(&ep, row->num_order, row->order, row->unphased, + row->max_shape, row->min_step); + CU_ASSERT_EQUAL(ret, row->ret); + if (ret == 0 && row->ret == 0) { + assert_ep_state(&ep, &row->after); + } + tsd_ep_free(&ep); + } +} + +static void +test_propagate_likelihood_branches(void) +{ + run_likelihood_rows(ep_likelihood_branch_rows, + sizeof(ep_likelihood_branch_rows) / sizeof(ep_likelihood_branch_rows[0])); +} + +static void +test_propagate_likelihood_tiny_scale(void) +{ + run_likelihood_rows( + ep_likelihood_tiny_scale_rows, sizeof(ep_likelihood_tiny_scale_rows) + / sizeof(ep_likelihood_tiny_scale_rows[0])); +} + +static void +test_rescale_factors(void) +{ + const size_t num_rows = sizeof(ep_rescale_rows) / sizeof(ep_rescale_rows[0]); + const ep_rescale_row_t *row; + tsd_ep_t ep; + size_t j; + + for (j = 0; j < num_rows; j++) { + row = ep_rescale_rows + j; + ep_setup(&ep, row->inputs, row->before); + tsd_ep_rescale_factors(&ep); + assert_ep_state(&ep, &row->after); + tsd_ep_free(&ep); + } +} + +static void +test_propagate_prior_table(void) +{ + const size_t num_rows = sizeof(ep_prior_rows) / sizeof(ep_prior_rows[0]); + const ep_prior_row_t *row; + tsd_ep_t ep; + size_t j; + int ret; + + for (j = 0; j < num_rows; j++) { + row = ep_prior_rows + j; + ep_setup(&ep, row->inputs, row->before); + ret = tsd_ep_propagate_prior( + &ep, row->free, row->max_shape, row->em_maxitt, row->em_reltol); + CU_ASSERT_EQUAL(ret, row->ret); + if (ret == 0 && row->ret == 0) { + assert_ep_state(&ep, &row->after); + } + tsd_ep_free(&ep); + } +} + +static void +test_propagate_mutations_table(void) +{ + const size_t num_rows = sizeof(ep_mutations_rows) / sizeof(ep_mutations_rows[0]); + const ep_mutations_row_t *row; + double posterior[2 * EP_MAX_MUTATIONS]; + double phase[EP_MAX_MUTATIONS]; + tsd_ep_t ep; + size_t j; + int ret; + + for (j = 0; j < num_rows; j++) { + row = ep_mutations_rows + j; + ep_setup(&ep, row->inputs, row->before); + ret = tsd_ep_propagate_mutations(&ep, row->num_mutations, row->mutations_edge, + row->unphased, posterior, phase); + CU_ASSERT_EQUAL(ret, row->ret); + if (ret == 0 && row->ret == 0) { + assert_array_close(posterior, &row->posterior[0][0], 2 * row->num_mutations); + assert_array_close(phase, row->phase, row->num_mutations); + } + tsd_ep_free(&ep); + } } int @@ -114,7 +6231,55 @@ main(int argc, char **argv) { "test_strerror_unknown", test_strerror_unknown }, { "test_trace_error", test_trace_error }, { "test_safe_free", test_safe_free }, - { "test_bug_assert_passes", test_bug_assert_passes }, + { "test_digamma", test_digamma }, + { "test_trigamma", test_trigamma }, + { "test_betaln", test_betaln }, + { "test_gammainc_der", test_gammainc_der }, + { "test_hyperu_laplace", test_hyperu_laplace }, + { "test_hyp1f1_laplace", test_hyp1f1_laplace }, + { "test_hyp2f1_laplace", test_hyp2f1_laplace }, + { "test_gammaincinv", test_gammaincinv }, + { "test_approximate_log_moments", test_approximate_log_moments }, + { "test_approximate_gamma_kl", test_approximate_gamma_kl }, + { "test_approximate_gamma_mom", test_approximate_gamma_mom }, + { "test_approximate_gamma_iqr", test_approximate_gamma_iqr }, + { "test_valid_moments_and_gamma", test_valid_moments_and_gamma }, + { "test_valid", test_valid }, + { "test_node_moments", test_node_moments }, + { "test_node_moments_reference", test_node_moments_reference }, + { "test_node_projections", test_node_projections }, + { "test_mutation_moments", test_mutation_moments }, + { "test_mutation_moments_reference", test_mutation_moments_reference }, + { "test_mutation_projections", test_mutation_projections }, + { "test_block_singletons", test_block_singletons }, + { "test_reallocate_unphased", test_reallocate_unphased }, + { "test_mutation_frequency", test_mutation_frequency }, + { "test_split_and_relabel", test_split_and_relabel }, + { "test_constrain_ages", test_constrain_ages }, + { "test_contains_unary_nodes", test_contains_unary_nodes }, + { "test_check_arguments", test_check_arguments }, + { "test_bad_tree_arguments", test_bad_tree_arguments }, + { "test_marginalize_over_ancestors", test_marginalize_over_ancestors }, + { "test_conditional_coalescent_variance", test_conditional_coalescent_variance }, + { "test_fixed_changepoints", test_fixed_changepoints }, + { "test_count_mutations", test_count_mutations }, + { "test_mutational_area", test_mutational_area }, + { "test_mutational_timescale", test_mutational_timescale }, + { "test_piecewise_scale_point_estimate", test_piecewise_scale_point_estimate }, + { "test_piecewise_scale_posterior", test_piecewise_scale_posterior }, + { "test_damp", test_damp }, + { "test_rescale", test_rescale }, + { "test_ep_init", test_ep_init }, + { "test_rescale_and_assemble_factors", test_rescale_and_assemble_factors }, + { "test_constraints_are_consistent", test_constraints_are_consistent }, + { "test_propagate_likelihood", test_propagate_likelihood }, + { "test_propagate_prior", test_propagate_prior }, + { "test_propagate_mutations", test_propagate_mutations }, + { "test_propagate_likelihood_branches", test_propagate_likelihood_branches }, + { "test_propagate_likelihood_tiny_scale", test_propagate_likelihood_tiny_scale }, + { "test_rescale_factors", test_rescale_factors }, + { "test_propagate_prior_table", test_propagate_prior_table }, + { "test_propagate_mutations_table", test_propagate_mutations_table }, CU_TEST_INFO_NULL, }; CU_SuiteInfo suites[] = { diff --git a/lib/tsdate.h b/lib/tsdate.h index 96575cc6..9a3ce118 100644 --- a/lib/tsdate.h +++ b/lib/tsdate.h @@ -25,10 +25,6 @@ #ifndef TSDATE_H #define TSDATE_H -#ifdef __cplusplus -extern "C" { -#endif - #include #include "err.h" @@ -38,8 +34,332 @@ typedef int32_t tsd_id_t; /* Counts and sizes; matches tsk_size_t. */ typedef uint64_t tsd_size_t; -#ifdef __cplusplus -} -#endif +/* + * Scalar special functions (hypergeo.c). Functions that can fail return 0 or a + * negative TSD_ERR_* code and write their results to the trailing output pointers; + * those that cannot fail return the result. NaN and infinite results are in-band (not + * errors): only violated domain assertions (TSD_ERR_INVALID_HYPERGEO) and divisions by + * zero (TSD_ERR_ZERO_DIVISION) fail. + */ +int tsd_digamma(double x, double *out); +int tsd_trigamma(double x, double *out); +double tsd_betaln(double p, double q); +int tsd_gammainc_der(double p, double x, double *out); +int tsd_hyperu_laplace(double a, double b, double x, double *value, double *dvalue); +int tsd_hyp1f1_laplace(double a, double b, double x, double *out); +int tsd_hyp2f1_laplace(double a, double b, double c, double x, double *out); + +/* + * The inverse of the regularised lower incomplete gamma function (gammaincinv.c): x + * such that gammainc(a, x) = p. Inside the domain it agrees with + * scipy.special.gammaincinv, bit for bit on x86-64 Linux. It returns 0 for p = 0, + * infinity for p = 1 and NaN (not an error) for arguments outside the domain. + */ +double tsd_gammaincinv(double a, double p); + +/* + * Approximations of gamma distributions and of the moments of the EP updates + * (approx.c). + * + * Gamma distributions are written as shape and rate (a, b), with density + * proportional to t^(a - 1) exp(-b t), or as "natural parameters" (a - 1, b); the + * latter are what the gamma_* approximation functions and the projections return and + * take. Errors are as for the special functions above, plus the TSD_ERR_* codes of + * the approximations. + * + * Convention for the moment and projection functions (sections of approx.c): + * + * - A function that can fail returns int: 0 or a negative TSD_ERR_* code. Results + * are written through trailing output pointers, which are written only on + * success (return 0) and must not alias the inputs. + * - Moment functions take, in the order of the oracles' arguments, ages (`t_i`, `t_j`: + * a fixed parent or child) and gamma SHAPE and rate (`a_i`, `b_i`, `a_j`, `b_j`: + * not natural parameters), the mutation count `y_ij` and the rate `mu_ij`. They + * write the values that the oracles return, in the same order: the log normalising + * constant (`logl`) or the phase probability (`pr_m`), then means and variances. + * An invalid hypergeometric domain gives NaN in every output, with return value 0. + * - Projection functions take the natural parameters of the cavity gammas as + * `const double pars_i[2]`, `pars_j[2]` and the edge data as `pars_ij[2]` + * (`y_ij`, `mu_ij`), or ages as in the moment functions. They write the log + * normalising constant (`*logl`, or `*pr_m` for mutation projections) and the + * projected natural parameters through `double proj_i[2]`, `proj_j[2]` (or + * `proj_m[2]`). Where the moments are unusable, `*logl` is NaN and `proj_*` is + * a copy of `pars_*`; mutation projections write NaN to `*pr_m` and to both + * entries of `proj_m`. + * - Functions of the gamma approximations that give a pair of natural parameters + * write them through `double out[2]`. + * - The `tsd_valid_*` predicates return 1 if the arguments are usable and 0 if not; + * a failure is in-band, not an error. + */ +int tsd_approximate_log_moments( + double mean, double variance, double *logx, double *xlogx, double *logx2); +int tsd_approximate_gamma_kl(double x, double logx, double out[2]); +int tsd_approximate_gamma_mom(double mean, double variance, double out[2]); +int tsd_approximate_gamma_iqr( + double q1, double q2, double x1, double x2, double max_shape, double out[2]); + +int tsd_valid_moments(double mn, double va); +int tsd_valid_gamma(double s, double r); +int tsd_valid_hyp1f1(double a, double b, double z); +int tsd_valid_hyperu(double a, double b, double z); +int tsd_valid_hyp2f1(double a, double b, double c, double z); + +/* Node moments (approx.c) */ +int tsd_moments(double a_i, double b_i, double a_j, double b_j, double y_ij, + double mu_ij, double *logl, double *mn_i, double *va_i, double *mn_j, double *va_j); +int tsd_rootward_moments(double t_j, double a_i, double b_i, double y_ij, double mu_ij, + double *logl, double *mn_i, double *va_i); +int tsd_leafward_moments(double t_i, double a_j, double b_j, double y_ij, double mu_ij, + double *logl, double *mn_j, double *va_j); +int tsd_unphased_moments(double a_i, double b_i, double a_j, double b_j, double y_ij, + double mu_ij, double *logl, double *mn_i, double *va_i, double *mn_j, double *va_j); +int tsd_twin_moments(double a_i, double b_i, double y_ij, double mu_ij, double *logl, + double *mn_i, double *va_i); +int tsd_sideways_moments(double t_i, double a_j, double b_j, double y_ij, double mu_ij, + double *logl, double *mn_j, double *va_j); + +/* Node projections */ +int tsd_gamma_projection(const double pars_i[2], const double pars_j[2], + const double pars_ij[2], double *logl, double proj_i[2], double proj_j[2]); +int tsd_leafward_projection(double t_i, const double pars_j[2], const double pars_ij[2], + double *logl, double proj_j[2]); +int tsd_rootward_projection(double t_j, const double pars_i[2], const double pars_ij[2], + double *logl, double proj_i[2]); +int tsd_unphased_projection(const double pars_i[2], const double pars_j[2], + const double pars_ij[2], double *logl, double proj_i[2], double proj_j[2]); +int tsd_twin_projection( + const double pars_i[2], const double pars_ij[2], double *logl, double proj_i[2]); +int tsd_sideways_projection(double t_i, const double pars_j[2], const double pars_ij[2], + double *logl, double proj_j[2]); + +/* Mutation moments */ +int tsd_mutation_moments(double a_i, double b_i, double a_j, double b_j, double y_ij, + double mu_ij, double *mn_m, double *va_m); +int tsd_mutation_rootward_moments(double t_j, double a_i, double b_i, double y_ij, + double mu_ij, double *mn_m, double *va_m); +int tsd_mutation_leafward_moments(double t_i, double a_j, double b_j, double y_ij, + double mu_ij, double *mn_m, double *va_m); +int tsd_mutation_unphased_moments(double a_i, double b_i, double a_j, double b_j, + double y_ij, double mu_ij, double *pr_m, double *mn_m, double *va_m); +int tsd_mutation_twin_moments(double a_i, double b_i, double y_ij, double mu_ij, + double *pr_m, double *mn_m, double *va_m); +int tsd_mutation_sideways_moments(double t_i, double a_j, double b_j, double y_ij, + double mu_ij, double *pr_m, double *mn_m, double *va_m); +int tsd_mutation_edge_moments(double t_i, double t_j, double *mn_m, double *va_m); +int tsd_mutation_block_moments( + double t_i, double t_j, double *pr_m, double *mn_m, double *va_m); + +/* Mutation projections */ +int tsd_mutation_gamma_projection(const double pars_i[2], const double pars_j[2], + const double pars_ij[2], double *pr_m, double proj_m[2]); +int tsd_mutation_leafward_projection(double t_i, const double pars_j[2], + const double pars_ij[2], double *pr_m, double proj_m[2]); +int tsd_mutation_rootward_projection(double t_j, const double pars_i[2], + const double pars_ij[2], double *pr_m, double proj_m[2]); +int tsd_mutation_edge_projection(double t_i, double t_j, double *pr_m, double proj_m[2]); +int tsd_mutation_unphased_projection(const double pars_i[2], const double pars_j[2], + const double pars_ij[2], double *pr_m, double proj_m[2]); +int tsd_mutation_twin_projection( + const double pars_i[2], const double pars_ij[2], double *pr_m, double proj_m[2]); +int tsd_mutation_sideways_projection(double t_i, const double pars_j[2], + const double pars_ij[2], double *pr_m, double proj_m[2]); +int tsd_mutation_block_projection( + double t_i, double t_j, double *pr_m, double proj_m[2]); + +/* The id of no node, edge, mutation, individual or block. */ +#define TSD_NULL ((tsd_id_t) - 1) + +/* + * Phasing of singletons (phasing.c), tree sequence utilities (util.c) and the + * coalescent prior (prior.c). Flags are arrays of uint8_t (numpy bool); the arrays + * of the edges are those of a tree sequence, with the indexes of the insertion and + * removal orders. Results of unknown size are allocated by the function and freed by + * the caller. Ids out of bounds, edges that a sweep over the trees cannot traverse + * (tsd_check_edge_sweep) and edges that form a cycle are errors. + */ +int tsd_argsort(tsd_size_t num_items, const double *keys, tsd_id_t *order); + +/* `err` unless every id is in [0, bound), or TSD_NULL if `allow_null`. */ +int tsd_check_ids( + tsd_size_t num_ids, const tsd_id_t *ids, tsd_size_t bound, int allow_null, int err); +/* TSD_ERR_NODE_OUT_OF_BOUNDS unless the parent and child of every edge are nodes. */ +int tsd_check_edges(tsd_size_t num_nodes, tsd_size_t num_edges, + const tsd_id_t *edges_parent, const tsd_id_t *edges_child); +/* + * The conditions under which a sweep over the trees terminates: every edge satisfies + * 0 <= left < right <= sequence_length (TSD_ERR_BAD_EDGE_INTERVAL), and the insertion + * and removal indexes each list every edge once (TSD_ERR_EDGE_OUT_OF_BOUNDS, + * TSD_ERR_BAD_EDGE_INDEXES), in order of left and right position respectively. + */ +int tsd_check_edge_sweep(tsd_size_t num_edges, const double *edges_left, + const double *edges_right, const tsd_id_t *indexes_insert, + const tsd_id_t *indexes_remove, double sequence_length); + +int tsd_block_singletons(tsd_size_t num_nodes, tsd_size_t num_individuals, + tsd_size_t num_edges, tsd_size_t num_mutations, const uint8_t *individuals_unphased, + const tsd_id_t *nodes_individual, const tsd_id_t *mutations_node, + const double *mutations_position, const tsd_id_t *edges_child, + const double *edges_left, const double *edges_right, const tsd_id_t *indexes_insert, + const tsd_id_t *indexes_remove, double sequence_length, tsd_size_t *num_blocks, + double **blocks_stats, tsd_id_t **blocks_edges, tsd_id_t *mutations_block); +int tsd_reallocate_unphased(tsd_size_t num_edges, tsd_size_t num_mutations, + tsd_size_t num_blocks, const double *mutations_phase, + const tsd_id_t *mutations_block, const tsd_id_t *blocks_edges, + double *edges_likelihood); +int tsd_mutation_frequency(tsd_size_t num_nodes, tsd_size_t num_sample_sets, + tsd_size_t num_edges, tsd_size_t num_mutations, const uint8_t *nodes_sample, + const tsd_id_t *mutations_node, const double *mutations_position, + const tsd_id_t *edges_parent, const tsd_id_t *edges_child, const double *edges_left, + const double *edges_right, const tsd_id_t *indexes_insert, + const tsd_id_t *indexes_remove, double sequence_length, int32_t *mutations_freq); + +int tsd_split_disjoint_nodes(tsd_size_t num_nodes, tsd_size_t num_edges, + const tsd_id_t *edges_parent, const tsd_id_t *edges_child, const double *edges_left, + const double *edges_right, const uint8_t *node_excluded, tsd_id_t *new_parent, + tsd_id_t *new_child, tsd_size_t *num_split, tsd_id_t **nodes_order); +int tsd_relabel_mutations_node(tsd_size_t num_nodes, tsd_size_t num_edges, + tsd_size_t num_mutations, const tsd_id_t *mutations_node, + const double *mutations_position, const tsd_id_t *nodes_order, + const tsd_id_t *edges_parent, const tsd_id_t *edges_child, const double *edges_left, + const double *edges_right, const tsd_id_t *insert_index, + const tsd_id_t *remove_index, tsd_id_t *output); +int tsd_constrain_ages(tsd_size_t num_nodes, tsd_size_t num_edges, + const double *nodes_time, const uint8_t *nodes_fixed, const tsd_id_t *edges_parent, + const tsd_id_t *edges_child, double epsilon, int64_t max_iterations, + double *out_time); +int tsd_contains_unary_nodes(tsd_size_t num_nodes, tsd_size_t num_edges, + const uint8_t *nodes_mask, const tsd_id_t *edges_parent, const double *edges_left, + const double *edges_right, const tsd_id_t *indexes_insert, + const tsd_id_t *indexes_remove, double sequence_length, int *contains_unary); + +/* `val` has `num_tips` rows, at least two; `out` has `num_tips + 1` rows. */ +int tsd_marginalize_over_ancestors( + tsd_size_t num_tips, tsd_size_t num_moments, const double *val, double *out); +/* `variance` has `num_tips + 1` entries; there is at least one tip. */ +int tsd_conditional_coalescent_variance(tsd_size_t num_tips, double *variance); +/* + * Time rescaling (rescaling.c). + * + * Array arguments are contiguous. `likelihoods` and the edge statistics are + * row-major with two columns per edge (mutation count, mutational span). The + * functions that return arrays whose size is not known beforehand allocate them + * with malloc, and the caller frees them (tsd_safe_free, tsd_epoch_stats_free). + * Array sizes are the caller's responsibility (tsd_bug_assert); violated numerical + * preconditions are reported as errors. + */ + +/* Per-epoch results of tsd_mutational_area; every array has `num_epochs` entries. */ +typedef struct { + tsd_size_t num_epochs; + double *counts; + double *offset; + double *duration; +} tsd_epoch_stats_t; + +void tsd_epoch_stats_free(tsd_epoch_stats_t *stats); + +/* Breakpoints (`*num_breaks == epochs + 1` of them) dividing the counts roughly + * equally between `epochs` epochs. */ +int tsd_fixed_changepoints(tsd_size_t num_counts, const double *counts, int64_t epochs, + tsd_id_t **breaks, tsd_size_t *num_breaks); +/* `edges_stats` has 2 * num_edges entries and `mutations_edge` num_mutations. */ +int tsd_count_mutations(tsd_size_t num_nodes, const uint8_t *node_is_sample, + tsd_size_t num_mutations, const tsd_id_t *mutations_node, + const double *mutations_position, tsd_size_t num_edges, const tsd_id_t *edges_parent, + const tsd_id_t *edges_child, const double *edges_left, const double *edges_right, + const tsd_id_t *indexes_insert, const tsd_id_t *indexes_remove, + double sequence_length, int size_biased, double *edges_stats, + tsd_id_t *mutations_edge); +/* `nodes_index` has num_nodes entries. */ +int tsd_mutational_area(tsd_size_t num_nodes, const double *nodes_time, + tsd_size_t num_edges, const double *likelihoods, const tsd_id_t *edges_parent, + const tsd_id_t *edges_child, tsd_epoch_stats_t *stats, tsd_id_t *nodes_index); +/* `*origin` and `*adjust` have `*num_breaks` entries. */ +int tsd_mutational_timescale(tsd_size_t num_nodes, const double *nodes_time, + tsd_size_t num_edges, const double *likelihoods, const tsd_id_t *edges_parent, + const tsd_id_t *edges_child, int64_t max_intervals, tsd_size_t *num_breaks, + double **origin, double **adjust); +/* There must be at least one breakpoint; `rescaled` has `num_points` entries. */ +int tsd_piecewise_scale_point_estimate(tsd_size_t num_points, + const double *point_estimate, const uint8_t *point_fixed, tsd_size_t num_breaks, + const double *original_breaks, const double *rescaled_breaks, double *rescaled); +/* `posteriors` and `new_posteriors` are natural parameters, row-major, two columns. */ +int tsd_piecewise_scale_posterior(tsd_size_t num_posteriors, const double *posteriors, + const uint8_t *posteriors_fixed, tsd_size_t num_breaks, + const double *original_breaks, const double *rescaled_breaks, double quantile_width, + double max_shape, double *new_posteriors); + +/* + * Expectation propagation (variational.c). + * + * The state of the algorithm. Natural parameters of a node are two doubles, so the + * constraints, likelihoods and posteriors have two columns, and the factors have + * shape [n][2][2]: for each edge (block of unphased singletons), the factor to the + * parent (first block node) and to the child (second), each of two natural + * parameters; for each node, the mixture prior and the constraint. Factors are + * stored divided by the scale of their node. Errors are violated numerical + * preconditions (parameters, improper posteriors) and those of the projections. + */ +typedef struct { + tsd_size_t num_nodes; + tsd_size_t num_edges; + tsd_size_t num_blocks; + double *constraints; /* num_nodes x 2: lower and upper bound on the age */ + tsd_id_t *edges_parent; /* num_edges */ + tsd_id_t *edges_child; /* num_edges */ + double *edges_likelihood; /* num_edges x 2: mutations and mutational span */ + tsd_id_t *blocks_left; /* num_blocks */ + tsd_id_t *blocks_right; /* num_blocks */ + double *blocks_likelihood; /* num_blocks x 2 */ + double *node; /* num_nodes x 2 x 2 */ + double *edge; /* num_edges x 2 x 2 */ + double *block; /* num_blocks x 2 x 2 */ + double *scale; /* num_nodes */ + double *posterior; /* num_nodes x 2 */ + double *edges_lognorm; /* num_edges */ + double *blocks_lognorm; /* num_blocks */ +} tsd_ep_t; + +/* + * Copy the inputs; the factors, posteriors and normalising constants start at zero + * and the scales at one. The ids must be nodes (TSD_ERR_NODE_OUT_OF_BOUNDS). + */ +int tsd_ep_init(tsd_ep_t *self, tsd_size_t num_nodes, tsd_size_t num_edges, + tsd_size_t num_blocks, const double *constraints, const tsd_id_t *edges_parent, + const tsd_id_t *edges_child, const double *edges_likelihood, + const tsd_id_t *blocks_left, const tsd_id_t *blocks_right, + const double *blocks_likelihood); +void tsd_ep_free(tsd_ep_t *self); +/* Multiply the factors by the scale of their node, and reset the scale to one. */ +void tsd_ep_rescale_factors(tsd_ep_t *self); +/* The posteriors implied by the factors; `posterior` has num_nodes x 2 entries. */ +void tsd_ep_assemble_factors(const tsd_ep_t *self, double *posterior); +/* + * Update the factors of the edges (blocks, if `unphased`) in `order`, which may + * repeat or omit them. + */ +int tsd_ep_propagate_likelihood(tsd_ep_t *self, tsd_size_t num_order, + const tsd_id_t *order, int unphased, double max_shape, double min_step); +/* Fit an exponential prior to the cavities of the free nodes and update their factors. + */ +int tsd_ep_propagate_prior(tsd_ep_t *self, const uint8_t *free, double max_shape, + int64_t em_maxitt, double em_reltol); +/* + * Posteriors (two columns) and phases of mutations from the edges (blocks) above + * them, `mutations_edge`; a mutation whose edge is TSD_NULL, above a root, has NaN + * posterior and phase one. The state is not changed. + */ +int tsd_ep_propagate_mutations(const tsd_ep_t *self, tsd_size_t num_mutations, + const tsd_id_t *mutations_edge, int unphased, double *mutations_posterior, + double *mutations_phase); + +/* The step `d` in (0, 1] so that the cavity `x - d * y` is proper, for `0 < s < 1`. */ +int tsd_damp(const double x[2], const double y[2], double s, double *out); +/* The factor that brings the shape of `x` between 1 / s and s; `s` is `max_shape`. */ +int tsd_rescale(const double x[2], double s, double *out); +/* `constraints` has num_nodes x 2 entries (lower and upper bound). */ +int tsd_constraints_are_consistent(tsd_size_t num_nodes, tsd_size_t num_edges, + const double *constraints, const tsd_id_t *edges_parent, const tsd_id_t *edges_child, + int *consistent); #endif diff --git a/lib/util.c b/lib/util.c new file mode 100644 index 00000000..f10f2865 --- /dev/null +++ b/lib/util.c @@ -0,0 +1,648 @@ +/* + * MIT License + * + * Copyright (c) 2026 Tskit Developers + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in all + * copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE + * SOFTWARE. + */ + +/* + * Utilities for the tree sequence tables: splitting + * nodes that are disconnected along the sequence, relabelling mutations accordingly, + * constraining node ages, and a test for unary nodes. + */ + +#include +#include +#include + +#include "mathutil.h" +#include "tsdate.h" + +/* A key with the index it came from. */ +typedef struct { + double key; + tsd_id_t index; +} tsd_sort_item_t; + +/* + * Stable bottom-up merge sort of `items` by key, using `buffer` (the same size) as + * scratch. Written out, rather than using qsort, because the comparison dominates the + * cost of sorting the edges and cannot be inlined through qsort. + */ +static void +sort_items(tsd_size_t num_items, tsd_sort_item_t *items, tsd_sort_item_t *buffer) +{ + tsd_sort_item_t *src = items; + tsd_sort_item_t *dst = buffer; + tsd_sort_item_t *swap; + tsd_size_t width, start, mid, stop, i, j, k; + + for (width = 1; width < num_items; width *= 2) { + for (start = 0; start < num_items; start += 2 * width) { + mid = start + width < num_items ? start + width : num_items; + stop = start + 2 * width < num_items ? start + 2 * width : num_items; + i = start; + j = mid; + for (k = start; k < stop; k++) { + if (i < mid && (j >= stop || !(src[j].key < src[i].key))) { + dst[k] = src[i]; + i++; + } else { + dst[k] = src[j]; + j++; + } + } + } + swap = src; + src = dst; + dst = swap; + } + if (src != items) { + memcpy(items, src, num_items * sizeof(*items)); + } +} + +/* + * The indexes that sort `keys`, ties broken by index (np.argsort, made deterministic: + * the callers do not depend on the order of ties). + */ +int +tsd_argsort(tsd_size_t num_items, const double *keys, tsd_id_t *order) +{ + int ret = 0; + tsd_sort_item_t *items = NULL; + tsd_sort_item_t *buffer = NULL; + const tsd_size_t alloc = num_items > 0 ? num_items : 1; + tsd_size_t j; + + items = malloc(alloc * sizeof(*items)); + buffer = malloc(alloc * sizeof(*buffer)); + if (items == NULL || buffer == NULL) { + ret = tsd_trace_error(TSD_ERR_NO_MEMORY); + goto out; + } + for (j = 0; j < num_items; j++) { + items[j].key = keys[j]; + items[j].index = (tsd_id_t) j; + } + sort_items(num_items, items, buffer); + for (j = 0; j < num_items; j++) { + order[j] = items[j].index; + } +out: + tsd_safe_free(items); + tsd_safe_free(buffer); + return ret; +} + +int +tsd_check_ids( + tsd_size_t num_ids, const tsd_id_t *ids, tsd_size_t bound, int allow_null, int err) +{ + tsd_size_t j; + tsd_id_t id; + + for (j = 0; j < num_ids; j++) { + id = ids[j]; + if (allow_null && id == TSD_NULL) { + continue; + } + if (id < 0 || (tsd_size_t) id >= bound) { + return tsd_trace_error(err); + } + } + return 0; +} + +int +tsd_check_edges(tsd_size_t num_nodes, tsd_size_t num_edges, const tsd_id_t *edges_parent, + const tsd_id_t *edges_child) +{ + int ret; + + ret = tsd_check_ids( + num_edges, edges_parent, num_nodes, 0, TSD_ERR_NODE_OUT_OF_BOUNDS); + if (ret != 0) { + return ret; + } + return tsd_check_ids( + num_edges, edges_child, num_nodes, 0, TSD_ERR_NODE_OUT_OF_BOUNDS); +} + +/* Whether each id in [0, num_edges) appears once in `index`. */ +static int +is_permutation(tsd_size_t num_edges, const tsd_id_t *index, uint8_t *seen) +{ + tsd_size_t j; + + memset(seen, 0, num_edges * sizeof(*seen)); + for (j = 0; j < num_edges; j++) { + if (seen[index[j]]) { + return 0; + } + seen[index[j]] = 1; + } + return 1; +} + +/* Whether `position[index[j]]` does not decrease with j. */ +static int +is_sorted_by(tsd_size_t num_edges, const tsd_id_t *index, const double *position) +{ + tsd_size_t j; + + for (j = 1; j < num_edges; j++) { + if (position[index[j]] < position[index[j - 1]]) { + return 0; + } + } + return 1; +} + +int +tsd_check_edge_sweep(tsd_size_t num_edges, const double *edges_left, + const double *edges_right, const tsd_id_t *indexes_insert, + const tsd_id_t *indexes_remove, double sequence_length) +{ + int ret = 0; + uint8_t *seen = NULL; + tsd_size_t e; + + for (e = 0; e < num_edges; e++) { + if (!(edges_left[e] >= 0 && edges_left[e] < edges_right[e] + && edges_right[e] <= sequence_length)) { + ret = tsd_trace_error(TSD_ERR_BAD_EDGE_INTERVAL); + goto out; + } + } + ret = tsd_check_ids( + num_edges, indexes_insert, num_edges, 0, TSD_ERR_EDGE_OUT_OF_BOUNDS); + if (ret != 0) { + goto out; + } + ret = tsd_check_ids( + num_edges, indexes_remove, num_edges, 0, TSD_ERR_EDGE_OUT_OF_BOUNDS); + if (ret != 0) { + goto out; + } + seen = malloc(num_edges > 0 ? num_edges : 1); + if (seen == NULL) { + ret = tsd_trace_error(TSD_ERR_NO_MEMORY); + goto out; + } + if (!is_permutation(num_edges, indexes_insert, seen) + || !is_permutation(num_edges, indexes_remove, seen) + || !is_sorted_by(num_edges, indexes_insert, edges_left) + || !is_sorted_by(num_edges, indexes_remove, edges_right)) { + ret = tsd_trace_error(TSD_ERR_BAD_EDGE_INDEXES); + goto out; + } +out: + tsd_safe_free(seen); + return ret; +} + +/* + * Label the disconnected segments of each non-excluded node along its edges: the + * segment of an edge increases when the edge starts after the previous edges of the + * node have ended. `edges_segments` holds the labels of the parents (first + * `num_edges` entries) and children. + */ +static int +label_node_segments(tsd_size_t num_nodes, tsd_size_t num_edges, + const tsd_id_t *edges_parent, const tsd_id_t *edges_child, const double *edges_left, + const double *edges_right, const uint8_t *node_excluded, tsd_id_t *edges_segments, + tsd_id_t *nodes_segments) +{ + int ret = 0; + tsd_id_t *edges_order = NULL; + double *nodes_right = NULL; + tsd_size_t j, k, side; + tsd_id_t e, n; + int new_segment; + + edges_order = malloc((num_edges > 0 ? num_edges : 1) * sizeof(*edges_order)); + nodes_right = malloc((num_nodes > 0 ? num_nodes : 1) * sizeof(*nodes_right)); + if (edges_order == NULL || nodes_right == NULL) { + ret = tsd_trace_error(TSD_ERR_NO_MEMORY); + goto out; + } + ret = tsd_argsort(num_edges, edges_left, edges_order); + if (ret != 0) { + goto out; + } + for (j = 0; j < num_nodes; j++) { + nodes_segments[j] = -1; + nodes_right[j] = -INFINITY; + } + for (j = 0; j < 2 * num_edges; j++) { + edges_segments[j] = -1; + } + for (j = 0; j < num_edges; j++) { + e = edges_order[j]; + for (side = 0; side < 2; side++) { + n = side == 0 ? edges_parent[e] : edges_child[e]; + if (node_excluded[n]) { + continue; + } + new_segment = edges_left[e] > nodes_right[n]; + nodes_segments[n] = (tsd_id_t) (nodes_segments[n] + new_segment); + k = side * num_edges + (tsd_size_t) e; + edges_segments[k] = nodes_segments[n]; + nodes_right[n] = tsd_max(nodes_right[n], edges_right[e]); + } + } +out: + tsd_safe_free(edges_order); + tsd_safe_free(nodes_right); + return ret; +} + +/* + * Split disconnected regions of nodes into separate nodes. A node with s + 1 + * disconnected segments gets s copies, numbered from `num_nodes`; the segments after + * the first are relabelled onto the copies. + * + * Writes the relabelled edges to `new_parent` and `new_child`. Allocates + * `*nodes_order`, of length `num_nodes + *num_split`: the identity on the original + * nodes, followed by the original node of each copy (the "split nodes"). The caller + * frees it. + */ +int +tsd_split_disjoint_nodes(tsd_size_t num_nodes, tsd_size_t num_edges, + const tsd_id_t *edges_parent, const tsd_id_t *edges_child, const double *edges_left, + const double *edges_right, const uint8_t *node_excluded, tsd_id_t *new_parent, + tsd_id_t *new_child, tsd_size_t *num_split, tsd_id_t **nodes_order) +{ + int ret = 0; + tsd_id_t *edges_segments = NULL; + tsd_id_t *nodes_segments = NULL; + tsd_id_t *nodes_map = NULL; + tsd_id_t *order = NULL; + tsd_size_t j, side, k, total, next; + tsd_id_t s, n, segment, e; + + ret = tsd_check_edges(num_nodes, num_edges, edges_parent, edges_child); + if (ret != 0) { + goto out; + } + edges_segments = malloc((2 * num_edges + 1) * sizeof(*edges_segments)); + nodes_segments = malloc((num_nodes > 0 ? num_nodes : 1) * sizeof(*nodes_segments)); + nodes_map = malloc((num_nodes > 0 ? num_nodes : 1) * sizeof(*nodes_map)); + if (edges_segments == NULL || nodes_segments == NULL || nodes_map == NULL) { + ret = tsd_trace_error(TSD_ERR_NO_MEMORY); + goto out; + } + ret = label_node_segments(num_nodes, num_edges, edges_parent, edges_child, + edges_left, edges_right, node_excluded, edges_segments, nodes_segments); + if (ret != 0) { + goto out; + } + + total = 0; + for (j = 0; j < num_nodes; j++) { + if (nodes_segments[j] > 0) { + total += (tsd_size_t) nodes_segments[j]; + } + } + order = malloc((num_nodes + total + 1) * sizeof(*order)); + if (order == NULL) { + ret = tsd_trace_error(TSD_ERR_NO_MEMORY); + goto out; + } + /* Copies of node j are numbered consecutively, the first being nodes_map[j] */ + next = num_nodes; + for (j = 0; j < num_nodes; j++) { + order[j] = (tsd_id_t) j; + nodes_map[j] = TSD_NULL; + s = nodes_segments[j]; + if (s > 0) { + nodes_map[j] = (tsd_id_t) next; + } + while (s > 0) { + order[next] = (tsd_id_t) j; + next++; + s--; + } + } + + for (e = 0; (tsd_size_t) e < num_edges; e++) { + for (side = 0; side < 2; side++) { + n = side == 0 ? edges_parent[e] : edges_child[e]; + k = side * num_edges + (tsd_size_t) e; + segment = edges_segments[k]; + if (segment > 0) { + segment = (tsd_id_t) (nodes_map[n] + segment - 1); + } else { + segment = n; + } + if (side == 0) { + new_parent[e] = segment; + } else { + new_child[e] = segment; + } + } + } + *num_split = total; + *nodes_order = order; + order = NULL; +out: + tsd_safe_free(edges_segments); + tsd_safe_free(nodes_segments); + tsd_safe_free(nodes_map); + tsd_safe_free(order); + return ret; +} + +/* + * Traverse the trees, maintaining the map from the old to the new id of the nodes in + * the current tree, and write the new node of each mutation. Mutations beyond the + * last edge, which the sweep does not reach, are NULL. + */ +int +tsd_relabel_mutations_node(tsd_size_t num_nodes, tsd_size_t num_edges, + tsd_size_t num_mutations, const tsd_id_t *mutations_node, + const double *mutations_position, const tsd_id_t *nodes_order, + const tsd_id_t *edges_parent, const tsd_id_t *edges_child, const double *edges_left, + const double *edges_right, const tsd_id_t *insert_index, + const tsd_id_t *remove_index, tsd_id_t *output) +{ + int ret = 0; + tsd_id_t *nodes_map = NULL; + tsd_size_t a, b, m, j; + tsd_id_t e, c, p; + double left, right, sequence_length; + + ret = tsd_check_edges(num_nodes, num_edges, edges_parent, edges_child); + if (ret != 0) { + goto out; + } + ret = tsd_check_ids( + num_nodes, nodes_order, num_nodes, 0, TSD_ERR_NODE_OUT_OF_BOUNDS); + if (ret != 0) { + goto out; + } + ret = tsd_check_ids( + num_mutations, mutations_node, num_nodes, 0, TSD_ERR_NODE_OUT_OF_BOUNDS); + if (ret != 0) { + goto out; + } + ret = tsd_check_edge_sweep( + num_edges, edges_left, edges_right, insert_index, remove_index, INFINITY); + if (ret != 0) { + goto out; + } + nodes_map = malloc((num_nodes > 0 ? num_nodes : 1) * sizeof(*nodes_map)); + if (nodes_map == NULL) { + ret = tsd_trace_error(TSD_ERR_NO_MEMORY); + goto out; + } + for (j = 0; j < num_nodes; j++) { + nodes_map[j] = TSD_NULL; + } + for (m = 0; m < num_mutations; m++) { + output[m] = TSD_NULL; + } + + sequence_length = 0.0; + if (num_edges > 0) { + sequence_length = edges_right[remove_index[num_edges - 1]]; + } + a = 0; + b = 0; + m = 0; + left = 0.0; + while (left < sequence_length) { + while (b < num_edges && edges_right[remove_index[b]] == left) { /* edges out */ + b++; + } + while (a < num_edges && edges_left[insert_index[a]] == left) { /* edges in */ + e = insert_index[a]; + c = edges_child[e]; + p = edges_parent[e]; + nodes_map[nodes_order[c]] = c; + nodes_map[nodes_order[p]] = p; + a++; + } + right = sequence_length; + if (b < num_edges) { + right = tsd_min(right, edges_right[remove_index[b]]); + } + if (a < num_edges) { + right = tsd_min(right, edges_left[insert_index[a]]); + } + left = right; + while (m < num_mutations && mutations_position[m] < right) { + if (nodes_map[mutations_node[m]] == TSD_NULL) { + ret = tsd_trace_error(TSD_ERR_MUTATION_NODE_NOT_IN_TREE); + goto out; + } + output[m] = nodes_map[mutations_node[m]]; + m++; + } + } +out: + tsd_safe_free(nodes_map); + return ret; +} + +/* Whether every edge is longer than epsilon, as a vector check of the ages. */ +static int +edges_satisfy_constraint(tsd_size_t num_edges, const double *nodes_time, + const tsd_id_t *edges_parent, const tsd_id_t *edges_child, double epsilon) +{ + tsd_size_t e; + double length; + + for (e = 0; e < num_edges; e++) { + length = nodes_time[edges_parent[e]] - nodes_time[edges_child[e]]; + if (!(length > epsilon)) { + return 0; + } + } + return 1; +} + +/* + * Approximate least squares solution to the positive branch length constraint, using + * the method of alternating projections. Loosely based on Dykstra's algorithm: Dykstra + * RL, "An algorithm for restricted least squares regression", JASA 1983. + * + * Writes the constrained ages to `out_time`, which does not alias `nodes_time`. + */ +int +tsd_constrain_ages(tsd_size_t num_nodes, tsd_size_t num_edges, const double *nodes_time, + const uint8_t *nodes_fixed, const tsd_id_t *edges_parent, + const tsd_id_t *edges_child, double epsilon, int64_t max_iterations, + double *out_time) +{ + int ret = 0; + double *edges_cavity = NULL; + int64_t iteration; + tsd_size_t e; + tsd_id_t p, c; + double adjustment; + double *cavity; + + ret = tsd_check_edges(num_nodes, num_edges, edges_parent, edges_child); + if (ret != 0) { + goto out; + } + edges_cavity = calloc(2 * num_edges + 1, sizeof(*edges_cavity)); + if (edges_cavity == NULL) { + ret = tsd_trace_error(TSD_ERR_NO_MEMORY); + goto out; + } + memcpy(out_time, nodes_time, num_nodes * sizeof(*out_time)); + + for (iteration = 0; iteration < max_iterations; iteration++) { + if (edges_satisfy_constraint( + num_edges, out_time, edges_parent, edges_child, epsilon)) { + goto out; + } + for (e = 0; e < num_edges; e++) { + p = edges_parent[e]; + c = edges_child[e]; + cavity = edges_cavity + 2 * e; + out_time[c] -= cavity[0]; + out_time[p] -= cavity[1]; + adjustment = out_time[c] - out_time[p]; + cavity[0] = 0.0; + cavity[1] = 0.0; + if (adjustment > 0) { + if (nodes_fixed[c] && nodes_fixed[p]) { + ret = tsd_trace_error(TSD_ERR_FIXED_NODES_VIOLATE_CONSTRAINT); + goto out; + } + if (!nodes_fixed[c] && !nodes_fixed[p]) { + cavity[0] = -adjustment / 2; + cavity[1] = adjustment / 2; + } else if (nodes_fixed[c]) { + cavity[1] = adjustment; + } else { + cavity[0] = -adjustment; + } + } + out_time[c] += cavity[0]; + out_time[p] += cavity[1]; + } + } + + /* Force the remaining constraint, which can change the ages of fixed nodes */ + for (e = 0; e < num_edges; e++) { + p = edges_parent[e]; + c = edges_child[e]; + if (out_time[c] + epsilon >= out_time[p]) { + out_time[p] = out_time[c] + epsilon; + } + } +out: + tsd_safe_free(edges_cavity); + return ret; +} + +/* Whether any unmasked node among the parents of the given edges has one child. */ +static int +parents_are_unary(tsd_size_t num_edges, const tsd_id_t *edges_parent, + const tsd_id_t *indexes, tsd_size_t start, tsd_size_t stop, + const uint8_t *nodes_mask, const tsd_id_t *nodes_children) +{ + tsd_size_t j; + tsd_id_t p; + + tsd_bug_assert(stop <= num_edges); + for (j = start; j < stop; j++) { + p = edges_parent[indexes[j]]; + if (!nodes_mask[p] && nodes_children[p] == 1) { + return 1; + } + } + return 0; +} + +/* + * Whether any unmasked node has exactly one child edge in any tree. Sets + * `*contains_unary` to 1 or 0. + */ +int +tsd_contains_unary_nodes(tsd_size_t num_nodes, tsd_size_t num_edges, + const uint8_t *nodes_mask, const tsd_id_t *edges_parent, const double *edges_left, + const double *edges_right, const tsd_id_t *indexes_insert, + const tsd_id_t *indexes_remove, double sequence_length, int *contains_unary) +{ + int ret = 0; + tsd_id_t *nodes_children = NULL; + tsd_size_t a, b, a_start, b_start; + tsd_id_t p; + double left, right; + + ret = tsd_check_ids( + num_edges, edges_parent, num_nodes, 0, TSD_ERR_NODE_OUT_OF_BOUNDS); + if (ret != 0) { + goto out; + } + ret = tsd_check_edge_sweep(num_edges, edges_left, edges_right, indexes_insert, + indexes_remove, sequence_length); + if (ret != 0) { + goto out; + } + nodes_children = calloc(num_nodes > 0 ? num_nodes : 1, sizeof(*nodes_children)); + if (nodes_children == NULL) { + ret = tsd_trace_error(TSD_ERR_NO_MEMORY); + goto out; + } + *contains_unary = 0; + a = 0; + b = 0; + left = 0.0; + while (a < num_edges || b < num_edges) { + a_start = a; + b_start = b; + while (b < num_edges && edges_right[indexes_remove[b]] == left) { /* out */ + p = edges_parent[indexes_remove[b]]; + nodes_children[p]--; + b++; + } + while (a < num_edges && edges_left[indexes_insert[a]] == left) { /* in */ + p = edges_parent[indexes_insert[a]]; + nodes_children[p]++; + a++; + } + /* The nodes to check are the parents of the edges that changed */ + if (parents_are_unary(num_edges, edges_parent, indexes_remove, b_start, b, + nodes_mask, nodes_children) + || parents_are_unary(num_edges, edges_parent, indexes_insert, a_start, a, + nodes_mask, nodes_children)) { + *contains_unary = 1; + goto out; + } + right = sequence_length; + if (b < num_edges) { + right = tsd_min(right, edges_right[indexes_remove[b]]); + } + if (a < num_edges) { + right = tsd_min(right, edges_left[indexes_insert[a]]); + } + left = right; + } +out: + tsd_safe_free(nodes_children); + return ret; +} diff --git a/lib/variational.c b/lib/variational.c new file mode 100644 index 00000000..a2ce8d53 --- /dev/null +++ b/lib/variational.c @@ -0,0 +1,835 @@ +/* + * MIT License + * + * Copyright (c) 2026 Tskit Developers + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in all + * copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE + * SOFTWARE. + */ + +/* + * The expectation propagation passes: the damping helpers, the passes over edges + * (blocks of unphased singletons), the prior and the mutations. Operation order + * matches the oracles in tests/oracle, which the tests compare exactly. + */ + +#include +#include +#include +#include + +#include "mathutil.h" +#include "tsdate.h" + +/* Indexes into the factors, as in tsdate.variational */ +#define ROOTWARD 0 +#define LEAFWARD 1 +#define MIXPRIOR 0 +#define CONSTRNT 1 +#define LOWER 0 +#define UPPER 1 + +/* Entry `i` of an array of pairs, `j` of an array of 2x2 factors. */ +#define PAIR(array, i) ((array) + 2 * (tsd_size_t) (i)) +#define FACTOR(array, i, which) ((array) + 4 * (tsd_size_t) (i) + 2 * (which)) + +int +tsd_ep_init(tsd_ep_t *self, tsd_size_t num_nodes, tsd_size_t num_edges, + tsd_size_t num_blocks, const double *constraints, const tsd_id_t *edges_parent, + const tsd_id_t *edges_child, const double *edges_likelihood, + const tsd_id_t *blocks_left, const tsd_id_t *blocks_right, + const double *blocks_likelihood) +{ + int ret = 0; + tsd_size_t j; + + memset(self, 0, sizeof(*self)); + ret = tsd_check_edges(num_nodes, num_edges, edges_parent, edges_child); + if (ret != 0) { + goto out; + } + ret = tsd_check_edges(num_nodes, num_blocks, blocks_left, blocks_right); + if (ret != 0) { + goto out; + } + self->num_nodes = num_nodes; + self->num_edges = num_edges; + self->num_blocks = num_blocks; + self->constraints = malloc((2 * num_nodes + 1) * sizeof(*self->constraints)); + self->edges_parent = malloc((num_edges + 1) * sizeof(*self->edges_parent)); + self->edges_child = malloc((num_edges + 1) * sizeof(*self->edges_child)); + self->edges_likelihood + = malloc((2 * num_edges + 1) * sizeof(*self->edges_likelihood)); + self->blocks_left = malloc((num_blocks + 1) * sizeof(*self->blocks_left)); + self->blocks_right = malloc((num_blocks + 1) * sizeof(*self->blocks_right)); + self->blocks_likelihood + = malloc((2 * num_blocks + 1) * sizeof(*self->blocks_likelihood)); + self->node = calloc(4 * num_nodes + 1, sizeof(*self->node)); + self->edge = calloc(4 * num_edges + 1, sizeof(*self->edge)); + self->block = calloc(4 * num_blocks + 1, sizeof(*self->block)); + self->scale = malloc((num_nodes + 1) * sizeof(*self->scale)); + self->posterior = calloc(2 * num_nodes + 1, sizeof(*self->posterior)); + self->edges_lognorm = calloc(num_edges + 1, sizeof(*self->edges_lognorm)); + self->blocks_lognorm = calloc(num_blocks + 1, sizeof(*self->blocks_lognorm)); + if (self->constraints == NULL || self->edges_parent == NULL + || self->edges_child == NULL || self->edges_likelihood == NULL + || self->blocks_left == NULL || self->blocks_right == NULL + || self->blocks_likelihood == NULL || self->node == NULL || self->edge == NULL + || self->block == NULL || self->scale == NULL || self->posterior == NULL + || self->edges_lognorm == NULL || self->blocks_lognorm == NULL) { + ret = tsd_trace_error(TSD_ERR_NO_MEMORY); + goto out; + } + memcpy(self->constraints, constraints, 2 * num_nodes * sizeof(*constraints)); + memcpy(self->edges_parent, edges_parent, num_edges * sizeof(*edges_parent)); + memcpy(self->edges_child, edges_child, num_edges * sizeof(*edges_child)); + memcpy(self->edges_likelihood, edges_likelihood, + 2 * num_edges * sizeof(*edges_likelihood)); + memcpy(self->blocks_left, blocks_left, num_blocks * sizeof(*blocks_left)); + memcpy(self->blocks_right, blocks_right, num_blocks * sizeof(*blocks_right)); + memcpy(self->blocks_likelihood, blocks_likelihood, + 2 * num_blocks * sizeof(*blocks_likelihood)); + for (j = 0; j < num_nodes; j++) { + self->scale[j] = 1.0; + } +out: + return ret; +} + +void +tsd_ep_free(tsd_ep_t *self) +{ + tsd_safe_free(self->constraints); + tsd_safe_free(self->edges_parent); + tsd_safe_free(self->edges_child); + tsd_safe_free(self->edges_likelihood); + tsd_safe_free(self->blocks_left); + tsd_safe_free(self->blocks_right); + tsd_safe_free(self->blocks_likelihood); + tsd_safe_free(self->node); + tsd_safe_free(self->edge); + tsd_safe_free(self->block); + tsd_safe_free(self->scale); + tsd_safe_free(self->posterior); + tsd_safe_free(self->edges_lognorm); + tsd_safe_free(self->blocks_lognorm); +} + +void +tsd_ep_rescale_factors(tsd_ep_t *self) +{ + const double *scale = self->scale; + tsd_size_t j, k; + double *f; + + for (j = 0; j < self->num_edges; j++) { + f = FACTOR(self->edge, j, ROOTWARD); + for (k = 0; k < 2; k++) { + f[k] *= scale[self->edges_parent[j]]; + } + f = FACTOR(self->edge, j, LEAFWARD); + for (k = 0; k < 2; k++) { + f[k] *= scale[self->edges_child[j]]; + } + } + for (j = 0; j < self->num_blocks; j++) { + f = FACTOR(self->block, j, ROOTWARD); + for (k = 0; k < 2; k++) { + f[k] *= scale[self->blocks_left[j]]; + } + f = FACTOR(self->block, j, LEAFWARD); + for (k = 0; k < 2; k++) { + f[k] *= scale[self->blocks_right[j]]; + } + } + for (j = 0; j < self->num_nodes; j++) { + f = FACTOR(self->node, j, MIXPRIOR); + for (k = 0; k < 2; k++) { + f[k] *= scale[j]; + } + f = FACTOR(self->node, j, CONSTRNT); + for (k = 0; k < 2; k++) { + f[k] *= scale[j]; + } + self->scale[j] = 1.0; + } +} + +void +tsd_ep_assemble_factors(const tsd_ep_t *self, double *posterior) +{ + tsd_size_t j, k; + double *post; + const double *f; + + for (j = 0; j < 2 * self->num_nodes; j++) { + posterior[j] = 0.0; + } + for (j = 0; j < self->num_edges; j++) { + post = PAIR(posterior, self->edges_parent[j]); + f = FACTOR(self->edge, j, ROOTWARD); + for (k = 0; k < 2; k++) { + post[k] += f[k]; + } + post = PAIR(posterior, self->edges_child[j]); + f = FACTOR(self->edge, j, LEAFWARD); + for (k = 0; k < 2; k++) { + post[k] += f[k]; + } + } + for (j = 0; j < self->num_blocks; j++) { + post = PAIR(posterior, self->blocks_left[j]); + f = FACTOR(self->block, j, ROOTWARD); + for (k = 0; k < 2; k++) { + post[k] += f[k]; + } + post = PAIR(posterior, self->blocks_right[j]); + f = FACTOR(self->block, j, LEAFWARD); + for (k = 0; k < 2; k++) { + post[k] += f[k]; + } + } + for (j = 0; j < self->num_nodes; j++) { + post = PAIR(posterior, j); + f = FACTOR(self->node, j, MIXPRIOR); + for (k = 0; k < 2; k++) { + post[k] += f[k]; + } + } + for (j = 0; j < self->num_nodes; j++) { + post = PAIR(posterior, j); + f = FACTOR(self->node, j, CONSTRNT); + for (k = 0; k < 2; k++) { + post[k] += f[k]; + } + } +} + +/* + * If `x - y` is too small, find `d` so that `x - d * y` is large enough: + * + * x[0] - d * y[0] + 1 >= (x[0] + 1) * s + * x[1] - d * y[1] >= y[1] * s + * + * for `0 < s < 1`. + */ +int +tsd_damp(const double x[2], const double y[2], double s, double *out) +{ + int ret = 0; + double a, b, d; + + if (y[0] == 0.0 && y[1] == 0.0 && x[0] == 0.0 && x[1] == 0.0) { + *out = 1.0; + goto out; + } + if (!(0 < s && s < 1)) { + ret = tsd_trace_error(TSD_ERR_INVALID_MIN_STEP); + goto out; + } + if (!(0.0 < x[0] + 1 && 0.0 < x[1])) { + ret = tsd_trace_error(TSD_ERR_INVALID_NODE_POSTERIOR); + goto out; + } + a = 1.0; + if (!(1 + x[0] - y[0] > (1 + x[0]) * s)) { + if (y[0] == 0.0) { + ret = tsd_trace_error(TSD_ERR_ZERO_DIVISION); + goto out; + } + a = (1 - s) * (1 + x[0]) / y[0]; + } + b = 1.0; + if (!(x[1] - y[1] > x[1] * s)) { + if (y[1] == 0.0) { + ret = tsd_trace_error(TSD_ERR_ZERO_DIVISION); + goto out; + } + b = (1 - s) * x[1] / y[1]; + } + d = tsd_min(a, b); + if (!(0.0 < d && d <= 1.0)) { + ret = tsd_trace_error(TSD_ERR_INVALID_DAMPING); + goto out; + } + *out = d; +out: + return ret; +} + +/* Find `d` so that `d * x[0] + 1 <= s` or `d * x[0] + 1 >= 1 / s`. */ +int +tsd_rescale(const double x[2], double s, double *out) +{ + int ret = 0; + + if (x[0] == 0.0 && x[1] == 0.0) { + *out = 1.0; + goto out; + } + if (!(0 < x[0] + 1 && 0 < x[1])) { + ret = tsd_trace_error(TSD_ERR_INVALID_NODE_POSTERIOR); + goto out; + } + if (1 + x[0] > s) { + if (x[0] == 0.0) { + ret = tsd_trace_error(TSD_ERR_ZERO_DIVISION); + goto out; + } + *out = (s - 1) / x[0]; + } else if (1 + x[0] < 1 / s) { + /* x[0] is not zero: that would have taken the first branch (s < 1). */ + *out = (1 / s - 1) / x[0]; + } else { + *out = 1.0; + } +out: + return ret; +} + +/* + * Whether the upper bound on each node's age is at least the maximum lower bound of + * its descendants' ages. Writes 1 to `consistent` if so, 0 if not. + */ +int +tsd_constraints_are_consistent(tsd_size_t num_nodes, tsd_size_t num_edges, + const double *constraints, const tsd_id_t *edges_parent, const tsd_id_t *edges_child, + int *consistent) +{ + int ret = 0; + double *lower_max = NULL; + tsd_size_t j; + tsd_id_t p, c; + + ret = tsd_check_edges(num_nodes, num_edges, edges_parent, edges_child); + if (ret != 0) { + goto out; + } + lower_max = malloc((num_nodes > 0 ? num_nodes : 1) * sizeof(*lower_max)); + if (lower_max == NULL) { + ret = tsd_trace_error(TSD_ERR_NO_MEMORY); + goto out; + } + for (j = 0; j < num_nodes; j++) { + lower_max[j] = constraints[2 * j + LOWER]; + } + for (j = 0; j < num_edges; j++) { + p = edges_parent[j]; + c = edges_child[j]; + lower_max[p] = tsd_max(lower_max[c], lower_max[p]); + } + *consistent = 1; + for (j = 0; j < num_nodes; j++) { + if (lower_max[j] > constraints[2 * j + UPPER]) { + *consistent = 0; + break; + } + } +out: + tsd_safe_free(lower_max); + return ret; +} + +/* cavity = posterior - delta * message */ +static void +get_cavity( + const double posterior[2], double delta, const double message[2], double cavity[2]) +{ + cavity[0] = posterior[0] - delta * message[0]; + cavity[1] = posterior[1] - delta * message[1]; +} + +/* The message from a factor, which is stored divided by the scale of the node. */ +static void +get_message(const double factor[2], double scale, double message[2]) +{ + message[0] = factor[0] * scale; + message[1] = factor[1] * scale; +} + +/* + * Update a factor given the cavity and the new posterior: + * factor = factor * (1 - delta) + (posterior - cavity) / scale + */ +static void +update_factor(double factor[2], double delta, const double posterior[2], + const double cavity[2], double scale) +{ + const double keep = 1.0 - delta; + + factor[0] *= keep; + factor[1] *= keep; + factor[0] += (posterior[0] - cavity[0]) / scale; + factor[1] += (posterior[1] - cavity[1]) / scale; +} + +/* Rescale the posterior of a node to keep its shape bounded, and its scale to match. */ +static int +rescale_posterior(double posterior[2], double *scale, double max_shape) +{ + int ret; + double eta; + + ret = tsd_rescale(posterior, max_shape, &eta); + if (ret != 0) { + goto out; + } + posterior[0] *= eta; + posterior[1] *= eta; + *scale *= eta; +out: + return ret; +} + +/* The arguments of the update of one edge (block), shared by all the edges of a pass. */ +typedef struct { + double max_shape; + double min_step; + int unphased; + const double *constraints; + const double *likelihoods; + double *posterior; + double *scale; + double *factor; /* the edge or block factors */ + double *lognorm; +} likelihood_pass_t; + +/* + * Update an edge with a fixed parent (`fixed_parent`) or a fixed child: only the + * free node, `free_node`, has a posterior to update. + */ +static int +update_fixed_edge(const likelihood_pass_t *pass, tsd_id_t i, tsd_id_t fixed_node, + tsd_id_t free_node, int fixed_parent) +{ + int ret = 0; + const int which = fixed_parent ? LEAFWARD : ROOTWARD; + double *post = PAIR(pass->posterior, free_node); + double *factor = FACTOR(pass->factor, i, which); + double *scale = pass->scale + free_node; + const double fixed_age = pass->constraints[2 * (tsd_size_t) fixed_node + LOWER]; + double message[2], cavity[2], edge_likelihood[2], proj[2]; + double delta, logl; + + get_message(factor, *scale, message); + ret = tsd_damp(post, message, pass->min_step, &delta); + if (ret != 0) { + goto out; + } + get_cavity(post, delta, message, cavity); + edge_likelihood[0] = delta * PAIR(pass->likelihoods, i)[0]; + edge_likelihood[1] = delta * PAIR(pass->likelihoods, i)[1]; + if (pass->unphased) { + ret = tsd_sideways_projection(fixed_age, cavity, edge_likelihood, &logl, proj); + } else if (fixed_parent) { + ret = tsd_leafward_projection(fixed_age, cavity, edge_likelihood, &logl, proj); + } else { + ret = tsd_rootward_projection(fixed_age, cavity, edge_likelihood, &logl, proj); + } + if (ret != 0) { + goto out; + } + pass->lognorm[i] = logl; + post[0] = proj[0]; + post[1] = proj[1]; + update_factor(factor, delta, post, cavity, *scale); + ret = rescale_posterior(post, scale, pass->max_shape); +out: + return ret; +} + +/* A block with a single node: the parent of the edge is its child. */ +static int +update_twin_edge(const likelihood_pass_t *pass, tsd_id_t i, tsd_id_t node) +{ + int ret = 0; + double *post = PAIR(pass->posterior, node); + double *factor = FACTOR(pass->factor, i, ROOTWARD); + double *scale = pass->scale + node; + double message[2], cavity[2], edge_likelihood[2], proj[2]; + double delta, logl; + + get_message(factor, *scale, message); + ret = tsd_damp(post, message, pass->min_step, &delta); + if (ret != 0) { + goto out; + } + get_cavity(post, delta, message, cavity); + edge_likelihood[0] = delta * PAIR(pass->likelihoods, i)[0]; + edge_likelihood[1] = delta * PAIR(pass->likelihoods, i)[1]; + if (!pass->unphased) { + ret = tsd_trace_error(TSD_ERR_TWIN_EDGE_IN_PHASED_PASS); + goto out; + } + ret = tsd_twin_projection(cavity, edge_likelihood, &logl, proj); + if (ret != 0) { + goto out; + } + pass->lognorm[i] = logl; + post[0] = proj[0]; + post[1] = proj[1]; + update_factor(factor, delta, post, cavity, *scale); + ret = rescale_posterior(post, scale, pass->max_shape); +out: + return ret; +} + +/* An edge with both nodes free, and a different parent and child. */ +static int +update_free_edge(const likelihood_pass_t *pass, tsd_id_t i, tsd_id_t p, tsd_id_t c) +{ + int ret = 0; + double *post_p = PAIR(pass->posterior, p); + double *post_c = PAIR(pass->posterior, c); + double *factor_p = FACTOR(pass->factor, i, ROOTWARD); + double *factor_c = FACTOR(pass->factor, i, LEAFWARD); + double *scale_p = pass->scale + p; + double *scale_c = pass->scale + c; + double message_p[2], message_c[2], cavity_p[2], cavity_c[2], edge_likelihood[2]; + double proj_p[2], proj_c[2]; + double delta_p, delta_c, delta, logl; + + get_message(factor_p, *scale_p, message_p); + get_message(factor_c, *scale_c, message_c); + ret = tsd_damp(post_p, message_p, pass->min_step, &delta_p); + if (ret != 0) { + goto out; + } + ret = tsd_damp(post_c, message_c, pass->min_step, &delta_c); + if (ret != 0) { + goto out; + } + delta = tsd_min(delta_p, delta_c); + get_cavity(post_p, delta, message_p, cavity_p); + get_cavity(post_c, delta, message_c, cavity_c); + edge_likelihood[0] = delta * PAIR(pass->likelihoods, i)[0]; + edge_likelihood[1] = delta * PAIR(pass->likelihoods, i)[1]; + if (pass->unphased) { + ret = tsd_unphased_projection( + cavity_p, cavity_c, edge_likelihood, &logl, proj_p, proj_c); + } else { + ret = tsd_gamma_projection( + cavity_p, cavity_c, edge_likelihood, &logl, proj_p, proj_c); + } + if (ret != 0) { + goto out; + } + pass->lognorm[i] = logl; + post_p[0] = proj_p[0]; + post_p[1] = proj_p[1]; + post_c[0] = proj_c[0]; + post_c[1] = proj_c[1]; + update_factor(factor_p, delta, post_p, cavity_p, *scale_p); + update_factor(factor_c, delta, post_c, cavity_c, *scale_c); + ret = rescale_posterior(post_p, scale_p, pass->max_shape); + if (ret != 0) { + goto out; + } + ret = rescale_posterior(post_c, scale_c, pass->max_shape); +out: + return ret; +} + +int +tsd_ep_propagate_likelihood(tsd_ep_t *self, tsd_size_t num_order, const tsd_id_t *order, + int unphased, double max_shape, double min_step) +{ + int ret = 0; + const double tiny = sqrt(DBL_MIN); + const double *constraints = self->constraints; + const tsd_size_t num_edges = unphased ? self->num_blocks : self->num_edges; + const tsd_id_t *edges_parent = unphased ? self->blocks_left : self->edges_parent; + const tsd_id_t *edges_child = unphased ? self->blocks_right : self->edges_child; + likelihood_pass_t pass; + tsd_size_t j; + tsd_id_t i, p, c; + int fixed_p, fixed_c; + + if (!(max_shape >= 1.0)) { + ret = tsd_trace_error(TSD_ERR_INVALID_MAX_SHAPE); + goto out; + } + if (!(0.0 < min_step && min_step < 1.0)) { + ret = tsd_trace_error(TSD_ERR_INVALID_MIN_STEP); + goto out; + } + ret = tsd_check_ids(num_order, order, num_edges, 0, + unphased ? TSD_ERR_BLOCK_OUT_OF_BOUNDS : TSD_ERR_EDGE_OUT_OF_BOUNDS); + if (ret != 0) { + goto out; + } + pass.max_shape = max_shape; + pass.min_step = min_step; + pass.unphased = unphased; + pass.constraints = constraints; + pass.likelihoods = unphased ? self->blocks_likelihood : self->edges_likelihood; + pass.posterior = self->posterior; + pass.scale = self->scale; + pass.factor = unphased ? self->block : self->edge; + pass.lognorm = unphased ? self->blocks_lognorm : self->edges_lognorm; + + for (j = 0; j < num_order; j++) { + i = order[j]; + p = edges_parent[i]; + c = edges_child[i]; + if (pass.scale[p] < tiny || pass.scale[c] < tiny) { + tsd_ep_rescale_factors(self); + } + fixed_p = constraints[2 * (tsd_size_t) p + LOWER] + == constraints[2 * (tsd_size_t) p + UPPER]; + fixed_c = constraints[2 * (tsd_size_t) c + LOWER] + == constraints[2 * (tsd_size_t) c + UPPER]; + if (fixed_p && fixed_c) { + continue; + } else if (fixed_p) { + /* a sample is the ancestor of another sample */ + ret = update_fixed_edge(&pass, i, p, c, 1); + } else if (fixed_c) { + /* a sample has age greater than zero */ + ret = update_fixed_edge(&pass, i, c, p, 0); + } else if (p == c) { + /* singleton block with single parent */ + ret = update_twin_edge(&pass, i, p); + } else { + ret = update_free_edge(&pass, i, p, c); + } + if (ret != 0) { + goto out; + } + } +out: + return ret; +} + +/* The prior cavity of a free node: the posterior without the mixture prior factor. */ +static void +get_prior_cavity(const tsd_ep_t *self, tsd_size_t j, double cavity[2]) +{ + double message[2]; + + get_message(FACTOR(self->node, j, MIXPRIOR), self->scale[j], message); + get_cavity(PAIR(self->posterior, j), 1.0, message, cavity); +} + +/* + * The mean over free nodes of shape / rate, with `penalty` added to the rate if + * `with_penalty`, summing sequentially. + */ +static double +mean_shape_over_rate( + const tsd_ep_t *self, const uint8_t *free, int with_penalty, double penalty) +{ + double cavity[2]; + double shape, rate, term; + double total = 0.0; + tsd_size_t j, count = 0; + + for (j = 0; j < self->num_nodes; j++) { + if (free[j]) { + get_prior_cavity(self, j, cavity); + shape = cavity[0] + 1; + rate = cavity[1]; + if (with_penalty) { + rate = rate + penalty; + } + term = shape / rate; + total += term; + count++; + } + } + return total / (double) count; +} + +int +tsd_ep_propagate_prior(tsd_ep_t *self, const uint8_t *free, double max_shape, + int64_t em_maxitt, double em_reltol) +{ + int ret = 0; + const tsd_size_t num_nodes = self->num_nodes; + double *posterior = self->posterior; + double cavity[2]; + double penalty, delta; + int64_t itt; + tsd_size_t j; + int any_free = 0; + + if (!(max_shape >= 1.0)) { + ret = tsd_trace_error(TSD_ERR_INVALID_MAX_SHAPE); + goto out; + } + for (j = 0; j < num_nodes; j++) { + any_free = any_free || free[j]; + } + if (!any_free) { + goto out; + } + + /* fit an exponential to cavity distributions for unconstrained nodes */ + penalty = 1 / mean_shape_over_rate(self, free, 0, 0.0); + itt = 0; + delta = INFINITY; + while (fabs(delta) > fabs(penalty) * em_reltol) { + if (itt > em_maxitt) { + break; + } + delta = 1 / mean_shape_over_rate(self, free, 1, penalty) - penalty; + penalty += delta; + itt++; + } + if (!(penalty > 0)) { + ret = tsd_trace_error(TSD_ERR_NONPOSITIVE_PENALTY); + goto out; + } + + /* update posteriors and rescale to keep shape bounded */ + for (j = 0; j < num_nodes; j++) { + if (free[j]) { + get_prior_cavity(self, j, cavity); + PAIR(posterior, j)[1] = cavity[1] + penalty; + FACTOR(self->node, j, MIXPRIOR) + [0] = (PAIR(posterior, j)[0] - cavity[0]) / self->scale[j]; + FACTOR(self->node, j, MIXPRIOR) + [1] = (PAIR(posterior, j)[1] - cavity[1]) / self->scale[j]; + } + } + for (j = 0; j < num_nodes; j++) { + if (free[j]) { + ret = rescale_posterior(PAIR(posterior, j), self->scale + j, max_shape); + if (ret != 0) { + goto out; + } + } + } +out: + return ret; +} + +/* The arguments of the projection of mutations; nothing is updated. */ +typedef struct { + int unphased; + const double *constraints; + const double *likelihoods; + const double *posterior; + const double *scale; + const double *factor; /* the edge or block factors */ +} mutation_pass_t; + +/* + * The posterior of one mutation, from the edge (block) above it: with both nodes + * fixed, the age of each; with one fixed, the fixed age and the cavity of the other; + * otherwise the cavities of both. The messages are not damped (the step is one). + */ +static int +project_mutation(const mutation_pass_t *pass, tsd_id_t i, tsd_id_t p, tsd_id_t c, + double *phase, double proj[2]) +{ + int ret = 0; + const double *constraints = pass->constraints; + const int fixed_p = constraints[2 * (tsd_size_t) p + LOWER] + == constraints[2 * (tsd_size_t) p + UPPER]; + const int fixed_c = constraints[2 * (tsd_size_t) c + LOWER] + == constraints[2 * (tsd_size_t) c + UPPER]; + const double age_p = constraints[2 * (tsd_size_t) p + LOWER]; + const double age_c = constraints[2 * (tsd_size_t) c + LOWER]; + const double *post_p = PAIR(pass->posterior, p); + const double *post_c = PAIR(pass->posterior, c); + const double *likelihood = PAIR(pass->likelihoods, i); + double message_p[2], message_c[2], cavity_p[2], cavity_c[2]; + + get_message(FACTOR(pass->factor, i, ROOTWARD), pass->scale[p], message_p); + get_message(FACTOR(pass->factor, i, LEAFWARD), pass->scale[c], message_c); + get_cavity(post_p, 1.0, message_p, cavity_p); + get_cavity(post_c, 1.0, message_c, cavity_c); + if (fixed_p && fixed_c) { + if (pass->unphased) { + ret = tsd_mutation_block_projection(age_p, age_c, phase, proj); + } else { + ret = tsd_mutation_edge_projection(age_p, age_c, phase, proj); + } + } else if (fixed_p) { + if (pass->unphased) { + ret = tsd_mutation_sideways_projection( + age_p, cavity_c, likelihood, phase, proj); + } else { + ret = tsd_mutation_leafward_projection( + age_p, cavity_c, likelihood, phase, proj); + } + } else if (fixed_c) { + if (pass->unphased) { + ret = tsd_mutation_sideways_projection( + age_c, cavity_p, likelihood, phase, proj); + } else { + ret = tsd_mutation_rootward_projection( + age_c, cavity_p, likelihood, phase, proj); + } + } else if (p == c) { + /* singleton block with single parent */ + ret = tsd_mutation_twin_projection(cavity_p, likelihood, phase, proj); + } else if (pass->unphased) { + ret = tsd_mutation_unphased_projection( + cavity_p, cavity_c, likelihood, phase, proj); + } else { + ret = tsd_mutation_gamma_projection(cavity_p, cavity_c, likelihood, phase, proj); + } + return ret; +} + +int +tsd_ep_propagate_mutations(const tsd_ep_t *self, tsd_size_t num_mutations, + const tsd_id_t *mutations_edge, int unphased, double *mutations_posterior, + double *mutations_phase) +{ + int ret = 0; + const tsd_size_t num_edges = unphased ? self->num_blocks : self->num_edges; + const tsd_id_t *edges_parent = unphased ? self->blocks_left : self->edges_parent; + const tsd_id_t *edges_child = unphased ? self->blocks_right : self->edges_child; + mutation_pass_t pass; + tsd_size_t m; + tsd_id_t i; + double phase, proj[2]; + + ret = tsd_check_ids(num_mutations, mutations_edge, num_edges, 1, + unphased ? TSD_ERR_BLOCK_OUT_OF_BOUNDS : TSD_ERR_EDGE_OUT_OF_BOUNDS); + if (ret != 0) { + goto out; + } + pass.unphased = unphased; + pass.constraints = self->constraints; + pass.likelihoods = unphased ? self->blocks_likelihood : self->edges_likelihood; + pass.posterior = self->posterior; + pass.scale = self->scale; + pass.factor = unphased ? self->block : self->edge; + for (m = 0; m < num_mutations; m++) { + mutations_posterior[2 * m] = NAN; + mutations_posterior[2 * m + 1] = NAN; + mutations_phase[m] = 1.0; + i = mutations_edge[m]; + if (i == TSD_NULL) { /* a mutation above a root */ + continue; + } + ret = project_mutation(&pass, i, edges_parent[i], edges_child[i], &phase, proj); + if (ret != 0) { + goto out; + } + mutations_phase[m] = phase; + mutations_posterior[2 * m] = proj[0]; + mutations_posterior[2 * m + 1] = proj[1]; + } +out: + return ret; +} diff --git a/pyproject.toml b/pyproject.toml index 6a302b1a..6750e360 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -50,8 +50,6 @@ dependencies = [ "tskit>=1.0.0", "numpy", "scipy>=1.13.0", - "numba>=0.58.1", - "mpmath", "tqdm", "appdirs", ] @@ -77,7 +75,6 @@ test = [ "pytest-cov", "msprime", "tsinfer", - "numdifftools", "matplotlib", ] @@ -163,13 +160,9 @@ known-third-party = [ build = ["cp311-*", "cp312-*", "cp313-*", "cp314-*", "cp315-*"] build-frontend = "build" build-verbosity = 1 -# scipy and numba publish no win32 wheels, and numba none for musllinux, so -# installing these wheels would mean building the dependencies from source. -skip = ["*musllinux*", "*-win32"] -# numba publishes no macOS x86_64 wheels after 0.62.1 (none at all for -# Python >= 3.14), so the install test fails there. Build these wheels, but -# only test them once numba is no longer a dependency. -test-skip = ["*-macosx_x86_64"] +# scipy publishes no win32 wheels, so installing these wheels would mean building +# it from source. +skip = ["*-win32"] test-command = [ "python -c \"import _tsdate\"", "tsdate --help", diff --git a/setup.py b/setup.py index e9b07c08..65b09b83 100644 --- a/setup.py +++ b/setup.py @@ -9,7 +9,17 @@ libdir = "lib" includes = [libdir] -tsd_source_files = ["err.c"] +tsd_source_files = [ + "err.c", + "gammaincinv.c", + "hypergeo.c", + "approx.c", + "rescaling.c", + "phasing.c", + "util.c", + "prior.c", + "variational.c", +] sources = ["_tsdatemodule.c"] + [os.path.join(libdir, f) for f in tsd_source_files] diff --git a/tests/conftest.py b/tests/conftest.py index d0f9dc15..8d200e4e 100644 --- a/tests/conftest.py +++ b/tests/conftest.py @@ -1,3 +1,5 @@ +import msprime +import numpy as np import pytest @@ -32,3 +34,48 @@ def pytest_configure(config): config.addinivalue_line( "markers", "makefiles: mark test to run only when --make-files option given" ) + + +@pytest.fixture +def rng(): + return np.random.default_rng(1024) + + +def _small_ts(samples, seed, mutation_rate=2e-8): + ts = msprime.sim_ancestry( + samples=samples, + population_size=1e4, + recombination_rate=1e-8, + sequence_length=2e5, + random_seed=seed, + ) + return msprime.sim_mutations(ts, rate=mutation_rate, random_seed=seed) + + +@pytest.fixture(scope="session") +def small_ts(): + """ + 20 contemporary diploid samples, ~2e5 bp, with mutations. + """ + return _small_ts(20, seed=11) + + +@pytest.fixture(scope="session") +def small_ts_unphased(): + """ + Like `small_ts` (15 diploids) with a high mutation rate so that there are many + singletons; use with ``singletons_phased=False``. Samples belong to individuals. + """ + return _small_ts(15, seed=12, mutation_rate=1e-7) + + +@pytest.fixture(scope="session") +def small_ts_historical(): + """ + 15 diploid samples, 5 of them sampled at time 500 (non-contemporary). + """ + samples = [ + msprime.SampleSet(10, ploidy=2, time=0), + msprime.SampleSet(5, ploidy=2, time=500), + ] + return _small_ts(samples, seed=13) diff --git a/tests/distribution_functions.py b/tests/distribution_functions.py deleted file mode 100644 index 6eb2d567..00000000 --- a/tests/distribution_functions.py +++ /dev/null @@ -1,506 +0,0 @@ -# MIT License -# -# Copyright (C) 2023 Tskit Developers -# Copyright (C) 2023 University of Oxford -# -# Permission is hereby granted, free of charge, to any person obtaining a copy -# of this software and associated documentation files (the "Software"), to deal -# in the Software without restriction, including without limitation the rights -# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -# copies of the Software, and to permit persons to whom the Software is -# furnished to do so, subject to the following conditions: -# -# The above copyright notice and this permission notice shall be included in all -# copies or substantial portions of the Software. -# -# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE -# SOFTWARE. -""" -Utility functions to construct distributions used in variational inference, -for testing purposes -""" - -import mpmath -import numpy as np -import scipy.integrate -import scipy.special - -from tsdate import approx, hypergeo - - -def kl_divergence(p, logq): - """ - KL(p||q) divergence for fixed p - """ - val, _ = scipy.integrate.quad(lambda x: -p(x) * logq(x), 0, np.inf) - return val - - -def conditional_coalescent_pdf(t, n, k): - """ - Evaluate the PDF of the conditional coalescent, using results from Wiuf and - Donnelly (1999). - """ - - def pr_t_bar_a(t, a, n): - """ - Phase-type distribution for sum of waiting times during which - there are n, n-1, ..., a+1 ancestors. - """ - lineages = np.arange(n, a, -1) - rate = (lineages * (lineages - 1)) / 2 - weight = [] - for i in range(len(rate)): - weight.append(1) - for j in range(len(rate)): - if i != j: - weight[-1] *= rate[j] / (rate[j] - rate[i]) - weight = np.array(weight) - val = np.sum(weight * rate * np.exp(-rate * t)) - return val - - def pr_a(a, n, k): - """ - Hypergeometric-ish distribution for number of ancestors "a" after - subsample of size "k" has coalesced in tree of size "n" - """ - return np.exp( - np.log(n + 1) - + scipy.special.betaln(n - k, k + 2) - - np.log(n - a) - - scipy.special.betaln(n - a - k + 2, k - 1) - - np.log(a + 1) - - scipy.special.betaln(a - 1, 3) - ) - - if n == k: - return pr_t_bar_a(t, 1) - else: - return np.sum([pr_a(a, n, k) * pr_t_bar_a(t, a, n) for a in range(2, n - k + 2)]) - - -class TiltedGammaDiff: - r""" - The distribution of the difference of two gamma RVs restricted to the - positive reals, tilted by an exponential function. - - Specifically, for p(x; a, b) = b^a/Gamma(a) x^{a-1} e^{-xb}, this is - - p(u; a1, a2, a3, b1, b2, b3) \propto p(u, a3, b3) \times - \int_u^inf p(x; a1, b1) p(x - u; a2, b2) dx, u \geq 0 - """ - - @staticmethod - def _2F1(a, b, c, z): - """ - log of |Re| for Gaussian hypergeometric function - """ - val = mpmath.log(mpmath.hyp2f1(a, b, c, z)) - return float(val) - - @staticmethod - def _U(a, b, z): - """ - log of |Re| for confluent hypergeometric function of the second kind - """ - val = mpmath.log(mpmath.hyperu(a, b, z)) - return float(val) - - def __init__(self, shape1, shape2, shape3, rate1, rate2, rate3, reorder=True): - assert shape1 > 0 - assert shape2 > 0 - assert shape3 > 0 - assert rate1 >= 0 - assert rate2 > 0 - assert rate3 >= 0 - # for convergence of 2F1, we need rate2 > rate3. Invariant - # transformations of 2F1 allow us to switch arguments, with - # appropriate rescaling - self.reparametrize = rate3 > rate2 - self.shape1 = shape1 - self.shape2 = shape2 - self.shape3 = shape3 - self.rate1 = rate1 - self.rate2 = rate2 - self.rate3 = rate3 - mu = (1.0 - shape1 - shape2) / 2 - nu = (shape3 - 1) + (shape1 + shape2) / 2 - zeta = 1 / 2 - (rate2 - rate3) / (rate1 + rate2) - assert zeta > -1 / 2, "Invalid parameters" - assert nu + 1 / 2 > abs(mu), "Invalid parameters" - - def pdf(self, x): - r""" - Probability density function, derived using equation 3.383.4 from - Gradshteyn & Ryzhik (2000) "Table of Integrals, Series, and Products" - - That is: - - u^{a3 - 1} e^{(b2 - b3) u} \times - \int_u^inf x^{a1-1} (x-u)^{a2-1} e^{-x(b1+b2)} dx = - u^{a3 - 1} e^{(b2 - b3) u} (b1+b2)^{-(a1+a2)/2} Gamma(a2) \times - u^{(a1+a2)/2-1} e^{-(b1+b2)/2 u} W((a1-a2)/2, (1-a1-a2)/2, (b1+b2)u) = - (b1+b2)^{-(a1+a2)/2} Gamma(a2) u^{a3 + (a1+a2)/2 - 2} \times - e^{-u(b1+b2)(1/2+(b3 - b2)/(b1 + b2))} \times - W((a1-a2)/2, (1-a1-a2)/2, (b1+b2)u) - - s.t. a2 > 0, (b1+b2)u > 0 - - Change variables, t = (b1+b2)*u and integrate t using 13.23.4 of DLMF, - to find the normalizing constant: - - (b1+b2)^{-(a1+a2)/2} Gamma(a2) (b1+b2)^{-a3-(a1+a2)/2+2} \times - \int_0^inf t^{a3+(a1+a2)/2-2} e^{-t (1/2+(b3-b2)/(b1+b2))} \times - W((a1-a2)/2, (1-a1-a2)/2, t) 1/(b1+b2) dt = - (b1+b2)^{-a1-a2-a3+1} Gamma(a1+a2+a3-1) Beta(a2,a3) \times - 2F1(a1+a2+a3-1, a3, a3+a2, (b2-b3)/(b1+b2)) - - Note that 2F1 is regularized in this equation, e.g. 2F1(a,b;c;z) = - 2F1(a,b;c;z)/Gamma(c) - - Transform W to U, and use Kummer's transformations: - - W((a1-a2)/2, (1-a1-a2)/2, (b1+b2)u) = - exp(-u(b1+b2)/2) (b1+b2)^(1-a1/2-a2/2) \times - u^(1-a1/2-a2/2) U(1-a1, 2-a1-a2, (b1+b2)u) = - exp(-u(b1+b2)/2) (b1+b2)^(a1/2+a2/2) \times - u^(a1/2+a2/2) U(a2, a1+a2, (b1+b2)u) - - so that the kernel becomes, - - Gamma(a2) u^(a3 + a1 + a2 - 2) \times - e^(-u(b1+b3)) U(a2, a1+a2, (b1+b2)u) - - In the special case where b1 == b3 == 0 and a1 == a3 == 1, the integral - becomes (via 3.382.2 GR2000): - - e^{u b2} \int_u^inf (x-u)^{a2-1} e^{-x b2} dx = Gamma(a2) b2^{-a2} - - e.g. a constant (this should never happen if the edge update order is - correct and samples are fixed to the present day, or if a proper prior - is used) - """ - assert x >= 0.0, "PDF is only defined for non-negative reals" - A = self.shape1 + self.shape2 + self.shape3 - 1 - B = self.shape3 - C = self.shape2 + self.shape3 - S = self.rate2 - self.rate3 - T = self.rate2 + self.rate1 - if self.reparametrize: - val = ( - scipy.stats.gamma.logpdf(x, A, scale=1 / (self.rate1 + self.rate3)) - + self._U( - self.shape2, - self.shape1 + self.shape2, - (self.rate1 + self.rate2) * x, - ) - + scipy.special.loggamma(self.shape2 + self.shape3) - - scipy.special.loggamma(self.shape3) - - self._2F1(A, C - B, C, S / (S - T)) - ) - else: - val = ( - scipy.stats.gamma.logpdf(x, A, scale=1 / (self.rate1 + self.rate3)) - + self._U( - self.shape2, - self.shape1 + self.shape2, - (self.rate1 + self.rate2) * x, - ) - + scipy.special.loggamma(self.shape2 + self.shape3) - - scipy.special.loggamma(self.shape3) - + A * np.log(T / (T - S)) - - self._2F1(A, B, C, S / T) - ) - return np.exp(val) - - def moments(self): - r""" - Returns the first two raw moments. - - Derived from differentiating the Laplace transform, and using the relation - - d^n 2F1(A, B, C, z) / dz^n = a_n b_n / c_n 2F1(A + 1, B + 1, C + 1, z) - - where x_n = x (x + 1) \dots (x + n - 1) is the rising factorial and 2F1 is the - Gaussian hypergeometric function. See 15.5.2 in DLMF. - """ - A = self.shape1 + self.shape2 + self.shape3 - 1 - B = self.shape3 - C = self.shape2 + self.shape3 - S = self.rate2 - self.rate3 - T = self.rate1 + self.rate2 - numer = 0 - denom = 0 - moments = [] - if self.reparametrize: - F0 = self._2F1(A, C - B, C, S / (S - T)) - A * np.log(1 - S / T) - for i in range(2): - numer += np.log(A + i) + np.log(B + i) - np.log(C + i) - np.log(T) - denom = ( - F0 - - self._2F1(A + i + 1, C - B, C + i + 1, S / (S - T)) - + (A + i + 1) * np.log(1 - S / T) - ) - moments.append(np.exp(numer - denom)) - else: - F0 = self._2F1(A, B, C, S / T) - for i in range(2): - numer += np.log(A + i) + np.log(B + i) - np.log(C + i) - np.log(T) - denom = F0 - self._2F1(A + i + 1, B + i + 1, C + i + 1, S / T) - moments.append(np.exp(numer - denom)) - return moments[0], moments[1] - - def sufficient_statistics(self): - r""" - Return E[x], E[x^2], and E[log x]. - - To get raw moments use the Laplace transform E[e^{-su}]: - - (b1+b2)^{-a1-a2-a3+1} Gamma(a1+a2+a3-1) Beta(a2,a3) \times - 2F1(a1+a2+a3-1, a3, a3+a2, (b2-b3-s)/(b1+b2)) - - To get log moments use the Mellin transform E[u^s]: - - (b1+b2)^{-a1-a2-a3-s+1} Gamma(a1+a2+a3+s-1) Beta(a2,a3+s) \times - 2F1(a1+a2+a3+s-1, a3+s, a3+s+a2, (b2-b3)/(b1+b2)) - - In both cases: differentiate wrt s, evaluate at zero, and normalize - """ - A = self.shape1 + self.shape2 + self.shape3 - 1 - B = self.shape3 - C = self.shape2 + self.shape3 - S = self.rate2 - self.rate3 - T = self.rate1 + self.rate2 - if self.reparametrize: - # underflow protection is used, so the actual derivatives are - # np.exp(F) * dF_dz, etc. - F, dF_da, _, dF_dc, dF_dz, d2F_dz2 = hypergeo._hyp2f1_series( - A, - C - B, - C, - S / (S - T), - ) - logconst = ( - F - + scipy.special.betaln(self.shape2, self.shape3) - + scipy.special.loggamma(A) - - A * np.log(T - S) - ) - x = -dF_dz * T / (S - T) ** 2 - A / (S - T) - xsq = ( - d2F_dz2 * T**2 / (S - T) ** 4 - + A * (A + 1) / (T - S) ** 2 - + 2 * dF_dz * (1 + A) * T / (S - T) ** (3) - ) - logx = ( - (dF_da + dF_dc) - + -np.log(1 - S / T) - + scipy.special.digamma(A) - + scipy.special.digamma(B) - - scipy.special.digamma(C) - - np.log(T) - ) - else: - F, dF_da, dF_db, dF_dc, dF_dz, d2F_dz2 = hypergeo._hyp2f1_series( - A, - B, - C, - S / T, - ) - logconst = ( - F - + scipy.special.betaln(self.shape2, self.shape3) - + scipy.special.loggamma(A) - - A * np.log(T) - ) - x = dF_dz / T - xsq = d2F_dz2 / T**2 - logx = ( - (dF_da + dF_db + dF_dc) - + scipy.special.digamma(A) - + scipy.special.digamma(B) - - scipy.special.digamma(C) - - np.log(T) - ) - return logconst, x, xsq, logx - - def to_gamma(self, minimize_kl=True): - """ - Return the shape and rate parameters of a gamma distribution with the - same expected sufficient statistics (if ``minimize_kl`` is ``True``), and - otherwise one with the same mean and variance. - """ - logconst, x, xsq, logx = self.sufficient_statistics() - if minimize_kl: - _, xlogx, _ = approx.approximate_log_moments(x, xsq) - alpha, beta = approx.approximate_gamma_kl(x, logx, xlogx) - else: - alpha, beta = approx.approximate_gamma_mom(x, xsq) - return logconst, alpha, beta - - -class TiltedGammaSum: - r""" - The distribution of the sum of two gamma RVs, tilted by an exponential function. - - Specifically, for p(x; a, b) = b^a/Gamma(a) x^{a-1} e^{-xb}, this is - - p(u; a1, a2, a3, b1, b2, b3) \propto p(u; a3, b3) \times - \int_0^u p(x; a1, b1) p(u - x; a2, b2) dx, u \geq 0 - """ - - @staticmethod - def _2F1(a, b, c, z): - """ - log of |Re| for Gaussian hypergeometric function - """ - val = mpmath.log(mpmath.hyp2f1(a, b, c, z)) - return float(val) - - @staticmethod - def _M(a, b, x): - """ - log of |Re| for confluent hypergeometric function (aka 1F1) - """ - val = mpmath.log(mpmath.hyp1f1(a, b, x)) - return float(val) - - def __init__(self, shape1, shape2, shape3, rate1, rate2, rate3): - assert shape1 > 0 - assert shape2 > 0 - assert shape3 > 0 - assert rate1 >= 0 - assert rate2 > 0 - assert rate3 >= 0 - # for numeric stability of hypergeometric we need rate2 > rate1 - # as this is a convolution, the order of (1) and (2) don't matter - self.reparametrize = rate1 > rate2 - self.shape1 = shape2 if self.reparametrize else shape1 - self.shape2 = shape1 if self.reparametrize else shape2 - self.shape3 = shape3 - self.rate1 = rate2 if self.reparametrize else rate1 - self.rate2 = rate1 if self.reparametrize else rate2 - self.rate3 = rate3 - assert shape1 + shape2 + shape3 - 1 > 0, "Invalid parameters" - assert rate3 + rate2 > max(0, rate2 - rate1), "Invalid parameters" - - def pdf(self, x): - r""" - Probability density function, derived using equation 3.383.1 from - Gradshteyn & Ryzhik (2000) "Table of Integrals, Series, and Products" - - u^{a3-1} e^{-u b3} \times - \int_0^u x^{a1-1} (u-x)^{a2-1} e^{-x b1} e^{-(u-x) b2} dx = - u^{a3-1} e^{-u (b2 + b3)} \times - \int_0^u x^{a1-1} (u-x)^{a2-1} e^{x (b2-b1)} dx = - Beta(a2, a1) u^{a1 + a2 + a3 - 2} e^{-u (b2+b3)} M(a1, a1+a2, (b2-b1) u) - - s.t. a1 > 0, a2 > 0 - - Then integrate u using 13.10.3 of DLMF -- note that this equation is - regularized, so that we have M(a,c,kt)/Gamma(c) and - 2F1(a,b;c;z)/Gamma(c) - - \int_0^\infty e^{-u (b2+b3)} u^{a1+a2+a3-2} M(a1, a1+a2, (b2-b1) u) du = - Gamma(a1+a2+a3-1) (b2+b3)^{-a1-a2-a3+1} \times - 2F1(a1, a1+a2+a3-1, a1+a2, (b2-b1)/(b2+b3)) - - s.t. a1+a2 > 1 - s.t. b2 > max(b2-b1, 0) - - In the special case where b1 == b3 == 0 and a1 == a3 == 1, the integrals - become (via 3.382.1 in GR2000): - - e^{-u b2} \int_0^u (u-x)^{a2-1} e^{x b2} dx = b2^(-a2) gamma(a2, b2 u) - - which is improper (this special case should never happen if edge order - is correct or priors are proper) - """ - assert x >= 0.0, "PDF is only defined for non-negative reals" - A = self.shape1 - B = self.shape1 + self.shape2 + self.shape3 - 1 - C = self.shape1 + self.shape2 - T = self.rate2 - self.rate1 - S = self.rate2 + self.rate3 - val = ( - scipy.stats.gamma.logpdf(x, B, scale=1 / S) - + self._M(self.shape1, self.shape1 + self.shape2, T * x) - - self._2F1(A, B, C, T / S) - ) - return np.exp(val) - - def moments(self): - r""" - First two raw moments, from differentiating the Laplace transform - """ - A = self.shape1 - B = self.shape1 + self.shape2 + self.shape3 - 1 - C = self.shape1 + self.shape2 - T = self.rate2 - self.rate1 - S = self.rate2 + self.rate3 - F0 = self._2F1(A, B, C, T / S) - Z1 = np.log(A) + np.log(B) - np.log(C) - F1 = self._2F1(A + 1, B + 1, C + 1, T / S) - Z2 = Z1 + np.log(A + 1) + np.log(B + 1) - np.log(C + 1) - F2 = self._2F1(A + 2, B + 2, C + 2, T / S) - x = np.exp(F1 - F0 + Z1) * T / S**2 + B / S - xsq = ( - B * (B + 1) / S**2 - + 2 * (B + 1) * T / S**3 * np.exp(Z1 + F1 - F0) - + T**2 / S**4 * np.exp(Z2 + F2 - F0) - ) - return x, xsq - - def sufficient_statistics(self): - r""" - Return E[x], E[x^2], and E[log x]. - - To get raw moments use the Laplace transform E[e^{-su}]: - - Gamma(a1+a2+a3-1) (b2+b3+s)^{-a1-a2-a3+1} \times - 2F1(a1, a1+a2+a3-1, a1+a2, (b2-b1)/(b2+b3+s)) - - To get log moments use the Mellin transform E[u^s]: - - Gamma(a1+a2+a3+s-1) (b2+b3)^{-a1-a2-a3+s+1} \times - 2F1(a1, a1+a2+a3+s-1, a1+a2, (b2-b1)/(b2+b3)) - - In both cases: differentiate wrt s, evaluate at zero, and normalize - """ - A = self.shape1 - B = self.shape1 + self.shape2 + self.shape3 - 1 - C = self.shape1 + self.shape2 - T = self.rate2 - self.rate1 - S = self.rate2 + self.rate3 - # underflow protection is used, so the actual derivatives are - # np.exp(F) * dF_dz, etc. - F, _, dF_db, _, dF_dz, d2F_dz2 = hypergeo._hyp2f1_series(A, B, C, T / S) - logconst = ( - F - + scipy.special.loggamma(B) - - B * np.log(S) - + scipy.special.betaln(self.shape1, self.shape2) - ) - x = dF_dz * T / S**2 + B / S - xsq = d2F_dz2 * T**2 / S**4 + B * (B + 1) / S**2 + 2 * dF_dz * (1 + B) * T / S**3 - logx = dF_db + scipy.special.digamma(B) - np.log(S) - return logconst, x, xsq, logx - - def to_gamma(self, minimize_kl=True): - """ - Return the shape and rate parameters of a gamma distribution with the - same expected sufficient statistics (if ``minimize_kl`` is ``True``), and - otherwise one with the same mean and variance. - """ - logconst, x, xsq, logx = self.sufficient_statistics() - if minimize_kl: - _, xlogx, _ = approx.approximate_log_moments(x, xsq) - alpha, beta = approx.approximate_gamma_kl(x, logx, xlogx) - else: - alpha, beta = approx.approximate_gamma_mom(x, xsq) - return logconst, alpha, beta diff --git a/tests/exact_moments.py b/tests/exact_moments.py deleted file mode 100644 index 827d00c8..00000000 --- a/tests/exact_moments.py +++ /dev/null @@ -1,1036 +0,0 @@ -# flake8: noqa -""" -Moments for EP updates using exact hypergeometric evaluations rather than -a Laplace approximation; intended for testing and accuracy benchmarking. -""" - -from math import exp -from math import log - -import mpmath -import numpy as np -import scipy -from scipy.special import betaln -from math import lgamma - - -def moments(a_i, b_i, a_j, b_j, y_ij, mu_ij): - """ - log p(t_i, t_j) := \ - log(t_i - t_j) * y_ij - mu_ij * (t_i - t_j) + \ - log(t_i) * (a_i - 1) - b_i * t_i + \ - log(t_j) * (a_j - 1) - b_j * t_j - """ - a = a_j - b = a_i + a_j + y_ij - c = a_j + y_ij + 1 - t = mu_ij + b_i - z = (mu_ij - b_j) / t - f0 = float(mpmath.log(mpmath.hyp2f1(a + 0, b + 0, c + 0, z))) - f1 = float(mpmath.log(mpmath.hyp2f1(a + 1, b + 1, c + 1, z))) - f2 = float(mpmath.log(mpmath.hyp2f1(a + 2, b + 2, c + 2, z))) - s1 = a * b / c - s2 = s1 * (a + 1) * (b + 1) / (c + 1) - d1 = s1 * exp(f1 - f0) - d2 = s2 * exp(f2 - f0) - logl = f0 + betaln(y_ij + 1, a) + lgamma(b) - b * log(t) - mn_j = d1 / t - sq_j = d2 / t**2 - va_j = sq_j - mn_j**2 - mn_i = mn_j * z + b / t - sq_i = sq_j * z**2 + (b + 1) * (mn_i + mn_j * z) / t - va_i = sq_i - mn_i**2 - return logl, mn_i, va_i, mn_j, va_j - - -def rootward_moments(t_j, a_i, b_i, y_ij, mu_ij): - """ - log p(t_i) := \ - log(t_i - t_j) * y_ij - mu_ij * (t_i - t_j) + \ - log(t_i) * (a_i - 1) - b_i * t_i - """ - assert t_j >= 0.0 - s = a_i + y_ij - r = mu_ij + b_i - a = y_ij + 1 - b = s + 1 - z = t_j * r - if t_j == 0.0: - logl = lgamma(s) - s * log(r) - mn_i = s / r - va_i = s / r**2 - return logl, mn_i, va_i - f0 = float(mpmath.log(mpmath.hyperu(a + 0, b + 0, z))) - f1 = float(mpmath.log(mpmath.hyperu(a + 1, b + 1, z))) - f2 = float(mpmath.log(mpmath.hyperu(a + 2, b + 2, z))) - d0 = -a * exp(f1 - f0) - d1 = -(a + 1) * exp(f2 - f1) - logl = f0 - b_i * t_j + (b - 1) * log(t_j) + lgamma(a) - mn_i = t_j * (1 - d0) - va_i = t_j**2 * d0 * (d1 - d0) - return logl, mn_i, va_i - - -def leafward_moments(t_i, a_j, b_j, y_ij, mu_ij): - """ - log p(t_j) := \ - log(t_i - t_j) * y_ij - mu_ij * (t_i - t_j) + \ - log(t_j) * (a_j - 1) - b_j * t_j - """ - assert t_i > 0.0 - a = a_j - b = a_j + y_ij + 1 - z = t_i * (mu_ij - b_j) - f0 = float(mpmath.log(mpmath.hyp1f1(a + 0, b + 0, z))) - f1 = float(mpmath.log(mpmath.hyp1f1(a + 1, b + 1, z))) - f2 = float(mpmath.log(mpmath.hyp1f1(a + 2, b + 2, z))) - d1 = a / b * exp(f1 - f0) - d2 = a / b * (a + 1) / (b + 1) * exp(f2 - f0) - logl = f0 - mu_ij * t_i + (b - 1) * log(t_i) + betaln(a, b - a) - mn_j = t_i * d1 - sq_j = t_i**2 * d2 - va_j = sq_j - mn_j**2 - return logl, mn_j, va_j - - -def unphased_moments(a_i, b_i, a_j, b_j, y_ij, mu_ij): - """ - log p(t_i, t_j) := \ - log(t_i + t_j) * y_ij - mu_ij * (t_i + t_j) + \ - log(t_i) * (a_i - 1) - b_i * t_i + \ - log(t_j) * (a_j - 1) - b_j * t_j - """ - a = a_j - b = a_i + a_j + y_ij - c = a_j + a_i - t = mu_ij + b_i - z = (mu_ij + b_j) / t - f0 = float(mpmath.log(mpmath.hyp2f1(a + 0, b + 0, c + 0, 1 - z))) - f1 = float(mpmath.log(mpmath.hyp2f1(a + 1, b + 1, c + 1, 1 - z))) - f2 = float(mpmath.log(mpmath.hyp2f1(a + 2, b + 2, c + 2, 1 - z))) - s1 = a * b / c - s2 = s1 * (a + 1) * (b + 1) / (c + 1) - d1 = s1 * exp(f1 - f0) - d2 = s2 * exp(f2 - f0) - logl = f0 + betaln(a_j, a_i) + lgamma(b) - b * log(t) - mn_j = d1 / t - sq_j = d2 / t**2 - va_j = sq_j - mn_j**2 - mn_i = b / t - mn_j * z - sq_i = sq_j * z**2 + (b + 1) * (mn_i - mn_j * z) / t - va_i = sq_i - mn_i**2 - return logl, mn_i, va_i, mn_j, va_j - - -def twin_moments(a_i, b_i, y_ij, mu_ij): - """ - log p(t_i) := \ - log(2 * t_i) * y_ij - mu_ij * (2 * t_i) + \ - log(t_i) * (a_i - 1) - b_i * t_i - """ - s = a_i + y_ij - r = b_i + 2 * mu_ij - logl = log(2) * y_ij + lgamma(s) - log(r) * s - mn_i = s / r - va_i = s / r**2 - return logl, mn_i, va_i - - -def sideways_moments(t_i, a_j, b_j, y_ij, mu_ij): - """ - log p(t_j) := \ - log(t_i + t_j) * y_ij - mu_ij * (t_i + t_j) + \ - log(t_j) * (a_j - 1) - b_j * t_j - """ - assert t_i > 0.0 - a = a_j - b = a_j + y_ij + 1 - z = t_i * (mu_ij + b_j) - f0 = float(mpmath.log(mpmath.hyperu(a + 0, b + 0, z))) - f1 = float(mpmath.log(mpmath.hyperu(a + 1, b + 1, z))) - f2 = float(mpmath.log(mpmath.hyperu(a + 2, b + 2, z))) - d0 = -a * exp(f1 - f0) - d1 = -(a + 1) * exp(f2 - f1) - logl = f0 - mu_ij * t_i + (b - 1) * log(t_i) + lgamma(a) - mn_j = -t_i * d0 - va_j = t_i**2 * d0 * (d1 - d0) - return logl, mn_j, va_j - - -def mutation_moments(a_i, b_i, a_j, b_j, y_ij, mu_ij): - """ - log p(t_m, t_i, t_j) := \ - log(t_i - t_j) * y_ij - mu_ij * (t_i - t_j) + \ - log(t_i) * (a_i - 1) - b_i * t_i + \ - log(t_j) * (a_j - 1) - b_j * t_j + \ - log(int(t_j < t_m < t_i) / (t_i - t_j)) - """ - a = a_j - b = a_i + a_j + y_ij - c = a_j + y_ij + 1 - t = mu_ij + b_i - z = (mu_ij - b_j) / t - f000 = float(mpmath.log(mpmath.hyp2f1(a + 0, b + 0, c + 0, z))) - f020 = float(mpmath.log(mpmath.hyp2f1(a + 0, b + 2, c + 0, z))) - f111 = float(mpmath.log(mpmath.hyp2f1(a + 1, b + 1, c + 1, z))) - f121 = float(mpmath.log(mpmath.hyp2f1(a + 1, b + 2, c + 1, z))) - f222 = float(mpmath.log(mpmath.hyp2f1(a + 2, b + 2, c + 2, z))) - s1 = a * b / c - s2 = s1 * (a + 1) * (b + 1) / (c + 1) - d1 = b * (b + 1) / t**2 - d2 = d1 * a / c - d3 = d2 * (a + 1) / (c + 1) - mn_m = s1 * exp(f111 - f000) / t / 2 * (1 + z) + b / t / 2 - sq_m = ( - d1 * exp(f020 - f000) / 3 + d2 * exp(f121 - f000) / 3 + d3 * exp(f222 - f000) / 3 - ) - va_m = sq_m - mn_m**2 - return mn_m, va_m - - -def mutation_rootward_moments(t_j, a_i, b_i, y_ij, mu_ij): - """ - log p(t_m, t_i) := \ - log(t_i - t_j) * y_ij - mu_ij * (t_i - t_j) + \ - log(t_i) * (a_i - 1) - b_i * t_i + \ - log(int(t_j < t_m < t_i) / (t_i - t_j)) - """ - logl, mn_i, va_i = rootward_moments(t_j, a_i, b_i, y_ij, mu_ij) - mn_m = mn_i / 2 + t_j / 2 - sq_m = (va_i + mn_i**2 + mn_i * t_j + t_j**2) / 3 - va_m = sq_m - mn_m**2 - return mn_m, va_m - - -def mutation_leafward_moments(t_i, a_j, b_j, y_ij, mu_ij): - """ - log p(t_m, t_j) := \ - log(t_i - t_j) * y_ij - mu_ij * (t_i - t_j) + \ - log(t_j) * (a_j - 1) - b_j * t_j + \ - log(int(t_j < t_m < t_i) / (t_i - t_j)) - """ - logl, mn_j, va_j = leafward_moments(t_i, a_j, b_j, y_ij, mu_ij) - mn_m = mn_j / 2 + t_i / 2 - sq_m = (va_j + mn_j**2 + mn_j * t_i + t_i**2) / 3 - va_m = sq_m - mn_m**2 - return mn_m, va_m - - -def mutation_unphased_moments(a_i, b_i, a_j, b_j, y_ij, mu_ij): - """ - log p(t_m, t_i, t_j) := \ - log(t_i + t_j) * y_ij - mu_ij * (t_i + t_j) + \ - log(t_i) * (a_i - 1) - b_i * t_i + \ - log(t_j) * (a_j - 1) - b_j * t_j + \ - log(t_i / (t_i + t_j) * int(0 < t_m < t_i) / t_i + \ - t_j / (t_i + t_j) * int(0 < t_m < t_j) / t_j) - """ - a = a_j - b = a_j + a_i + y_ij - c = a_j + a_i - t = mu_ij + b_i - z = (mu_ij + b_j) / t - f000 = float(mpmath.log(mpmath.hyp2f1(a + 0, b + 0, c + 0, 1 - z))) - f001 = float(mpmath.log(mpmath.hyp2f1(a + 0, b + 0, c + 1, 1 - z))) - f012 = float(mpmath.log(mpmath.hyp2f1(a + 0, b + 1, c + 2, 1 - z))) - f023 = float(mpmath.log(mpmath.hyp2f1(a + 0, b + 2, c + 3, 1 - z))) - f212 = float(mpmath.log(mpmath.hyp2f1(a + 2, b + 1, c + 2, 1 - z))) - f323 = float(mpmath.log(mpmath.hyp2f1(a + 3, b + 2, c + 3, 1 - z))) - s0 = b / t / c / (c + 1) - s1 = (c - a) * (c - a + 1) - s2 = a * (a + 1) - d0 = s0 * (b + 1) / t / (c + 2) - d1 = s1 * (c - a + 2) - d2 = s2 * (a + 2) - mn_m = s0 * s1 * exp(f012 - f000) / 2 + s0 * s2 * exp(f212 - f000) / 2 - sq_m = d0 * d1 * exp(f023 - f000) / 3 + d0 * d2 * exp(f323 - f000) / 3 - va_m = sq_m - mn_m**2 - pr_m = (c - a) / c * exp(f001 - f000) - return pr_m, mn_m, va_m - - -def mutation_twin_moments(a_i, b_i, y_ij, mu_ij): - """ - log p(t_m, t_i) := \ - log(int(0 < t_m < t_i) / t_i) + \ - log(2 * t_i) * y_ij - mu_ij * (2 * t_i) + \ - log(t_i) * (a_i - 1) - b_i * t_i - """ - s = a_i + y_ij - r = b_i + 2 * mu_ij - pr_m = 0.5 - mn_m = s / r / 2 - sq_m = (s + 1) * s / 3 / r**2 - va_m = sq_m - mn_m**2 - return pr_m, mn_m, va_m - - -def mutation_sideways_moments(t_i, a_j, b_j, y_ij, mu_ij): - """ - log p(t_m, t_j) := \ - log(t_i + t_j) * y_ij - mu_ij * (t_i + t_j) + \ - log(t_j) * (a_j - 1) - b_j * t_j + \ - log(t_i / (t_i + t_j) * int(0 < t_m < t_i) / t_i + \ - t_j / (t_i + t_j) * int(0 < t_m < t_j) / t_j) - """ - a = a_j - b = a_j + y_ij + 1 - z = t_i * (mu_ij + b_j) - f00 = float(mpmath.log(mpmath.hyperu(a + 0, b + 0, z))) - f10 = float(mpmath.log(mpmath.hyperu(a + 1, b + 0, z))) - f21 = float(mpmath.log(mpmath.hyperu(a + 2, b + 1, z))) - f32 = float(mpmath.log(mpmath.hyperu(a + 3, b + 2, z))) - pr_m = 1.0 - exp(f10 - f00) * a - mn_m = pr_m * t_i / 2 + t_i * exp(f21 - f00) * a * (a + 1) / 2 - sq_m = pr_m * t_i**2 / 3 + t_i**2 * exp(f32 - f00) * a * (a + 1) * (a + 2) / 3 - va_m = sq_m - mn_m**2 - return pr_m, mn_m, va_m - - -def mutation_edge_moments(t_i, t_j): - """ - log p(t_m) := int(t_j < t_m < t_i) / (t_i - t_j) - """ - mn_m = t_i / 2 + t_j / 2 - va_m = (t_i - t_j) ** 2 / 12 - return mn_m, va_m - - -def mutation_block_moments(t_i, t_j): - """ - log p(t_m) := \ - log(t_i / (t_i + t_j) * int(0 < t_m < t_i) / t_i + \ - t_j / (t_i + t_j) * int(0 < t_m < t_j) / t_j) - """ - pr_m = t_i / (t_i + t_j) - mn_m = pr_m * t_i / 2 + (1 - pr_m) * t_j / 2 - sq_m = pr_m * t_i**2 / 3 + (1 - pr_m) * t_j**2 / 3 - va_m = sq_m - mn_m**2 - return pr_m, mn_m, va_m - - -# --- verify exact solutions with quadrature --- # - - -class TestExactMoments: - @staticmethod - def pdf(t_i, t_j, a_i, b_i, a_j, b_j, y, mu): - """ - Target joint (pair) distribution, proportional to the parent/child - marginals (gamma) and a Poisson mutation likelihood - """ - assert 0 < t_j < t_i - return ( - t_i ** (a_i - 1) - * np.exp(-t_i * b_i) - * t_j ** (a_j - 1) - * np.exp(-t_j * b_j) - * (t_i - t_j) ** y - * np.exp(-(t_i - t_j) * mu) - ) - - @staticmethod - def pdf_rootward(t_i, t_j, a_i, b_i, y, mu): - """ - Target conditional distribution, proportional to the parent - marginals (gamma) and a Poisson mutation likelihood at a - fixed child age - """ - assert 0 <= t_j < t_i - return ( - t_i ** (a_i - 1) - * np.exp(-t_i * b_i) - * (t_i - t_j) ** y - * np.exp(-(t_i - t_j) * mu) - ) - - @staticmethod - def pdf_leafward(t_i, t_j, a_j, b_j, y, mu): - """ - Target conditional distribution, proportional to the child - marginals (gamma) and a Poisson mutation likelihood at a - fixed parent age - """ - assert 0 < t_j < t_i - return ( - t_j ** (a_j - 1) - * np.exp(-t_j * b_j) - * (t_i - t_j) ** y - * np.exp(-(t_i - t_j) * mu) - ) - - @staticmethod - def pdf_unphased(t_i, t_j, a_i, b_i, a_j, b_j, y, mu): - """ - Target joint (pair) distribution, proportional to the parent - marginals (gamma) and a Poisson mutation likelihood over the - two branches leading from (present-day) individual to parents - """ - assert t_i > 0 and t_j > 0 - return ( - t_i ** (a_i - 1) - * np.exp(-t_i * b_i) - * t_j ** (a_j - 1) - * np.exp(-t_j * b_j) - * (t_i + t_j) ** y - * np.exp(-(t_i + t_j) * mu) - ) - - @staticmethod - def pdf_twin(t_i, a_i, b_i, y, mu): - """ - Target marginal distribution, proportional to the parent - marginal (gamma) and a Poisson mutation likelihood over the two - branches leading from (present-day) individual to a *single* parent - """ - assert t_i > 0 - return ( - t_i ** (a_i - 1) - * np.exp(-t_i * b_i) - * (t_i + t_i) ** y - * np.exp(-(t_i + t_i) * mu) - ) - - @staticmethod - def pdf_sideways(t_i, t_j, a_j, b_j, y, mu): - """ - Target joint (pair) distribution, proportional to the parent - marginals (gamma) and a Poisson mutation likelihood over the - two branches leading from (present-day) individual to parents, - with left parent fixed to t_i - """ - assert t_i > 0 and t_j > 0 - return ( - t_j ** (a_j - 1) - * np.exp(-t_j * b_j) - * (t_i + t_j) ** y - * np.exp(-(t_i + t_j) * mu) - ) - - @staticmethod - def pdf_edge(x, t_i, t_j): - """ - Mutation uniformly distributed between child and parent - """ - assert t_i > 0 and t_j > 0 - return int(t_j < x < t_i) / (t_i - t_j) - - @staticmethod - def pdf_block(x, t_i, t_j): - """ - Mutation uniformly distributed between child at time zero and one of - two parents with fixed ages - """ - assert t_i > 0 and t_j > 0 - return (int(0 < x < t_i) + int(0 < x < t_j)) / (t_i + t_j) - - def test_moments(self, pars): - """ - Test mean and variance when ages of both nodes are free - """ - logconst, t_i, var_t_i, t_j, var_t_j = moments(*pars) - ck_normconst = scipy.integrate.dblquad( - lambda t_i, t_j: self.pdf(t_i, t_j, *pars), - 0, - np.inf, - lambda t_j: t_j, - np.inf, - epsabs=0, - )[0] - assert np.isclose(logconst, np.log(ck_normconst)) - ck_t_i = scipy.integrate.dblquad( - lambda t_i, t_j: t_i * self.pdf(t_i, t_j, *pars) / ck_normconst, - 0, - np.inf, - lambda t_j: t_j, - np.inf, - epsabs=0, - )[0] - assert np.isclose(t_i, ck_t_i) - ck_t_j = scipy.integrate.dblquad( - lambda t_i, t_j: t_j * self.pdf(t_i, t_j, *pars) / ck_normconst, - 0, - np.inf, - lambda t_j: t_j, - np.inf, - epsabs=0, - )[0] - assert np.isclose(t_j, ck_t_j) - ck_var_t_i = ( - scipy.integrate.dblquad( - lambda t_i, t_j: t_i**2 * self.pdf(t_i, t_j, *pars) / ck_normconst, - 0, - np.inf, - lambda t_j: t_j, - np.inf, - epsabs=0, - )[0] - - ck_t_i**2 - ) - assert np.isclose(var_t_i, ck_var_t_i) - ck_var_t_j = ( - scipy.integrate.dblquad( - lambda t_i, t_j: t_j**2 * self.pdf(t_i, t_j, *pars) / ck_normconst, - 0, - np.inf, - lambda t_j: t_j, - np.inf, - epsabs=0, - )[0] - - ck_t_j**2 - ) - assert np.isclose(var_t_j, ck_var_t_j) - - def test_rootward_moments(self, pars): - """ - Test mean and variance of parent age when child age is fixed to a nonzero value - """ - a_i, b_i, a_j, b_j, y, mu = pars - pars_redux = (a_i, b_i, y, mu) - mn_j = a_j / b_j # point "estimate" for child - for t_j in [0.0, mn_j]: - logconst, t_i, var_t_i = rootward_moments(t_j, *pars_redux) - ck_normconst = scipy.integrate.quad( - lambda t_i: self.pdf_rootward(t_i, t_j, *pars_redux), - t_j, - np.inf, - epsabs=0, - )[0] - assert np.isclose(logconst, np.log(ck_normconst)) - ck_t_i = scipy.integrate.quad( - lambda t_i: t_i * self.pdf_rootward(t_i, t_j, *pars_redux) / ck_normconst, - t_j, - np.inf, - epsabs=0, - )[0] - assert np.isclose(t_i, ck_t_i) - ck_var_t_i = ( - scipy.integrate.quad( - lambda t_i: ( - t_i**2 * self.pdf_rootward(t_i, t_j, *pars_redux) / ck_normconst - ), - t_j, - np.inf, - epsabs=0, - )[0] - - ck_t_i**2 - ) - assert np.isclose(var_t_i, ck_var_t_i) - - def test_leafward_moments(self, pars): - """ - Test mean and variance of child age when parent age is fixed to a nonzero value - """ - a_i, b_i, a_j, b_j, y, mu = pars - t_i = a_i / b_i # point "estimate" for parent - pars_redux = (a_j, b_j, y, mu) - logconst, t_j, var_t_j = leafward_moments(t_i, *pars_redux) - ck_normconst = scipy.integrate.quad( - lambda t_j: self.pdf_leafward(t_i, t_j, *pars_redux), - 0, - t_i, - epsabs=0, - )[0] - assert np.isclose(logconst, np.log(ck_normconst)) - ck_t_j = scipy.integrate.quad( - lambda t_j: t_j * self.pdf_leafward(t_i, t_j, *pars_redux) / ck_normconst, - 0, - t_i, - epsabs=0, - )[0] - assert np.isclose(t_j, ck_t_j) - ck_var_t_j = ( - scipy.integrate.quad( - lambda t_j: ( - t_j**2 * self.pdf_leafward(t_i, t_j, *pars_redux) / ck_normconst - ), - 0, - t_i, - epsabs=0, - )[0] - - ck_t_j**2 - ) - assert np.isclose(var_t_j, ck_var_t_j) - - def test_unphased_moments(self, pars): - """ - Parent ages for an singleton nodes above an unphased individual - """ - logconst, t_i, var_t_i, t_j, var_t_j = unphased_moments(*pars) - ck_normconst = scipy.integrate.dblquad( - lambda t_i, t_j: self.pdf_unphased(t_i, t_j, *pars), - 0, - np.inf, - 0, - np.inf, - epsabs=0, - )[0] - assert np.isclose(logconst, np.log(ck_normconst)) - ck_t_i = scipy.integrate.dblquad( - lambda t_i, t_j: t_i * self.pdf_unphased(t_i, t_j, *pars) / ck_normconst, - 0, - np.inf, - 0, - np.inf, - epsabs=0, - )[0] - assert np.isclose(t_i, ck_t_i) - ck_t_j = scipy.integrate.dblquad( - lambda t_i, t_j: t_j * self.pdf_unphased(t_i, t_j, *pars) / ck_normconst, - 0, - np.inf, - 0, - np.inf, - epsabs=0, - )[0] - assert np.isclose(t_j, ck_t_j) - ck_var_t_i = ( - scipy.integrate.dblquad( - lambda t_i, t_j: ( - t_i**2 * self.pdf_unphased(t_i, t_j, *pars) / ck_normconst - ), - 0, - np.inf, - 0, - np.inf, - epsabs=0, - )[0] - - ck_t_i**2 - ) - assert np.isclose(var_t_i, ck_var_t_i) - ck_var_t_j = ( - scipy.integrate.dblquad( - lambda t_i, t_j: ( - t_j**2 * self.pdf_unphased(t_i, t_j, *pars) / ck_normconst - ), - 0, - np.inf, - 0, - np.inf, - epsabs=0, - )[0] - - ck_t_j**2 - ) - assert np.isclose(var_t_j, ck_var_t_j) - - def test_twin_moments(self, pars): - """ - Parent age for one singleton node above an unphased individual - """ - a_i, b_i, a_j, b_j, y_ij, mu_ij = pars - pars_redux = (a_i, b_i, y_ij, mu_ij) - logconst, t_i, var_t_i = twin_moments(*pars_redux) - ck_normconst = scipy.integrate.quad( - lambda t_i: self.pdf_twin(t_i, *pars_redux), - 0, - np.inf, - epsabs=0, - )[0] - assert np.isclose(logconst, np.log(ck_normconst)) - ck_t_i = scipy.integrate.quad( - lambda t_i: t_i * self.pdf_twin(t_i, *pars_redux) / ck_normconst, - 0, - np.inf, - epsabs=0, - )[0] - assert np.isclose(t_i, ck_t_i) - ck_var_t_i = ( - scipy.integrate.quad( - lambda t_i: t_i**2 * self.pdf_twin(t_i, *pars_redux) / ck_normconst, - 0, - np.inf, - epsabs=0, - )[0] - - ck_t_i**2 - ) - assert np.isclose(var_t_i, ck_var_t_i) - - def test_sideways_moments(self, pars): - """ - Parent ages for an singleton nodes above an unphased individual, where - second parent is fixed to a particular time - """ - a_i, b_i, a_j, b_j, y, mu = pars - pars_redux = (a_j, b_j, y, mu) - t_i = a_i / b_i # point "estimate" for left parent - nc, mn, va = sideways_moments(t_i, *pars_redux) - ck_nc = scipy.integrate.quad( - lambda t_j: self.pdf_sideways(t_i, t_j, *pars_redux), - 0, - np.inf, - )[0] - assert np.isclose(np.exp(nc), ck_nc) - ck_mn = ( - scipy.integrate.quad( - lambda t_j: t_j * self.pdf_sideways(t_i, t_j, *pars_redux), - 0, - np.inf, - )[0] - / ck_nc - ) - assert np.isclose(mn, ck_mn) - ck_va = ( - scipy.integrate.quad( - lambda t_j: t_j**2 * self.pdf_sideways(t_i, t_j, *pars_redux), - 0, - np.inf, - )[0] - / ck_nc - - ck_mn**2 - ) - assert np.isclose(va, ck_va) - - def test_mutation_moments(self, pars): - """ - Mutation mapped to a single branch with both nodes free - """ - - def f(t_i, t_j): - assert t_j < t_i - mn = t_i / 2 + t_j / 2 - sq = (t_i**2 + t_i * t_j + t_j**2) / 3 - return mn, sq - - mn, va = mutation_moments(*pars) - nc = scipy.integrate.dblquad( - lambda t_i, t_j: self.pdf(t_i, t_j, *pars), - 0, - np.inf, - lambda t_j: t_j, - np.inf, - epsabs=0, - )[0] - ck_mn = ( - scipy.integrate.dblquad( - lambda t_i, t_j: f(t_i, t_j)[0] * self.pdf(t_i, t_j, *pars), - 0, - np.inf, - lambda t_j: t_j, - np.inf, - epsabs=0, - )[0] - / nc - ) - assert np.isclose(mn, ck_mn) - ck_va = ( - scipy.integrate.dblquad( - lambda t_i, t_j: f(t_i, t_j)[1] * self.pdf(t_i, t_j, *pars), - 0, - np.inf, - lambda t_j: t_j, - np.inf, - epsabs=0, - )[0] - / nc - - ck_mn**2 - ) - assert np.isclose(va, ck_va) - - def test_mutation_rootward_moments(self, pars): - """ - Mutation mapped to a single branch with child node fixed - """ - - def f(t_i, t_j): # conditional moments - assert t_j < t_i - mn = t_i / 2 + t_j / 2 - sq = (t_i**2 + t_i * t_j + t_j**2) / 3 - return mn, sq - - a_i, b_i, a_j, b_j, y, mu = pars - pars_redux = (a_i, b_i, y, mu) - mn_j = a_j / b_j # point "estimate" for child - for t_j in [0.0, mn_j]: - mn, va = mutation_rootward_moments(t_j, *pars_redux) - nc = scipy.integrate.quad( - lambda t_i: self.pdf_rootward(t_i, t_j, *pars_redux), - t_j, - np.inf, - )[0] - ck_mn = ( - scipy.integrate.quad( - lambda t_i: f(t_i, t_j)[0] * self.pdf_rootward(t_i, t_j, *pars_redux), - t_j, - np.inf, - )[0] - / nc - ) - assert np.isclose(mn, ck_mn) - ck_va = ( - scipy.integrate.quad( - lambda t_i: f(t_i, t_j)[1] * self.pdf_rootward(t_i, t_j, *pars_redux), - t_j, - np.inf, - )[0] - / nc - - ck_mn**2 - ) - assert np.isclose(va, ck_va) - - def test_mutation_leafward_moments(self, pars): - """ - Mutation mapped to a single branch with parent node fixed - """ - - def f(t_i, t_j): - assert t_j < t_i - mn = t_i / 2 + t_j / 2 - sq = (t_i**2 + t_i * t_j + t_j**2) / 3 - return mn, sq - - a_i, b_i, a_j, b_j, y, mu = pars - t_i = a_i / b_i # point "estimate" for parent - pars_redux = (a_j, b_j, y, mu) - mn, va = mutation_leafward_moments(t_i, *pars_redux) - nc = scipy.integrate.quad( - lambda t_j: self.pdf_leafward(t_i, t_j, *pars_redux), - 0, - t_i, - )[0] - ck_mn = ( - scipy.integrate.quad( - lambda t_j: f(t_i, t_j)[0] * self.pdf_leafward(t_i, t_j, *pars_redux), - 0, - t_i, - )[0] - / nc - ) - assert np.isclose(mn, ck_mn) - ck_va = ( - scipy.integrate.quad( - lambda t_j: f(t_i, t_j)[1] * self.pdf_leafward(t_i, t_j, *pars_redux), - 0, - t_i, - )[0] - / nc - - ck_mn**2 - ) - assert np.isclose(va, ck_va) - - def test_mutation_unphased_moments(self, pars): - """ - Mutation mapped to two singleton branches with children fixed to time zero - """ - - def f(t_i, t_j): # conditional moments - pr = t_i / (t_i + t_j) - mn = pr * t_i / 2 + (1 - pr) * t_j / 2 - sq = pr * t_i**2 / 3 + (1 - pr) * t_j**2 / 3 - return pr, mn, sq - - pr, mn, va = mutation_unphased_moments(*pars) - nc = scipy.integrate.dblquad( - lambda t_i, t_j: self.pdf_unphased(t_i, t_j, *pars), - 0, - np.inf, - 0, - np.inf, - epsabs=0, - )[0] - ck_pr = ( - scipy.integrate.dblquad( - lambda t_i, t_j: f(t_i, t_j)[0] * self.pdf_unphased(t_i, t_j, *pars), - 0, - np.inf, - 0, - np.inf, - epsabs=0, - )[0] - / nc - ) - assert np.isclose(pr, ck_pr) - ck_mn = ( - scipy.integrate.dblquad( - lambda t_i, t_j: f(t_i, t_j)[1] * self.pdf_unphased(t_i, t_j, *pars), - 0, - np.inf, - 0, - np.inf, - epsabs=0, - )[0] - / nc - ) - assert np.isclose(mn, ck_mn) - ck_va = ( - scipy.integrate.dblquad( - lambda t_i, t_j: f(t_i, t_j)[2] * self.pdf_unphased(t_i, t_j, *pars), - 0, - np.inf, - 0, - np.inf, - epsabs=0, - )[0] - / nc - - ck_mn**2 - ) - assert np.isclose(va, ck_va) - - def test_mutation_twin_moments(self, pars): - """ - Mutation mapped to two singleton branches with children fixed to time zero - and a single parent node - """ - - def f(t_i): # conditional moments - pr = 0.5 - mn = t_i / 2 - sq = t_i**2 / 3 - return pr, mn, sq - - a_i, b_i, a_j, b_j, y_ij, mu_ij = pars - pars_redux = (a_i, b_i, y_ij, mu_ij) - pr, mn, va = mutation_twin_moments(*pars_redux) - nc = scipy.integrate.quad( - lambda t_i: self.pdf_twin(t_i, *pars_redux), - 0, - np.inf, - epsabs=0, - )[0] - ck_pr = ( - scipy.integrate.quad( - lambda t_i: f(t_i)[0] * self.pdf_twin(t_i, *pars_redux), - 0, - np.inf, - epsabs=0, - )[0] - / nc - ) - assert np.isclose(pr, ck_pr) - ck_mn = ( - scipy.integrate.quad( - lambda t_i: f(t_i)[1] * self.pdf_twin(t_i, *pars_redux), - 0, - np.inf, - epsabs=0, - )[0] - / nc - ) - assert np.isclose(mn, ck_mn) - ck_va = ( - scipy.integrate.quad( - lambda t_i: f(t_i)[2] * self.pdf_twin(t_i, *pars_redux), - 0, - np.inf, - epsabs=0, - )[0] - / nc - - ck_mn**2 - ) - assert np.isclose(va, ck_va) - - def test_mutation_sideways_moments(self, pars): - """ - Mutation mapped to two branches with children fixed to time zero, and - left parent (i) fixed - """ - - def f(t_i, t_j): # conditional moments - pr = t_i / (t_i + t_j) - mn = pr * t_i / 2 + (1 - pr) * t_j / 2 - sq = pr * t_i**2 / 3 + (1 - pr) * t_j**2 / 3 - return pr, mn, sq - - a_i, b_i, a_j, b_j, y, mu = pars - pars_redux = a_j, b_j, y, mu - t_i = a_i / b_i # point "estimate" for left parent - pr, mn, va = mutation_sideways_moments(t_i, *pars_redux) - nc = scipy.integrate.quad( - lambda t_j: self.pdf_sideways(t_i, t_j, *pars_redux), - 0, - np.inf, - )[0] - ck_pr = ( - scipy.integrate.quad( - lambda t_j: f(t_i, t_j)[0] * self.pdf_sideways(t_i, t_j, *pars_redux), - 0, - np.inf, - )[0] - / nc - ) - assert np.isclose(pr, ck_pr) - ck_mn = ( - scipy.integrate.quad( - lambda t_j: f(t_i, t_j)[1] * self.pdf_sideways(t_i, t_j, *pars_redux), - 0, - np.inf, - )[0] - / nc - ) - assert np.isclose(mn, ck_mn) - ck_va = ( - scipy.integrate.quad( - lambda t_j: f(t_i, t_j)[2] * self.pdf_sideways(t_i, t_j, *pars_redux), - 0, - np.inf, - )[0] - / nc - - ck_mn**2 - ) - assert np.isclose(va, ck_va) - - def test_mutation_edge_moments(self, pars): - """ - Mutation mapped to two branches with children fixed to time zero, and - both parents fixed - """ - a_i, b_i, a_j, b_j, y, mu = pars - t_i = a_i / b_i - t_j = a_j / b_j - mn, va = mutation_edge_moments(t_i, t_j) - ck_mn = scipy.integrate.quad( - lambda x: x * self.pdf_edge(x, t_i, t_j), - 0, - max(t_i, t_j), - )[0] - assert np.isclose(mn, ck_mn) - ck_va = ( - scipy.integrate.quad( - lambda x: x**2 * self.pdf_edge(x, t_i, t_j), - 0, - max(t_i, t_j), - )[0] - - ck_mn**2 - ) - assert np.isclose(va, ck_va) - - def test_mutation_block_moments(self, pars): - """ - Mutation mapped to two branches with children fixed to time zero, and - both parents fixed - """ - a_i, b_i, a_j, b_j, y, mu = pars - t_i = a_i / b_i - t_j = a_j / b_j - pars_redux = (a_j, b_j, y, mu) - pr, mn, va = mutation_block_moments(t_i, t_j) - ck_pr = t_i / (t_i + t_j) - assert np.isclose(pr, ck_pr) - ck_mn = scipy.integrate.quad( - lambda x: x * self.pdf_block(x, t_i, t_j), - 0, - max(t_i, t_j), - )[0] - assert np.isclose(mn, ck_mn) - ck_va = ( - scipy.integrate.quad( - lambda x: x**2 * self.pdf_block(x, t_i, t_j), - 0, - max(t_i, t_j), - )[0] - - ck_mn**2 - ) - assert np.isclose(va, ck_va) - - -def validate(): - tests = TestExactMoments() - test_names = [f for f in dir(tests) if f.startswith("test")] - test_cases = [ # [shape1, rate1, shape2, rate2, muts, rate] - [2.0, 0.0005, 1.5, 0.005, 0.0, 0.001], - [2.0, 0.0005, 1.5, 0.005, 1.0, 0.001], - [2.0, 0.0005, 1.5, 0.005, 2.0, 0.001], - [2.0, 0.0005, 1.5, 0.005, 3.0, 0.001], - ] - for pars in test_cases: - for test in test_names: - getattr(tests, test)(pars) diff --git a/tests/oracle/__init__.py b/tests/oracle/__init__.py new file mode 100644 index 00000000..4d3e2236 --- /dev/null +++ b/tests/oracle/__init__.py @@ -0,0 +1,22 @@ +""" +Plain-Python reference implementations ("oracles") of the tree-sweep functions of the +C extension ``_tsdate``. + +Each function has an oracle in the module of the same name here, e.g. +``oracle.phasing.block_singletons`` for ``_tsdate.block_singletons``. Equivalence +tests (``tests/test_oracle_*.py``) call the ``_tsdate`` functions and the oracles with +the same arguments and compare the results. + +Rules: + +* An oracle is written as array code in plain Python with the operation order of the + C library. +* Oracles call other oracles, never ``_tsdate``, except for the messages of the + library's error codes (``errors``, as ``_tsdate.strerror`` gives them). +* Where the C library returns an error code, the oracle raises + ``errors.library_error(code)``, the ``_tsdate.LibraryError`` with that code's + message. Oracles do not check the sizes of their arrays (``_tsdate`` does, and + ``tests/test_python_c.py`` tests it). Internal invariants, which the library does + not report, are plain ``assert`` statements. +* Names, arguments and results are those of ``_tsdate``'s functions. +""" diff --git a/tests/oracle/errors.py b/tests/oracle/errors.py new file mode 100644 index 00000000..1dca105e --- /dev/null +++ b/tests/oracle/errors.py @@ -0,0 +1,21 @@ +""" +The error codes of the C library that the oracles raise (``lib/err.h``, without the +``TSD_ERR_`` prefix), and the exceptions with which ``_tsdate`` reports them. +""" + +import _tsdate + +UNPHASED_INDIVIDUAL_EDGES = -16 +BLOCK_OUT_OF_BOUNDS = -17 +PHASE_OUT_OF_RANGE = -18 +UNPHASED_LIKELIHOOD_NOT_CONSERVED = -19 +MUTATION_NODE_NOT_IN_TREE = -20 +FIXED_NODES_VIOLATE_CONSTRAINT = -21 + + +def library_error(code): + """ + The exception with which ``_tsdate`` reports error ``code``. + """ + message = _tsdate.strerror(code) + return _tsdate.LibraryError(message) diff --git a/tests/oracle/helpers.py b/tests/oracle/helpers.py new file mode 100644 index 00000000..7c1ab78f --- /dev/null +++ b/tests/oracle/helpers.py @@ -0,0 +1,79 @@ +""" +Helpers shared by the oracle equivalence tests. +""" + +import re + +import _tsdate +import numpy as np +import pytest +import tskit + + +def copies(kwargs): + """ + The keyword arguments with copies of their arrays + """ + return { + name: value.copy() if isinstance(value, np.ndarray) else value + for name, value in kwargs.items() + } + + +def assert_same_result(function, oracle, **kwargs): + """ + Call the ``_tsdate`` function and its oracle with (copies of) the keyword + arguments, assert that they return arrays of the same values, shapes and types, + with NaNs in the same places, and return the result + """ + expected = oracle(**copies(kwargs)) + actual = function(**copies(kwargs)) + if isinstance(expected, tuple): + assert len(actual) == len(expected) + for actual_array, expected_array in zip(actual, expected): + np.testing.assert_array_equal(actual_array, expected_array, strict=True) + else: + np.testing.assert_array_equal(actual, expected, strict=True) + return actual + + +def raises_library_error(code): + """ + ``pytest.raises`` for the library error ``code`` + """ + return pytest.raises(_tsdate.LibraryError, match=re.escape(_tsdate.strerror(code))) + + +def assert_same_error(function, oracle, code, **kwargs): + """ + Assert that the ``_tsdate`` function and its oracle both raise the library error + ``code`` for the keyword arguments + """ + with raises_library_error(code): + oracle(**copies(kwargs)) + with raises_library_error(code): + function(**copies(kwargs)) + + +def make_ts(nodes, edges, mutations, length, num_individuals=0): + """ + Tree sequence from ``nodes`` ``(is_sample, time)`` or ``(is_sample, time, + individual)``, ``edges`` ``(left, right, parent, child)`` and ``mutations`` + ``(position, node)``, with ``num_individuals`` empty individuals. + """ + tables = tskit.TableCollection(length) + for _ in range(num_individuals): + tables.individuals.add_row() + for is_sample, time, *individual in nodes: + tables.nodes.add_row( + flags=int(is_sample), + time=time, + individual=individual[0] if individual else -1, + ) + for left, right, parent, child in edges: + tables.edges.add_row(left, right, parent, child) + for i, (position, node) in enumerate(mutations): + tables.sites.add_row(position, "0") + tables.mutations.add_row(i, node, "1") + tables.sort() + return tables.tree_sequence() diff --git a/tests/oracle/phasing.py b/tests/oracle/phasing.py new file mode 100644 index 00000000..d21a814c --- /dev/null +++ b/tests/oracle/phasing.py @@ -0,0 +1,220 @@ +""" +Oracles for the phasing functions (``lib/phasing.c``). +""" + +import numpy as np +import tskit + +from . import errors +from .errors import library_error + + +def reallocate_unphased(edges_likelihood, mutations_phase, mutations_block, blocks_edges): + """ + The edge likelihoods with a proportion of each unphased singleton mutation added + to one of the two edges to which it maps + """ + edges_likelihood = edges_likelihood.copy() + + num_edges = edges_likelihood.shape[0] + edges_unphased = np.full(num_edges, False) + edges_unphased[blocks_edges[:, 0]] = True + edges_unphased[blocks_edges[:, 1]] = True + + num_unphased = np.sum(edges_likelihood[edges_unphased, 0]) + edges_likelihood[edges_unphased, 0] = 0.0 + for m, b in enumerate(mutations_block): + if b == tskit.NULL: + continue + i, j = blocks_edges[b] + if not (tskit.NULL < i < num_edges and tskit.NULL < j < num_edges): + raise library_error(errors.BLOCK_OUT_OF_BOUNDS) + assert edges_unphased[i] + assert edges_unphased[j] + if np.isnan(mutations_phase[m]): # TODO: fix rare numerical issue + continue + if not (0.0 <= mutations_phase[m] <= 1.0): + raise library_error(errors.PHASE_OUT_OF_RANGE) + edges_likelihood[i, 0] += mutations_phase[m] + edges_likelihood[j, 0] += 1 - mutations_phase[m] + if not np.isclose(num_unphased, np.sum(edges_likelihood[edges_unphased, 0])): + raise library_error(errors.UNPHASED_LIKELIHOOD_NOT_CONSERVED) + return edges_likelihood + + +def block_singletons( + individuals_unphased, + nodes_individual, + mutations_node, + mutations_position, + edges_child, + edges_left, + edges_right, + indexes_insert, + indexes_remove, + sequence_length, +): + """ + Blocks of the singleton mutations of unphased individuals: ``(blocks_stats, + blocks_edges, mutations_block)``. + """ + num_mutations = mutations_node.size + num_edges = edges_child.size + num_individuals = individuals_unphased.size + + indexes_mutation = np.argsort(mutations_position) + position_insert = edges_left[indexes_insert] + position_remove = edges_right[indexes_remove] + position_mutation = mutations_position[indexes_mutation] + + individuals_edges = np.full((num_individuals, 2), tskit.NULL) + individuals_position = np.full(num_individuals, np.nan) + individuals_singletons = np.zeros(num_individuals) + individuals_block = np.full(num_edges, tskit.NULL) + mutations_block = np.full(num_mutations, tskit.NULL) + + blocks_span = [] + blocks_singletons = [] + blocks_edges = [] + blocks_order = [] + + num_blocks = 0 + left = 0.0 + a, b, d = 0, 0, 0 + while a < num_edges or b < num_edges: + while b < num_edges and position_remove[b] == left: # edges out + e = indexes_remove[b] + c = edges_child[e] + i = nodes_individual[c] + if i != tskit.NULL and individuals_unphased[i]: + u, v = individuals_edges[i] + assert u == e or v == e + s = u if v == e else v + individuals_edges[i] = s, tskit.NULL + if s != tskit.NULL: # flush block + blocks_order.append(individuals_block[i]) + blocks_edges.extend([e, s]) + blocks_singletons.append(individuals_singletons[i]) + blocks_span.append(left - individuals_position[i]) + individuals_position[i] = np.nan + individuals_block[i] = tskit.NULL + individuals_singletons[i] = 0.0 + b += 1 + + while a < num_edges and position_insert[a] == left: # edges in + e = indexes_insert[a] + c = edges_child[e] + i = nodes_individual[c] + if i != tskit.NULL and individuals_unphased[i]: + u, v = individuals_edges[i] + if u != tskit.NULL and v != tskit.NULL: + raise library_error(errors.UNPHASED_INDIVIDUAL_EDGES) + individuals_edges[i] = [e, max(u, v)] + individuals_position[i] = left + if individuals_block[i] == tskit.NULL: + individuals_block[i] = num_blocks + num_blocks += 1 + a += 1 + + right = sequence_length + if b < num_edges: + right = min(right, position_remove[b]) + if a < num_edges: + right = min(right, position_insert[a]) + left = right + + while d < num_mutations and position_mutation[d] < right: # mutations + m = indexes_mutation[d] + c = mutations_node[m] + i = nodes_individual[c] + if i != tskit.NULL and individuals_unphased[i]: + mutations_block[m] = individuals_block[i] + individuals_singletons[i] += 1.0 + d += 1 + + mutations_block = mutations_block.astype(np.int32) + blocks_edges = np.array(blocks_edges, dtype=np.int32).reshape(-1, 2) + blocks_singletons = np.array(blocks_singletons) + blocks_span = np.array(blocks_span) + blocks_order = np.array(blocks_order) + blocks_stats = np.column_stack((blocks_singletons, blocks_span)) + # every block must have been completed + if num_blocks != blocks_edges.shape[0]: + raise library_error(errors.UNPHASED_INDIVIDUAL_EDGES) + + # sort block arrays so that mutations_block points to correct row + blocks_order = np.argsort(blocks_order) + blocks_edges = blocks_edges[blocks_order] + blocks_stats = blocks_stats[blocks_order] + + return blocks_stats, blocks_edges, mutations_block + + +def mutation_frequency( + nodes_sample, + mutations_node, + mutations_position, + edges_parent, + edges_child, + edges_left, + edges_right, + indexes_insert, + indexes_remove, + sequence_length, +): + """ + The number of samples of each sample set below each mutation, as an array of + shape ``(num_mutations, num_sample_sets)``. + """ + num_nodes, num_sample_sets = nodes_sample.shape + num_mutations = mutations_node.size + num_edges = edges_parent.size + + indexes_mutation = np.argsort(mutations_position) + position_insert = edges_left[indexes_insert] + position_remove = edges_right[indexes_remove] + position_mutation = mutations_position[indexes_mutation] + + nodes_parent = np.full(num_nodes, tskit.NULL) + nodes_samples = np.zeros((num_nodes, num_sample_sets), dtype=np.int32) + mutations_freq = np.zeros((num_mutations, num_sample_sets), dtype=np.int32) + + # TODO: there's a better way than passing a big bool array + for i in range(num_sample_sets): + nodes_samples[nodes_sample[:, i], i] = 1.0 + + left = 0.0 + a, b, d = 0, 0, 0 + while a < num_edges or b < num_edges: + while b < num_edges and position_remove[b] == left: # edges out + e = indexes_remove[b] + p, c = edges_parent[e], edges_child[e] + nodes_parent[c] = tskit.NULL + while p != tskit.NULL: + nodes_samples[p] -= nodes_samples[c] + p = nodes_parent[p] + b += 1 + + while a < num_edges and position_insert[a] == left: # edges in + e = indexes_insert[a] + p, c = edges_parent[e], edges_child[e] + nodes_parent[c] = p + while p != tskit.NULL: + nodes_samples[p] += nodes_samples[c] + p = nodes_parent[p] + a += 1 + + right = sequence_length + if b < num_edges: + right = min(right, position_remove[b]) + if a < num_edges: + right = min(right, position_insert[a]) + left = right + + while d < num_mutations and position_mutation[d] < right: + m = indexes_mutation[d] + c = mutations_node[m] + mutations_freq[m] = nodes_samples[c] + d += 1 + + return mutations_freq diff --git a/tests/oracle/util.py b/tests/oracle/util.py new file mode 100644 index 00000000..fad50e6b --- /dev/null +++ b/tests/oracle/util.py @@ -0,0 +1,221 @@ +""" +Oracles for the tree sequence utilities (``lib/util.c``). +""" + +import numpy as np +import tskit + +from . import errors +from .errors import library_error + + +def split_disjoint_nodes( + edges_parent, edges_child, edges_left, edges_right, nodes_excluded +): + """ + Split disconnected regions of nodes into separate nodes. + + Returns updated edges_parent, edges_child, mutations_node, and indices indicating + from which original node the new nodes are derived. + """ + num_edges = edges_parent.size + num_nodes = nodes_excluded.size + + # For each edge, check whether parent/child is separated by a gap from the + # previous edge involving either parent/child. Label disconnected segments + # per node by integers starting at zero. + edges_order = np.argsort(edges_left) + # TODO: is a sort really needed here? + edges_segments = np.full((2, num_edges), -1, dtype=np.int32) + nodes_segments = np.full(num_nodes, -1, dtype=np.int32) + nodes_right = np.full(nodes_excluded.size, -np.inf, dtype=np.float64) + for e in edges_order: + nodes = edges_parent[e], edges_child[e] + for i, n in enumerate(nodes): + if nodes_excluded[n]: + continue + nodes_segments[n] += edges_left[e] > nodes_right[n] + edges_segments[i, e] = nodes_segments[n] + nodes_right[n] = max(nodes_right[n], edges_right[e]) + + # Create "nodes_segments[i]" supplementary nodes by copying node "i". + # Store the id of the first supplement for each node in "nodes_map". + split_nodes = [] # the nodes in the original that were split + nodes_map = np.full(num_nodes, -1, dtype=np.int32) + for i, s in enumerate(nodes_segments): + for j in range(s): + if j == 0: + nodes_map[i] = num_nodes + split_nodes.append(i) + num_nodes += 1 + split_nodes = np.array(split_nodes, dtype=np.int32) + nodes_order = np.arange(num_nodes, dtype=np.int32) + if len(split_nodes) > 0: + nodes_order[-len(split_nodes) :] = split_nodes + + # Relabel the nodes on each edge given "nodes_map" + for e in edges_order: + nodes = edges_parent[e], edges_child[e] + for i, n in enumerate(nodes): + if edges_segments[i, e] > 0: + edges_segments[i, e] += nodes_map[n] - 1 + else: + edges_segments[i, e] = n + edges_parent, edges_child = edges_segments[0, ...], edges_segments[1, ...] + + return edges_parent, edges_child, nodes_order, split_nodes + + +def relabel_mutations_node( + mutations_node, + mutations_position, + nodes_order, + edges_parent, + edges_child, + edges_left, + edges_right, + indexes_insert, + indexes_remove, +): + """ + Traverse trees, maintaining a mapping between old and new node IDs in the + current tree. Update `mutations_node` to reflect new IDs. + """ + num_nodes = nodes_order.size + num_edges = edges_parent.size + num_mutations = mutations_position.size + + insert_position = edges_left[indexes_insert] + remove_position = edges_right[indexes_remove] + sequence_length = remove_position[-1] + + output = np.full(num_mutations, tskit.NULL, dtype=np.int32) + nodes_map = np.full(num_nodes, tskit.NULL, dtype=np.int32) + a, b, m = 0, 0, 0 + left = 0.0 + while left < sequence_length: + while b < num_edges and remove_position[b] == left: # edges out + b += 1 + + while a < num_edges and insert_position[a] == left: # edges in + e = indexes_insert[a] + c, p = edges_child[e], edges_parent[e] + nodes_map[nodes_order[c]] = c + nodes_map[nodes_order[p]] = p + a += 1 + + right = sequence_length + if b < num_edges: + right = min(right, remove_position[b]) + if a < num_edges: + right = min(right, insert_position[a]) + left = right + + while m < num_mutations and mutations_position[m] < right: + if nodes_map[mutations_node[m]] == tskit.NULL: + raise library_error(errors.MUTATION_NODE_NOT_IN_TREE) + output[m] = nodes_map[mutations_node[m]] + m += 1 + + return output + + +def constrain_ages( + nodes_time, nodes_fixed, edges_parent, edges_child, epsilon, max_iterations +): + """ + Approximate least squares solution to the positive branch length + constraint, using the method of alternating projections. Loosely based on + Dykstra's algorithm, see: + + Dykstra RL, "An algorithm for restricted least squares regression", JASA + 1983 + """ + num_edges = edges_parent.size + nodes_time = nodes_time.copy() + edges_cavity = np.zeros((num_edges, 2)) + for _ in range(max_iterations): # method of alternating projections + if np.all(nodes_time[edges_parent] - nodes_time[edges_child] > epsilon): + return nodes_time + for e in range(num_edges): + p, c = edges_parent[e], edges_child[e] + nodes_time[c] -= edges_cavity[e, 0] + nodes_time[p] -= edges_cavity[e, 1] + adjustment = nodes_time[c] - nodes_time[p] # + epsilon + edges_cavity[e, :] = 0.0 + if adjustment > 0: + if nodes_fixed[c] and nodes_fixed[p]: + raise library_error(errors.FIXED_NODES_VIOLATE_CONSTRAINT) + if not nodes_fixed[c] and not nodes_fixed[p]: + edges_cavity[e, 0] = -adjustment / 2 + edges_cavity[e, 1] = adjustment / 2 + elif nodes_fixed[c] and not nodes_fixed[p]: + edges_cavity[e, 0] = 0 + edges_cavity[e, 1] = adjustment + elif not nodes_fixed[c] and nodes_fixed[p]: + edges_cavity[e, 0] = -adjustment + edges_cavity[e, 1] = 0 + nodes_time[c] += edges_cavity[e, 0] + nodes_time[p] += edges_cavity[e, 1] + # print( + # "min length:", np.min(nodes_time[edges_parent] - nodes_time[edges_child]) + # ) + + # force remaining constraint, which can change the ages of fixed nodes + for e in range(num_edges): + p, c = edges_parent[e], edges_child[e] + # TODO: even if nodes_fixed[p], this will still change the age + if nodes_time[c] + epsilon >= nodes_time[p]: + nodes_time[p] = nodes_time[c] + epsilon + + return nodes_time + + +def contains_unary_nodes( + nodes_mask, + edges_parent, + edges_left, + edges_right, + indexes_insert, + indexes_remove, + sequence_length, +): + """ + Whether a node outside ``nodes_mask`` has exactly one child in some tree. + """ + num_edges = edges_parent.size + nodes_children = np.zeros(nodes_mask.size, dtype=np.int32) + position_insert = edges_left[indexes_insert] + position_remove = edges_right[indexes_remove] + + left = 0.0 + a, b = 0, 0 + while a < num_edges or b < num_edges: + check = set() + + while b < num_edges and position_remove[b] == left: # edges out + e = indexes_remove[b] + p = edges_parent[e] + nodes_children[p] -= 1 + check.add(p) + b += 1 + + while a < num_edges and position_insert[a] == left: # edges in + e = indexes_insert[a] + p = edges_parent[e] + nodes_children[p] += 1 + check.add(p) + a += 1 + + for p in check: + if not nodes_mask[p] and nodes_children[p] == 1: + return True + + right = sequence_length + if b < num_edges: + right = min(right, position_remove[b]) + if a < num_edges: + right = min(right, position_insert[a]) + left = right + + return False diff --git a/tests/test_approximations.py b/tests/test_approximations.py deleted file mode 100644 index 454e72a6..00000000 --- a/tests/test_approximations.py +++ /dev/null @@ -1,325 +0,0 @@ -# MIT License -# -# Copyright (c) 2021-23 Tskit Developers -# Copyright (c) 2020-21 University of Oxford -# -# Permission is hereby granted, free of charge, to any person obtaining a copy -# of this software and associated documentation files (the "Software"), to deal -# in the Software without restriction, including without limitation the rights -# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -# copies of the Software, and to permit persons to whom the Software is -# furnished to do so, subject to the following conditions: -# -# The above copyright notice and this permission notice shall be included in -# all -# copies or substantial portions of the Software. -# -# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE -# SOFTWARE. -""" -Test cases for the gamma-variational approximations in tsdate -""" - -from math import sqrt - -import numpy as np -import pytest -import scipy.integrate -import scipy.special -import scipy.stats -from exact_moments import ( - leafward_moments, - moments, - mutation_block_moments, - mutation_edge_moments, - mutation_leafward_moments, - mutation_moments, - mutation_rootward_moments, - mutation_sideways_moments, - mutation_twin_moments, - mutation_unphased_moments, - rootward_moments, - sideways_moments, - twin_moments, - unphased_moments, -) - -from tsdate import approx, hypergeo - -# TODO: better test set? -_gamma_trio_test_cases = [ # [shape1, rate1, shape2, rate2, muts, rate] - [2.0, 0.0005, 1.5, 0.005, 0.0, 0.001], - [2.0, 0.0005, 1.5, 0.005, 1.0, 0.001], - [2.0, 0.0005, 1.5, 0.005, 2.0, 0.001], - [2.0, 0.0005, 1.5, 0.005, 3.0, 0.001], -] - - -@pytest.mark.parametrize("pars", _gamma_trio_test_cases) -class TestPosteriorMomentMatching: - """ - Test Laplace approximation of pairwise joint distributions for EP updates - """ - - def test_moments(self, pars): - """ - Test mean and variance when ages of both nodes are free - """ - rtol = 1e-2 - ll, mn_i, va_i, mn_j, va_j = approx.moments(*pars) - ck_ll, ck_mn_i, ck_va_i, ck_mn_j, ck_va_j = moments(*pars) - assert np.isclose(ck_ll, ll, rtol=rtol) - assert np.isclose(ck_mn_i, mn_i, rtol=rtol) - assert np.isclose(ck_mn_j, mn_j, rtol=rtol) - assert np.isclose(sqrt(ck_va_i), sqrt(va_i), rtol=rtol) - assert np.isclose(sqrt(ck_va_j), sqrt(va_j), rtol=rtol) - - def test_rootward_moments(self, pars): - """ - Test mean and variance of parent age when child age is fixed to a nonzero value - """ - rtol = 2e-2 - a_i, b_i, a_j, b_j, y, mu = pars - pars_redux = (a_i, b_i, y, mu) - mn_j = a_j / b_j - for t_j in [0.0, mn_j]: - ll, mn_i, va_i = approx.rootward_moments(t_j, *pars_redux) - ck_ll, ck_mn_i, ck_va_i = rootward_moments(t_j, *pars_redux) - assert np.isclose(ck_ll, ll, rtol=rtol) - assert np.isclose(ck_mn_i, mn_i, rtol=rtol) - assert np.isclose(sqrt(ck_va_i), sqrt(va_i), rtol=rtol) - - def test_leafward_moments(self, pars): - """ - Test mean and variance of child age when parent age is fixed to a nonzero value - """ - rtol = 1e-2 - a_i, b_i, a_j, b_j, y, mu = pars - t_i = a_i / b_i - pars_redux = (a_j, b_j, y, mu) - ll, mn_j, va_j = approx.leafward_moments(t_i, *pars_redux) - ck_ll, ck_mn_j, ck_va_j = leafward_moments(t_i, *pars_redux) - assert np.isclose(ck_ll, ll, rtol=rtol) - assert np.isclose(ck_mn_j, mn_j, rtol=rtol) - assert np.isclose(sqrt(ck_va_j), sqrt(va_j), rtol=rtol) - - def test_unphased_moments(self, pars): - """ - Parent ages for an singleton nodes above an unphased individual - """ - rtol = 1e-2 - ll, mn_i, va_i, mn_j, va_j = approx.unphased_moments(*pars) - ck_ll, ck_mn_i, ck_va_i, ck_mn_j, ck_va_j = unphased_moments(*pars) - assert np.isclose(ck_ll, ll, rtol=rtol) - assert np.isclose(ck_mn_i, mn_i, rtol=rtol) - assert np.isclose(ck_mn_j, mn_j, rtol=rtol) - assert np.isclose(sqrt(ck_va_i), sqrt(va_i), rtol=rtol) - assert np.isclose(sqrt(ck_va_j), sqrt(va_j), rtol=rtol) - - def test_twin_moments(self, pars): - """ - Parent age for a singleton node above both edges of an unphased - individual - """ - a_i, b_i, a_j, b_j, y_ij, mu_ij = pars - pars_redux = (a_i, b_i, y_ij, mu_ij) - ll, mn_i, va_i = approx.twin_moments(*pars_redux) - ck_ll, ck_mn_i, ck_va_i = twin_moments(*pars_redux) - assert np.isclose(ck_ll, ll) - assert np.isclose(ck_mn_i, mn_i) - assert np.isclose(sqrt(ck_va_i), sqrt(va_i)) - - def test_sideways_moments(self, pars): - """ - Parent ages for an singleton nodes above an unphased individual, where - second parent is fixed to a particular time - """ - rtol = 1e-2 - a_i, b_i, a_j, b_j, y, mu = pars - pars_redux = (a_j, b_j, y, mu) - t_i = a_i / b_i - ll, mn_j, va_j = approx.sideways_moments(t_i, *pars_redux) - ck_ll, ck_mn_j, ck_va_j = sideways_moments(t_i, *pars_redux) - assert np.isclose(ck_ll, ll, rtol=rtol) - assert np.isclose(ck_mn_j, mn_j, rtol=rtol) - assert np.isclose(sqrt(ck_va_j), sqrt(va_j), rtol=rtol) - - def test_mutation_moments(self, pars): - """ - Mutation mapped to a single branch with both nodes free - """ - rtol = 2e-2 - mn, va = approx.mutation_moments(*pars) - ck_mn, ck_va = mutation_moments(*pars) - assert np.isclose(ck_mn, mn, rtol=rtol) - assert np.isclose(sqrt(ck_va), sqrt(va), rtol=rtol) - - def test_mutation_rootward_moments(self, pars): - """ - Mutation mapped to a single branch with child node fixed - """ - rtol = 1e-2 - a_i, b_i, a_j, b_j, y, mu = pars - pars_redux = (a_i, b_i, y, mu) - mn_j = a_j / b_j - for t_j in [0.0, mn_j]: - mn, va = approx.mutation_rootward_moments(t_j, *pars_redux) - ck_mn, ck_va = mutation_rootward_moments(t_j, *pars_redux) - assert np.isclose(ck_mn, mn, rtol=rtol) - assert np.isclose(sqrt(ck_va), sqrt(va), rtol=rtol) - - def test_mutation_leafward_moments(self, pars): - """ - Mutation mapped to a single branch with parent node fixed - """ - rtol = 1e-2 - a_i, b_i, a_j, b_j, y, mu = pars - t_i = a_i / b_i - pars_redux = (a_j, b_j, y, mu) - mn, va = approx.mutation_leafward_moments(t_i, *pars_redux) - ck_mn, ck_va = mutation_leafward_moments(t_i, *pars_redux) - assert np.isclose(ck_mn, mn, rtol=rtol) - assert np.isclose(sqrt(ck_va), sqrt(va), rtol=rtol) - - def test_mutation_unphased_moments(self, pars): - """ - Mutation mapped to two singleton branches with children fixed to time zero - """ - rtol = 1e-2 - pr, mn, va = approx.mutation_unphased_moments(*pars) - ck_pr, ck_mn, ck_va = mutation_unphased_moments(*pars) - assert np.isclose(ck_pr, pr, rtol=rtol) - assert np.isclose(ck_mn, mn, rtol=rtol) - assert np.isclose(sqrt(ck_va), sqrt(va), rtol=rtol) - - def test_mutation_twin_moments(self, pars): - """ - Mutation mapped to two singleton branches with children fixed to time zero - and the same parent - """ - a_i, b_i, a_j, b_j, y_ij, mu_ij = pars - pars_redux = (a_i, b_i, y_ij, mu_ij) - pr, mn, va = approx.mutation_twin_moments(*pars_redux) - ck_pr, ck_mn, ck_va = mutation_twin_moments(*pars_redux) - assert np.isclose(ck_pr, pr) - assert np.isclose(ck_mn, mn) - assert np.isclose(sqrt(ck_va), sqrt(va)) - - def test_mutation_sideways_moments(self, pars): - """ - Mutation mapped to two branches with children fixed to time zero, and - left parent (i) fixed - """ - rtol = 1e-2 - a_i, b_i, a_j, b_j, y, mu = pars - t_i = a_i / b_i - pars_redux = (a_j, b_j, y, mu) - pr, mn, va = approx.mutation_sideways_moments(t_i, *pars_redux) - ck_pr, ck_mn, ck_va = mutation_sideways_moments(t_i, *pars_redux) - assert np.isclose(ck_pr, pr, rtol=rtol) - assert np.isclose(ck_mn, mn, rtol=rtol) - assert np.isclose(sqrt(ck_va), sqrt(va), rtol=rtol) - - def test_mutation_edge_moments(self, pars): - """ - Mutation mapped to a single edge with parent and child fixed - """ - a_i, b_i, a_j, b_j, y, mu = pars - t_i = a_i / b_i - t_j = a_j / b_j - mn, va = approx.mutation_edge_moments(t_i, t_j) - ck_mn, ck_va = mutation_edge_moments(t_i, t_j) - assert np.isclose(ck_mn, mn) - assert np.isclose(sqrt(ck_va), sqrt(va)) - - def test_mutation_block_moments(self, pars): - """ - Mutation mapped to two branches with children fixed to time zero, and - both parents fixed - """ - a_i, b_i, a_j, b_j, y, mu = pars - t_i = a_i / b_i - t_j = a_j / b_j - pr, mn, va = approx.mutation_block_moments(t_i, t_j) - ck_pr, ck_mn, ck_va = mutation_block_moments(t_i, t_j) - assert np.isclose(ck_pr, pr) - assert np.isclose(ck_mn, mn) - assert np.isclose(sqrt(ck_va), sqrt(va)) - - def test_approximate_gamma_kl(self, pars): - a_i, b_i, a_j, b_j, y, mu = pars - t_i = a_i / b_i - ln_t_i = hypergeo._digamma(a_i) - np.log(b_i) - t_j = a_j / b_j - ln_t_j = hypergeo._digamma(a_j) - np.log(b_j) - alpha_i, beta_i = approx.approximate_gamma_kl(t_i, ln_t_i) - alpha_j, beta_j = approx.approximate_gamma_kl(t_j, ln_t_j) - ck_t_i = (alpha_i + 1) / beta_i - assert np.isclose(t_i, ck_t_i) - ck_t_j = (alpha_j + 1) / beta_j - assert np.isclose(t_j, ck_t_j) - ck_ln_t_i = hypergeo._digamma(alpha_i + 1) - np.log(beta_i) - assert np.isclose(ln_t_i, ck_ln_t_i) - ck_ln_t_j = hypergeo._digamma(alpha_j + 1) - np.log(beta_j) - assert np.isclose(ln_t_j, ck_ln_t_j) - - def test_approximate_gamma_mom(self, pars): - _, t_i, va_t_i, t_j, va_t_j = approx.moments(*pars) - alpha_i, beta_i = approx.approximate_gamma_mom(t_i, va_t_i) - alpha_j, beta_j = approx.approximate_gamma_mom(t_j, va_t_j) - ck_t_i = (alpha_i + 1) / beta_i - assert np.isclose(t_i, ck_t_i) - ck_t_j = (alpha_j + 1) / beta_j - assert np.isclose(t_j, ck_t_j) - ck_va_t_i = (alpha_i + 1) / beta_i**2 - assert np.isclose(va_t_i, ck_va_t_i) - ck_va_t_j = (alpha_j + 1) / beta_j**2 - assert np.isclose(va_t_j, ck_va_t_j) - - -class TestGammaFactorization: - """ - Test various functions for manipulating factorizations of gamma distributions - """ - - def test_average_gammas(self): - # E[x] = shape/rate - # E[log x] = digamma(shape) - log(rate) - shape = np.array([0.5, 1.5]) - rate = np.array([1.0, 1.0]) - avg_shape, avg_rate = approx.average_gammas(shape, rate) - E_x = np.mean(shape + 1) - E_logx = np.mean(scipy.special.digamma(shape + 1)) - assert np.isclose(E_x, (avg_shape + 1) / avg_rate) - assert np.isclose(E_logx, scipy.special.digamma(avg_shape + 1) - np.log(avg_rate)) - - -class TestKLMinimizationFailed: - """ - Test errors in KL minimization - """ - - def test_violates_jensen(self): - with pytest.raises(approx.KLMinimizationFailedError, match="violates Jensen's"): - approx.approximate_gamma_kl(1, 0) - - def test_asymptotic_bound(self): - # check that bound is returned over threshold (rather than optimization) - logx = -0.000001 - alpha, _ = approx.approximate_gamma_kl(1, logx) - alpha += 1 - alpha_bound = -0.5 / logx - assert alpha == alpha_bound - assert alpha > 1e4 - # check that bound matches optimization result just under threshold - logx = -0.000051 - alpha, _ = approx.approximate_gamma_kl(1, logx) - alpha += 1 - alpha_bound = -0.5 / logx - assert np.abs(alpha - alpha_bound) < 1 - assert alpha < 1e4 diff --git a/tests/test_functions.py b/tests/test_functions.py index f7444887..40b080f8 100644 --- a/tests/test_functions.py +++ b/tests/test_functions.py @@ -1653,7 +1653,7 @@ def test_constrain_ages_backcompat(self): ts = msprime.sim_mutations(ts, rate=1e-8, random_seed=1) sample_data = tsinfer.SampleData.from_tree_sequence(ts) inf_ts = tsinfer.infer(sample_data).simplify() - rng = np.random.default_rng() + rng = np.random.default_rng(1) noise = rng.uniform(0, 0.1, size=inf_ts.num_nodes) nodes_time = inf_ts.nodes_time + noise eps = 1e-6 diff --git a/tests/test_hypergeo.py b/tests/test_hypergeo.py deleted file mode 100644 index cfb3e566..00000000 --- a/tests/test_hypergeo.py +++ /dev/null @@ -1,216 +0,0 @@ -# MIT License -# -# Copyright (c) 2021-23 Tskit Developers -# Copyright (c) 2020-21 University of Oxford -# -# Permission is hereby granted, free of charge, to any person obtaining a copy -# of this software and associated documentation files (the "Software"), to deal -# in the Software without restriction, including without limitation the rights -# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -# copies of the Software, and to permit persons to whom the Software is -# furnished to do so, subject to the following conditions: -# -# The above copyright notice and this permission notice shall be included in -# all copies or substantial portions of the Software. -# -# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE -# SOFTWARE. -""" -Test cases for numba-fied hypergeometric functions -""" - -from math import lgamma - -import mpmath -import numdifftools as nd -import numpy as np -import pytest - -from tsdate import hypergeo - - -@pytest.mark.parametrize("x", [-0.3, 1e-10, 1e-6, 1e-2, 1e1, 1e2, 1e3, 1e5, 1e10]) -class TestPolygamma: - """ - Test numba-fied gamma functions - """ - - def test_lgamma(self, x): - assert np.isclose(lgamma(x), float(mpmath.re(mpmath.loggamma(x)))) - - def test_digamma(self, x): - assert np.isclose(hypergeo._digamma(x), float(mpmath.psi(0, x))) - - def test_trigamma(self, x): - assert np.isclose(hypergeo._trigamma(x), float(mpmath.psi(1, x))) - - def test_betaln(self, x): - assert np.isclose( - hypergeo._betaln(x, 2 * x), - float(mpmath.re(mpmath.log(mpmath.beta(x, 2 * x)))), - ) - - -@pytest.mark.parametrize( - "pars", - [ - [969.5, 0.1062, 984.72, 0.1215, 0.0, 0.000239], - [897.8, 0.0954, 936.03, 0.1042, 1.0, 0.000840], - [37.94, 0.0087, 413.54, 0.1122, 0.0, 2.70e-05], - [748.1, 0.0857, 544.65, 0.0621, 0.0, 0.000511], - [21.18, 0.0226, 21.898, 0.0292, 0.0, 0.000618], - [7.931, 0.0010, 1000.0, 0.1675, 0.0, 0.000290], - [77.15, 0.0484, 42.007, 0.0348, 0.0, 0.000277], - [990.5, 0.1318, 130.68, 0.0205, 1.0, 0.000245], - [678.9, 0.1184, 121.71, 0.0958, 2.0, 0.000208], - ], -) -class TestLaplaceApprox2F1: - """ - Test that Laplace approximation to 2F1 returns reasonable answers - """ - - @staticmethod - def _2f1_validate(a_i, b_i, a_j, b_j, y, mu, offset=1.0): - A = a_j - B = a_i + a_j + y - C = a_j + y + 1 - z = (mu - b_j) / (mu + b_i) - val = mpmath.re(mpmath.hyp2f1(A, B, C, z, maxterms=1e6)) - return val / offset - - def test_2f1(self, pars): - a_i, b_i, a_j, b_j, y, mu = pars - A = a_j - B = a_i + a_j + y - C = a_j + y + 1 - z = (mu - b_j) / (mu + b_i) - f = hypergeo._hyp2f1_laplace(A, B, C, z) - check = float(mpmath.log(self._2f1_validate(*pars))) - assert np.isclose(f, check, rtol=2e-2) - - -@pytest.mark.parametrize( - "pars", - [ - [202.865, 0.0153, 0.0012724, 101353547.00, 0.0, 2.404560e-05], - [999.998, 0.1041, 0.0012612, 14749022.000, 2.0, 7.830300e-05], - [157.778, 0.0182, 0.0011993, 20861958.000, 0.0, 4.128000e-07], - [1000.00, 0.1431, 0.0009718, 22638776.000, 0.0, 5.881110e-05], - [405.482, 0.1484, 0.0009711, 41053809.000, 0.0, 6.229410e-05], - [115.773, 0.7506, 0.0015549, 23315696857.0, 0.0, 3.601680e-05], - [73.4909, 1.0600, 0.0010028, 56254280956.0, 0.0, 0.0002302392], - [18.9981, 0.1315, 0.0015053, 23443723634.0, 1.0, 2.470348e-05], - ], -) -class Test2F1Unity: - """ - As TestLaplaceApprox2F1 but in the argument-close-to-unity limit - """ - - @staticmethod - def _2f1_validate(a_i, b_i, a_j, b_j, y, mu, offset=1.0): - A = a_j - B = a_i + a_j + y - C = a_j + y + 1 - z = (mu - b_j) / (mu + b_i) - val = mpmath.re(mpmath.hyp2f1(A, B, C, z, maxterms=1e7)) - return val / offset - - @pytest.mark.skip(reason="_hyp2f1_unity now an inner function for numba") - def test_2f1(self, pars): - a_i, b_i, a_j, b_j, y, mu = pars - A = a_j - B = a_i + a_j + y - C = a_j + y + 1 - z = (mu - b_j) / (mu + b_i) - s = 0.0 - if z < 0.0: - s = -B * np.log(1 - z) - A = C - A - z = z / (z - 1) - f = hypergeo._hyp2f1_unity(A, B, C, z) + s - check = float(mpmath.log(self._2f1_validate(*pars))) - assert np.isclose(f, check, rtol=1e-2) - - -@pytest.mark.parametrize( - "pars", - [ - [92.301156, 3.338, 0.008172, 0.0, 0.00022691], - [92.301156, 3.678, 0.005831, 0.0, 0.00250921], - [2998.6825, 3.999, 0.000750, 1.0, 0.00098396], - [11985.278, 5.251, 0.000193, 8.0, 1.9537e-05], - [11985.278, 14.46, 0.000822, 3.0, 0.00011632], - [12957.347, 0.999, 9.999e-5, 1.0, 0.00019150], - ], -) -class TestLaplaceApproxU: - """ - Test that Laplace approximation to Tricomi's confluent hypergeometric - function returns reasonable answers - """ - - @staticmethod - def _hyperu_validate(t_j, a_i, b_i, y, mu, offset=1.0): - A = y + 1 - B = a_i + y + 1 - z = t_j * (mu + b_i) - val = mpmath.re(mpmath.hyperu(A, B, z, maxterms=1e6)) - return val / offset - - def test_hyperu(self, pars): - t_j, a_i, b_i, y, mu = pars - A = y + 1 - B = a_i + y + 1 - z = t_j * (mu + b_i) - f, df = hypergeo._hyperu_laplace(A, B, z) - der = nd.Derivative( - lambda z: hypergeo._hyperu_laplace(A, B, z)[0], n=1, step=1e-4 - ) - check_f = float(mpmath.log(self._hyperu_validate(*pars))) - check_df = der(z) - assert np.isclose(f, check_f, rtol=2e-2) - assert np.isclose(df, check_df, rtol=2e-2) - - -@pytest.mark.parametrize( - "pars", - [ - [25128.46, 132.48, 0.006849, 0.0, 4.4562e-05], - [15900.89, 997.09, 0.093978, 1.0, 0.00010288], - [10062.80, 978.24, 0.102753, 0.0, 0.00022747], - [11659.45, 713.52, 0.064035, 8.0, 0.00064625], - [40888.01, 999.99, 0.071372, 3.0, 3.7925e-05], - [11659.45, 989.08, 0.096664, 2.0, 0.00010425], - [22333.94, 28.546, 0.001817, 0.0, 9.6225e-05], - [30613.25, 30.956, 0.000942, 0.0, 1.1250e-07], - ], -) -class TestLaplaceApproxM: - """ - Test that Laplace approximation to Kummer's confluent hypergeometric - function returns reasonable answers - """ - - @staticmethod - def _hyp1f1_validate(t_i, a_j, b_j, y, mu, offset=1.0): - A = a_j - B = a_j + y + 1 - z = t_i * (b_j - mu) - val = mpmath.re(mpmath.hyp1f1(A, B, z, maxterms=1e6)) - return val / offset - - def test_hyp1f1(self, pars): - t_i, a_j, b_j, y, mu = pars - A = a_j - B = a_j + y + 1 - z = t_i * (b_j - mu) - f = hypergeo._hyp1f1_laplace(A, B, z) - check = float(mpmath.log(self._hyp1f1_validate(*pars))) - assert np.isclose(f, check, rtol=2e-2) diff --git a/tests/test_oracle_phasing.py b/tests/test_oracle_phasing.py new file mode 100644 index 00000000..1cf5f274 --- /dev/null +++ b/tests/test_oracle_phasing.py @@ -0,0 +1,413 @@ +""" +Equivalence of the phasing functions of ``_tsdate`` with their oracles: random +inputs built as in ``ExpectationPropagation``, degenerate inputs, and every error. +""" + +import _tsdate +import numpy as np +import pytest +import tskit +from oracle import phasing +from oracle.errors import ( + BLOCK_OUT_OF_BOUNDS, + PHASE_OUT_OF_RANGE, + UNPHASED_INDIVIDUAL_EDGES, + UNPHASED_LIKELIHOOD_NOT_CONSERVED, +) +from oracle.helpers import assert_same_error, assert_same_result, make_ts + +from tsdate.phasing import block_singletons +from tsdate.rescaling import count_mutations + + +def block_singletons_kwargs(ts, unphased): + return dict( + individuals_unphased=np.array(unphased, dtype=bool), + nodes_individual=ts.nodes_individual, + mutations_node=ts.mutations_node, + mutations_position=ts.sites_position[ts.mutations_site], + edges_child=ts.edges_child, + edges_left=ts.edges_left, + edges_right=ts.edges_right, + indexes_insert=ts.indexes_edge_insertion_order, + indexes_remove=ts.indexes_edge_removal_order, + sequence_length=ts.sequence_length, + ) + + +# nodes 0, 1 belong to individual 0, nodes 2, 3 to individual 1, node 4 is the root +NODES = [(1, 0, 0), (1, 0, 0), (1, 0, 1), (1, 0, 1), (0, 1, -1)] +STAR = [(0, 10, 4, 0), (0, 10, 4, 1), (0, 10, 4, 2), (0, 10, 4, 3)] +GAP = [(0, 4, 4, 0), (0, 4, 4, 1), (6, 10, 4, 0), (6, 10, 4, 1)] + STAR[2:] +SKEW = [(0, 4, 4, 0), (0, 6, 4, 1), (4, 10, 4, 0), (6, 10, 4, 1)] + STAR[2:] +SPLIT = [(0, 5, 4, 0), (5, 10, 4, 0), (0, 10, 4, 1)] + STAR[2:] +NO_INDIVIDUALS = [(1, 0, -1), (1, 0, -1), (0, 1, -1)] +ONE_INDIVIDUAL = [(1, 0, 0), (1, 0, 0), (1, 0, -1), (0, 1, -1)] + +# nodes, number of individuals, edges, mutations, unphased +BLOCK_EDGE_CASES = [ + pytest.param(NODES, 2, STAR, [(1, 4)], [1, 1], id="no_singletons"), + pytest.param(NODES, 2, STAR, [(1, 0)], [1, 1], id="singleton"), + pytest.param(NODES, 2, STAR, [(1, 0)], [0, 0], id="all_phased"), + pytest.param(NODES, 2, STAR, [], [1, 1], id="no_mutations"), + pytest.param(NODES, 2, [], [(1, 0)], [1, 1], id="no_edges"), + pytest.param( + NO_INDIVIDUALS, + 0, + [(0, 10, 2, 0), (0, 10, 2, 1)], + [(1, 0)], + [], + id="no_individuals", + ), + pytest.param( + ONE_INDIVIDUAL, + 1, + [(0, 10, 3, 0), (0, 10, 3, 1), (0, 10, 3, 2)], + [(1, 0), (2, 2)], + [1], + id="node_without_individual", + ), +] + +# edges, mutations, unphased, mutations_block (block ids are numbered in the order +# that blocks start; a mutation in no block is NULL) +BLOCK_NUMBERING = [ + pytest.param(STAR, [(1, 0)], [1, 1], [0], id="singleton"), + pytest.param(STAR, [(1, 0), (2, 2), (3, 0)], [1, 0], [0, tskit.NULL, 0], id="mixed"), + pytest.param( + GAP, + [(1, 0), (5, 0), (7, 0), (7.5, 1)], + [1, 1], + [0, tskit.NULL, 2, 2], + id="mutation_in_gap", + ), + pytest.param(SPLIT, [(1, 0), (7, 0)], [1, 1], [0, 2], id="breakpoint_one_node"), + pytest.param( + SKEW, + [(1, 0), (5, 0), (5.5, 1), (8, 1), (8.5, 0)], + [1, 1], + [0, 2, 2, 3, 3], + id="breakpoints_differ", + ), +] + + +class TestBlockSingletons: + @pytest.mark.parametrize( + ("nodes", "num_individuals", "edges", "mutations", "unphased"), + BLOCK_EDGE_CASES, + ) + def test_edge_cases(self, nodes, num_individuals, edges, mutations, unphased): + ts = make_ts(nodes, edges, mutations, 10.0, num_individuals) + kwargs = block_singletons_kwargs(ts, unphased) + assert_same_result(_tsdate.block_singletons, phasing.block_singletons, **kwargs) + + def test_one_haplotype_edge_missing(self): + # NOTE: current behaviour, possibly a bug: reachable from real data + # (one haplotype of an unphased individual missing over a region); its block + # is never flushed and the final consistency check fails + edges = [(0, 10, 4, 0), (0, 10, 4, 2), (0, 10, 4, 3)] + ts = make_ts(NODES, edges, [(1, 0)], 10.0, 2) + kwargs = block_singletons_kwargs(ts, [1, 1]) + assert_same_error( + _tsdate.block_singletons, + phasing.block_singletons, + UNPHASED_INDIVIDUAL_EDGES, + **kwargs, + ) + + @pytest.mark.parametrize( + ("edges", "mutations", "unphased", "expected"), BLOCK_NUMBERING + ) + def test_block_numbering(self, edges, mutations, unphased, expected): + ts = make_ts(NODES, edges, mutations, 10.0, 2) + kwargs = block_singletons_kwargs(ts, unphased) + _, _, mutations_block = assert_same_result( + _tsdate.block_singletons, phasing.block_singletons, **kwargs + ) + assert mutations_block.tolist() == expected + + @pytest.mark.parametrize("fraction", [0.0, 0.5, 1.0]) + @pytest.mark.parametrize("seed", range(2)) + def test_random(self, small_ts_unphased, seed, fraction): + ts = small_ts_unphased + rng = np.random.default_rng(seed) + unphased = rng.random(ts.num_individuals) < fraction + kwargs = block_singletons_kwargs(ts, unphased) + assert_same_result(_tsdate.block_singletons, phasing.block_singletons, **kwargs) + + +def reallocate_unphased_kwargs(ts): + """ + Arguments of ``reallocate_unphased`` for ``ts``, with all individuals unphased and + every phase one half + """ + unphased = np.full(ts.num_individuals, True) + _, blocks_edges, mutations_block = block_singletons(ts, unphased) + edges_likelihood, _ = count_mutations(ts) + return dict( + edges_likelihood=edges_likelihood, + mutations_phase=np.full(ts.num_mutations, 0.5), + mutations_block=mutations_block, + blocks_edges=blocks_edges, + ) + + +def first_blocked_mutation(kwargs): + """ + The first mutation that is in a block + """ + return np.flatnonzero(kwargs["mutations_block"] != tskit.NULL)[0] + + +# edges_likelihood, mutations_phase, mutations_block, blocks_edges +REALLOCATE_SMALL = [ + pytest.param( + [[2.0, 5.0], [0.0, 5.0]], + [0.0, 0.0], + [0, 0], + [[0, 1]], + id="phases_zero", + ), + pytest.param( + [[2.0, 5.0], [0.0, 5.0]], + [1.0, 1.0], + [0, 0], + [[0, 1]], + id="phases_one", + ), + pytest.param( + [[2.0, 5.0], [0.0, 5.0], [7.0, 5.0]], + [0.25, 1.0, np.nan], + [0, 0, -1], + [[0, 1]], + id="single_block_with_unblocked_nan", + ), + pytest.param( + [[3.0, 1.0], [1.0, 1.0], [0.0, 1.0]], + [0.5, 0.5, 0.5, 0.5], + [0, 0, 1, 1], + [[0, 1], [1, 2]], + id="edge_in_two_blocks", + ), + pytest.param( + np.zeros((0, 2)), + [], + [], + np.zeros((0, 2)), + id="nothing_at_all", + ), +] + + +class TestReallocateUnphased: + @pytest.mark.parametrize( + ("edges_likelihood", "mutations_phase", "mutations_block", "blocks_edges"), + REALLOCATE_SMALL, + ) + def test_small( + self, edges_likelihood, mutations_phase, mutations_block, blocks_edges + ): + assert_same_result( + _tsdate.reallocate_unphased, + phasing.reallocate_unphased, + edges_likelihood=np.array(edges_likelihood, dtype=np.float64), + mutations_phase=np.array(mutations_phase, dtype=np.float64), + mutations_block=np.array(mutations_block, dtype=np.int32), + blocks_edges=np.array(blocks_edges, dtype=np.int32), + ) + + def test_null_edge_in_block(self): + assert_same_error( + _tsdate.reallocate_unphased, + phasing.reallocate_unphased, + BLOCK_OUT_OF_BOUNDS, + edges_likelihood=np.ones((2, 2)), + mutations_phase=np.array([0.5]), + mutations_block=np.array([0], dtype=np.int32), + blocks_edges=np.array([[0, -1]], dtype=np.int32), + ) + + @pytest.mark.parametrize("mode", ["fractional", "mixed"]) + @pytest.mark.parametrize("seed", range(3)) + def test_random(self, small_ts_unphased, seed, mode): + ts = small_ts_unphased + rng = np.random.default_rng(seed) + kwargs = reallocate_unphased_kwargs(ts) + if mode == "fractional": + kwargs["mutations_phase"] = rng.uniform(0, 1, ts.num_mutations) + else: + phases = [0.0, 1.0, 0.5, 0.25] + kwargs["mutations_phase"] = rng.choice(phases, ts.num_mutations) + assert_same_result( + _tsdate.reallocate_unphased, phasing.reallocate_unphased, **kwargs + ) + + @pytest.mark.parametrize("value", [1.5, -1e-9, np.inf, -np.inf]) + def test_phase_out_of_range(self, small_ts_unphased, value): + kwargs = reallocate_unphased_kwargs(small_ts_unphased) + kwargs["mutations_phase"][first_blocked_mutation(kwargs)] = value + assert_same_error( + _tsdate.reallocate_unphased, + phasing.reallocate_unphased, + PHASE_OUT_OF_RANGE, + **kwargs, + ) + + @pytest.mark.parametrize("value", [np.nan, 7.0]) + def test_phase_ignored_without_block(self, small_ts_unphased, value): + kwargs = reallocate_unphased_kwargs(small_ts_unphased) + unblocked = kwargs["mutations_block"] == tskit.NULL + kwargs["mutations_phase"][unblocked] = value + assert_same_result( + _tsdate.reallocate_unphased, phasing.reallocate_unphased, **kwargs + ) + + def test_nan_phase(self, small_ts_unphased): + # NOTE: current behaviour, possibly a bug: a NaN phase on a + # blocked mutation is skipped, leaving its singleton unallocated, so the + # final `np.isclose` check fails. It only passes if the likelihoods happen to + # total one less + kwargs = reallocate_unphased_kwargs(small_ts_unphased) + kwargs["mutations_phase"][first_blocked_mutation(kwargs)] = np.nan + assert_same_error( + _tsdate.reallocate_unphased, + phasing.reallocate_unphased, + UNPHASED_LIKELIHOOD_NOT_CONSERVED, + **kwargs, + ) + first_edge = kwargs["blocks_edges"][0, 0] + kwargs["edges_likelihood"][first_edge, 0] -= 1.0 + assert_same_result( + _tsdate.reallocate_unphased, phasing.reallocate_unphased, **kwargs + ) + + def test_no_mutations(self, small_ts_unphased): + # likelihood on the edges of the blocks, but no mutation to allocate it + kwargs = reallocate_unphased_kwargs(small_ts_unphased) + kwargs["mutations_phase"] = np.zeros(0) + kwargs["mutations_block"] = np.zeros(0, dtype=np.int32) + assert_same_error( + _tsdate.reallocate_unphased, + phasing.reallocate_unphased, + UNPHASED_LIKELIHOOD_NOT_CONSERVED, + **kwargs, + ) + + def test_no_mutations_in_blocks(self, small_ts_unphased): + # likelihood on the edges of the blocks, but no mutation to allocate it + kwargs = reallocate_unphased_kwargs(small_ts_unphased) + kwargs["mutations_block"][:] = tskit.NULL + assert_same_error( + _tsdate.reallocate_unphased, + phasing.reallocate_unphased, + UNPHASED_LIKELIHOOD_NOT_CONSERVED, + **kwargs, + ) + + +def mutation_frequency_kwargs(ts, sample_sets): + """ + Arguments of ``mutation_frequency`` for ``ts``, with a column of ``nodes_sample`` + for each list of nodes in ``sample_sets`` + """ + nodes_sample = np.zeros((ts.num_nodes, len(sample_sets)), dtype=bool) + for i, nodes in enumerate(sample_sets): + nodes_sample[list(nodes), i] = True + return dict( + nodes_sample=nodes_sample, + mutations_node=ts.mutations_node, + mutations_position=ts.sites_position[ts.mutations_site], + edges_parent=ts.edges_parent, + edges_child=ts.edges_child, + edges_left=ts.edges_left, + edges_right=ts.edges_right, + indexes_insert=ts.indexes_edge_insertion_order, + indexes_remove=ts.indexes_edge_removal_order, + sequence_length=ts.sequence_length, + ) + + +# samples 0, 1, 2 (time 0), internal nodes 3 (time 1) and 4 (time 2); node 3 is a +# child of 4 throughout, but its parent edge is split at position 5 +FREQ_NODES = [(1, 0), (1, 0), (1, 0), (0, 1), (0, 2)] +FREQ_EDGES = [(0, 10, 3, 0), (0, 10, 3, 1), (0, 5, 4, 3), (0, 10, 4, 2), (5, 10, 4, 3)] +FREQ_MUTATIONS = [(1, 0), (2, 3), (3, 4), (6, 2), (7, 3)] +FREQ_TS = make_ts(FREQ_NODES, FREQ_EDGES, FREQ_MUTATIONS, 10.0) + +SAMPLE_SETS = [ + pytest.param([[0, 1, 2]], id="all_samples"), + pytest.param([[0]], id="single_sample"), + pytest.param([[]], id="empty_set"), + pytest.param([], id="no_sets"), + pytest.param([[], [0, 1, 2]], id="empty_and_full"), + pytest.param([[0, 1], [1, 2], [0, 1, 2]], id="overlapping"), + pytest.param([[0, 1], [0, 1]], id="identical"), + pytest.param([[3]], id="internal_node"), + pytest.param([[4, 0]], id="root_and_sample"), +] + + +class TestMutationFrequency: + @pytest.mark.parametrize("sample_sets", SAMPLE_SETS) + def test_sample_sets(self, sample_sets): + kwargs = mutation_frequency_kwargs(FREQ_TS, sample_sets) + assert_same_result( + _tsdate.mutation_frequency, phasing.mutation_frequency, **kwargs + ) + + def test_no_mutations(self): + ts = make_ts([(1, 0), (0, 1)], [(0, 10, 1, 0)], [], 10.0) + kwargs = mutation_frequency_kwargs(ts, [[0]]) + assert_same_result( + _tsdate.mutation_frequency, phasing.mutation_frequency, **kwargs + ) + + def test_no_edges(self): + # NOTE: current behaviour, possibly a bug: with no edges the + # sweep is never entered, so every frequency is zero, even above a member + ts = make_ts([(1, 0), (0, 1)], [], [(1, 0), (2, 1)], 10.0) + kwargs = mutation_frequency_kwargs(ts, [[0, 1]]) + assert_same_result( + _tsdate.mutation_frequency, phasing.mutation_frequency, **kwargs + ) + + def test_mutation_beyond_last_edge(self): + nodes = [(1, 0), (1, 0), (0, 1)] + edges = [(0, 5, 2, 0), (0, 5, 2, 1)] + ts = make_ts(nodes, edges, [(1, 2), (7, 2)], 10.0) + kwargs = mutation_frequency_kwargs(ts, [[0, 1]]) + assert_same_result( + _tsdate.mutation_frequency, phasing.mutation_frequency, **kwargs + ) + + def test_mutation_at_breakpoint(self): + # a mutation exactly at a breakpoint belongs to the tree to its right + ts = make_ts(FREQ_NODES, FREQ_EDGES, [(5, 4)], 10.0) + kwargs = mutation_frequency_kwargs(ts, [[0, 1, 2]]) + assert_same_result( + _tsdate.mutation_frequency, phasing.mutation_frequency, **kwargs + ) + + def test_unsorted_mutations(self): + order = np.array([3, 0, 4, 1, 2]) + kwargs = mutation_frequency_kwargs(FREQ_TS, [[0, 1, 2]]) + kwargs["mutations_node"] = kwargs["mutations_node"][order] + kwargs["mutations_position"] = kwargs["mutations_position"][order] + assert_same_result( + _tsdate.mutation_frequency, phasing.mutation_frequency, **kwargs + ) + + @pytest.mark.parametrize("num_sets", [1, 4]) + @pytest.mark.parametrize("seed", range(2)) + def test_random(self, small_ts, seed, num_sets): + ts = small_ts + rng = np.random.default_rng(seed) + sample_sets = [] + for _ in range(num_sets): + size = rng.integers(0, ts.num_samples + 1) + sample_sets.append(rng.choice(ts.samples(), size=size, replace=False)) + kwargs = mutation_frequency_kwargs(ts, sample_sets) + assert_same_result( + _tsdate.mutation_frequency, phasing.mutation_frequency, **kwargs + ) diff --git a/tests/test_oracle_util.py b/tests/test_oracle_util.py new file mode 100644 index 00000000..ff1b707e --- /dev/null +++ b/tests/test_oracle_util.py @@ -0,0 +1,396 @@ +""" +Equivalence of the tree sequence utilities of ``_tsdate`` with their oracles: +simulated tree sequences, degenerate inputs, and every error. +""" + +import _tsdate +import numpy as np +import pytest +import tskit +from oracle import util +from oracle.errors import FIXED_NODES_VIOLATE_CONSTRAINT, MUTATION_NODE_NOT_IN_TREE +from oracle.helpers import assert_same_error, assert_same_result, make_ts + + +@pytest.fixture(params=["small_ts", "small_ts_historical"]) +def sim_ts(request): + return request.getfixturevalue(request.param) + + +def sample_flags(ts): + return np.bitwise_and(ts.nodes_flags, tskit.NODE_IS_SAMPLE).astype(bool) + + +# edges_parent, edges_child, edges_left, edges_right, nodes_excluded, and the +# expected split_nodes (new nodes are numbered from the number of nodes, and each is +# a copy of an old node: `split_nodes` lists the old ids) +SPLIT_CASES = [ + pytest.param([2, 2], [0, 1], [0, 0], [10, 10], [1, 1, 0], [], id="no_disjoint"), + pytest.param([], [], [], [], [1, 0], [], id="no_edges"), + pytest.param([], [], [], [], [], [], id="no_nodes"), + pytest.param( + [2, 2, 2], [0, 1, 1], [0, 2, 6], [2, 4, 8], [1, 1, 0], [2], id="one_split" + ), + pytest.param( + [2, 2, 2], [0, 0, 1], [0, 6, 0], [4, 10, 10], [1, 1, 0], [], id="excluded" + ), + pytest.param( + [3, 3, 3], [0, 0, 0], [0, 3, 6], [1, 4, 7], [1, 1, 1, 1], [], id="all_excluded" + ), + pytest.param( + [3, 3, 3], + [0, 0, 0], + [0, 3, 6], + [1, 4, 7], + [0, 0, 0, 0], + [0, 0, 3, 3], + id="many_splits", + ), + pytest.param( + [3, 3, 3, 3, 4], + [0, 0, 0, 1, 3], + [0, 3, 6, 0, 0], + [1, 4, 7, 10, 10], + [1, 1, 1, 0, 0], + [], + id="contiguous_over_another_child", + ), + pytest.param([3, 3], [0, 0], [0, 1], [1, 2], [0] * 4, [], id="touching"), + pytest.param([3, 3], [0, 0], [0, 0], [2, 5], [0] * 4, [], id="overlapping"), + pytest.param([3, 3], [0, 0], [0, 1.0000001], [1, 2], [0] * 4, [0, 3], id="tiny_gap"), + pytest.param( + [2, 2, 2], [1, 1, 0], [6, 2, 0], [8, 4, 2], [1, 1, 0], [2], id="unsorted" + ), + pytest.param([2], [0], [0], [1], [1, 0, 0], [], id="first_edge_at_zero"), +] + + +class TestSplitDisjointNodes: + @pytest.mark.parametrize( + ("parent", "child", "left", "right", "excluded", "expected"), SPLIT_CASES + ) + def test_edge_cases(self, parent, child, left, right, excluded, expected): + _, _, _, split_nodes = assert_same_result( + _tsdate.split_disjoint_nodes, + util.split_disjoint_nodes, + edges_parent=np.array(parent, dtype=np.int32), + edges_child=np.array(child, dtype=np.int32), + edges_left=np.array(left, dtype=np.float64), + edges_right=np.array(right, dtype=np.float64), + nodes_excluded=np.array(excluded, dtype=bool), + ) + assert split_nodes.tolist() == expected + + def test_simulated(self, sim_ts): + assert_same_result( + _tsdate.split_disjoint_nodes, + util.split_disjoint_nodes, + edges_parent=sim_ts.edges_parent, + edges_child=sim_ts.edges_child, + edges_left=sim_ts.edges_left, + edges_right=sim_ts.edges_right, + nodes_excluded=sample_flags(sim_ts), + ) + + +def relabel_mutations_node_kwargs(ts): + """ + Arguments of ``relabel_mutations_node``, with the nodes of ``ts`` split as by + ``util.split_disjoint_nodes`` + """ + edges_parent, edges_child, nodes_order, _ = util.split_disjoint_nodes( + edges_parent=ts.edges_parent, + edges_child=ts.edges_child, + edges_left=ts.edges_left, + edges_right=ts.edges_right, + nodes_excluded=sample_flags(ts), + ) + return dict( + mutations_node=ts.mutations_node, + mutations_position=ts.sites_position[ts.mutations_site], + nodes_order=nodes_order, + edges_parent=edges_parent, + edges_child=edges_child, + edges_left=ts.edges_left, + edges_right=ts.edges_right, + indexes_insert=ts.indexes_edge_insertion_order, + indexes_remove=ts.indexes_edge_removal_order, + ) + + +# nodes 0, 1 are samples, 2 and 3 are internal and have a gap at [4, 6) +GAP_NODES = [(1, 0), (1, 0), (0, 1), (0, 2)] +GAP_EDGES = [(0, 4, 2, 0), (0, 4, 2, 1), (6, 10, 2, 0), (6, 10, 2, 1)] +GAP_EDGES += [(0, 4, 3, 2), (6, 10, 3, 2)] +BINARY_EDGES = [(0, 10, 2, 0), (0, 10, 2, 1)] + +# nodes, edges, mutations, sequence length +RELABEL_CASES = [ + pytest.param(GAP_NODES, GAP_EDGES, [], 10.0, id="no_mutations"), + pytest.param( + GAP_NODES[:3], BINARY_EDGES, [(1, 0), (2, 2), (3, 1)], 10.0, id="no_splits" + ), + # the sweep stops at the largest edge right coordinate: later mutations are NULL + pytest.param(GAP_NODES, GAP_EDGES, [(1, 2), (10.0, 2)], 20.0, id="beyond_last_edge"), +] + + +class TestRelabelMutationsNode: + @pytest.mark.parametrize(("nodes", "edges", "mutations", "length"), RELABEL_CASES) + def test_edge_cases(self, nodes, edges, mutations, length): + ts = make_ts(nodes, edges, mutations, length) + kwargs = relabel_mutations_node_kwargs(ts) + assert_same_result( + _tsdate.relabel_mutations_node, util.relabel_mutations_node, **kwargs + ) + + def test_node_not_in_tree(self): + # node 3 has no edges + ts = make_ts(GAP_NODES, BINARY_EDGES, [(1, 3)], 10.0) + kwargs = relabel_mutations_node_kwargs(ts) + assert_same_error( + _tsdate.relabel_mutations_node, + util.relabel_mutations_node, + MUTATION_NODE_NOT_IN_TREE, + **kwargs, + ) + + def test_mutations_on_split_nodes(self): + mutations = [(0.5, 0), (1, 2), (2, 3), (5, 0), (7, 2), (8, 3)] + ts = make_ts(GAP_NODES, GAP_EDGES, mutations, 10.0) + kwargs = relabel_mutations_node_kwargs(ts) + result = assert_same_result( + _tsdate.relabel_mutations_node, util.relabel_mutations_node, **kwargs + ) + # right-hand pieces of nodes 2 and 3 are the new nodes 4 and 5; the mutation + # at 5 is in the gap, on the (unsplit) sample 0 + assert result.tolist() == [0, 2, 3, 0, 4, 5] + + def test_simulated(self, sim_ts): + kwargs = relabel_mutations_node_kwargs(sim_ts) + assert_same_result( + _tsdate.relabel_mutations_node, util.relabel_mutations_node, **kwargs + ) + + +def constrain_ages_kwargs(times, fixed, parents, children, epsilon, max_iterations): + return dict( + nodes_time=np.array(times, dtype=np.float64), + nodes_fixed=np.array(fixed, dtype=bool), + edges_parent=np.array(parents, dtype=np.int32), + edges_child=np.array(children, dtype=np.int32), + epsilon=epsilon, + max_iterations=max_iterations, + ) + + +# nodes_time, nodes_fixed, edges_parent, edges_child +# node 2 (age 1) is above samples 0, 1; node 3 (age 0.5) is above node 2: violated +VIOLATED = ([0, 0, 1.0, 0.5], [1, 1, 0, 0], [2, 3], [0, 2]) +CONSISTENT = ([0, 0, 1.0], [1, 1, 0], [2, 2], [0, 1]) +# one edge with parent age 0 and child age 1 (a violation); node 0 is the parent +INVERTED = ([0.0, 1.0], [0, 0], [0], [1]) + +# nodes_time, nodes_fixed, edges_parent, edges_child, epsilon, max_iterations +CONSTRAIN_EDGE_CASES = [ + pytest.param(*CONSISTENT, 1e-6, 0, id="consistent_forced"), + pytest.param(*CONSISTENT, 1e-6, 10, id="consistent_iterated"), + pytest.param(*CONSISTENT, 1.0, 0, id="branch_length_equals_epsilon"), + pytest.param(*CONSISTENT, 1.0, 10, id="branch_length_equals_epsilon_it"), + pytest.param([0, 1.0], [1, 0], [1], [0], 2.0, 0, id="shorter_than_epsilon"), + pytest.param(*VIOLATED, 1e-6, -1, id="negative_iterations"), + pytest.param(*INVERTED, 0.1, 100, id="free_nodes_meet"), + pytest.param([0.0, 1.0], [1, 0], [0], [1], 0.1, 100, id="fixed_parent"), + pytest.param([0.0, 1.0], [0, 1], [0], [1], 0.1, 100, id="fixed_child"), + # with no iterations the forcing step changes the age of a fixed node + pytest.param([0.0, 1.0], [1, 1], [0], [1], 0.1, 0, id="both_fixed_forced"), + pytest.param([0.0, 1.0], [1, 0], [], [], 0.1, 10, id="no_edges"), + pytest.param([], [], [], [], 0.1, 10, id="no_nodes"), + pytest.param([0.0, 1.0], [1, 0], [1], [0], -0.5, 3, id="negative_epsilon"), + pytest.param([0.0, 0.0], [1, 0], [1], [0], 0.0, 3, id="equal_ages_zero_eps"), + pytest.param( + [1.0] * 5, + [1, 0, 0, 0, 0], + [1, 2, 3, 4], + [0, 1, 2, 3], + 1e-3, + 1000, + id="slow_convergence_chain", + ), +] + + +class TestConstrainAges: + @pytest.mark.parametrize("max_iterations", [0, 1, 1000]) + @pytest.mark.parametrize("epsilon", [0.0, 1e-6, 0.5]) + def test_violation(self, epsilon, max_iterations): + kwargs = constrain_ages_kwargs(*VIOLATED, epsilon, max_iterations) + assert_same_result(_tsdate.constrain_ages, util.constrain_ages, **kwargs) + + @pytest.mark.parametrize( + ("times", "fixed", "parents", "children", "epsilon", "max_iterations"), + CONSTRAIN_EDGE_CASES, + ) + def test_edge_cases(self, times, fixed, parents, children, epsilon, max_iterations): + kwargs = constrain_ages_kwargs( + times, fixed, parents, children, epsilon, max_iterations + ) + result = assert_same_result(_tsdate.constrain_ages, util.constrain_ages, **kwargs) + assert np.all(np.isfinite(result)) + + @pytest.mark.parametrize( + "times", [pytest.param([0.0, np.nan]), pytest.param([np.nan, 1.0])] + ) + def test_nan_age(self, times): + # NaN comparisons are all false: no branch is a violation, and NaN is carried + kwargs = constrain_ages_kwargs(times, [1, 0], [1], [0], 0.1, 3) + result = assert_same_result(_tsdate.constrain_ages, util.constrain_ages, **kwargs) + assert np.isnan(result).tolist() == np.isnan(times).tolist() + + def test_both_fixed(self): + # NOTE: current behaviour, possibly a bug: two fixed nodes on a + # violated edge are an error (reachable via `constrain_ages` with + # inconsistent ancient sample ages) + kwargs = constrain_ages_kwargs([0.0, 1.0], [1, 1], [0], [1], 0.1, 100) + assert_same_error( + _tsdate.constrain_ages, + util.constrain_ages, + FIXED_NODES_VIOLATE_CONSTRAINT, + **kwargs, + ) + + @pytest.mark.parametrize("mode", ["iterated", "forced"]) + @pytest.mark.parametrize("seed", range(2)) + def test_simulated(self, sim_ts, seed, mode): + ts = sim_ts + rng = np.random.default_rng(seed) + if mode == "iterated": + noise = rng.uniform(0.9, 1.1, ts.num_nodes) + epsilon = 1e-6 + max_iterations = 50 + else: + noise = rng.uniform(0.5, 1.5, ts.num_nodes) + epsilon = 1e-2 + max_iterations = 0 + fixed = sample_flags(ts) + nodes_time = ts.nodes_time * noise + nodes_time[fixed] = ts.nodes_time[fixed] + assert_same_result( + _tsdate.constrain_ages, + util.constrain_ages, + nodes_time=nodes_time, + nodes_fixed=fixed, + edges_parent=ts.edges_parent, + edges_child=ts.edges_child, + epsilon=epsilon, + max_iterations=max_iterations, + ) + + +def contains_unary_nodes_kwargs(ts, skip_samples): + """ + Arguments of ``contains_unary_nodes`` for ``ts``, with the samples masked if + ``skip_samples`` + """ + nodes_mask = np.full(ts.num_nodes, False) + if skip_samples: + nodes_mask[ts.samples()] = True + return dict( + nodes_mask=nodes_mask, + edges_parent=ts.edges_parent, + edges_left=ts.edges_left, + edges_right=ts.edges_right, + indexes_insert=ts.indexes_edge_insertion_order, + indexes_remove=ts.indexes_edge_removal_order, + sequence_length=ts.sequence_length, + ) + + +# nodes, edges, and the expected results with the samples skipped and not skipped +UNARY_CASES = [ + pytest.param([(1, 0), (1, 0), (0, 1)], BINARY_EDGES, False, False, id="binary"), + pytest.param([(1, 0), (1, 0)], [], False, False, id="no_edges"), + pytest.param( + [(1, 0), (1, 0), (0, 1), (0, 2)], + BINARY_EDGES + [(0, 10, 3, 2)], + True, + True, + id="unary_internal_node", + ), + pytest.param( + # sample 3 has the single child 0; the root has three children + [(1, 0), (1, 0), (1, 0), (1, 1), (0, 2)], + [(0, 10, 3, 0), (0, 10, 4, 3), (0, 10, 4, 1), (0, 10, 4, 2)], + False, + True, + id="unary_sample", + ), + pytest.param( + # node 3 is unary only over [4, 6) + [(1, 0), (1, 0), (1, 0), (0, 1), (0, 2)], + [(0, 4, 3, 0), (0, 4, 3, 1), (4, 6, 3, 0), (6, 10, 3, 0)] + + [(6, 10, 3, 1), (0, 10, 4, 3), (0, 10, 4, 2)], + True, + True, + id="unary_in_middle_tree", + ), + pytest.param( + # node 3 loses child 0 and gains child 2 at 5: it always has two children + [(1, 0), (1, 0), (1, 0), (0, 1)], + [(0, 5, 3, 0), (0, 10, 3, 1), (5, 10, 3, 2)], + False, + False, + id="child_replaced_at_breakpoint", + ), + pytest.param( + [(1, 0), (1, 0), (0, 1)], + [(0, 5, 2, 0), (0, 5, 2, 1), (5, 10, 2, 0)], + True, + True, + id="unary_in_last_tree", + ), + pytest.param( + [(1, 0), (1, 0), (0, 1)], + [(0, 5, 2, 0), (5, 10, 2, 0), (5, 10, 2, 1)], + True, + True, + id="unary_in_first_tree", + ), +] + + +class TestContainsUnaryNodes: + @pytest.mark.parametrize(("nodes", "edges", "skipped", "not_skipped"), UNARY_CASES) + def test_hand_built(self, nodes, edges, skipped, not_skipped): + ts = make_ts(nodes, edges, [], 10.0) + kwargs = contains_unary_nodes_kwargs(ts, skip_samples=True) + result = assert_same_result( + _tsdate.contains_unary_nodes, util.contains_unary_nodes, **kwargs + ) + assert result is skipped + kwargs = contains_unary_nodes_kwargs(ts, skip_samples=False) + result = assert_same_result( + _tsdate.contains_unary_nodes, util.contains_unary_nodes, **kwargs + ) + assert result is not_skipped + + def test_all_nodes_masked(self): + nodes = [(1, 0), (0, 1), (0, 2)] + ts = make_ts(nodes, [(0, 10, 1, 0), (0, 10, 2, 1)], [], 10.0) + kwargs = contains_unary_nodes_kwargs(ts, skip_samples=False) + kwargs["nodes_mask"][:] = True + result = assert_same_result( + _tsdate.contains_unary_nodes, util.contains_unary_nodes, **kwargs + ) + assert result is False + + @pytest.mark.parametrize("skip_samples", [True, False]) + @pytest.mark.parametrize("keep", [None, 3, 20]) + def test_simulated(self, sim_ts, keep, skip_samples): + ts = sim_ts + if keep is not None: + ts = ts.simplify(ts.samples()[:keep], keep_unary=True) + kwargs = contains_unary_nodes_kwargs(ts, skip_samples) + assert_same_result( + _tsdate.contains_unary_nodes, util.contains_unary_nodes, **kwargs + ) diff --git a/tests/test_python_c.py b/tests/test_python_c.py index d3d5def1..3a5ed56b 100644 --- a/tests/test_python_c.py +++ b/tests/test_python_c.py @@ -1,16 +1,56 @@ """ -Tests for the low-level _tsdate C module. +Tests for the low-level _tsdate C module: argument handling, and each library error +through each function that reports it. """ +import re + import _tsdate +import msprime +import numpy as np import pytest ERR_GENERIC = -1 ERR_NO_MEMORY = -2 ERR_BAD_PARAM = -3 +ERR_ZERO_DIVISION = -4 +ERR_UNSORTED_QUANTILES = -11 +ERR_UNPHASED_INDIVIDUAL_EDGES = -16 +ERR_BLOCK_OUT_OF_BOUNDS = -17 +ERR_PHASE_OUT_OF_RANGE = -18 +ERR_UNPHASED_LIKELIHOOD_NOT_CONSERVED = -19 +ERR_MUTATION_NODE_NOT_IN_TREE = -20 +ERR_FIXED_NODES_VIOLATE_CONSTRAINT = -21 +ERR_NONPOSITIVE_INTERVALS = -22 +ERR_ZERO_EDGE_SPAN = -24 +ERR_NON_INCREASING_BREAKPOINTS = -25 +ERR_INVALID_QUANTILE_WIDTH = -26 +ERR_INVALID_POSTERIOR = -27 +ERR_TIME_BELOW_FIRST_BREAKPOINT = -28 +ERR_NO_POSTERIORS = -29 +ERR_INVALID_MAX_SHAPE = -30 +ERR_INVALID_MIN_STEP = -31 +ERR_TWIN_EDGE_IN_PHASED_PASS = -34 +ERR_NONPOSITIVE_PENALTY = -35 ALL_ERRORS = [ERR_GENERIC, ERR_NO_MEMORY, ERR_BAD_PARAM] +def raises_library_error(code): + """ + ``pytest.raises`` for the library error ``code`` + """ + return pytest.raises(_tsdate.LibraryError, match=re.escape(_tsdate.strerror(code))) + + +def with_entry(array, index, value): + """ + A copy of ``array`` with entry ``index`` set to ``value`` + """ + array = array.copy() + array[index] = value + return array + + class TestModule: def test_name(self): assert _tsdate.__name__ == "_tsdate" @@ -64,3 +104,1087 @@ def test_unknown_code(self): def test_bad_argument(self): with pytest.raises(TypeError): _tsdate.raise_library_error("x") + + +# Two diploid individuals, with recombination (seven trees) and mutations +TS = msprime.sim_mutations( + msprime.sim_ancestry( + 2, + sequence_length=1e4, + recombination_rate=1e-8, + population_size=1e4, + random_seed=2, + ), + rate=1e-7, + random_seed=2, +) +SAMPLES = np.isin(np.arange(TS.num_nodes), TS.samples()) + + +# Valid keyword arguments of each function, in the order of its parameters + + +def block_singletons_kwargs(): + return dict( + individuals_unphased=np.ones(TS.num_individuals, dtype=bool), + nodes_individual=TS.nodes_individual, + mutations_node=TS.mutations_node, + mutations_position=TS.sites_position[TS.mutations_site], + edges_child=TS.edges_child, + edges_left=TS.edges_left, + edges_right=TS.edges_right, + indexes_insert=TS.indexes_edge_insertion_order, + indexes_remove=TS.indexes_edge_removal_order, + sequence_length=TS.sequence_length, + ) + + +def reallocate_unphased_kwargs(): + # one block of edges 0 and 1, with two mutations, and a mutation in no block + return dict( + edges_likelihood=np.array([[2.0, 5.0], [0.0, 5.0], [1.0, 5.0]]), + mutations_phase=np.array([0.25, 0.5, np.nan]), + mutations_block=np.array([0, 0, -1], dtype=np.int32), + blocks_edges=np.array([[0, 1]], dtype=np.int32), + ) + + +def mutation_frequency_kwargs(): + return dict( + nodes_sample=SAMPLES[:, np.newaxis], + mutations_node=TS.mutations_node, + mutations_position=TS.sites_position[TS.mutations_site], + edges_parent=TS.edges_parent, + edges_child=TS.edges_child, + edges_left=TS.edges_left, + edges_right=TS.edges_right, + indexes_insert=TS.indexes_edge_insertion_order, + indexes_remove=TS.indexes_edge_removal_order, + sequence_length=TS.sequence_length, + ) + + +def split_disjoint_nodes_kwargs(): + return dict( + edges_parent=TS.edges_parent, + edges_child=TS.edges_child, + edges_left=TS.edges_left, + edges_right=TS.edges_right, + nodes_excluded=SAMPLES, + ) + + +def relabel_mutations_node_kwargs(): + return dict( + mutations_node=TS.mutations_node, + mutations_position=TS.sites_position[TS.mutations_site], + nodes_order=np.arange(TS.num_nodes, dtype=np.int32), + edges_parent=TS.edges_parent, + edges_child=TS.edges_child, + edges_left=TS.edges_left, + edges_right=TS.edges_right, + indexes_insert=TS.indexes_edge_insertion_order, + indexes_remove=TS.indexes_edge_removal_order, + ) + + +def constrain_ages_kwargs(): + return dict( + nodes_time=TS.nodes_time, + nodes_fixed=SAMPLES, + edges_parent=TS.edges_parent, + edges_child=TS.edges_child, + epsilon=1e-6, + max_iterations=2, + ) + + +def contains_unary_nodes_kwargs(): + return dict( + nodes_mask=SAMPLES, + edges_parent=TS.edges_parent, + edges_left=TS.edges_left, + edges_right=TS.edges_right, + indexes_insert=TS.indexes_edge_insertion_order, + indexes_remove=TS.indexes_edge_removal_order, + sequence_length=TS.sequence_length, + ) + + +def conditional_coalescent_variance_kwargs(): + return dict(num_tips=5) + + +def count_mutations_kwargs(): + return dict( + nodes_sample=SAMPLES, + mutations_node=TS.mutations_node, + mutations_position=TS.sites_position[TS.mutations_site], + edges_parent=TS.edges_parent, + edges_child=TS.edges_child, + edges_left=TS.edges_left, + edges_right=TS.edges_right, + indexes_insert=TS.indexes_edge_insertion_order, + indexes_remove=TS.indexes_edge_removal_order, + sequence_length=TS.sequence_length, + size_biased=True, + ) + + +def mutational_area_kwargs(): + return dict( + nodes_time=TS.nodes_time, + edges_likelihood=np.ones((TS.num_edges, 2)), + edges_parent=TS.edges_parent, + edges_child=TS.edges_child, + ) + + +def mutational_timescale_kwargs(): + return dict( + nodes_time=TS.nodes_time, + edges_likelihood=np.ones((TS.num_edges, 2)), + nodes_fixed=SAMPLES, + edges_parent=TS.edges_parent, + edges_child=TS.edges_child, + max_intervals=3, + ) + + +def piecewise_scale_point_estimate_kwargs(): + return dict( + point_estimate=np.array([0.0, 0.5, 5.0]), + point_fixed=np.array([True, False, False]), + original_breaks=np.array([0.0, 1.0, 10.0]), + rescaled_breaks=np.array([0.0, 2.0, 20.0]), + ) + + +def piecewise_scale_posterior_kwargs(): + return dict( + posteriors=np.ones((3, 2)), + posteriors_fixed=np.array([False, False, True]), + original_breaks=np.array([0.0, 1.0, 10.0]), + rescaled_breaks=np.array([0.0, 2.0, 20.0]), + quantile_width=0.5, + max_shape=1000.0, + ) + + +def constraints_are_consistent_kwargs(): + constraints = np.zeros((TS.num_nodes, 2)) + constraints[~SAMPLES, 1] = np.inf + return dict( + constraints=constraints, + edges_parent=TS.edges_parent, + edges_child=TS.edges_child, + ) + + +def names(functions): + """ + The names of the functions of a list of (function, make_kwargs), as test ids + """ + return [function.__name__ for function, _ in functions] + + +FUNCTIONS = [ + (_tsdate.block_singletons, block_singletons_kwargs), + (_tsdate.reallocate_unphased, reallocate_unphased_kwargs), + (_tsdate.mutation_frequency, mutation_frequency_kwargs), + (_tsdate.split_disjoint_nodes, split_disjoint_nodes_kwargs), + (_tsdate.relabel_mutations_node, relabel_mutations_node_kwargs), + (_tsdate.constrain_ages, constrain_ages_kwargs), + (_tsdate.contains_unary_nodes, contains_unary_nodes_kwargs), + (_tsdate.conditional_coalescent_variance, conditional_coalescent_variance_kwargs), + (_tsdate.count_mutations, count_mutations_kwargs), + (_tsdate.mutational_area, mutational_area_kwargs), + (_tsdate.mutational_timescale, mutational_timescale_kwargs), + (_tsdate.piecewise_scale_point_estimate, piecewise_scale_point_estimate_kwargs), + (_tsdate.piecewise_scale_posterior, piecewise_scale_posterior_kwargs), + (_tsdate.constraints_are_consistent, constraints_are_consistent_kwargs), +] + + +@pytest.mark.parametrize(("function", "make_kwargs"), FUNCTIONS, ids=names(FUNCTIONS)) +class TestArguments: + """ + The parsing of the arguments of each function: counts, keywords and types + """ + + def test_keywords(self, function, make_kwargs): + function(**make_kwargs()) + + def test_positional(self, function, make_kwargs): + args = list(make_kwargs().values()) + function(*args) + + def test_too_few_arguments(self, function, make_kwargs): + args = list(make_kwargs().values()) + with pytest.raises(TypeError): + function(*args[:-1]) + + def test_too_many_arguments(self, function, make_kwargs): + args = list(make_kwargs().values()) + with pytest.raises(TypeError): + function(*args, args[-1]) + + def test_unknown_keyword(self, function, make_kwargs): + kwargs = make_kwargs() + with pytest.raises(TypeError): + function(**kwargs, not_an_argument=1) + + def test_bad_dtype(self, function, make_kwargs): + # float arrays as complex numbers, the others as floats: neither casts safely + for name, value in make_kwargs().items(): + if not isinstance(value, np.ndarray): + continue + kwargs = make_kwargs() + if value.dtype == np.float64: + kwargs[name] = value.astype(np.complex128) + else: + kwargs[name] = value.astype(np.float64) + with pytest.raises(TypeError): + function(**kwargs) + + def test_bad_dimension(self, function, make_kwargs): + for name, value in make_kwargs().items(): + if not isinstance(value, np.ndarray): + continue + kwargs = make_kwargs() + if value.ndim == 2: + kwargs[name] = value.reshape(-1) + else: + kwargs[name] = value.reshape(1, -1) + with pytest.raises(ValueError): + function(**kwargs) + + def test_not_an_array(self, function, make_kwargs): + for name, value in make_kwargs().items(): + if not isinstance(value, np.ndarray): + continue + kwargs = make_kwargs() + kwargs[name] = "not an array" + with pytest.raises((TypeError, ValueError)): + function(**kwargs) + + def test_not_a_number(self, function, make_kwargs): + # flags are not included: they take any object, as its truth value + for name, value in make_kwargs().items(): + if isinstance(value, (np.ndarray, bool)): + continue + kwargs = make_kwargs() + kwargs[name] = "not a number" + with pytest.raises(TypeError): + function(**kwargs) + + +SWEEPS_WITH_SEQUENCE_LENGTH = [ + (_tsdate.block_singletons, block_singletons_kwargs), + (_tsdate.mutation_frequency, mutation_frequency_kwargs), + (_tsdate.contains_unary_nodes, contains_unary_nodes_kwargs), + (_tsdate.count_mutations, count_mutations_kwargs), +] +SWEEPS = SWEEPS_WITH_SEQUENCE_LENGTH + [ + (_tsdate.relabel_mutations_node, relabel_mutations_node_kwargs), +] + + +class TestEdgeSweep: + """ + The library's errors for edges that a sweep over the trees cannot traverse, through + each function that sweeps + """ + + @pytest.mark.parametrize(("function", "make_kwargs"), SWEEPS, ids=names(SWEEPS)) + def test_nan_interval(self, function, make_kwargs): + kwargs = make_kwargs() + kwargs["edges_right"] = with_entry(TS.edges_right, -1, np.nan) + with pytest.raises(_tsdate.LibraryError, match="Edge interval"): + function(**kwargs) + + @pytest.mark.parametrize(("function", "make_kwargs"), SWEEPS, ids=names(SWEEPS)) + def test_empty_interval(self, function, make_kwargs): + kwargs = make_kwargs() + kwargs["edges_left"] = with_entry(TS.edges_left, -1, TS.edges_right[-1]) + with pytest.raises(_tsdate.LibraryError, match="Edge interval"): + function(**kwargs) + + @pytest.mark.parametrize( + ("function", "make_kwargs"), + SWEEPS_WITH_SEQUENCE_LENGTH, + ids=names(SWEEPS_WITH_SEQUENCE_LENGTH), + ) + def test_interval_past_end(self, function, make_kwargs): + kwargs = make_kwargs() + kwargs["edges_right"] = with_entry(TS.edges_right, -1, 2 * TS.sequence_length) + with pytest.raises(_tsdate.LibraryError, match="Edge interval"): + function(**kwargs) + + @pytest.mark.parametrize(("function", "make_kwargs"), SWEEPS, ids=names(SWEEPS)) + def test_index_out_of_bounds(self, function, make_kwargs): + kwargs = make_kwargs() + insert = TS.indexes_edge_insertion_order + kwargs["indexes_insert"] = with_entry(insert, -1, TS.num_edges) + with pytest.raises(_tsdate.LibraryError, match="Edge id out of bounds"): + function(**kwargs) + + @pytest.mark.parametrize(("function", "make_kwargs"), SWEEPS, ids=names(SWEEPS)) + def test_unsorted_index(self, function, make_kwargs): + kwargs = make_kwargs() + kwargs["indexes_remove"] = TS.indexes_edge_removal_order[::-1].copy() + with pytest.raises(_tsdate.LibraryError, match="Edge indexes must list"): + function(**kwargs) + + +class TestBlockSingletons: + def test_mismatched_edge_arrays(self): + for name in [ + "edges_left", + "edges_right", + "indexes_insert", + "indexes_remove", + ]: + kwargs = block_singletons_kwargs() + kwargs[name] = kwargs[name][:-1] + with pytest.raises(ValueError, match="Edge arrays must have the same size"): + _tsdate.block_singletons(**kwargs) + + def test_mismatched_mutation_arrays(self): + kwargs = block_singletons_kwargs() + kwargs["mutations_position"] = kwargs["mutations_position"][:-1] + with pytest.raises(ValueError, match="Mutation arrays must have the same size"): + _tsdate.block_singletons(**kwargs) + + def test_mutation_node_out_of_bounds(self): + kwargs = block_singletons_kwargs() + kwargs["mutations_node"] = with_entry(TS.mutations_node, -1, TS.num_nodes) + with pytest.raises(_tsdate.LibraryError, match="Node id out of bounds"): + _tsdate.block_singletons(**kwargs) + + def test_individual_out_of_bounds(self): + kwargs = block_singletons_kwargs() + individuals = with_entry(TS.nodes_individual, -1, TS.num_individuals) + kwargs["nodes_individual"] = individuals + with pytest.raises(_tsdate.LibraryError, match="Individual id out of bounds"): + _tsdate.block_singletons(**kwargs) + + def test_individual_with_three_nodes(self): + # nodes 0 and 1 belong to individual 0: give it node 2 as well + assert TS.nodes_individual[:3].tolist() == [0, 0, 1] + kwargs = block_singletons_kwargs() + kwargs["nodes_individual"] = with_entry(TS.nodes_individual, 2, 0) + with raises_library_error(ERR_UNPHASED_INDIVIDUAL_EDGES): + _tsdate.block_singletons(**kwargs) + + +class TestReallocateUnphased: + def test_result(self): + # the two mutations give edge 0 their phases and edge 1 the remainders + kwargs = reallocate_unphased_kwargs() + result = _tsdate.reallocate_unphased(**kwargs) + assert result.tolist() == [[0.75, 5.0], [1.25, 5.0], [1.0, 5.0]] + + def test_leaves_input(self): + kwargs = reallocate_unphased_kwargs() + _tsdate.reallocate_unphased(**kwargs) + assert kwargs["edges_likelihood"].tolist() == [[2, 5], [0, 5], [1, 5]] + + def test_mismatched_mutation_arrays(self): + kwargs = reallocate_unphased_kwargs() + kwargs["mutations_block"] = kwargs["mutations_block"][:-1] + with pytest.raises(ValueError, match="Mutation arrays must have the same size"): + _tsdate.reallocate_unphased(**kwargs) + + def test_three_columns(self): + for name in ["edges_likelihood", "blocks_edges"]: + kwargs = reallocate_unphased_kwargs() + value = kwargs[name] + kwargs[name] = np.hstack((value, value[:, :1])) + with pytest.raises(ValueError, match="must have two columns"): + _tsdate.reallocate_unphased(**kwargs) + + def test_block_out_of_bounds(self): + kwargs = reallocate_unphased_kwargs() + kwargs["mutations_block"] = np.array([0, 1, -1], dtype=np.int32) + with raises_library_error(ERR_BLOCK_OUT_OF_BOUNDS): + _tsdate.reallocate_unphased(**kwargs) + + def test_edge_of_block_out_of_bounds(self): + kwargs = reallocate_unphased_kwargs() + kwargs["blocks_edges"] = np.array([[0, 3]], dtype=np.int32) + with raises_library_error(ERR_BLOCK_OUT_OF_BOUNDS): + _tsdate.reallocate_unphased(**kwargs) + + def test_phase_out_of_range(self): + kwargs = reallocate_unphased_kwargs() + kwargs["mutations_phase"] = np.array([0.25, 1.5, np.nan]) + with raises_library_error(ERR_PHASE_OUT_OF_RANGE): + _tsdate.reallocate_unphased(**kwargs) + + def test_likelihood_not_conserved(self): + # a NaN phase is skipped, so one mutation's likelihood is not reallocated + kwargs = reallocate_unphased_kwargs() + kwargs["mutations_phase"] = np.array([0.25, np.nan, np.nan]) + with raises_library_error(ERR_UNPHASED_LIKELIHOOD_NOT_CONSERVED): + _tsdate.reallocate_unphased(**kwargs) + + +class TestMutationFrequency: + def test_mismatched_edge_arrays(self): + for name in [ + "edges_child", + "edges_left", + "edges_right", + "indexes_insert", + "indexes_remove", + ]: + kwargs = mutation_frequency_kwargs() + kwargs[name] = kwargs[name][:-1] + with pytest.raises(ValueError, match="Edge arrays must have the same size"): + _tsdate.mutation_frequency(**kwargs) + + def test_mismatched_mutation_arrays(self): + kwargs = mutation_frequency_kwargs() + kwargs["mutations_position"] = kwargs["mutations_position"][:-1] + with pytest.raises(ValueError, match="Mutation arrays must have the same size"): + _tsdate.mutation_frequency(**kwargs) + + @pytest.mark.parametrize("value", [-1, 2**30]) + def test_parent_out_of_bounds(self, value): + kwargs = mutation_frequency_kwargs() + kwargs["edges_parent"] = with_entry(TS.edges_parent, -1, value) + with pytest.raises(_tsdate.LibraryError, match="Node id out of bounds"): + _tsdate.mutation_frequency(**kwargs) + + def test_mutation_node_out_of_bounds(self): + kwargs = mutation_frequency_kwargs() + kwargs["mutations_node"] = with_entry(TS.mutations_node, -1, TS.num_nodes) + with pytest.raises(_tsdate.LibraryError, match="Node id out of bounds"): + _tsdate.mutation_frequency(**kwargs) + + def test_cycle(self): + # an edge from node 0 to node 1 and one back, over the whole sequence + kwargs = mutation_frequency_kwargs() + kwargs["edges_parent"] = np.array([1, 0], dtype=np.int32) + kwargs["edges_child"] = np.array([0, 1], dtype=np.int32) + kwargs["edges_left"] = np.array([0.0, 0.0]) + kwargs["edges_right"] = np.array([TS.sequence_length, TS.sequence_length]) + kwargs["indexes_insert"] = np.array([0, 1], dtype=np.int32) + kwargs["indexes_remove"] = np.array([0, 1], dtype=np.int32) + with pytest.raises(_tsdate.LibraryError, match="Edges form a cycle"): + _tsdate.mutation_frequency(**kwargs) + + +class TestSplitDisjointNodes: + def test_mismatched_edge_arrays(self): + for name in ["edges_child", "edges_left", "edges_right"]: + kwargs = split_disjoint_nodes_kwargs() + kwargs[name] = kwargs[name][:-1] + with pytest.raises(ValueError, match="Edge arrays must have the same size"): + _tsdate.split_disjoint_nodes(**kwargs) + + def test_parent_out_of_bounds(self): + kwargs = split_disjoint_nodes_kwargs() + kwargs["edges_parent"] = with_entry(TS.edges_parent, -1, TS.num_nodes) + with pytest.raises(_tsdate.LibraryError, match="Node id out of bounds"): + _tsdate.split_disjoint_nodes(**kwargs) + + +class TestRelabelMutationsNode: + def test_mismatched_edge_arrays(self): + for name in [ + "edges_child", + "edges_left", + "edges_right", + "indexes_insert", + "indexes_remove", + ]: + kwargs = relabel_mutations_node_kwargs() + kwargs[name] = kwargs[name][:-1] + with pytest.raises(ValueError, match="Edge arrays must have the same size"): + _tsdate.relabel_mutations_node(**kwargs) + + def test_mismatched_mutation_arrays(self): + kwargs = relabel_mutations_node_kwargs() + kwargs["mutations_position"] = kwargs["mutations_position"][:-1] + with pytest.raises(ValueError, match="Mutation arrays must have the same size"): + _tsdate.relabel_mutations_node(**kwargs) + + @pytest.mark.parametrize("value", [-1, 2**30]) + def test_parent_out_of_bounds(self, value): + kwargs = relabel_mutations_node_kwargs() + kwargs["edges_parent"] = with_entry(TS.edges_parent, -1, value) + with pytest.raises(_tsdate.LibraryError, match="Node id out of bounds"): + _tsdate.relabel_mutations_node(**kwargs) + + def test_mutation_node_out_of_bounds(self): + kwargs = relabel_mutations_node_kwargs() + kwargs["mutations_node"] = with_entry(TS.mutations_node, -1, TS.num_nodes) + with pytest.raises(_tsdate.LibraryError, match="Node id out of bounds"): + _tsdate.relabel_mutations_node(**kwargs) + + def test_nodes_order_out_of_bounds(self): + kwargs = relabel_mutations_node_kwargs() + kwargs["nodes_order"] = with_entry(kwargs["nodes_order"], -1, TS.num_nodes) + with pytest.raises(_tsdate.LibraryError, match="Node id out of bounds"): + _tsdate.relabel_mutations_node(**kwargs) + + def test_mutation_node_not_in_tree(self): + position = TS.sites_position[TS.mutations_site[0]] + absent = set(range(TS.num_nodes)) - set(TS.at(position).nodes()) + kwargs = relabel_mutations_node_kwargs() + kwargs["mutations_node"] = with_entry(TS.mutations_node, 0, min(absent)) + with raises_library_error(ERR_MUTATION_NODE_NOT_IN_TREE): + _tsdate.relabel_mutations_node(**kwargs) + + +class TestConstrainAges: + def test_mismatched_node_arrays(self): + kwargs = constrain_ages_kwargs() + kwargs["nodes_fixed"] = kwargs["nodes_fixed"][:-1] + with pytest.raises(ValueError, match="Node arrays must have the same size"): + _tsdate.constrain_ages(**kwargs) + + def test_mismatched_edge_arrays(self): + kwargs = constrain_ages_kwargs() + kwargs["edges_child"] = kwargs["edges_child"][:-1] + with pytest.raises(ValueError, match="Edge arrays must have the same size"): + _tsdate.constrain_ages(**kwargs) + + @pytest.mark.parametrize("value", [-1, 2**30]) + def test_child_out_of_bounds(self, value): + kwargs = constrain_ages_kwargs() + kwargs["edges_child"] = with_entry(TS.edges_child, -1, value) + with pytest.raises(_tsdate.LibraryError, match="Node id out of bounds"): + _tsdate.constrain_ages(**kwargs) + + def test_fixed_nodes_violate_constraint(self): + # every node fixed, at an age that makes every parent younger than its child + kwargs = constrain_ages_kwargs() + kwargs["nodes_fixed"] = np.ones(TS.num_nodes, dtype=bool) + kwargs["nodes_time"] = TS.nodes_time.max() - TS.nodes_time + with raises_library_error(ERR_FIXED_NODES_VIOLATE_CONSTRAINT): + _tsdate.constrain_ages(**kwargs) + + +class TestContainsUnaryNodes: + def test_mismatched_edge_arrays(self): + for name in ["edges_left", "edges_right", "indexes_insert", "indexes_remove"]: + kwargs = contains_unary_nodes_kwargs() + kwargs[name] = kwargs[name][:-1] + with pytest.raises(ValueError, match="Edge arrays must have the same size"): + _tsdate.contains_unary_nodes(**kwargs) + + @pytest.mark.parametrize("value", [-1, 2**30]) + def test_parent_out_of_bounds(self, value): + kwargs = contains_unary_nodes_kwargs() + kwargs["edges_parent"] = with_entry(TS.edges_parent, -1, value) + with pytest.raises(_tsdate.LibraryError, match="Node id out of bounds"): + _tsdate.contains_unary_nodes(**kwargs) + + +class TestConditionalCoalescentVariance: + def test_one_tip(self): + # the result is unused by tsdate + assert _tsdate.conditional_coalescent_variance(1).tolist() == [0.0, 0.0] + + def test_no_tips(self): + with pytest.raises(_tsdate.LibraryError, match="Too few tips"): + _tsdate.conditional_coalescent_variance(0) + + def test_negative_tips(self): + with pytest.raises(ValueError, match="non-negative"): + _tsdate.conditional_coalescent_variance(-1) + + +class TestCountMutations: + def test_not_size_biased(self): + kwargs = count_mutations_kwargs() + kwargs["size_biased"] = False + edges_stats, _ = _tsdate.count_mutations(**kwargs) + assert edges_stats.shape == (TS.num_edges, 2) + + def test_mismatched_edge_arrays(self): + for name in [ + "edges_child", + "edges_left", + "edges_right", + "indexes_insert", + "indexes_remove", + ]: + kwargs = count_mutations_kwargs() + kwargs[name] = kwargs[name][:-1] + with pytest.raises(ValueError, match="Edge arrays must have the same size"): + _tsdate.count_mutations(**kwargs) + + def test_mismatched_mutation_arrays(self): + kwargs = count_mutations_kwargs() + kwargs["mutations_position"] = kwargs["mutations_position"][:-1] + with pytest.raises(ValueError, match="Mutation arrays must have the same size"): + _tsdate.count_mutations(**kwargs) + + @pytest.mark.parametrize("value", [-1, 2**30]) + def test_parent_out_of_bounds(self, value): + kwargs = count_mutations_kwargs() + kwargs["edges_parent"] = with_entry(TS.edges_parent, -1, value) + with pytest.raises(_tsdate.LibraryError, match="Node id out of bounds"): + _tsdate.count_mutations(**kwargs) + + def test_mutation_node_out_of_bounds(self): + kwargs = count_mutations_kwargs() + kwargs["mutations_node"] = with_entry(TS.mutations_node, -1, TS.num_nodes) + with pytest.raises(_tsdate.LibraryError, match="Node id out of bounds"): + _tsdate.count_mutations(**kwargs) + + def test_cycle(self): + # an edge from node 0 to node 1 and one back, over the whole sequence + kwargs = count_mutations_kwargs() + kwargs["edges_parent"] = np.array([1, 0], dtype=np.int32) + kwargs["edges_child"] = np.array([0, 1], dtype=np.int32) + kwargs["edges_left"] = np.array([0.0, 0.0]) + kwargs["edges_right"] = np.array([TS.sequence_length, TS.sequence_length]) + kwargs["indexes_insert"] = np.array([0, 1], dtype=np.int32) + kwargs["indexes_remove"] = np.array([0, 1], dtype=np.int32) + with pytest.raises(_tsdate.LibraryError, match="Edges form a cycle"): + _tsdate.count_mutations(**kwargs) + + +class TestMutationalArea: + def test_mismatched_edge_arrays(self): + kwargs = mutational_area_kwargs() + kwargs["edges_child"] = kwargs["edges_child"][:-1] + with pytest.raises(ValueError, match="Edge arrays must have the same size"): + _tsdate.mutational_area(**kwargs) + + def test_mismatched_likelihoods(self): + kwargs = mutational_area_kwargs() + kwargs["edges_likelihood"] = kwargs["edges_likelihood"][:-1] + with pytest.raises(ValueError, match="one row of two columns per edge"): + _tsdate.mutational_area(**kwargs) + + def test_three_columns(self): + kwargs = mutational_area_kwargs() + kwargs["edges_likelihood"] = np.ones((TS.num_edges, 3)) + with pytest.raises(ValueError, match="one row of two columns per edge"): + _tsdate.mutational_area(**kwargs) + + def test_child_out_of_bounds(self): + kwargs = mutational_area_kwargs() + kwargs["edges_child"] = with_entry(TS.edges_child, -1, TS.num_nodes) + with pytest.raises(_tsdate.LibraryError, match="Node id out of bounds"): + _tsdate.mutational_area(**kwargs) + + +class TestMutationalTimescale: + def test_mismatched_edge_arrays(self): + kwargs = mutational_timescale_kwargs() + kwargs["edges_child"] = kwargs["edges_child"][:-1] + with pytest.raises(ValueError, match="Edge arrays must have the same size"): + _tsdate.mutational_timescale(**kwargs) + + def test_mismatched_likelihoods(self): + kwargs = mutational_timescale_kwargs() + kwargs["edges_likelihood"] = kwargs["edges_likelihood"][:-1] + with pytest.raises(ValueError, match="one row of two columns per edge"): + _tsdate.mutational_timescale(**kwargs) + + def test_three_columns(self): + kwargs = mutational_timescale_kwargs() + kwargs["edges_likelihood"] = np.ones((TS.num_edges, 3)) + with pytest.raises(ValueError, match="one row of two columns per edge"): + _tsdate.mutational_timescale(**kwargs) + + def test_mismatched_node_arrays(self): + kwargs = mutational_timescale_kwargs() + kwargs["nodes_fixed"] = kwargs["nodes_fixed"][:-1] + with pytest.raises(ValueError, match="nodes_fixed and nodes_time"): + _tsdate.mutational_timescale(**kwargs) + + def test_child_out_of_bounds(self): + kwargs = mutational_timescale_kwargs() + kwargs["edges_child"] = with_entry(TS.edges_child, -1, TS.num_nodes) + with pytest.raises(_tsdate.LibraryError, match="Node id out of bounds"): + _tsdate.mutational_timescale(**kwargs) + + def test_no_intervals(self): + kwargs = mutational_timescale_kwargs() + kwargs["max_intervals"] = 0 + with raises_library_error(ERR_NONPOSITIVE_INTERVALS): + _tsdate.mutational_timescale(**kwargs) + + def test_zero_edge_span(self): + kwargs = mutational_timescale_kwargs() + kwargs["edges_likelihood"] = np.zeros((TS.num_edges, 2)) + with raises_library_error(ERR_ZERO_EDGE_SPAN): + _tsdate.mutational_timescale(**kwargs) + + +class TestPiecewiseScalePointEstimate: + def test_mismatched_points(self): + kwargs = piecewise_scale_point_estimate_kwargs() + kwargs["point_fixed"] = kwargs["point_fixed"][:-1] + with pytest.raises(ValueError, match="point_fixed and point_estimate"): + _tsdate.piecewise_scale_point_estimate(**kwargs) + + def test_mismatched_breakpoints(self): + kwargs = piecewise_scale_point_estimate_kwargs() + kwargs["rescaled_breaks"] = kwargs["rescaled_breaks"][:-1] + with pytest.raises(ValueError, match="Breakpoints must be of the same size"): + _tsdate.piecewise_scale_point_estimate(**kwargs) + + def test_no_breakpoints(self): + kwargs = piecewise_scale_point_estimate_kwargs() + kwargs["original_breaks"] = np.array([]) + kwargs["rescaled_breaks"] = np.array([]) + with pytest.raises(_tsdate.LibraryError, match="No breakpoints"): + _tsdate.piecewise_scale_point_estimate(**kwargs) + + def test_decreasing_breakpoints(self): + kwargs = piecewise_scale_point_estimate_kwargs() + kwargs["original_breaks"] = np.array([10.0, 1.0, 0.0]) + with raises_library_error(ERR_NON_INCREASING_BREAKPOINTS): + _tsdate.piecewise_scale_point_estimate(**kwargs) + + +class TestPiecewiseScalePosterior: + def test_mismatched_posteriors(self): + kwargs = piecewise_scale_posterior_kwargs() + kwargs["posteriors_fixed"] = kwargs["posteriors_fixed"][:-1] + with pytest.raises(ValueError, match="one row per fixed flag"): + _tsdate.piecewise_scale_posterior(**kwargs) + + def test_three_columns(self): + kwargs = piecewise_scale_posterior_kwargs() + kwargs["posteriors"] = np.ones((3, 3)) + with pytest.raises(ValueError, match="must have two columns"): + _tsdate.piecewise_scale_posterior(**kwargs) + + def test_mismatched_breakpoints(self): + kwargs = piecewise_scale_posterior_kwargs() + kwargs["rescaled_breaks"] = kwargs["rescaled_breaks"][:-1] + with pytest.raises(ValueError, match="Breakpoints must be of the same size"): + _tsdate.piecewise_scale_posterior(**kwargs) + + def test_no_breakpoints(self): + kwargs = piecewise_scale_posterior_kwargs() + kwargs["original_breaks"] = np.array([]) + kwargs["rescaled_breaks"] = np.array([]) + with pytest.raises(_tsdate.LibraryError, match="No breakpoints"): + _tsdate.piecewise_scale_posterior(**kwargs) + + def test_decreasing_breakpoints(self): + kwargs = piecewise_scale_posterior_kwargs() + kwargs["rescaled_breaks"] = np.array([20.0, 2.0, 0.0]) + with raises_library_error(ERR_NON_INCREASING_BREAKPOINTS): + _tsdate.piecewise_scale_posterior(**kwargs) + + def test_quantile_width(self): + kwargs = piecewise_scale_posterior_kwargs() + kwargs["quantile_width"] = 1.0 + with raises_library_error(ERR_INVALID_QUANTILE_WIDTH): + _tsdate.piecewise_scale_posterior(**kwargs) + + def test_invalid_posterior(self): + kwargs = piecewise_scale_posterior_kwargs() + kwargs["posteriors"] = np.array([[1.0, 0.0], [1.0, 1.0], [1.0, 1.0]]) + with raises_library_error(ERR_INVALID_POSTERIOR): + _tsdate.piecewise_scale_posterior(**kwargs) + + def test_no_posteriors(self): + kwargs = piecewise_scale_posterior_kwargs() + kwargs["posteriors"] = np.zeros((0, 2)) + kwargs["posteriors_fixed"] = np.zeros(0, dtype=bool) + with raises_library_error(ERR_NO_POSTERIORS): + _tsdate.piecewise_scale_posterior(**kwargs) + + def test_time_below_first_breakpoint(self): + kwargs = piecewise_scale_posterior_kwargs() + kwargs["original_breaks"] = np.array([50.0, 51.0, 60.0]) + with raises_library_error(ERR_TIME_BELOW_FIRST_BREAKPOINT): + _tsdate.piecewise_scale_posterior(**kwargs) + + def test_zero_quantile(self): + kwargs = piecewise_scale_posterior_kwargs() + kwargs["posteriors"] = np.array([[1.0, np.inf], [1.0, 1.0], [1.0, 1.0]]) + with raises_library_error(ERR_ZERO_DIVISION): + _tsdate.piecewise_scale_posterior(**kwargs) + + def test_unsorted_quantiles(self): + kwargs = piecewise_scale_posterior_kwargs() + kwargs["posteriors"] = np.array([[np.inf, 1.0], [1.0, 1.0], [1.0, 1.0]]) + with raises_library_error(ERR_UNSORTED_QUANTILES): + _tsdate.piecewise_scale_posterior(**kwargs) + + +class TestConstraintsAreConsistent: + def test_mismatched_edge_arrays(self): + kwargs = constraints_are_consistent_kwargs() + kwargs["edges_child"] = kwargs["edges_child"][:-1] + with pytest.raises(ValueError, match="Edge arrays must have the same size"): + _tsdate.constraints_are_consistent(**kwargs) + + def test_three_columns(self): + kwargs = constraints_are_consistent_kwargs() + kwargs["constraints"] = np.zeros((TS.num_nodes, 3)) + with pytest.raises(ValueError, match="constraints must have two columns"): + _tsdate.constraints_are_consistent(**kwargs) + + def test_parent_out_of_bounds(self): + kwargs = constraints_are_consistent_kwargs() + kwargs["edges_parent"] = with_entry(TS.edges_parent, -1, -1) + with pytest.raises(_tsdate.LibraryError, match="Node id out of bounds"): + _tsdate.constraints_are_consistent(**kwargs) + + +def ep_arrays(**replace): + """ + Arguments of ``ExpectationPropagation``: two samples (nodes 0 and 1) below a free + root (node 2), and a block whose nodes are both the root + """ + args = { + "constraints": np.array([[0.0, 0.0], [0.0, 0.0], [0.0, np.inf]]), + "edges_parent": np.array([2, 2], dtype=np.int32), + "edges_child": np.array([0, 1], dtype=np.int32), + "edges_likelihood": np.array([[1.0, 1.0], [2.0, 1.0]]), + "blocks_left": np.array([2], dtype=np.int32), + "blocks_right": np.array([2], dtype=np.int32), + "blocks_likelihood": np.array([[1.0, 1.0]]), + } + args.update(replace) + return args + + +def new_ep(**replace): + """ + An ``ExpectationPropagation`` with the arguments of ``ep_arrays`` + """ + return _tsdate.ExpectationPropagation(**ep_arrays(**replace)) + + +EDGES = np.array([0, 1], dtype=np.int32) +BLOCKS = np.array([0], dtype=np.int32) + + +class TestExpectationPropagationInit: + def test_initial_state(self): + ep = new_ep() + assert ep.posterior.tolist() == [[0.0, 0.0]] * 3 + assert ep.edges_lognorm.tolist() == [0.0, 0.0] + assert ep.blocks_lognorm.tolist() == [0.0] + + def test_positional_arguments(self): + ep = _tsdate.ExpectationPropagation(*ep_arrays().values()) + assert ep.posterior.shape == (3, 2) + + def test_no_blocks(self): + empty = np.zeros(0, dtype=np.int32) + ep = new_ep( + blocks_left=empty, blocks_right=empty, blocks_likelihood=np.zeros((0, 2)) + ) + assert ep.blocks_lognorm.size == 0 + + @pytest.mark.parametrize("num_args", [0, 6, 8]) + def test_wrong_number_of_arguments(self, num_args): + args = list(ep_arrays().values()) + [None] + with pytest.raises(TypeError): + _tsdate.ExpectationPropagation(*args[:num_args]) + + @pytest.mark.parametrize("name", list(ep_arrays())) + def test_bad_dtype(self, name): + value = ep_arrays()[name] + bad = value.astype(np.float64 if value.dtype == np.int32 else np.complex128) + with pytest.raises(TypeError): + new_ep(**{name: bad}) + + @pytest.mark.parametrize("name", list(ep_arrays())) + def test_bad_dimension(self, name): + value = ep_arrays()[name] + bad = value.reshape(-1) if value.ndim == 2 else value.reshape(1, -1) + with pytest.raises(ValueError): + new_ep(**{name: bad}) + + @pytest.mark.parametrize( + "name", ["constraints", "edges_likelihood", "blocks_likelihood"] + ) + def test_three_columns(self, name): + value = ep_arrays()[name] + bad = np.hstack((value, value[:, :1])) + with pytest.raises(ValueError, match="two columns"): + new_ep(**{name: bad}) + + @pytest.mark.parametrize( + ("name", "match"), + [ + ("edges_child", "Edge arrays"), + ("edges_likelihood", "Edge arrays"), + ("blocks_right", "Block arrays"), + ("blocks_likelihood", "Block arrays"), + ], + ) + def test_mismatched_lengths(self, name, match): + bad = ep_arrays()[name][:-1] + with pytest.raises(ValueError, match=match): + new_ep(**{name: bad}) + + @pytest.mark.parametrize( + "name", ["edges_parent", "edges_child", "blocks_left", "blocks_right"] + ) + @pytest.mark.parametrize("value", [-1, 3]) + def test_node_out_of_bounds(self, name, value): + with pytest.raises(_tsdate.LibraryError, match="Node id out of bounds"): + new_ep(**{name: with_entry(ep_arrays()[name], -1, value)}) + + def test_failed_init_leaves_no_state(self): + ep = new_ep() + with pytest.raises(_tsdate.LibraryError): + ep.__init__(**ep_arrays(edges_parent=np.array([2, 9], dtype=np.int32))) + with pytest.raises(SystemError, match="not initialised"): + ep.rescale_factors() + + def test_uninitialised(self): + ep = _tsdate.ExpectationPropagation.__new__(_tsdate.ExpectationPropagation) + for method in (ep.rescale_factors, ep.assemble_factors): + with pytest.raises(SystemError, match="not initialised"): + method() + for name in ("posterior", "edges_lognorm", "blocks_lognorm"): + with pytest.raises(SystemError, match="not initialised"): + getattr(ep, name) + with pytest.raises(SystemError, match="not initialised"): + ep.propagate_likelihood(EDGES, False, 1000.0, 0.1) + with pytest.raises(SystemError, match="not initialised"): + ep.propagate_prior(np.ones(3, dtype=bool), 1000.0, 10, 1e-8) + with pytest.raises(SystemError, match="not initialised"): + ep.propagate_mutations(EDGES, False) + + def test_properties_are_read_only_copies(self): + ep = new_ep() + posterior = ep.posterior + posterior[:] = 1.0 + assert ep.posterior.tolist() == [[0.0, 0.0]] * 3 + with pytest.raises(AttributeError): + ep.posterior = posterior + + def test_inputs_are_copied(self): + arrays = ep_arrays() + ep = _tsdate.ExpectationPropagation(**arrays) + arrays["edges_parent"][:] = 99 + ep.propagate_likelihood(EDGES, False, 1000.0, 0.1) + assert np.all(np.isfinite(ep.posterior[2])) + + +class TestExpectationPropagationMethods: + def test_iteration(self): + ep = new_ep() + ep.propagate_likelihood( + order=EDGES, unphased=False, max_shape=1000.0, min_step=0.1 + ) + ep.propagate_likelihood( + order=BLOCKS, unphased=True, max_shape=1000.0, min_step=0.1 + ) + ep.rescale_factors() + assert np.all(ep.posterior[2] > 0) + assert np.all(np.isfinite(ep.edges_lognorm)) + np.testing.assert_allclose(ep.assemble_factors(), ep.posterior) + + def test_propagate_prior(self): + ep = new_ep() + ep.propagate_likelihood(EDGES, False, 1000.0, 0.1) + free = np.array([False, False, True]) + ep.propagate_prior(free=free, max_shape=1000.0, em_maxitt=10, em_reltol=1e-8) + assert np.all(ep.posterior[2] > 0) + + def test_propagate_mutations(self): + ep = new_ep() + ep.propagate_likelihood(EDGES, False, 1000.0, 0.1) + edges = np.array([0, -1, 1], dtype=np.int32) + posterior, phase = ep.propagate_mutations(mutations_edge=edges, unphased=False) + assert posterior.shape == (3, 2) + assert np.all(np.isnan(posterior[1])) + assert phase.tolist()[1] == 1.0 + assert np.all(np.isfinite(posterior[[0, 2]])) + + @pytest.mark.parametrize( + "method", ["propagate_likelihood", "propagate_prior", "propagate_mutations"] + ) + def test_wrong_number_of_arguments(self, method): + with pytest.raises(TypeError): + getattr(new_ep(), method)(EDGES) + + @pytest.mark.parametrize("method", ["rescale_factors", "assemble_factors"]) + def test_no_arguments(self, method): + with pytest.raises(TypeError): + getattr(new_ep(), method)(1) + + def test_bad_arrays(self): + ep = new_ep() + with pytest.raises(TypeError): + ep.propagate_likelihood(EDGES.astype(np.float64), False, 1000.0, 0.1) + with pytest.raises(ValueError): + ep.propagate_likelihood(EDGES.reshape(1, -1), False, 1000.0, 0.1) + with pytest.raises(TypeError): + ep.propagate_prior(np.ones(3), 1000.0, 10, 1e-8) + with pytest.raises(ValueError, match="one entry per node"): + ep.propagate_prior(np.ones(2, dtype=bool), 1000.0, 10, 1e-8) + with pytest.raises(TypeError): + ep.propagate_mutations(EDGES.astype(np.float64), False) + with pytest.raises(ValueError): + ep.propagate_mutations(EDGES.reshape(1, -1), False) + + @pytest.mark.parametrize( + ("order", "unphased", "match"), + [ + ([2], False, "Edge id out of bounds"), + ([-1], False, "Edge id out of bounds"), + ([1], True, "Block id"), + ], + ) + def test_order_out_of_bounds(self, order, unphased, match): + order = np.array(order, dtype=np.int32) + with pytest.raises(_tsdate.LibraryError, match=match): + new_ep().propagate_likelihood(order, unphased, 1000.0, 0.1) + + @pytest.mark.parametrize( + ("edges", "unphased", "match"), + [ + ([2], False, "Edge id out of bounds"), + ([-2], False, "Edge id out of bounds"), + ([1], True, "Block id"), + ], + ) + def test_mutations_edge_out_of_bounds(self, edges, unphased, match): + edges = np.array(edges, dtype=np.int32) + with pytest.raises(_tsdate.LibraryError, match=match): + new_ep().propagate_mutations(edges, unphased) + + def test_likelihood_max_shape(self): + with raises_library_error(ERR_INVALID_MAX_SHAPE): + new_ep().propagate_likelihood(EDGES, False, 0.5, 0.1) + + def test_likelihood_min_step(self): + with raises_library_error(ERR_INVALID_MIN_STEP): + new_ep().propagate_likelihood(EDGES, False, 1000.0, 1.0) + + def test_prior_max_shape(self): + with raises_library_error(ERR_INVALID_MAX_SHAPE): + new_ep().propagate_prior(np.ones(3, dtype=bool), 0.5, 10, 1e-8) + + def test_twin_edge_in_phased_pass(self): + ep = new_ep(edges_child=np.array([0, 2], dtype=np.int32)) + with raises_library_error(ERR_TWIN_EDGE_IN_PHASED_PASS): + ep.propagate_likelihood(np.array([1], dtype=np.int32), False, 1000.0, 0.1) + + def test_nonpositive_penalty(self): + # the fixed samples have cavities of zero rate + with raises_library_error(ERR_NONPOSITIVE_PENALTY): + new_ep().propagate_prior(np.ones(3, dtype=bool), 1000.0, 10, 1e-8) + + def test_zero_division(self): + # a huge mutational target, with a fixed node of an unphased block + ep = new_ep( + constraints=np.array([[0.0, 0.0], [5.0, 5.0], [0.0, np.inf]]), + blocks_right=np.array([1], dtype=np.int32), + blocks_likelihood=np.array([[1.0, 1e300]]), + ) + with raises_library_error(ERR_ZERO_DIVISION): + ep.propagate_likelihood(BLOCKS, True, 1000.0, 0.1) diff --git a/tests/test_rescaling.py b/tests/test_rescaling.py index 60659427..5b55fcae 100644 --- a/tests/test_rescaling.py +++ b/tests/test_rescaling.py @@ -227,6 +227,20 @@ def test_count_sizebiased(self, inferred_ts): np.testing.assert_array_almost_equal(ck_edge_stats, edge_stats) np.testing.assert_array_equal(ck_muts_edge, muts_edge) + def test_count_with_sample_mask(self, inferred_ts): + node_is_sample = np.full(inferred_ts.num_nodes, False) + node_is_sample[inferred_ts.samples()] = True + edge_stats, muts_edge = count_mutations( + inferred_ts, node_is_sample=node_is_sample, size_biased=True + ) + ck_edge_stats, ck_muts_edge = self.naive_count_sizebiased(inferred_ts) + np.testing.assert_array_almost_equal(ck_edge_stats, edge_stats) + np.testing.assert_array_equal(ck_muts_edge, muts_edge) + + def test_count_with_wrong_size_mask(self, inferred_ts): + with pytest.raises(AssertionError): + count_mutations(inferred_ts, node_is_sample=np.full(1, True)) + @pytest.mark.skip("Ancient samples not implemented") def test_count_sizebiased_with_ancient(self, inferred_ts): # TODO: if there are ancestral samples, these should not be used as weights. diff --git a/tsdate/accelerate.py b/tsdate/accelerate.py deleted file mode 100644 index 1fe81050..00000000 --- a/tsdate/accelerate.py +++ /dev/null @@ -1,27 +0,0 @@ -import os -from collections.abc import Callable - -from numba import jit - -# By default we disable the numba cache. See e.g. -# https://github.com/sgkit-dev/sgkit/blob/main/sgkit/accelerate.py -_ENABLE_CACHE = os.environ.get("TSDATE_ENABLE_NUMBA_CACHE", "0") - -try: - CACHE_NUMBA = {"0": False, "1": True}[_ENABLE_CACHE] -except KeyError as e: # pragma: no cover - raise KeyError( - "Environment variable 'TSDATE_ENABLE_NUMBA_CACHE' must be '0' or '1'" - ) from e - - -DEFAULT_NUMBA_ARGS = { - "nopython": True, - "cache": CACHE_NUMBA, -} - - -def numba_jit(*args, **kwargs) -> Callable: # pragma: no cover - kwargs_ = DEFAULT_NUMBA_ARGS.copy() - kwargs_.update(kwargs) - return jit(*args, **kwargs_) diff --git a/tsdate/approx.py b/tsdate/approx.py deleted file mode 100644 index 0671378a..00000000 --- a/tsdate/approx.py +++ /dev/null @@ -1,1037 +0,0 @@ -# MIT License -# -# Copyright (c) 2021-23 Tskit Developers -# Copyright (c) 2020-21 University of Oxford -# -# Permission is hereby granted, free of charge, to any person obtaining a copy -# of this software and associated documentation files (the "Software"), to deal -# in the Software without restriction, including without limitation the rights -# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -# copies of the Software, and to permit persons to whom the Software is -# furnished to do so, subject to the following conditions: -# -# The above copyright notice and this permission notice shall be included in -# all copies or substantial portions of the Software. -# -# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE -# SOFTWARE. -""" -Tools for approximating combinations of Gamma variates with Gamma distributions -""" - -from math import exp, inf, lgamma, log, nan - -import numba -import numpy as np - -from . import hypergeo -from .accelerate import numba_jit - -# TODO: these are reasonable defaults but could -# be set via a control dict -_KLMIN_MAXITT = 100 -_KLMIN_RELTOL = np.sqrt(np.finfo(np.float64).eps) - - -# shorthand for numba readonly array types, [type][dimension][constness] -# type is one of "i" (int32), "f" (float64), "b" (boolean) -# constness is one of "r" (read-only) or "w" (writable) -_f = numba.types.float64 -_i = numba.types.int32 -_b = numba.types.bool_ -_f1w = numba.types.Array(_f, 1, "C", readonly=False) -_f1r = numba.types.Array(_f, 1, "C", readonly=True) -_f2w = numba.types.Array(_f, 2, "C", readonly=False) -_f2r = numba.types.Array(_f, 2, "C", readonly=True) -_f3w = numba.types.Array(_f, 3, "C", readonly=False) -_f3r = numba.types.Array(_f, 3, "C", readonly=True) -_i1w = numba.types.Array(_i, 1, "C", readonly=False) -_i1r = numba.types.Array(_i, 1, "C", readonly=True) -_i2w = numba.types.Array(_i, 2, "C", readonly=False) -_i2r = numba.types.Array(_i, 2, "C", readonly=True) -_i3w = numba.types.Array(_i, 3, "C", readonly=False) -_i3r = numba.types.Array(_i, 3, "C", readonly=True) -_b1w = numba.types.Array(_b, 1, "C", readonly=False) -_b1r = numba.types.Array(_b, 1, "C", readonly=True) -_b2w = numba.types.Array(_b, 2, "C", readonly=False) -_b2r = numba.types.Array(_b, 2, "C", readonly=True) -_b3w = numba.types.Array(_b, 3, "C", readonly=False) -_b3r = numba.types.Array(_b, 3, "C", readonly=True) -_tuple = numba.types.Tuple -_unituple = numba.types.UniTuple -_void = numba.types.void - - -class KLMinimizationFailedError(Exception): - pass - - -@numba_jit(_unituple(_f, 3)(_f, _f)) -def approximate_log_moments(mean, variance): - """ - Approximate log moments via a second-order Taylor series expansion around - the mean, e.g.: - - E[f(x)] \\approx E[f(mean)] + variance * f''(mean)/2 - - Returns approximations to E[log x], E[x log x], E[(log x)^2] - """ - assert mean > 0 - assert variance > 0 - logx = np.log(mean) - 0.5 * variance / mean**2 - xlogx = mean * np.log(mean) + 0.5 * variance / mean - logx2 = np.log(mean) ** 2 + (1 - np.log(mean)) * variance / mean**2 - return logx, xlogx, logx2 - - -@numba_jit(_unituple(_f, 2)(_f, _f)) -def approximate_gamma_kl(x, logx): - """ - Use Newton root finding to get gamma natural parameters matching the sufficient - statistics :math:`E[x]` and :math:`E[\\log x]`, minimizing KL divergence. - - The initial condition uses the upper bound :math:`digamma(x) \\leq log(x) - 1/2x`. - - Returns the shape and rate of the approximating gamma. - """ - if x <= 0.0 or np.isinf(logx): - raise KLMinimizationFailedError("Nonpositive or nonfinite moments") - if not np.log(x) > logx: - raise KLMinimizationFailedError( - "log E[t] <= E[log t] violates Jensen's inequality" - ) - alpha = 0.5 / (np.log(x) - logx) # lower bound on alpha - # asymptotically the lower bound becomes sharp - if 1.0 / alpha < 1e-4: - return alpha - 1.0, alpha / x - itt = 0 - delta = np.inf - # determine convergence when the change in alpha falls below - # some small value (e.g. square root of machine precision) - while np.abs(delta) > np.abs(alpha) * _KLMIN_RELTOL: - if itt > _KLMIN_MAXITT: - raise KLMinimizationFailedError( - "Maximum iterations reached in KL minimization" - ) - delta = hypergeo._digamma(alpha) - np.log(alpha) + np.log(x) - logx - delta /= hypergeo._trigamma(alpha) - 1 / alpha - alpha -= delta - itt += 1 - if not np.isfinite(alpha) or alpha <= 0: - raise KLMinimizationFailedError("Invalid shape parameter in KL minimization") - return alpha - 1.0, alpha / x - - -@numba_jit(_unituple(_f, 2)(_f, _f)) -def approximate_gamma_mom(mean, variance): - """ - Use the method of moments to approximate a distribution with a gamma of the - same mean and variance, returning natural parameters - """ - if not (mean > 0.0 and variance > 0.0): - raise KLMinimizationFailedError("Nonpositive central moments") - shape = mean**2 / variance - rate = mean / variance - return shape - 1.0, rate - - -@numba.njit(_unituple(_f, 2)(_f, _f, _f, _f, _f)) -def approximate_gamma_iqr(q1, q2, x1, x2, max_shape): - """Find gamma natural parameters that match empirical quantiles""" - - def upper_bound(q, x): # cap shape parameter - beta = hypergeo._gammainc_inv(max_shape, q) / x - return max_shape - 1, beta - - if x2 == x1: - return upper_bound(q1, x1) - if not (q2 > q1 and x2 > x1): - raise KLMinimizationFailedError("Quantiles must be sorted") - alpha = log(q2 / q1) / log(x2 / x1) # lower bound - if alpha > max_shape: - return upper_bound(q1, x1) - - # refine with newton iteration - delta = inf - itt = 0 - while abs(delta) > abs(alpha) * _KLMIN_RELTOL: - if itt > _KLMIN_MAXITT: - raise KLMinimizationFailedError( - "Maximum iterations reached in quantile matching" - ) - y1 = hypergeo._gammainc_inv(alpha, q1) - y2 = hypergeo._gammainc_inv(alpha, q2) - obj = y2 / y1 - x2 / x1 - inv_1 = -exp(y1 + log(y1) * (1 - alpha) + lgamma(alpha)) - inv_2 = -exp(y2 + log(y2) * (1 - alpha) + lgamma(alpha)) - # print(itt, alpha, y1, y2) #DEBUG - gra_1 = hypergeo._gammainc_der(alpha, y1) * inv_1 - gra_2 = hypergeo._gammainc_der(alpha, y2) * inv_2 - gra = (gra_2 * y1 - gra_1 * y2) / y1**2 - delta = -obj / gra - alpha += delta - itt += 1 - - if not alpha > 0: - raise KLMinimizationFailedError("Negative shape parameter") - if alpha > max_shape: - return upper_bound(q1, x1) - beta = hypergeo._gammainc_inv(alpha, q1) / x1 - return alpha - 1, beta - - -@numba_jit(_unituple(_f, 2)(_f1r, _f1r)) -def average_gammas(alpha, beta): - """ - Given natural parameters for a set of gammas, average sufficient - statistics so as to get a "global" gamma, returning natural - parameters - """ - assert alpha.size == beta.size, "Array sizes are not equal" - avg_x = 0.0 - avg_logx = 0.0 - for shape, rate in zip(alpha + 1.0, beta): - avg_logx += hypergeo._digamma(shape) - np.log(rate) - avg_x += shape / rate - avg_x /= alpha.size - avg_logx /= alpha.size - return approximate_gamma_kl(avg_x, avg_logx) - - -@numba_jit(_b(_f, _f)) -def _valid_moments(mn, va): - if not (np.isfinite(mn) and np.isfinite(va)): - return False - if not (mn > 0.0 and va > 0.0): - return False - return True - - -@numba_jit(_b(_f, _f)) -def _valid_gamma(s, r): - if not (np.isfinite(s) and np.isfinite(r)): - return False - if s <= 0.0 or r <= 0.0: - return False - return True - - -@numba_jit(_b(_f, _f, _f)) -def _valid_hyp1f1(a, b, z): - if not (np.isfinite(a) and np.isfinite(b) and np.isfinite(z)): - return False - if not (b >= a > 0.0): - return False - return True - - -@numba_jit(_b(_f, _f, _f)) -def _valid_hyperu(a, b, z): - if not (np.isfinite(a) and np.isfinite(b) and np.isfinite(z)): - return False - if z <= 0.0: - return False - if not (b > a > 0.0): - return False - return True - - -@numba_jit(_b(_f, _f, _f, _f)) -def _valid_hyp2f1(a, b, c, z): - if not (np.isfinite(a) and np.isfinite(b) and np.isfinite(c)): - return False - if not np.isfinite(z) or z >= 1 or z / (z - 1) >= 1: - return False - if not (a > 0 and b > 0 and c > 0): - return False - return True - - -# --- various EP updates --- # - - -@numba_jit(_unituple(_f, 5)(_f, _f, _f, _f, _f, _f)) -def moments(a_i, b_i, a_j, b_j, y_ij, mu_ij): - r""" - log p(t_i, t_j) := \ - log(t_i - t_j) * y_ij - mu_ij * (t_i - t_j) + \ - log(t_i) * (a_i - 1) - b_i * t_i + \ - log(t_j) * (a_j - 1) - b_j * t_j - - Returns normalizing constant, E[t_i], V[t_i], E[t_j], V[t_j]. - """ - - a = a_j - b = a_i + a_j + y_ij - c = a_j + y_ij + 1 - t = mu_ij + b_i - z = (mu_ij - b_j) / t if t > 0 else nan - - if not _valid_hyp2f1(a, b, c, z): - return nan, nan, nan, nan, nan - - hyp2f1 = hypergeo._hyp2f1_laplace - f0 = hyp2f1(a + 0, b + 0, c + 0, z) - f1 = hyp2f1(a + 1, b + 1, c + 1, z) - f2 = hyp2f1(a + 2, b + 2, c + 2, z) - s1 = a * b / c - s2 = s1 * (a + 1) * (b + 1) / (c + 1) - d1 = s1 * exp(f1 - f0) - d2 = s2 * exp(f2 - f0) - - logl = f0 + hypergeo._betaln(y_ij + 1, a) + lgamma(b) - b * log(t) - - mn_j = d1 / t - sq_j = d2 / t**2 - va_j = sq_j - mn_j**2 - - mn_i = mn_j * z + b / t - sq_i = sq_j * z**2 + (b + 1) * (mn_i + mn_j * z) / t - va_i = sq_i - mn_i**2 - - return logl, mn_i, va_i, mn_j, va_j - - -@numba_jit(_unituple(_f, 3)(_f, _f, _f, _f, _f)) -def rootward_moments(t_j, a_i, b_i, y_ij, mu_ij): - r""" - log p(t_i) := \ - log(t_i - t_j) * y_ij - mu_ij * (t_i - t_j) + \ - log(t_i) * (a_i - 1) - b_i * t_i - - Returns normalizing constant, E[t_i], V[t_i]. - """ - - assert t_j >= 0.0 - - s = a_i + y_ij - r = mu_ij + b_i - - if not _valid_gamma(s, r): - return nan, nan, nan - - if t_j == 0.0: - logl = lgamma(s) - s * log(r) - mn_i = s / r - va_i = s / r**2 - return logl, mn_i, va_i - - a = y_ij + 1 - b = s + 1 - z = t_j * r - - if not _valid_hyperu(a, b, z): - return nan, nan, nan - - hyperu = hypergeo._hyperu_laplace - f0, d0 = hyperu(a + 0, b + 0, z) - f1, d1 = hyperu(a + 1, b + 1, z) - - logl = f0 - b_i * t_j + (b - 1) * log(t_j) + lgamma(a) - mn_i = t_j * (1 - d0) - va_i = t_j**2 * d0 * (d1 - d0) - - return logl, mn_i, va_i - - -@numba_jit(_unituple(_f, 3)(_f, _f, _f, _f, _f)) -def leafward_moments(t_i, a_j, b_j, y_ij, mu_ij): - r""" - log p(t_j) := \ - log(t_i - t_j) * y_ij - mu_ij * (t_i - t_j) + \ - log(t_j) * (a_j - 1) - b_j * t_j - - Returns normalizing constant, E[t_j], V[t_j]. - """ - - assert t_i > 0.0 - - a = a_j - b = a_j + y_ij + 1 - z = t_i * (mu_ij - b_j) - - if not _valid_hyp1f1(a, b, z): - return nan, nan, nan - - hyp1f1 = hypergeo._hyp1f1_laplace - f0 = hyp1f1(a + 0, b + 0, z) - f1 = hyp1f1(a + 1, b + 1, z) - f2 = hyp1f1(a + 2, b + 2, z) - d1 = a / b * exp(f1 - f0) - d2 = a / b * (a + 1) / (b + 1) * exp(f2 - f0) - - logl = f0 - mu_ij * t_i + (b - 1) * log(t_i) + hypergeo._betaln(a, b - a) - mn_j = t_i * d1 - sq_j = t_i**2 * d2 - va_j = sq_j - mn_j**2 - - return logl, mn_j, va_j - - -@numba_jit(_unituple(_f, 5)(_f, _f, _f, _f, _f, _f)) -def unphased_moments(a_i, b_i, a_j, b_j, y_ij, mu_ij): - r""" - log p(t_i, t_j) := \ - log(t_i + t_j) * y_ij - mu_ij * (t_i + t_j) + \ - log(t_i) * (a_i - 1) - b_i * t_i + \ - log(t_j) * (a_j - 1) - b_j * t_j - - Returns normalizing constant, E[t_i], V[t_i], E[t_j], V[t_j]. - """ - - a = a_j - b = a_i + a_j + y_ij - c = a_j + a_i - t = mu_ij + b_i - z = (mu_ij + b_j) / t if t > 0 else nan - - if not _valid_hyp2f1(a, b, c, 1 - z): - return nan, nan, nan, nan, nan - - hyp2f1 = hypergeo._hyp2f1_laplace - f0 = hyp2f1(a + 0, b + 0, c + 0, 1 - z) - f1 = hyp2f1(a + 1, b + 1, c + 1, 1 - z) - f2 = hyp2f1(a + 2, b + 2, c + 2, 1 - z) - s1 = a * b / c - s2 = s1 * (a + 1) * (b + 1) / (c + 1) - d1 = s1 * exp(f1 - f0) - d2 = s2 * exp(f2 - f0) - - logl = f0 + hypergeo._betaln(a_j, a_i) + lgamma(b) - b * log(t) - - mn_j = d1 / t - sq_j = d2 / t**2 - va_j = sq_j - mn_j**2 - - mn_i = b / t - mn_j * z - sq_i = sq_j * z**2 + (b + 1) * (mn_i - mn_j * z) / t - va_i = sq_i - mn_i**2 - - return logl, mn_i, va_i, mn_j, va_j - - -@numba_jit(_unituple(_f, 3)(_f, _f, _f, _f)) -def twin_moments(a_i, b_i, y_ij, mu_ij): - r""" - log p(t_i) := \ - log(2 * t_i) * y_ij - mu_ij * (2 * t_i) + \ - log(t_i) * (a_i - 1) - b_i * t_i - - Returns normalizing constant, E[t_i], V[t_i]. - """ - s = a_i + y_ij - r = b_i + 2 * mu_ij - logl = log(2) * y_ij + lgamma(s) - log(r) * s - mn_i = s / r - va_i = s / r**2 - return logl, mn_i, va_i - - -@numba_jit(_unituple(_f, 3)(_f, _f, _f, _f, _f)) -def sideways_moments(t_i, a_j, b_j, y_ij, mu_ij): - r""" - log p(t_j) := \ - log(t_i + t_j) * y_ij - mu_ij * (t_i + t_j) + \ - log(t_j) * (a_j - 1) - b_j * t_j - - Returns normalizing constant, E[t_j], V[t_j]. - """ - - assert t_i > 0.0 - - a = a_j - b = a_j + y_ij + 1 - z = t_i * (mu_ij + b_j) - - if not _valid_hyperu(a, b, z): - return nan, nan, nan - - hyperu = hypergeo._hyperu_laplace - f0, d0 = hyperu(a + 0, b + 0, z) - f1, d1 = hyperu(a + 1, b + 1, z) - - logl = f0 - mu_ij * t_i + (b - 1) * log(t_i) + lgamma(a) - mn_j = -t_i * d0 - va_j = t_i**2 * d0 * (d1 - d0) - - return logl, mn_j, va_j - - -@numba_jit(_unituple(_f, 2)(_f, _f, _f, _f, _f, _f)) -def mutation_moments(a_i, b_i, a_j, b_j, y_ij, mu_ij): - r""" - log p(t_m, t_i, t_j) = \ - log(t_i - t_j) * y_ij - mu_ij * (t_i - t_j) + \ - log(t_i) * (a_i - 1) - b_i * t_i + \ - log(t_j) * (a_j - 1) - b_j * t_j - \ - log(t_i - t_j) + log(int(t_j < t_m < t_i)) - - Returns E[t_m], V[t_m]. - """ - - a = a_j - b = a_i + a_j + y_ij - c = a_j + y_ij + 1 - t = mu_ij + b_i - z = (mu_ij - b_j) / t if t > 0 else nan - - if not _valid_hyp2f1(a, b, c, z): - return nan, nan - - hyp2f1 = hypergeo._hyp2f1_laplace - f000 = hyp2f1(a + 0, b + 0, c + 0, z) - f020 = hyp2f1(a + 0, b + 2, c + 0, z) - f111 = hyp2f1(a + 1, b + 1, c + 1, z) - f121 = hyp2f1(a + 1, b + 2, c + 1, z) - f222 = hyp2f1(a + 2, b + 2, c + 2, z) - - s1 = a * b / c - d1 = b * (b + 1) / t**2 - d2 = d1 * a / c - d3 = d2 * (a + 1) / (c + 1) - - mn_m = s1 * exp(f111 - f000) / t / 2 * (1 + z) + b / t / 2 - sq_m = ( - d1 * exp(f020 - f000) / 3 + d2 * exp(f121 - f000) / 3 + d3 * exp(f222 - f000) / 3 - ) - va_m = sq_m - mn_m**2 - - return mn_m, va_m - - -@numba_jit(_unituple(_f, 2)(_f, _f, _f, _f, _f)) -def mutation_rootward_moments(t_j, a_i, b_i, y_ij, mu_ij): - r""" - log p(t_m, t_i) := \ - log(t_i - t_j) * y_ij - mu_ij * (t_i - t_j) + \ - log(t_i) * (a_i - 1) - b_i * t_i - \ - log(t_i - t_j) + log(int(t_j < t_m < t_i)) - - Returns E[t_m], V[t_m]. - """ - - logl, mn_i, va_i = rootward_moments(t_j, a_i, b_i, y_ij, mu_ij) - mn_m = mn_i / 2 + t_j / 2 - sq_m = (va_i + mn_i**2 + mn_i * t_j + t_j**2) / 3 - va_m = sq_m - mn_m**2 - - return mn_m, va_m - - -@numba_jit(_unituple(_f, 2)(_f, _f, _f, _f, _f)) -def mutation_leafward_moments(t_i, a_j, b_j, y_ij, mu_ij): - r""" - log p(t_m, t_j) := \ - log(t_i - t_j) * y_ij - mu_ij * (t_i - t_j) + \ - log(t_j) * (a_j - 1) - b_j * t_j - \ - log(t_i - t_j) + log(int(t_j < t_m < t_i)) - - Returns E[t_m], V[t_m]. - """ - - logl, mn_j, va_j = leafward_moments(t_i, a_j, b_j, y_ij, mu_ij) - mn_m = mn_j / 2 + t_i / 2 - sq_m = (va_j + mn_j**2 + mn_j * t_i + t_i**2) / 3 - va_m = sq_m - mn_m**2 - - return mn_m, va_m - - -@numba_jit(_unituple(_f, 3)(_f, _f, _f, _f, _f, _f)) -def mutation_unphased_moments(a_i, b_i, a_j, b_j, y_ij, mu_ij): - r""" - log p(t_m, t_i, t_j) := \ - log(t_i + t_j) * y_ij - mu_ij * (t_i + t_j) + \ - log(t_i) * (a_i - 1) - b_i * t_i + \ - log(t_j) * (a_j - 1) - b_j * t_j + \ - log(t_i / (t_i + t_j) * int(0 < t_m < t_i) / t_i + \ - t_j / (t_i + t_j) * int(0 < t_m < t_j) / t_j) - - Returns P[m under i], E[t_m], V[t_m]. - """ - - # Conditioning on ages of parents: - # P[x under i | t_i, t_j] = t_i / (t_i + t_j) - # E[x | x under t_i, t_i] = t_i / 2 - # E[x^2 | x under t_i, t_i] = t_i**2 / 3 - # and equivalently for t_j. Integrating these moments over the EP surrogate - # density leads to hypergeometric functions similar to the node case, but - # with integer perturbations of a_i, a_j, y_ij. - - a = a_j - b = a_j + a_i + y_ij - c = a_j + a_i - t = mu_ij + b_i - z = (mu_ij + b_j) / t if t > 0 else nan - - if not _valid_hyp2f1(a, b, c, 1 - z): - return nan, nan, nan - - hyp2f1 = hypergeo._hyp2f1_laplace - f000 = hyp2f1(a + 0, b + 0, c + 0, 1 - z) - f001 = hyp2f1(a + 0, b + 0, c + 1, 1 - z) - f012 = hyp2f1(a + 0, b + 1, c + 2, 1 - z) - f023 = hyp2f1(a + 0, b + 2, c + 3, 1 - z) - f212 = hyp2f1(a + 2, b + 1, c + 2, 1 - z) - f323 = hyp2f1(a + 3, b + 2, c + 3, 1 - z) - - s0 = b / t / c / (c + 1) - s1 = (c - a) * (c - a + 1) - s2 = a * (a + 1) - d0 = s0 * (b + 1) / t / (c + 2) - d1 = s1 * (c - a + 2) - d2 = s2 * (a + 2) - - mn_m = s0 * s1 * exp(f012 - f000) / 2 + s0 * s2 * exp(f212 - f000) / 2 - sq_m = d0 * d1 * exp(f023 - f000) / 3 + d0 * d2 * exp(f323 - f000) / 3 - va_m = sq_m - mn_m**2 - pr_m = (c - a) / c * exp(f001 - f000) - - return pr_m, mn_m, va_m - - -@numba_jit(_unituple(_f, 3)(_f, _f, _f, _f)) -def mutation_twin_moments(a_i, b_i, y_ij, mu_ij): - r""" - log p(t_m, t_i) := \ - log(2 * t_i) * y_ij - mu_ij * (2 * t_i) + \ - log(t_i) * (a_i - 1) - b_i * t_i + \ - log(int(0 < t_m < t_i) / t_i) - """ - - s = a_i + y_ij - r = b_i + 2 * mu_ij - pr_m = 0.5 - mn_m = s / r / 2 - sq_m = (s + 1) * s / 3 / r**2 - va_m = sq_m - mn_m**2 - - return pr_m, mn_m, va_m - - -@numba_jit(_unituple(_f, 3)(_f, _f, _f, _f, _f)) -def mutation_sideways_moments(t_i, a_j, b_j, y_ij, mu_ij): - r""" - log p(t_m, t_j) := \ - log(t_i + t_j) * y_ij - mu_ij * (t_i + t_j) + \ - log(t_j) * (a_j - 1) - b_j * t_j + \ - log(t_i / (t_i + t_j) * int(0 < t_m < t_i) / t_i + \ - t_j / (t_i + t_j) * int(0 < t_m < t_j) / t_j) - - Returns P[m under i], E[t_m], V[t_m]. - """ - - assert t_i > 0 - - # Conditioning on ages of parents: - # P[x under i | t_i, t_j] = t_i / (t_i + t_j) - # E[x | x under t_i, t_i] = t_i / 2 - # E[x^2 | x under t_i, t_i] = t_i**2 / 3 - # and equivalently for t_j. Integrating these moments over the EP surrogate - # density leads to Tricomi functions similar to the node case, but - # with integer perturbations of a_j, y_ij. - - a = a_j - b = a_j + y_ij + 1 - z = t_i * (mu_ij + b_j) - - if not _valid_hyperu(a, b, z): - return nan, nan, nan - - # direct but unstable: - hyperu = hypergeo._hyperu_laplace - f00, d00 = hyperu(a + 0, b + 0, z) - f10, d10 = hyperu(a + 1, b + 0, z) - f21, d21 = hyperu(a + 2, b + 1, z) - f32, d32 = hyperu(a + 3, b + 2, z) - pr_m = 1.0 - exp(f10 - f00) * a - mn_m = pr_m * t_i / 2 + t_i * exp(f21 - f00) * a * (a + 1) / 2 - sq_m = pr_m * t_i**2 / 3 + t_i**2 * exp(f32 - f00) * a * (a + 1) * (a + 2) / 3 - - # TODO: use a stabler approach with derivatives - # note that exp(f10 - f00) = (a + z * d00) / (a - b + 1) - # however the denominator is 0 if y_ij is 0 - # note that when y_ij == 0 then a == b + 1 and f00 = z**(-a) - - va_m = sq_m - mn_m**2 - - return pr_m, mn_m, va_m - - -@numba_jit(_unituple(_f, 2)(_f, _f)) -def mutation_edge_moments(t_i, t_j): - r""" - log p(t_m) := \ - log(t_i - t_j) + log(int(t_j < t_m < t_i)) - - Returns E[t_m], V[t_m]. - """ - - mn_m = 1 / 2 * (t_i + t_j) - va_m = 1 / 12 * (t_i - t_j) ** 2 - - return mn_m, va_m - - -@numba_jit(_unituple(_f, 3)(_f, _f)) -def mutation_block_moments(t_i, t_j): - r""" - log p(t_m) := \ - log(t_i / (t_i + t_j) * int(0 < t_m < t_i) / t_i + \ - t_j / (t_i + t_j) * int(0 < t_m < t_j) / t_j) - - Returns P[m under i], E[t_m], V[t_m]. - """ - - assert t_i > 0 - assert t_j > 0 - - pr_m = t_i / (t_i + t_j) - mn_m = pr_m * t_i / 2 + (1 - pr_m) * t_j / 2 - sq_m = pr_m * t_i**2 / 3 + (1 - pr_m) * t_j**2 / 3 - va_m = sq_m - mn_m**2 - - return pr_m, mn_m, va_m - - -# --- wrappers around updates --- # - - -@numba_jit(_tuple((_f, _f1r, _f1r))(_f1r, _f1r, _f1r)) -def gamma_projection(pars_i, pars_j, pars_ij): - r""" - log p(t_i, t_j) := \ - log(t_i - t_j) * y_ij - mu_ij * (t_i - t_j) + \ - log(t_i) * (a_i - 1) - b_i * t_i + \ - log(t_j) * (a_j - 1) - b_j * t_j - - Returns normalizing constant, gamma natural parameters for parent and child ages - """ - a_i, b_i = pars_i - a_j, b_j = pars_j - y_ij, mu_ij = pars_ij - a_i += 1 - a_j += 1 - - logl, mn_i, va_i, mn_j, va_j = moments(a_i, b_i, a_j, b_j, y_ij, mu_ij) - - if not (_valid_moments(mn_i, va_i) and _valid_moments(mn_j, va_j)): - return np.nan, pars_i, pars_j - - proj_i = approximate_gamma_mom(mn_i, va_i) - proj_j = approximate_gamma_mom(mn_j, va_j) - - return logl, np.array(proj_i), np.array(proj_j) - - -@numba_jit(_tuple((_f, _f1r))(_f, _f1r, _f1r)) -def leafward_projection(t_i, pars_j, pars_ij): - r""" - log p(t_j) := \ - log(t_i - t_j) * y_ij - mu_ij * (t_i - t_j) + \ - log(t_j) * (a_j - 1) - b_j * t_j - - Returns normalizing constant, gamma natural parameters for child age - """ - a_j, b_j = pars_j - y_ij, mu_ij = pars_ij - a_j += 1 - - logl, mn_j, va_j = leafward_moments(t_i, a_j, b_j, y_ij, mu_ij) - - if not _valid_moments(mn_j, va_j): - return np.nan, pars_j - - proj_j = approximate_gamma_mom(mn_j, va_j) - - return logl, np.array(proj_j) - - -@numba_jit(_tuple((_f, _f1r))(_f, _f1r, _f1r)) -def rootward_projection(t_j, pars_i, pars_ij): - r""" - log p(t_i) := \ - log(t_i - t_j) * y_ij - mu_ij * (t_i - t_j) + \ - log(t_i) * (a_i - 1) - b_i * t_i - - Returns normalizing constant, gamma natural parameters for parent age - """ - a_i, b_i = pars_i - y_ij, mu_ij = pars_ij - a_i += 1 - - logl, mn_i, va_i = rootward_moments(t_j, a_i, b_i, y_ij, mu_ij) - - if not _valid_moments(mn_i, va_i): - return np.nan, pars_i - - proj_i = approximate_gamma_mom(mn_i, va_i) - - return logl, np.array(proj_i) - - -@numba_jit(_tuple((_f, _f1r, _f1r))(_f1r, _f1r, _f1r)) -def unphased_projection(pars_i, pars_j, pars_ij): - r""" - log p(t_i, t_j) := \ - log(t_i + t_j) * y_ij - mu_ij * (t_i + t_j) + \ - log(t_i) * (a_i - 1) - b_i * t_i + \ - log(t_j) * (a_j - 1) - b_j * t_j - - Returns normalizing constant, gamma natural parameters for parent ages - """ - a_i, b_i = pars_i - a_j, b_j = pars_j - y_ij, mu_ij = pars_ij - a_i += 1 - a_j += 1 - - logl, mn_i, va_i, mn_j, va_j = unphased_moments(a_i, b_i, a_j, b_j, y_ij, mu_ij) - - if not _valid_moments(mn_i, va_i) or not _valid_moments(mn_j, va_j): - return np.nan, pars_i, pars_j - - proj_i = approximate_gamma_mom(mn_i, va_i) - proj_j = approximate_gamma_mom(mn_j, va_j) - - return logl, np.array(proj_i), np.array(proj_j) - - -@numba_jit(_tuple((_f, _f1r))(_f1r, _f1r)) -def twin_projection(pars_i, pars_ij): - r""" - log p(t_i) := \ - log(2 * t_i) * y_ij - mu_ij * (2 * t_i) + \ - log(t_i) * (a_i - 1) - b_i * t_i - - Returns normalizing constant, gamma natural parameters for parent ages - """ - a_i, b_i = pars_i - y_ij, mu_ij = pars_ij - a_i += 1 - - logl, mn_i, va_i = twin_moments(a_i, b_i, y_ij, mu_ij) - - if not _valid_moments(mn_i, va_i): - return np.nan, pars_i - - proj_i = approximate_gamma_mom(mn_i, va_i) - - return logl, np.array(proj_i) - - -@numba_jit(_tuple((_f, _f1r))(_f, _f1r, _f1r)) -def sideways_projection(t_i, pars_j, pars_ij): - r""" - log p(t_j) := \ - log(t_i + t_j) * y_ij - mu_ij * (t_i + t_j) + \ - log(t_j) * (a_j - 1) - b_j * t_j - - Returns normalizing constant, gamma natural parameters for nonfixed parent age - """ - a_j, b_j = pars_j - y_ij, mu_ij = pars_ij - a_j += 1 - - logl, mn_j, va_j = sideways_moments(t_i, a_j, b_j, y_ij, mu_ij) - - if not _valid_moments(mn_j, va_j): - return np.nan, pars_j - - proj_j = approximate_gamma_mom(mn_j, va_j) - - return logl, np.array(proj_j) - - -@numba_jit(_tuple((_f, _f1r))(_f1r, _f1r, _f1r)) -def mutation_gamma_projection(pars_i, pars_j, pars_ij): - r""" - log p(t_m, t_i, t_j) = \ - log(t_i - t_j) * y_ij - mu_ij * (t_i - t_j) + \ - log(t_i) * (a_i - 1) - b_i * t_i + \ - log(t_j) * (a_j - 1) - b_j * t_j - \ - log(t_i - t_j) + log(int(t_j < t_m < t_i)) - - Returns phase probability, gamma natural parameters for mutation age - """ - a_i, b_i = pars_i - a_j, b_j = pars_j - y_ij, mu_ij = pars_ij - a_i += 1 - a_j += 1 - - mn_m, va_m = mutation_moments(a_i, b_i, a_j, b_j, y_ij, mu_ij) - - if not _valid_moments(mn_m, va_m): - return np.nan, np.full(2, np.nan) - - proj_m = approximate_gamma_mom(mn_m, va_m) - - return 1.0, np.array(proj_m) - - -@numba_jit(_tuple((_f, _f1r))(_f, _f1r, _f1r)) -def mutation_leafward_projection(t_i, pars_j, pars_ij): - r""" - log p(t_m, t_j) := \ - log(t_i - t_j) * y_ij - mu_ij * (t_i - t_j) + \ - log(t_j) * (a_j - 1) - b_j * t_j - \ - log(t_i - t_j) + log(int(t_j < t_m < t_i)) - - Returns phase probability, gamma natural parameters for mutation age - """ - a_j, b_j = pars_j - y_ij, mu_ij = pars_ij - a_j += 1 - - mn_m, va_m = mutation_leafward_moments(t_i, a_j, b_j, y_ij, mu_ij) - - if not _valid_moments(mn_m, va_m): - return np.nan, np.full(2, np.nan) - - proj_m = approximate_gamma_mom(mn_m, va_m) - - return 1.0, np.array(proj_m) - - -@numba_jit(_tuple((_f, _f1r))(_f, _f1r, _f1r)) -def mutation_rootward_projection(t_j, pars_i, pars_ij): - r""" - log p(t_m, t_i) := \ - log(t_i - t_j) * y_ij - mu_ij * (t_i - t_j) + \ - log(t_i) * (a_i - 1) - b_i * t_i - \ - log(t_i - t_j) + log(int(t_j < t_m < t_i)) - - Returns phase probability, gamma natural parameters for mutation age - """ - a_i, b_i = pars_i - y_ij, mu_ij = pars_ij - a_i += 1 - - mn_m, va_m = mutation_rootward_moments(t_j, a_i, b_i, y_ij, mu_ij) - - if not _valid_moments(mn_m, va_m): - return np.nan, np.full(2, np.nan) - - proj_m = approximate_gamma_mom(mn_m, va_m) - - return 1.0, np.array(proj_m) - - -@numba_jit(_tuple((_f, _f1r))(_f, _f)) -def mutation_edge_projection(t_i, t_j): - r""" - log p(t_m) := \ - log(t_i - t_j) + log(int(t_j < t_m < t_i)) - - Returns phase probability, gamma natural parameters for mutation age - """ - mn_m, va_m = mutation_edge_moments(t_i, t_j) - - if not _valid_moments(mn_m, va_m): - return np.nan, np.full(2, np.nan) - - proj_m = approximate_gamma_mom(mn_m, va_m) - - return 1.0, np.array(proj_m) - - -@numba_jit(_tuple((_f, _f1r))(_f1r, _f1r, _f1r)) -def mutation_unphased_projection(pars_i, pars_j, pars_ij): - r""" - log p(t_m, t_i, t_j) := \ - log(t_i + t_j) * y_ij - mu_ij * (t_i + t_j) + \ - log(t_i) * (a_i - 1) - b_i * t_i + \ - log(t_j) * (a_j - 1) - b_j * t_j + \ - log(t_i / (t_i + t_j) * int(0 < t_m < t_i) + \ - t_j / (t_i + t_j) * int(0 < t_m < t_j)) - - Returns phase probability, gamma natural parameters for mutation age - """ - a_i, b_i = pars_i - a_j, b_j = pars_j - y_ij, mu_ij = pars_ij - a_i += 1 - a_j += 1 - - pr_m, mn_m, va_m = mutation_unphased_moments(a_i, b_i, a_j, b_j, y_ij, mu_ij) - - if not _valid_moments(mn_m, va_m) or not (0 <= pr_m <= 1): - return np.nan, np.full(2, np.nan) - - proj_m = approximate_gamma_mom(mn_m, va_m) - - return pr_m, np.array(proj_m) - - -@numba_jit(_tuple((_f, _f1r))(_f1r, _f1r)) -def mutation_twin_projection(pars_i, pars_ij): - r""" - log p(t_m, t_i) := \ - log(2 * t_i) * y_ij - mu_ij * (2 * t_i) + \ - log(t_i) * (a_i - 1) - b_i * t_i + \ - log(int(0 < t_m < t_i) / t_i) - - Returns phase probability, gamma natural parameters for mutation age - """ - a_i, b_i = pars_i - y_ij, mu_ij = pars_ij - a_i += 1 - - pr_m, mn_m, va_m = mutation_twin_moments(a_i, b_i, y_ij, mu_ij) - - if not _valid_moments(mn_m, va_m) or not (0 <= pr_m <= 1): - return np.nan, np.full(2, np.nan) - - proj_m = approximate_gamma_mom(mn_m, va_m) - - return pr_m, np.array(proj_m) - - -@numba_jit(_tuple((_f, _f1r))(_f, _f1r, _f1r)) -def mutation_sideways_projection(t_i, pars_j, pars_ij): - r""" - log p(t_m, t_j) := \ - log(t_i + t_j) * y_ij - mu_ij * (t_i + t_j) + \ - log(t_j) * (a_j - 1) - b_j * t_j + \ - log(t_i / (t_i + t_j) * int(0 < t_m < t_i) + \ - t_j / (t_i + t_j) * int(0 < t_m < t_j)) - - Returns phase probability, gamma natural parameters for mutation age - """ - a_j, b_j = pars_j - y_ij, mu_ij = pars_ij - a_j += 1 - - pr_m, mn_m, va_m = mutation_sideways_moments(t_i, a_j, b_j, y_ij, mu_ij) - - if not _valid_moments(mn_m, va_m) or not (0 <= pr_m <= 1): - return np.nan, np.full(2, np.nan) - - proj_m = approximate_gamma_mom(mn_m, va_m) - - return pr_m, np.array(proj_m) - - -@numba_jit(_tuple((_f, _f1r))(_f, _f)) -def mutation_block_projection(t_i, t_j): - r""" - log p(t_m) := \ - log(t_i / (t_i + t_j) * int(0 < t_m < t_i) + \ - t_j / (t_i + t_j) * int(0 < t_m < t_j)) - - Returns phase probability, gamma natural parameters for mutation age - """ - pr_m, mn_m, va_m = mutation_block_moments(t_i, t_j) - - if not _valid_moments(mn_m, va_m) or not (0 <= pr_m <= 1): - return np.nan, np.full(2, np.nan) - - proj_m = approximate_gamma_mom(mn_m, va_m) - - return pr_m, np.array(proj_m) diff --git a/tsdate/core.py b/tsdate/core.py index 02bdbfdc..06e040e6 100644 --- a/tsdate/core.py +++ b/tsdate/core.py @@ -248,7 +248,6 @@ def get_modified_ts(self, result): f"Set ages of {num_root_muts} nonsegregating mutations to root times." ) if self.provenance_params is not None: - # Note that the time recorded in provenance excludes numba compilation time provenance.record_provenance( tables, self.name, self.start_time, **self.provenance_params ) diff --git a/tsdate/discrete.py b/tsdate/discrete.py index e2e656d5..b959729e 100644 --- a/tsdate/discrete.py +++ b/tsdate/discrete.py @@ -11,7 +11,6 @@ import tskit from tqdm.auto import tqdm -from .accelerate import numba_jit from .node_time_class import LIN_GRID, LOG_GRID @@ -353,6 +352,20 @@ def scale_geometric(self, fraction, value): return value**fraction +def logsumexp_reduceat(x, indices): + """ + The log of the sum of exp(x) over each slice of `x` starting at `indices`, as + np.logaddexp.reduceat(x, indices) for increasing `indices`, with one exponential + per element + """ + maxima = np.maximum.reduceat(x, indices) + shifts = np.where(np.isfinite(maxima), maxima, 0.0) + lengths = np.diff(indices, append=x.size) + sums = np.add.reduceat(np.exp(x - np.repeat(shifts, lengths)), indices) + with np.errstate(divide="ignore"): + return np.log(sums) + shifts + + class LogLikelihoods(Likelihoods): """ Identical to the Likelihoods class but stores and returns log likelihoods @@ -362,25 +375,9 @@ class LogLikelihoods(Likelihoods): identity_constant = 0.0 null_constant = -np.inf - """ - Uses an alternative to logsumexp, useful for large grid sizes, see - http://www.nowozin.net/sebastian/blog/streaming-log-sum-exp-computation.html - """ - @staticmethod - @numba_jit def logsumexp(X): - alpha = -np.inf - r = 0.0 - for x in X: - if x != -np.inf: - if x <= alpha: - r += np.exp(x - alpha) - else: - r *= np.exp(alpha - x) - r += 1.0 - alpha = x - return -np.inf if r == 0 else np.log(r) + alpha + return logsumexp_reduceat(X, np.zeros(1, dtype=int))[0] @staticmethod def _lik(muts, span, dt, mutation_rate, standardize=True): @@ -404,32 +401,12 @@ def _lik_wrapper(muts_span, dt, mutation_rate, standardize=True): ) def rowsum_lower_tri(self, input_array): - """ - The function below is equivalent to (but numba makes it faster than) - np.logaddexp.reduceat(input_array, self.row_indices[0]) - """ assert len(input_array) == self.tri_size - res = list() - i_start = self.row_indices[0][0] - for i in self.row_indices[0][1:]: - res.append(self.logsumexp(input_array[i_start:i])) - i_start = i - res.append(self.logsumexp(input_array[i:])) - return np.array(res) + return logsumexp_reduceat(input_array, self.row_indices[0]) def rowsum_upper_tri(self, input_array): - """ - The function below is equivalent to (but numba makes it faster than) - np.logaddexp.reduceat(input_array, self.col_indices) - """ assert len(input_array) == self.tri_size - res = list() - i_start = self.col_indices[0] - for i in self.col_indices[1:]: - res.append(self.logsumexp(input_array[i_start:i])) - i_start = i - res.append(self.logsumexp(input_array[i:])) - return np.array(res) + return logsumexp_reduceat(input_array, self.col_indices) def _recombination_loglik(self, edge, fixed=True): # Needs to return a lower tri *or* flattened array depending on `fixed` diff --git a/tsdate/hypergeo.py b/tsdate/hypergeo.py deleted file mode 100644 index ab3d121e..00000000 --- a/tsdate/hypergeo.py +++ /dev/null @@ -1,347 +0,0 @@ -# MIT License -# -# Copyright (c) 2021-23 Tskit Developers -# Copyright (c) 2020-21 University of Oxford -# -# Permission is hereby granted, free of charge, to any person obtaining a copy -# of this software and associated documentation files (the "Software"), to deal -# in the Software without restriction, including without limitation the rights -# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -# copies of the Software, and to permit persons to whom the Software is -# furnished to do so, subject to the following conditions: -# -# The above copyright notice and this permission notice shall be included in -# all copies or substantial portions of the Software. -# -# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE -# SOFTWARE. -""" -Numerically stable implementations of the Gauss hypergeometric function with numba. -""" - -import ctypes -from math import erf, exp, lgamma, log, pi, pow, sqrt # noqa: A004 - -import numba -import numpy as np -from numba.extending import get_cython_function_address - -from .accelerate import numba_jit - -_HYP2F1_TOL = 1e-10 -_HYP2F1_MAXTERM = int(1e6) - - -class Invalid2F1(Exception): # noqa N818 - pass - - -# --- numba bindings for scipy cython interface --- # - -_dbl = ctypes.c_double - -# for caching reasons, we use math.lgamma rather than scipy.special.cython_special.gammaln - -# gammaincinv -_gammaincinv_addr = get_cython_function_address( - "scipy.special.cython_special", "gammaincinv" -) -_gammaincinv_functype = ctypes.CFUNCTYPE(_dbl, _dbl, _dbl) -_gammaincinv_f8 = _gammaincinv_functype(_gammaincinv_addr) - - -@numba.cfunc("f8(f8, f8)") -def _gammainc_inv(a, x): - """scipy.special.cython_special.gammaincinv""" - return _gammaincinv_f8(a, x) - - -@numba_jit("f8(f8)") -def _digamma(x): - """ - Digamma (psi) function, from asymptotic series expansion. - """ - if x <= 0.0: - return _digamma(1 - x) - np.pi / np.tan(np.pi * x) - if x <= 1e-5: - return -np.euler_gamma - (1 / x) - if x < 8.5: - return _digamma(1 + x) - 1 / x - xpm2 = 1 / x**2 - return ( - np.log(x) - - 0.5 / x - - 0.083333333333333333 * xpm2 - + 0.008333333333333333 * xpm2**2 - - 0.003968253968253968 * xpm2**3 - + 0.004166666666666667 * xpm2**4 - - 0.007575757575757576 * xpm2**5 - + 0.021092796092796094 * xpm2**6 - ) - - -@numba_jit("f8(f8)") -def _trigamma(x): - """ - Trigamma function, from asymptotic series expansion - """ - if x <= 0.0: - return -_trigamma(1 - x) + np.pi**2 / np.sin(np.pi * x) ** 2 - if x <= 1e-4: - return 1 / x**2 - if x < 5: - return _trigamma(1 + x) + 1 / x**2 - xpm1 = 1 / x - xpm2 = 1 / x**2 - return xpm1 * ( - 1.000000000000000000 - + 0.500000000000000000 * xpm1 - + 0.166666666666666667 * np.power(xpm2, 1) - - 0.033333333333333333 * np.power(xpm2, 2) - + 0.023809523809523808 * np.power(xpm2, 3) - - 0.033333333333333333 * np.power(xpm2, 4) - + 0.075757575757575756 * np.power(xpm2, 5) - - 0.253113553113553102 * np.power(xpm2, 6) - + 1.166666666666666741 * np.power(xpm2, 7) - ) - - -@numba_jit("f8(f8, f8)") -def _betaln(p, q): - return lgamma(p) + lgamma(q) - lgamma(p + q) - - -@numba_jit("UniTuple(f8, 2)(f8, f8, f8)") -def _hyperu_laplace(a, b, x): - """ - Approximate Tricomi's confluent hypergeometric function with real - arguments, using Laplace's method with a calibration point. - - Also returns derivative wrt x. - - TODO: details - """ - - assert b >= a > 0.0 - assert x > 0.0 - - t = b - x - 1 - u = 2 * a / (sqrt(t**2 + 4 * x * a) - t) - r = (b - a - 1) * u**2 + a * (1 + u) ** 2 - g = (b - a) * log(1 + u) + a * (1 + log(u)) - x * u - log(a) * (a - 1 / 2) - - w = (b - 1) * u + a - v = u * (1 + u) - dr = w / (w * u + a * (1 + u)) - dg = (w - x * v + u) / v - du = -u * v / (w - x * u + a) - - return g - log(r) / 2, (dg - dr) * du - u - - -@numba_jit("f8(f8, f8, f8)") -def _hyp1f1_laplace(a, b, x): - """ - Approximate Kummer's confluent hypergeometric function with real arguments, - using Laplace's method with a calibration point. - - TODO: details - """ - - assert b > a > 0.0 - - if x == 0.0: - return 0.0 - - t = x - b - u = 2 * a / (sqrt(t**2 + 4 * x * a) - t) - r = u**2 * b / a + (1 - u) ** 2 * b / (b - a) - g = ( - (b - a) * log(1 - u) - + a * log(u) - + b * log(b) - - (b - a) * log(b - a) - - a * log(a) - + x * u - ) - - return g - log(r) / 2 - - -@numba_jit("f8(f8, f8, f8, f8)") -def _hyp2f1_laplace(a, b, c, x): - r""" - Approximate a Gaussian hypergeometric function with real arguments, - using Laplace's method with a calibration point. - - TODO: details - """ - - def _hyp2f1_unity(a, b, c, x): - """ - Gauss hypergeometric function when `x` is near unity - - See limits in DLMF 15.4. - - TODO: this works in practice, but when (c - a - b) is close to zero the - limits don't converge. A good reference is Buhring 2003 "Partial sums of - hypergeometric series of unit argument" - """ - assert np.isclose(x, 1.0) - assert x < 1.0 - - g = c - a - b - - if g < 0.0: - return lgamma(c) + lgamma(-g) - lgamma(a) - lgamma(b) + g * log(1 - x) - elif g > 0.0: - # will only occur when a_i + a_j < 1 - return lgamma(c) + lgamma(g) - lgamma(c - a) - lgamma(c - b) - else: - # will only occur when a_i + a_j == 1 - return log(-log(1 - x)) + lgamma(a + b) - lgamma(a) - lgamma(b) - - # TODO: simplify, we can safely assume a,b > 0? - assert c > 0.0 - assert a >= 0.0 - assert b >= 0.0 - assert c >= a - assert x < 1.0 - - if x == 0.0: - return 0.0 - - s = 0.0 - if x < 0.0: - s = -b * log(1 - x) - a = c - a - x = x / (x - 1) - - if np.isclose(x, 1.0): - return s + _hyp2f1_unity(a, b, c, x) - - t = x * (b - a) - c - u = sqrt(t**2 - 4 * a * x * (c - b)) - t - y = 2 * a / u - - assert 0 < y < 1, "Root on boundary" - - yy = y**2 / a - my = (1 - y) ** 2 / (c - a) - ymy = x**2 * b * yy * my / (1 - x * y) ** 2 - r = yy + my - ymy - f = ( - (c - 1 / 2) * log(c) - + a * (log(y) - log(a)) - + (c - a) * (log(1 - y) - log(c - a)) - - b * log(1 - x * y) - ) - - return f - log(r) / 2 + s - - -@numba_jit("f8(f8, f8)") -def _gammainc_der(p, x): - """ - Derivative of lower incomplete gamma function with regards to `p`. - - Based on Shea B (1988) "Algorithm AS 239" Applied Statistics 37: 466-473 - - Adapted from https://people.math.sc.edu/Burkardt/cpp_src/asa239/asa239.cpp - """ - - elimit = -88.0 - oflo = 1.0e37 - plimit = 1.0e3 - tol = 1.0e-14 - xbig = 1.0e8 - - assert x >= 0.0 - assert p > 0.0 - - if x == 0: - value, grad = 0.0, 0.0 - return grad - - if x > xbig: - value, grad = 1.0, 0.0 - return grad - - if p > plimit: # gaussian approximation - pn1 = 3 * sqrt(p) * (pow(x / p, 1 / 3) + 1 / (9 * p) - 1) - grad = pn1 / (2 * p) - 1 / sqrt(p) * (pow(x / p, 1 / 3) + 1 / (3 * p)) - grad *= 1 / sqrt(2 * pi) * exp(-(pn1**2) / 2) - value = (1 + erf(pn1 / sqrt(2))) / 2 - return grad - - if x <= 1 or x < p: # series expansion - arg = p * log(x) - x - lgamma(p + 1) - value, grad = 1.0, 0.0 - c, dc = 1.0, 0.0 - a = p - while True: - a += 1.0 - dc = -c * x / a**2 + dc * x / a - c *= x / a - value += c - grad += dc - if c <= tol: - break - darg = exp(arg) * (log(x) - _digamma(p + 1)) - grad = grad * exp(arg) + value * darg - arg += log(value) - if arg >= elimit: - value = exp(arg) - else: - grad = 0.0 - value = 0.0 - return grad - else: # continued fraction - arg = p * log(x) - x - lgamma(p) - a = 1.0 - p - b = a + x + 1.0 - c = 0.0 - pn1, pn2, pn3, pn4 = 1.0, x, x + 1.0, x * b - dpn1, dpn2, dpn3, dpn4 = 0.0, 0.0, 0.0, -x - value, grad = pn3 / pn4, 0.0 - while True: - a += 1.0 - b += 2.0 - c += 1.0 - an = a * c - pn5 = b * pn3 - an * pn1 - pn6 = b * pn4 - an * pn2 - dpn5 = b * dpn3 - pn3 - an * dpn1 + c * pn1 - dpn6 = b * dpn4 - pn4 - an * dpn2 + c * pn2 - if pn6 != 0.0: - rn = pn5 / pn6 - grad = (dpn5 * pn6 - pn5 * dpn6) / pn6**2 - if abs(value - rn) <= min(tol, tol * rn): - break - value = rn - pn1, pn2, pn3, pn4 = pn3, pn4, pn5, pn6 - dpn1, dpn2, dpn3, dpn4 = dpn3, dpn4, dpn5, dpn6 - if oflo <= abs(pn5): - pn1 /= oflo - pn2 /= oflo - pn3 /= oflo - pn4 /= oflo - dpn1 /= oflo - dpn2 /= oflo - dpn3 /= oflo - dpn4 /= oflo - darg = exp(arg) * (log(x) - _digamma(p)) - grad = grad * exp(arg) + value * darg - arg += log(value) - if arg >= elimit: - grad *= -1.0 - value = 1.0 - exp(arg) - else: - grad = 0.0 - value = 1.0 - return grad diff --git a/tsdate/phasing.py b/tsdate/phasing.py index 5dba4d7b..e3815687 100644 --- a/tsdate/phasing.py +++ b/tsdate/phasing.py @@ -23,164 +23,32 @@ Tools for phasing singleton mutations """ +import _tsdate import numpy as np import tskit -from .accelerate import numba_jit -from .approx import _b1r, _b2r, _f, _f1r, _f2w, _i1r, _i1w, _i2r, _i2w, _tuple, _void - # --- machinery used by ExpectationPropagation class --- # -@numba_jit(_void(_f2w, _f1r, _i1r, _i2r)) -def reallocate_unphased(edges_likelihood, mutations_phase, mutations_block, blocks_edges): - """ - Add a proportion of each unphased singleton mutation to one of the two - edges to which it maps - """ - assert mutations_phase.size == mutations_block.size - assert blocks_edges.shape[1] == 2 - - num_edges = edges_likelihood.shape[0] - edges_unphased = np.full(num_edges, False) - edges_unphased[blocks_edges[:, 0]] = True - edges_unphased[blocks_edges[:, 1]] = True - - num_unphased = np.sum(edges_likelihood[edges_unphased, 0]) - edges_likelihood[edges_unphased, 0] = 0.0 - for m, b in enumerate(mutations_block): - if b == tskit.NULL: - continue - i, j = blocks_edges[b] - assert tskit.NULL < i < num_edges - assert edges_unphased[i] - assert tskit.NULL < j < num_edges - assert edges_unphased[j] - if np.isnan(mutations_phase[m]): # TODO: fix rare numerical issue - continue - assert 0.0 <= mutations_phase[m] <= 1.0 - edges_likelihood[i, 0] += mutations_phase[m] - edges_likelihood[j, 0] += 1 - mutations_phase[m] - assert np.isclose(num_unphased, np.sum(edges_likelihood[edges_unphased, 0])) - - -@numba_jit( - _tuple((_f2w, _i2w, _i1w))( - _b1r, _i1r, _i1r, _f1r, _i1r, _i1r, _f1r, _f1r, _i1r, _i1r, _f - ) -) -def _block_singletons( - individuals_unphased, - nodes_individual, - mutations_node, - mutations_position, - edges_parent, - edges_child, - edges_left, - edges_right, - indexes_insert, - indexes_remove, - sequence_length, -): - """ - TODO - """ - assert edges_parent.size == edges_child.size == edges_left.size == edges_right.size - assert indexes_insert.size == indexes_remove.size == edges_parent.size - assert mutations_node.size == mutations_position.size - - num_mutations = mutations_node.size - num_edges = edges_parent.size - num_individuals = individuals_unphased.size - - indexes_mutation = np.argsort(mutations_position) - position_insert = edges_left[indexes_insert] - position_remove = edges_right[indexes_remove] - position_mutation = mutations_position[indexes_mutation] - - individuals_edges = np.full((num_individuals, 2), tskit.NULL) - individuals_position = np.full(num_individuals, np.nan) - individuals_singletons = np.zeros(num_individuals) - individuals_block = np.full(num_edges, tskit.NULL) - mutations_block = np.full(num_mutations, tskit.NULL) - - blocks_span = [] - blocks_singletons = [] - blocks_edges = [] - blocks_order = [] - - num_blocks = 0 - left = 0.0 - a, b, d = 0, 0, 0 - while a < num_edges or b < num_edges: - while b < num_edges and position_remove[b] == left: # edges out - e = indexes_remove[b] - c = edges_child[e] - i = nodes_individual[c] - if i != tskit.NULL and individuals_unphased[i]: - u, v = individuals_edges[i] - assert u == e or v == e - s = u if v == e else v - individuals_edges[i] = s, tskit.NULL - if s != tskit.NULL: # flush block - blocks_order.append(individuals_block[i]) - blocks_edges.extend([e, s]) - blocks_singletons.append(individuals_singletons[i]) - blocks_span.append(left - individuals_position[i]) - individuals_position[i] = np.nan - individuals_block[i] = tskit.NULL - individuals_singletons[i] = 0.0 - b += 1 - - while a < num_edges and position_insert[a] == left: # edges in - e = indexes_insert[a] - c = edges_child[e] - i = nodes_individual[c] - if i != tskit.NULL and individuals_unphased[i]: - u, v = individuals_edges[i] - assert u == tskit.NULL or v == tskit.NULL - individuals_edges[i] = [e, max(u, v)] - individuals_position[i] = left - if individuals_block[i] == tskit.NULL: - individuals_block[i] = num_blocks - num_blocks += 1 - a += 1 - - right = sequence_length - if b < num_edges: - right = min(right, position_remove[b]) - if a < num_edges: - right = min(right, position_insert[a]) - left = right - - while d < num_mutations and position_mutation[d] < right: # mutations - m = indexes_mutation[d] - c = mutations_node[m] - i = nodes_individual[c] - if i != tskit.NULL and individuals_unphased[i]: - mutations_block[m] = individuals_block[i] - individuals_singletons[i] += 1.0 - d += 1 - - mutations_block = mutations_block.astype(np.int32) - blocks_edges = np.array(blocks_edges, dtype=np.int32).reshape(-1, 2) - blocks_singletons = np.array(blocks_singletons) - blocks_span = np.array(blocks_span) - blocks_order = np.array(blocks_order) - blocks_stats = np.column_stack((blocks_singletons, blocks_span)) - assert num_blocks == blocks_edges.shape[0] == blocks_stats.shape[0] - - # sort block arrays so that mutations_block points to correct row - blocks_order = np.argsort(blocks_order) - blocks_edges = blocks_edges[blocks_order] - blocks_stats = blocks_stats[blocks_order] - - return blocks_stats, blocks_edges, mutations_block +reallocate_unphased = _tsdate.reallocate_unphased def block_singletons(ts, individuals_unphased): """ - TODO + Group the singleton mutations of unphased individuals into blocks: the regions + over which both edges above an individual's two nodes are unchanged. The + unphased individuals must be diploid and contemporary. + + :param tskit.TreeSequence ts: The tree sequence. + :param numpy.ndarray individuals_unphased: Boolean array, one entry per + individual, true for the individuals whose singletons are blocked. + :return: A tuple ``(blocks_stats, blocks_edges, mutations_block)``: + ``blocks_stats`` has one row per block, the number of singletons in the + block and its span; ``blocks_edges`` has one row per block, the two edges of + the block; ``mutations_block`` gives the block of each mutation, or + ``tskit.NULL`` for mutations outside the unphased individuals. + :raises ValueError: If an unphased individual is not diploid or not + contemporary. """ for i in ts.individuals(): if individuals_unphased[i.id]: @@ -190,98 +58,30 @@ def block_singletons(ts, individuals_unphased): raise ValueError("Singleton blocking assumes contemporary individuals") # TODO: adjust spans by an accessibility mask - return _block_singletons( - individuals_unphased, - ts.nodes_individual, - ts.mutations_node, - ts.sites_position[ts.mutations_site], - ts.edges_parent, - ts.edges_child, - ts.edges_left, - ts.edges_right, - ts.indexes_edge_insertion_order, - ts.indexes_edge_removal_order, - ts.sequence_length, + return _tsdate.block_singletons( + individuals_unphased=individuals_unphased, + nodes_individual=ts.nodes_individual, + mutations_node=ts.mutations_node, + mutations_position=ts.sites_position[ts.mutations_site], + edges_child=ts.edges_child, + edges_left=ts.edges_left, + edges_right=ts.edges_right, + indexes_insert=ts.indexes_edge_insertion_order, + indexes_remove=ts.indexes_edge_removal_order, + sequence_length=ts.sequence_length, ) -@numba_jit(_i2w(_b2r, _i1r, _f1r, _i1r, _i1r, _f1r, _f1r, _i1r, _i1r, _f)) -def _mutation_frequency( - nodes_sample, - mutations_node, - mutations_position, - edges_parent, - edges_child, - edges_left, - edges_right, - indexes_insert, - indexes_remove, - sequence_length, -): - """ - TODO - """ - assert edges_parent.size == edges_child.size == edges_left.size == edges_right.size - assert indexes_insert.size == indexes_remove.size == edges_parent.size - assert mutations_node.size == mutations_position.size - - num_nodes, num_sample_sets = nodes_sample.shape - num_mutations = mutations_node.size - num_edges = edges_parent.size - - indexes_mutation = np.argsort(mutations_position) - position_insert = edges_left[indexes_insert] - position_remove = edges_right[indexes_remove] - position_mutation = mutations_position[indexes_mutation] - - nodes_parent = np.full(num_nodes, tskit.NULL) - nodes_samples = np.zeros((num_nodes, num_sample_sets), dtype=np.int32) - mutations_freq = np.zeros((num_mutations, num_sample_sets), dtype=np.int32) - - # TODO: there's a better way than passing a big bool array - for i in range(num_sample_sets): - nodes_samples[nodes_sample[:, i], i] = 1.0 - - left = 0.0 - a, b, d = 0, 0, 0 - while a < num_edges or b < num_edges: - while b < num_edges and position_remove[b] == left: # edges out - e = indexes_remove[b] - p, c = edges_parent[e], edges_child[e] - nodes_parent[c] = tskit.NULL - while p != tskit.NULL: - nodes_samples[p] -= nodes_samples[c] - p = nodes_parent[p] - b += 1 - - while a < num_edges and position_insert[a] == left: # edges in - e = indexes_insert[a] - p, c = edges_parent[e], edges_child[e] - nodes_parent[c] = p - while p != tskit.NULL: - nodes_samples[p] += nodes_samples[c] - p = nodes_parent[p] - a += 1 - - right = sequence_length - if b < num_edges: - right = min(right, position_remove[b]) - if a < num_edges: - right = min(right, position_insert[a]) - left = right - - while d < num_mutations and position_mutation[d] < right: - m = indexes_mutation[d] - c = mutations_node[m] - mutations_freq[m] = nodes_samples[c] - d += 1 - - return mutations_freq - - def mutation_frequency(ts, sample_sets=None): """ - TODO + The number of samples of each sample set that carry each mutation, that is the + samples below the mutation's node in the tree at its position. + + :param tskit.TreeSequence ts: The tree sequence. + :param list sample_sets: A list of lists of sample node ids (default: one set of + all samples). + :return: An integer array of shape ``(num_mutations, num_sample_sets)``, with + dimensions of size one removed (so 1-d for a single sample set). """ if sample_sets is None: sample_sets = [list(ts.samples())] @@ -291,17 +91,17 @@ def mutation_frequency(ts, sample_sets=None): assert min(s) >= 0 and max(s) < ts.num_samples, "Sample out of range" # NOQA: PT018 nodes_sample[s, i] = True - return _mutation_frequency( - nodes_sample, - ts.mutations_node, - ts.sites_position[ts.mutations_site], - ts.edges_parent, - ts.edges_child, - ts.edges_left, - ts.edges_right, - ts.indexes_edge_insertion_order, - ts.indexes_edge_removal_order, - ts.sequence_length, + return _tsdate.mutation_frequency( + nodes_sample=nodes_sample, + mutations_node=ts.mutations_node, + mutations_position=ts.sites_position[ts.mutations_site], + edges_parent=ts.edges_parent, + edges_child=ts.edges_child, + edges_left=ts.edges_left, + edges_right=ts.edges_right, + indexes_insert=ts.indexes_edge_insertion_order, + indexes_remove=ts.indexes_edge_removal_order, + sequence_length=ts.sequence_length, ).squeeze() diff --git a/tsdate/prior.py b/tsdate/prior.py index 2cb0095f..7c8c722d 100644 --- a/tsdate/prior.py +++ b/tsdate/prior.py @@ -28,6 +28,7 @@ import os from collections import defaultdict, namedtuple +import _tsdate import numpy as np import scipy.cluster import scipy.special @@ -36,7 +37,6 @@ from tqdm.auto import tqdm from . import cache, demography, node_time_class, provenance, util -from .accelerate import numba_jit #: The default value for `approx_prior_size` (see :func:`~tsdate.build_prior_grid` and #: :func:`~tsdate.build_parameter_grid`) @@ -67,55 +67,7 @@ def gamma_approx(mean, variance): return (mean**2) / variance, mean / variance -@numba_jit("float64[:, :](float64[:, :])") -def _marginalize_over_ancestors(val): - """ - Integrate an expectation over counts of extant ancestors. In a tree with - "n" tips, the probability that there are "a" extent ancestors when a - subtree of size "k" coalesces is hypergeometric-ish (Wuif & Donnelly 1998), - and may be calculated recursively over increasing "a" and decreasing "k" - (e.g. using recursive relationships for binomial coefficients). - """ - n, N = val.shape # number of tips, number of moments - pr_a_ln = [np.nan, np.nan, 0.0] # log Pr(a | k, n) - out = np.zeros((n + 1, N)) - for k in range(n - 1, 1, -1): - const = np.log(n - k) + np.log(k - 2) - np.log(k + 1) - for a in range(2, n - k + 2): - out[k] += np.exp(pr_a_ln[a]) * val[a] - if k > 2: # Pr(a | k, n) to Pr(a | k - 1, n) - pr_a_ln[a] += const - np.log(n - a - k + 2) - if k > 2: # Pr(n - k + 1 | k - 1, n) to Pr(n - k + 2 | k - 1, n) - pr_a_ln.append(pr_a_ln[-1] + np.log(n - k + 2) - np.log(k + 1) - const) - out[n] = val[1] - return out - - -@numba_jit("float64[:](uint64)") -def conditional_coalescent_variance(num_tips): - """ - Variance of node age conditional on the number of descendant leaves, under - the standard coalescent. Returns array indexed by number of descendant - leaves. - """ - - coal_rates = np.array( - [2 / (i * (i - 1)) if i > 1 else 0.0 for i in range(1, num_tips + 1)] - ) - - # hypoexponential mean and variance; e.g. conditional on the number of - # extant ancestors when the node coalesces, the expected time of - # coalescence is the sum of exponential RVs (Wuif and Donnelly 1998) - mean = coal_rates.copy() - variance = coal_rates.copy() ** 2 - for i in range(coal_rates.size - 2, 0, -1): - mean[i] += mean[i + 1] - variance[i] += variance[i + 1] - - # marginalize over number of ancestors using recursive algorithm - moments = _marginalize_over_ancestors(np.stack((mean, variance + mean**2), 1)) - - return moments[:, 1] - moments[:, 0] ** 2 +conditional_coalescent_variance = _tsdate.conditional_coalescent_variance class ConditionalCoalescentTimes: @@ -263,7 +215,8 @@ def precalculate_priors_for_approximation(self, precalc_approximation_n): prior_lookup_table = np.zeros((n, 2)) all_tips = np.arange(2, n + 1) prior_lookup_table[1:, 0] = all_tips / n - prior_lookup_table[1:, 1] = conditional_coalescent_variance(n + 1)[all_tips] + variance = conditional_coalescent_variance(num_tips=n + 1) + prior_lookup_table[1:, 1] = variance[all_tips] np.savetxt(self.get_precalc_cache(n), prior_lookup_table) return prior_lookup_table @@ -316,7 +269,7 @@ def tau_var_lookup(self, total_tips, all_tips): return interpolated_priors def tau_var_exact(self, total_tips, all_tips): - return conditional_coalescent_variance(total_tips)[all_tips] + return conditional_coalescent_variance(num_tips=total_tips)[all_tips] def mixture_expect_and_var(self, mixture, weight_by_log_span=False): """ diff --git a/tsdate/rescaling.py b/tsdate/rescaling.py index 3792011f..0878f133 100644 --- a/tsdate/rescaling.py +++ b/tsdate/rescaling.py @@ -23,189 +23,13 @@ Utilities for rescaling time according to a mutational clock """ -from math import inf, log - -import numba +import _tsdate import numpy as np import tskit -from .accelerate import numba_jit -from .approx import ( - _b, - _b1r, - _f, - _f1r, - _f1w, - _f2r, - _f2w, - _i, - _i1r, - _i1w, - _tuple, - _unituple, - approximate_gamma_iqr, -) -from .hypergeo import _gammainc_inv as gammainc_inv from .util import mutation_span_array # NOQA: F401 -@numba_jit(_i1w(_f1r, _i)) -def _fixed_changepoints(counts, epochs): - """ - Find breakpoints such that `counts` is divided roughly equally across `epochs` - """ - assert epochs > 0 - Y = np.append(0.0, np.cumsum(counts)) - Z = Y / Y[-1] - z = np.linspace(0, 1, epochs + 1) - e = np.searchsorted(Z, z, "right") - 1 - if e[0] > 0: - e[0] = 0 - if e[-1] < counts.size: - e[-1] = counts.size - return e.astype(np.int32) - - -@numba_jit(_i1w(_f1r, _f1r, _f, _f, _f)) -def _poisson_changepoints(counts, offset, penalty, min_counts, min_offset): - """ - Given Poisson counts and offsets for a sequence of observations, find the set - of changepoints for the Poisson rate that maximizes the profile likelihood - under a linear penalty on complexity (e.g. penalty == 2 is AIC). - - See: "Optimal detection of changepoints with a linear computation cost" - (https://doi.org/10.1080/01621459.2012.737745) - """ - - assert counts.size == offset.size - assert min_counts >= 0 - assert min_offset >= 0 - assert penalty >= 0 - - N = np.append(0, np.cumsum(offset)) - Y = np.append(0, np.cumsum(counts)) - - def f(i, j): # loss - n = N[j] - N[i] - y = Y[j] - Y[i] - s = n < min_offset or y < min_counts - return inf if s else -2 * y * (log(y) - log(n) - 1) - - dim = counts.size - cost = np.empty(dim) - F = np.empty(dim + 1) - C = {0: np.empty(0, dtype=np.int64)} - - F[0] = -penalty - for j in np.arange(1, dim + 1): - argmin, minval = 0, np.inf - for i in C: # minimize - cost[i] = F[i] + f(i, j) + penalty - if cost[i] < minval: - minval = cost[i] - argmin = i - F[j] = minval - for i in set(C): # prune - if cost[i] > F[j] + penalty: - C.pop(i) - C[j] = np.append(C[argmin], argmin) - - breaks = np.append(C[dim], dim).astype(np.int32) - return breaks - - -@numba_jit( - _tuple((_f2w, _i1w))(_b1r, _i1r, _f1r, _i1r, _i1r, _f1r, _f1r, _i1r, _i1r, _f, _b) -) -def _count_mutations( - node_is_sample, - mutations_node, - mutations_position, - edges_parent, - edges_child, - edges_left, - edges_right, - indexes_insert, - indexes_remove, - sequence_length, - size_biased, -): - assert edges_parent.size == edges_child.size == edges_left.size == edges_right.size - assert indexes_insert.size == indexes_remove.size == edges_parent.size - assert mutations_node.size == mutations_position.size - - num_mutations = mutations_node.size - num_edges = edges_parent.size - num_nodes = node_is_sample.size - - indexes_mutation = np.argsort(mutations_position) - position_insert = edges_left[indexes_insert] - position_remove = edges_right[indexes_remove] - position_mutation = mutations_position[indexes_mutation] - - nodes_samples = np.zeros(num_nodes) - nodes_edge = np.full(num_nodes, tskit.NULL) - nodes_parent = np.full(num_nodes, tskit.NULL) - mutations_edge = np.full(num_mutations, tskit.NULL) - edges_mutations = np.zeros(num_edges) - edges_span = np.zeros(num_edges) - - nodes_samples[node_is_sample] = 1.0 - left = 0.0 - a, b, d = 0, 0, 0 - while a < num_edges or b < num_edges: - remainder = sequence_length - left - - while b < num_edges and position_remove[b] == left: # edges out - e = indexes_remove[b] - p, c = edges_parent[e], edges_child[e] - nodes_edge[c] = tskit.NULL - nodes_parent[c] = tskit.NULL - if size_biased: - while p != tskit.NULL: # downdate sample counts - edges_span[e] -= nodes_samples[c] * remainder - nodes_samples[p] -= nodes_samples[c] - e, p = nodes_edge[p], nodes_parent[p] - else: - edges_span[e] -= remainder - b += 1 - - while a < num_edges and position_insert[a] == left: # edges in - e = indexes_insert[a] - p, c = edges_parent[e], edges_child[e] - nodes_edge[c] = e - nodes_parent[c] = p - if size_biased: - while p != tskit.NULL: # update sample counts - edges_span[e] += nodes_samples[c] * remainder - nodes_samples[p] += nodes_samples[c] - e, p = nodes_edge[p], nodes_parent[p] - else: - edges_span[e] += remainder - a += 1 - - right = sequence_length - if b < num_edges: - right = min(right, position_remove[b]) - if a < num_edges: - right = min(right, position_insert[a]) - left = right - - while d < num_mutations and position_mutation[d] < right: - m = indexes_mutation[d] - c = mutations_node[m] - e = nodes_edge[c] - if e != tskit.NULL: - mutations_edge[m] = e - edges_mutations[e] += nodes_samples[c] if size_biased else 1.0 - d += 1 - - mutations_edge = mutations_edge.astype(np.int32) - edges_stats = np.column_stack((edges_mutations, edges_span)) - - return edges_stats, mutations_edge - - def count_mutations(ts, node_is_sample=None, size_biased=False): """ Return an array with `num_edges` rows, and columns that are the number of @@ -222,233 +46,40 @@ def count_mutations(ts, node_is_sample=None, size_biased=False): node_is_sample = np.full(ts.num_nodes, False) node_is_sample[list(ts.samples())] = True else: - assert node_is_sample.size != ts.num_nodes - - return _count_mutations( - node_is_sample, - ts.mutations_node, - ts.sites_position[ts.mutations_site], - ts.edges_parent, - ts.edges_child, - ts.edges_left, - ts.edges_right, - ts.indexes_edge_insertion_order, - ts.indexes_edge_removal_order, - ts.sequence_length, - size_biased, + assert node_is_sample.size == ts.num_nodes + + return _tsdate.count_mutations( + nodes_sample=node_is_sample, + mutations_node=ts.mutations_node, + mutations_position=ts.sites_position[ts.mutations_site], + edges_parent=ts.edges_parent, + edges_child=ts.edges_child, + edges_left=ts.edges_left, + edges_right=ts.edges_right, + indexes_insert=ts.indexes_edge_insertion_order, + indexes_remove=ts.indexes_edge_removal_order, + sequence_length=ts.sequence_length, + size_biased=size_biased, ) -@numba_jit(_tuple((_f1w, _f1w, _f1w, _i1w))(_f1r, _f2r, _i1r, _i1r)) -def mutational_area( - nodes_time, - likelihoods, - edges_parent, - edges_child, -): - """ - Calculate the total number of mutations and mutational area per inter-node - interval. These are infinitesimal; e.g. the actual count in an interval is - `returned_count * duration`. - - :param np.ndarray nodes_time: point estimates for node ages - :param np.ndarray likelihoods: edges are rows; mutation - counts and mutational span are columns - :param np.ndarray edges_parent: node index for the parent of each edge - :param np.ndarray edges_child: node index for the child of each edge - :param np.ndarray edges_weight: a weight for each edge - """ - - assert edges_parent.size == edges_child.size - assert likelihoods.shape == (edges_parent.size, 2) - - # index node by unique time breaks - nodes_order = np.argsort(nodes_time) - nodes_index = np.zeros(nodes_time.size, dtype=np.int32) - epoch_breaks = [0.0] - k = 0 - for i, j in zip(nodes_order[1:], nodes_order[:-1]): - if nodes_time[i] > nodes_time[j]: - epoch_breaks.append(nodes_time[i]) - k += 1 - nodes_index[i] = k - epoch_breaks = np.array(epoch_breaks) - num_epochs = epoch_breaks.size - 1 - - # instantaneous mutation rate per edge - edges_length = nodes_time[edges_parent] - nodes_time[edges_child] - edges_subset = edges_length > 0 - edges_counts = likelihoods.copy() - edges_counts[edges_subset, 0] /= edges_length[edges_subset] - - # pass over edges, measuring overlap with each time interval - epoch_counts = np.zeros((num_epochs, 2)) - for e in np.flatnonzero(edges_subset): - p, c = edges_parent[e], edges_child[e] - a, b = nodes_index[c], nodes_index[p] - if a < num_epochs: - epoch_counts[a] += edges_counts[e] - if b < num_epochs: - epoch_counts[b] -= edges_counts[e] - counts = np.cumsum(epoch_counts[:, 0]) - offset = np.cumsum(epoch_counts[:, 1]) - duration = np.diff(epoch_breaks) - - return counts, offset, duration, nodes_index - - -# --- version before refactor, keeping around for reference --- -# @numba_jit(_unituple(_f1w, 2)(_f1r, _f2r, _f2r, _i1r, _i1r, _f1r, _i)) -# def mutational_timescale( -# nodes_time, -# likelihoods, -# constraints, -# edges_parent, -# edges_child, -# edges_weight, -# max_intervals, -# ): -# """ -# Rescale node ages so that the instantaneous mutation rate is constant. -# Edges with a negative duration are ignored when calculating the total -# rate. Returns a rescaled point estimate and the posterior. -# -# :param np.ndarray nodes_time: point estimates for node ages -# :param np.ndarray likelihoods: edges are rows; mutation -# counts and mutational span are columns -# :param np.ndarray constraints: lower and upper bounds on node age -# :param np.ndarray edges_parent: node index for the parent of each edge -# :param np.ndarray edges_child: node index for the child of each edge -# :param np.ndarray edges_weight: a weight for each edge -# :param int max_intervals: maximum number of intervals within which to -# estimate the time scaling -# """ -# -# assert edges_parent.size == edges_child.size == edges_weight.size -# assert likelihoods.shape[0] == edges_parent.size and likelihoods.shape[1] == 2 -# assert constraints.shape[0] == nodes_time.size and constraints.shape[1] == 2 -# assert max_intervals > 0 -# -# nodes_fixed = constraints[:, 0] == constraints[:, 1] -# assert np.all(nodes_time[nodes_fixed] == constraints[nodes_fixed, 0]) -# -# # index node by unique time breaks -# nodes_order = np.argsort(nodes_time) -# nodes_index = np.zeros(nodes_time.size, dtype=np.int32) -# epoch_breaks = [0.0] -# k = 0 -# for i, j in zip(nodes_order[1:], nodes_order[:-1]): -# if nodes_time[i] > nodes_time[j]: -# epoch_breaks.append(nodes_time[i]) -# k += 1 -# nodes_index[i] = k -# epoch_breaks = np.array(epoch_breaks) -# epoch_length = np.diff(epoch_breaks) -# num_epochs = epoch_length.size -# -# # instantaneous mutation rate per edge -# edges_length = nodes_time[edges_parent] - nodes_time[edges_child] -# edges_subset = edges_length > 0 -# edges_counts = likelihoods.copy() -# edges_counts[edges_subset, 0] /= edges_length[edges_subset] -# -# # pass over edges, measuring overlap with each time interval -# epoch_counts = np.zeros((num_epochs, 2)) -# for e in np.flatnonzero(edges_subset): -# p, c = edges_parent[e], edges_child[e] -# a, b = nodes_index[c], nodes_index[p] -# if a < num_epochs: -# epoch_counts[a] += edges_counts[e] * edges_weight[e] -# if b < num_epochs: -# epoch_counts[b] -= edges_counts[e] * edges_weight[e] -# counts = np.cumsum(epoch_counts[:, 0]) -# offset = np.cumsum(epoch_counts[:, 1]) -# -# # rescale time such that mutation density is constant between changepoints -# # TODO: use poisson changepoints to further refine -# changepoints = _fixed_changepoints(offset * epoch_length, max_intervals) -# changepoints = np.union1d(changepoints, nodes_index[nodes_fixed]) -# adjust = np.zeros(changepoints.size) -# k = 0 -# for i, j in zip(changepoints[:-1], changepoints[1:]): -# assert j > i -# # TODO: when changepoint intersects a fixed node? -# n = np.sum(offset[i:j]) -# y = np.sum(counts[i:j]) -# z = np.sum(epoch_length[i:j]) -# assert n > 0, "Zero edge span in interval" -# adjust[k + 1] = z * y / n -# k += 1 -# adjust = np.cumsum(adjust) -# origin = epoch_breaks[changepoints] -# -# return origin, adjust - - -@numba_jit(_unituple(_f1w, 2)(_f1r, _f2r, _b1r, _i1r, _i1r, _i)) -def mutational_timescale( - nodes_time, - likelihoods, - nodes_fixed, - edges_parent, - edges_child, - max_intervals, -): - """ - Rescale node ages so that the instantaneous mutation rate is constant. - Edges with a negative duration are ignored when calculating the total - rate. Returns a rescaled point estimate and the posterior. +mutational_area = _tsdate.mutational_area - :param np.ndarray nodes_time: point estimates for node ages - :param np.ndarray likelihoods: edges are rows; mutation - counts and mutational span are columns - :param np.ndarray constraints: lower and upper bounds on node age - :param np.ndarray edges_parent: node index for the parent of each edge - :param np.ndarray edges_child: node index for the child of each edge - :param int max_intervals: maximum number of intervals within which to - estimate the time scaling - """ - - assert edges_parent.size == edges_child.size - assert likelihoods.shape[0] == edges_parent.size - assert likelihoods.shape[1] == 2 - assert nodes_fixed.size == nodes_time.size - assert max_intervals > 0 - - counts, offset, duration, indexes = mutational_area( - nodes_time, - likelihoods, - edges_parent, - edges_child, - ) - # rescale time such that mutation density is constant between changepoints - # TODO: use poisson changepoints to further refine - epoch_breaks = np.append(0.0, np.cumsum(duration)) - changepoints = _fixed_changepoints(offset * duration, max_intervals) - changepoints = np.unique(changepoints) - # changepoints = np.union1d(changepoints, indexes[nodes_fixed]) - adjust = np.zeros(changepoints.size) +mutational_timescale = _tsdate.mutational_timescale - # --- without any internal constraints --- - k = 0 - for i, j in zip(changepoints[:-1], changepoints[1:]): - assert j > i - # TODO: when changepoint intersects a fixed node? - n = np.sum(offset[i:j]) - y = np.sum(counts[i:j]) - z = np.sum(duration[i:j]) - assert n > 0, "Zero edge span in interval" - adjust[k + 1] = z * y / n - k += 1 - adjust = np.cumsum(adjust) - origin = epoch_breaks[changepoints] - - return origin, adjust +def _check_increasing_breaks(original_breaks, rescaled_breaks): + if not np.all(np.diff(rescaled_breaks) > 0) or not np.all( + np.diff(original_breaks) > 0 + ): + raise ValueError( + "Rescaling produced non-increasing time breakpoints. " + "Try setting `rescaling_intervals` to a smaller value " + "(e.g. half its current value)." + ) -@numba.njit(_f2w(_f2r, _b1r, _f1r, _f1r, _f, _f)) def piecewise_scale_posterior( posteriors, posteriors_fixed, @@ -457,96 +88,27 @@ def piecewise_scale_posterior( quantile_width, max_shape, ): - """ - :param np.ndarray posteriors_fixed: if True do not rescale corresponding posterior - :param float quantile_width: width of interquantile range to use for estimating - rescaled shape parameter, e.g. 0.5 uses interquartile range - """ - - assert posteriors_fixed.size == posteriors.shape[0] - assert original_breaks.size == rescaled_breaks.size - assert 1 > quantile_width > 0 - - if not np.all(np.diff(rescaled_breaks) > 0): - raise ValueError( - "Rescaling produced non-increasing time breakpoints. " - "Try setting `rescaling_intervals` to a smaller value " - "(e.g. half its current value)." - ) - if not np.all(np.diff(original_breaks) > 0): - raise ValueError( - "Rescaling produced non-increasing time breakpoints. " - "Try setting `rescaling_intervals` to a smaller value " - "(e.g. half its current value)." - ) - - dim = posteriors.shape[0] - quant_lower = quantile_width / 2 - quant_upper = 1 - quantile_width / 2 - - freed = ~posteriors_fixed - assert np.all(np.logical_and(posteriors[freed, 0] > -1, posteriors[freed, 1] > 0)) - - # use posterior mean as a point estimate - lower = np.zeros(dim) - upper = np.zeros(dim) - midpt = np.zeros(dim) - for i in np.flatnonzero(freed): - alpha, beta = posteriors[i] - lower[i] = gammainc_inv(alpha + 1, quant_lower) / beta - upper[i] = gammainc_inv(alpha + 1, quant_upper) / beta - midpt[i] = (alpha + 1) / beta - - # rescale quantiles - scalings = np.append(np.diff(rescaled_breaks) / np.diff(original_breaks), 0) - - def rescale(x): - i = np.searchsorted(original_breaks, x, "right") - 1 - assert i.min() >= 0 # DEBUG - assert i.max() < scalings.size # DEBUG - return rescaled_breaks[i] + scalings[i] * (x - original_breaks[i]) - - midpt = rescale(midpt) - lower = rescale(lower) - upper = rescale(upper) - - # reproject posteriors using inter-quantile range - new_posteriors = np.full(posteriors.shape, np.nan) - for i in np.flatnonzero(freed): - alpha, beta = approximate_gamma_iqr( - quant_lower, quant_upper, lower[i], upper[i], max_shape - ) - beta = (alpha + 1) / midpt[i] # choose rate so as to keep mean - new_posteriors[i] = alpha, beta - - return new_posteriors + _check_increasing_breaks(original_breaks, rescaled_breaks) + return _tsdate.piecewise_scale_posterior( + posteriors=posteriors, + posteriors_fixed=posteriors_fixed, + original_breaks=original_breaks, + rescaled_breaks=rescaled_breaks, + quantile_width=quantile_width, + max_shape=max_shape, + ) -@numba_jit(_f1w(_f1r, _b1r, _f1r, _f1r)) def piecewise_scale_point_estimate( - point_estimate, - point_fixed, - original_breaks, - rescaled_breaks, + point_estimate, point_fixed, original_breaks, rescaled_breaks ): - if not np.all(np.diff(rescaled_breaks) > 0): - raise ValueError( - "Rescaling produced non-increasing time breakpoints. " - "Try setting `rescaling_intervals` to a smaller value " - "(e.g. half its current value)." - ) - if not np.all(np.diff(original_breaks) > 0): - raise ValueError( - "Rescaling produced non-increasing time breakpoints. " - "Try setting `rescaling_intervals` to a smaller value " - "(e.g. half its current value)." - ) - scalings = np.append(np.diff(rescaled_breaks) / np.diff(original_breaks), 0) - idx = np.searchsorted(original_breaks, point_estimate, "right") - 1 - rescaled_estimate = rescaled_breaks[idx] + \ - scalings[idx] * (point_estimate - original_breaks[idx]) # fmt: skip - rescaled_estimate[point_fixed] = point_estimate[point_fixed] - return rescaled_estimate + _check_increasing_breaks(original_breaks, rescaled_breaks) + return _tsdate.piecewise_scale_point_estimate( + point_estimate=point_estimate, + point_fixed=point_fixed, + original_breaks=original_breaks, + rescaled_breaks=rescaled_breaks, + ) # standalone API for rescaling (TODO: needs testing) @@ -589,12 +151,12 @@ def rescale_tree_sequence( nodes_time = ts.nodes_time.copy() for _ in np.arange(num_iterations): original_breaks, rescaled_breaks = mutational_timescale( - nodes_time, - mutations_span, - constraints, - ts.edges_parent, - ts.edges_child, - num_intervals, + nodes_time=nodes_time, + edges_likelihood=mutations_span, + nodes_fixed=constraints, + edges_parent=ts.edges_parent, + edges_child=ts.edges_child, + max_intervals=num_intervals, ) nodes_time = piecewise_scale_point_estimate( nodes_time, fixed_nodes, original_breaks, rescaled_breaks diff --git a/tsdate/util.py b/tsdate/util.py index a31e0960..8e833e99 100644 --- a/tsdate/util.py +++ b/tsdate/util.py @@ -28,15 +28,13 @@ import logging import time +import _tsdate import numpy as np import tskit -from numba.types import UniTuple as _unituple # NOQA: N813 import tsdate from . import provenance -from .accelerate import numba_jit -from .approx import _b, _b1r, _f, _f1r, _f1w, _i, _i1r, _i1w logger = logging.getLogger(__name__) @@ -373,7 +371,6 @@ def mutation_span_array(tree_sequence): # Some functions for changing tskit metadata # See https://github.com/tskit-dev/tskit/discussions/2954 -# TODO - potentially possible to speed up using numba? def _reorder_nodes(node_table, order, extra_md_dict): # extra_md_dict ({rowid: new_byte_metadata}) can be used to pass metadata to replace # the existing metadata in a row. This works by creating new rows for the metadata, @@ -405,123 +402,6 @@ def _reorder_nodes(node_table, order, extra_md_dict): ) -@numba_jit(_unituple(_i1w, 4)(_i1r, _i1r, _f1r, _f1r, _b1r)) -def _split_disjoint_nodes( - edges_parent, edges_child, edges_left, edges_right, node_excluded -): - """ - Split disconnected regions of nodes into separate nodes. - - Returns updated edges_parent, edges_child, mutations_node, and indices indicating - from which original node the new nodes are derived. - """ - assert edges_parent.size == edges_child.size == edges_left.size == edges_right.size - num_edges = edges_parent.size - num_nodes = node_excluded.size - - # For each edge, check whether parent/child is separated by a gap from the - # previous edge involving either parent/child. Label disconnected segments - # per node by integers starting at zero. - edges_order = np.argsort(edges_left) - # TODO: is a sort really needed here? - edges_segments = np.full((2, num_edges), -1, dtype=np.int32) - nodes_segments = np.full(num_nodes, -1, dtype=np.int32) - nodes_right = np.full(node_excluded.size, -np.inf, dtype=np.float64) - for e in edges_order: - nodes = edges_parent[e], edges_child[e] - for i, n in enumerate(nodes): - if node_excluded[n]: - continue - nodes_segments[n] += edges_left[e] > nodes_right[n] - edges_segments[i, e] = nodes_segments[n] - nodes_right[n] = max(nodes_right[n], edges_right[e]) - - # Create "nodes_segments[i]" supplementary nodes by copying node "i". - # Store the id of the first supplement for each node in "nodes_map". - split_nodes = [] # the nodes in the original that were split - nodes_map = np.full(num_nodes, -1, dtype=np.int32) - for i, s in enumerate(nodes_segments): - for j in range(s): - if j == 0: - nodes_map[i] = num_nodes - split_nodes.append(i) - num_nodes += 1 - split_nodes = np.array(split_nodes, dtype=np.int32) - nodes_order = np.arange(num_nodes, dtype=np.int32) - if len(split_nodes) > 0: - nodes_order[-len(split_nodes) :] = split_nodes - - # Relabel the nodes on each edge given "nodes_map" - for e in edges_order: - nodes = edges_parent[e], edges_child[e] - for i, n in enumerate(nodes): - if edges_segments[i, e] > 0: - edges_segments[i, e] += nodes_map[n] - 1 - else: - edges_segments[i, e] = n - edges_parent, edges_child = edges_segments[0, ...], edges_segments[1, ...] - - return edges_parent, edges_child, nodes_order, split_nodes - - -@numba_jit(_i1w(_i1r, _f1r, _i1r, _i1r, _i1r, _f1r, _f1r, _i1r, _i1r)) -def _relabel_mutations_node( - mutations_node, - mutations_position, - nodes_order, - edges_parent, - edges_child, - edges_left, - edges_right, - insert_index, - remove_index, -): - """ - Traverse trees, maintaining a mapping between old and new node IDs in the - current tree. Update `mutations_node` to reflect new IDs. - """ - assert edges_parent.size == edges_child.size == edges_left.size == edges_right.size - assert edges_parent.size == insert_index.size == remove_index.size - assert mutations_position.size == mutations_node.size - - num_nodes = nodes_order.size - num_edges = edges_parent.size - num_mutations = mutations_position.size - - insert_position = edges_left[insert_index] - remove_position = edges_right[remove_index] - sequence_length = remove_position[-1] - - output = np.full(num_mutations, tskit.NULL, dtype=np.int32) - nodes_map = np.full(num_nodes, tskit.NULL, dtype=np.int32) - a, b, m = 0, 0, 0 - left = 0.0 - while left < sequence_length: - while b < num_edges and remove_position[b] == left: # edges out - b += 1 - - while a < num_edges and insert_position[a] == left: # edges in - e = insert_index[a] - c, p = edges_child[e], edges_parent[e] - nodes_map[nodes_order[c]] = c - nodes_map[nodes_order[p]] = p - a += 1 - - right = sequence_length - if b < num_edges: - right = min(right, remove_position[b]) - if a < num_edges: - right = min(right, insert_position[a]) - left = right - - while m < num_mutations and mutations_position[m] < right: - assert nodes_map[mutations_node[m]] != tskit.NULL - output[m] = nodes_map[mutations_node[m]] - m += 1 - - return output - - def split_disjoint_nodes(ts, *, record_provenance=None): """ For each non-sample node, split regions separated by gaps into distinct @@ -545,24 +425,24 @@ def split_disjoint_nodes(ts, *, record_provenance=None): if record_provenance is None: record_provenance = True node_is_sample = np.bitwise_and(ts.nodes_flags, tskit.NODE_IS_SAMPLE).astype(bool) - edges_parent, edges_child, nodes_order, split_nodes = _split_disjoint_nodes( - ts.edges_parent, - ts.edges_child, - ts.edges_left, - ts.edges_right, - node_is_sample, + edges_parent, edges_child, nodes_order, split_nodes = _tsdate.split_disjoint_nodes( + edges_parent=ts.edges_parent, + edges_child=ts.edges_child, + edges_left=ts.edges_left, + edges_right=ts.edges_right, + nodes_excluded=node_is_sample, ) - mutations_node = _relabel_mutations_node( - ts.mutations_node, - ts.sites_position[ts.mutations_site], - nodes_order, - edges_parent, - edges_child, - ts.edges_left, - ts.edges_right, - ts.indexes_edge_insertion_order, - ts.indexes_edge_removal_order, + mutations_node = _tsdate.relabel_mutations_node( + mutations_node=ts.mutations_node, + mutations_position=ts.sites_position[ts.mutations_site], + nodes_order=nodes_order, + edges_parent=edges_parent, + edges_child=edges_child, + edges_left=ts.edges_left, + edges_right=ts.edges_right, + indexes_insert=ts.indexes_edge_insertion_order, + indexes_remove=ts.indexes_edge_removal_order, ) tables = ts.dump_tables() @@ -596,60 +476,6 @@ def split_disjoint_nodes(ts, *, record_provenance=None): return tables.tree_sequence() -@numba_jit(_f1w(_f1r, _b1r, _i1r, _i1r, _f, _i)) -def _constrain_ages( - nodes_time, nodes_fixed, edges_parent, edges_child, epsilon, max_iterations -): - """ - Approximate least squares solution to the positive branch length - constraint, using the method of alternating projections. Loosely based on - Dykstra's algorithm, see: - - Dykstra RL, "An algorithm for restricted least squares regression", JASA - 1983 - """ - assert nodes_time.size == nodes_fixed.size - assert edges_parent.size == edges_child.size - - num_edges = edges_parent.size - nodes_time = nodes_time.copy() - edges_cavity = np.zeros((num_edges, 2)) - for _ in range(max_iterations): # method of alternating projections - if np.all(nodes_time[edges_parent] - nodes_time[edges_child] > epsilon): - return nodes_time - for e in range(num_edges): - p, c = edges_parent[e], edges_child[e] - nodes_time[c] -= edges_cavity[e, 0] - nodes_time[p] -= edges_cavity[e, 1] - adjustment = nodes_time[c] - nodes_time[p] # + epsilon - edges_cavity[e, :] = 0.0 - if adjustment > 0: - assert not (nodes_fixed[c] and nodes_fixed[p]) - if not nodes_fixed[c] and not nodes_fixed[p]: - edges_cavity[e, 0] = -adjustment / 2 - edges_cavity[e, 1] = adjustment / 2 - elif nodes_fixed[c] and not nodes_fixed[p]: - edges_cavity[e, 0] = 0 - edges_cavity[e, 1] = adjustment - elif not nodes_fixed[c] and nodes_fixed[p]: - edges_cavity[e, 0] = -adjustment - edges_cavity[e, 1] = 0 - nodes_time[c] += edges_cavity[e, 0] - nodes_time[p] += edges_cavity[e, 1] - # print( - # "min length:", np.min(nodes_time[edges_parent] - nodes_time[edges_child]) - # ) - - # force remaining constraint, which can change the ages of fixed nodes - for e in range(num_edges): - p, c = edges_parent[e], edges_child[e] - # TODO: even if nodes_fixed[p], this will still change the age - if nodes_time[c] + epsilon >= nodes_time[p]: - nodes_time[p] = nodes_time[c] + epsilon - - return nodes_time - - def constrain_ages(ts, nodes_time, epsilon=1e-6, max_iterations=0): """ Use a hybrid approach to adjust node times such that branch lengths are @@ -676,13 +502,13 @@ def constrain_ages(ts, nodes_time, epsilon=1e-6, max_iterations=0): assert max_iterations >= 0 nodes_fixed = np.bitwise_and(ts.nodes_flags, tskit.NODE_IS_SAMPLE).astype(bool) - constrained_nodes_time = _constrain_ages( - nodes_time, - nodes_fixed, - ts.edges_parent, - ts.edges_child, - epsilon, - max_iterations, + constrained_nodes_time = _tsdate.constrain_ages( + nodes_time=nodes_time, + nodes_fixed=nodes_fixed, + edges_parent=ts.edges_parent, + edges_child=ts.edges_child, + epsilon=epsilon, + max_iterations=max_iterations, ) modified = np.sum(~np.isclose(nodes_time, constrained_nodes_time)) logging.info(f"Modified ages of {modified} nodes to satisfy constraints") @@ -690,58 +516,6 @@ def constrain_ages(ts, nodes_time, epsilon=1e-6, max_iterations=0): return constrained_nodes_time -@numba_jit(_b(_b1r, _i1r, _f1r, _f1r, _i1r, _i1r, _f, _i)) -def _contains_unary_nodes( - nodes_mask, - edges_parent, - edges_left, - edges_right, - indexes_insert, - indexes_remove, - sequence_length, - num_nodes, -): - assert edges_parent.size == edges_left.size == edges_right.size - assert indexes_insert.size == indexes_remove.size == edges_parent.size - - num_edges = edges_parent.size - nodes_children = np.zeros(num_nodes, dtype=np.int32) - position_insert = edges_left[indexes_insert] - position_remove = edges_right[indexes_remove] - - left = 0.0 - a, b = 0, 0 - while a < num_edges or b < num_edges: - check = set() - - while b < num_edges and position_remove[b] == left: # edges out - e = indexes_remove[b] - p = edges_parent[e] - nodes_children[p] -= 1 - check.add(p) - b += 1 - - while a < num_edges and position_insert[a] == left: # edges in - e = indexes_insert[a] - p = edges_parent[e] - nodes_children[p] += 1 - check.add(p) - a += 1 - - for p in check: - if not nodes_mask[p] and nodes_children[p] == 1: - return True - - right = sequence_length - if b < num_edges: - right = min(right, position_remove[b]) - if a < num_edges: - right = min(right, position_insert[a]) - left = right - - return False - - def contains_unary_nodes(ts, skip_samples=True): """ Check if any internal node in the tree sequence is unary over some portion @@ -753,15 +527,14 @@ def contains_unary_nodes(ts, skip_samples=True): if skip_samples: nodes_mask[list(ts.samples())] = True - return _contains_unary_nodes( - nodes_mask, - ts.edges_parent, - ts.edges_left, - ts.edges_right, - ts.indexes_edge_insertion_order, - ts.indexes_edge_removal_order, - ts.sequence_length, - ts.num_nodes, + return _tsdate.contains_unary_nodes( + nodes_mask=nodes_mask, + edges_parent=ts.edges_parent, + edges_left=ts.edges_left, + edges_right=ts.edges_right, + indexes_insert=ts.indexes_edge_insertion_order, + indexes_remove=ts.indexes_edge_removal_order, + sequence_length=ts.sequence_length, ) diff --git a/tsdate/variational.py b/tsdate/variational.py index 0056e6bc..438352b2 100644 --- a/tsdate/variational.py +++ b/tsdate/variational.py @@ -27,15 +27,11 @@ import logging import time -import numba +import _tsdate import numpy as np import tskit -from numba.types import void as _void from tqdm.auto import tqdm -from . import approx -from .accelerate import numba_jit -from .approx import _b, _b1r, _f, _f1r, _f1w, _f2r, _f2w, _f3w, _i, _i1r from .phasing import block_singletons, reallocate_unphased from .rescaling import ( count_mutations, @@ -69,131 +65,6 @@ TINY = np.sqrt(np.finfo(np.float64).tiny) # DEBUG -# dataclass for factors -_EPFactors = [ - ("node", _f3w), - ("edge", _f3w), - ("block", _f3w), - ("scale", _f1w), - ("_p", _i1r), - ("_c", _i1r), - ("_j", _i1r), - ("_k", _i1r), -] - - -@numba.experimental.jitclass(_EPFactors) -class EPFactors: - """ - Mutable state of the EP algorithm, that is the factors associated - with each edge likelihood / block likelihood / prior factor, that - together form the posterior. - - Because of constraints on numba's AOT compilation of jitclass, - this is a dataclass (no intrinsic methods). - """ - - def __init__( - self, - node_constraints, - edge_parents, - edge_children, - block_left, - block_right, - ): - assert edge_parents.size == edge_children.size - assert block_left.size == block_right.size - num_nodes = node_constraints.shape[0] - num_edges = edge_parents.size - num_blocks = block_left.size - self.node = np.zeros((num_nodes, 2, 2)) - self.edge = np.zeros((num_edges, 2, 2)) - self.block = np.zeros((num_blocks, 2, 2)) - self.scale = np.ones(num_nodes) - self._p, self._c = edge_parents, edge_children - self._j, self._k = block_left, block_right - - -# bypass bug in https://github.com/numba/numba/issues/7808 -_fac = numba.deferred_type() if numba.config.DISABLE_JIT \ - else EPFactors.class_type.instance_type # fmt: skip - - -# helper functions for numerical stability -@numba_jit(_void(_fac)) -def _rescale_factors(factors): - """ - At each update, all factors associated with a node need to be rescaled. - This is expensive, so we keep track of the scaling in a separate vector. - As updates progress, the factors will drift upward in magnitude while - the scaling drifts downward. To avoid underflow, we may need to - cancel out the scaling. - """ - factors.edge[:, ROOTWARD] *= factors.scale[factors._p, np.newaxis] - factors.edge[:, LEAFWARD] *= factors.scale[factors._c, np.newaxis] - factors.block[:, ROOTWARD] *= factors.scale[factors._j, np.newaxis] - factors.block[:, LEAFWARD] *= factors.scale[factors._k, np.newaxis] - factors.node[:, MIXPRIOR] *= factors.scale[:, np.newaxis] - factors.node[:, CONSTRNT] *= factors.scale[:, np.newaxis] - factors.scale[:] = 1.0 - - -@numba_jit(_f2w(_fac)) -def _assemble_factors(factors): - """ - Transform factors into posteriors, intended for debugging purposes only. - """ - posterior = np.zeros((factors.scale.size, 2)) - for i, (p, c) in enumerate(zip(factors._p, factors._c)): - posterior[p] += factors.edge[i, ROOTWARD] - posterior[c] += factors.edge[i, LEAFWARD] - for i, (j, k) in enumerate(zip(factors._j, factors._k)): - posterior[j] += factors.block[i, ROOTWARD] - posterior[k] += factors.block[i, LEAFWARD] - posterior += factors.node[:, MIXPRIOR] - posterior += factors.node[:, CONSTRNT] - return posterior - - -@numba_jit(_f(_f1r, _f1r, _f)) -def _damp(x, y, s): - """ - If `x - y` is too small, find `d` so that `x - d*y` is large enough: - - x[0] - d*y[0] + 1 >= (x[0] + 1)*s - x[1] - d*y[1] >= y[1]*s - - for `0 < s < 1`. - """ - assert x.size == y.size == 2 - if np.all(y == 0.0) and np.all(x == 0.0): - return 1.0 - assert 0 < s < 1 - assert 0.0 < x[0] + 1 - assert 0.0 < x[1] - a = 1.0 if (1 + x[0] - y[0] > (1 + x[0]) * s) else (1 - s) * (1 + x[0]) / y[0] - b = 1.0 if (x[1] - y[1] > x[1] * s) else (1 - s) * x[1] / y[1] - d = min(a, b) - assert 0.0 < d <= 1.0 - return d - - -@numba_jit(_f(_f1r, _f)) -def _rescale(x, s): - """ - Find `d` so that `d*x[0] + 1 <= s[0]` or `d*x[0] + 1 >= 1/s[0]` - """ - assert x.size == 2 - if np.all(x == 0.0): - return 1.0 - assert 0 < x[0] + 1 - assert 0 < x[1] - if 1 + x[0] > s: - return (s - 1) / x[0] - elif 1 + x[0] < 1 / s: - return (1 / s - 1) / x[0] - return 1.0 - # main algorithm class ExpectationPropagation: @@ -231,14 +102,13 @@ class ExpectationPropagation: """ @staticmethod - @numba_jit(_void(_f2r, _i1r, _i1r)) def _check_valid_constraints(constraints, edges_parent, edges_child): # Check that upper-bound on node age is greater than maximum lower-bound # for ages of descendants - lower_max = constraints[:, LOWER].copy() - for p, c in zip(edges_parent, edges_child): - lower_max[p] = max(lower_max[c], lower_max[p]) - if np.any(lower_max > constraints[:, UPPER]): + consistent = _tsdate.constraints_are_consistent( + constraints=constraints, edges_parent=edges_parent, edges_child=edges_child + ) + if not consistent: raise ValueError( "Node age constraints are inconsistent, some descendants have" " lower bounds that exceed upper bounds of their ancestors." @@ -251,14 +121,10 @@ def _check_valid_inputs(ts, mutation_rate, allow_unary): if not allow_unary and contains_unary_nodes(ts): raise ValueError("Tree sequence contains unary nodes, simplify first") - @staticmethod - def _check_valid_state( - posterior, - factors, - ): + def _check_valid_state(self): # Check that the messages sum to the posterior (debugging only) - posterior_check = _assemble_factors(factors) - np.testing.assert_allclose(posterior_check, posterior) + posterior_check = self._ep.assemble_factors() + np.testing.assert_allclose(posterior_check, self._ep.posterior) def __init__(self, ts, *, mutation_rate, allow_unary=False, singletons_phased=True): """ @@ -314,12 +180,14 @@ def __init__(self, ts, *, mutation_rate, allow_unary=False, singletons_phased=Tr logger.debug(f"Phased singletons in {abs(phase_timing):.2f} seconds") # mutable - self.factors = EPFactors( - self.node_constraints, - self.edge_parents, - self.edge_children, - self.block_nodes[0], - self.block_nodes[1], + self._ep = _tsdate.ExpectationPropagation( + constraints=self.node_constraints, + edges_parent=self.edge_parents, + edges_child=self.edge_children, + edges_likelihood=self.edge_likelihoods, + blocks_left=self.block_nodes[ROOTWARD], + blocks_right=self.block_nodes[LEAFWARD], + blocks_likelihood=self.block_likelihoods, ) self.node_posterior = np.zeros((ts.num_nodes, 2)) self.mutation_posterior = np.full((ts.num_mutations, 2), np.nan) @@ -348,351 +216,6 @@ def __init__(self, ts, *, mutation_rate, allow_unary=False, singletons_phased=Tr edges = np.arange(ts.num_edges, dtype=np.int32)[~edge_unphased] self.edge_order = np.concatenate((edges[:-1], np.flip(edges))) self.block_order = np.arange(num_blocks, dtype=np.int32) - self.mutation_order = np.arange(ts.num_mutations, dtype=np.int32) - - @staticmethod - @numba_jit(_void(_i1r, _i1r, _i1r, _f2r, _f2r, _f2w, _fac, _f1w, _f, _f, _b)) - def propagate_likelihood( - edge_order, - edges_parent, - edges_child, - likelihoods, - constraints, - posterior, - factors, - lognorm, - max_shape, - min_step, - unphased, - ): - # Update approximating factors for Poisson mutation likelihoods on edges. - # - # :param numpy.ndarray edges_parent: integer array of parent ids per edge - # :param numpy.ndarray edges_child: integer array of child ids per edge - # :param numpy.ndarray likelihoods: array of dimension `[num_edges, 2]` - # containing mutation count and mutational target size per edge. - # :param numpy.ndarray constraints: array of dimension `[num_nodes, 2]` - # containing lower and upper bounds for each node. - # :param numpy.ndarray posterior: array of dimension `[num_nodes, 2]` - # containing natural parameters for each node, updated in-place. - # :param EPFactors factors: object containing parent and child factors - # (natural parameters) for each edge, updated in-place. - # :param numpy.ndarray lognorm: array of dimension `[num_edges]` - # containing the approximate normalizing constants per edge, - # updated in-place. - # :param float max_shape: the maximum allowed shape for node posteriors. - # :param float min_step: the minimum allowed step size in (0, 1). - # :param bool unphased: if True, edges are treated as blocks of unphased - # singletons in contemporary individuals - - assert constraints.shape == posterior.shape - assert edges_child.size == edges_parent.size - assert likelihoods.shape == (edges_parent.size, 2) - assert max_shape >= 1.0 - assert 0.0 < min_step < 1.0 - - def cavity_damping(x, y): - return _damp(x, y, min_step) - - def posterior_damping(x): - return _rescale(x, max_shape) - - def leafward_projection(x, y, z): - if unphased: - return approx.sideways_projection(x, y, z) - return approx.leafward_projection(x, y, z) - - def rootward_projection(x, y, z): - if unphased: - return approx.sideways_projection(x, y, z) - return approx.rootward_projection(x, y, z) - - def gamma_projection(x, y, z): - if unphased: - return approx.unphased_projection(x, y, z) - return approx.gamma_projection(x, y, z) - - def twin_projection(x, y): - assert unphased, "Invalid update" - return approx.twin_projection(x, y) - - fixed = constraints[:, LOWER] == constraints[:, UPPER] - - scale = factors.scale - factor = factors.block if unphased else factors.edge - assert factor.shape == (edges_parent.size, 2, 2) - - for i in edge_order: - p, c = edges_parent[i], edges_child[i] - if scale[p] < TINY or scale[c] < TINY: - # modifies `scale` and `factor` by reference - _rescale_factors(factors) - if fixed[p] and fixed[c]: - continue - elif fixed[p] and not fixed[c]: - # in practice this should only occur if a sample is the - # ancestor of another sample - child_message = factor[i, LEAFWARD] * scale[c] - child_delta = cavity_damping(posterior[c], child_message) - child_cavity = posterior[c] - child_delta * child_message - edge_likelihood = child_delta * likelihoods[i] - parent_age = constraints[p, LOWER] - lognorm[i], posterior[c] = leafward_projection( - parent_age, - child_cavity, - edge_likelihood, - ) - factor[i, LEAFWARD] *= 1.0 - child_delta - factor[i, LEAFWARD] += (posterior[c] - child_cavity) / scale[c] - child_eta = posterior_damping(posterior[c]) - posterior[c] *= child_eta - scale[c] *= child_eta - elif fixed[c] and not fixed[p]: - # in practice this should only occur if a sample has age - # greater than zero - parent_message = factor[i, ROOTWARD] * scale[p] - parent_delta = cavity_damping(posterior[p], parent_message) - parent_cavity = posterior[p] - parent_delta * parent_message - edge_likelihood = parent_delta * likelihoods[i] - child_age = constraints[c, LOWER] - lognorm[i], posterior[p] = rootward_projection( - child_age, - parent_cavity, - edge_likelihood, - ) - factor[i, ROOTWARD] *= 1.0 - parent_delta - factor[i, ROOTWARD] += (posterior[p] - parent_cavity) / scale[p] - parent_eta = posterior_damping(posterior[p]) - posterior[p] *= parent_eta - scale[p] *= parent_eta - else: - if p == c: # singleton block with single parent - parent_message = factor[i, ROOTWARD] * scale[p] - parent_delta = cavity_damping(posterior[p], parent_message) - parent_cavity = posterior[p] - parent_delta * parent_message - edge_likelihood = parent_delta * likelihoods[i] - child_age = constraints[c, LOWER] - lognorm[i], posterior[p] = \ - twin_projection(parent_cavity, edge_likelihood) # fmt: skip - factor[i, ROOTWARD] *= 1.0 - parent_delta - factor[i, ROOTWARD] += (posterior[p] - parent_cavity) / scale[p] - parent_eta = posterior_damping(posterior[p]) - posterior[p] *= parent_eta - scale[p] *= parent_eta - else: - # lower-bound cavity - parent_message = factor[i, ROOTWARD] * scale[p] - child_message = factor[i, LEAFWARD] * scale[c] - parent_delta = cavity_damping(posterior[p], parent_message) - child_delta = cavity_damping(posterior[c], child_message) - delta = min(parent_delta, child_delta) - - parent_cavity = posterior[p] - delta * parent_message - child_cavity = posterior[c] - delta * child_message - edge_likelihood = delta * likelihoods[i] - - # match moments and update factors - lognorm[i], posterior[p], posterior[c] = gamma_projection( - parent_cavity, - child_cavity, - edge_likelihood, - ) - factor[i, ROOTWARD] *= 1.0 - delta - factor[i, ROOTWARD] += (posterior[p] - parent_cavity) / scale[p] - factor[i, LEAFWARD] *= 1.0 - delta - factor[i, LEAFWARD] += (posterior[c] - child_cavity) / scale[c] - - # upper-bound posterior - parent_eta = posterior_damping(posterior[p]) - child_eta = posterior_damping(posterior[c]) - posterior[p] *= parent_eta - posterior[c] *= child_eta - scale[p] *= parent_eta - scale[c] *= child_eta - - @staticmethod - @numba_jit(_void(_b1r, _f2w, _fac, _f, _i, _f)) - def propagate_prior(free, posterior, factors, max_shape, em_maxitt, em_reltol): - # Update approximating factors for global prior. - # - # :param ndarray free: boolean array for if prior should be applied to node - # :param ndarray penalty: initial value for regularisation penalty - # :param ndarray posterior: rows are nodes, columns are first and - # second natural parameters of gamma posteriors. Updated in place. - # :param EPFactors factors: object containing EP messages for nodes. - # Updated in place. - # :param float max_shape: the maximum allowed shape for node posteriors. - # :param int em_maxitt: the maximum number of EM iterations to use when - # fitting the regularisation. - # :param int em_reltol: the termination criterion for relative change in - # log-likelihood. - - assert free.size == posterior.shape[0] - assert max_shape >= 1.0 - - def posterior_damping(x): - return _rescale(x, max_shape) - - if not np.any(free): - return - - factor = factors.node - scale = factors.scale - assert factor.shape == (free.size, 2, 2) - assert scale.size == free.size - - # fit an exponential to cavity distributions for unconstrained nodes - cavity = posterior - factor[:, MIXPRIOR] * scale[:, np.newaxis] - shape, rate = cavity[free, 0] + 1, cavity[free, 1] - penalty = 1 / np.mean(shape / rate) - itt, delta = 0, np.inf - while abs(delta) > abs(penalty) * em_reltol: - if itt > em_maxitt: - break - delta = 1 / np.mean(shape / (rate + penalty)) - penalty - penalty += delta - itt += 1 - assert penalty > 0 - - # update posteriors and rescale to keep shape bounded - posterior[free, 1] = cavity[free, 1] + penalty - factor[free, MIXPRIOR] = \ - (posterior[free] - cavity[free]) / scale[free, np.newaxis] # fmt: skip - for i in np.flatnonzero(free): - eta = posterior_damping(posterior[i]) - posterior[i] *= eta - scale[i] *= eta - - @staticmethod - @numba_jit(_void(_i1r, _f2w, _f1w, _i1r, _i1r, _i1r, _f2r, _f2r, _f2r, _fac, _b)) - def propagate_mutations( - mutations_order, - mutations_posterior, - mutations_phase, - mutations_edge, - edges_parent, - edges_child, - likelihoods, - constraints, - posterior, - factors, - unphased, - ): - # Calculate posteriors for mutations. (publicly undocumented) - # - # :param ndarray mutations_order: integer array giving order in - # which to traverse mutations - # :param ndarray mutations_posterior: array of dimension `(num_mutations, 2)` - # containing natural parameters for each mutation, modified in place - # :param ndarray mutations_phase: array of dimension `(num_mutations, )` - # containing mutation phase, modified in place - # :param ndarray mutations_edge: integer array giving edge for each mutation - # :param ndarray edges_parent: integer array of parent ids per edge - # :param ndarray edges_child: integer array of child ids per edge - # :param ndarray likelihoods: array of dimension `[num_edges, 2]` - # containing mutation count and mutational target size per edge. - # :param ndarray constraints: array of dimension `[num_nodes, 2]` - # containing lower and upper bounds for each node. - # :param ndarray posterior: array of dimension `[num_nodes, 2]` - # containing natural parameters for each node - # :param EPFactors factors: object containing - # containing parent and child factors (natural parameters) for each edge - # :param bool unphased: if True, edges are treated as blocks of unphased - # singletons in contemporary individuals - - # TODO: scale should be 1.0, can we delete - # TODO: we don't seem to need to damp? - - # TODO: assert more stuff here? - assert mutations_phase.size == mutations_edge.size - assert mutations_posterior.shape == (mutations_phase.size, 2) - assert constraints.shape == posterior.shape - assert edges_child.size == edges_parent.size - assert likelihoods.shape == (edges_parent.size, 2) - - def leafward_projection(x, y, z): - if unphased: - return approx.mutation_sideways_projection(x, y, z) - return approx.mutation_leafward_projection(x, y, z) - - def rootward_projection(x, y, z): - if unphased: - return approx.mutation_sideways_projection(x, y, z) - return approx.mutation_rootward_projection(x, y, z) - - def gamma_projection(x, y, z): - if unphased: - return approx.mutation_unphased_projection(x, y, z) - return approx.mutation_gamma_projection(x, y, z) - - def fixed_projection(x, y): - if unphased: - return approx.mutation_block_projection(x, y) - return approx.mutation_edge_projection(x, y) - - twin_projection = approx.mutation_twin_projection - - fixed = constraints[:, LOWER] == constraints[:, UPPER] - - scale = factors.scale - factor = factors.block if unphased else factors.edge - assert factor.shape == (edges_parent.size, 2, 2) - - for m in mutations_order: - i = mutations_edge[m] - if i == tskit.NULL: # skip mutations above root - continue - p, c = edges_parent[i], edges_child[i] - if fixed[p] and fixed[c]: - child_age = constraints[c, 0] - parent_age = constraints[p, 0] - mutations_phase[m], mutations_posterior[m] = \ - fixed_projection(parent_age, child_age) # fmt: skip - elif fixed[p] and not fixed[c]: - child_message = factor[i, LEAFWARD] * scale[c] - child_delta = 1.0 # hopefully we don't need to damp - child_cavity = posterior[c] - child_delta * child_message - edge_likelihood = child_delta * likelihoods[i] - parent_age = constraints[p, LOWER] - mutations_phase[m], mutations_posterior[m] = leafward_projection( - parent_age, - child_cavity, - edge_likelihood, - ) - elif fixed[c] and not fixed[p]: - parent_message = factor[i, ROOTWARD] * scale[p] - parent_delta = 1.0 # hopefully we don't need to damp - parent_cavity = posterior[p] - parent_delta * parent_message - edge_likelihood = parent_delta * likelihoods[i] - child_age = constraints[c, LOWER] - mutations_phase[m], mutations_posterior[m] = rootward_projection( - child_age, - parent_cavity, - edge_likelihood, - ) - else: - if p == c: # singleton block with single parent - parent_message = factor[i, ROOTWARD] * scale[p] - parent_delta = 1.0 # hopefully we don't need to damp - parent_cavity = posterior[p] - parent_delta * parent_message - edge_likelihood = parent_delta * likelihoods[i] - child_age = constraints[c, LOWER] - mutations_phase[m], mutations_posterior[m] = \ - twin_projection(parent_cavity, edge_likelihood) # fmt: skip - else: - parent_message = factor[i, ROOTWARD] * scale[p] - child_message = factor[i, LEAFWARD] * scale[c] - parent_delta = 1.0 # hopefully we don't need to damp - child_delta = 1.0 # hopefully we don't need to damp - delta = min(parent_delta, child_delta) - parent_cavity = posterior[p] - delta * parent_message - child_cavity = posterior[c] - delta * child_message - edge_likelihood = delta * likelihoods[i] - mutations_phase[m], mutations_posterior[m] = gamma_projection( - parent_cavity, - child_cavity, - edge_likelihood, - ) def iterate( self, @@ -705,51 +228,38 @@ def iterate( check_valid=False, # for debugging ): logger.debug("Passing through singleton blocks") - self.propagate_likelihood( - self.block_order, - self.block_nodes[ROOTWARD], - self.block_nodes[LEAFWARD], - self.block_likelihoods, - self.node_constraints, - self.node_posterior, - self.factors, - self.block_logconst, - max_shape, - min_step, - USE_BLOCK_LIKELIHOOD, + self._ep.propagate_likelihood( + order=self.block_order, + unphased=USE_BLOCK_LIKELIHOOD, + max_shape=max_shape, + min_step=min_step, ) logger.debug("Rootward + leafward pass through edges") - self.propagate_likelihood( - self.edge_order, - self.edge_parents, - self.edge_children, - self.edge_likelihoods, - self.node_constraints, - self.node_posterior, - self.factors, - self.edge_logconst, - max_shape, - min_step, - USE_EDGE_LIKELIHOOD, + self._ep.propagate_likelihood( + order=self.edge_order, + unphased=USE_EDGE_LIKELIHOOD, + max_shape=max_shape, + min_step=min_step, ) if regularise: logger.debug("Exponential regularization on roots") - self.propagate_prior( - self.unconstrained_roots, - self.node_posterior, - self.factors, - max_shape, - em_maxitt, - em_reltol, + self._ep.propagate_prior( + free=self.unconstrained_roots, + max_shape=max_shape, + em_maxitt=em_maxitt, + em_reltol=em_reltol, ) logger.debug("Absorbing scaling term into the factors") - _rescale_factors(self.factors) + self._ep.rescale_factors() + self.node_posterior = self._ep.posterior + self.edge_logconst = self._ep.edges_lognorm + self.block_logconst = self._ep.blocks_lognorm if check_valid: # for debugging - self._check_valid_state(self.node_posterior, self.factors) + self._check_valid_state() def rescale( self, @@ -764,11 +274,11 @@ def rescale( # Normalise posteriors so that empirical mutation rate is constant likelihoods = self.edge_likelihoods if rescale_segsites \ else self.sizebiased_likelihoods # fmt: skip - reallocate_unphased( # correct mutation counts for unphased singletons - likelihoods, - self.mutation_phase, - self.mutation_blocks, - self.block_edges, + likelihoods = reallocate_unphased( # correct counts for unphased singletons + edges_likelihood=likelihoods, + mutations_phase=self.mutation_phase, + mutations_block=self.mutation_blocks, + blocks_edges=self.block_edges, ) nodes_fixed = self.node_constraints[:, 0] == self.node_constraints[:, 1] mutations_fixed = np.isnan(self.mutation_posterior[:, 0]) @@ -776,12 +286,12 @@ def rescale( rescaled_nodes_time = nodes_time.copy() for _ in np.arange(rescale_iterations): # estimate time rescaling original_breaks, rescaled_breaks = mutational_timescale( - rescaled_nodes_time, - likelihoods, - nodes_fixed, - self.edge_parents, - self.edge_children, - rescale_intervals, + nodes_time=rescaled_nodes_time, + edges_likelihood=likelihoods, + nodes_fixed=nodes_fixed, + edges_parent=self.edge_parents, + edges_child=self.edge_children, + max_intervals=rescale_intervals, ) rescaled_nodes_time = piecewise_scale_point_estimate( rescaled_nodes_time, @@ -850,35 +360,21 @@ def infer( logger.info(f"Calculated node posteriors in {abs(nodes_timing):.2f} seconds") muts_timing = time.time() - mutations_phased = self.mutation_blocks == tskit.NULL + unphased = self.mutation_blocks != tskit.NULL logger.debug("Passing through unphased singletons") - self.propagate_mutations( # unphased singletons - self.mutation_order[~mutations_phased], - self.mutation_posterior, - self.mutation_phase, - self.mutation_blocks, - self.block_nodes[ROOTWARD], - self.block_nodes[LEAFWARD], - self.block_likelihoods, - self.node_constraints, - self.node_posterior, - self.factors, - USE_BLOCK_LIKELIHOOD, + posterior, phase = self._ep.propagate_mutations( + mutations_edge=self.mutation_blocks[unphased], + unphased=USE_BLOCK_LIKELIHOOD, ) + self.mutation_posterior[unphased] = posterior + self.mutation_phase[unphased] = phase logger.debug("Passing through phased mutations") - self.propagate_mutations( # phased mutations - self.mutation_order[mutations_phased], - self.mutation_posterior, - self.mutation_phase, - self.mutation_edges, - self.edge_parents, - self.edge_children, - self.edge_likelihoods, - self.node_constraints, - self.node_posterior, - self.factors, - USE_EDGE_LIKELIHOOD, + posterior, phase = self._ep.propagate_mutations( + mutations_edge=self.mutation_edges[~unphased], + unphased=USE_EDGE_LIKELIHOOD, ) + self.mutation_posterior[~unphased] = posterior + self.mutation_phase[~unphased] = phase muts_timing -= time.time() skipped_muts = np.sum(np.isnan(self.mutation_posterior[:, 0])) logger.info(f"Skipped {skipped_muts} mutations with invalid posteriors") diff --git a/uv.lock b/uv.lock index b46f01c8..638c65a5 100644 --- a/uv.lock +++ b/uv.lock @@ -1893,15 +1893,6 @@ wheels = [ { url = "https://files.pythonhosted.org/packages/5d/57/3c4b1c6f2e0cc29ba023802458ea3d2a996f87085559e4a5f2192d549532/more_itertools-11.2.1-py3-none-any.whl", hash = "sha256:35a7377edd1dd6608dcb2cdf534ded55ea32d49448875ad042cd3f879fb1ded0", size = 74405, upload-time = "2026-10-14T18:50:29.116Z" }, ] -[[package]] -name = "mpmath" -version = "1.4.1" -source = { registry = "https://pypi.org/simple" } -sdist = { url = "https://files.pythonhosted.org/packages/c5/b0/6de8e78014ff1842a90cc9a56da6ccfb598a5390ed0257fcdb7d9680c18b/mpmath-1.4.1.tar.gz", hash = "sha256:efd6d1b75f09d69524a67609949812668b28e81ecbfe0ab449ced8c13e92642e", size = 2093211, upload-time = "2026-03-15T01:17:38.245Z" } -wheels = [ - { url = "https://files.pythonhosted.org/packages/13/f2/abeec3db71d221ccd3cd89d206be1fabf5a3ee7178862f5fba23a59607e0/mpmath-1.4.1-py3-none-any.whl", hash = "sha256:dc4f0ea2304480d4a9a48a94c1020571558ade522b44a6912efac63a586e140f", size = 567787, upload-time = "2026-03-15T01:17:36.392Z" }, -] - [[package]] name = "msprime" version = "1.4.4" @@ -2119,21 +2110,6 @@ wheels = [ { url = "https://files.pythonhosted.org/packages/8b/ff/904fb9a49fd78801d8f57c19f2193785e8dc242c0f077baf7949f65384a7/numcodecs-0.15.2-cp313-cp313-win_amd64.whl", hash = "sha256:b1c684e0c2113a06cf29263a4311c6f86c710ece72d0729a355bbdb2220e2328", size = 843902, upload-time = "2026-10-20T19:26:17.447Z" }, ] -[[package]] -name = "numdifftools" -version = "0.11.2" -source = { registry = "https://pypi.org/simple" } -dependencies = [ - { name = "numpy", version = "2.4.6", source = { registry = "https://pypi.org/simple" }, marker = "python_full_version < '3.12'" }, - { name = "numpy", version = "2.5.4", source = { registry = "https://pypi.org/simple" }, marker = "python_full_version >= '3.12'" }, - { name = "scipy", version = "1.17.1", source = { registry = "https://pypi.org/simple" }, marker = "python_full_version < '3.12'" }, - { name = "scipy", version = "1.18.1", source = { registry = "https://pypi.org/simple" }, marker = "python_full_version >= '3.12'" }, -] -sdist = { url = "https://files.pythonhosted.org/packages/c9/9a/cffaad9e8443d4e04f89f44b8ceb3a6886d6fb529737e6dacc0d2d70fbe0/numdifftools-0.11.2.tar.gz", hash = "sha256:0508bbcea72f4706d8f4d518812bec11949d75bd0656047777d4e36357322344", size = 82603, upload-time = "2026-10-25T23:11:52.281Z" } -wheels = [ - { url = "https://files.pythonhosted.org/packages/ce/7c/9f48699da472a5c5141bdf3f52ae1767a8cee76abfe8f5169705db58a734/numdifftools-0.11.2-py3-none-any.whl", hash = "sha256:1281419f8c63068bc41a0c8b1b52cd644582621f4208e61cbf80eaed5591585f", size = 97817, upload-time = "2026-10-25T23:11:50.92Z" }, -] - [[package]] name = "numpy" version = "2.4.6" @@ -3813,8 +3789,6 @@ name = "tsdate" source = { editable = "." } dependencies = [ { name = "appdirs" }, - { name = "mpmath" }, - { name = "numba" }, { name = "numpy", version = "2.4.6", source = { registry = "https://pypi.org/simple" }, marker = "python_full_version < '3.12'" }, { name = "numpy", version = "2.5.4", source = { registry = "https://pypi.org/simple" }, marker = "python_full_version >= '3.12'" }, { name = "scipy", version = "1.17.1", source = { registry = "https://pypi.org/simple" }, marker = "python_full_version < '3.12'" }, @@ -3832,7 +3806,6 @@ dev = [ { name = "jupyter-book" }, { name = "matplotlib" }, { name = "msprime" }, - { name = "numdifftools" }, { name = "pandas" }, { name = "prek" }, { name = "pytest" }, @@ -3878,7 +3851,6 @@ packaging = [ test = [ { name = "matplotlib" }, { name = "msprime" }, - { name = "numdifftools" }, { name = "pytest" }, { name = "pytest-cov" }, { name = "pytest-xdist" }, @@ -3892,8 +3864,6 @@ wheels = [ [package.metadata] requires-dist = [ { name = "appdirs" }, - { name = "mpmath" }, - { name = "numba", specifier = ">=0.58.1" }, { name = "numpy" }, { name = "scipy", specifier = ">=1.13.0" }, { name = "tqdm" }, @@ -3909,7 +3879,6 @@ dev = [ { name = "jupyter-book", specifier = "<2" }, { name = "matplotlib" }, { name = "msprime" }, - { name = "numdifftools" }, { name = "pandas" }, { name = "prek", specifier = "==0.3.3" }, { name = "pytest" }, @@ -3955,7 +3924,6 @@ packaging = [ test = [ { name = "matplotlib" }, { name = "msprime" }, - { name = "numdifftools" }, { name = "pytest" }, { name = "pytest-cov" }, { name = "pytest-xdist" },