Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
23 changes: 18 additions & 5 deletions pyhealth/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,11 +5,24 @@

__version__ = "2.1.0"

# package-level cache path
BASE_CACHE_PATH = os.path.join(str(Path.home()), ".cache/pyhealth/")
# BASE_CACHE_PATH = "/srv/local/data/pyhealth-cache"
if not os.path.exists(BASE_CACHE_PATH):
os.makedirs(BASE_CACHE_PATH)
# package-level cache path (created lazily on first write)
BASE_CACHE_PATH = os.environ.get("PYHEALTH_CACHE_DIR") or os.path.join(
str(Path.home()), ".cache/pyhealth/"
)


def ensure_cache_dir(path: str = BASE_CACHE_PATH) -> str:
"""Create and return a cache directory lazily and race-safely.

Examples:
>>> import tempfile
>>> from pyhealth import ensure_cache_dir
>>> with tempfile.TemporaryDirectory() as tmp:
... ensure_cache_dir(tmp) == tmp
True
"""
os.makedirs(path, exist_ok=True)
return path

# logging
logger = logging.getLogger(__name__)
Expand Down
3 changes: 2 additions & 1 deletion pyhealth/datasets/base_dataset.py
Original file line number Diff line number Diff line change
Expand Up @@ -386,7 +386,8 @@ def _task_transform_fn(
"`if __name__ == '__main__':` block, so define the task class at "
"module level in an importable file, or use num_workers=1."
) from e
total_patients = len(list(patient_ids))
patient_ids = list(patient_ids)
total_patients = len(patient_ids)
logger.info(
f"Worker {worker_id} started processing {total_patients} patients. (Polars threads: {pl.thread_pool_size()})"
)
Expand Down
2 changes: 0 additions & 2 deletions pyhealth/datasets/utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -13,10 +13,8 @@
from torch.utils.data import DataLoader

from pyhealth import BASE_CACHE_PATH
from pyhealth.utils import create_directory

MODULE_CACHE_PATH = os.path.join(BASE_CACHE_PATH, "datasets")
create_directory(MODULE_CACHE_PATH)
#PyG import for graph-based models
try:
from torch_geometric.data import Data as PyGData, Batch as PyGBatch
Expand Down
10 changes: 1 addition & 9 deletions pyhealth/medcode/utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,11 +5,10 @@
import pandas as pd

from pyhealth import BASE_CACHE_PATH
from pyhealth.utils import create_directory, download_file, load_pickle, load_json
from pyhealth.utils import download_file, load_json, load_pickle

BASE_URL = "https://storage.googleapis.com/pyhealth/resource/"
MODULE_CACHE_PATH = os.path.join(BASE_CACHE_PATH, "medcode")
create_directory(MODULE_CACHE_PATH)

logger = logging.getLogger(__name__)

Expand Down Expand Up @@ -44,13 +43,6 @@ def download_and_read_csv(filename: str, refresh_cache: bool = False) -> pd.Data

embedding_types = ['KG/transe', 'LM/clinicalbert', 'LM/gpt3', 'LM/biogpt', 'LM/sapbert']
features = ['conditions', 'procedures', 'drugs']
for embedding_type in embedding_types:
for feature in features:
MODULE_CACHE_PATH_TMP = os.path.join(BASE_CACHE_PATH, "medcode", "embeddings", embedding_type, feature)
create_directory(MODULE_CACHE_PATH_TMP)

MODULE_CACHE_PATH_TMP = os.path.join(BASE_CACHE_PATH, "medcode", "embeddings", embedding_type, "special_tokens")
create_directory(MODULE_CACHE_PATH_TMP)


def download_and_read_pkl(filename: str, refresh_cache: bool = False):
Expand Down
2 changes: 1 addition & 1 deletion pyhealth/models/generators/corgan.py
Original file line number Diff line number Diff line change
Expand Up @@ -684,7 +684,7 @@ def save_model(self, path: str) -> None:

def load_model(self, path: str) -> None:
"""Load weights and vocabulary from a checkpoint."""
ckpt = torch.load(path, map_location=self.device)
ckpt = torch.load(path, map_location=self.device, weights_only=True)
self.autoencoder.load_state_dict(ckpt["autoencoder"])
self.generator.load_state_dict(ckpt["generator"])
self.critic.load_state_dict(ckpt["critic"])
Expand Down
4 changes: 3 additions & 1 deletion pyhealth/models/generators/gpt2.py
Original file line number Diff line number Diff line change
Expand Up @@ -232,7 +232,9 @@ def train_model(self, train_dataset, val_dataset=None, device=None) -> None:

checkpoint_path = os.path.join(self.save_dir, "gpt2_model")
if os.path.exists(checkpoint_path):
checkpoint = torch.load(checkpoint_path, map_location=self.device)
checkpoint = torch.load(
checkpoint_path, map_location=self.device, weights_only=True
)
self.gpt2.load_state_dict(checkpoint["model"])
optimizer.load_state_dict(checkpoint["optimizer"])

Expand Down
4 changes: 3 additions & 1 deletion pyhealth/models/generators/halo.py
Original file line number Diff line number Diff line change
Expand Up @@ -603,7 +603,9 @@ def train_model(self, train_dataset, val_dataset=None, device=None) -> None:

checkpoint_path = os.path.join(self.save_dir, "halo_model")
if os.path.exists(checkpoint_path):
checkpoint = torch.load(checkpoint_path, map_location=self.device)
checkpoint = torch.load(
checkpoint_path, map_location=self.device, weights_only=True
)
self.halo_model.load_state_dict(checkpoint["model"])
optimizer.load_state_dict(checkpoint["optimizer"])

Expand Down
2 changes: 1 addition & 1 deletion pyhealth/models/generators/medgan.py
Original file line number Diff line number Diff line change
Expand Up @@ -510,7 +510,7 @@ def save_model(self, path: str) -> None:

def load_model(self, path: str) -> None:
"""Load weights and the code vocabulary from a checkpoint."""
ckpt = torch.load(path, map_location=self.device)
ckpt = torch.load(path, map_location=self.device, weights_only=True)
self.autoencoder.load_state_dict(ckpt["autoencoder"])
self.generator.load_state_dict(ckpt["generator"])
self.discriminator.load_state_dict(ckpt["discriminator"])
Expand Down
4 changes: 3 additions & 1 deletion pyhealth/models/generators/promptehr.py
Original file line number Diff line number Diff line change
Expand Up @@ -372,7 +372,9 @@ def train_model(self, train_dataset, val_dataset=None, device=None) -> None:

checkpoint_path = os.path.join(self.save_dir, "promptehr_model")
if os.path.exists(checkpoint_path):
checkpoint = torch.load(checkpoint_path, map_location=self.device)
checkpoint = torch.load(
checkpoint_path, map_location=self.device, weights_only=True
)
self.load_state_dict(checkpoint["model"])
optimizer.load_state_dict(checkpoint["optimizer"])

Expand Down
74 changes: 53 additions & 21 deletions pyhealth/models/molerec.py
Original file line number Diff line number Diff line change
Expand Up @@ -21,8 +21,14 @@
from pyhealth.models.utils import save_ddi_adj


smiles2graph = None
AtomEncoder = None
BondEncoder = None


def _import_ogb(min_version: str = "1.3.5") -> None:
"""Import ogb components and validate version."""
global smiles2graph, AtomEncoder, BondEncoder
try:
installed = importlib_metadata.version("ogb")
except importlib_metadata.PackageNotFoundError as exc:
Expand All @@ -33,19 +39,24 @@ def _import_ogb(min_version: str = "1.3.5") -> None:
f"ogb>={min_version} required, but found {installed}."
)

from ogb.utils import smiles2graph
from ogb.graphproppred.mol_encoder import AtomEncoder, BondEncoder
from ogb.graphproppred.mol_encoder import AtomEncoder as _AtomEncoder
from ogb.graphproppred.mol_encoder import BondEncoder as _BondEncoder
from ogb.utils import smiles2graph as _smiles2graph

globals().update(
{
"smiles2graph": smiles2graph,
"AtomEncoder": AtomEncoder,
"BondEncoder": BondEncoder,
}
)
smiles2graph = _smiles2graph
AtomEncoder = _AtomEncoder
BondEncoder = _BondEncoder


def graph_batch_from_smiles(smiles_list, device=torch.device("cpu")):
"""Build a batched molecular graph dictionary from SMILES strings.

Examples:
>>> from pyhealth.models.molerec import graph_batch_from_smiles
>>> batch = graph_batch_from_smiles([])
>>> batch["num_edges"]
0
"""
edge_idxes, edge_feats, node_feats, lstnode, batch = [], [], [], 0, []

if not smiles_list:
Expand All @@ -59,18 +70,21 @@ def graph_batch_from_smiles(smiles_list, device=torch.device("cpu")):
}
return result

try:
graphs = [smiles2graph(x) for x in smiles_list]
except NameError:
result = {
"edge_index": torch.zeros((2, 0), dtype=torch.long, device=device),
"edge_attr": torch.zeros((0, 3), dtype=torch.long, device=device),
"batch": torch.zeros((1,), dtype=torch.long, device=device),
"x": torch.zeros((1, 9), dtype=torch.long, device=device),
"num_nodes": 1,
"num_edges": 0,
}
return result
if smiles2graph is None:
try:
_import_ogb()
except ImportError:
result = {
"edge_index": torch.zeros((2, 0), dtype=torch.long, device=device),
"edge_attr": torch.zeros((0, 3), dtype=torch.long, device=device),
"batch": torch.zeros((1,), dtype=torch.long, device=device),
"x": torch.zeros((1, 9), dtype=torch.long, device=device),
"num_nodes": 1,
"num_edges": 0,
}
return result

graphs = [smiles2graph(x) for x in smiles_list]

for idx, graph in enumerate(graphs):
edge_idxes.append(graph["edge_index"] + lstnode)
Expand Down Expand Up @@ -118,6 +132,13 @@ def __setitem__(self, key: str, value: Any):


class GINConv(torch.nn.Module):
"""Graph Isomorphism Network convolution layer with bond embeddings.

Examples:
>>> from pyhealth.models.molerec import GINConv
>>> conv = GINConv(embedding_dim=16) # doctest: +SKIP
"""

def __init__(self, embedding_dim: int = 64):
super(GINConv, self).__init__()
self.mlp = torch.nn.Sequential(
Expand All @@ -127,6 +148,8 @@ def __init__(self, embedding_dim: int = 64):
torch.nn.Linear(2 * embedding_dim, embedding_dim),
)
self.eps = torch.nn.Parameter(torch.Tensor([0]))
if BondEncoder is None:
_import_ogb()
self.bond_encoder = BondEncoder(emb_dim=embedding_dim)

def forward(
Expand All @@ -150,13 +173,22 @@ def forward(


class GINGraph(torch.nn.Module):
"""Multi-layer GIN encoder for molecular graphs.

Examples:
>>> from pyhealth.models.molerec import GINGraph
>>> encoder = GINGraph(num_layers=2, embedding_dim=16) # doctest: +SKIP
"""

def __init__(
self, num_layers: int = 4, embedding_dim: int = 64, dropout: float = 0.7
):
super(GINGraph, self).__init__()
if num_layers < 2:
raise ValueError("Number of GNN layers must be greater than 1.")

if AtomEncoder is None:
_import_ogb()
self.atom_encoder = AtomEncoder(emb_dim=embedding_dim)
self.convs = torch.nn.ModuleList()
self.batch_norms = torch.nn.ModuleList()
Expand Down
46 changes: 15 additions & 31 deletions pyhealth/nlp/metrics.py
Original file line number Diff line number Diff line change
Expand Up @@ -429,6 +429,10 @@ class Scorer(object):
"""A class that scores sentences using a set of registered methods
(:obj:`methods`).

Examples:
>>> from pyhealth.nlp.metrics import ScoreContext, Scorer
>>> scorer = Scorer() # doctest: +SKIP
>>> scorer.score(ScoreContext([("a b", "a b")])) # doctest: +SKIP
"""
methods: Dict[str, ScoreMethod] = field(
default_factory=lambda: {
Expand All @@ -454,43 +458,23 @@ class Scorer(object):
:obj:`.ScoreContext.meth` in the call to :meth:`score`.

"""
def _install(self, req: str):
pybin: str = sys.executable
cmd: str = f"{pybin} -m pip install '{req}'"
res: int = os.system(cmd)
if res != 0:
raise ScorerError(f"Pip eror installing '{req}'")

def _install_all(self, reqs: Tuple[str, ...]) -> bool:
req: str
for req in reqs:
try:
output: str = self._install(req)
if logger.isEnabledFor(logging.INFO):
logger.info(f'installed: {req}')
if logger.isEnabledFor(logging.DEBUG):
logger.debug(f'install output: <<{output}>>')
except Exception as e:
logger.warning(
f"could not install scoring requirement '{req}': {e}")
return False
return True

def _get_missing_modules(self) -> Tuple[str, ...]:
missing: List[str] = []
not_avail: List[str] = []
def _get_missing_modules(self) -> tuple[str, ...]:
all_missing: list[str] = []
not_avail: list[str] = []
name: str
meth: ScoreMethod
for name, meth in self.methods.items():
missing: Tuple[str, ...] = meth.missing_modules()
if len(missing) > 0 and not self._install_all(missing):
logger.warning(f'method {meth} is not available: ' +
f'missing {missing}')
meth_missing: tuple[str, ...] = meth.missing_modules()
if len(meth_missing) > 0:
logger.warning(
f"method {meth} is not available: missing {meth_missing}. "
"Install optional NLP dependencies with `pip install pyhealth[nlp]`."
)
not_avail.append(name)
missing.extend(missing)
all_missing.extend(meth_missing)
for name in not_avail:
del self.methods[name]
return tuple(missing)
return tuple(all_missing)

def score(self, context: ScoreContext) -> ScoreSet:
"""Score the sentences in ``context``.
Expand Down
31 changes: 21 additions & 10 deletions pyhealth/sampler/sage_sampler.py
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,27 @@ def to(self, *args, **kwargs):
edge_index = self.edge_index.to(*args, **kwargs)
e_id = self.e_id.to(*args, **kwargs) if self.e_id is not None else None
return EdgeIndex(edge_index, e_id, self.size)


class Adj(NamedTuple):
"""Sampled sparse adjacency tuple returned by :class:`NeighborSampler`.

Examples:
>>> import torch
>>> from pyhealth.sampler.sage_sampler import Adj
>>> adj = Adj(torch.tensor([1]), None, (1, 1))
>>> adj.to("cpu").size
(1, 1)
"""

adj_t: object
e_id: Tensor | None
size: tuple[int, int]

def to(self, *args, **kwargs):
adj_t = self.adj_t.to(*args, **kwargs)
e_id = self.e_id.to(*args, **kwargs) if self.e_id is not None else None
return Adj(adj_t, e_id, self.size)


class NeighborSampler(torch.utils.data.DataLoader):
Expand Down Expand Up @@ -124,16 +145,6 @@ def __init__(self, dataset, edge_index, # is a Union[Tensor, SparseTensor],
self.transform = transform
self.is_sparse_tensor = isinstance(edge_index, SparseTensor)
self.__val__ = None

class Adj(NamedTuple):
adj_t: SparseTensor
e_id: Optional[Tensor]
size: Tuple[int, int]

def to(self, *args, **kwargs):
adj_t = self.adj_t.to(*args, **kwargs)
e_id = self.e_id.to(*args, **kwargs) if self.e_id is not None else None
return Adj(adj_t, e_id, self.size)

# Obtain a *transposed* `SparseTensor` instance.
if not self.is_sparse_tensor:
Expand Down
Loading
Loading