Search is not available for this dataset
text
stringlengths
75
104k
def listen(self, func): """ Listen to parameters change. Parameters ---------- func : callable Function to be called when a parameter changes. """ self._C0.listen(func) self._C1.listen(func)
def _LhD(self): """ Implements Lₕ and D. Returns ------- Lh : ndarray Uₕᵀ S₁⁻½ U₁ᵀ. D : ndarray (Sₕ ⊗ Sₓ + Iₕₓ)⁻¹. """ from numpy_sugar.linalg import ddot self._init_svd() if self._cache["LhD"] is not None: ...
def value(self): """ Covariance matrix K = C₀ ⊗ GGᵀ + C₁ ⊗ I. Returns ------- K : ndarray C₀ ⊗ GGᵀ + C₁ ⊗ I. """ C0 = self._C0.value() C1 = self._C1.value() return kron(C0, self._GG) + kron(C1, self._I)
def gradient(self): """ Gradient of K. Returns ------- C0 : ndarray Derivative of C₀ over its parameters. C1 : ndarray Derivative of C₁ over its parameters. """ self._init_svd() C0 = self._C0.gradient()["Lu"].T C1 =...
def gradient_dot(self, v): """ Implements ∂K⋅v. Parameters ---------- v : array_like Vector from ∂K⋅v. Returns ------- C0.Lu : ndarray ∂K⋅v, where the gradient is taken over the C₀ parameters. C1.Lu : ndarray ∂...
def solve(self, v): """ Implements the product K⁻¹⋅v. Parameters ---------- v : array_like Array to be multiplied. Returns ------- x : ndarray Solution x to the equation K⋅x = y. """ from numpy_sugar.linalg import ...
def logdet(self): """ Implements log|K| = - log|D| + n⋅log|C₁|. Returns ------- logdet : float Log-determinant of K. """ self._init_svd() return -log(self._De).sum() + self.G.shape[0] * self.C1.logdet()
def logdet_gradient(self): """ Implements ∂log|K| = Tr[K⁻¹∂K]. It can be shown that:: ∂log|K| = diag(D)ᵀdiag(L(∂K)Lᵀ) = diag(D)ᵀ(diag(Lₕ∂C₀Lₕᵀ)⊗diag(LₓGGᵀLₓᵀ)), when the derivative is over the parameters of C₀. Similarly, ∂log|K| = diag(D)ᵀdiag(L(∂K)Lᵀ) = diag...
def LdKL_dot(self, v, v1=None): """ Implements L(∂K)Lᵀv. The array v can have one or two dimensions and the first dimension has to have size n⋅p. Let vec(V) = v. We have L(∂K)Lᵀ⋅v = ((Lₕ∂C₀Lₕᵀ) ⊗ (LₓGGᵀLₓᵀ))vec(V) = vec(LₓGGᵀLₓᵀVLₕ∂C₀Lₕᵀ), when the derivat...
def rsolve(A, y): """ Robust solve Ax=y. """ from numpy_sugar.linalg import rsolve as _rsolve try: beta = _rsolve(A, y) except LinAlgError: msg = "Could not converge to solve Ax=y." msg += " Setting x to zero." warnings.warn(msg, RuntimeWarning) beta = ze...
def multivariate_normal(random, mean, cov): """ Draw random samples from a multivariate normal distribution. Parameters ---------- random : np.random.RandomState instance Random state. mean : array_like Mean of the n-dimensional distribution. cov : array_like Covaria...
def gradient(self): """ Sum of covariance function derivatives. Returns ------- dict ∂K₀ + ∂K₁ + ⋯ """ grad = {} for i, f in enumerate(self._covariances): for varname, g in f.gradient().items(): grad[f"{self._name}[...
def value(self): """ Covariance matrix. Returns ------- K : ndarray s⋅XXᵀ. """ X = self.X return self.scale * (X @ X.T)
def B(self): """ Effect-sizes parameter, B. """ return unvec(self._vecB.value, (self.X.shape[1], self.A.shape[0]))
def bernoulli_sample( offset, G, heritability=0.5, causal_variants=None, causal_variance=0, random_state=None, ): r"""Bernoulli likelihood sampling. Sample according to .. math:: \mathbf y \sim \prod_{i=1}^n \text{Bernoulli}(\mu_i = \text{logit}(z_i)) \math...
def poisson_sample( offset, G, heritability=0.5, causal_variants=None, causal_variance=0, random_state=None, ): """Poisson likelihood sampling. Parameters ---------- random_state : random_state Set the initial random state. Example ------- .. doctest:: ...
def L(self): r"""Cholesky decomposition of :math:`\mathrm B`. .. math:: \mathrm B = \mathrm Q^{\intercal}\tilde{\mathrm{T}}\mathrm Q + \mathrm{S}^{-1} """ from numpy_sugar.linalg import ddot, sum2diag if self._L_cache is not None: return...
def fit(self, verbose=True, factr=1e5, pgtol=1e-7): r"""Maximise the marginal likelihood. Parameters ---------- verbose : bool ``True`` for progress output; ``False`` otherwise. Defaults to ``True``. factr : float, optional The iteration stops...
def covariance(self): r"""Covariance of the prior. Returns ------- :class:`numpy.ndarray` :math:`v_0 \mathrm K + v_1 \mathrm I`. """ from numpy_sugar.linalg import ddot, sum2diag Q0 = self._QS[0][0] S0 = self._QS[1] return sum2diag(do...
def fit(self, verbose=True, factr=1e5, pgtol=1e-7): r"""Maximise the marginal likelihood. Parameters ---------- verbose : bool ``True`` for progress output; ``False`` otherwise. Defaults to ``True``. factr : float, optional The iteration stops...
def posteriori_mean(self): r""" Mean of the estimated posteriori. This is also the maximum a posteriori estimation of the latent variable. """ from numpy_sugar.linalg import rsolve Sigma = self.posteriori_covariance() eta = self._ep._posterior.eta return dot(Sig...
def posteriori_covariance(self): r""" Covariance of the estimated posteriori.""" K = GLMM.covariance(self) tau = self._ep._posterior.tau return pinv(pinv(K) + diag(1 / tau))
def _bstar_1effect(beta, alpha, yTBy, yTBX, yTBM, XTBX, XTBM, MTBM): """ Same as :func:`_bstar_set` but for single-effect. """ from numpy_sugar import epsilon from numpy_sugar.linalg import dotd from numpy import sum r = full(MTBM[0].shape[0], yTBy) r -= 2 * add.reduce([dot(i, beta) for...
def _bstar_set(beta, alpha, yTBy, yTBX, yTBM, XTBX, XTBM, MTBM): """ Compute -2𝐲ᵀBEⱼ𝐛ⱼ + (𝐛ⱼEⱼ)ᵀBEⱼ𝐛ⱼ. For 𝐛ⱼ = [𝜷ⱼᵀ 𝜶ⱼᵀ]ᵀ. """ from numpy_sugar import epsilon r = yTBy r -= 2 * add.reduce([i @ beta for i in yTBX]) r -= 2 * add.reduce([i @ alpha for i in yTBM]) r += add.redu...
def null_lml(self): """ Log of the marginal likelihood for the null hypothesis. It is implemented as :: 2·log(p(Y)) = -n·log(2𝜋s) - log|D| - n, Returns ------- lml : float Log of the marginal likelihood. """ n = self._nsamples ...
def null_beta(self): """ Optimal 𝜷 according to the marginal likelihood. It is compute by solving the equation :: (XᵀBX)𝜷 = XᵀB𝐲. Returns ------- beta : ndarray Optimal 𝜷. """ ETBE = self._ETBE yTBX = self._yTBX ...
def null_beta_covariance(self): """ Covariance of the optimal 𝜷 according to the marginal likelihood. Returns ------- beta_covariance : ndarray (Xᵀ(s(K + vI))⁻¹X)⁻¹. """ A = sum(i @ j.T for (i, j) in zip(self._XTQDi, self._XTQ)) return self.n...
def null_scale(self): """ Optimal s according to the marginal likelihood. The optimal s is given by :: s = n⁻¹𝐲ᵀB(𝐲 - X𝜷), where 𝜷 is optimal. Returns ------- scale : float Optimal scale. """ n = self._nsamples ...
def fast_scan(self, M, verbose=True): """ LMLs, fixed-effect sizes, and scales for single-marker scan. Parameters ---------- M : array_like Matrix of fixed-effects across columns. verbose : bool, optional ``True`` for progress information; ``False...
def scan(self, M): """ LML, fixed-effect sizes, and scale of the candidate set. Parameters ---------- M : array_like Fixed-effects set. Returns ------- lml : float Log of the marginal likelihood. effsizes0 : ndarray ...
def null_lml(self): """ Log of the marginal likelihood for the null hypothesis. It is implemented as :: 2·log(p(Y)) = -n·p·log(2𝜋s) - log|K| - n·p, for which s and 𝚩 are optimal. Returns ------- lml : float Log of the marginal likelih...
def null_scale(self): """ Optimal s according to the marginal likelihood. The optimal s is given by s = (n·p)⁻¹𝐲ᵀK⁻¹(𝐲 - 𝐦), where 𝐦 = (A ⊗ X)vec(𝚩) and 𝚩 is optimal. Returns ------- scale : float Optimal scale. """ ...
def scan(self, A1, X1): """ LML, fixed-effect sizes, and scale of the candidate set. Parameters ---------- A1 : (p, e) array_like Trait-by-environments design matrix. X1 : (n, m) array_like Variants set matrix. Returns ------- ...
def sample(self, random_state=None): r"""Sample from the specified distribution. Parameters ---------- random_state : random_state Set the initial random state. Returns ------- numpy.ndarray Sample. """ from numpy_sugar im...
def economic_qs_zeros(n): """Eigen decomposition of a zero matrix.""" Q0 = empty((n, 0)) Q1 = eye(n) S0 = empty(0) return ((Q0, Q1), S0)
def get_fast_scanner(self): """ Return :class:`.FastScanner` for association scan. Returns ------- :class:`.FastScanner` Instance of a class designed to perform very fast association scan. """ terms = self._terms return KronFastScanner(self._Y...
def lml(self): """ Log of the marginal likelihood. Let 𝐲 = vec(Y), M = A⊗X, and H = MᵀK⁻¹M. The restricted log of the marginal likelihood is given by [R07]_:: 2⋅log(p(𝐲)) = -(n⋅p - c⋅p) log(2π) + log(|MᵀM|) - log(|K|) - log(|H|) - (𝐲-𝐦)ᵀ K⁻¹ (𝐲-𝐦), ...
def _lml_gradient(self): """ Gradient of the log of the marginal likelihood. Let 𝐲 = vec(Y), 𝕂 = K⁻¹∂(K)K⁻¹, and H = MᵀK⁻¹M. The gradient is given by:: 2⋅∂log(p(𝐲)) = -tr(K⁻¹∂K) - tr(H⁻¹∂H) + 𝐲ᵀ𝕂𝐲 - 𝐦ᵀ𝕂(2⋅𝐲-𝐦) - 2⋅(𝐦-𝐲)ᵀK⁻¹∂(𝐦). Observe that ...
def gradient(self): r"""Gradient of the log of the marginal likelihood. Returns ------- dict Map between variables to their gradient values. """ self._update_approx() g = self._ep.lml_derivatives(self._X) ed = exp(-self.logitdelta) es...
def gradient(self): """ Derivative of the covariance matrix over the lower triangular, flat part of L. It is equal to ∂K/∂Lᵢⱼ = ALᵀ + LAᵀ, where Aᵢⱼ is an n×m matrix of zeros except at [Aᵢⱼ]ᵢⱼ=1. Returns ------- Lu : ndarray Derivative ...
def beta(self): """ Fixed-effect sizes. Returns ------- effect-sizes : numpy.ndarray Optimal fixed-effect sizes. Notes ----- Setting the derivative of log(p(𝐲)) over effect sizes equal to zero leads to solutions 𝜷 from equation :: ...
def beta_covariance(self): """ Estimates the covariance-matrix of the optimal beta. Returns ------- beta-covariance : ndarray (Xᵀ(s((1-𝛿)K + 𝛿I))⁻¹X)⁻¹. References ---------- .. Rencher, A. C., & Schaalje, G. B. (2008). Linear models in sta...
def fix(self, param): """ Disable parameter optimization. Parameters ---------- param : str Possible values are ``"delta"``, ``"beta"``, and ``"scale"``. """ if param == "delta": super()._fix("logistic") else: self._fix...
def unfix(self, param): """ Enable parameter optimization. Parameters ---------- param : str Possible values are ``"delta"``, ``"beta"``, and ``"scale"``. """ if param == "delta": self._unfix("logistic") else: self._fix...
def fit(self, verbose=True): """ Maximise the marginal likelihood. Parameters ---------- verbose : bool, optional ``True`` for progress output; ``False`` otherwise. Defaults to ``True``. """ if not self._isfixed("logistic"): se...
def get_fast_scanner(self): """ Return :class:`.FastScanner` for association scan. Returns ------- fast-scanner : :class:`.FastScanner` Instance of a class designed to perform very fast association scan. """ v0 = self.v0 v1 = self.v1 Q...
def value(self): """ Internal use only. """ if not self._fix["beta"]: self._update_beta() if not self._fix["scale"]: self._update_scale() return self.lml()
def lml(self): """ Log of the marginal likelihood. Returns ------- lml : float Log of the marginal likelihood. Notes ----- The log of the marginal likelihood is given by :: 2⋅log(p(𝐲)) = -n⋅log(2π) - n⋅log(s) - log|D| - (Qᵀ𝐲)ᵀs...
def delta(self): """ Variance ratio between ``K`` and ``I``. """ v = float(self._logistic.value) if v > 0.0: v = 1 / (1 + exp(-v)) else: v = exp(v) v = v / (v + 1.0) return min(max(v, epsilon.tiny), 1 - epsilon.tiny)
def _logdetXX(self): """ log(|XᵀX|). """ if not self._restricted: return 0.0 ldet = slogdet(self._X["tX"].T @ self._X["tX"]) if ldet[0] != 1.0: raise ValueError("The determinant of XᵀX should be positive.") return ldet[1]
def _logdetH(self): """ log(|H|) for H = s⁻¹XᵀQD⁻¹QᵀX. """ if not self._restricted: return 0.0 ldet = slogdet(sum(self._XTQDiQTX) / self.scale) if ldet[0] != 1.0: raise ValueError("The determinant of H should be positive.") return ldet[1]
def _lml_optimal_scale(self): """ Log of the marginal likelihood for optimal scale. Implementation for unrestricted LML:: Returns ------- lml : float Log of the marginal likelihood. """ assert self._optimal["scale"] n = len(self._y) ...
def _lml_arbitrary_scale(self): """ Log of the marginal likelihood for arbitrary scale. Returns ------- lml : float Log of the marginal likelihood. """ s = self.scale D = self._D n = len(self._y) lml = -self._df * log2pi - n * ...
def _df(self): """ Degrees of freedom. """ if not self._restricted: return self.nsamples return self.nsamples - self._X["tX"].shape[1]
def get_fast_scanner(self): r"""Return :class:`glimix_core.lmm.FastScanner` for the current delta.""" from numpy_sugar.linalg import ddot, economic_qs, sum2diag y = self.eta / self.tau if self._QS is None: K = eye(y.shape[0]) / self.tau else: Q0 ...
def value(self): r"""Log of the marginal likelihood. Formally, .. math:: - \frac{n}{2}\log{2\pi} - \frac{1}{2} \log{\left| v_0 \mathrm K + v_1 \mathrm I + \tilde{\Sigma} \right|} - \frac{1}{2} \left(\tilde{\boldsymbol\mu} - ...
def _initialize(self): r"""Initialize the mean and covariance of the posterior. Given that :math:`\tilde{\mathrm T}` is a matrix of zeros right before the first EP iteration, we have .. math:: \boldsymbol\mu = \mathrm K^{-1} \mathbf m ~\text{ and }~ \Sigma = \m...
def L(self): r"""Cholesky decomposition of :math:`\mathrm B`. .. math:: \mathrm B = \mathrm Q^{\intercal}\tilde{\mathrm{T}}\mathrm Q + \mathrm{S}^{-1} """ from scipy.linalg import cho_factor from numpy_sugar.linalg import ddot, sum2diag if s...
def build_engine_session(connection, echo=False, autoflush=None, autocommit=None, expire_on_commit=None, scopefunc=None): """Build an engine and a session. :param str connection: An RFC-1738 database connection string :param bool echo: Turn on echoing SQL :param Optional[bool] ...
def _get_connection(cls, connection: Optional[str] = None) -> str: """Get a default connection string. Wraps :func:`bio2bel.utils.get_connection` and passing this class's :data:`module_name` to it. """ return get_connection(cls.module_name, connection=connection)
def setup_smtp_factory(**settings): """ expects a dictionary with 'mail.' keys to create an appropriate smtplib.SMTP instance""" return CustomSMTP( host=settings.get('mail.host', 'localhost'), port=int(settings.get('mail.port', 25)), user=settings.get('mail.user'), password=setti...
def sendMultiPart(smtp, gpg_context, sender, recipients, subject, text, attachments): """ a helper method that composes and sends an email with attachments requires a pre-configured smtplib.SMTP instance""" sent = 0 for to in recipients: if not to.startswith('<'): uid = '<%s>' % to ...
def begin(self): """ connects and optionally authenticates a connection.""" self.connect(self.host, self.port) if self.user: self.starttls() self.login(self.user, self.password)
def make_downloader(url: str, path: str) -> Callable[[bool], str]: # noqa: D202 """Make a function that downloads the data for you, or uses a cached version at the given path. :param url: The URL of some data :param path: The path of the cached data, or where data is cached if it does not already exist ...
def make_df_getter(data_url: str, data_path: str, **kwargs) -> Callable[[Optional[str], bool, bool], pd.DataFrame]: """Build a function that handles downloading tabular data and parsing it into a pandas DataFrame. :param data_url: The URL of the data :param data_path: The path where the data should get sto...
def generate(self, **kwargs): ''' Generate a :term:`URI` based on parameters passed. :param id: The id of the concept or collection. :param type: What we're generating a :term:`URI` for: `concept` or `collection`. :rtype: string ''' if kwargs['type'] ...
def has_address(start: int, data_length: int) -> bool: """ Determine whether the packet has an "address" encoded into it. There exists an undocumented bug/edge case in the spec - some packets with 0x82 as _start_, still encode the address into the packet, and thus throws off decoding. This edge case...
def decode_timestamp(data: str) -> datetime.datetime: """ Decode timestamp using bespoke decoder. Cannot use simple strptime since the ness panel contains a bug that P199E zone and state updates emitted on the hour cause a minute value of `60` to be sent, causing strptime to fail. This decoder handl...
def create_application(connection: Optional[str] = None) -> Flask: """Create a Flask application.""" app = Flask(__name__) flask_bootstrap.Bootstrap(app) Admin(app) connection = connection or DEFAULT_CACHE_CONNECTION engine, session = build_engine_session(connection) for name, add_admin i...
def register_provider(self, provider): ''' Register a :class:`skosprovider.providers.VocabularyProvider`. :param skosprovider.providers.VocabularyProvider provider: The provider to register. :raises RegistryException: A provider with this id or uri has already b...
def remove_provider(self, id): ''' Remove the provider with the given id or :term:`URI`. :param str id: The identifier for the provider. :returns: A :class:`skosprovider.providers.VocabularyProvider` or `False` if the id is unknown. ''' if id in self.provider...
def get_provider(self, id): ''' Get a provider by id or :term:`uri`. :param str id: The identifier for the provider. This can either be the id with which it was registered or the :term:`uri` of the conceptscheme that the provider services. :returns: A :class:`sko...
def get_providers(self, **kwargs): '''Get all providers registered. If keyword `ids` is present, get only the providers with these ids. If keys `subject` is present, get only the providers that have this subject. .. code-block:: python # Get all providers with subject 'bio...
def find(self, query, **kwargs): '''Launch a query across all or a selection of providers. .. code-block:: python # Find anything that has a label of church in any provider. registry.find({'label': 'church'}) # Find anything that has a label of church with the BUIL...
def get_all(self, **kwargs): '''Get all concepts from all providers. .. code-block:: python # get all concepts in all providers. registry.get_all() # get all concepts in all providers. # If possible, display the results with a Dutch label. r...
def get_by_uri(self, uri): '''Get a concept or collection by its uri. Returns a single concept or collection if one exists with this uri. Returns False otherwise. :param string uri: The uri to find a concept or collection for. :raises ValueError: The uri is invalid. :rt...
def find_module(self, fullname, path=None): """Find a module if its name starts with :code:`self.group` and is registered.""" if not fullname.startswith(self._group_with_dot): return end_name = fullname[len(self._group_with_dot):] for entry_point in iter_entry_points(group=se...
def load_module(self, fullname): """Load a module if its name starts with :code:`self.group` and is registered.""" if fullname in sys.modules: return sys.modules[fullname] end_name = fullname[len(self._group_with_dot):] for entry_point in iter_entry_points(group=self.group, n...
def upload_theme(): """ upload and/or update the theme with the current git state""" get_vars() with fab.settings(): local_theme_path = path.abspath( path.join(fab.env['config_base'], fab.env.instance.config['local_theme_path'])) rsync( '-av', ...
def upload_pgp_keys(): """ upload and/or update the PGP keys for editors, import them into PGP""" get_vars() upload_target = '/tmp/pgp_pubkeys.tmp' with fab.settings(fab.hide('running')): fab.run('rm -rf %s' % upload_target) fab.run('mkdir %s' % upload_target) local_key_path = pa...
def upload_backend(index='dev', user=None): """ Build the backend and upload it to the remote server at the given index """ get_vars() use_devpi(index=index) with fab.lcd('../application'): fab.local('make upload')
def update_backend(use_pypi=False, index='dev', build=True, user=None, version=None): """ Install the backend from the given devpi index at the given version on the target host and restart the service. If version is None, it defaults to the latest version Optionally, build and upload the application f...
def _sort(self, concepts, sort=None, language='any', reverse=False): ''' Returns a sorted version of a list of concepts. Will leave the original list unsorted. :param list concepts: A list of concepts and collections. :param string sort: What to sort on: `id`, `label` or `sortla...
def _include_in_find(self, c, query): ''' :param c: A :class:`skosprovider.skos.Concept` or :class:`skosprovider.skos.Collection`. :param query: A dict that can be used to express a query. :rtype: boolean ''' include = True if include and 'type' in que...
def _get_find_dict(self, c, **kwargs): ''' Return a dict that can be used in the return list of the :meth:`find` method. :param c: A :class:`skosprovider.skos.Concept` or :class:`skosprovider.skos.Collection`. :rtype: dict ''' language = self._get_lan...
async def update(self) -> None: """Force update of alarm status and zones""" _LOGGER.debug("Requesting state update from server (S00, S14)") await asyncio.gather( # List unsealed Zones self.send_command('S00'), # Arming status update self.send_comm...
async def _update_loop(self) -> None: """Schedule a state update to keep the connection alive""" await asyncio.sleep(self._update_interval) while not self._closed: await self.update() await asyncio.sleep(self._update_interval)
def add_cli_to_bel_namespace(main: click.Group) -> click.Group: # noqa: D202 """Add a ``upload_bel_namespace`` command to main :mod:`click` function.""" @main.command() @click.option('-u', '--update', is_flag=True) @click.pass_obj def upload(manager: BELNamespaceManagerMixin, update): """U...
def add_cli_clear_bel_namespace(main: click.Group) -> click.Group: # noqa: D202 """Add a ``clear_bel_namespace`` command to main :mod:`click` function.""" @main.command() @click.pass_obj def drop(manager: BELNamespaceManagerMixin): """Clear names/identifiers to terminology store.""" na...
def add_cli_write_bel_namespace(main: click.Group) -> click.Group: # noqa: D202 """Add a ``write_bel_namespace`` command to main :mod:`click` function.""" @main.command() @click.option('-d', '--directory', type=click.Path(file_okay=False, dir_okay=True), default=os.getcwd(), help='output...
def add_cli_write_bel_annotation(main: click.Group) -> click.Group: # noqa: D202 """Add a ``write_bel_annotation`` command to main :mod:`click` function.""" @main.command() @click.option('-d', '--directory', type=click.Path(file_okay=False, dir_okay=True), default=os.getcwd(), help='outp...
def _iterate_namespace_models(self, **kwargs) -> Iterable: """Return an iterator over the models to be converted to the namespace.""" return tqdm( self._get_query(self.namespace_model), total=self._count_model(self.namespace_model), **kwargs )
def _get_default_namespace(self) -> Optional[Namespace]: """Get the reference BEL namespace if it exists.""" return self._get_query(Namespace).filter(Namespace.url == self._get_namespace_url()).one_or_none()
def _make_namespace(self) -> Namespace: """Make a namespace.""" namespace = Namespace( name=self._get_namespace_name(), keyword=self._get_namespace_keyword(), url=self._get_namespace_url(), version=str(time.asctime()), ) self.session.add(na...
def _get_old_entry_identifiers(namespace: Namespace) -> Set[NamespaceEntry]: """Convert a PyBEL generalized namespace entries to a set. Default to using the identifier, but can be overridden to use the name instead. >>> {term.identifier for term in namespace.entries} """ return...
def _update_namespace(self, namespace: Namespace) -> None: """Update an already-created namespace. Note: Only call this if namespace won't be none! """ old_entry_identifiers = self._get_old_entry_identifiers(namespace) new_count = 0 skip_count = 0 for model in s...
def add_namespace_to_graph(self, graph: BELGraph) -> Namespace: """Add this manager's namespace to the graph.""" namespace = self.upload_bel_namespace() graph.namespace_url[namespace.keyword] = namespace.url # Add this manager as an annotation, too self._add_annotation_to_graph(...
def _add_annotation_to_graph(self, graph: BELGraph) -> None: """Add this manager as an annotation to the graph.""" if 'bio2bel' not in graph.annotation_list: graph.annotation_list['bio2bel'] = set() graph.annotation_list['bio2bel'].add(self.module_name)
def upload_bel_namespace(self, update: bool = False) -> Namespace: """Upload the namespace to the PyBEL database. :param update: Should the namespace be updated first? """ if not self.is_populated(): self.populate() namespace = self._get_default_namespace() ...
def drop_bel_namespace(self) -> Optional[Namespace]: """Remove the default namespace if it exists.""" namespace = self._get_default_namespace() if namespace is not None: for entry in tqdm(namespace.entries, desc=f'deleting entries in {self._get_namespace_name()}'): s...