Skip to content

Commit

Permalink
extract message out of all touched errors
Browse files Browse the repository at this point in the history
  • Loading branch information
flying-sheep committed Jan 13, 2025
1 parent d7111f9 commit 903f0b0
Show file tree
Hide file tree
Showing 8 changed files with 27 additions and 28 deletions.
11 changes: 6 additions & 5 deletions src/scanpy/_utils/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -195,7 +195,8 @@ def _import_name(name: str) -> Any:
try:
obj = getattr(obj, name)
except AttributeError:
raise RuntimeError(f"{parts[:i]}, {parts[i + 1 :]}, {obj} {name}")
msg = f"{parts[:i]}, {parts[i + 1 :]}, {obj} {name}"
raise RuntimeError(msg)
return obj


Expand Down Expand Up @@ -1130,18 +1131,18 @@ def __contains__(self, key: str) -> bool:
def _choose_graph(adata, obsp, neighbors_key):
"""Choose connectivities from neighbbors or another obsp column"""
if obsp is not None and neighbors_key is not None:
raise ValueError(
"You can't specify both obsp, neighbors_key. Please select only one."
)
msg = "You can't specify both obsp, neighbors_key. Please select only one."
raise ValueError(msg)

if obsp is not None:
return adata.obsp[obsp]
else:
neighbors = NeighborsView(adata, neighbors_key)
if "connectivities" not in neighbors:
raise ValueError(
msg = (
"You need to run `pp.neighbors` first to compute a neighborhood graph."
)
raise ValueError(msg)
return neighbors["connectivities"]


Expand Down
8 changes: 4 additions & 4 deletions src/scanpy/neighbors/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -823,10 +823,11 @@ def _init_iroot(self):
# set iroot directly
if "iroot" in self._adata.uns:
if self._adata.uns["iroot"] >= self._adata.n_obs:
logg.warning(
msg = (
f"Root cell index {self._adata.uns['iroot']} does not "
f"exist for {self._adata.n_obs} samples. It’s ignored."
)
logg.warning(msg)
else:
self.iroot = self._adata.uns["iroot"]
return
Expand Down Expand Up @@ -888,9 +889,8 @@ def _set_iroot_via_xroot(self, xroot: np.ndarray):
condition, only relevant for computing pseudotime.
"""
if self._adata.shape[1] != xroot.size:
raise ValueError(
"The root vector you provided does not have the correct dimension."
)
msg = "The root vector you provided does not have the correct dimension."
raise ValueError(msg)
# this is the squared distance
dsqroot = 1e10
iroot = 0
Expand Down
5 changes: 2 additions & 3 deletions src/scanpy/plotting/_anndata.py
Original file line number Diff line number Diff line change
Expand Up @@ -848,9 +848,8 @@ def violin(
f"Expected number of y-labels to be `1`, found `{len(ylabel)}`."
)
elif len(ylabel) != len(keys):
raise ValueError(
f"Expected number of y-labels to be `{len(keys)}`, found `{len(ylabel)}`."
)
msg = f"Expected number of y-labels to be `{len(keys)}`, found `{len(ylabel)}`."
raise ValueError(msg)

if groupby is not None:
obs_df = get.obs_df(adata, keys=[groupby] + keys, layer=layer, use_raw=use_raw)
Expand Down
5 changes: 2 additions & 3 deletions src/scanpy/plotting/_tools/paga.py
Original file line number Diff line number Diff line change
Expand Up @@ -547,9 +547,8 @@ def is_flat(x):

if isinstance(root, str):
if root not in labels:
raise ValueError(
f"If `root` is a string, it needs to be one of {labels} not {root!r}."
)
msg = f"If `root` is a string, it needs to be one of {labels} not {root!r}."
raise ValueError(msg)
root = list(labels).index(root)
if isinstance(root, Sequence) and root[0] in labels:
root = [list(labels).index(r) for r in root]
Expand Down
10 changes: 5 additions & 5 deletions src/scanpy/readwrite.py
Original file line number Diff line number Diff line change
Expand Up @@ -219,10 +219,11 @@ def read_10x_h5(
adata = _read_v3_10x_h5(filename, start=start)
if genome:
if genome not in adata.var["genome"].values:
raise ValueError(
msg = (
f"Could not find data corresponding to genome '{genome}' in '{filename}'. "
f"Available genomes are: {list(adata.var['genome'].unique())}."
)
raise ValueError(msg)
adata = adata[:, adata.var["genome"] == genome]
if gex_only:
adata = adata[:, adata.var["feature_types"] == "Gene Expression"]
Expand Down Expand Up @@ -766,9 +767,8 @@ def _read(
**kwargs,
):
if ext is not None and ext not in avail_exts:
raise ValueError(
f"Please provide one of the available extensions.\n{avail_exts}"
)
msg = f"Please provide one of the available extensions.\n{avail_exts}"
raise ValueError(msg)
else:
ext = is_valid_filename(filename, return_ext=True)
is_present = _check_datafile_present_and_download(filename, backup_url=backup_url)
Expand Down Expand Up @@ -816,7 +816,7 @@ def _read(
elif ext in {"txt", "tab", "data", "tsv"}:
if ext == "data":
logg.hint(
"... assuming '.data' means tab or white-space separated text file",
"... assuming '.data' means tab or white-space separated text file"
)
logg.hint("change this by passing `ext` to sc.read")
adata = read_text(filename, delimiter, first_column_names)
Expand Down
5 changes: 2 additions & 3 deletions src/scanpy/tools/_louvain.py
Original file line number Diff line number Diff line change
Expand Up @@ -143,9 +143,8 @@ def louvain(
partition_kwargs = dict(partition_kwargs)
start = logg.info("running Louvain clustering")
if (flavor != "vtraag") and (partition_type is not None):
raise ValueError(
'`partition_type` is only a valid argument when `flavour` is "vtraag"'
)
msg = '`partition_type` is only a valid argument when `flavour` is "vtraag"'
raise ValueError(msg)
adata = adata.copy() if copy else adata
if adjacency is None:
adjacency = _choose_graph(adata, obsp, neighbors_key)
Expand Down
8 changes: 4 additions & 4 deletions src/scanpy/tools/_sim.py
Original file line number Diff line number Diff line change
Expand Up @@ -854,9 +854,8 @@ def build_boolCoeff(self):
raise ValueError(f"specify coupling value for {key} <- {g}")
else:
if np.abs(self.Coupl[self.varNames[key], g]) > 1e-10:
raise ValueError(
f"there should be no coupling value for {key} <- {g}"
)
msg = f"there should be no coupling value for {key} <- {g}"
raise ValueError(msg)
if self.verbosity > 1:
settings.m(0, "..." + key)
settings.m(0, rule)
Expand Down Expand Up @@ -1045,7 +1044,8 @@ def sample_coupling_matrix(
check = True
break
if not check:
raise ValueError(f"did not find graph without cycles after{max_trial} trials")
msg = f"did not find graph without cycles after {max_trial} trials"
raise ValueError(msg)
return Coupl, Adj, Adj_signed, n_edges


Expand Down
3 changes: 2 additions & 1 deletion src/scanpy/tools/_utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -128,5 +128,6 @@ def get_init_pos_from_paga(
else:
init_pos[subset] = group_pos
else:
raise ValueError("Plot PAGA first, so that adata.uns['paga']with key 'pos'.")
msg = "Plot PAGA first, so that adata.uns['paga'] with key 'pos'."
raise ValueError(msg)
return init_pos

0 comments on commit 903f0b0

Please sign in to comment.