query
stringlengths
9
9.05k
document
stringlengths
10
222k
negatives
listlengths
19
20
metadata
dict
Reconstruct the tree of the given ``rank``
def unrank(num_leaves, rank, *, span=1, branch_length=1) -> Tree: rank_tree = combinatorics.RankTree.unrank(num_leaves, rank) return rank_tree.to_tsk_tree(span=span, branch_length=branch_length)
[ "def standize_ranked_tree(raw_tree):\n #remove the subclass and suborder nodes (with a rank 3.5 or 4.5\n nodes_to_remove = [n for n in raw_tree.iterNodes(include_self=False)\n if n.params['rank'] % 1]\n for node in nodes_to_remove:\n node.removeSelf()\n #add nodes to gaps\n nodes_to...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Calculates the distribution of embedded topologies for every combination of the sample sets in ``sample_sets``. ``sample_sets`` defaults to all samples in the tree grouped by population. ``sample_sets`` need not include all samples but must be pairwise disjoint.
def count_topologies(self, sample_sets=None) -> tskit.TopologyCounter: if sample_sets is None: sample_sets = [ self.tree_sequence.samples(population=pop.id) for pop in self.tree_sequence.populations() ] return combinatorics.tree_count_topologies(s...
[ "def process_sampleset(G, sampleset):\n # Get the best solution to display\n sample = sampleset.first.sample\n\n # Get a subset of the original graph (just the nodes assigned to group 1)\n set1_nodes = [node for node in sample if sample[node] == 1]\n subgraph1 = G.subgraph(set1_nodes)\n set0_nodes...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Returns the length of the branch (in units of time) joining the specified node to its parent. This is equivalent to >>> tree.time(tree.parent(u)) tree.time(u) The branch length for a node that has no parent (e.g., a root) is defined as zero. Note that this is not related to the property `.length` which
def branch_length(self, u): ret = 0 parent = self.parent(u) if parent != NULL: ret = self.time(parent) - self.time(u) return ret
[ "def branch_length(self, u):\n return self.time(self.get_parent(u)) - self.time(u)", "def depth(self):\n if self.parent is None:\n return self.length\n else:\n return self.parent.depth + self.length", "def _self_time(self):\r\n return self.duration() - sum([child.du...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Returns the sum of all the branch lengths in this tree (in units of time). This is equivalent to >>> sum(tree.branch_length(u) for u in tree.nodes()) Note that the branch lengths for root nodes are defined as zero. As this is defined by a traversal of the tree, technically we return the sum of all branch lengths that a...
def total_branch_length(self): return self._ll_tree.get_total_branch_length()
[ "def total_branch_length(self):\n return sum(\n self.get_branch_length(u) for u in self.nodes() if u not in self.roots)", "def total_branch_length(self):\n return sum(node.branch_length for node in self.find_clades(branch_length=True))", "def GetBranchLengths(tree):\n\n nnodes = GetM...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Returns the time of the most recent common ancestor of the specified
def tmrca(self, *args): mrca = self.mrca(*args) if mrca == tskit.NULL: raise ValueError(f"Nodes {args} do not share a common ancestor in the tree") return self.get_time(mrca)
[ "def get_recent_common_ancestor(self, nodes):\n if len(nodes) == 0:\n raise PhyloValueError(\"Error: could not determing the recent common ancestor, as no nodes were given.\")\n elif len(nodes) == 1:\n return nodes[0]\n ancestor = None\n for ancestor_nodes in zip(*(...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
A numpy array (dtype=np.int32) encoding the parent of each node in this tree, such that ``tree.parent_array[u] == tree.parent(u)``
def parent_array(self): return self._parent_array
[ "def generate_parent_space(self):\n\n parent_node = self.node+'_ZERO'\n parent_node = mc.ls(parent_node)\n\n if not parent_node:\n parent_node = utils.get_parent(self.const_node)\n\n parent_node = mc.ls(parent_node)\n\n if parent_node:\n return ['parent', par...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
A numpy array (dtype=np.int32) encoding the left child of each node in this tree, such that ``tree.left_child_array[u] == tree.left_child(u)``
def left_child_array(self): return self._left_child_array
[ "def get_left_child(tree, traversal_order):\n left_child = np.full(tree.num_nodes + 1, NULL, dtype=int)\n for u in tree.nodes(order=traversal_order):\n parent = tree.parent(u)\n if parent != NULL and left_child[parent] == NULL:\n left_child[parent] = u\n return left_child", "def ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
A numpy array (dtype=np.int32) encoding the right child of each node in this tree, such that ``tree.right_child_array[u] == tree.right_child(u)``
def right_child_array(self): return self._right_child_array
[ "def get_children_right(self) -> np.ndarray:\n pass", "def get_right_child(self: object) -> 'BinaryTreeNode':\n return self.right", "def right_binarize(tree):\n if is_leaf(tree):\n return tree\n if len(tree) > 2:\n tree = [tree[0], tree[1:]]\n return [right_binarize(b) for b...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
A numpy array (dtype=np.int32) encoding the left sib of each node in this tree, such that ``tree.left_sib_array[u] == tree.left_sib(u)``
def left_sib_array(self): return self._left_sib_array
[ "def lefts(self):\n lstack = [len(self.arr)]\n i = len(self.arr) - 1\n while i >= 0:\n if self.arr[i] > self.arr[lstack[-1] - 1]:\n while lstack and self.arr[i] > self.arr[lstack[-1] - 1]:\n x = lstack.pop()\n self.left[x - 1] = i ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
A numpy array (dtype=np.int32) encoding the right sib of each node in this tree, such that ``tree.right_sib_array[u] == tree.right_sib(u)``
def right_sib_array(self): return self._right_sib_array
[ "def right_binarize(tree):\n if is_leaf(tree):\n return tree\n if len(tree) > 2:\n tree = [tree[0], tree[1:]]\n return [right_binarize(b) for b in tree]", "def bin_right_edges(self):\n return self.bins[..., 1]", "def left_sib_array(self):\n return self._left_sib_array", "d...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Returns the sibling(s) of the specified node ``u`` as a tuple of integer node IDs. If ``u`` has no siblings or is not a node in the current tree, returns an empty tuple. If ``u`` is the root of a singleroot tree, returns an empty tuple; if ``u`` is the root of a multiroot tree, returns the other roots (note all the roo...
def siblings(self, u): if u == self.virtual_root: return tuple() parent = self.parent(u) if self.is_root(u): parent = self.virtual_root if parent != tskit.NULL: return tuple(v for v in self.children(parent) if u != v) return tuple()
[ "def get_neighbors(self, u):\n return self.pg_base.predecessors(u) + self.pg_base.successors(u)", "def get_adjacent_nodes(self, u):\r\n return self.__adjacency_list.get(u, set())", "def sibling(self, n):\n parent = self.parent(n)\n if parent is None: # n is root\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
A numpy array (dtype=np.int32) encoding the number of children of each node in this tree, such that ``tree.num_children_array[u] == tree.num_children(u)`` for all
def num_children_array(self): return self._num_children_array
[ "def children_count(self):\n\n cnt = 0\n if self.left:\n cnt += 1\n if self.right:\n cnt += 1\n return cnt", "def num_nodes(self):\n ans = 1\n for child in self._children:\n ans += child.num_nodes()\n return ans", "def child_count...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Returns the id of the edge encoding the relationship between ``u``
def edge(self, u): return self._ll_tree.get_edge(u)
[ "def get_id(self):\n return self._edge_id", "def get_edge_id(self):\n ident = self.eid\n self.eid += 1\n return ident", "def arc_id(self, u, v):\n arcs = []\n for arc, info in self.arc_info.items():\n if info[\"start\"] == u and info[\"destin\"] == v:\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
The ID of the virtual root in this tree. This is equal to
def virtual_root(self): return self._ll_tree.get_virtual_root()
[ "def root_graph_id(self):\n return self._node.root_graph_id", "def root_id(self) -> pulumi.Output[str]:\n return pulumi.get(self, \"root_id\")", "def rootkey(self):\n return self._follow(self._tree_ref).key", "def get_id(self):\n return self._node_id", "def get_id(self):\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
The total number of edges in this tree. This is equal to the number of tree sequence edges that intersect with this tree's genomic interval. Note that this may be greater than the number of branches that are reachable from the tree's roots, since we can have topology that is not associated with any samples.
def num_edges(self): return self._ll_tree.get_num_edges()
[ "def number_of_edges(self) -> int:\n return self.graph.number_of_edges()", "def number_of_edges(self):\n return self.__graph__.number_of_edges", "def number_of_edges(self):\n num = 0\n for node_id, node in self.Nodes.items():\n neighbors = node.get_neighbors()\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
The leftmost root in this tree. If there are multiple roots in this tree, they are siblings of this node, and so we can
def left_root(self): return self.left_child(self.virtual_root)
[ "def getLeftmost(self, root):\n current = root\n while current.left is not None:\n current = current.left\n return current", "def root(self):\n if self.has_multiple_roots:\n raise ValueError(\"More than one root exists. Use tree.roots instead\")\n return se...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Returns the children of the specified node ``u`` as a tuple of integer node IDs. If ``u`` is a leaf, return the empty tuple. The ordering of children is arbitrary and should not be depended on; see the
def children(self, u): return self._ll_tree.get_children(u)
[ "def siblings(self, u):\n if u == self.virtual_root:\n return tuple()\n parent = self.parent(u)\n if self.is_root(u):\n parent = self.virtual_root\n if parent != tskit.NULL:\n return tuple(v for v in self.children(parent) if u != v)\n return tuple(...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Returns the time of the specified node. This is equivalently to ``tree.tree_sequence.node(u).time`` except for the special
def time(self, u): return self._ll_tree.get_time(u)
[ "def getCurrentNodeTime(self):\n return self.currentNodeTime", "def individuals_time(self):\n if self._individuals_time is None:\n self._individuals_time = self._ll_tree_sequence.get_individuals_time()\n return self._individuals_time", "def get_time(cls):\n now = rospy.Tim...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Returns the number of nodes on the path from ``u`` to a root, not including ``u``. Thus, the depth of a root is zero.
def depth(self, u): return self._ll_tree.depth(u)
[ "def size_subtree(tree, u):\n children = tree.successors(u)\n #base case: u is a leaf\n if not children:\n return 1\n else:\n size = 1\n for c in children:\n size += size_subtree(tree, c)\n return size", "def path_length(self, u, v):\n mrca = self.mrca(u, ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Returns the population associated with the specified node. Equivalent to ``tree.tree_sequence.node(u).population``.
def population(self, u): return self._ll_tree.get_population(u)
[ "def __getPopulation__(self):\n\n return self.population", "def getPopulation(self):\n\n return self.p", "def individuals_population(self):\n if self._individuals_population is None:\n self._individuals_population = (\n self._ll_tree_sequence.get_individuals_popula...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Returns True if the specified node u is a descendant of node v and False
def is_descendant(self, u, v): return bool(self._ll_tree.is_descendant(u, v))
[ "def eligible(self, u, v):\n return self.eligible_node(u) and self.eligible_node(v) and u != v", "def descendant(self,src_node,dest_node):\n if src_node == dest_node:\n return True\n for child in self.edges(src_node):\n if self.descendant(child,dest_node):\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
``True`` if this tree has a single root, ``False`` otherwise. Equivalent to tree.num_roots == 1. This is a O(1) operation.
def has_single_root(self): root = self.left_root if root != NULL and self.right_sib(root) == NULL: return True return False
[ "def is_root(self):\n return self.root is None", "def is_root(self, node: Node) -> bool:\n return node == self._root", "def is_root(self, node: object) -> bool:\n if node == self.root:\n return True\n else:\n return False", "def is_root(self, n):\n retu...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
``True`` if this tree has more than one root, ``False`` otherwise. Equivalent to tree.num_roots > 1. This is a O(1) operation.
def has_multiple_roots(self): root = self.left_root if root != NULL and self.right_sib(root) != NULL: return True return False
[ "def has_single_root(self):\n root = self.left_root\n if root != NULL and self.right_sib(root) == NULL:\n return True\n return False", "def isEmptyTree(self):\n return len(self.root.children) == 0", "def is_root(self):\n return self.root is None", "def has_childre...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
The root of this tree. If the tree contains multiple roots, a ValueError is
def root(self): if self.has_multiple_roots: raise ValueError("More than one root exists. Use tree.roots instead") return self.left_root
[ "def root(self):\n root = self.left_root\n if root != NULL and self.right_sib(root) != NULL:\n raise ValueError(\"More than one root exists. Use tree.roots instead\")\n return root", "def root(self):\n # type: () -> tree_node.TreeNode\n return self._root", "def get_...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Returns the total number of mutations across all sites on this tree.
def num_mutations(self): return sum(len(site.mutations) for site in self.sites())
[ "def num_sites(self):\n return len(self.cluster_subspace.structure) * self.size", "def count_fragments(self):\n n = 0\n for chain in self.iter_chains():\n n += chain.count_fragments()\n return n", "def total_node_size(self):\r\n return sum(map(self.node_size, self.n...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Returns the number of sites on this tree.
def num_sites(self): return self._ll_tree.get_num_sites()
[ "def num_sites(self) -> int:\n return self._sites.size", "def countSites(self):\n self.ni = len(self.sites)\n return self.ni", "def n_sites(self):\n return len(self.sites)", "def num_sites(self):\n return len(self.cluster_subspace.structure) * self.size", "def number_of_op...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Returns an iterator over the numerical IDs of all the sample nodes in this tree that are underneath the node with ID ``u``. If ``u`` is a sample, it is included in the returned iterator. If ``u`` is not a sample, it is possible for the returned iterator to be empty, for example if ``u`` is an
def samples(self, u=None): roots = [u] if u is None: roots = self.roots for root in roots: yield from self._sample_generator(root)
[ "def samples(self, u=None):\n roots = [u]\n if u is None:\n roots = self.roots\n for root in roots:\n for v in self._sample_generator(root):\n yield v", "def sample_ids(self):\n flags = self.tables.nodes.flags\n out = []\n for input_id...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Returns the number of children of the specified node (i.e., ``len(tree.children(u))``)
def num_children(self, u): return self._ll_tree.get_num_children(u)
[ "def _count_children(self, item):\n return len(self.tree.get_children(item))", "def get_num_children(self):\n return len(self.children)", "def child_count(self):\n\t\treturn len(self._children)", "def child_count(self):\n return len(self.children)", "def size_subtree(tree, u):\n chil...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Returns the number of sample nodes in this tree underneath the specified node (including the node itself). If u is not specified return the total number of samples in the tree. This is a constant time operation.
def num_samples(self, u=None): u = self.virtual_root if u is None else u return self._ll_tree.get_num_samples(u)
[ "def num_samples(self, u=None):\n if u is None:\n return sum(self._ll_tree.get_num_samples(u) for u in self.roots)\n else:\n return self._ll_tree.get_num_samples(u)", "def size_subtree(tree, u):\n children = tree.successors(u)\n #base case: u is a leaf\n if not childre...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Returns a numpy array of node ids. Starting at `u`, returns the reachable descendant nodes in order of increasing time (most recent first), falling back to increasing ID if times are equal. Also see
def timeasc(self, u=NULL): nodes = self.preorder(u) is_virtual_root = u == self.virtual_root time = self.tree_sequence.nodes_time if is_virtual_root: # We could avoid creating this array if we wanted to, but # it's not that often people will be using this with the...
[ "def listNodeIds(self,ignoreStops=True):\n node_ids = []\n for node in self.n:\n nodeNum = int(node.num)\n if(ignoreStops):\n nodeNum = abs(nodeNum)\n node_ids.append(nodeNum)\n return node_ids", "def get_adjacent_nodes(self, u):\r\n retu...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Postorder traversal that visits leaves in minimum lexicographic order. Minlex stands for minimum lexicographic. We wish to visit a tree in such a way that the leaves visited, when their IDs are listed out, have minimum lexicographic order. This is a useful ordering for drawing multiple Trees of a TreeSequence, as it le...
def _minlex_postorder_traversal(self, root): # We compute a dictionary mapping from internal node ID to min leaf ID # under the node, using a first postorder traversal min_leaf = {} for u in self.nodes(root, order="postorder"): if self.is_leaf(u): min_leaf[u]...
[ "def preorder(tree):\n return _preorder(tree)", "def preorder(self):\n\n traversal = []\n self.preorder_helper(self.root, traversal)\n return traversal", "def pre_order(self):\n stack = []\n node = self\n while stack or node:\n if node:\n yield node.val...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Call into the fast but limited C implementation of the newick conversion.
def _as_newick_fast(self, *, root, precision, legacy_ms_labels): root_time = max(1, self.time(root)) max_label_size = math.ceil(math.log10(self.tree_sequence.num_nodes)) single_node_size = ( 5 + max_label_size + math.ceil(math.log10(root_time)) + precision ) buffer_si...
[ "def _convert():", "def ggml_conv_1d(ctx: ffi.CData, a: ffi.CData, b: ffi.CData, s0: int, p0: int, d0: int) -> ffi.CData:\n ...", "def convert(self):", "def ggml_map_binary_f32(ctx: ffi.CData, a: ffi.CData, b: ffi.CData, fun: ffi.CData) -> ffi.CData:\n ...", "def ggml_map_custom2_f32(ctx: ffi.CData, a...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Given observations for the samples in this tree described by the specified set of genotypes and alleles, return a parsimonious set of state transitions explaining these observations. The genotypes array is interpreted as indexes into the alleles list in the same manner as described in the
def map_mutations(self, genotypes, alleles, ancestral_state=None): genotypes = util.safe_np_int_cast(genotypes, np.int8) max_alleles = np.max(genotypes) if ancestral_state is not None: if isinstance(ancestral_state, str): # Will raise a ValueError if not in the list ...
[ "def alleles(self) -> set[str]:\n return {self.ancestral_state} | {m.derived_state for m in self.mutations}", "def gen_hypothesis(self) -> Onfsm:\n state_distinguish = dict()\n states_dict = dict()\n initial = None\n\n unified_S = self.S + self.S_dot_A\n\n stateCounter = ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Returns the KendallColijn distance between the specified pair of trees. The ``lambda_`` parameter determines the relative weight of topology vs branch lengths in calculating the distance. If ``lambda_`` is 0 (the default) we only consider topology, and if it is 1 we only consider branch lengths. See `Kendall & Colijn (...
def kc_distance(self, other, lambda_=0.0): return self._ll_tree.get_kc_distance(other._ll_tree, lambda_)
[ "def lambda_dist(A1, A2, k=None, p=2, kind=\"laplacian\"):\n # ensure valid k\n n1, n2 = [A.shape[0] for A in [A1, A2]]\n N = min(n1, n2) # minimum size between the two graphs\n if k is None or k > N:\n k = N\n\n # form matrices\n L1, L2 = [laplacian_matrix(A) for A in [A1, A2]]\n # get...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Returns the path length between two nodes (i.e., the number of edges between two nodes in this tree). If the two nodes have a most recent common ancestor, then this is defined as ``tree.depth(u) + tree.depth(v) 2 tree.depth(tree.mrca(u, v))``. If the nodes do not have an MRCA (i.e., they are in disconnected subtrees) t...
def path_length(self, u, v): mrca = self.mrca(u, v) if mrca == -1: return math.inf return self.depth(u) + self.depth(v) - 2 * self.depth(mrca)
[ "def distance(self, target1, target2=None):\n if target2 is None:\n return sum(\n n.branch_length\n for n in self.get_path(target1)\n if n.branch_length is not None\n )\n mrca = self.common_ancestor(target1, target2)\n return mr...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Returns the number of lineages present in this tree at time ``t``. This is defined as the number of branches in this tree (reachable from the samples) that intersect with ``t``. Thus, ``tree.num_lineages(t)`` is equal to 0 for any ``t`` greater than or equal to the time of the root in a singlyrooted tree.
def num_lineages(self, t): return self._ll_tree.get_num_lineages(t)
[ "def num_trees(self):\n return self._ll_tree_sequence.get_num_trees()", "def path_counter(t, n):\n\tif is_leaf(t):\n\t\treturn one(t.entry >= n)\n\telse:\n\t\treturn sum([path_counter(st, n - t.entry) for st in t.branches])", "def leaf_count(t):\n if len(t.children) == 0:\n # t is a leaf\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Parse the specified filelike object containing a whitespace delimited description of a population table and returns the corresponding
def parse_populations( source, strict=True, encoding="utf8", base64_metadata=True, table=None ): sep = None if strict: sep = "\t" if table is None: table = tables.PopulationTable() # Read the header and find the indexes of the required fields. header = source.readline().rstrip("\...
[ "def parse_populations(\n source, strict=True, encoding='utf8', base64_metadata=True, table=None):\n sep = None\n if strict:\n sep = \"\\t\"\n if table is None:\n table = tables.PopulationTable()\n # Read the header and find the indexes of the required fields.\n header = source.r...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Parse the specified filelike object containing a whitespace delimited description of a migration table and returns the corresponding
def parse_migrations( source, strict=True, encoding="utf8", base64_metadata=True, table=None ): sep = None if strict: sep = "\t" if table is None: table = tables.MigrationTable() header = source.readline().rstrip("\n").split(sep) left_index = header.index("left") right_index ...
[ "def parse_migration_file(migration_file_content, table_name=r'.*?'):\n info_mo = re.search(r'Schema::create\\([\\'\"]'\n r'(?P<table_name>\\w+)[\\'\"].*?\\).*?\\{'\n r'(?P<column_info>[\\s\\S]+?)\\}\\);',\n migration_file_content)\n info = ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Returns a dictionary mapping names to tables in the
def tables_dict(self): return self.tables.table_name_map
[ "def table_names(tables):\n return dict(map(lambda name: (name, table_name(name)), tables))", "def tables(self):\n if self.__tables is None:\n self.__tables = {}\n for key, value in self.__pvl:\n if key == 'Table':\n table = ISISTable(self.filename...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Writes a text representation of the tables underlying the tree sequence to the specified connections. If Base64 encoding is not used, then metadata will be saved directly, possibly resulting in errors reading the tables back in if metadata includes whitespace.
def dump_text( self, nodes=None, edges=None, sites=None, mutations=None, individuals=None, populations=None, migrations=None, provenances=None, precision=6, encoding="utf8", base64_metadata=True, ): text_formats....
[ "def store_contents(self):\n string_buffer = os.linesep.join(\n map(\n lambda x: os.linesep.join(\n [\"<begin_table>\"] + [x.name] + x.columns + [\"<end_table>\"]\n ),\n self.tables\n )\n )\n\n with open(METAD...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Return an html summary of a tree sequence. Called by jupyter notebooks to render a TreeSequence.
def _repr_html_(self): return util.tree_sequence_html(self)
[ "def summary():\n return render_template('summary.html')", "def summary(self):\n s = super(TreeClassifier, self).summary()\n if self.trained:\n s += \"\\n Node classifiers summaries:\"\n for i, (clfname, clf) in enumerate(self.clfs.iteritems()):\n s += '\\n + ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Returns the number of sample nodes in this tree sequence. This is also the number of sample nodes in each tree.
def num_samples(self): return self._ll_tree_sequence.get_num_samples()
[ "def nsamples(self) -> int:\n return self.shadow_tree.get_node_nsamples(self.id)", "def get_sample_counts(tree_sequence, st):\n nu = [0 for j in range(tree_sequence.get_num_nodes())]\n for j in range(tree_sequence.get_num_samples()):\n u = j\n while u != _tskit.NULL:\n nu[u] ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
The set of metadata schemas for the tables in this tree sequence.
def table_metadata_schemas(self) -> TableMetadataSchemas: return self._table_metadata_schemas
[ "def schemas(self):\n return model.Schemas(self)", "def schema_tables(self) -> List[str]:\n return list(self._query_provider.schema.keys())", "def get_tables_and_schemas(self):\n pass", "def schemas(self):\n if not self._schemas:\n self._schemas = get_schema(self.attribu...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Returns the min time in this tree sequence. This is the minimum of the node times and mutation times. Note that mutation times with the value ``tskit.UNKNOWN_TIME`` are ignored.
def min_time(self): return self._ll_tree_sequence.get_min_time()
[ "def min_time(self) -> str:\n return self._min_time", "def min_time(self):\n #{{{ function to return time of first sample\n\n return self.mintime", "def initialtime_min(self):\n return self._get_time_info([\"Initial_Time_M\", \"initialTimeMinute\"])", "def get_tmin(self):\n tmin...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Returns the max time in this tree sequence. This is the maximum of the node times and mutation times. Note that mutation times with the value ``tskit.UNKNOWN_TIME`` are ignored.
def max_time(self): return self._ll_tree_sequence.get_max_time()
[ "def max_time(self) -> float:\r\n if(len(self.operations_by_name) == 0):\r\n return -1\r\n return max(map(lambda x: x[\"time_step\"], self.operations_by_name.values()))", "def max_time(self) -> str:\n return self._max_time", "def max_root_time(self):\n if self.num_samples ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
The decoded metadata for this TreeSequence.
def metadata(self) -> Any: return self.metadata_schema.decode_row(self._ll_tree_sequence.get_metadata())
[ "def metadata(self) -> Dict:\n return self._metadata", "def metadata(self):\n return self._metadata if self._metadata is not None else u''", "def readMetaInfo(self):\n\t\tdata = self._fileSystem.readMetaInfo()\n\t\treturn data", "def getMetaData(self):\n return self._nodeMetaData", "def...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
String describing the units of the time dimension for this TreeSequence.
def time_units(self) -> str: return self._ll_tree_sequence.get_time_units()
[ "def units(self):\n return self._time_unit.name.capitalize()", "def timestep(self):\n return str(self._timeunit)", "def time_series_unit(self):\n return self._time_series_unit", "def time_unit(self):\n return self._time_unit", "def get_units(self):\n return \"\"", "def t...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Returns the time of the oldest root in any of the trees in this tree sequence. This is usually equal to ``np.max(ts.tables.nodes.time)`` but may not be since there can be nonsample nodes that are not present in any tree. Note that isolated samples are also defined as roots (so there can be a max_root_time even in a tre...
def max_root_time(self): if self.num_samples == 0: raise ValueError( "max_root_time is not defined in a tree sequence with 0 samples" ) ret = max(self.nodes_time[u] for u in self.samples()) if self.num_edges > 0: # Edges are guaranteed to be li...
[ "def min_time(self):\n return self._ll_tree_sequence.get_min_time()", "def max_time(self):\n return self._ll_tree_sequence.get_max_time()", "def timeasc(self, u=NULL):\n nodes = self.preorder(u)\n is_virtual_root = u == self.virtual_root\n time = self.tree_sequence.nodes_time\...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Returns the breakpoints that separate trees along the chromosome, including the two extreme points 0 and L. This is equivalent to >>> iter([0] + [t.interval.right for t in self.trees()]) By default we return an iterator over the breakpoints as Python float objects; if ``as_array`` is True we return them as a numpy arra...
def breakpoints(self, as_array=False): breakpoints = self.ll_tree_sequence.get_breakpoints() if not as_array: # Convert to Python floats for backward compatibility. breakpoints = map(float, breakpoints) return breakpoints
[ "def breakpoints(self):\n yield 0\n for t in self.trees():\n yield t.interval[1]", "def binary_trees(self):\n for ip in self.lower_contained_intervals():\n yield ip.upper_binary_tree()", "def __iter__(self):\n if self.findsymbols():\n raise TypeError(...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Returns the tree covering the specified genomic location. The returned tree will have ``tree.interval.left`` <= ``position`` < ``tree.interval.right``.
def at(self, position, **kwargs): tree = Tree(self, **kwargs) tree.seek(position) return tree
[ "def get_rand_tree(position):\n max_width = random.randint(50, 100)\n min_width = random.randint(5, 10)\n itter_width = random.randint(5, 20)\n itter_height = random.randint(5, 20)\n random_tree = Tree(max_width, min_width, itter_width,\n itter_height)\n random_tree.loc_trans...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Returns an iterator over the pairs of trees for each distinct interval in the specified pair of tree sequences.
def coiterate(self, other, **kwargs): if self.sequence_length != other.sequence_length: raise ValueError("Tree sequences must be of equal sequence length.") L = self.sequence_length trees1 = self.trees(**kwargs) trees2 = other.trees(**kwargs) tree1 = next(trees1) ...
[ "def iterRanges(self):\r\n\r\n for sr in self.subranges:\r\n for r in sr.iterRanges():\r\n yield r\r\n\r\n if self.parent!=None:\r\n yield self.parent, self.recursive", "def expand_ranges(ranges):\n for low, high in low_high_pairs:\n for j in range(low,...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Returns the length``num_individuals`` array containing, for each individual, the ``population`` attribute of their nodes, or ``tskit.NULL`` for individuals with no nodes. Errors if any individual has nodes with inconsistent nonNULL populations.
def individuals_population(self): if self._individuals_population is None: self._individuals_population = ( self._ll_tree_sequence.get_individuals_population() ) return self._individuals_population
[ "def testNumberIndividuals(self):\n self.assertEqual(1690, self.tree.get_number_individuals())\n self.assertEqual(120, self.tree.get_number_individuals(fragment=\"fragment1\"))\n self.assertEqual(280, self.tree.get_number_individuals(fragment=\"fragment2\"))", "def create_population(self, n_i...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Returns the length``num_individuals`` array containing, for each individual, the ``time`` attribute of their nodes or ``np.nan`` for individuals with no nodes. Errors if any individual has nodes with inconsistent times.
def individuals_time(self): if self._individuals_time is None: self._individuals_time = self._ll_tree_sequence.get_individuals_time() return self._individuals_time
[ "def build_metrics_times_data(time_metrics):\n return [{'name': name, 'latencies': latencies.get_latencies()}\n for name, latencies in iteritems(time_metrics)]", "def get_times(self):\n self.ensureDetection()\n times=[]\n for ap in self.APs:\n times.append(ap[\"T\"])\...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Convenience method returning the ``num_individuals x n`` array whose row kth row contains the ``location`` property of the kth individual. The method only works if all individuals' locations have the same length (which is ``n``), and errors otherwise.
def individuals_location(self): if self._individuals_location is None: individuals = self.tables.individuals n = 0 lens = np.unique(np.diff(individuals.location_offset)) if len(lens) > 1: raise ValueError("Individual locations are not all the same ...
[ "def number_of_locations(self):\n return self._number_of_locations", "def num_locations(self):\n return len(self.locations)", "def locations_count(self):\n return len(self.locations)", "def agent_count(city):\n agents = 0\n empty = 0\n landmarks = 0\n for (x,y), house in np.nd...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Efficient access to the ``edge_insertion_order`` column in the
def indexes_edge_insertion_order(self): return self._indexes_edge_insertion_order
[ "def indexes_edge_removal_order(self):\n return self._indexes_edge_removal_order", "def ordering(self):\n return self._ordering", "def gather_referring_orders (gdbval):\n# TODO: Somehow also note speculative references and attributes in\n# general\n vec = gdbval[\"referring\"]\n return [int(...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Efficient access to the ``edge_removal_order`` column in the
def indexes_edge_removal_order(self): return self._indexes_edge_removal_order
[ "def indexes_edge_insertion_order(self):\n return self._indexes_edge_insertion_order", "def remove_edge(e, R):\n\tR.remove_edge(e[0], e[1])\n\tupdate_after_mod(e,R)", "def remove_edge(self, edge: Edge) -> Edge:", "def get_edge(self, e):\r\n return self.edges[e]", "def targeted_order(ugraph):\n...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Returns an array of the sample node IDs in this tree sequence. If `population` is specified, only return sample IDs from that population. It is also possible to restrict samples by time using the parameter `time`. If `time` is a numeric value, only return sample IDs whose node time is approximately equal to the specifi...
def samples(self, population=None, *, population_id=None, time=None): if population is not None and population_id is not None: raise ValueError( "population_id and population are aliases. Cannot specify both" ) if population_id is not None: population ...
[ "def samples(self, population=None, population_id=None):\n if population is not None and population_id is not None:\n raise ValueError(\n \"population_id and population are aliases. Cannot specify both\")\n if population_id is not None:\n population = population_id...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Returns a simplified tree sequence that retains only the history of the nodes given in the list ``samples``. If ``map_nodes`` is true, also return a numpy array whose ``u``th element is the ID of the node in the simplified tree sequence that corresponds to node ``u`` in the
def simplify( self, samples=None, *, map_nodes=False, reduce_to_site_topology=False, filter_populations=None, filter_individuals=None, filter_sites=None, filter_nodes=None, update_sample_flags=None, keep_unary=False, keep_un...
[ "def tree_sequence(self, samples=None):\n if samples is None:\n samples = self.sample_ids()\n else:\n self.check_ids(samples)\n self.update_times()\n if self.timings is not None:\n start = timer.process_time()\n self.tables.sort()\n self.mar...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Returns a copy of this tree sequence with the specified sites (and their associated mutations) entirely removed. The site IDs do not need to be in any particular order, and specifying the same ID multiple times does not have any effect (i.e., calling ``tree_sequence.delete_sites([0, 1, 1])`` has the same effect as call...
def delete_sites(self, site_ids, record_provenance=True): tables = self.dump_tables() tables.delete_sites(site_ids, record_provenance) return tables.tree_sequence()
[ "def delete_site_mutations(tables, site_ids, record_provenance=True):\n keep_sites = np.ones(len(tables.sites), dtype=bool)\n site_ids = site_ids.astype(np.int32)\n if np.any(site_ids < 0) or np.any(site_ids >= len(tables.sites)):\n raise ValueError(\"Site ID out of bounds\")\n keep_sites[site_id...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Returns a copy of this tree sequence for which information in the specified list of genomic intervals has been deleted. Edges spanning these intervals are truncated or deleted, and sites and mutations falling within them are discarded. Note that it is the information in the intervals that is deleted, not the intervals ...
def delete_intervals(self, intervals, simplify=True, record_provenance=True): tables = self.dump_tables() tables.delete_intervals(intervals, simplify, record_provenance) return tables.tree_sequence()
[ "def delta_interval_deletion(self):\n\n self.debug('delta interval deletes')\n\n # We do a delta-debugging style thing here where we initially try to\n # delete many intervals at once and prune it down exponentially to\n # eventually only trying to delete one interval at a time.\n\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Returns a copy of this tree sequence which includes only information in the specified list of genomic intervals. Edges are truncated to lie within these intervals, and sites and mutations falling outside these intervals are discarded. Note that it is the information outside the intervals that is deleted, not the interv...
def keep_intervals(self, intervals, simplify=True, record_provenance=True): tables = self.dump_tables() tables.keep_intervals(intervals, simplify, record_provenance) return tables.tree_sequence()
[ "def delete_intervals(self, intervals, simplify=True, record_provenance=True):\n tables = self.dump_tables()\n tables.delete_intervals(intervals, simplify, record_provenance)\n return tables.tree_sequence()", "def trim_region(self, start, stop):\n if stop > len(self.bases):\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Returns a copy of this tree sequence in which we replace any edge ``(left, right, parent, child)`` in which ``node_time[child] < time < node_time[parent]`` with two edges ``(left, right, parent, u)`` and ``(left, right, u, child)``, where ``u`` is a newly added node for each intersecting edge. If ``metadata``, ``flags`...
def split_edges(self, time, *, flags=None, population=None, metadata=None): population = tskit.NULL if population is None else population flags = 0 if flags is None else flags schema = self.table_metadata_schemas.node if metadata is None: metadata = schema.empty_value ...
[ "def _alter_node(node):\n if isinstance(node, (de.TFRecordDataset, de.TextFileDataset)) and node.shuffle_level == de.Shuffle.GLOBAL:\n # Remove the connection between the parent's node to the current node because we are inserting a node.\n if node.output:\n node.output.pop()\n # P...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Delete all edge topology and mutational information at least as old as the specified time from this tree sequence. Removes all edges in which the time of the child is >= the specified time ``t``, and breaks edges that intersect with ``t``. For each edge intersecting with ``t`` we create a new node with time equal to ``...
def decapitate(self, time, *, flags=None, population=None, metadata=None): split_ts = self.split_edges( time, flags=flags, population=population, metadata=metadata ) tables = split_ts.dump_tables() del split_ts tables.delete_older(time) return tables.tree_sequ...
[ "def split_edges(self, time, *, flags=None, population=None, metadata=None):\n population = tskit.NULL if population is None else population\n flags = 0 if flags is None else flags\n schema = self.table_metadata_schemas.node\n if metadata is None:\n metadata = schema.empty_val...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Returns an expanded tree sequence which contains the nodewise union of ``self`` and ``other``, obtained by adding the nonshared portions of ``other`` onto ``self``. The "shared" portions are specified using a map that specifies which nodes in ``other`` are equivalent to those in
def union( self, other, node_mapping, check_shared_equality=True, add_populations=True, record_provenance=True, ): tables = self.dump_tables() other_tables = other.dump_tables() tables.union( other_tables, node_mapping, ...
[ "def union(self, other):\n union = MySet()\n for i in range(self.n):\n union.add(self.set[i])\n\n for i in range(len(other)):\n union.add(other[i])\n\n return union", "def join_union(self, other):\n\n assert type(self) is type(other), 'Expected NestedRE ins...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Return an SVG representation of a tree sequence. See the
def draw_svg( self, path=None, *, size=None, x_scale=None, time_scale=None, tree_height_scale=None, node_labels=None, mutation_labels=None, root_svg_attributes=None, style=None, order=None, force_root_branch=None, ...
[ "def generate_svg(tree):\n tree = tree_normalize(tree)\n\n dwg = svgwrite.Drawing(size=get_max_vals(tree))\n\n # Add each branch to the drawing\n for branch in tree:\n width = math.floor(find_branch_length(branch) / 8)\n if width < 1:\n width = 1\n color = svgwrite.rgb(13...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
r""" Computes mean genetic divergence between (and within) pairs of sets of nodes from ``sample_sets``. This is the "average number of differences", usually referred to as "dxy"; a common citation for this definition is Nei and Li (1979), who called it
def divergence( self, sample_sets, indexes=None, windows=None, mode="site", span_normalise=True ): return self.__k_way_sample_set_stat( self._ll_tree_sequence.divergence, 2, sample_sets, indexes=indexes, windows=windows, mode=mo...
[ "def mean_descendants(self, sample_sets):\n return self._ll_tree_sequence.mean_descendants(sample_sets)", "def group_divergence(self):\n total_div = 0\n num_pairs = 0\n for g1,g2 in self.pairwise_group_generator:\n m1 = np.mean(self.get_group_values(g1))\n m2 = np...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Returns a list of (at most) num_chunks windows, which represent splitting up the specified list of windows into roughly equal work. Currently this is implemented by just splitting up into roughly equal numbers of windows in each chunk.
def _chunk_windows(windows, num_chunks): if num_chunks <= 0 or int(num_chunks) != num_chunks: raise ValueError("Number of chunks must be an integer > 0") num_chunks = min(len(windows) - 1, num_chunks) splits = np.array_split(windows[:-1], num_chunks) chunks = [] for j...
[ "def _get_chunked_windows(\n chunks: ArrayLike,\n window_starts: ArrayLike,\n window_stops: ArrayLike,\n) -> Tuple[ArrayLike, ArrayLike]:\n\n # Find the indexes for the start positions of all chunks\n chunk_starts = _sizes_to_start_offsets(chunks)\n\n # Find which chunk each window falls in\n c...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
No windows were specified, so we can chunk up the whole genome by tree, and do a simple sum of the results. This means that we have to handle span_normalise specially, though.
def _parallelise_divmat_by_tree(self, num_threads, span_normalise, **kwargs): def worker(interval): return self._ll_tree_sequence.divergence_matrix(interval, **kwargs) work = self._chunk_sequence_by_tree(num_threads) with concurrent.futures.ThreadPoolExecutor(max_workers=num_thread...
[ "def _compute_delta_normalizer(self, delta_window=2):\n self._delta_normalizer = 0\n self._delta_window = delta_window\n\n self._delta_window_array = np.array(\n range(-1 * self._delta_window, self._delta_window + 1))\n self._delta_normalizer = np.sum(np.square(self._delta_window_array))\n sel...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Computes genetic relatedness between (and within) pairs of sets of nodes from ``sample_sets``. Operates on ``k = 2`` sample sets at a time; please see the
def genetic_relatedness( self, sample_sets, indexes=None, windows=None, mode="site", span_normalise=True, polarised=False, proportion=True, ): if proportion: # TODO this should be done in C also all_samples = list({u for...
[ "def process_sampleset(G, sampleset):\n # Get the best solution to display\n sample = sampleset.first.sample\n\n # Get a subset of the original graph (just the nodes assigned to group 1)\n set1_nodes = [node for node in sample if sample[node] == 1]\n subgraph1 = G.subgraph(set1_nodes)\n set0_nodes...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
r""" Computes weighted genetic relatedness. If the kth pair of indices is (i, j) then the kth column of output will be
def genetic_relatedness_weighted( self, W, indexes=None, windows=None, mode="site", span_normalise=True, polarised=False, ): if len(W) != self.num_samples: raise ValueError( "First trait dimension must be equal to number of ...
[ "def _dominantWeights(self, weight):\n keyStore = tuple(weight)\n if keyStore in self._dominantWeightsStore:\n return self._dominantWeightsStore[keyStore]\n # convert the weight\n weight = np.array([weight], dtype=int)\n listw = [weight]\n counter = 1\n wh...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Computes the mean squared correlations between each of the columns of ``W`` (the "phenotypes") and inheritance along the tree sequence.
def trait_correlation(self, W, windows=None, mode="site", span_normalise=True): if W.shape[0] != self.num_samples: raise ValueError( "First trait dimension must be equal to number of samples." ) sds = np.std(W, axis=0) if np.any(sds == 0): rais...
[ "def weighted_correlation(x, y, w):\n\n def weighted_mean(x, w):\n \"\"\"Weighted Mean\"\"\"\n return np.sum(x * w) / np.sum(w)\n\n def weighted_cov(x, y, w):\n \"\"\"Weighted Covariance\"\"\"\n return np.sum(w * (x - weighted_mean(x, w)) * (y - weighted_mean(y, w))) / np.sum(w)\n\...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Computes the density of segregating sites for each of the sets of nodes from ``sample_sets``, and related quantities.
def segregating_sites( self, sample_sets=None, windows=None, mode="site", span_normalise=True ): return self.__one_way_sample_set_stat( self._ll_tree_sequence.segregating_sites, sample_sets, windows=windows, mode=mode, span_normalise=span_n...
[ "def Tajimas_D(self, sample_sets=None, windows=None, mode=\"site\"):\n\n # TODO this should be done in C as we'll want to support this method there.\n def tjd_func(sample_set_sizes, flattened, **kwargs):\n n = sample_set_sizes\n T = self.ll_tree_sequence.diversity(n, flattened, *...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Computes the allele frequency spectrum (AFS) in windows across the genome for with respect to the specified ``sample_sets``.
def allele_frequency_spectrum( self, sample_sets=None, windows=None, mode="site", span_normalise=True, polarised=False, ): if sample_sets is None: sample_sets = [self.samples()] return self.__one_way_sample_set_stat( self._ll_tr...
[ "def onsets_to_onset_times(onsets, fs, N, hop):\n\n onset_times = (onsets * np.arange(0, len(onsets)) * hop + N / 2) / fs \n return onset_times[onset_times > N / 2 / fs]", "def calc_sfs(aln):\n\n sfs_folded = [0 for i in range(int(aln.ns / 2) + 1)]\n for site_index in range(aln.ls):\n site_freq = e...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Computes Tajima's D of sets of nodes from ``sample_sets`` in windows.
def Tajimas_D(self, sample_sets=None, windows=None, mode="site"): # TODO this should be done in C as we'll want to support this method there. def tjd_func(sample_set_sizes, flattened, **kwargs): n = sample_set_sizes T = self.ll_tree_sequence.diversity(n, flattened, **kwargs) ...
[ "def Fst(\n self, sample_sets, indexes=None, windows=None, mode=\"site\", span_normalise=True\n ):\n # TODO this should really be implemented in C (presumably C programmers will want\n # to compute Fst too), but in the mean time implementing using the low-level\n # calls has two advan...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Computes "windowed" Fst between pairs of sets of nodes from ``sample_sets``. Operates on ``k = 2`` sample sets at a time; please see the
def Fst( self, sample_sets, indexes=None, windows=None, mode="site", span_normalise=True ): # TODO this should really be implemented in C (presumably C programmers will want # to compute Fst too), but in the mean time implementing using the low-level # calls has two advantages: (a) w...
[ "def f2(\n self, sample_sets, indexes=None, windows=None, mode=\"site\", span_normalise=True\n ):\n return self.__k_way_sample_set_stat(\n self._ll_tree_sequence.f2,\n 2,\n sample_sets,\n indexes=indexes,\n windows=windows,\n mode=mo...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Computes the 'Y' statistic between triples of sets of nodes from ``sample_sets``. Operates on ``k = 3`` sample sets at a time; please see the
def Y3( self, sample_sets, indexes=None, windows=None, mode="site", span_normalise=True ): return self.__k_way_sample_set_stat( self._ll_tree_sequence.Y3, 3, sample_sets, indexes=indexes, windows=windows, mode=mode, ...
[ "def Y2(\n self, sample_sets, indexes=None, windows=None, mode=\"site\", span_normalise=True\n ):\n return self.__k_way_sample_set_stat(\n self._ll_tree_sequence.Y2,\n 2,\n sample_sets,\n indexes=indexes,\n windows=windows,\n mode=mo...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Computes the 'Y2' statistic between pairs of sets of nodes from ``sample_sets``. Operates on ``k = 2`` sample sets at a time; please see the
def Y2( self, sample_sets, indexes=None, windows=None, mode="site", span_normalise=True ): return self.__k_way_sample_set_stat( self._ll_tree_sequence.Y2, 2, sample_sets, indexes=indexes, windows=windows, mode=mode, ...
[ "def f2(\n self, sample_sets, indexes=None, windows=None, mode=\"site\", span_normalise=True\n ):\n return self.__k_way_sample_set_stat(\n self._ll_tree_sequence.f2,\n 2,\n sample_sets,\n indexes=indexes,\n windows=windows,\n mode=mo...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Computes the 'Y1' statistic within each of the sets of nodes given by ``sample_sets``.
def Y1(self, sample_sets, windows=None, mode="site", span_normalise=True): return self.__one_way_sample_set_stat( self._ll_tree_sequence.Y1, sample_sets, windows=windows, mode=mode, span_normalise=span_normalise, )
[ "def Y2(\n self, sample_sets, indexes=None, windows=None, mode=\"site\", span_normalise=True\n ):\n return self.__k_way_sample_set_stat(\n self._ll_tree_sequence.Y2,\n 2,\n sample_sets,\n indexes=indexes,\n windows=windows,\n mode=mo...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Computes Patterson's f4 statistic between four groups of nodes from ``sample_sets``. Operates on ``k = 4`` sample sets at a time; please see the
def f4( self, sample_sets, indexes=None, windows=None, mode="site", span_normalise=True ): return self.__k_way_sample_set_stat( self._ll_tree_sequence.f4, 4, sample_sets, indexes=indexes, windows=windows, mode=mode, ...
[ "def subsample_fourier(x, k):\n return subsamplefourier(x,k)", "def CombineDataExperiment05(numShuffles): \n datasets = ['U133A_combat_DMFS', 'U133A_combat_RFS']\n networks = [\n 'nwEdgesKEGG', \n 'nwEdgesHPRD9', \n 'nwEdgesI2D', \n 'nwEdgesIPP'\n ]\n pathways = ['nwGeneS...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
r""" Computes Patterson's f3 statistic between three groups of nodes from ``sample_sets``.
def f3( self, sample_sets, indexes=None, windows=None, mode="site", span_normalise=True ): return self.__k_way_sample_set_stat( self._ll_tree_sequence.f3, 3, sample_sets, indexes=indexes, windows=windows, mode=mode, ...
[ "def Y3(\n self, sample_sets, indexes=None, windows=None, mode=\"site\", span_normalise=True\n ):\n return self.__k_way_sample_set_stat(\n self._ll_tree_sequence.Y3,\n 3,\n sample_sets,\n indexes=indexes,\n windows=windows,\n mode=mo...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Computes Patterson's f2 statistic between two groups of nodes from ``sample_sets``. Operates on ``k = 2`` sample sets at a time; please see the
def f2( self, sample_sets, indexes=None, windows=None, mode="site", span_normalise=True ): return self.__k_way_sample_set_stat( self._ll_tree_sequence.f2, 2, sample_sets, indexes=indexes, windows=windows, mode=mode, ...
[ "def K2pgram2(x, y, f1, fs, AT, ATA):\n amp2s = np.zeros_like(fs)\n for i, f2 in enumerate(fs):\n if f1 != f2:\n amp2s[i] = eval_2nd_freq(x, y, f1, f2, AT, ATA)\n return amp2s", "def ks_test(df1, df2):\n p_val_list = []\n stat_list = []\n for element in df1.columns:\n re...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Computes for every node the mean number of samples in each of the `sample_sets` that descend from that node, averaged over the portions of the genome for which the node is ancestral to any sample. The output is an array, `C[node, j]`, which reports the total span of all genomes in `sample_sets[j]` that inherit from `no...
def mean_descendants(self, sample_sets): return self._ll_tree_sequence.mean_descendants(sample_sets)
[ "def mean_descendants(self, reference_sets):\n return self._ll_tree_sequence.mean_descendants(reference_sets)", "def _count_pair_coalescence_events(node, tree, sample_sets):\n\n # TODO needs to be optimized, use np.intersect1d\n children = tree.children(node)\n samples_per_child = [set...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Returns the pairwise nucleotide site diversity, the average number of sites that differ between a every possible pair of distinct samples. If `samples` is specified, calculate the diversity within this set.
def pairwise_diversity(self, samples=None): if samples is None: samples = self.samples() return float( self.diversity( [samples], windows=[0, self.sequence_length], span_normalise=False )[0] )
[ "def pairwise_diversity(calls):\n # Count up the number of reference and alternate genotypes.\n if 0 in calls:\n ref_count = calls.count(0)\n else:\n return 0\n if 1 in calls:\n alt_count = calls.count(1)\n else:\n return 0\n # This sample size will change depending...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Write ``ms`` formatted output from the genotypes of a tree sequence
def write_ms( tree_sequence, output, print_trees=False, precision=4, num_replicates=1, write_header=True, ): if not isinstance(tree_sequence, collections.abc.Iterable): tree_sequence = [tree_sequence] i = 0 for tree_seq in tree_sequence: if i > 0: write_h...
[ "def printGeneTree(self):\n align = AlignIO.read(self.newPhylip, 'phylip') # Reads created .phy file containing the SeqRecord\n #print (align) # prints concatenated allignments\n calculator = DistanceCalculator('identity')\n dm = calculator.get_distance(align)# Calculate the distance ma...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
The location of the Certfificate Authority data used for SSL, or None if SSL is not enabled
def ssl_ca_location(self): if "ssl.ca.location" not in self._config: return None return self._config["ssl.ca.location"]
[ "def trusted_cert_path(self) -> Optional[Any]:\n return pulumi.get(self, \"trusted_cert_path\")", "def GetCurrentCertsFile():\n return _ca_certs_file", "def ssl_cert(self) -> Optional[pulumi.Input[str]]:\n return pulumi.get(self, \"ssl_cert\")", "def ssl_cert(self) -> pulumi.Output[Optional[str...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
The OpenID Connect token endpoint, or None if OpenID Connect is not enabled
def token_endpoint(self): return self._config.get("sasl.oauthbearer.token.endpoint.url")
[ "def oauth_oidc_token_endpoint(self) -> str:\n return self._oauth_oidc_token_endpoint", "def token_endpoint(self) -> str:\n return pulumi.get(self, \"token_endpoint\")", "def get_auth_token_url() -> str:\n return f\"{KONFUZIO_HOST}/api/token-auth/\"", "def authorization_endpoint(self) -> Opti...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Configures Auth instances from a configuration file.
def load_auth(config_file=None): if config_file is None: config_file = configure.get_config_path("auth") # If finding data automatically, as a fallback, look to see if the auth data is in the main # config in the old style. if not os.path.exists(config_file): main_config_...
[ "def load_credentials(self):\n if self.rc_file is None:\n return\n config = configparser.ConfigParser()\n rc = os.path.expanduser(self.rc_file)\n if os.path.exists(rc):\n config.read(rc)\n trace(1, \"load credentials from\", rc)\n try:\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Remove auth data from a general configuration file. This can be needed when updating auth data which was read from the general config for backwards compatibility, but is then written out to the correct new location in a separate auth config, as is now proper. With no further action, this would leave a vestigial copy fr...
def prune_outdated_auth(config_file=None): if config_file is None: config_file = configure.get_config_path("general") if not os.path.exists(config_file): return # nothing to do! with open(config_file, "r") as f: try: config_data = toml.loads(f.read()) except Exce...
[ "def auth_revoke_all(uid):\n\n cp = configparser.ConfigParser()\n cp.optionxform = str\n cp.read(DB_FILE)\n\n user = pwd.getpwuid(uid).pw_name\n\n sections = cp.sections()\n for title in sections:\n if title.startswith(\"user:%s:\" % user):\n cp.remove_section(title)\n\n with ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Selects the most appropriate credential to use when attempting to contact the given host.
def select_matching_auth(creds, hostname, username=None): matches = [] inexact_matches = [] exact_hostname_match = False inexact_hostname_match = False target_host, target_port = _decompose_host_port(hostname) default_port = "9092" for cred in creds: maybe_exact_hostname_match = Fa...
[ "def get_credentials(host):\n netrc_hosts = netrc.netrc().hosts\n if host in netrc_hosts:\n return netrc_hosts[host][0], netrc_hosts[host][2]\n return None, None", "def rpc_credential(unpack, verifier=False):\n try:\n # Get credential/verifier flavor\n flavor = unpack.unpack_uint(...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Ensure that a value entered for a hostname looks plausible. The user is supposed to enter a hostname, possibly with a port, not a URL.
def _validate_hostname(input: str): if len(input) == 0: return input name_re = re.compile(r"^(kafka://)?(([^[:/]+|\[[^\]/]+\])(:[0-9]*)?)$") match = name_re.match(input) if match is None: raise RuntimeError("Unable to parse hostname. " "Please enter either `hos...
[ "def test_utils_is_valid_hostname_invalid(self):\n # A hostname that's empty, None, or more than 255 chars is invalid\n empty_hostname = ''\n res = is_valid_hostname(empty_hostname)\n self.assertFalse(res)\n\n none_hostname = None\n res = is_valid_hostname(none_hostname)\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Import a credential from a CSV file or obtain it interactively from the user.
def read_new_credential(csv_file=None): options = {} if csv_file is None: logger.info("Generating configuration with user-specified username + password") username = input("Username: ") if len(username) == 0: raise RuntimeError("Username may not be empty") password = g...
[ "def importCsvAsCreds(self, filename):\n #todo strip whitespace\n self.gLogging.debug(\"importCsvAsCreds invoked\")\n MyCred = Query()\n try:\n with open(filename, 'r') as infile:\n for line in infile:\n if len(line) > 4:\n\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Write configuration file for the set of credentials. Creates containing directories as needed.
def write_auth_data(config_file, credentials): cred_list = [] for cred in credentials: cred_dict = {"username": cred.username, "password": cred.password, "protocol": cred.protocol, "mechanism": cred.mechanism, "token_endpoint": cred.token_endpoint} if le...
[ "def _writeConfigFile(self):\n configfile = open(self.config_file, \"w\")\n self.config.write(configfile)\n configfile.close()", "def write_config(host, tenant, login, password, profile='DEFAULT'):\n configpath = pathlib.Path().home() / '.preservica/config.json'\n if configpath....
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Create an error message for an ambiguous request to delete a credential. This function should only be used by `delete_credential`.
def _construct_ambiguous_deletion_message(username, hostname, matches): err = f"Ambiguous credentials found for username '{username}'" if hostname is not None: err += f" with hostname '{hostname}'\n" else: err += " with no hostname specified\n" err += "Matched credentials:" for match...
[ "def error_message(cls, identifier, error_status, error_message):\n return OPDSMessage(identifier.urn, error_status, error_message)", "def create_error_message(message='Error was happened.'):\n return {'error': message}", "def error(endpoint, reason, advice=None):\r\n return u'7::%s:%s+%s' % (endpo...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Test API can create a pressure (POST request)
def test_pressure_creation(self): res = self.client().post('/pressures/', data = self.pressure) self.assertEqual(res.status_code, 201) self.assertIn('120', str(res.data))
[ "def test_perturb_sensor_post(self):\n Parameters = Parameters1()\n response = self.client.open('/perturb/sensor',\n method='POST',\n data=json.dumps(Parameters),\n content_type='application/json')...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Test API can get a pressure (GET request).
def test_api_can_get_all_pressures(self): res = self.client().post('/pressures/', data=self.pressure) self.assertEqual(res.status_code, 201) res = self.client().get('/pressures/') self.assertEqual(res.status_code, 200) self.assertIn('120', str(res.data))
[ "def test_api_can_get_pressure_by_id(self):\n rv = self.client().post('/pressures/', data=self.pressure)\n self.assertEqual(rv.status_code, 201)\n result_in_json = json.loads(rv.data.decode('utf-8').replace(\"'\", \"\\\"\"))\n result = self.client().get(\n '/pressures/{}'.form...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Test API can get a single pressure by using it's id.
def test_api_can_get_pressure_by_id(self): rv = self.client().post('/pressures/', data=self.pressure) self.assertEqual(rv.status_code, 201) result_in_json = json.loads(rv.data.decode('utf-8').replace("'", "\"")) result = self.client().get( '/pressures/{}'.format(result_in_jso...
[ "def test_prisons_id_get(self):\n headers = { \n 'Accept': 'application/json',\n }\n response = self.client.open(\n '/v0.0.1/prisons/{id}'.format(id='id_example'),\n method='GET',\n headers=headers)\n self.assert200(response,\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Parses incoming filters paramters and converts them to Django usable operations if valid. BE AWARE! WILL NOT WORK UNLESS POSITIONAL ARGUMENT 3 IS FILTERS!
def parse_filters(func, *args, **kwargs): request = args[1] filters = request.query_params.get("filters", None) if not filters: return func(*args, **kwargs) cleaned_filters = {} try: filters = json.loads(filters) for field, operations in filters.items(): for oper...
[ "def parse_filters(func, *args, **kwargs):\n request = args[1]\n filters = request.query_params.get('filters', None)\n\n if not filters:\n return func(*args, **kwargs)\n cleaned_filters = {}\n try:\n filters = json.loads(filters)\n for field, operations in filters.items():\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Find the vector of this word. Maybe it is in the word2vec file, maybe it's in the unknown word2vec list.
def find_word(self, word): # word out of w2v if word not in self.w2v_idx: raise ValueError("word not in this word2vec: %s" % word) index = self.w2v_idx[word] if index >= self.word_len: vector = self.w2v_out[index - self.word_len] else: self.w2...
[ "def w2v_get_vector(word, model=None):\n try:\n return model.get_vector(word)\n except Exception as e:\n return None", "def get_word_vector(self, word: str):\n if word in self.word_vectors:\n return self.word_vectors[word]\n else:\n output_vector = self.make...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Add the unknown word into the total Word2Vec
def add_word(self, word, vector=None, low=-2., high=2.): if word not in self.w2v_idx: self.w2v_idx[word] = len(self.w2v_idx) if vector is None: vector = np.random.uniform(low=low, high=high, size=(self.w2v_dim,)) self.w2v_out.append(np.asarray(vector, dtype=np...
[ "def add_word(self, word):\n if word not in self.word2idx:\n self.word2idx[word] = len(self.idx2word)\n self.idx2word.append(word)\n return self.word2idx[word]", "def add_unknown_words(word_vecs, vocab, embedding_size = 300):\r\n for word in vocab:\r\n if word not in ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Split dataset into stratified cross validation folds.
def stratified_kfold_cross_validation(X, y, n_splits=5): #Define variables X_train_folds = [] X_test_folds = [] #Create dictionary y_dict = myutils.group_by(y) #Split data folds = [[] for _ in range(n_splits)] for category in y_dict.keys(): index = y_dict[category] ...
[ "def cross_validation_split(data, folds_number):\n\n folds = split_in_folds(data, folds_number)\n sets = cross_validation_sets(folds)\n\n return sets", "def stratified_kfold_cross_validation(X, y, n_splits=5):\r\n indices = [x for x in range(0, len(X))]\r\n labels = []\r\n uniq_feat = []\r\n\r\n...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }