Skip to content

Commit

Permalink
🎨 Proper deprecation warning (#138)
Browse files Browse the repository at this point in the history
Signed-off-by: zethson <lukas.heumos@posteo.net>
  • Loading branch information
Zethson authored Oct 28, 2024
1 parent 8cf7f06 commit 592e30a
Show file tree
Hide file tree
Showing 4 changed files with 54 additions and 44 deletions.
10 changes: 5 additions & 5 deletions bionty/_bionty.py
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@
from lamin_utils import logger
from lnschema_core.models import Record

import bionty.base as bionty_base
import bionty.base as bt_base

from . import ids

Expand Down Expand Up @@ -41,7 +41,7 @@ def create_or_get_organism_record(
organism_record = Organism.from_source(name=organism)
# link the organism record to the default bionty source
organism_record.source = get_source_record(
bionty_base.Organism(), Organism
bt_base.Organism(), Organism
) # type:ignore
organism_record.save() # type:ignore
except KeyError:
Expand All @@ -62,7 +62,7 @@ def create_or_get_organism_record(


def get_source_record(
public_ontology: bionty_base.PublicOntology, registry: type[Record]
public_ontology: bt_base.PublicOntology, registry: type[Record]
) -> Record:
from .models import Source

Expand Down Expand Up @@ -164,15 +164,15 @@ def lookup2kwargs(record: Record, *args, **kwargs) -> dict:
bionty_kwargs = arg[0]._asdict()

if len(bionty_kwargs) > 0:
import bionty.base as bionty_base
import bionty.base as bt_base

# add organism and source
organism_record = create_or_get_organism_record(
registry=record.__class__, organism=kwargs.get("organism")
)
if organism_record is not None:
bionty_kwargs["organism"] = organism_record
public_ontology = getattr(bionty_base, record.__class__.__name__)(
public_ontology = getattr(bt_base, record.__class__.__name__)(
organism=organism_record.name if organism_record is not None else None
)
bionty_kwargs["source"] = get_source_record(public_ontology, record.__class__)
Expand Down
42 changes: 23 additions & 19 deletions bionty/core/_add_ontology.py
Original file line number Diff line number Diff line change
@@ -1,13 +1,17 @@
from typing import Iterable, List, Optional, Set, Tuple, Type, Union
from __future__ import annotations

from typing import TYPE_CHECKING, Iterable, List, Optional, Set, Tuple, Type, Union

import pandas as pd
from lamin_utils import logger
from lnschema_core.models import Record

from bionty.models import BioRecord, Source
if TYPE_CHECKING:
import pandas as pd
from lnschema_core.models import Record

from bionty.models import BioRecord, Source


def get_all_ancestors(df: pd.DataFrame, ontology_ids: Iterable[str]) -> Set[str]:
def get_all_ancestors(df: pd.DataFrame, ontology_ids: Iterable[str]) -> set[str]:
ancestors = set()
stack = list(ontology_ids)
while stack:
Expand All @@ -31,8 +35,8 @@ def prepare_dataframe(df: pd.DataFrame) -> pd.DataFrame:


def get_new_ontology_ids(
registry: Type[BioRecord], ontology_ids: Iterable[str], df: pd.DataFrame
) -> Tuple[Set[str], Set[str]]:
registry: type[BioRecord], ontology_ids: Iterable[str], df: pd.DataFrame
) -> tuple[set[str], set[str]]:
all_ontology_ids = set(ontology_ids) | get_all_ancestors(df, ontology_ids)
existing_ontology_ids = set(
registry.filter(ontology_id__in=all_ontology_ids).values_list(
Expand All @@ -43,8 +47,8 @@ def get_new_ontology_ids(


def create_records(
registry: Type[BioRecord], df: pd.DataFrame, source_record: Source
) -> List[Record]:
registry: type[BioRecord], df: pd.DataFrame, source_record: Source
) -> list[Record]:
import lamindb as ln

df_records = (
Expand All @@ -65,8 +69,8 @@ def create_records(


def create_link_records(
registry: Type[BioRecord], df: pd.DataFrame, records: List[Record]
) -> List[Record]:
registry: type[BioRecord], df: pd.DataFrame, records: list[Record]
) -> list[Record]:
"""Create link records.
Args:
Expand Down Expand Up @@ -103,7 +107,7 @@ def create_link_records(


def check_source_in_db(
registry: Type[BioRecord],
registry: type[BioRecord],
source: Source,
n_all: int = None,
n_in_db: int = None,
Expand All @@ -124,10 +128,10 @@ def check_source_in_db(


def add_ontology_from_df(
registry: Type[BioRecord],
ontology_ids: Optional[List[str]] = None,
organism: Union[str, Record, None] = None,
source: Optional[Source] = None,
registry: type[BioRecord],
ontology_ids: list[str] | None = None,
organism: str | Record | None = None,
source: Source | None = None,
ignore_conflicts: bool = True,
):
import lamindb as ln
Expand Down Expand Up @@ -192,9 +196,9 @@ def add_ontology_from_df(


def add_ontology(
records: List[BioRecord],
organism: Union[str, Record, None] = None,
source: Optional[Source] = None,
records: list[BioRecord],
organism: str | Record | None = None,
source: Source | None = None,
ignore_conflicts: bool = True,
):
registry = records[0]._meta.model
Expand Down
6 changes: 3 additions & 3 deletions bionty/core/_bionty.py
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@
from lamindb_setup.core._setup_bionty_sources import RENAME
from lnschema_core.models import Artifact, Record

import bionty.base as bionty_base
import bionty.base as bt_base


def sync_all_sources_to_latest():
Expand All @@ -25,7 +25,7 @@ def sync_all_sources_to_latest():
try:
ln.settings.creation.search_names = False
records = Source.filter().all()
df_sources = bionty_base.display_available_sources().reset_index()
df_sources = bt_base.display_available_sources().reset_index()
bionty_models = list_biorecord_models(bionty)
for _, row in df_sources.iterrows():
kwargs = row.to_dict()
Expand Down Expand Up @@ -79,7 +79,7 @@ def set_latest_sources_as_currently_used():


def filter_bionty_df_columns(
model: Type[Record], public_ontology: bionty_base.PublicOntology
model: Type[Record], public_ontology: bt_base.PublicOntology
) -> pd.DataFrame:
"""Filter columns of public ontology to match the model fields."""
bionty_df = pd.DataFrame()
Expand Down
40 changes: 23 additions & 17 deletions bionty/models.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
from __future__ import annotations

from typing import TYPE_CHECKING, List, Tuple, overload
import warnings
from typing import TYPE_CHECKING, Tuple, overload

import numpy as np
from django.db import models
Expand All @@ -18,7 +19,7 @@
TracksUpdates,
)

import bionty.base as bionty_base
import bionty.base as bt_base

from . import ids
from ._bionty import encode_uid, lookup2kwargs
Expand Down Expand Up @@ -131,7 +132,7 @@ def set_as_currently_used(self):
Source.filter(
entity=self.entity, organism=self.organism, name=self.name
).exclude(uid=self.uid).update(currently_used=False)
logger.success(f"set {self} as currently used")
logger.success(f"set {self} as currently used.")
logger.warning("please reload your instance to reflect the updates!")


Expand Down Expand Up @@ -164,12 +165,12 @@ def __init__(self, *args, **kwargs):
if (
args
and len(args) == 1
and isinstance(args[0], (Tuple, List))
and isinstance(args[0], (Tuple, list))
and len(args[0]) > 0
):
if isinstance(args[0], List) and len(args[0]) > 1:
if isinstance(args[0], list) and len(args[0]) > 1:
logger.warning(
"multiple lookup/search results are passed, only returning record from the first entry"
"multiple lookup/search results were passed. Only returning record from the first entry."
)
result = lookup2kwargs(self, *args, **kwargs) # type:ignore
# exclude "parents" from query arguments
Expand All @@ -195,7 +196,7 @@ def __init__(self, *args, **kwargs):
raise RuntimeError("please pass a organism!")
elif kwargs.get("organism") is not None:
if not isinstance(kwargs.get("organism"), Organism):
raise TypeError("organism must be a `bionty.Organism` record")
raise TypeError("organism must be a `bionty.Organism` record.")

kwargs = encode_uid(registry=self.__class__, kwargs=kwargs)

Expand All @@ -208,7 +209,7 @@ def __init__(self, *args, **kwargs):
if isinstance(parents, (list, np.ndarray)) and len(parents) > 0:
if not isinstance(parents[0], str):
raise ValueError(
"not a valid parents kwarg, got to be list of ontology ids"
"Invalid parents kwarg passed. Provide a list of ontology ids."
)
self._parents = parents

Expand All @@ -222,15 +223,15 @@ def import_from_source(
organism: str | Record | None = None,
ignore_conflicts: bool = True,
):
"""Bulk save records from a dataframe.
"""Bulk save records from a Pandas DataFrame.
Use this method to initialize your registry with public ontology.
Args:
ontology_ids: List of ontology ids to save
organism: Organism record or name
source: Source record
ignore_conflicts: Ignore conflicts during bulk create
ontology_ids: List of ontology ids to save.
organism: Organism name or record.
source: Source record to import records from.
ignore_conflicts: Whether to ignore conflicts during bulk record creation.
Examples:
>>> bionty.CellType.import_from_source()
Expand Down Expand Up @@ -321,7 +322,10 @@ def add_source(cls, source: Source, currently_used=True) -> Source:
)
if bionty_source is None:
logger.warning(
"please register a DataFrame artifact! \n→ artifact = ln.Artifact(df, visibility=0, run=False).save() \n→ source.dataframe_artifact = artifact \n→ source.save()"
"please register a DataFrame artifact! \n"
"→ artifact = ln.Artifact(df, visibility=0, run=False).save() \n"
"→ source.dataframe_artifact = artifact \n"
"→ source.save()"
)
else:
df_artifact = ln.Artifact(
Expand Down Expand Up @@ -372,7 +376,7 @@ def public(
version = None

try:
return getattr(bionty_base, cls.__name__)(
return getattr(bt_base, cls.__name__)(
organism=organism, source=source_name, version=version
)
except InvalidParamError as e:
Expand All @@ -394,8 +398,10 @@ def public(
@classmethod
def _from_public(cls, *args, **kwargs) -> BioRecord | list[BioRecord] | None:
"""Deprecated in favor of `from_source`."""
logger.warning(
"`.from_public()` is deprecated and will be removed in a future version. Use `.from_source()` instead!"
warnings.warn(
"`.from_public()` is deprecated and will be removed in a future version. Use `.from_source()` instead!",
DeprecationWarning,
stacklevel=2,
)
return cls.from_source(*args, **kwargs)

Expand Down

0 comments on commit 592e30a

Please sign in to comment.