How to use the cogent3.util.dict_array.DictArrayTemplate function in cogent3

To help you get started, we’ve selected a few cogent3 examples, based on popular ways it is used in public projects.

Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.

github cogent3 / cogent3 / tests / test_util / test_dictarray.py View on Github external
def test_write(self):
        """exercising write method"""
        data = [[3, 7], [2, 8], [5, 5]]
        darr = DictArrayTemplate(list("ABC"), list("ab")).wrap(data)
        with TemporaryDirectory(dir=".") as dirname:
            outpath = os.path.join(dirname, "delme.tsv")
            darr.write(outpath)
            with open(outpath) as infile:
                contents = [l.strip().split() for l in infile]
            header = contents.pop(0)
            self.assertEqual(header, ["dim-1", "dim-2", "value"])
            got = {(k1, k2): int(v) for k1, k2, v in contents}
            self.assertEqual(got, darr.to_dict(flatten=True))
github cogent3 / cogent3 / tests / test_util / test_dictarray.py View on Github external
def test_convert_for_dictarray2(self):
        """convert_for_dictarray correctly delegates"""
        b = DictArrayTemplate("abc", "ABC").wrap(self.a)
        data_types = (
            [[245, 599]],
            dict(a=dict(b=4, c=5)),
            {("a", "b"): 4, ("a", "c"): 5},
            dict(a=0, b=35, c=45),
            b,
        )
        for data in data_types:
            vals, row_keys, col_keys = convert_for_dictarray(data)
            _ = DictArrayTemplate(row_keys, col_keys).wrap(vals)
github cogent3 / cogent3 / tests / test_util / test_dictarray.py View on Github external
def test_int_labels(self):
        """DictArray with no labels."""
        b = DictArrayTemplate(3, 3).wrap(self.a)
        self.assertEqual(b.keys(), [0, 1, 2])
        self.assertEqual(b[0].keys(), [0, 1, 2])
        self.assertEqual(sum(b[0]), 1)
github cogent3 / cogent3 / tests / test_draw / test_logo.py View on Github external
def test_get_logo_missing(self):
        """copes with positions with no values"""
        data = [
            [0.1, 0.3, 0.5, 0.1],
            [0.05, 0.8, 0.05, 0.1],
            [0, 0, 0, 0],
            [0.7, 0.1, 0.1, 0.1],
            [0.6, 0.15, 0.05, 0.2],
        ]
        data = DictArrayTemplate(5, "ACGT").wrap(data)
        d = get_logo(data)
github cogent3 / cogent3 / tests / test_util / test_dictarray.py View on Github external
def test_to_dict(self):
        """DictArray should convert 1D / 2D arrays with/without named row"""
        # 1D data, only 1D keys provided
        data = [0, 35, 45]
        keys = "a", "b", "c"
        darr = DictArrayTemplate(keys).wrap(data)
        self.assertEqual(darr.to_dict(), dict(zip(keys, data)))
        # 2D data, 2D keys, both string, provided
        data = [[0, 35, 45]]
        darr = DictArrayTemplate(["0"], keys).wrap(data)
        darr.to_dict()
        self.assertEqual(darr.to_dict(), {"0": {"a": 0, "b": 35, "c": 45}})
        # 2D data, 2D keys, one int, one string, provided
        darr = DictArrayTemplate([1], keys).wrap(data)
        self.assertEqual(darr.to_dict(), {1: {"a": 0, "b": 35, "c": 45}})
        darr = DictArrayTemplate([0], keys).wrap(data)
        self.assertEqual(darr.to_dict(), {0: {"a": 0, "b": 35, "c": 45}})
github cogent3 / cogent3 / src / cogent3 / recalculation / definition.py View on Github external
def __init__(
        self, default=None, name=None, dimensions=None, dimension=None, size=None, **kw
    ):
        assert name
        if size is not None:
            pass
        elif default is not None:
            size = len(default)
        elif dimension is not None:
            size = len(dimension[1])
        self.size = size
        if dimension is not None:
            self.internal_dimension = dimension
            (dim_name, dim_cats) = dimension
            self.bin_names = dim_cats
            self.array_template = DictArrayTemplate(dim_cats)
            self.internal_dimensions = (dim_name,)
        if default is None:
            default = self._make_default_value()
        elif self.array_template is not None:
            default = self.array_template.unwrap(default)
        else:
            default = numpy.asarray(default)
        _InputDefn.__init__(
            self, name=name, default=default, dimensions=dimensions, **kw
        )
        self.check_value_is_valid(default, True)
github cogent3 / cogent3 / src / cogent3 / util / table.py View on Github external
def __delitem__(self, key):
        key = self._get_key_(key)
        del self.__dict__[key]
        self._order = tuple(k for k in self._order if k != key)
        self._template = DictArrayTemplate(self._order)
github cogent3 / cogent3 / src / cogent3 / evolve / likelihood_function.py View on Github external
bin_names = None
            bin_index = None

        used_dims = defn.used_dimensions()
        edge_index = defn.valid_dimensions.index("edge")

        indices = {defn.valid_dimensions.index(k) for k in used_dims}
        if not calibrated:
            indices.add(edge_index)

        if not calibrated and rate_het:
            indices.add(bin_index)

        indices = list(sorted(indices))
        result = {}
        darr_template = DictArrayTemplate(self._motifs, self._motifs)
        for scope, index in defn.index.items():
            q = defn.values[index]  # this gives the appropriate Q
            # from scope we extract only the relevant dimensions
            key = tuple(numpy.take(scope, indices))
            q = q.copy()
            if not calibrated:
                length = self.get_param_value("length", edge=scope[edge_index])
                if rate_het:
                    bdex = bin_names[scope[bin_index]]
                    rate = rate_het.values[bdex]
                    length *= rate
                q *= length
            result[key] = darr_template.wrap(q)
            if not indices and calibrated:
                break  # single rate matrix
github cogent3 / cogent3 / src / cogent3 / evolve / likelihood_function.py View on Github external
expanded = numpy.zeros(len(self.motifs), dtype=float)
            for i, motif in enumerate(self.motifs):
                val = 1.0
                for b in motif:
                    val *= mprobs[b]
                expanded[i] = val
            mprobs = expanded / expanded.sum()
        else:
            mprobs = [mprobs[m] for m in self.motifs]
        edges = []
        values = []
        for e in self.tree.postorder():
            edges.append(e.name)
            values.append(mprobs)

        return DictArrayTemplate(edges, self.motifs).wrap(values)
github cogent3 / cogent3 / src / cogent3 / util / table.py View on Github external
def to_dict(self, flatten=False):
        if self.index_name:
            index = self.columns[self.index_name]
        else:
            index = self.shape[0]
        template = DictArrayTemplate(index, self.columns.order)
        darr = template.wrap(self.array)
        return darr.to_dict(flatten=flatten)