Source code for pyhealth.utils
import json
import os
import pickle
import random
import contextlib
import numpy as np
import torch
def set_seed(seed):
random.seed(seed)
np.random.seed(seed)
torch.manual_seed(seed)
if torch.cuda.is_available():
torch.cuda.manual_seed(seed)
torch.cuda.manual_seed_all(seed)
torch.backends.cudnn.deterministic = True
torch.backends.cudnn.benchmark = False
os.environ["PYTHONHASHSEED"] = str(seed)
def load_pickle(filename):
with open(filename, "rb") as f:
return pickle.load(f)
def save_pickle(data, filename):
with open(filename, "wb") as f:
pickle.dump(data, f)
def load_json(filename):
with open(filename, "r") as f:
return json.load(f)
def save_json(data, filename):
with open(filename, "w") as f:
json.dump(data, f)
@contextlib.contextmanager
def set_env(**environ):
"""
Temporarily set the process environment variables.
>>> with set_env(PLUGINS_DIR='test/plugins'):
... "PLUGINS_DIR" in os.environ
True
>>> "PLUGINS_DIR" in os.environ
False
:type environ: dict[str, unicode]
:param environ: Environment variables to set
"""
old_environ = dict(os.environ)
os.environ.update(environ)
try:
yield
finally:
os.environ.clear()
os.environ.update(old_environ)