Skip to content

Commit

Permalink
Deleted deprecated code. Made tools have optional deps.
Browse files Browse the repository at this point in the history
  • Loading branch information
dmyersturnbull committed Sep 2, 2020
1 parent f2cc8fc commit dbefb11
Show file tree
Hide file tree
Showing 37 changed files with 953 additions and 1,371 deletions.
1 change: 1 addition & 0 deletions .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -38,6 +38,7 @@ dist/
eggs/
sdist/
docs/_build
docs/autoapi/
cython_debug/

# Hidden files that are definitely unwanted (redundant)
Expand Down
10 changes: 10 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,16 @@ Adheres to [Semantic Versioning 2.0](https://semver.org/spec/v2.0.0.html) and
[Keep a Changelog](https://keepachangelog.com/en/1.0.0/).


## [0.2.0] - 2020-09-01

### Removed:
- `db` subpackage
- `toml_data` module. Use `NestedDotDict` instead.

### Changed:
- Made `tools` require the `tools` optional package


## [0.1.0] - 2020-08-06

### Added:
Expand Down
2 changes: 1 addition & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,7 @@
Adorable little Python functions for you to copy or import.

`pip install pocketutils`. To get the optional packages, use:
`pip install pocketutils[biochem,db,misc,notebooks,plotting]`
`pip install pocketutils[tools,biochem,misc,notebooks,plotting]`

Among the more useful are `zip_strict`, `frozenlist`, `SmartEnum`, `is_lambda`, `strip_paired_brackets`,
`sanitize_path_node`, `TomlData`, `PrettyRecordFactory`, `parallel_with_cursor`, `groupby_parallel`,
Expand Down
29 changes: 10 additions & 19 deletions pocketutils/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,21 +3,20 @@
"""

import logging
from pathlib import Path, PurePath
from typing import Union

# importlib.metadata is compat with Python 3.8 only
from importlib_metadata import PackageNotFoundError
from importlib_metadata import metadata as __load
# If you need Python < 3.8, change to importlib_metadata and add it as a dependency
from importlib.metadata import PackageNotFoundError
from importlib.metadata import metadata as __load
from pathlib import Path

logger = logging.getLogger(Path(__file__).parent.name)

metadata = None
try:
metadata = __load(Path(__file__).absolute().parent.name)
__status__ = "Development"
__copyright__ = "Copyright 2016–2020"
__date__ = "2020-08-24"
__copyright__ = "Copyright 2020"
__date__ = "2020-09-01"
__uri__ = metadata["home-page"]
__title__ = metadata["name"]
__summary__ = metadata["summary"]
Expand All @@ -26,21 +25,13 @@
__author__ = metadata["author"]
__maintainer__ = metadata["maintainer"]
__contact__ = metadata["maintainer"]
except PackageNotFoundError:
except PackageNotFoundError: # pragma: no cover
logger.error(
"Could not load package metadata for {}. Is it installed?".format(
Path(__file__).absolute().parent.name
)
f"Could not load package metadata for {Path(__file__).absolute().parent.name}. Is it installed?"
)


def resource(*nodes: Union[PurePath, str]) -> Path:
"""Gets a path of a resource file under resources/ directory."""
return Path(Path(__file__).parent, "resources", *nodes)


if __name__ == "__main__":
if __name__ == "__main__": # pragma: no cover
if metadata is not None:
print("{} (v{})".format(metadata["name"], metadata["version"]))
print(f"{metadata['name']} (v{metadata['version']})")
else:
print("Unknown project info")
2 changes: 1 addition & 1 deletion pocketutils/biochem/tissue_expression.py
Original file line number Diff line number Diff line change
Expand Up @@ -28,7 +28,7 @@ def load(
filter_fn: Callable[[pd.DataFrame], pd.DataFrame] = pd.DataFrame.dropna,
) -> TissueTable:
"""
Get a DataFrame of Human Protein Atlas tissue expression data,
Gets a DataFrame of Human Protein Atlas tissue expression data,
indexed by Gene name and with the 'Gene' and 'Reliability' columns dropped.
The expression level ('Level') is replaced using this map: {'Not detected': 0, 'Low': 1, 'Medium': 2, 'High': 3}.
Downloads the file from http://www.proteinatlas.org/download/normal_tissue.tsv.zip
Expand Down
21 changes: 14 additions & 7 deletions pocketutils/biochem/uniprot_go.py
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,7 @@ class FlatGoTerm:
"""
A Gene Ontology term.
Not to be confused with GOTerm in goatools: obo_parser.GOTerm
Attributes:
ID (str); ex: GO:0005737
kind (str: 'P'==process, 'C'==component, 'F'==function)
Expand Down Expand Up @@ -66,7 +67,9 @@ class UniprotGoTerms:
def fetch_uniprot_data(self, uniprot_ids: Union[str, List[str]]) -> List[Mapping[str, str]]:
"""
Fetches a list of dicts of UniProt metadata, one per UniProt ID.
Raises a ValueError if a UniProt ID wasn't found.
Raises:
ValueError: If a UniProt ID wasn't found.
"""
if isinstance(uniprot_ids, str): # not a list type
uniprot_ids = [uniprot_ids]
Expand Down Expand Up @@ -95,7 +98,9 @@ def go_terms_for_uniprot_id_as_df(self, uniprot_id: str) -> pd.DataFrame:

class GoTermsAtLevel:
"""
Example: go_term_ancestors_for_uniprot_id_as_df('P42681', 2)
Gene ontology terms organized by level.
Example:
>>> go_term_ancestors_for_uniprot_id_as_df('P42681', 2)
"""

def __init__(self) -> None:
Expand Down Expand Up @@ -127,8 +132,9 @@ def get_ancestors_of_go_term(self, term_id: str, level: int) -> Iterable[GOTerm]
From a GO term in the form 'GO:0007344', returns a set of ancestor GOTerm objects at the specified level.
The traversal is restricted to is-a relationships.
Note that the level is the minimum number of steps to the root.
Arguments:
level: starting at 0 (root)
Args:
level: starting at 0 (root)
"""

def traverse_up(term, buildup_set, level):
Expand All @@ -149,9 +155,10 @@ def go_term_ancestors_for_uniprot_id(
Gets the GO terms associated with a UniProt ID and returns a set of their ancestors at the specified level.
The traversal is restricted to is-a relationships.
Note that the level is the minimum number of steps to the root.
Arguments:
level: starting at 0 (root)
kinds_allowed: a set containing any combination of 'P', 'F', or 'C'
Args:
level: starting at 0 (root)
kinds_allowed: a set containing any combination of 'P', 'F', or 'C'
"""
if kinds_allowed is None:
kinds_allowed = ["P", "F", "C"]
Expand Down
23 changes: 13 additions & 10 deletions pocketutils/core/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -112,15 +112,18 @@ def _new_type(
) -> Type[LazyWrapped]:
"""
Creates a new mutable wrapped type.
For ex:
```
LazyRemoteTime = LazyWrap.new_type('RemoteTime', lambda: urllib...)
dt = LazyRemoteTime() # nothing happens
print(dt.get()) # has a value
```
:param dtype: The name of the data type, such as 'datetime' if generator=datetime.now
:param generator: This is called to (lazily) initialize an instance of the LazyWrapped
:return: A new class subclassing LazyWrapped
Example:
>>> LazyRemoteTime = LazyWrap.new_type('RemoteTime', lambda: ...)
>>> dt = LazyRemoteTime() # nothing happens
>>> dt.get() # has a value
Args:
dtype: The name of the data type, such as 'datetime' if generator=datetime.now
generator: This is called to (lazily) initialize an instance of the LazyWrapped
Returns:
A new class subclassing LazyWrapped
"""

class X(superclass):
Expand All @@ -144,7 +147,7 @@ class SmartEnum(enum.Enum):
def of(cls, v):
"""
Returns the member of this enum class from a string with the member's name,
case-insentive and stripping whitespace.
case-insensitive and stripping whitespace.
Will return ``v`` if ``v`` is already an instance of this class.
"""
if isinstance(v, cls):
Expand Down
2 changes: 1 addition & 1 deletion pocketutils/core/dot_dict.py
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,7 @@ class NestedDotDict:
A thin wrapper around a nested dict to make getting values easier.
Keys must not contain dots (.), which are reserved for splitting of values.
This class is especially useful for TOML but also works well for JSON and Python dicts.
Also see ``toml_data``. This has some advantages.
Also see ``toml_data``. ``NestedDotDict`` has some advantages over it.
"""

@classmethod
Expand Down
6 changes: 4 additions & 2 deletions pocketutils/core/exceptions.py
Original file line number Diff line number Diff line change
Expand Up @@ -29,8 +29,10 @@ def args(**names):
"""
Decorator.
Add a __init__ that calls the superclass and takes any argument in names.
The __init__ will set: (self.name =value if name is passed else None) for all name in names.
:param names: A map from str to Type
The __init__ will set: (self.name=value if name is passed else None) for all name in names.
Args:
names: A map from str to Type
"""
assert not any([s == "info" or s.startswith("__") and s.endswith("__") for s in names])

Expand Down
8 changes: 5 additions & 3 deletions pocketutils/core/internal.py
Original file line number Diff line number Diff line change
Expand Up @@ -70,9 +70,11 @@ def expanded(cls, item, depth=1):
def nicesize(nbytes: int, space: str = "") -> str:
"""
Uses IEC 1998 units, such as KiB (1024).
:param nbytes: Number of bytes
:param space: Separator between digits and units
:return: Formatted string
nbytes: Number of bytes
space: Separator between digits and units
Returns:
Formatted string
"""
data = {
"PiB": 1024 ** 5,
Expand Down
8 changes: 5 additions & 3 deletions pocketutils/core/iterators.py
Original file line number Diff line number Diff line change
Expand Up @@ -68,9 +68,11 @@ def __next__(self) -> T:
class TieredIterator(SeqIterator):
"""
A SizedIterator that iterates over every tuples of combination from multiple sequences.
Ex:
it = TieredIterator([[1, 2, 3], [5, 6]])
list(it) # [(1,5), (1,6), (2,5), (2,6), (3,5), (3,6)]
Example:
>>> it = TieredIterator([[1, 2, 3], [5, 6]])
>>> list(it)
[(1,5), (1,6), (2,5), (2,6), (3,5), (3,6)]
"""

# noinspection PyMissingConstructor
Expand Down
105 changes: 0 additions & 105 deletions pocketutils/core/toml_data.py

This file was deleted.

Empty file removed pocketutils/db/__init__.py
Empty file.

0 comments on commit dbefb11

Please sign in to comment.