repo
stringlengths
3
91
file
stringlengths
16
152
code
stringlengths
0
3.77M
file_length
int64
0
3.77M
avg_line_length
float64
0
16k
max_line_length
int64
0
273k
extension_type
stringclasses
1 value
nosnoc_py
nosnoc_py-main/test/test_initializing.py
import numpy as np import unittest import nosnoc from examples.sliding_mode_ocp.sliding_mode_ocp import get_sliding_mode_ocp_description, get_default_options, X0, TERMINAL_TIME class TestInitialization(unittest.TestCase): """Test several initialization methods.""" def test_initialization(self): """Test initialization of x and u.""" global X0 opts = get_default_options() opts.terminal_time = TERMINAL_TIME opts.sigma_0 = 1e-1 opts.comp_tol = 1e-6 opts2 = get_default_options() opts2.terminal_time = TERMINAL_TIME opts2.sigma_0 = 1e-1 opts2.comp_tol = 1e-6 [model, ocp] = get_sliding_mode_ocp_description() [model2, ocp2] = get_sliding_mode_ocp_description() u1_est = np.zeros((opts.N_stages, 1)) u1_est[-1] = -2.5 u1_est[-2] = 0.1 u2_est = np.zeros((opts.N_stages, 1)) u2_est[-1] = 0.5 u2_est[-2] = -2.0 u_guess = np.concatenate((u1_est, u2_est), axis=1) X0 = X0.reshape((1, -1)) x_est = np.concatenate((X0 * 2 / 3, X0 * 1 / 3, np.zeros((opts.N_stages - 2, 4)))) opts.initialization_strategy = nosnoc.InitializationStrategy.EXTERNAL solver = nosnoc.NosnocSolver(opts, model, ocp) solver.set("x", x_est) for i in range(opts.N_stages): self.assertTrue( np.array_equal(solver.problem.w0[solver.problem.ind_x[i][0][0]], x_est[i, :])) solver.set("u", u_guess) self.assertTrue(np.array_equal(solver.problem.w0[solver.problem.ind_u], u_guess)) print("Solve with good initialization") res_initialized = solver.solve() print("Solve with bad initialization") solver2 = nosnoc.NosnocSolver(opts2, model2, ocp2) solver2.set("u", -u_guess) res_bad_init = solver2.solve() ipopt_iter_initialized = sum(res_initialized["nlp_iter"]) ipopt_iter_bad_init = sum(res_bad_init["nlp_iter"]) print(f"{ipopt_iter_initialized=} \t {ipopt_iter_bad_init=}") # If initialized, the iteration should be faster self.assertLessEqual(ipopt_iter_initialized, ipopt_iter_bad_init) if __name__ == "__main__": unittest.main()
2,247
34.68254
127
py
nosnoc_py
nosnoc_py-main/test/test_validation.py
import unittest import numpy as np from casadi import SX, horzcat, vertcat import nosnoc from examples.sliding_mode_ocp.sliding_mode_ocp import get_default_options, get_sliding_mode_ocp_description class TestValidation(unittest.TestCase): """Test validation of the inputs.""" def test_default_constructor(self): model, ocp = get_sliding_mode_ocp_description() opts = get_default_options() nosnoc.NosnocSolver(opts, model, ocp=ocp) def test_no_c_S_and_g_Stewart(self): x = SX.sym('x') F = [horzcat(-1, 1)] c = vertcat(0) S = [np.array([[1], [-1]])] g = [x, -x] X0 = np.array([0]) with self.assertRaises(ValueError): nosnoc.NosnocModel(x=x, F=F, x0=X0, c=c, S=S, g_Stewart=g) def test_no_switching_system(self): x = SX.sym('x') F = [horzcat(-1)] c = vertcat(1) S = [np.array([-1])] X0 = np.array([0]) model = nosnoc.NosnocModel(x=x, F=F, x0=X0, c=c, S=S) opts = get_default_options() with self.assertRaises(Warning): nosnoc.NosnocSolver(opts, model) def test_switching_system_wrong_g_Stewart(self): x = SX.sym('x') F = [horzcat(-1, 1)] g = [x, -x, -100] X0 = np.array([0]) model = nosnoc.NosnocModel(x=x, F=F, x0=X0, g_Stewart=g) opts = get_default_options() with self.assertRaises(ValueError): nosnoc.NosnocSolver(opts, model) def test_switching_system_wrong_S_shape(self): x = SX.sym('x') F = [horzcat(-x, 2 * x)] c = [x + x**2] S = [np.array([-1])] X0 = np.array([0]) model = nosnoc.NosnocModel(x=x, F=F, x0=X0, c=c, S=S) opts = get_default_options() with self.assertRaises(ValueError): nosnoc.NosnocSolver(opts, model) def test_option_check(self): model, ocp = get_sliding_mode_ocp_description() opts = get_default_options() opts.constraint_handling = True with self.assertRaises(TypeError): nosnoc.NosnocSolver(opts, model, ocp=ocp) opts = get_default_options() opts.constraint_handling = nosnoc.CrossComplementarityMode.COMPLEMENT_ALL_STAGE_VALUES_WITH_EACH_OTHER with self.assertRaises(TypeError): nosnoc.NosnocSolver(opts, model, ocp=ocp) if __name__ == "__main__": unittest.main()
2,426
30.934211
110
py
nosnoc_py
nosnoc_py-main/test/test_ocp.py
import unittest from parameterized import parameterized import numpy as np import nosnoc from examples.sliding_mode_ocp.sliding_mode_ocp import ( solve_ocp, example, get_default_options, X0, X_TARGET, TERMINAL_TIME, UBU, LBU, ) EQUIDISTANT_CONTROLS = [True, False] PSS_MODES = [nosnoc.PssMode.STEWART] MPCC_MODES = [ nosnoc.MpccMode.SCHOLTES_INEQ, nosnoc.MpccMode.SCHOLTES_EQ, nosnoc.MpccMode.ELASTIC_INEQ, nosnoc.MpccMode.ELASTIC_EQ, nosnoc.MpccMode.ELASTIC_TWO_SIDED ] STEP_EQUILIBRATION_MODES = [ nosnoc.StepEquilibrationMode.HEURISTIC_MEAN, nosnoc.StepEquilibrationMode.HEURISTIC_DELTA, nosnoc.StepEquilibrationMode.L2_RELAXED, nosnoc.StepEquilibrationMode.L2_RELAXED_SCALED ] options = [ (equidistant_control_grid, step_equilibration, irk_representation, irk_scheme, pss_mode, nosnoc.HomotopyUpdateRule.LINEAR, nosnoc.MpccMode.SCHOLTES_INEQ) for equidistant_control_grid in EQUIDISTANT_CONTROLS for step_equilibration in STEP_EQUILIBRATION_MODES for irk_representation in nosnoc.IrkRepresentation for irk_scheme in nosnoc.IrkSchemes for pss_mode in PSS_MODES ] # test MpccMode separately without cartesian product options = [ (True, nosnoc.StepEquilibrationMode.HEURISTIC_MEAN, nosnoc.IrkRepresentation.DIFFERENTIAL, nosnoc.IrkSchemes.RADAU_IIA, nosnoc.PssMode.STEWART, nosnoc.HomotopyUpdateRule.LINEAR, mpcc_mode) for mpcc_mode in MPCC_MODES ] # test HomotopyUpdateRule.SUPERLINEAR separately without cartesian product # options += [ # (True, nosnoc.StepEquilibrationMode.L2_RELAXED, nosnoc.IrkRepresentation.DIFFERENTIAL, # nosnoc.IrkSchemes.RADAU_IIA, nosnoc.PssMode.STEWART, nosnoc.HomotopyUpdateRule.SUPERLINEAR, nosnoc.MpccMode.SCHOLTES_EQ), # ] class TestOcp(unittest.TestCase): def test_default(self): example(plot=False) @parameterized.expand(options) def test_combination(self, equidistant_control_grid, step_equilibration, irk_representation, irk_scheme, pss_mode, homotopy_update_rule, mpcc_mode): opts = get_default_options() opts.comp_tol = 1e-5 opts.N_stages = 5 opts.N_finite_elements = 2 opts.equidistant_control_grid = equidistant_control_grid opts.step_equilibration = step_equilibration opts.irk_representation = irk_representation opts.irk_scheme = irk_scheme opts.pss_mode = pss_mode opts.homotopy_update_rule = homotopy_update_rule opts.mpcc_mode = mpcc_mode message = ( f"Test setting: equidistant_control_grid {equidistant_control_grid}" + f"\n{step_equilibration}\n{irk_representation}\n{irk_scheme}\n{pss_mode}\n{homotopy_update_rule}" f"\n{mpcc_mode}" ) print(message) results = solve_ocp(opts) x_traj = results["x_traj"] u_traj = results["u_traj"] t_grid = results["t_grid"] self.assertTrue(np.allclose(x_traj[0], X0, atol=1e-4), message) self.assertTrue(np.allclose(x_traj[-1][:2], X_TARGET, atol=1e-4), message) self.assertTrue(np.allclose(t_grid[-1], TERMINAL_TIME, atol=1e-6), message) self.assertTrue(np.allclose(t_grid[0], 0.0, atol=1e-6), message) self.assertTrue(np.alltrue(u_traj < UBU), message) self.assertTrue(np.alltrue(u_traj > LBU), message) if __name__ == "__main__": unittest.main()
3,435
34.791667
147
py
nosnoc_py
nosnoc_py-main/docs/source/conf.py
# Configuration file for the Sphinx documentation builder. # -- Project information import sys, os # TODO: needed? sys.path.insert(0, os.path.abspath('../..')) print(sys.path) project = 'nosnoc' copyright = '2023, Jonathan Frey, Anton Pozharskiy, Armin Nurkanovic' author = 'Jonathan Frey, Anton Pozharskiy, Armin Nurkanovic' release = '0.1' version = '0.1.0' # -- General configuration extensions = [ 'sphinx.ext.duration', 'sphinx.ext.doctest', 'sphinx.ext.autodoc', 'sphinx.ext.autosummary', 'sphinx.ext.intersphinx', 'enum_tools.autoenum', ] intersphinx_mapping = { 'python': ('https://docs.python.org/3/', None), 'sphinx': ('https://www.sphinx-doc.org/en/master/', None), } intersphinx_disabled_domains = ['std'] templates_path = ['_templates'] # -- Options for HTML output html_theme = 'sphinx_rtd_theme' # -- Options for EPUB output epub_show_urls = 'footnote'
911
20.714286
69
py
nosnoc_py
nosnoc_py-main/nosnoc/plot_utils.py
import numpy as np import matplotlib.pyplot as plt import matplotlib from nosnoc import NosnocProblem, get_results_from_primal_vector from .utils import flatten_layer from .nosnoc_types import PssMode def latexify_plot(): params = { # "backend": "TkAgg", "text.latex.preamble": r"\usepackage{gensymb} \usepackage{amsmath}", "axes.labelsize": 10, "axes.titlesize": 10, "legend.fontsize": 10, "xtick.labelsize": 10, "ytick.labelsize": 10, "text.usetex": True, "font.family": "serif", } matplotlib.rcParams.update(params) def plot_timings(timings: np.ndarray, latexify=True, title=None, figure_filename=None): if latexify: latexify_plot() # timings = [sum(t) for t in timings] nlp_iter = timings.shape[1] Nsim = timings.shape[0] x = range(Nsim) y = np.zeros((Nsim,)) plt.figure() for i in range(nlp_iter): y_iter = timings[:, i] plt.bar(x, y_iter, bottom=y, label=f'homotopy iter {i+1}') y += y_iter x_range = [-.5, Nsim - .5] mean_cpu = np.mean(np.sum(timings, axis=1)) plt.plot(x_range, mean_cpu * np.ones(2,), label=f'mean/step {mean_cpu:.3f}', linestyle=':', color='black') plt.ylabel('CPU time [s]') plt.xlabel('simulation step') plt.legend() plt.xlim(x_range) plt.grid(alpha=0.3) if title is not None: plt.title(title) if figure_filename is not None: plt.savefig(figure_filename) print(f'stored figure as {figure_filename}') plt.show() def plot_iterates(problem: NosnocProblem, iterates: list, latexify=False, title_list=[], figure_filename=None): if latexify: latexify_plot() plt.figure() n_iterates = len(iterates) if title_list == []: title_list = n_iterates * [''] if problem.opts.pss_mode != PssMode.STEWART: raise NotImplementedError n_row = 3 for it, iterate in enumerate(iterates): results = get_results_from_primal_vector(problem, iterate) # flatten sys layer lambdas = flatten_layer(results['lambda_list'], 2) thetas = flatten_layer(results['theta_list'], 2) mus = flatten_layer(results['mu_list'], 2) # flatten fe layer lambdas = flatten_layer(lambdas, 0) thetas = flatten_layer(thetas, 0) mus = flatten_layer(mus, 0) n_lam = len(lambdas[0]) n_mu = len(mus[0]) # plot lambda, mu plt.subplot(n_row, n_iterates, n_iterates * 0 + it + 1) for i in range(n_lam): plt.plot([x[i] for x in lambdas], label=f'$\\lambda_{i+1}$') for i in range(n_mu): plt.plot([x[i] for x in mus], label=f'$\\mu_{i+1}$') plt.grid(alpha=0.3) plt.title(title_list[it]) plt.legend() # plot theta # TODO: make this step plot? plt.subplot(n_row, n_iterates, n_iterates * 1 + it + 1) for i in range(n_lam): plt.plot([x[i] for x in thetas], label=r'$\\theta_' + f'{i+1}$') plt.grid(alpha=0.3) plt.legend() # plot x x_list = results['x_all_list'] plt.subplot(n_row, n_iterates, n_iterates * 2 + it + 1) for i in range(problem.model.dims.n_x): plt.plot([x[i] for x in x_list], label=r'$x_' + f'{i+1}$') plt.grid(alpha=0.3) plt.legend() if figure_filename is not None: plt.savefig(figure_filename) print(f'stored figure as {figure_filename}') # plt.show() return def plot_voronoi_2d(Z, show=True, annotate=False, ax=None): """Plot voronoi regions.""" from scipy.spatial import Voronoi, voronoi_plot_2d if not isinstance(Z, np.ndarray): Z = np.array(Z) vor = Voronoi(Z) fig = voronoi_plot_2d(vor, ax=ax, show_vertices=False) if ax is None: ax = fig.axes[0] if annotate: for i in range(Z.shape[0]): ax.text(Z[i, 0], Z[i, 1], f"p{i+1}") plt.grid(visible=True) if show: plt.show() return ax def scatter_3d(Z, show=True, ax=None, annotate=False): """ 3D scatter points. :param Z: List of points :param show: Show the scatterplot after drawing :param ax: Optional axis to draw the points onto :param annotate: Annotate the points (with p_x) :return: ax """ if ax is None: fig = plt.figure() ax = fig.add_subplot(projection='3d') ax.scatter( [z[0] for z in Z], [z[1] for z in Z], [z[2] for z in Z], ) if annotate: for i, pi in enumerate(Z): ax.text(pi[0], pi[1], pi[2], f"p{i+1}", zdir=(1, 0, 0)) if show: plt.show() return ax def _plot_color_hack_3d(ax, x, y, z, t): """Color hack for 3d plot.""" t_min = min(t) dt = max(t) - t_min for i in range(np.size(x)-1): ax.plot(x[i:i+2], y[i:i+2], z[i:i+2], color=plt.cm.hot( (t[i] - t_min) / dt )) def plot_colored_line_3d(x, y, z, t, ax=None, label="Trajectory", label_4d="Time"): """ Plot colored line in 3D. :param x: x values :param y: y values :param z: z values :param t: time values (fourth dimension) :param ax: axis :param label: Label of the line :param label_4d: Label of the 4th dimension (None = don't add) :return ax """ if ax is None: fig = plt.figure() ax = fig.add_subplot(projection='3d') _plot_color_hack_3d(ax, x, y, z, t) im = ax.scatter(x, y, z, c=t, label=label, cmap=plt.hot()) if label_4d is not None: im.set_label(label_4d) plt.colorbar(im, ax=ax) return ax
5,818
25.692661
87
py
nosnoc_py
nosnoc_py-main/nosnoc/problem.py
from typing import Optional, List from abc import ABC, abstractmethod from copy import copy import numpy as np import casadi as ca from nosnoc.model import NosnocModel from nosnoc.nosnoc_opts import NosnocOpts from nosnoc.nosnoc_types import MpccMode, CrossComplementarityMode, StepEquilibrationMode, PssMode, IrkRepresentation, ConstraintHandling from nosnoc.ocp import NosnocOcp from nosnoc.utils import casadi_length, casadi_vertcat_list, casadi_sum_list, flatten, increment_indices, create_empty_list_matrix class NosnocFormulationObject(ABC): @abstractmethod def __init__(self): # optimization variables with initial guess, bounds self.w: ca.SX = ca.SX([]) self.w0: np.array = np.array([]) self.lbw: np.array = np.array([]) self.ubw: np.array = np.array([]) # constraints and bounds self.g: ca.SX = ca.SX([]) self.lbg: np.array = np.array([]) self.ubg: np.array = np.array([]) # cost self.cost: ca.SX = ca.SX.zeros(1) # index lists self.ind_x: list self.ind_lam: list self.ind_lambda_n: list self.ind_lambda_p: list def __repr__(self): return repr(self.__dict__) def add_variable(self, symbolic: ca.SX, index: list, lb: np.array, ub: np.array, initial: np.array, stage: Optional[int] = None, sys: Optional[int] = None): n = casadi_length(symbolic) nw = casadi_length(self.w) if len(lb) != n or len(ub) != n or len(initial) != n: raise Exception( f'add_variable, inconsistent dimension: {symbolic=}, {lb=}, {ub=}, {initial=}') self.w = ca.vertcat(self.w, symbolic) self.lbw = np.concatenate((self.lbw, lb)) self.ubw = np.concatenate((self.ubw, ub)) self.w0 = np.concatenate((self.w0, initial)) new_indices = list(range(nw, nw + n)) if stage is None: index.append(new_indices) else: if sys is not None: index[stage][sys] = new_indices else: index[stage] = new_indices return def add_constraint(self, symbolic: ca.SX, lb=None, ub=None, index: Optional[list] = None): n = casadi_length(symbolic) if n == 0: return if lb is None: lb = np.zeros((n,)) if ub is None: ub = np.zeros((n,)) if len(lb) != n or len(ub) != n: raise Exception(f'add_constraint, inconsistent dimension: {symbolic=}, {lb=}, {ub=}') if index is not None: ng = casadi_length(self.g) new_indices = list(range(ng, ng + n)) index.append(new_indices) self.g = ca.vertcat(self.g, symbolic) self.lbg = np.concatenate((self.lbg, lb)) self.ubg = np.concatenate((self.ubg, ub)) return def create_complementarity(self, x: List[ca.SX], y: ca.SX, sigma: ca.SX, tau: ca.SX, s_elastic: ca.SX) -> None: """ adds complementarity constraints corresponding to (x_i, y) for x_i in x to the FiniteElement. :param x: list of ca.SX :param y: ca.SX :param sigma: smoothing parameter :param tau: another smoothing parameter """ opts = self.opts n = casadi_length(y) if opts.mpcc_mode in [MpccMode.SCHOLTES_EQ, MpccMode.SCHOLTES_INEQ]: # g_comp = ca.diag(y) @ casadi_sum_list([x_i for x_i in x]) - sigma # this works too but is a bit slower. g_comp = ca.diag(casadi_sum_list([x_i for x_i in x])) @ y - sigma # NOTE: this line should be equivalent but yield different results # g_comp = casadi_sum_list([ca.diag(x_i) @ y for x_i in x]) - sigma elif opts.mpcc_mode in [MpccMode.ELASTIC_EQ, MpccMode.ELASTIC_INEQ]: g = ca.diag(casadi_sum_list([x_i for x_i in x])) @ y g_comp = g - s_elastic * np.ones((n, 1)) elif opts.mpcc_mode == MpccMode.ELASTIC_TWO_SIDED: g = ca.diag(casadi_sum_list([x_i for x_i in x])) @ y g_comp = ca.vertcat( g - s_elastic * np.ones((n, 1)), g + s_elastic * np.ones((n, 1)) ) elif opts.mpcc_mode == MpccMode.FISCHER_BURMEISTER: g_comp = ca.SX.zeros(n, 1) for j in range(n): for x_i in x: g_comp[j] += x_i[j] + y[j] - ca.sqrt(x_i[j]**2 + y[j]**2 + sigma**2) elif opts.mpcc_mode == MpccMode.FISCHER_BURMEISTER_IP_AUG: if len(x) != 1: raise Exception("not supported") g_comp = ca.SX.zeros(4 * n, 1) # classic FB for j in range(n): for x_i in x: g_comp[j] += x_i[j] + y[j] - ca.sqrt(x_i[j]**2 + y[j]**2 + sigma**2) # augment 1 for j in range(n): for x_i in x: g_comp[j + n] = opts.fb_ip_aug1_weight * (x_i[j] - sigma) * ca.sqrt(tau) g_comp[j + 2 * n] = opts.fb_ip_aug1_weight * (y[j] - sigma) * ca.sqrt(tau) # augment 2 for j in range(n): for x_i in x: g_comp[j + 3 * n] = opts.fb_ip_aug2_weight * (g_comp[j]) * ca.sqrt(1 + (x_i[j] - y[j])**2) n_comp = casadi_length(g_comp) if opts.mpcc_mode in [MpccMode.SCHOLTES_INEQ, MpccMode.ELASTIC_INEQ]: lb_comp = -np.inf * np.ones((n_comp,)) ub_comp = np.zeros((n_comp,)) elif opts.mpcc_mode in [ MpccMode.SCHOLTES_EQ, MpccMode.FISCHER_BURMEISTER, MpccMode.FISCHER_BURMEISTER_IP_AUG, MpccMode.ELASTIC_EQ ]: lb_comp = np.zeros((n_comp,)) ub_comp = np.zeros((n_comp,)) elif opts.mpcc_mode == MpccMode.ELASTIC_TWO_SIDED: lb_comp = np.hstack((-ca.inf*np.ones((n,)), np.zeros((n,)))) ub_comp = np.hstack((np.zeros((n,)), ca.inf*np.ones((n,)))) self.add_constraint(g_comp, lb=lb_comp, ub=ub_comp, index=self.ind_comp) return class FiniteElementBase(NosnocFormulationObject): def Lambda(self, stage=slice(None), sys=slice(None)): return ca.vertcat(self.w[flatten(self.ind_lam[stage][sys])], self.w[flatten(self.ind_lambda_n[stage][sys])], self.w[flatten(self.ind_lambda_p[stage][sys])]) class FiniteElementZero(FiniteElementBase): def __init__(self, opts: NosnocOpts, model: NosnocModel): super().__init__() dims = model.dims self.ind_x = create_empty_list_matrix((1,)) self.ind_lam = create_empty_list_matrix((1, dims.n_sys)) self.ind_lambda_n = create_empty_list_matrix((1, dims.n_sys)) self.ind_lambda_p = create_empty_list_matrix((1, dims.n_sys)) # NOTE: bounds are actually not used, maybe rewrite without add_vairable # X0 self.add_variable(ca.SX.sym('X0', dims.n_x), self.ind_x, model.x0, model.x0, model.x0, 0) # lambda00 if opts.pss_mode == PssMode.STEWART: for ij in range(dims.n_sys): self.add_variable(ca.SX.sym(f'lambda00_{ij+1}', dims.n_f_sys[ij]), self.ind_lam, -np.inf * np.ones(dims.n_f_sys[ij]), np.inf * np.ones(dims.n_f_sys[ij]), opts.init_lambda * np.ones(dims.n_f_sys[ij]), 0, ij) elif opts.pss_mode == PssMode.STEP: for ij in range(dims.n_sys): self.add_variable(ca.SX.sym(f'lambda00_n_{ij+1}', dims.n_c_sys[ij]), self.ind_lambda_n, -np.inf * np.ones(dims.n_c_sys[ij]), np.inf * np.ones(dims.n_c_sys[ij]), opts.init_lambda * np.ones(dims.n_c_sys[ij]), 0, ij) self.add_variable(ca.SX.sym(f'lambda00_p_{ij+1}', dims.n_c_sys[ij]), self.ind_lambda_p, -np.inf * np.ones(dims.n_c_sys[ij]), np.inf * np.ones(dims.n_c_sys[ij]), opts.init_lambda * np.ones(dims.n_c_sys[ij]), 0, ij) class FiniteElement(FiniteElementBase): def __init__(self, opts: NosnocOpts, model: NosnocModel, ocp: NosnocOcp, ctrl_idx: int, fe_idx: int, prev_fe=None): super().__init__() n_s = opts.n_s # store info self.n_rkstages = n_s self.ctrl_idx = ctrl_idx self.fe_idx = fe_idx self.opts = opts self.model = model self.ocp = ocp self.prev_fe: FiniteElementBase = prev_fe self.p = model.p_ctrl_stages[ctrl_idx] dims = self.model.dims # right boundary create_right_boundary_point = (opts.use_fesd and not opts.right_boundary_point_explicit and fe_idx < opts.Nfe_list[ctrl_idx] - 1) end_allowance = 1 if create_right_boundary_point else 0 # Initialze index lists if opts.irk_representation == IrkRepresentation.DIFFERENTIAL: # only x_end self.ind_x = create_empty_list_matrix((1,)) elif opts.right_boundary_point_explicit: self.ind_x = create_empty_list_matrix((n_s,)) else: self.ind_x = create_empty_list_matrix((n_s + 1,)) self.ind_v: list = create_empty_list_matrix((n_s,)) self.ind_theta = create_empty_list_matrix((n_s, dims.n_sys)) self.ind_lam = create_empty_list_matrix((n_s + end_allowance, dims.n_sys)) self.ind_mu = create_empty_list_matrix((n_s + end_allowance, dims.n_sys)) self.ind_alpha = create_empty_list_matrix((n_s, dims.n_sys)) self.ind_lambda_n = create_empty_list_matrix((n_s + end_allowance, dims.n_sys)) self.ind_lambda_p = create_empty_list_matrix((n_s + end_allowance, dims.n_sys)) self.ind_z = create_empty_list_matrix((n_s,)) self.ind_h = [] self.ind_comp = [] # create variables h = ca.SX.sym(f'h_{ctrl_idx}_{fe_idx}') h_ctrl_stage = opts.terminal_time / opts.N_stages h0 = np.array([h_ctrl_stage / np.array(opts.Nfe_list[ctrl_idx])]) ubh = (1 + opts.gamma_h) * h0 lbh = (1 - opts.gamma_h) * h0 self.add_step_size_variable(h, lbh, ubh, h0) if opts.mpcc_mode in [MpccMode.SCHOLTES_EQ, MpccMode.SCHOLTES_INEQ, MpccMode.ELASTIC_TWO_SIDED]: lb_dual = 0.0 else: lb_dual = -np.inf # RK stage stuff for ii in range(opts.n_s): # state derivatives if (opts.irk_representation in [IrkRepresentation.DIFFERENTIAL, IrkRepresentation.DIFFERENTIAL_LIFT_X]): self.add_variable(ca.SX.sym(f'V_{ctrl_idx}_{fe_idx}_{ii+1}', dims.n_x), self.ind_v, -np.inf * np.ones(dims.n_x), np.inf * np.ones(dims.n_x), np.zeros(dims.n_x), ii) # states if (opts.irk_representation in [IrkRepresentation.INTEGRAL, IrkRepresentation.DIFFERENTIAL_LIFT_X]): self.add_variable(ca.SX.sym(f'X_{ctrl_idx}_{fe_idx}_{ii+1}', dims.n_x), self.ind_x, ocp.lbx, ocp.ubx, model.x0, ii) # algebraic variables if opts.pss_mode == PssMode.STEWART: # add thetas for ij in range(dims.n_sys): self.add_variable( ca.SX.sym(f'theta_{ctrl_idx}_{fe_idx}_{ii+1}_{ij+1}', dims.n_f_sys[ij]), self.ind_theta, lb_dual * np.ones(dims.n_f_sys[ij]), np.inf * np.ones(dims.n_f_sys[ij]), opts.init_theta * np.ones(dims.n_f_sys[ij]), ii, ij) # add lambdas for ij in range(dims.n_sys): self.add_variable( ca.SX.sym(f'lambda_{ctrl_idx}_{fe_idx}_{ii+1}_{ij+1}', dims.n_f_sys[ij]), self.ind_lam, lb_dual * np.ones(dims.n_f_sys[ij]), np.inf * np.ones(dims.n_f_sys[ij]), opts.init_lambda * np.ones(dims.n_f_sys[ij]), ii, ij) # add mu for ij in range(dims.n_sys): self.add_variable(ca.SX.sym(f'mu_{ctrl_idx}_{fe_idx}_{ii+1}_{ij+1}', 1), self.ind_mu, -np.inf * np.ones(1), np.inf * np.ones(1), opts.init_mu * np.ones(1), ii, ij) elif opts.pss_mode == PssMode.STEP: # add alpha for ij in range(dims.n_sys): self.add_variable( ca.SX.sym(f'alpha_{ctrl_idx}_{fe_idx}_{ii+1}_{ij+1}', dims.n_c_sys[ij]), self.ind_alpha, lb_dual * np.ones(dims.n_c_sys[ij]), np.ones(dims.n_c_sys[ij]), opts.init_theta * np.ones(dims.n_c_sys[ij]), ii, ij) # add lambda_n for ij in range(dims.n_sys): self.add_variable( ca.SX.sym(f'lambda_n_{ctrl_idx}_{fe_idx}_{ii+1}_{ij+1}', dims.n_c_sys[ij]), self.ind_lambda_n, lb_dual * np.ones(dims.n_c_sys[ij]), np.inf * np.ones(dims.n_c_sys[ij]), opts.init_lambda * np.ones(dims.n_c_sys[ij]), ii, ij) # add lambda_p for ij in range(dims.n_sys): self.add_variable( ca.SX.sym(f'lambda_p_{ctrl_idx}_{fe_idx}_{ii+1}_{ij+1}', dims.n_c_sys[ij]), self.ind_lambda_p, lb_dual * np.ones(dims.n_c_sys[ij]), np.inf * np.ones(dims.n_c_sys[ij]), opts.init_mu * np.ones(dims.n_c_sys[ij]), ii, ij) # user algebraic variables self.add_variable( ca.SX.sym(f'z_{ctrl_idx}_{fe_idx}_{ii+1}', dims.n_z), self.ind_z, model.lbz, model.ubz, model.z0, ii ) # Add right boundary points if needed if create_right_boundary_point: if opts.pss_mode == PssMode.STEWART: # add lambdas for ij in range(dims.n_sys): self.add_variable( ca.SX.sym(f'lambda_{ctrl_idx}_{fe_idx}_end_{ij+1}', dims.n_f_sys[ij]), self.ind_lam, lb_dual * np.ones(dims.n_f_sys[ij]), np.inf * np.ones(dims.n_f_sys[ij]), opts.init_lambda * np.ones(dims.n_f_sys[ij]), opts.n_s, ij) # add mu for ij in range(dims.n_sys): self.add_variable(ca.SX.sym(f'mu_{ctrl_idx}_{fe_idx}_end_{ij+1}', 1), self.ind_mu, -np.inf * np.ones(1), np.inf * np.ones(1), opts.init_mu * np.ones(1), opts.n_s, ij) elif opts.pss_mode == PssMode.STEP: # add lambda_n for ij in range(dims.n_sys): self.add_variable( ca.SX.sym(f'lambda_n_{ctrl_idx}_{fe_idx}_end_{ij+1}', dims.n_c_sys[ij]), self.ind_lambda_n, lb_dual * np.ones(dims.n_c_sys[ij]), np.inf * np.ones(dims.n_c_sys[ij]), opts.init_lambda * np.ones(dims.n_c_sys[ij]), opts.n_s, ij) # add lambda_p for ij in range(dims.n_sys): self.add_variable( ca.SX.sym(f'lambda_p_{ctrl_idx}_{fe_idx}_end_{ij+1}', dims.n_c_sys[ij]), self.ind_lambda_p, lb_dual * np.ones(dims.n_c_sys[ij]), np.inf * np.ones(dims.n_c_sys[ij]), opts.init_mu * np.ones(dims.n_c_sys[ij]), opts.n_s, ij) if (not opts.right_boundary_point_explicit or opts.irk_representation == IrkRepresentation.DIFFERENTIAL): # add final X variables self.add_variable(ca.SX.sym(f'X_end_{ctrl_idx}_{fe_idx+1}', dims.n_x), self.ind_x, ocp.lbx, ocp.ubx, model.x0, -1) def add_step_size_variable(self, symbolic: ca.SX, lb: float, ub: float, initial: float): self.ind_h = casadi_length(self.w) self.w = ca.vertcat(self.w, symbolic) self.lbw = np.append(self.lbw, lb) self.ubw = np.append(self.ubw, ub) self.w0 = np.append(self.w0, initial) return def rk_stage_z(self, stage) -> ca.SX: idx = np.concatenate((flatten(self.ind_theta[stage]), flatten(self.ind_lam[stage]), flatten(self.ind_mu[stage]), flatten(self.ind_alpha[stage]), flatten(self.ind_lambda_n[stage]), flatten(self.ind_lambda_p[stage]), self.ind_z[stage])) return self.w[idx] def Theta(self, stage=slice(None), sys=slice(None)) -> ca.SX: return ca.vertcat( self.w[flatten(self.ind_theta[stage][sys])], self.w[flatten(self.ind_alpha[stage][sys])], np.ones(len(flatten(self.ind_alpha[stage][sys]))) - self.w[flatten(self.ind_alpha[stage][sys])]) def get_Theta_list(self) -> list: return [self.Theta(stage=ii) for ii in range(len(self.ind_theta))] def sum_Theta(self) -> ca.SX: return casadi_sum_list(self.get_Theta_list()) def get_Lambdas_incl_last_prev_fe(self, sys=slice(None)): Lambdas = [self.Lambda(stage=ii, sys=sys) for ii in range(len(self.ind_lam))] Lambdas += [self.prev_fe.Lambda(stage=-1, sys=sys)] return Lambdas def sum_Lambda(self, sys=slice(None)): """NOTE: includes the prev fes last stage lambda""" Lambdas = self.get_Lambdas_incl_last_prev_fe(sys) return casadi_sum_list(Lambdas) def h(self) -> List[ca.SX]: return self.w[self.ind_h] def X_fe(self) -> List[ca.SX]: """returns list of all x values in finite element""" opts = self.opts if opts.irk_representation == IrkRepresentation.INTEGRAL: X_fe = [self.w[ind] for ind in self.ind_x] elif opts.irk_representation == IrkRepresentation.DIFFERENTIAL: X_fe = [] for j in range(opts.n_s): x_temp = self.prev_fe.w[self.prev_fe.ind_x[-1]] for r in range(opts.n_s): x_temp += self.h() * opts.A_irk[j, r] * self.w[self.ind_v[r]] X_fe.append(x_temp) X_fe.append(self.w[self.ind_x[-1]]) elif opts.irk_representation == IrkRepresentation.DIFFERENTIAL_LIFT_X: X_fe = [self.w[ind] for ind in self.ind_x] return X_fe def forward_simulation(self, ocp: NosnocOcp, Uk: ca.SX) -> None: opts = self.opts model = self.model # setup X_fe: list of x values on fe, initialize X_end X_fe = self.X_fe() if opts.irk_representation == IrkRepresentation.INTEGRAL: Xk_end = opts.D_irk[0] * self.prev_fe.w[self.prev_fe.ind_x[-1]] elif opts.irk_representation == IrkRepresentation.DIFFERENTIAL: Xk_end = self.prev_fe.w[self.prev_fe.ind_x[-1]] elif opts.irk_representation == IrkRepresentation.DIFFERENTIAL_LIFT_X: Xk_end = self.prev_fe.w[self.prev_fe.ind_x[-1]] for j in range(opts.n_s): x_temp = self.prev_fe.w[self.prev_fe.ind_x[-1]] for r in range(opts.n_s): x_temp += self.h() * opts.A_irk[j, r] * self.w[self.ind_v[r]] # lifting constraints self.add_constraint(self.w[self.ind_x[j]] - x_temp) for j in range(opts.n_s): # Dynamics excluding complementarities fj = model.f_x_fun(X_fe[j], self.rk_stage_z(j), Uk, self.p, model.v_global) qj = ocp.f_q_fun(X_fe[j], Uk, self.p, model.v_global) gqj = ocp.g_path_fun(X_fe[j], Uk, self.p, model.v_global) self.add_constraint(gqj, ocp.lbg, ocp.ubg) # path constraint gj = model.g_z_all_fun(X_fe[j], self.rk_stage_z(j), Uk, self.p) self.add_constraint(gj) if opts.irk_representation == IrkRepresentation.INTEGRAL: xj = opts.C_irk[0, j + 1] * self.prev_fe.w[self.prev_fe.ind_x[-1]] for r in range(opts.n_s): xj += opts.C_irk[r + 1, j + 1] * X_fe[r] Xk_end += opts.D_irk[j + 1] * X_fe[j] self.add_constraint(self.h() * fj - xj) self.cost += opts.B_irk[j + 1] * self.h() * qj elif (opts.irk_representation in [IrkRepresentation.DIFFERENTIAL, IrkRepresentation.DIFFERENTIAL_LIFT_X]): Xk_end += self.h() * opts.b_irk[j] * self.w[self.ind_v[j]] self.add_constraint(fj - self.w[self.ind_v[j]]) self.cost += opts.b_irk[j] * self.h() * qj # continuity condition: end of fe state - final stage state if (not opts.right_boundary_point_explicit or opts.irk_representation == IrkRepresentation.DIFFERENTIAL): self.add_constraint(Xk_end - self.w[self.ind_x[-1]]) # g_z_all constraint for boundary point and continuity of algebraic variables. if not opts.right_boundary_point_explicit and opts.use_fesd and ( self.fe_idx < opts.Nfe_list[self.ctrl_idx] - 1): self.add_constraint( model.g_z_switching_fun(self.w[self.ind_x[-1]], self.rk_stage_z(-1), Uk, self.p)) return def create_complementarity_constraints(self, sigma_p: ca.SX, tau: ca.SX, Uk: ca.SX, s_elastic: ca.SX) -> None: opts = self.opts X_fe = self.X_fe() for j in range(opts.n_s): z = self.rk_stage_z(j) stage_comps = self.ocp.g_rk_comp_fun(X_fe[j], Uk, z, self.p, self.model.v_global) # TODO maybe should include stage z a, b = ca.horzsplit(stage_comps) self.create_complementarity([a], b, sigma_p, tau, s_elastic) if self.fe_idx == opts.N_finite_elements-1: ctrl_comps = self.ocp.g_ctrl_comp_fun(Uk, self.p, self.model.v_global) a, b = ca.horzsplit(ctrl_comps) self.create_complementarity([a], b, sigma_p, tau, s_elastic) if not opts.use_fesd: for j in range(opts.n_s): self.create_complementarity([self.Lambda(stage=j)], self.Theta(stage=j), sigma_p, tau, s_elastic) elif opts.cross_comp_mode == CrossComplementarityMode.COMPLEMENT_ALL_STAGE_VALUES_WITH_EACH_OTHER: for j in range(opts.n_s): # cross comp with prev_fe self.create_complementarity([self.Theta(stage=j)], self.prev_fe.Lambda(stage=-1), sigma_p, tau, s_elastic) for jj in range(opts.n_s): # within fe self.create_complementarity([self.Theta(stage=j)], self.Lambda(stage=jj), sigma_p, tau, s_elastic) elif opts.cross_comp_mode == CrossComplementarityMode.SUM_LAMBDAS_COMPLEMENT_WITH_EVERY_THETA: for j in range(opts.n_s): # Note: sum_Lambda contains last stage of prev_fe Lambda_list = self.get_Lambdas_incl_last_prev_fe() self.create_complementarity(Lambda_list, (self.Theta(stage=j)), sigma_p, tau, s_elastic) return def step_equilibration(self, sigma_p: ca.SX, tau: ca.SX, s_elastic: Optional[ca.SX]) -> None: opts = self.opts if not opts.use_fesd: return # only step equilibration mode that does not require previous finite element if opts.step_equilibration == StepEquilibrationMode.HEURISTIC_MEAN: h_fe = opts.terminal_time / (opts.N_stages * opts.Nfe_list[self.ctrl_idx]) self.cost += opts.rho_h * (self.h() - h_fe)**2 return elif not self.fe_idx > 0: return prev_fe: FiniteElement = self.prev_fe delta_h_ki = self.h() - prev_fe.h() if opts.step_equilibration == StepEquilibrationMode.HEURISTIC_DELTA: self.cost += opts.rho_h * delta_h_ki**2 return # modes that need nu_k eta_k = prev_fe.sum_Lambda() * self.sum_Lambda() + \ prev_fe.sum_Theta() * self.sum_Theta() nu_k = 1 for jjj in range(casadi_length(eta_k)): nu_k = nu_k * eta_k[jjj] if opts.step_equilibration == StepEquilibrationMode.L2_RELAXED_SCALED: self.cost += opts.rho_h * ca.tanh(nu_k / opts.step_equilibration_sigma) * delta_h_ki**2 elif opts.step_equilibration == StepEquilibrationMode.L2_RELAXED: self.cost += opts.rho_h * nu_k * delta_h_ki**2 elif opts.step_equilibration == StepEquilibrationMode.DIRECT: self.add_constraint(nu_k * delta_h_ki) elif opts.step_equilibration == StepEquilibrationMode.DIRECT_COMPLEMENTARITY: self.create_complementarity([nu_k], delta_h_ki, sigma_p, tau, s_elastic) elif opts.step_equilibration == StepEquilibrationMode.HEURISTIC_DELTA_H_COMP: self.create_complementarity([ca.SX.zeros()], delta_h_ki, sigma_p, tau, s_elastic) # elif opts.step_equilibration == StepEquilibrationMode.DIRECT_TANH: # self.add_constraint(ca.tanh(nu_k)*delta_h_ki) return class NosnocProblem(NosnocFormulationObject): def __create_control_stage(self, ctrl_idx, prev_fe): # Create control vars Uk = ca.SX.sym(f'U_{ctrl_idx}', self.model.dims.n_u) self.add_variable(Uk, self.ind_u, self.ocp.lbu, self.ocp.ubu, self.ocp.u_guess) # Create Finite elements in this control stage control_stage = [] for ii in range(self.opts.Nfe_list[ctrl_idx]): fe = FiniteElement(self.opts, self.model, self.ocp, ctrl_idx, fe_idx=ii, prev_fe=prev_fe) self._add_finite_element(fe, ctrl_idx) control_stage.append(fe) prev_fe = fe return control_stage def __create_primal_variables(self): # Initial self.fe0 = FiniteElementZero(self.opts, self.model) x0 = self.fe0.w[self.fe0.ind_x[0]] lambda00 = self.fe0.Lambda() # lambda00 is parameter self.p = ca.vertcat(self.p, lambda00) self.p = ca.vertcat(self.p, x0) # v_global self.add_variable(self.model.v_global, self.ind_v_global, self.ocp.lbv_global, self.ocp.ubv_global, self.ocp.v_global_guess) # Generate control_stages prev_fe = self.fe0 for ii in range(self.opts.N_stages): stage = self.__create_control_stage(ii, prev_fe=prev_fe) self.stages.append(stage) prev_fe = stage[-1] def _add_finite_element(self, fe: FiniteElement, ctrl_idx: int): w_len = casadi_length(self.w) self._add_primal_vector(fe.w, fe.lbw, fe.ubw, fe.w0) # update all indices self.ind_h.append(fe.ind_h + w_len) self.ind_x[ctrl_idx].append(increment_indices(fe.ind_x, w_len)) self.ind_x_cont[ctrl_idx].append(increment_indices(fe.ind_x[-1], w_len)) self.ind_v[ctrl_idx].append(increment_indices(fe.ind_v, w_len)) self.ind_theta[ctrl_idx].append(increment_indices(fe.ind_theta, w_len)) self.ind_lam[ctrl_idx].append(increment_indices(fe.ind_lam, w_len)) self.ind_mu[ctrl_idx].append(increment_indices(fe.ind_mu, w_len)) self.ind_alpha[ctrl_idx].append(increment_indices(fe.ind_alpha, w_len)) self.ind_lambda_n[ctrl_idx].append(increment_indices(fe.ind_lambda_n, w_len)) self.ind_lambda_p[ctrl_idx].append(increment_indices(fe.ind_lambda_p, w_len)) self.ind_z[ctrl_idx].append(increment_indices(fe.ind_z, w_len)) # TODO: can we just use add_variable? It is a bit involved, since index vectors here have different format. def _add_primal_vector(self, symbolic: ca.SX, lb: np.array, ub, initial): n = casadi_length(symbolic) if len(lb) != n or len(ub) != n or len(initial) != n: raise Exception( f'_add_primal_vector, inconsistent dimension: {symbolic=}, {lb=}, {ub=}, {initial=}' ) self.w = ca.vertcat(self.w, symbolic) self.lbw = np.concatenate((self.lbw, lb)) self.ubw = np.concatenate((self.ubw, ub)) self.w0 = np.concatenate((self.w0, initial)) return def add_fe_constraints(self, fe: FiniteElement, ctrl_idx: int): g_len = casadi_length(self.g) self.add_constraint(fe.g, fe.lbg, fe.ubg) # constraint indices self.ind_comp[ctrl_idx].append(increment_indices(fe.ind_comp, g_len)) return def create_global_compl_constraints(self, sigma_p: ca.SX, tau: ca.SX, s_elastic: ca.SX) -> None: # TODO add other complementarity modes here. p_global = self.p[self.model.dims.n_p_time_var:self.model.dims.n_p_time_var + self.model.dims.n_p_glob] stage_comps = self.ocp.g_global_comp_fun(p_global, self.model.v_global) # TODO maybe should include stage z a, b = ca.horzsplit(stage_comps) self.create_complementarity([a], b, sigma_p, tau, s_elastic) return def __init__(self, opts: NosnocOpts, model: NosnocModel, ocp: Optional[NosnocOcp] = None): super().__init__() self.model = model self.opts = opts if ocp is None: self.ocp_trivial = True ocp = NosnocOcp() else: self.ocp_trivial = False ocp.preprocess_ocp(model) self.ocp = ocp h_ctrl_stage = opts.terminal_time / opts.N_stages self.stages: list[list[FiniteElement]] = [] # Index vectors of optimization variables self.ind_x = create_empty_list_matrix((opts.N_stages,)) self.ind_x_cont = create_empty_list_matrix((opts.N_stages,)) self.ind_v = create_empty_list_matrix((opts.N_stages,)) self.ind_theta = create_empty_list_matrix((opts.N_stages,)) self.ind_lam = create_empty_list_matrix((opts.N_stages,)) self.ind_mu = create_empty_list_matrix((opts.N_stages,)) self.ind_alpha = create_empty_list_matrix((opts.N_stages,)) self.ind_lambda_n = create_empty_list_matrix((opts.N_stages,)) self.ind_lambda_p = create_empty_list_matrix((opts.N_stages,)) self.ind_z = create_empty_list_matrix((opts.N_stages,)) self.ind_elastic = [] self.ind_u = [] self.ind_h = [] self.ind_v_global = [] # Index vectors within constraints g self.ind_comp = create_empty_list_matrix((opts.N_stages,)) # setup parameters, lambda00 is added later: sigma_p = ca.SX.sym('sigma_p') # homotopy parameter if opts.mpcc_mode in [MpccMode.ELASTIC_TWO_SIDED, MpccMode.ELASTIC_EQ, MpccMode.ELASTIC_INEQ]: # Elasticity parameter s_elastic = ca.SX.sym('s_elastic') self.add_variable(s_elastic, self.ind_elastic, opts.s_elastic_min * np.ones(1), opts.s_elastic_max * np.ones(1), opts.s_elastic_0 * np.ones(1)) self.cost += 1 / sigma_p * s_elastic else: s_elastic = None tau = ca.SX.sym('tau') # homotopy parameter self.p = ca.vertcat(casadi_vertcat_list(model.p_ctrl_stages), sigma_p, tau) # Generate all the variables we need self.__create_primal_variables() fe: FiniteElement stage: List[FiniteElement] if opts.time_freezing: t0 = model.t_fun(self.fe0.w[self.fe0.ind_x[-1]]) for ctrl_idx, stage in enumerate(self.stages): Uk = self.w[self.ind_u[ctrl_idx]] for _, fe in enumerate(stage): # 1) Stewart Runge-Kutta discretization fe.forward_simulation(ocp, Uk) # 2) Complementarity Constraints fe.create_complementarity_constraints(sigma_p, tau, Uk, s_elastic) # 3) Step Equilibration fe.step_equilibration(sigma_p, tau, s_elastic) # 4) add cost and constraints from FE to problem self.cost += fe.cost self.add_fe_constraints(fe, ctrl_idx) if opts.use_fesd and opts.equidistant_control_grid: self.add_constraint(sum([fe.h() for fe in stage]) - h_ctrl_stage) if opts.time_freezing and opts.equidistant_control_grid: # TODO: make t0 dynamic (since now it needs to be 0!) t_now = opts.terminal_time / opts.N_stages * (ctrl_idx + 1) + t0 Xk_end = stage[-1].w[stage[-1].ind_x[-1]] self.add_constraint( model.t_fun(Xk_end) - t_now, [-opts.time_freezing_tolerance], [opts.time_freezing_tolerance]) # Create global complementarities self.create_global_compl_constraints(sigma_p, tau, s_elastic) # Scalar-valued complementarity residual if opts.use_fesd: J_comp = 0.0 for fe in flatten(self.stages): sum_abs_lam = casadi_sum_list( [ca.fabs(lam) for lam in fe.get_Lambdas_incl_last_prev_fe()]) sum_abs_theta = casadi_sum_list([ca.fabs(t) for t in fe.get_Theta_list()]) J_comp += ca.sum1(ca.diag(sum_abs_theta) @ sum_abs_lam) else: J_comp = casadi_sum_list([ model.std_compl_res_fun(fe.rk_stage_z(j), fe.p) for j in range(opts.n_s) for fe in flatten(self.stages) ]) # terminal constraint and cost # NOTE: this was evaluated at Xk_end (expression for previous state before) # which should be worse for convergence. x_terminal = self.w[self.ind_x[-1][-1][-1]] g_terminal = ocp.g_terminal_fun(x_terminal, model.p_ctrl_stages[-1], model.v_global) self.add_constraint(g_terminal) self.cost += ocp.f_q_T_fun(x_terminal, model.p_ctrl_stages[-1], model.v_global) # Terminal numerical time if opts.N_stages > 1 and opts.use_fesd: all_h = [fe.h() for stage in self.stages for fe in stage] self.add_constraint(sum(all_h) - opts.terminal_time) # CasADi Functions self.cost_fun = ca.Function('cost_fun', [self.w, self.p], [self.cost]) self.comp_res = ca.Function('comp_res', [self.w, self.p], [J_comp]) self.g_fun = ca.Function('g_fun', [self.w, self.p], [self.g]) # copy original w0 self.w0_original = self.w0.copy() # LEAST_SQUARES reformulation if opts.constraint_handling == ConstraintHandling.LEAST_SQUARES: self.g_lsq = copy(self.g) for ii in range(casadi_length(self.g)): if self.lbg[ii] != 0.0: raise Exception( f"least_squares constraint handling only supported if all lbg, ubg == 0.0, got {self.lbg[ii]=}, {self.ubg[ii]=}, {self.g[ii]=}" ) self.cost += self.g[ii]**2 self.g = ca.SX([]) self.lbg = np.array([]) self.ubg = np.array([]) def print(self): errors = 0 # constraints print("i\tlbg\t\t ubg\t\t g_expr") for i in range(len(self.lbg)): print(f"{i}: {self.lbg[i]:7} \t {self.ubg[i]:7} \t {self.g[i]}") # variables and bounds print("\nw \t\t\t w0 \t\t lbw \t\t ubw") for i in range(len(self.lbw)): extra_info = "" if self.lbw[i] > self.ubw[i]: extra_info = " BOUND ERROR!" errors += 1 elif self.w0[i] < self.lbw[i] or self.ubw[i] > self.ubw[i]: extra_info = " W0 ERROR!" errors += 1 print( f"{i}: {self.w[i].name():<15} \t {self.w0[i]:.2e} \t {self.lbw[i]:7} \t {self.ubw[i]:.2e}{extra_info}" ) # cost print(f"\ncost:\n{self.cost}") print(f"\nerrors: {errors}") def is_sim_problem(self): if self.model.dims.n_u != 0: return False if self.opts.N_stages != 1: return False if not self.ocp_trivial: return False return True
37,087
44.119221
151
py
nosnoc_py
nosnoc_py-main/nosnoc/utils.py
import numpy as np from typing import Union, List, get_origin, get_args import casadi as ca def make_object_json_dumpable(input): if isinstance(input, (np.ndarray)): return input.tolist() else: raise TypeError(f"Cannot make input of type {type(input)} dumpable.") def validate(obj: object) -> bool: for attr, expected_type in obj.__annotations__.items(): value = getattr(obj, attr) if get_origin(expected_type) is Union: if not isinstance(value, get_args(expected_type)): raise TypeError( f"object {type(obj)} does not match type annotations. Attribute {attr} should be of type {expected_type}, got {type(value)}" ) elif get_origin(expected_type) is List: if not isinstance(value, list): raise TypeError( f"object {type(obj)} does not match type annotations. Attribute {attr} should be of type {expected_type}, got {type(value)}" ) elif not isinstance(value, expected_type): raise TypeError( f"object {type(obj)} does not match type annotations. Attribute {attr} should be of type {expected_type}, got {type(value)}" ) return def print_dict(input: dict): out = '' for k, v in input.items(): out += f"{k} : {v}\n" print(out) return def casadi_length(x) -> int: return x.shape[0] def print_casadi_vector(x): for i in range(casadi_length(x)): print(x[i]) def casadi_vertcat_list(x): result = [] for el in x: result = ca.vertcat(result, el) return result def casadi_sum_list(input: list): result = input[0] for v in input[1:]: result += v return result def check_ipopt_success(status: str): if status in ['Solve_Succeeded', 'Solved_To_Acceptable_Level', 'Feasible_Point_Found', 'Search_Direction_Becomes_Too_Small']: return True else: return False # Note this is not generalized, it expects equivalent depth, greater than `layer` def flatten_layer(L: list, layer: int = 0): if layer == 0: # Check if already flat if any(isinstance(e, list) for e in L): return sum(L, []) else: return L else: return [flatten_layer(l, layer=layer - 1) for l in L] # Completely flattens the list def flatten(L): if isinstance(L, list): return [a for i in L for a in flatten(i)] else: return [L] def flatten_outer_layers(L: list, n_layers: int): for _ in range(n_layers): L = flatten_layer(L, 0) return L def increment_indices(L, inc): L_new = [] for e in L: if isinstance(e, int): L_new.append(e + inc) elif isinstance(e, list): L_new.append(increment_indices(e, inc)) else: raise ValueError('Not a nested list of integers') return L_new def create_empty_list_matrix(list_dims: tuple): return np.empty(list_dims + (0,), dtype=int).tolist() def get_cont_algebraic_indices(ind_alg: list): return [ind_rk[-1] for ind_fe in ind_alg for ind_rk in ind_fe]
3,174
26.850877
144
py
nosnoc_py
nosnoc_py-main/nosnoc/model.py
from typing import Optional, List import numpy as np import casadi as ca from nosnoc.nosnoc_opts import NosnocOpts from nosnoc.dims import NosnocDims from nosnoc.nosnoc_types import PssMode from nosnoc.utils import casadi_length, casadi_vertcat_list class NosnocModel: r""" \dot{x} \in f_i(x, u, p_time_var, p_global, v_global) if x(t) in R_i \subset \R^{n_x} with R_i = {x \in \R^{n_x} | diag(S_i,\dot) * c(x) > 0} where S_i denotes the rows of S. An alternate model can be used if your system cannot be defined as a Fillipov system. in that case user can provide an \alpha vector (analogous to the \alpha defined in the step reformulation) with the same size as c, along with the expression for \dot{x}. This alpha vector is then used as in the Step reformulation to do switch detection. \dot{x} = f_x(x,u,\alpha,p) :param x: state variables :param x0: initial state :param F: set of state equations for the different regions :param c: set of region boundaries :param S: determination of the boundaries region connecting different state equations with each boundary zone :param g_Stewart: List of stewart functions to define the regions (instead of S & c) :param u: controls :param z: user defined algebraic state variables :param z0: initial guess for user defined algebraic variables :param lbz: lower bounds on user algebraic variables :param ubz: upper bounds on user algebraic variables :param g_z: user defined algebraic constraints :param alpha: optionally provided alpha variables for general inclusions :param theta: optionally provided theta variables for stewart reformulation provided only if some functions are dependent on them. NOTE: EXPERIMENTAL :param f_x: optionally provided rhs used for general inclusions :param p_time_var: time varying parameters :param p_global: global parameters :param p_time_var_val: initial values of the time varying parameters (for each control stage) :param p_global_val: values of the global parameters :param v_global: additional timefree optimization variables :param t_var: time variable (for time freezing) :param name: name of the model """ # TODO: extend docu for n_sys > 1 # NOTE: n_sys is needed decoupled systems: see FESD: "Remark on Cartesian products of Filippov systems" # NOTE: theta is not meant to be used, def __init__(self, x: ca.SX, x0: Optional[np.ndarray], F: Optional[List[ca.SX]] = None, c: Optional[List[ca.SX]] = None, S: Optional[List[np.ndarray]] = None, g_Stewart: Optional[List[ca.SX]] = None, u: ca.SX = ca.SX.sym('u_dummy', 0, 1), z: ca.SX = ca.SX.sym('z_dummy', 0, 1), z0: Optional[np.ndarray] = None, lbz: Optional[np.ndarray] = None, ubz: Optional[np.ndarray] = None, alpha: Optional[List[ca.SX]] = None, theta: Optional[List[ca.SX]] = None, f_x: Optional[List[ca.SX]] = None, g_z: ca.SX = ca.SX.sym('g_z_dummy', 0, 1), p_time_var: ca.SX = ca.SX.sym('p_time_var_dummy', 0, 1), p_global: ca.SX = ca.SX.sym('p_global_dummy', 0, 1), p_time_var_val: Optional[np.ndarray] = None, p_global_val: np.ndarray = np.array([]), v_global: ca.SX = ca.SX.sym('v_global_dummy', 0, 1), t_var: Optional[ca.SX] = None, name: str = 'nosnoc'): self.x: ca.SX = x self.alpha: List[ca.SX] = alpha self.theta: List[ca.SX] = theta self.F: Optional[List[ca.SX]] = F self.f_x: List[ca.SX] = f_x self.g_z: ca.SX = g_z self.c: List[ca.SX] = c self.S: List[np.ndarray] = S self.g_Stewart = g_Stewart if not (bool(F is not None) ^ bool((f_x is not None) and (alpha is not None))): raise ValueError("Provide either F (Fillipov) or f_x and alpha") # Either c and S or g is given! if F is not None: if not (bool(c is not None and S is not None) ^ bool(g_Stewart is not None)): raise ValueError("Provide either c and S or g, not both!") self.x0: np.ndarray = x0 self.p_time_var: ca.SX = p_time_var self.p_global: ca.SX = p_global self.p_time_var_val: np.ndarray = p_time_var_val self.p_global_val: np.ndarray = p_global_val self.v_global = v_global self.u: ca.SX = u self.z: ca.SX = z self.t_var: ca.SX = t_var self.name: str = name self.z0 = z0 self.lbz = lbz self.ubz = ubz self.dims: NosnocDims = None def __repr__(self) -> str: out = '' for k, v in self.__dict__.items(): out += f"{k} : {v}\n" return out def preprocess_model(self, opts: NosnocOpts): # detect dimensions n_x = casadi_length(self.x) n_u = casadi_length(self.u) n_z = casadi_length(self.z) n_sys = len(self.F) if self.F is not None else len(self.f_x) if self.z0 is None: self.z0 = np.zeros((n_z,)) elif len(self.z0) != n_z: raise ValueError("z0 should be empty or of length n_z.") if self.lbz is None: self.lbz = -np.inf * np.ones((n_z,)) elif len(self.lbz) != n_z: raise ValueError("lbz should be empty or of length n_z.") if self.ubz is None: self.ubz = np.inf * np.ones((n_z,)) elif len(self.ubz) != n_z: raise ValueError("ubz should be empty or of length n_z.") if self.g_Stewart: n_c_sys = [0] # No c used! else: n_c_sys = [casadi_length(self.c[i]) for i in range(n_sys)] # sanity checks if self.F is not None: n_f_sys = [self.F[i].shape[1] for i in range(n_sys)] if not isinstance(self.F, list): raise ValueError("model.F should be a list.") for i, f in enumerate(self.F): if f.shape[1] == 1: raise Warning(f"model.F item {i} is not a switching system!") if self.g_Stewart: if opts.pss_mode != PssMode.STEWART: raise ValueError("model.g_Stewart is used and pss_mode should be STEWART") if not isinstance(self.g_Stewart, list): raise ValueError("model.g_Stewart should be a list.") for i, g_Stewart in enumerate(self.g_Stewart): if g_Stewart.shape[0] != self.F[i].shape[1]: raise ValueError(f"Dimensions g_Stewart and F for item {i} should be equal!") else: if not isinstance(self.c, list): raise ValueError("model.c should be a list.") if not isinstance(self.S, list): raise ValueError("model.S should be a list.") if len(self.c) != len(self.S): raise ValueError("model.c and model.S should have the same length!") for i, (fi, Si) in enumerate(zip(self.F, self.S)): if fi.shape[1] != Si.shape[0]: raise ValueError( f"model.F item {i} and S {i} should have the same number of columns") else: # Only check Step because Stewart is not allowed for general inclusions if opts.pss_mode == PssMode.STEWART: raise ValueError("model formulation with general inclusions using model.f_x is not supported with PssMode.STEWART") n_f_sys = [self.f_x[i].shape[1] for i in range(n_sys)] if not isinstance(self.c, list): raise ValueError("model.c should be a list.") if casadi_length(casadi_vertcat_list(self.c)) != casadi_length(casadi_vertcat_list(self.alpha)): raise ValueError("model.c and model.alpha should have the same length!") # parameters n_p_glob = casadi_length(self.p_global) if not self.p_global_val.shape == (n_p_glob,): raise Exception("dimension of p_global_val and p_global mismatch.", f"Expected shape ({n_p_glob},), got p_global_val.shape {self.p_global_val.shape}," f"p_global {self.p_global}, p_global_val {self.p_global_val}") n_p_time_var = casadi_length(self.p_time_var) if self.p_time_var_val is None: self.p_time_var_val = np.zeros((opts.N_stages, n_p_time_var)) if not self.p_time_var_val.shape == (opts.N_stages, n_p_time_var): raise Exception( "dimension of p_time_var_val and p_time_var mismatch.", f"Expected shape: ({opts.N_stages}, {n_p_time_var}), " f"got p_time_var_val.shape {self.p_time_var_val.shape}" f"p_time_var {self.p_time_var}, p_time_var_val {self.p_time_var_val}") # extend parameters for each stage n_p = n_p_time_var + n_p_glob self.p = ca.vertcat(self.p_time_var, self.p_global) self.p_ctrl_stages = [ca.SX.sym(f'p_stage{i}', n_p) for i in range(opts.N_stages)] self.p_val_ctrl_stages = np.zeros((opts.N_stages, n_p)) for i in range(opts.N_stages): self.p_val_ctrl_stages[i, :n_p_time_var] = self.p_time_var_val[i, :] self.p_val_ctrl_stages[i, n_p_time_var:] = self.p_global_val # initial guess z0 if opts.rootfinder_for_initial_z: g_z0_fun = ca.Function('g_z0_fun', [self.z, ca.vertcat(self.x, self.p)], [self.g_z]) self.z0_rootfinder = ca.rootfinder('z0_rootfinder', 'newton', g_z0_fun) # dimensions self.dims = NosnocDims(n_x=n_x, n_u=n_u, n_sys=n_sys, n_c_sys=n_c_sys, n_f_sys=n_f_sys, n_p_time_var=n_p_time_var, n_p_glob=n_p_glob, n_z=n_z) if opts.pss_mode == PssMode.STEWART: if self.g_Stewart: g_Stewart_list = self.g_Stewart else: g_Stewart_list = [-self.S[i] @ self.c[i] for i in range(n_sys)] g_Stewart = casadi_vertcat_list(g_Stewart_list) # create FESD variables theta, lam, mu, alpha, lambda_n, lambda_p = self.create_stage_vars(opts) if self.alpha is not None: alpha = self.alpha if self.theta is not None: theta = self.theta # setup upsilon upsilon = [] if opts.pss_mode == PssMode.STEP and self.F is not None: for ii in range(self.dims.n_sys): upsilon_temp = [] S_temp = self.S[ii] for j in range(len(S_temp)): upsilon_ij = 1 for k in range(len(S_temp[0, :])): # create multiafine term if S_temp[j, k] != 0: upsilon_ij *= (0.5 * (1 - S_temp[j, k]) + S_temp[j, k] * alpha[ii][k]) upsilon_temp = ca.vertcat(upsilon_temp, upsilon_ij) upsilon = ca.horzcat(upsilon, upsilon_temp) # start empty g_lift = ca.SX.zeros((0, 1)) g_switching = ca.SX.zeros((0, 1)) g_convex = ca.SX.zeros((0, 1)) # equation for the convex multiplers 1 = e' \theta lambda00_expr = ca.SX.zeros(0, 0) std_compl_res = ca.SX.zeros(1) # residual of standard complementarity # Note: this is the order of z used by FiniteElement z = ca.vertcat(casadi_vertcat_list(theta), casadi_vertcat_list(lam), casadi_vertcat_list(mu), casadi_vertcat_list(alpha), casadi_vertcat_list(lambda_n), casadi_vertcat_list(lambda_p), self.z) # Reformulate the Filippov ODE into a DCS if self.F is None: f_x = casadi_vertcat_list(self.f_x) z[0:sum(n_c_sys)] = casadi_vertcat_list(self.alpha) else: f_x = ca.SX.zeros((n_x, 1)) if opts.pss_mode == PssMode.STEWART: for ii in range(n_sys): f_x = f_x + self.F[ii] @ theta[ii] g_switching = ca.vertcat( g_switching, g_Stewart_list[ii] - lam[ii] + mu[ii]) g_convex = ca.vertcat(g_convex, ca.sum1(theta[ii]) - 1) std_compl_res += ca.fabs(lam[ii].T @ theta[ii]) lambda00_expr = ca.vertcat(lambda00_expr, g_Stewart_list[ii] - ca.mmin(g_Stewart_list[ii])) elif opts.pss_mode == PssMode.STEP: for ii in range(n_sys): if self.F is not None: f_x = f_x + self.F[ii] @ upsilon[:, ii] alpha_ii = alpha[ii] else: alpha_ii = self.alpha[ii] g_switching = ca.vertcat( g_switching, self.c[ii] - lambda_p[ii] + lambda_n[ii]) std_compl_res += ca.transpose(lambda_n[ii]) @ alpha_ii std_compl_res += ca.transpose(lambda_p[ii]) @ (np.ones(n_c_sys[ii]) - alpha_ii) lambda00_expr = ca.vertcat(lambda00_expr, -ca.fmin(self.c[ii], 0), ca.fmax(self.c[ii], 0)) # collect all algebraic equations g_z_all = ca.vertcat(g_switching, g_convex, g_lift, self.g_z) # g_lift_forces # CasADi functions for indicator and region constraint functions self.z_all = z # dynamics self.f_x_fun = ca.Function('f_x_fun', [self.x, z, self.u, self.p, self.v_global], [f_x]) # lp kkt conditions without bilinear complementarity terms self.g_z_switching_fun = ca.Function('g_z_switching_fun', [self.x, z, self.u, self.p], [g_switching]) self.g_z_all_fun = ca.Function('g_z_all_fun', [self.x, z, self.u, self.p], [g_z_all]) if self.t_var is not None: self.t_fun = ca.Function("t_fun", [self.x], [self.t_var]) elif opts.time_freezing: raise ValueError("Please provide t_var for time freezing!") self.lambda00_fun = ca.Function('lambda00_fun', [self.x, self.z, self.p], [lambda00_expr]) self.std_compl_res_fun = ca.Function('std_compl_res_fun', [z, self.p], [std_compl_res]) if opts.pss_mode == PssMode.STEWART: mu00_stewart = casadi_vertcat_list([ca.mmin(g_Stewart_list[ii]) for ii in range(n_sys)]) self.mu00_stewart_fun = ca.Function('mu00_stewart_fun', [self.x, self.p], [mu00_stewart]) self.g_Stewart_fun = ca.Function('g_Stewart_fun', [self.x, self.p], [g_Stewart]) def create_stage_vars(self, opts: NosnocOpts): """ Create the algebraic vars for a single stage. """ dims = self.dims # algebraic variables if opts.pss_mode == PssMode.STEWART: # add thetas theta = [ca.SX.sym('theta', dims.n_f_sys[ij]) for ij in range(dims.n_sys)] # add lambdas lam = [ca.SX.sym('lambda', dims.n_f_sys[ij]) for ij in range(dims.n_sys)] # add mu mu = [ca.SX.sym('mu', 1) for ij in range(dims.n_sys)] # unused alpha = [] lambda_n = [] lambda_p = [] elif opts.pss_mode == PssMode.STEP: # add alpha alpha = [ca.SX.sym('alpha', dims.n_c_sys[ij]) for ij in range(dims.n_sys)] # add lambda_n lambda_n = [ca.SX.sym('lambda_n', dims.n_c_sys[ij]) for ij in range(dims.n_sys)] # add lambda_p lambda_p = [ca.SX.sym('lambda_p', dims.n_c_sys[ij]) for ij in range(dims.n_sys)] # unused theta = [] lam = [] mu = [] return theta, lam, mu, alpha, lambda_n, lambda_p def add_smooth_step_representation(self, smoothing_parameter: float = 1e1): """ smoothing_parameter: larger -> smoother, smaller -> more exact """ if self.g_Stewart: raise NotImplementedError() if smoothing_parameter <= 0: raise ValueError("smoothing_parameter should be > 0") dims = self.dims # smooth step function y = ca.SX.sym('y') smooth_step_fun = ca.Function('smooth_step_fun', [y], [(ca.tanh(1 / smoothing_parameter * y) + 1) / 2]) lambda_smooth = [] g_Stewart_list = [-self.S[i] @ self.c[i] for i in range(dims.n_sys)] theta_list = [ca.SX.zeros(nf) for nf in dims.n_f_sys] mu_smooth_list = [] f_x_smooth = ca.SX.zeros((dims.n_x, 1)) for s in range(dims.n_sys): n_c: int = dims.n_c_sys[s] alpha_expr_s = casadi_vertcat_list([smooth_step_fun(self.c[s][i]) for i in range(n_c)]) min_in = ca.SX.sym('min_in', dims.n_f_sys[s]) min_out = ca.sum1(casadi_vertcat_list([min_in[i]*ca.exp(-1/smoothing_parameter * min_in[i]) for i in range(casadi_length(min_in))])) / \ ca.sum1(casadi_vertcat_list([ca.exp(-1/smoothing_parameter * min_in[i]) for i in range(casadi_length(min_in))])) smooth_min_fun = ca.Function('smooth_min_fun', [min_in], [min_out]) mu_smooth_list.append(-smooth_min_fun(g_Stewart_list[s])) lambda_smooth = ca.vertcat(lambda_smooth, g_Stewart_list[s] - smooth_min_fun(g_Stewart_list[s])) for i in range(dims.n_f_sys[s]): n_Ri = sum(np.abs(self.S[s][i, :])) theta_list[s][i] = 2**(n_c - n_Ri) for j in range(n_c): theta_list[s][i] *= ((1 - self.S[s][i, j]) / 2 + self.S[s][i, j] * alpha_expr_s[j]) f_x_smooth += self.F[s] @ theta_list[s] theta_smooth = casadi_vertcat_list(theta_list) mu_smooth = casadi_vertcat_list(mu_smooth_list) self.f_x_smooth_fun = ca.Function('f_x_smooth_fun', [self.x], [f_x_smooth]) self.theta_smooth_fun = ca.Function('theta_smooth_fun', [self.x, self.p], [theta_smooth]) self.mu_smooth_fun = ca.Function('mu_smooth_fun', [self.x, self.p], [mu_smooth]) self.lambda_smooth_fun = ca.Function('lambda_smooth_fun', [self.x, self.p], [lambda_smooth]) def compute_lambda00(self, opts: NosnocOpts): x0 = self.x0 p0 = self.p_val_ctrl_stages[0] if opts.rootfinder_for_initial_z: z0 = self.z0_rootfinder(self.z0, np.concatenate((self.x0, p0))).full().flatten() else: z0 = self.z0 return self.lambda00_fun(x0, z0, p0).full().flatten()
19,241
45.033493
148
py
nosnoc_py
nosnoc_py-main/nosnoc/auto_model.py
import casadi as ca import numpy as np from itertools import product from collections import defaultdict from typing import List from nosnoc.utils import casadi_vertcat_list, casadi_sum_list from nosnoc.model import NosnocModel class NosnocAutoModel: r""" An interface to automatically generate a NosnocModel given: - x: symbolic state vector - f_nonsmooth_ode: symbolic vector field of the nonsmooth ODE Outputs the switching functions c as well as either: - F: Filippov inclusion functions - S: Switching matrix or: - alpha: Step reformulation multipliers used in the general inclusions expert mode. - f: x dot provided for general inclusions expert mode. Calling reformulate will return a NosnocModel object Currently supported nonsmooth functions: - :math: `\mathrm{sign}(\cdot)` - :math: `\mathrm{max}(\cdot, \cdot)` - :math: `\mathrm{min}(\cdot, \cdot)` - TODO: more nonsmooth functions! In particular figure out a way to handle if_else (ca.OP_IF_ELSE_ZERO) """ def __init__(self, x: ca.SX, x0: np.ndarray, u: ca.SX, f_nonsmooth_ode: ca.SX): self.x = x self.x0 = x0 self.u = u self.f_nonsmooth_ode = f_nonsmooth_ode self.c = [] self.S = [] self.F = [] self.f = [] self.alpha = [] def reformulate(self) -> NosnocModel: """ Reformulate the given nonsmooth ODE into a NosnocModel. Note: It care must be taken if your model is complex, in which case the Pss Mode `STEP` should be used. """ if self._detect_additive(): self._reformulate_nonlin() return NosnocModel(x=self.x, f_x=[self.f], c=self.c, alpha=[casadi_vertcat_list(self.alpha)], x0=self.x0, u=self.u) else: self._reformulate_linear() return NosnocModel(x=self.x, F=self.F, c=self.c, S=self.S, x0=self.x0, u=self.u) def _reformulate_linear(self): # TODO actually implement linear reformulation fs_nonsmooth = ca.vertsplit(self.f_nonsmooth_ode) nsm = [] sm = [] for f_nonsmooth in fs_nonsmooth: nonlin_components = self._find_nonlinear_components(f_nonsmooth) smooth_components = [] nonsmooth_components = [] for nonlin_component in nonlin_components: smooth = self._check_smooth(nonlin_component) if smooth: smooth_components.append(nonlin_component) else: nonsmooth_components.append(nonlin_component) nsm.append(nonsmooth_components) sm.append(smooth_components) # each smooth component is part of the common dynamics this is added to the first element f_common = casadi_vertcat_list([casadi_sum_list(f) for f in sm]) # Extract all the Additive components and categorize them by switching function collated_components = [] for components in nsm: collated = defaultdict(list) for component in components: f, c, S = self._rebuild_additive_component(component) collated[c.str()].append((f, c, S)) collated_components.append(collated) all_c = set().union(*[component.keys() for component in collated_components]) # Build the set of switching function and S pairs, along with the stacked vector of c -> f maps cS_map = {} fs = [] for ii, collated in enumerate(collated_components): f_i = defaultdict(lambda: ca.SX.zeros(1, 2)) for c_str in all_c: comps = collated[c_str] f_ij = [ca.SX(0), ca.SX(0)] for f, c, S in comps: cS_map[c] = S f_ij[0] += f[0] f_ij[1] += f[1] f_i[c_str] = ca.horzcat(*f_ij) fs.append(f_i) for c, S in cS_map.items(): self.F.append(casadi_vertcat_list([f_i[c.str()] for f_i in fs])) self.c.append(c) self.S.append(S) self.F[0][:, 0] += f_common self.F[0][:, 1] += f_common def _reformulate_nonlin(self): fs_nonsmooth = ca.vertsplit(self.f_nonsmooth_ode) fs = [self._rebuild_nonlin(f_nonsmooth) for f_nonsmooth in fs_nonsmooth] self.f = ca.vertcat(*fs) def _detect_additive(self): fs_nonsmooth = ca.vertsplit(self.f_nonsmooth_ode) for f_nonsmooth in fs_nonsmooth: nonlin_components = self._find_nonlinear_components(f_nonsmooth) for component in nonlin_components: additive = self._check_additive(component) if additive: return True return False # TODO type output def _rebuild_additive_component(self, node: ca.SX): if node.n_dep() == 0: # elementary variable return [node], None, None elif node.n_dep() == 1: # unary operator if node.is_op(ca.OP_SIGN): return [ca.SX(1), ca.SX(-1)], node.dep(0), np.array([[1], [-1]]) else: # In this case do nothing children, c, S = self._rebuild_additive_component(node.dep(0)) return [ca.SX.unary(node.op(), child) for child in children], c, S else: if node.is_op(ca.OP_FMAX): return [node.dep(0), node.dep(1)], node.dep(0)-node.dep(1), np.array([[1], [-1]]) elif node.is_op(ca.OP_FMIN): return [node.dep(0), node.dep(1)], node.dep(0)-node.dep(1), np.array([[-1], [1]]), node.dep(0)-node.dep(1), np.array([[-1], [1]]) else: # binary operator l_children, l_c, l_S = self._rebuild_additive_component(node.dep(0)) r_children, r_c, r_S = self._rebuild_additive_component(node.dep(1)) c = l_c if l_c is not None else r_c S = l_S if l_S is not None else r_S return [ca.SX.binary(node.op(), lc, rc) for lc, rc in product(l_children, r_children)], c, S def _rebuild_nonlin(self, node: ca.SX): if node.n_dep() == 0: # elementary variable return node elif node.n_dep() == 1: # unary operator if node.is_op(ca.OP_SIGN): # TODO need to process multiple layers, i.e. a nonsmooth function of nonsmooth inputs. Not handled for now # but may be useful to detect at least. # get c and alpha for this nonsmoothness alpha, fresh = self._find_matching_expr_nonlin(node.dep(0)) if fresh: self.c.append(node.dep(0)) self.alpha.append(alpha) # calculate the equivalent expression for this node eq_expr = 2*alpha - 1 return eq_expr else: # In this case do nothing child = self._rebuild_nonlin(node.dep(0)) return ca.SX.unary(node.op(), child) # TODO: add more switching functions else: if node.is_op(ca.OP_FMAX): # get c and alpha for this nonsmoothness alpha, fresh = self._find_matching_expr_nonlin(node.dep(0)-node.dep(1)) if fresh: self.c.append(node.dep(0)-node.dep(1)) self.alpha.append(alpha) # calculate the equivalent expression for this node eq_expr = alpha*node.dep(0) + (1-alpha)*node.dep(1) return eq_expr elif node.is_op(ca.OP_FMIN): # get c and alpha for this nonsmoothness alpha, fresh = self._find_matching_expr_nonlin(node.dep(0)-node.dep(1)) if fresh: self.c.append(node.dep(0)-node.dep(1)) self.alpha.append(alpha) # calculate the equivalent expression for this node eq_expr = (1-alpha)*node.dep(0) + alpha*node.dep(1) return eq_expr else: # binary operator l_child = self._rebuild_nonlin(node.dep(0)) r_child = self._rebuild_nonlin(node.dep(1)) return ca.SX.binary(node.op(), l_child, r_child) def _find_matching_expr_nonlin(self, expr: ca.SX): found_c = None found_alpha = None # TODO: implement actual routine to find corresponding c if found_c is not None: return found_alpha, False else: # create a fresh alpha return ca.SX.sym(f'alpha_{len(self.alpha)}'), True def _check_additive(self, node: ca.SX) -> bool: if node.n_dep() == 1: # If negated go down one level if node.is_op(ca.OP_NEG): return self._check_additive(node.dep(0)) elif node.is_op(ca.OP_SIGN): return True else: # If min or max. Then we are additive. if node.is_op(ca.OP_FMIN): return True elif node.is_op(ca.OP_FMAX): return True # If multiply figure out which one is nonsmooth and check the other one for smoothness elif node.is_op(ca.OP_MUL): if node.dep(0).is_op(ca.OP_SIGN) or node.dep(0).is_op(ca.OP_FMAX) or node.dep(0).is_op(ca.OP_FMIN): return self._check_smooth(node.dep(1)) elif node.dep(1).is_op(ca.OP_SIGN) or node.dep(1).is_op(ca.OP_FMAX) or node.dep(1).is_op(ca.OP_FMIN): return self._check_smooth(node.dep(0)) else: return False # NOTE: This is not a sufficient condition to say this doesn't work but for now this is ok. else: return False # NOTE: This is not a sufficient condition to say this doesn't work but for now this is ok. pass def _check_smooth(self, node: ca.SX) -> bool: if node.n_dep() == 0: return True elif node.n_dep() == 1: if node.is_op(ca.OP_SIGN): return False else: smooth = self._check_smooth(node.dep(0)) return smooth else: if node.is_op(ca.OP_FMAX): return False elif node.is_op(ca.OP_FMIN): return False else: l_smooth = self._check_smooth(node.dep(0)) r_smooth = self._check_smooth(node.dep(1)) return l_smooth and r_smooth def _find_nonlinear_components(self, node: ca.SX) -> List[ca.SX]: if node.n_dep() == 0: return [node] elif node.n_dep() == 1: if node.is_op(ca.OP_NEG): # Note this is not used for rebuild so we dont care about polarity of components return [node.unary(ca.OP_NEG, component) for component in self._find_nonlinear_components(node.dep(0))] else: # TODO: are there any other linear unary operators? return [node] else: if node.is_op(ca.OP_ADD): return self._find_nonlinear_components(node.dep(0)) + self._find_nonlinear_components(node.dep(1)) elif node.is_op(ca.OP_SUB): return self._find_nonlinear_components(node.dep(0)) + [node.unary(ca.OP_NEG, component) for component in self._find_nonlinear_components(node.dep(1))] else: return [node]
11,669
41.904412
166
py
nosnoc_py
nosnoc_py-main/nosnoc/dims.py
from dataclasses import dataclass @dataclass class NosnocDims: """ detected automatically """ n_x: int n_u: int n_z: int n_sys: int n_p_time_var: int n_p_glob: int n_c_sys: list n_f_sys: list
238
13.058824
33
py
nosnoc_py
nosnoc_py-main/nosnoc/ocp.py
from typing import Optional from warnings import warn import numpy as np import casadi as ca from nosnoc.utils import casadi_length from nosnoc.model import NosnocModel from nosnoc.dims import NosnocDims class NosnocOcp: """ allows to specify 1) constraints of the form: lbu <= u <= ubu lbx <= x <= ubx lbv_global <= v_global <= ubv_global g_terminal(x_terminal) = 0 g_path_comp(x) 2) cost of the form: f_q(x, u) -- integrated over the time horizon + f_terminal(x_terminal) -- evaluated at the end """ def __init__( self, lbu: Optional[np.ndarray] = None, ubu: Optional[np.ndarray] = None, u_guess: Optional[np.ndarray] = None, lbx: Optional[np.ndarray] = None, ubx: Optional[np.ndarray] = None, f_q: ca.SX = ca.SX.zeros(1), g_path: ca.SX = ca.SX.zeros(0), lbg: Optional[np.ndarray] = None, ubg: Optional[np.ndarray] = None, g_path_comp: ca.SX = ca.SX.zeros(0, 2), f_terminal: ca.SX = ca.SX.zeros(1), g_terminal: ca.SX = ca.SX.zeros(0), lbv_global: Optional[np.ndarray] = None, ubv_global: Optional[np.ndarray] = None, v_global_guess: Optional[np.ndarray] = None, ): # TODO: Make everything more pythonic via optionals instead of empty arrays self.lbu: Optional[np.ndarray] = lbu self.ubu: Optional[np.ndarray] = ubu self.u_guess: Optional[np.ndarray] = u_guess self.lbx: np.ndarray = lbx self.ubx: np.ndarray = ubx self.f_q: ca.SX = f_q self.g_path: ca.SX = g_path self.lbg: np.ndarray = lbg self.ubg: np.ndarray = ubg self.g_path_comp: ca.SX = g_path_comp self.f_terminal: ca.SX = f_terminal self.g_terminal: ca.SX = g_terminal self.lbv_global: np.ndarray = lbv_global self.ubv_global: np.ndarray = ubv_global self.v_global_guess: np.ndarray = v_global_guess def preprocess_ocp(self, model: NosnocModel): dims: NosnocDims = model.dims self.g_terminal_fun = ca.Function('g_terminal_fun', [model.x, model.p, model.v_global], [self.g_terminal]) self.f_q_T_fun = ca.Function('f_q_T_fun', [model.x, model.p, model.v_global], [self.f_terminal]) self.f_q_fun = ca.Function('f_q_fun', [model.x, model.u, model.p, model.v_global], [self.f_q]) self.g_path_fun = ca.Function('g_path_fun', [model.x, model.u, model.p, model.v_global], [self.g_path]) # path complementarities if self.g_path_comp.shape[1] != 2: raise ValueError("path complementarities should be width 2") if self.g_path_comp.shape[0] != 0: warn("OCP: using path complementarities. Note that all expressions a, b need to be bound as 0 <= a, 0 <= b. This is not yet done automatically.") # Process complementarities into 3 categories: # rk_stage, ctrl_stage, global self.g_global_comp = ca.SX.zeros(0, 2) self.g_ctrl_comp = ca.SX.zeros(0, 2) self.g_stage_comp = ca.SX.zeros(0, 2) rk_stage_vars = ca.vertcat(model.x, model.z) control_stage_vars = ca.vertcat(model.u, model.p_time_var) for ii in range(self.g_path_comp.shape[0]): expr = self.g_path_comp[ii, :] if any(ca.which_depends(expr, rk_stage_vars)): self.g_stage_comp = ca.vertcat(self.g_stage_comp, expr) elif any(ca.which_depends(expr, control_stage_vars)): self.g_ctrl_comp = ca.vertcat(self.g_ctrl_comp, expr) else: self.g_global_comp = ca.vertcat(self.g_global_comp, expr) self.g_global_comp_fun = ca.Function('g_global_comp_fun', [model.p_global, model.v_global], [self.g_global_comp]) self.g_ctrl_comp_fun = ca.Function('g_ctrl_comp_fun', [model.u, model.p, model.v_global], [self.g_ctrl_comp]) self.g_rk_comp_fun = ca.Function('g_rk_comp_fun', [model.x, model.u, model.z_all, model.p, model.v_global], [self.g_stage_comp]) # path constraints n_g_path = casadi_length(self.g_path) if self.lbg is None: self.lbg = np.zeros((n_g_path,)) elif len(self.lbg) != n_g_path: raise ValueError("lbg and g_path have inconsistent shapes.") if self.ubg is None: self.ubg = np.zeros((n_g_path,)) elif len(self.ubg) != n_g_path: raise ValueError("ubg and g_path have inconsistent shapes") # box constraints if self.lbx is None: self.lbx = -np.inf * np.ones((dims.n_x,)) elif len(self.lbx) != dims.n_x: raise ValueError("lbx should be empty or of length n_x.") if self.ubx is None: self.ubx = np.inf * np.ones((dims.n_x,)) elif len(self.ubx) != dims.n_x: raise ValueError("ubx should be empty or of length n_x.") # box constraints for u if self.lbu is None: self.lbu = -np.inf * np.ones((dims.n_u,)) elif len(self.lbu) != dims.n_u: raise ValueError("lbu should be empty or of length n_u.") if self.ubu is None: self.ubu = np.inf * np.ones((dims.n_u,)) elif len(self.ubu) != dims.n_u: raise ValueError("ubu should be empty or of length n_u.") if self.u_guess is None: self.u_guess = np.zeros((dims.n_u,)) elif len(self.u_guess) != dims.n_u: raise ValueError("u_guess should be empty or of length n_u.") # global variables n_v_global = casadi_length(model.v_global) if self.lbv_global is None: self.lbv_global = -np.inf * np.ones((n_v_global,)) if self.lbv_global.shape != (n_v_global,): raise Exception("lbv_global and v_global have inconsistent shapes.") if self.ubv_global is None: self.ubv_global = np.inf * np.ones((n_v_global,)) if self.ubv_global.shape != (n_v_global,): raise Exception("ubv_global and v_global have inconsistent shapes.") if self.v_global_guess is None: self.v_global_guess = np.zeros((n_v_global,)) if self.v_global_guess.shape != (n_v_global,): raise Exception("v_global_guess and v_global have inconsistent shapes.")
6,568
41.934641
157
py
nosnoc_py
nosnoc_py-main/nosnoc/__init__.py
from .auto_model import NosnocAutoModel from .solver import NosnocSolver, get_results_from_primal_vector from .problem import NosnocProblem from .model import NosnocModel from .ocp import NosnocOcp from .nosnoc_opts import NosnocOpts from .nosnoc_types import MpccMode, IrkSchemes, StepEquilibrationMode, CrossComplementarityMode, IrkRepresentation, PssMode, IrkRepresentation, HomotopyUpdateRule, InitializationStrategy, ConstraintHandling, Status from .helpers import NosnocSimLooper from .utils import casadi_length, casadi_vertcat_list, print_casadi_vector, flatten_layer, make_object_json_dumpable from .plot_utils import plot_timings, plot_iterates, latexify_plot from .rk_utils import rk4 import warnings warnings.simplefilter("always")
745
48.733333
214
py
nosnoc_py
nosnoc_py-main/nosnoc/nosnoc_types.py
from enum import Enum, auto class MpccMode(Enum): """ MpccMode determines how complementarities w_1^T w_2 =0 are handled MPCC (Mathematical Program with Complementarity Constraints) `SCHOLTES_EQ`: w_1^T w_2 - sigma == 0 `SCHOLTES_INEQ`: w_1^T w_2 - sigma <= 0 `ELASTIC*`: - a bounded slack variable s_elastic is introduced. - bounds for s_elastic: [opts.s_elastic_min, opts.s_elastic_max] - s_elastic is initialized by opts.s_elastic_0 `ELASTIC_INEQ`: w_1^T w_2 - s_elastic * np.ones((n, 1)) < 0 `ELASTIC_EQ`: w_1^T w_2 - s_elastic * np.ones((n, 1)) == 0 `ELASTIC_TWO_SIDED`: w_1^T w_2 - s_elastic * np.ones((n, 1)) <= 0 w_1^T w_2 + s_elastic * np.ones((n, 1)) >= 0 """ SCHOLTES_INEQ = auto() SCHOLTES_EQ = auto() FISCHER_BURMEISTER = auto() FISCHER_BURMEISTER_IP_AUG = auto() ELASTIC_INEQ = auto() ELASTIC_EQ = auto() ELASTIC_TWO_SIDED = auto() # KANZOW_SCHWARTZ = auto() # NOSNOC: 'scholtes_ineq' (3), 'scholtes_eq' (2) # NOTE: tested in simple_sim_tests class IrkSchemes(Enum): RADAU_IIA = auto() GAUSS_LEGENDRE = auto() # NOTE: tested in simple_sim_tests class InitializationStrategy(Enum): ALL_XCURRENT_W0_START = auto() ALL_XCURRENT_WOPT_PREV = auto() EXTERNAL = auto() # let user do from outside RK4_SMOOTHENED = auto() # experimental # Other ideas # OLD_SOLUTION = auto() # lp_initialization class StepEquilibrationMode(Enum): HEURISTIC_MEAN = auto() HEURISTIC_DELTA = auto() L2_RELAXED_SCALED = auto() L2_RELAXED = auto() DIRECT = auto() DIRECT_COMPLEMENTARITY = auto() HEURISTIC_DELTA_H_COMP = auto() # NOTE: tested in test_ocp_motor class CrossComplementarityMode(Enum): COMPLEMENT_ALL_STAGE_VALUES_WITH_EACH_OTHER = auto() # nosnoc 1 SUM_LAMBDAS_COMPLEMENT_WITH_EVERY_THETA = auto() # nosnoc 3 # NOTE: tested in simple_sim_tests class IrkRepresentation(Enum): INTEGRAL = auto() DIFFERENTIAL = auto() DIFFERENTIAL_LIFT_X = auto() # NOTE: tested in test_ocp class HomotopyUpdateRule(Enum): LINEAR = auto() SUPERLINEAR = auto() class ConstraintHandling(Enum): EXACT = auto() LEAST_SQUARES = auto() class PssMode(Enum): """ Mode to represent the Piecewise Smooth System (PSS). """ # NOTE: tested in simple_sim_tests, test_ocp_motor STEWART = auto() """ Stewart representaion basic algebraic equations and complementarity condtions of the DCS lambda_i'*theta_i = 0; for all i = 1,..., n_sys lambda_i >= 0; for all i = 1,..., n_sys theta_i >= 0; for all i = 1,..., n_sys """ STEP = auto() """ Step representaion c_i(x) - (lambda_p_i-lambda_n_i) = 0; for all i = 1,..., n_sys lambda_n_i'*alpha_i = 0; for all i = 1,..., n_sys lambda_p_i'*(e-alpha_i) = 0; for all i = 1,..., n_sys lambda_n_i >= 0; for all i = 1,..., n_sys lambda_p_i >= 0; for all i = 1,..., n_sys alpha_i >= 0; for all i = 1,..., n_sys """ class Status(Enum): SUCCESS = auto() INFEASIBLE = auto()
3,151
26.408696
70
py
nosnoc_py
nosnoc_py-main/nosnoc/solver.py
from abc import ABC, abstractmethod from typing import Optional import casadi as ca import numpy as np import time from nosnoc.model import NosnocModel from nosnoc.nosnoc_opts import NosnocOpts from nosnoc.nosnoc_types import InitializationStrategy, PssMode, HomotopyUpdateRule, ConstraintHandling, Status from nosnoc.ocp import NosnocOcp from nosnoc.problem import NosnocProblem from nosnoc.rk_utils import rk4_on_timegrid from nosnoc.utils import flatten_layer, flatten, get_cont_algebraic_indices, flatten_outer_layers, check_ipopt_success class NosnocSolverBase(ABC): @abstractmethod def __init__(self, opts: NosnocOpts, model: NosnocModel, ocp: Optional[NosnocOcp] = None) -> None: # preprocess inputs opts.preprocess() model.preprocess_model(opts) if opts.initialization_strategy == InitializationStrategy.RK4_SMOOTHENED: model.add_smooth_step_representation(smoothing_parameter=opts.smoothing_parameter) # store references self.model = model self.ocp = ocp self.opts = opts # create problem problem = NosnocProblem(opts, model, ocp) self.problem: NosnocProblem = problem return def set(self, field: str, value: np.ndarray) -> None: """ Set values. :param field: in ["x0", "x", "u", "p_global", "p_time_var", "w"] :param value: np.ndarray: numerical value of appropriate size """ prob = self.problem dims = prob.model.dims if field == 'x0': prob.model.x0 = value elif field == 'x': # TODO: check other dimensions for useful error message if value.shape[0] == self.opts.N_stages: # Shape is equal to the number of control stages for i, sub_idx in enumerate(prob.ind_x): for ssub_idx in sub_idx: for sssub_idx in ssub_idx: prob.w0[sssub_idx] = value[i, :] elif value.shape[0] == sum(self.opts.Nfe_list): # Shape is equal to the number of finite elements i = 0 for sub_idx in prob.ind_x: for ssub_idx in sub_idx: for sssub_idx in ssub_idx: prob.w0[sssub_idx] = value[i, :] i += 1 else: raise ValueError("value should have shape matching N_stages " f"({self.opts.N_stages}) or sum(Nfe_list) " f"({sum(self.opts.Nfe_list)}), shape: {value.shape[0]}") if self.opts.initialization_strategy is not InitializationStrategy.EXTERNAL: raise Warning( 'initialization of x might be overwritten due to InitializationStrategy != EXTERNAL.' ) elif field == 'u': prob.w0[np.array(prob.ind_u)] = value elif field == 'v_global': prob.w0[np.array(prob.ind_v_global)] = value elif field == 'p_global': for i in range(self.opts.N_stages): self.model.p_val_ctrl_stages[i, dims.n_p_time_var:] = value elif field == 'p_time_var': for i in range(self.opts.N_stages): self.model.p_val_ctrl_stages[i, :dims.n_p_time_var] = value[i, :] elif field == 'w': prob.w0 = value if self.opts.initialization_strategy is not InitializationStrategy.EXTERNAL: raise Warning( 'full initialization w might be overwritten due to InitializationStrategy != EXTERNAL.' ) else: raise NotImplementedError() def print_problem(self) -> None: self.problem.print() return def initialize(self) -> None: opts = self.opts prob = self.problem x0 = prob.model.x0 self.compute_lambda00() if opts.initialization_strategy in [ InitializationStrategy.ALL_XCURRENT_W0_START, InitializationStrategy.ALL_XCURRENT_WOPT_PREV ]: for ind in prob.ind_x: prob.w0[np.array(ind)] = x0 elif opts.initialization_strategy == InitializationStrategy.EXTERNAL: pass # This is experimental elif opts.initialization_strategy == InitializationStrategy.RK4_SMOOTHENED: # print(f"updating w0 with RK4 smoothened") # NOTE: assume N_stages = 1 and STEWART dt_fe = opts.terminal_time / (opts.N_stages * opts.N_finite_elements) irk_time_grid = np.array( [opts.irk_time_points[0]] + [opts.irk_time_points[k] - opts.irk_time_points[k - 1] for k in range(1, opts.n_s)]) rk4_t_grid = dt_fe * irk_time_grid x_rk4_current = x0 db_updated_indices = list() for i in range(opts.N_finite_elements): Xrk4 = rk4_on_timegrid(self.model.f_x_smooth_fun, x0=x_rk4_current, t_grid=rk4_t_grid) x_rk4_current = Xrk4[-1] # print(f"{Xrk4=}") for k in range(opts.n_s): x_ki = Xrk4[k + 1] prob.w0[prob.ind_x[0][i][k]] = x_ki # NOTE: we don't use lambda_smooth_fun, since it gives negative lambdas # -> infeasible. Possibly another smooth min fun could be used. # However, this would be inconsistent with mu. p_0 = self.model.p_val_ctrl_stages[0] # NOTE: z not supported! lam_ki = self.model.lambda00_fun(x_ki, [], p_0) mu_ki = self.model.mu_smooth_fun(x_ki, p_0) theta_ki = self.model.theta_smooth_fun(x_ki, p_0) # print(f"{x_ki=}") # print(f"theta_ki = {list(theta_ki.full())}") # print(f"mu_ki = {list(mu_ki.full())}") # print(f"lam_ki = {list(lam_ki.full())}\n") for s in range(self.model.dims.n_sys): ind_theta_s = range(sum(self.model.dims.n_f_sys[:s]), sum(self.model.dims.n_f_sys[:s + 1])) prob.w0[prob.ind_theta[0][i][k][s]] = theta_ki[ind_theta_s].full().flatten() prob.w0[prob.ind_lam[0][i][k][s]] = lam_ki[ind_theta_s].full().flatten() prob.w0[prob.ind_mu[0][i][k][s]] = mu_ki[s].full().flatten() # TODO: ind_v db_updated_indices += prob.ind_theta[0][i][k][s] + prob.ind_lam[0][i][k][ s] + prob.ind_mu[0][i][k][s] + prob.ind_x[0][i][k] + prob.ind_h if opts.irk_time_points[-1] != 1.0: raise NotImplementedError else: # Xk_end prob.w0[prob.ind_x[0][i][-1]] = x_ki db_updated_indices += prob.ind_x[0][i][-1] # print("w0 after RK4 init:") # print(prob.w0) missing_indices = sorted(set(range(len(prob.w0))) - set(db_updated_indices)) # print(f"{missing_indices=}") return def _print_iter_stats(self, sigma_k, complementarity_residual, nlp_res, cost_val, cpu_time_nlp, nlp_iter, status): print(f'{sigma_k:.1e} \t {complementarity_residual:.2e} \t {nlp_res:.2e}' + f'\t {cost_val:.2e} \t {cpu_time_nlp:3f} \t {nlp_iter} \t {status}') def homotopy_sigma_update(self, sigma_k): opts = self.opts if opts.homotopy_update_rule == HomotopyUpdateRule.LINEAR: return opts.homotopy_update_slope * sigma_k elif opts.homotopy_update_rule == HomotopyUpdateRule.SUPERLINEAR: return max(opts.sigma_N, min(opts.homotopy_update_slope * sigma_k, sigma_k**opts.homotopy_update_exponent)) def compute_lambda00(self) -> None: self.lambda00 = self.problem.model.compute_lambda00(self.opts) return def setup_p_val(self, sigma, tau) -> None: model: NosnocModel = self.problem.model self.p_val = np.concatenate( (model.p_val_ctrl_stages.flatten(), np.array([sigma, tau]), self.lambda00, model.x0)) return def polish_solution(self, casadi_ipopt_solver, w_guess): opts = self.opts prob = self.problem eps_sigma = 1e1 * opts.comp_tol ind_set = flatten(prob.ind_lam + prob.ind_lambda_n + prob.ind_lambda_p + prob.ind_alpha + prob.ind_theta + prob.ind_mu) ind_dont_set = flatten(prob.ind_h + prob.ind_u + prob.ind_x + prob.ind_v_global + prob.ind_v + prob.ind_z + prob.ind_elastic) # sanity check ind_all = ind_set + ind_dont_set for iw in range(len(w_guess)): if iw not in ind_all: raise Exception(f"w[{iw}] = {prob.w[iw]} not handled proprerly") w_fix_zero = w_guess < eps_sigma w_fix_zero[ind_dont_set] = False ind_fix_zero = np.where(w_fix_zero)[0].tolist() w_fix_one = np.abs(w_guess - 1.0) < eps_sigma w_fix_one[ind_dont_set] = False ind_fix_one = np.where(w_fix_one)[0].tolist() lbw = prob.lbw.copy() ubw = prob.ubw.copy() lbw[ind_fix_zero] = 0.0 ubw[ind_fix_zero] = 0.0 lbw[ind_fix_one] = 1.0 ubw[ind_fix_one] = 1.0 # fix some variables if opts.print_level: print( f"polishing step: setting {len(ind_fix_zero)} variables to 0.0, {len(ind_fix_one)} to 1.0." ) for i_ctrl in range(opts.N_stages): for i_fe in range(opts.Nfe_list[i_ctrl]): w_guess[prob.ind_theta[i_ctrl][i_fe][:]] sigma_k, tau_val = 0.0, 0.0 self.setup_p_val(sigma_k, tau_val) # solve NLP t = time.time() sol = casadi_ipopt_solver(x0=w_guess, lbg=prob.lbg, ubg=prob.ubg, lbx=lbw, ubx=ubw, p=self.p_val) cpu_time_nlp = time.time() - t # print and process solution solver_stats = casadi_ipopt_solver.stats() status = solver_stats['return_status'] nlp_iter = solver_stats['iter_count'] nlp_res = ca.norm_inf(sol['g']).full()[0][0] cost_val = ca.norm_inf(sol['f']).full()[0][0] w_opt = sol['x'].full().flatten() complementarity_residual = prob.comp_res(w_opt, self.p_val).full()[0][0] if opts.print_level: self._print_iter_stats(sigma_k, complementarity_residual, nlp_res, cost_val, cpu_time_nlp, nlp_iter, status) if status not in ['Solve_Succeeded', 'Solved_To_Acceptable_Level']: print(f"Warning: IPOPT exited with status {status}") return w_opt, cpu_time_nlp, nlp_iter, status def create_function_calculate_vector_field(self, sigma, p=[], v=[]): """Create a function to calculate the vector field.""" if self.opts.pss_mode != PssMode.STEWART: raise NotImplementedError() shape = self.model.g_Stewart_fun.size_out(0) g = ca.SX.sym('g', shape[0]) mu = ca.SX.sym('mu', 1) theta = ca.SX.sym('theta', shape[0]) lam = g - mu * np.ones(shape) theta_fun = ca.rootfinder("lambda_fun", "newton", dict( x=ca.vertcat(theta, mu), p=g, g=ca.vertcat( ca.sqrt(lam * lam - theta*theta + sigma*sigma) - (lam + theta), ca.sum1(theta)-1 ) )) def fun(x, u): g = self.model.g_Stewart_fun(x, p) theta = theta_fun(0, g)[:-1] F = self.model.F_fun(x, u, p, v) return np.dot(F, theta) return fun class NosnocSolver(NosnocSolverBase): """ Main solver class which solves the nonsmooth problem by applying a homotopy and solving the NLP subproblems using IPOPT. The nonsmooth problem is formulated internally based on the given options, dynamic model, and (optionally) the ocp data. """ def __init__(self, opts: NosnocOpts, model: NosnocModel, ocp: Optional[NosnocOcp] = None): """Constructor. """ super().__init__(opts, model, ocp) # create NLP Solver try: casadi_nlp = { 'f': self.problem.cost, 'x': self.problem.w, 'g': self.problem.g, 'p': self.problem.p } self.solver = ca.nlpsol(model.name, 'ipopt', casadi_nlp, opts.opts_casadi_nlp) except Exception as err: self.print_problem() print(f"{opts=}") print("\nerror creating solver for problem above.") raise err def solve(self) -> dict: """ Solves the NLP with the currently stored parameters. :return: Returns a dictionary containing ... TODO document all fields """ opts = self.opts prob = self.problem # initialize self.initialize() w0 = prob.w0.copy() w_all = [w0.copy()] n_iter_polish = opts.max_iter_homotopy + (1 if opts.do_polishing_step else 0) complementarity_stats = n_iter_polish * [None] cpu_time_nlp = n_iter_polish * [None] nlp_iter = n_iter_polish * [None] if opts.print_level: print('-------------------------------------------') print('sigma \t\t compl_res \t nlp_res \t cost_val \t CPU time \t iter \t status') sigma_k = opts.sigma_0 if opts.fix_active_set_fe0 and opts.pss_mode == PssMode.STEWART: lbw = prob.lbw.copy() ubw = prob.ubw.copy() # lambda00 != 0.0 -> corresponding thetas on first fe are zero I_active_lam = np.where(self.lambda00 > 1e1*opts.comp_tol)[0].tolist() ind_theta_fe1 = flatten_layer(prob.ind_theta[0][0], 2) # flatten sys w_zero_indices = [] for i in range(opts.n_s): tmp = flatten(ind_theta_fe1[i]) try: w_zero_indices += [tmp[i] for i in I_active_lam] except: breakpoint() # if all but one lambda are zero: this theta can be fixed to 1.0, all other thetas are 0.0 w_one_indices = [] # I_lam_zero = set(range(len(self.lambda00))).difference( I_active_lam ) # n_lam = sum(prob.model.dims.n_f_sys) # if len(I_active_lam) == n_lam - 1: # for i in range(opts.n_s): # tmp = flatten(ind_theta_fe1[i]) # w_one_indices += [tmp[i] for i in I_lam_zero] if opts.print_level > 1: print(f"fixing {prob.w[w_one_indices]} = 1. and {prob.w[w_zero_indices]} = 0.") print(f"Since self.lambda00 = {self.lambda00}") w0[w_zero_indices] = 0.0 lbw[w_zero_indices] = 0.0 ubw[w_zero_indices] = 0.0 w0[w_one_indices] = 1.0 lbw[w_one_indices] = 1.0 ubw[w_one_indices] = 1.0 else: lbw = prob.lbw ubw = prob.ubw # homotopy loop for ii in range(opts.max_iter_homotopy): tau_val = min(sigma_k ** 1.5, sigma_k) # tau_val = sigma_k**1.5*1e3 self.setup_p_val(sigma_k, tau_val) # solve NLP sol = self.solver(x0=w0, lbg=prob.lbg, ubg=prob.ubg, lbx=lbw, ubx=ubw, p=self.p_val) # statistics solver_stats = self.solver.stats() cpu_time_nlp[ii] = solver_stats['t_proc_total'] status = solver_stats['return_status'] nlp_iter[ii] = solver_stats['iter_count'] nlp_res = ca.norm_inf(sol['g']).full()[0][0] cost_val = ca.norm_inf(sol['f']).full()[0][0] # process iterate w_opt = sol['x'].full().flatten() w0 = w_opt w_all.append(w_opt) complementarity_residual = prob.comp_res(w_opt, self.p_val).full()[0][0] complementarity_stats[ii] = complementarity_residual if opts.print_level: self._print_iter_stats(sigma_k, complementarity_residual, nlp_res, cost_val, cpu_time_nlp[ii], nlp_iter[ii], status) if not check_ipopt_success(status): print(f"Warning: IPOPT exited with status {status}") if complementarity_residual < opts.comp_tol: break if sigma_k <= opts.sigma_N: break # Update the homotopy parameter. sigma_k = self.homotopy_sigma_update(sigma_k) if opts.do_polishing_step: w_opt, cpu_time_nlp[n_iter_polish - 1], nlp_iter[n_iter_polish - 1], status = \ self.polish_solution(self.solver, w_opt) # collect results results = get_results_from_primal_vector(prob, w_opt) # print constraint violation if opts.print_level > 1 and opts.constraint_handling == ConstraintHandling.LEAST_SQUARES: threshold = np.max([np.sqrt(cost_val) / 100, opts.comp_tol * 1e2, 1e-5]) g_val = prob.g_fun(w_opt, self.p_val).full().flatten() if max(abs(g_val)) > threshold: print("\nconstraint violations:") for ii in range(len(g_val)): if abs(g_val[ii]) > threshold: print(f"|g_val[{ii}]| = {abs(g_val[ii]):.2e} expr: {prob.g_lsq[ii]}") print(f"h values: {w_opt[prob.ind_h]}") # print(f"theta values: {w_opt[prob.ind_theta]}") # print(f"lambda values: {w_opt[prob.ind_lam]}") # print_casadi_vector(prob.g_lsq) if opts.initialization_strategy == InitializationStrategy.ALL_XCURRENT_WOPT_PREV: prob.w0[:] = w_opt[:] # stats results["cpu_time_nlp"] = cpu_time_nlp results["nlp_iter"] = nlp_iter results["w_all"] = w_all results["w_sol"] = w_opt results["cost_val"] = cost_val if check_ipopt_success(status): results["status"] = Status.SUCCESS else: results["status"] = Status.INFEASIBLE return results def get_results_from_primal_vector(prob: NosnocProblem, w_opt: np.ndarray) -> dict: opts = prob.opts results = dict() results["x_out"] = w_opt[prob.ind_x[-1][-1][-1]] # TODO: improve naming here? results["x_list"] = [w_opt[ind] for ind in flatten_layer(prob.ind_x_cont)] x0 = prob.model.x0 ind_x_all = flatten_outer_layers(prob.ind_x, 2) results["x_all_list"] = [x0] + [w_opt[np.array(ind)] for ind in ind_x_all] results["u_list"] = [w_opt[ind] for ind in prob.ind_u] results["theta_list"] = [w_opt[ind] for ind in get_cont_algebraic_indices(prob.ind_theta)] results["lambda_list"] = [w_opt[ind] for ind in get_cont_algebraic_indices(prob.ind_lam)] # results["mu_list"] = [w_opt[ind] for ind in ind_mu_all] # if opts.pss_mode == PssMode.STEP: results["alpha_list"] = [ w_opt[flatten_layer(ind)] for ind in get_cont_algebraic_indices(prob.ind_alpha) ] results["lambda_n_list"] = [ w_opt[flatten_layer(ind)] for ind in get_cont_algebraic_indices(prob.ind_lambda_n) ] results["lambda_p_list"] = [ w_opt[flatten_layer(ind)] for ind in get_cont_algebraic_indices(prob.ind_lambda_p) ] if opts.use_fesd: time_steps = w_opt[prob.ind_h] else: t_stages = opts.terminal_time / opts.N_stages for Nfe in opts.Nfe_list: time_steps = Nfe * [t_stages / Nfe] results["time_steps"] = time_steps # results relevant for OCP: results["x_traj"] = [x0] + results["x_list"] results["u_traj"] = results["u_list"] # duplicate name t_grid = np.concatenate((np.array([0.0]), np.cumsum(time_steps))) results["t_grid"] = t_grid u_grid = [0] + np.cumsum(opts.Nfe_list).tolist() results["t_grid_u"] = [t_grid[i] for i in u_grid] results["v_global"] = w_opt[prob.ind_v_global] # NOTE: this doesn't handle sliding modes well. But seems nontrivial. # compute based on changes in alpha or theta switch_indices = [] if opts.pss_mode == PssMode.STEP: alpha_prev = results["alpha_list"][0] for i, alpha in enumerate(results["alpha_list"][1:]): if any(np.abs(alpha - alpha_prev) > 0.1): switch_indices.append(i) alpha_prev = alpha else: theta_prev = results["theta_list"][0] for i, theta in enumerate(results["theta_list"][1:]): if any(np.abs(theta.flatten() - theta_prev.flatten()) > 0.1): switch_indices.append(i) theta_prev = theta results["switch_times"] = np.array([time_steps[i] for i in switch_indices]) return results
21,470
39.741935
118
py
nosnoc_py
nosnoc_py-main/nosnoc/helpers.py
from typing import Optional import numpy as np from .solver import NosnocSolver class NosnocSimLooper: def __init__(self, solver: NosnocSolver, x0: np.ndarray, Nsim: int, p_values: Optional[np.ndarray] = None, w_init: Optional[list] = None, print_level: Optional[int] = None ): """ :param solver: NosnocSolver to be called in a loop :param x0: np.ndarray: initial state :param Nsim: int: number of simulation steps :param p_values: Optional np.ndarray of shape (Nsim, n_p_glob), parameter values p_glob are updated at each simulation step accordingly. :param w_init: Optional: a list of np.ndarray with w values to initialize the solver at each step. """ # check that NosnocSolver solves a pure simulation problem. if not solver.problem.is_sim_problem(): raise Exception("NosnocSimLooper can only be used with pure simulation problem") # p values self.p_values = p_values if self.p_values is not None: if self.p_values.shape != (Nsim, solver.problem.model.dims.n_p_glob): raise ValueError("p_values should have shape (Nsim, n_p_glob). " f"Expected ({Nsim}, {solver.problem.model.dims.n_p_glob}), got {self.p_values.shape}") # create self.solver: NosnocSolver = solver self.Nsim = Nsim self.xcurrent = x0 self.X_sim = [x0] self.time_steps = np.array([]) self.theta_sim = [] self.lambda_sim = [] self.alpha_sim = [] self.w_sim = [] self.w_all = [] self.cost_vals = [] self.w_init = w_init if print_level is not None: self.print_level = print_level else: self.print_level = solver.opts.print_level self.status = [] self.switch_times = [] self.cpu_nlp = np.zeros((Nsim, solver.opts.max_iter_homotopy + (1 if solver.opts.do_polishing_step else 0))) def run(self, stop_on_failure=False) -> None: """Run the simulation loop.""" for i in range(self.Nsim): # set values self.solver.set("x0", self.xcurrent) if self.w_init is not None: self.solver.set("w", self.w_init[i]) if self.p_values is not None: self.solver.set("p_global", self.p_values[i, :]) # solve results = self.solver.solve() # add previous time to switch times if results["switch_times"].size > 0: switch_times_sim = results["switch_times"] + np.sum(self.time_steps) self.switch_times += switch_times_sim.tolist() # collect self.X_sim += results["x_list"] self.xcurrent = self.X_sim[-1] self.cpu_nlp[i, :] = results["cpu_time_nlp"] self.time_steps = np.concatenate((self.time_steps, results["time_steps"])) self.theta_sim.append(results["theta_list"]) self.lambda_sim.append(results["lambda_list"]) self.alpha_sim.append(results["alpha_list"]) self.w_sim += [results["w_sol"]] self.w_all += [results["w_all"]] self.cost_vals.append(results["cost_val"]) self.status.append(results["status"]) if self.print_level > 0: print(f"Sim step {i + 1}/{self.Nsim}\t status: {results['status']}") if (stop_on_failure and results["status"] == "Infeasible_Problem_Detected"): return False return True def get_results(self) -> dict: self.t_grid = np.concatenate((np.array([0.0]), np.cumsum(self.time_steps))) results = { "X_sim": np.array(self.X_sim), "cpu_nlp": np.nan_to_num(self.cpu_nlp), "time_steps": self.time_steps, "t_grid": self.t_grid, "theta_sim": self.theta_sim, "lambda_sim": self.lambda_sim, "alpha_sim": self.alpha_sim, "w_sim": self.w_sim, "w_all": self.w_all, "cost_vals": self.cost_vals, "status": self.status, "switch_times": self.switch_times, } return results
4,362
37.955357
144
py
nosnoc_py
nosnoc_py-main/nosnoc/rk_utils.py
import numpy as np import casadi as ca from .nosnoc_types import IrkSchemes def rk4(f, x0, tf: float, n_steps: int = 1): # Compute time step from final time and number of steps dt = tf / n_steps # Create time vector t = np.linspace(0, tf, n_steps + 1) # Create storage for solution x = np.zeros((n_steps + 1, len(x0))) x[0, :] = x0 # Runge-Kutta 4th order method for i in range(n_steps): k1 = f(x[i, :]) k2 = f(x[i, :] + dt * k1 / 2) k3 = f(x[i, :] + dt * k2 / 2) k4 = f(x[i, :] + dt * k3) x[i + 1, :] = x[i, :] + dt / 6 * (k1 + 2 * k2 + 2 * k3 + k4).full().flatten() x = x.tolist() return x, t def rk4_on_timegrid(f, x0, t_grid: np.ndarray) -> list: x = np.zeros((len(t_grid) + 1, len(x0))) x[0, :] = x0 # Runge-Kutta 4th order method for i in range(len(t_grid)): # TODO: multiple steps? dt = t_grid[i] k1 = f(x[i, :]) k2 = f(x[i, :] + dt * k1 / 2) k3 = f(x[i, :] + dt * k2 / 2) k4 = f(x[i, :] + dt * k3) x[i + 1, :] = x[i, :] + dt / 6 * (k1 + 2 * k2 + 2 * k3 + k4).full().flatten() x = x.tolist() return x def generate_butcher_tableu(n_s, irk_scheme): if irk_scheme == IrkSchemes.RADAU_IIA: order = 2 * n_s - 1 if n_s == 1: A = np.array([[1.0]]) b = np.array([1.0]) c = np.array([1.0]) elif n_s == 2: A = np.array([[0.4166666666666666, -0.08333333333333334], [0.75, 0.25]]) b = np.array([0.75, 0.25]) c = np.array([0.3333333333333334, 1]) elif n_s == 3: A = np.array([[ 0.196815477223660, -0.065535425850198, 0.023770974348220, ], [ 0.394424314739087, 0.292073411665228, -0.041548752125998, ], [ 0.376403062700467, 0.512485826188421, 0.111111111111110, ]]) b = np.array([ 0.376403062700467, 0.512485826188421, 0.111111111111110, ]) c = np.array([ 0.155051025721682, 0.644948974278318, 1.000000000000000, ]) elif n_s == 4: A = np.array([[ 0.112999479323157, -0.040309220723522, 0.025802377420337, -0.009904676507266, ], [ 0.234383995747400, 0.206892573935358, -0.047857128048540, 0.016047422806516, ], [ 0.216681784623251, 0.406123263867372, 0.189036518170056, -0.024182104899833, ], [ 0.220462211176769, 0.388193468843169, 0.328844319980059, 0.062500000000000, ]]) b = np.array([ 0.220462211176769, 0.388193468843169, 0.328844319980059, 0.062500000000000, ]) c = np.array([ 0.088587959512704, 0.409466864440735, 0.787659461760847, 1.000000000000000, ]) elif n_s == 5: A = np.array([[ 0.072998864317904, -0.026735331107946, 0.018676929763985, -0.012879106093307, 0.005042839233882, ], [ 0.153775231479183, 0.146214867847492, -0.036444568905127, 0.021233063119304, -0.007935579902729, ], [ 0.140063045684810, 0.298967129491284, 0.167585070135249, -0.033969101686618, 0.010944288744192, ], [ 0.144894308109535, 0.276500068760161, 0.325797922910417, 0.128756753254908, -0.015708917378806, ], [ 0.143713560791225, 0.281356015149471, 0.311826522975734, 0.223103901083569, 0.039999999999999, ]]) b = np.array([ 0.143713560791225, 0.281356015149471, 0.311826522975734, 0.223103901083569, 0.039999999999999, ]) c = np.array([ 0.057104196114518, 0.276843013638124, 0.583590432368917, 0.860240135656219, 1.000000000000000, ]) elif n_s == 6: A = np.array([[ 0.050950010994641, -0.018907306554292, 0.013686071433088, -0.010370038766046, 0.007360656396640, -0.002909536452562, ], [ 0.108221658919059, 0.106975519937331, -0.027539023355392, 0.017496747141228, -0.011653721891195, 0.004512237122577, ], [ 0.097779670092646, 0.223172250636896, 0.136314679273052, -0.029646965988196, 0.016358578843438, -0.006003402610448, ], [ 0.102122375612935, 0.202975957373093, 0.276399136380739, 0.131006023136051, -0.024876303199822, 0.007837084050643, ], [ 0.100331001384960, 0.210247308553335, 0.256085372050322, 0.253365934704577, 0.092430534335701, -0.010995236827731, ], [ 0.100794192626740, 0.208450667155965, 0.260463391594751, 0.242693594234513, 0.159820376610253, 0.027777777777780, ]]) b = np.array([ 0.100794192626740, 0.208450667155965, 0.260463391594751, 0.242693594234513, 0.159820376610253, 0.027777777777780, ]) c = np.array([ 0.039809857051469, 0.198013417873608, 0.437974810247386, 0.695464273353636, 0.901464914201173, 1.000000000000000, ]) elif n_s == 7: A = np.array([[ 0.037546264993922, -0.014039334556461, 0.010352789600743, -0.008158322540275, 0.006388413879535, -0.004602326779149, 0.001828942561471, ], [ 0.080147596515620, 0.081062063985891, -0.021237992120711, 0.014000291238817, -0.010234185730090, 0.007153465151364, -0.002812639372407, ], [ 0.072063846941883, 0.171068354983886, 0.109614564040073, -0.024619871728985, 0.014760377043950, -0.009575259396791, 0.003672678397138, ], [ 0.075705125819825, 0.154090155142168, 0.227107736673208, 0.117478187037015, -0.023810827153042, 0.012709985533668, -0.004608844281289, ], [ 0.073912342163194, 0.161355607615931, 0.206867241552146, 0.237007115342664, 0.103086793533791, -0.018854139152552, 0.005858900974893, ], [ 0.074705562059812, 0.158307223872441, 0.214153423267192, 0.219877847031825, 0.198752121680627, 0.069265501605543, -0.008116008197746, ], [ 0.074494235556031, 0.159102115733617, 0.212351889503054, 0.223554914507190, 0.190474936822056, 0.119613744612707, 0.020408163265273, ]]) b = np.array([ 0.074494235556031, 0.159102115733617, 0.212351889503054, 0.223554914507190, 0.190474936822056, 0.119613744612707, 0.020408163265273, ]) c = np.array([ 0.029316427159785, 0.148078599668484, 0.336984690281154, 0.558671518771550, 0.769233862030055, 0.926945671319741, 1.000000000000000, ]) elif n_s == 8: A = np.array([[ 0.028802823892618, -0.010821698052016, 0.008069010203852, -0.006493073596536, 0.005300041017295, -0.004223309650010, 0.003069413349141, -0.001223820725630, ], [ 0.061680826212951, 0.063307905435285, -0.016766167621301, 0.011276575963179, -0.008575400848083, 0.006607056898422, -0.004723817373992, 0.001872074494442, ], [ 0.055285563267235, 0.134572019854444, 0.088830181899131, -0.020322485837009, 0.012631022220424, -0.008970025754043, 0.006180900917007, -0.002417353782599, ], [ 0.058300686057541, 0.120477661477342, 0.186414284318503, 0.101430904157414, -0.021196196398552, 0.012247274295402, -0.007798637777912, 0.002970397539715, ], [ 0.056682008984804, 0.127043161483419, 0.168088370419389, 0.209202248763793, 0.099187005744731, -0.019275308810477, 0.010069646505077, -0.003621850204030, ], [ 0.057543032017261, 0.123740992239338, 0.175951552284005, 0.190819813746984, 0.199456888942931, 0.082437024757780, -0.014724795758206, 0.004534800032808, ], [ 0.057146971559293, 0.125220694738182, 0.172643313188367, 0.197414436139205, 0.185210784696057, 0.158621287474583, 0.053712487445948, -0.006232535779285, ], [ 0.057254407372170, 0.124823950664929, 0.173507397817925, 0.195786083725501, 0.188258772694223, 0.152065310323877, 0.092679077400701, 0.015624999999989, ]]) b = np.array([ 0.057254407372170, 0.124823950664929, 0.173507397817925, 0.195786083725501, 0.188258772694223, 0.152065310323877, 0.092679077400701, 0.015624999999989, ]) c = np.array([ 0.022479386438713, 0.114679053160904, 0.265789822784590, 0.452846373669445, 0.647375282886830, 0.819759308263108, 0.943737439463077, 1.000000000000000, ]) elif n_s == 9: A = np.array([[ 0.022788378793460, -0.008589639752939, 0.006451029176996, -0.005257528699750, 0.004388833809362, -0.003651215553691, 0.002940488213753, -0.002149274163883, 0.000858843324058, ], [ 0.048907952447500, 0.050702050480828, -0.013523807196021, 0.009209373774305, -0.007155713317537, 0.005747246699432, -0.004542582976394, 0.003288161681791, -0.001309073694109, ], [ 0.043742760091572, 0.108301892902740, 0.072919565937428, -0.016879877210016, 0.010704551844802, -0.007901946479239, 0.005991406942180, -0.004248024439987, 0.001678149806150, ], [ 0.046249237453949, 0.096560730726800, 0.154298769790035, 0.086719369303118, -0.018451639643615, 0.011036658729825, -0.007673280940271, 0.005228224999886, -0.002035905836478, ], [ 0.044834436586896, 0.102306849685959, 0.138217634192387, 0.181263934682107, 0.090433600599454, -0.018085063366811, 0.010193387903882, -0.006405265418863, 0.002427169938414, ], [ 0.045658755719302, 0.099145470489361, 0.145747040497213, 0.163648281233691, 0.185944587344693, 0.083613260231573, -0.015809936146070, 0.008138252693868, -0.002910469207819, ], [ 0.045200600187684, 0.100853706718908, 0.141942236794193, 0.171189471837806, 0.169783386170366, 0.167768291173161, 0.067079034322205, -0.011792230536457, 0.003609246288590, ], [ 0.045416516657269, 0.100060402446161, 0.143652840987215, 0.168019080978866, 0.175560768418563, 0.155886270451902, 0.128893913517004, 0.042810826024379, -0.004934574771255, ], [ 0.045357252461599, 0.100276649011903, 0.143193348179011, 0.168846983486219, 0.174136501388603, 0.158421887836084, 0.123594689101992, 0.073827009522574, 0.012345679012242, ]]) b = np.array([ 0.045357252461599, 0.100276649011903, 0.143193348179011, 0.168846983486219, 0.174136501388603, 0.158421887836084, 0.123594689101992, 0.073827009522574, 0.012345679012242, ]) c = np.array([ 0.017779915147364, 0.091323607899794, 0.214308479395630, 0.371932164583272, 0.545186684803427, 0.713175242855570, 0.855633742957854, 0.955366044710030, 1.000000000000000, ]) else: raise NotImplementedError() elif irk_scheme == IrkSchemes.GAUSS_LEGENDRE: order = 2 * n_s if n_s == 1: A = np.array([[ 0.500000000000000, ]]) b = np.array([ 1.000000000000000, ]) c = np.array([ 0.500000000000000, ]) elif n_s == 2: A = np.array([[ 0.250000000000000, -0.038675134594813, ], [ 0.538675134594813, 0.250000000000000, ]]) b = np.array([ 0.500000000000000, 0.500000000000000, ]) c = np.array([ 0.211324865405187, 0.788675134594813, ]) elif n_s == 3: A = np.array([[ 0.138888888888889, -0.035976667524939, 0.009789444015308, ], [ 0.300263194980865, 0.222222222222222, -0.022485417203087, ], [ 0.267988333762469, 0.480421111969383, 0.138888888888889, ]]) b = np.array([ 0.277777777777778, 0.444444444444444, 0.277777777777778, ]) c = np.array([ 0.112701665379258, 0.500000000000000, 0.887298334620742, ]) elif n_s == 4: A = np.array([[ 0.086963711284363, -0.026604180084999, 0.012627462689405, -0.003555149685796, ], [ 0.188118117499868, 0.163036288715637, -0.027880428602471, 0.006735500594538, ], [ 0.167191921974189, 0.353953006033745, 0.163036288715636, -0.014190694931141, ], [ 0.177482572254522, 0.313445114741872, 0.352676757516270, 0.086963711284364, ]]) b = np.array([ 0.173927422568726, 0.326072577431278, 0.326072577431272, 0.173927422568728, ]) c = np.array([ 0.069431844202974, 0.330009478207572, 0.669990521792428, 0.930568155797026, ]) elif n_s == 5: A = np.array([[ 0.059231721264047, -0.019570364359076, 0.011254400818643, -0.005593793660812, 0.001588112967866, ], [ 0.128151005670045, 0.119657167624842, -0.024592114619642, 0.010318280670683, -0.002768994398770, ], [ 0.113776288004224, 0.260004651680642, 0.142222222222221, -0.020690316430958, 0.004687154523870, ], [ 0.121232436926862, 0.228996054578998, 0.309036559064083, 0.119657167624843, -0.009687563141950, ], [ 0.116875329560226, 0.244908128910493, 0.273190043625792, 0.258884699608764, 0.059231721264048, ]]) b = np.array([ 0.118463442528091, 0.239314335249677, 0.284444444444436, 0.239314335249684, 0.118463442528096, ]) c = np.array([ 0.046910077030668, 0.230765344947159, 0.500000000000000, 0.769234655052841, 0.953089922969332, ]) elif n_s == 6: A = np.array([[ 0.042831123094792, -0.014763725997197, 0.009325050706477, -0.005668858049483, 0.002854433315099, -0.000812780171265, ], [ 0.092673491430378, 0.090190393262035, -0.020300102293240, 0.010363156240247, -0.004887192928038, 0.001355561055485, ], [ 0.082247922612843, 0.196032162333246, 0.116978483643174, -0.020482527745657, 0.007989991899662, -0.002075625784866, ], [ 0.087737871974450, 0.172390794624414, 0.254439495032005, 0.116978483643169, -0.015651375809174, 0.003414323576741, ], [ 0.084306685134102, 0.185267979452117, 0.223593811046108, 0.254257069579578, 0.090190393262038, -0.007011245240795, ], [ 0.086475026360850, 0.177526353209002, 0.239625825335853, 0.224631916579851, 0.195144512521278, 0.042831123094790, ]]) b = np.array([ 0.085662246189586, 0.180380786524101, 0.233956967286350, 0.233956967286344, 0.180380786524064, 0.085662246189580, ]) c = np.array([ 0.033765242898423, 0.169395306766867, 0.380690406958402, 0.619309593041598, 0.830604693233132, 0.966234757101576, ]) elif n_s == 7: A = np.array([[ 0.032371241542217, -0.011451017283184, 0.007633203872423, -0.005133733563225, 0.003175058773686, -0.001606819037046, 0.000458109523749, ], [ 0.070043541378726, 0.069926347872320, -0.016590006578848, 0.009349622783444, -0.005397091931896, 0.002645843866730, -0.000743850190172, ], [ 0.062153935787349, 0.152005522057830, 0.095457512626279, -0.018375244215452, 0.008712562598475, -0.003953580158811, 0.001076715615628, ], [ 0.066332928617678, 0.133595769223878, 0.207701880765966, 0.104489795918363, -0.016786855513410, 0.006256926520753, -0.001590445533250, ], [ 0.063665767468791, 0.143806275903430, 0.182202462654061, 0.227354836052162, 0.095457512626282, -0.012152826313210, 0.002588547297082, ], [ 0.065486333274562, 0.137206851877894, 0.196312117184414, 0.199629969053189, 0.207505031831440, 0.069926347872274, -0.005301058294296, ], [ 0.064284373560617, 0.141459514781547, 0.187739966478872, 0.214113325399745, 0.183281821380140, 0.151303713027731, 0.032371241542209, ]]) b = np.array([ 0.064742483084360, 0.139852695744546, 0.190915025252464, 0.208979591836627, 0.190915025252578, 0.139852695744521, 0.064742483084429, ]) c = np.array([ 0.025446043828620, 0.129234407200303, 0.297077424311301, 0.500000000000000, 0.702922575688699, 0.870765592799697, 0.974553956171379, ]) elif n_s == 8: A = np.array([[ 0.025307134072594, -0.009105943305970, 0.006280831147030, -0.004483015613055, 0.003078491368327, -0.001917675254637, 0.000972757664059, -0.000277508327117, ], [ 0.054759321767554, 0.055595258613345, -0.013639796235782, 0.008149708858361, -0.005215352089147, 0.003139752985464, -0.001564934910949, 0.000442802304342, ], [ 0.048587535998913, 0.120859524997173, 0.078426661469471, -0.015975103361879, 0.008371732720226, -0.004643465862104, 0.002225714775285, -0.000618805695251, ], [ 0.051865520970582, 0.106193490148350, 0.170671134274548, 0.090670945844584, -0.016021041321030, 0.007241206561225, -0.003197814310362, 0.000859236584265, ], [ 0.049755031560927, 0.114388331537048, 0.149612116377682, 0.197362933010172, 0.090670945844598, -0.013817811335584, 0.004997027078331, -0.001251252825391, ], [ 0.051233073840447, 0.108964802451400, 0.161496788800919, 0.172970158968791, 0.197316995050984, 0.078426661469599, -0.009669007770489, 0.002026732146281, ], [ 0.050171465840885, 0.112755452137506, 0.153713569953126, 0.186557243777861, 0.173192182830976, 0.170493119175010, 0.055595258613351, -0.004145053622349, ], [ 0.050891776472231, 0.110217759562534, 0.158770998192800, 0.178263400320301, 0.185824907302086, 0.150572491792394, 0.120296460532602, 0.025307134072634, ]]) b = np.array([ 0.050614268145260, 0.111190517226596, 0.156853322938151, 0.181341891688295, 0.181341891689184, 0.156853322939500, 0.111190517226614, 0.050614268145245, ]) c = np.array([ 0.019855071751232, 0.101666761293187, 0.237233795041836, 0.408282678752175, 0.591717321247825, 0.762766204958164, 0.898333238706813, 0.980144928248768, ]) elif n_s == 9: A = np.array([[ 0.020318597090394, -0.007397868566149, 0.005222003592100, -0.003873451291745, 0.002831369450070, -0.001962194188391, 0.001226609788813, -0.000622964091649, 0.000177778462745, ], [ 0.043965527226529, 0.045162040173714, -0.011335464012335, 0.007034766801735, -0.004788276131017, 0.003203360151985, -0.001964405739953, 0.000987172103666, -0.000280274237641, ], [ 0.039008653396285, 0.098181511959848, 0.065152674100733, -0.013770833986609, 0.007664175624643, -0.004713586467799, 0.002770828892759, -0.001361671983073, 0.000382532112918, ], [ 0.041645087027326, 0.086255472772503, 0.141795216041138, 0.078086769260000, -0.014618957875909, 0.007300428262182, -0.003932839915038, 0.001852686200821, -0.000510573474928, ], [ 0.039940372869860, 0.092943372272725, 0.124257110410740, 0.170000445255294, 0.082559838750321, -0.013826906735218, 0.006048237790678, -0.002619291925299, 0.000696821310955, ], [ 0.041147767655826, 0.088471394146737, 0.134238188116171, 0.148873110258109, 0.179738635376310, 0.078086769260125, -0.011489867839813, 0.004068607574951, -0.001007892846527, ], [ 0.040254662068108, 0.091685752330989, 0.127534519308256, 0.160887124988221, 0.157455501875688, 0.169944372506848, 0.065152674100318, -0.007857431612422, 0.001628540784537, ], [ 0.040917468419025, 0.089336908244377, 0.132269753940591, 0.152970178368378, 0.169907953631991, 0.149138771718299, 0.141640812213154, 0.045162040173409, -0.003328333045658, ], [ 0.040459415718829, 0.090947044440327, 0.129078738411408, 0.158135732709525, 0.162288308049938, 0.160046989811690, 0.125083344608356, 0.097721948913431, 0.020318597090466, ]]) b = np.array([ 0.040637194181613, 0.090324080348182, 0.130305348199727, 0.156173538521216, 0.165119677500115, 0.156173538521216, 0.130305348200636, 0.090324080347500, 0.040637194181045, ]) c = np.array([ 0.015919880246187, 0.081984446336682, 0.193314283649705, 0.337873288298095, 0.500000000000000, 0.662126711701905, 0.806685716350295, 0.918015553663318, 0.984080119753813, ]) else: raise NotImplementedError() return A, b, c, order def generate_butcher_tableu_integral(n_s, irk_scheme): IRK_SCHEME_TO_STRING = {IrkSchemes.GAUSS_LEGENDRE: "legendre", IrkSchemes.RADAU_IIA: "radau"} points = ca.collocation_points(n_s, IRK_SCHEME_TO_STRING[irk_scheme]) tau_root = np.array([0.0] + points) # Coefficients of the collocation equation C = np.zeros((n_s + 1, n_s + 1)) # Coefficients of the continuity equation D = np.zeros((n_s + 1, 1)) # Coefficients of the quadrature function B = np.zeros((n_s + 1, 1)) # Construct polynomial basis for j in range(n_s + 1): # Construct Lagrange polynomials to get the polynomial basis at the collocation point coeff = 1 for r in range(n_s + 1): if not r == j: coeff = np.convolve(coeff, [1, -tau_root[r]]) coeff = coeff / (tau_root[j] - tau_root[r]) # Evaluate the polynomial at the final time to get the coefficients of the continuity equation D[j] = np.polyval(coeff, 1.0) # Evaluate the time derivative of the polynomial at all collocation points to get the coefficients of the continuity equation pder = np.polyder(coeff) for r in range(n_s + 1): C[j, r] = np.polyval(pder, tau_root[r]) # Evaluate the integral of the polynomial to get the coefficients of the quadrature function pint = np.polyint(coeff) B[j] = np.polyval(pint, 1.0) return B, C, D, tau_root if __name__ == "__main__": # test RK tableaus for irk_scheme in IrkSchemes: n_s = 2 B, C, D, tau_root = generate_butcher_tableu_integral(n_s, irk_scheme) print(f"Tableau for {n_s=} {irk_scheme.name} reads") print(f"{B=}\n{C=}\n{D=}\n{tau_root=}\n\n")
41,761
37.104015
133
py
nosnoc_py
nosnoc_py-main/nosnoc/nosnoc_opts.py
from typing import Union from dataclasses import dataclass, field import numpy as np from .rk_utils import generate_butcher_tableu, generate_butcher_tableu_integral from .utils import validate from .nosnoc_types import MpccMode, IrkSchemes, StepEquilibrationMode, CrossComplementarityMode, IrkRepresentation, PssMode, IrkRepresentation, HomotopyUpdateRule, InitializationStrategy, ConstraintHandling def _assign(dictionary, keys, value): """Assign a value.""" for key in keys: dictionary[key] = value @dataclass class NosnocOpts: # discretization terminal_time: Union[float, int] = 1.0 # TODO: make param? use_fesd: bool = True #: Selects use of fesd or normal RK formulation. print_level: int = 0 #: higher -> more info max_iter_homotopy: int = 0 initialization_strategy: InitializationStrategy = InitializationStrategy.ALL_XCURRENT_W0_START irk_representation: IrkRepresentation = IrkRepresentation.INTEGRAL # IRK and FESD opts n_s: int = 2 #: Number of IRK stages irk_scheme: IrkSchemes = IrkSchemes.RADAU_IIA cross_comp_mode: CrossComplementarityMode = CrossComplementarityMode.SUM_LAMBDAS_COMPLEMENT_WITH_EVERY_THETA mpcc_mode: MpccMode = MpccMode.SCHOLTES_INEQ constraint_handling: ConstraintHandling = ConstraintHandling.EXACT pss_mode: PssMode = PssMode.STEWART # possible options: Stewart and Step use_upper_bound_h: bool = True gamma_h: float = 1.0 smoothing_parameter: float = 1e1 #: used for smoothed Step representation # used in InitializationStrategy.RK4_smoothed fix_active_set_fe0: bool = False # initialization - Stewart init_theta: float = 1.0 init_lambda: float = 1.0 init_mu: float = 1.0 # initialization - Step init_alpha: float = 0.5 # for step only init_beta: float = 1.0 N_finite_elements: int = 2 # Nfe_list: list = field(default_factory=list) #: list of length N_stages, Nfe per stage # MPCC and Homotopy opts comp_tol: float = 1e-8 #: complementarity tolerance sigma_0: float = 1.0 sigma_N: float = 1e-8 homotopy_update_slope: float = 0.1 homotopy_update_exponent: float = 1.5 homotopy_update_rule: HomotopyUpdateRule = HomotopyUpdateRule.LINEAR # step equilibration step_equilibration: StepEquilibrationMode = StepEquilibrationMode.HEURISTIC_DELTA step_equilibration_sigma: float = 0.1 rho_h: float = 1.0 # for MpccMode.FISCHER_BURMEISTER_IP_AUG fb_ip_aug1_weight: float = 1e0 fb_ip_aug2_weight: float = 1e-1 # polishing step do_polishing_step: bool = False # OCP only N_stages: int = 1 equidistant_control_grid: bool = True # NOTE: tested in test_ocp s_elastic_0: float = 1.0 s_elastic_max: float = 1e1 s_elastic_min: float = 0.0 # IPOPT opts opts_casadi_nlp = dict() opts_casadi_nlp['print_time'] = 0 opts_casadi_nlp['verbose'] = False opts_casadi_nlp['ipopt'] = dict() opts_casadi_nlp['ipopt']['sb'] = 'yes' opts_casadi_nlp['ipopt']['max_iter'] = 500 opts_casadi_nlp['ipopt']['print_level'] = 0 opts_casadi_nlp['ipopt']['bound_relax_factor'] = 0 tol_ipopt = property( fget=lambda s: s.opts_casadi_nlp['ipopt']['tol'], fset=lambda s, v: _assign( s.opts_casadi_nlp['ipopt'], ['tol', 'dual_inf_tol', 'compl_inf_tol', 'mu_target'], v ), doc="Ipopt tolerance." ) opts_casadi_nlp['ipopt']['tol'] = None opts_casadi_nlp['ipopt']['dual_inf_tol'] = None opts_casadi_nlp['ipopt']['compl_inf_tol'] = None opts_casadi_nlp['ipopt']['mu_strategy'] = 'adaptive' opts_casadi_nlp['ipopt']['mu_oracle'] = 'quality-function' opts_casadi_nlp["record_time"] = True # opts_casadi_nlp['ipopt']['linear_solver'] = 'ma27' # opts_casadi_nlp['ipopt']['linear_solver'] = 'ma57' time_freezing: bool = False time_freezing_tolerance: float = 1e-3 rootfinder_for_initial_z: bool = False # Usabillity: nlp_max_iter = property( fget=lambda s: s.opts_casadi_nlp["ipopt"]["max_iter"], fset=lambda s, v: _assign(s.opts_casadi_nlp["ipopt"], ["max_iter"], v), doc="Maximum amount of iterations for the subsolver." ) def __repr__(self) -> str: out = '' for k, v in self.__dict__.items(): out += f"{k} : {v}\n" return out def preprocess(self): # IPOPT tol should be smaller than outer tol, but not too much # Note IPOPT option list: https://coin-or.github.io/Ipopt/OPTIONS.html if self.tol_ipopt is None: self.tol_ipopt = self.comp_tol * 1e-2 validate(self) # self.opts_casadi_nlp['ipopt']['print_level'] = self.print_level if self.time_freezing: if self.n_s < 3: Warning("Problem might be illposed if n_s < 3 and time freezing") # TODO: Extend checks if self.max_iter_homotopy == 0: self.max_iter_homotopy = int(np.round(np.abs(np.log(self.comp_tol / self.sigma_0) / np.log(self.homotopy_update_slope)))) + 1 if len(self.Nfe_list) == 0: self.Nfe_list = self.N_stages * [self.N_finite_elements] # Butcher Tableau if self.irk_representation == IrkRepresentation.INTEGRAL: B_irk, C_irk, D_irk, irk_time_points = generate_butcher_tableu_integral( self.n_s, self.irk_scheme) self.B_irk = B_irk self.C_irk = C_irk self.D_irk = D_irk elif (self.irk_representation in [IrkRepresentation.DIFFERENTIAL, IrkRepresentation.DIFFERENTIAL_LIFT_X]): A_irk, b_irk, irk_time_points, _ = generate_butcher_tableu(self.n_s, self.irk_scheme) self.A_irk = A_irk self.b_irk = b_irk self.irk_time_points = irk_time_points if np.abs(irk_time_points[-1] - 1.0) < 1e-9: self.right_boundary_point_explicit = True else: self.right_boundary_point_explicit = False # checks: if (self.cross_comp_mode == CrossComplementarityMode.SUM_LAMBDAS_COMPLEMENT_WITH_EVERY_THETA and self.mpcc_mode in [MpccMode.FISCHER_BURMEISTER, MpccMode.FISCHER_BURMEISTER_IP_AUG]): Warning( "UNSUPPORTED option combination comp_mode: SUM_LAMBDAS_COMPLEMENT_WITH_EVERY_THETA and mpcc_mode: MpccMode.FISCHER_BURMEISTER" ) if self.mpcc_mode == MpccMode.FISCHER_BURMEISTER and self.constraint_handling != ConstraintHandling.LEAST_SQUARES: Warning( "UNSUPPORTED option combination comp_mode: mpcc_mode == MpccMode.FISCHER_BURMEISTER and constraint_handling != ConstraintHandling.LEAST_SQUARES" ) if (self.step_equilibration in [StepEquilibrationMode.DIRECT, StepEquilibrationMode.DIRECT_COMPLEMENTARITY] and self.constraint_handling != ConstraintHandling.LEAST_SQUARES): Warning( "UNSUPPORTED option combination: StepEquilibrationMode.DIRECT* and constraint_handling != ConstraintHandling.LEAST_SQUARES" ) return ## Options in matlab.. # MPCC related, not implemented yet. # Time-Setting # NOTE: all not needed (for now) # Time-Freezing # time_freezing_inelastic: bool = False # time_rescaling: bool = False # # for time optimal problems and equidistant control grids in physical time # use_speed_of_time_variables: bool = True # local_speed_of_time_variable: bool = False # stagewise_clock_constraint: bool = True # impose_terminal_phyisical_time: bool = True # # S_sot_nominal = 1 # # rho_sot = 0 # s_sot0: float = 1.0 # s_sot_max: float = 25. # s_sot_min: float = 1.0 # time_freezing_reduced_model = 0 # analytic reduction of lifter formulation, less algebraic variables # time_freezing_hysteresis = 0 # do not do automatic time freezing generation for hysteresis, it is not supported yet. # time_freezing_nonlinear_friction_cone = 1 # 1 - use nonlienar friction cone, 0 - use polyhedral l_inf approximation. # time_freezing_quadrature_state = 0 # make a nonsmooth quadrature state to integrate only if physical time is running ## Some Nosnoc options that are not relevant here (yet) # n_depth_step_lifting = 2; # it is not recomended to change this (increase nonlinearity and harms convergenc), depth is number of multilinar terms to wich a lifting variables is equated to. # # Default opts for the barrier tuned penalty/slack variables for mpcc modes 8 do 10. # rho_penalty = 1e1; # sigma_penalty = 0; # ## Homotopy preprocess and polishing steps # h_fixed_max_iter = 1; # number of iterations that are done with fixed h in the homotopy loop # h_fixed_change_sigma = 1; # if this is on, do not update sigma and just solve on nlp with fixed h. # polishing_step = 0; # Heuristic for fixing active set, yet exerimental, not recommended to use. # polishing_derivative_test = 0; # check in sliding mode also the derivative of switching functions # h_fixed_to_free_homotopy = 0; # start with large penaly for equidistant grid, end with variable equilibrated grid. # ## Step equilibration # delta_h_regularization = 0; # piecewise_equidistant_grid = 0; # piecewise_equidistant_grid_sigma 1; # piecewise_equidistant_grid_slack_mode = 0; # # step_equilibration_penalty = 0.1; #(rho_h in step_equilibration modde 1, as qudratic penalty)
9,556
40.372294
206
py
RAFnet
RAFnet-main/opt_rnn_attention.py
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ @author: lry """ import scipy.io as sio import numpy as np sep = [20,40,61,103] # please pay attention to this seperation , setted according to the spectral response function of different sensors. # setting global parameters patch_size = 16 patch_size1 = 16 patch_size2 = 16 patch_num = 2 batch_size = patch_size*patch_size*patch_num gap = 12 # the interval between two adjacent patches, must smaller than 'patch_size' sigmaInit = 0.01 lastTrain = 0 # go on the former training Pretrain = 500 # the number of iteration for pretraining Maxiter = 3000 # the max iterations for training # try 2000 3000 4000 step = 100 # save the model every "step" iterations learning_rate = 0.0001 max_grad_norm = 0.1 # saving path path = './result_fusion' filename = "../processed_data/.." print("Loading data") data = sio.loadmat(filename) Xl_3d = data['xl'] Xl_bicubic = data['xl_bicubic'] # this is the bibubic-interpolated xl image acquired with matlab Xg_3d = data['xg'] scale = data['scale'][0][0] Trans_data = data['P'] N1,N2,dimX = data['xh'].shape s1,s2 = data['xl'].shape[0], data['xl'].shape[1] dimXg = Xg_3d.shape[2] Xl_2d = np.reshape(Xl_3d,[-1,dimX]) num = s1*s2 # the number of low-resolution pixels f2_1 = 9 # 1D filter size f3_1 = 5 # 2D filter size hidden_size_local = 30 hidden_size_global = 20 gener_hidden_size = 20 enc_q = enc_k = hidden_size_global * 2 enc_v = hidden_size_global * 2 enc_k_z = enc_v_z = 30 dec_q = 30 filter_num_1 = 20 filter_num_2 = 20 filter_num_3 = hidden_size_global*2*dimXg #### hidden_size_global*2*dimXg f_1 = 5 f_2 = 3 f_3 = 1 H3_1 = dimX dimZ = dimXg*hidden_size_global # dimension of z
1,775
25.909091
139
py
RAFnet
RAFnet-main/main_rnn_attention.py
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ @author: lry """ import tensorflow as tf import numpy as np import time import os import random import opt_rnn_attention as opt from rnn_attention_model import rnn_model index1 = np.arange(0, opt.N1, opt.scale) index2 = np.arange(0, opt.N2, opt.scale) Xl_big = np.zeros((opt.N1, opt.N2, opt.dimX), dtype='float32') for r1 in range(len(index1)): for r2 in range(len(index2)): Xl_big[index1[r1]: index1[r1]+opt.scale, index2[r2]: index2[r2]+opt.scale, :] = opt.Xl_3d[r1, r2, :] def weight_variable(shape): initial = tf.truncated_normal(shape, stddev=opt.sigmaInit, dtype=tf.float32) return tf.Variable(initial) def bias_variable(shape): initial = tf.constant(0, shape=shape, dtype=tf.float32) return tf.Variable(initial) def conv2d(x, w): return tf.nn.conv2d(x, w, strides=[1, 1, 1, 1], padding='SAME') def conv_t(x, w, s): return tf.nn.conv2d_transpose(x, w, output_shape=s, strides=[1, 1, 1, 1], padding='SAME') def average_pool_2x2(x): return tf.layers.average_pooling2d(x, pool_size=[2, 2], strides=[2, 2], padding='SAME') # inputs x_low = tf.placeholder('float32', [opt.num, opt.dimX]) x_bic = tf.placeholder('float32', [opt.patch_num, opt.patch_size, opt.patch_size, opt.dimX]) x_rgb = tf.placeholder('float32', [opt.patch_num, opt.patch_size, opt.patch_size, opt.dimXg]) x_pri = tf.placeholder('float32', [opt.patch_num, opt.patch_size, opt.patch_size, opt.dimX]) Trans = tf.placeholder('float32', [opt.dimX, opt.dimXg]) eps1 = tf.placeholder('float32', [opt.num, opt.dimZ]) eps2 = tf.placeholder('float32', [opt.batch_size, opt.dimZ]) RNN_model = rnn_model(opt) outputs_global, outputs_xg = RNN_model.inference(x_low,x_rgb,x_bic) Loss1,Loss2,xh_outputs = RNN_model.generator(eps1,eps2,x_low,x_rgb,x_bic,outputs_global, outputs_xg,Trans) optimizer1 = tf.train.AdamOptimizer(learning_rate=0.001).minimize(-Loss1) optimizer = tf.train.AdamOptimizer(learning_rate=0.001).minimize(-Loss1-Loss2) # joint_loss = -Loss1-Loss2 # joint_tvars = tf.trainable_variables() # joint_grads, _ = tf.clip_by_global_norm(tf.gradients(joint_loss, joint_tvars), opt.max_grad_norm) # optimizer = tf.train.AdamOptimizer(opt.learning_rate).apply_gradients(zip(joint_grads, joint_tvars)) os.environ["CUDA_VISIBLE_DEVICES"] = "0" saver = tf.train.Saver(max_to_keep=int(opt.Maxiter/opt.step)) graph = tf.get_default_graph() # gpu_options = tf.GPUOptions(per_process_gpu_memory_fraction=0.5) # tf.Graph().as_default() # config = tf.ConfigProto(allow_soft_placement=True, gpu_options = gpu_options) config = tf.ConfigProto() config.gpu_options.allow_growth = True with graph.as_default(), tf.Session(config = config) as sess: sess.run(tf.global_variables_initializer()) print('pretraining ... ...') for i in range(opt.Pretrain): e0 = np.random.normal(0, 1, [opt.num, opt.dimZ]) _, loss1 = sess.run([optimizer1, Loss1], feed_dict={x_low: opt.Xl_2d, eps1: e0}) print("PreIter {}, loss1 = {}".format(i+1, loss1 / opt.num)) if os.path.exists(opt.path + '/params/checkpoint'): saver.restore(sess, opt.path + '/params/model_{}.ckpt'.format(opt.lastTrain)) print('*********load model*********') if not os.path.exists(opt.path): os.mkdir(opt.path) if not os.path.exists(opt.path+'/params'): os.mkdir(opt.path+'/params') index1 = np.arange(0, opt.N1-opt.patch_size, opt.gap) # 0 is included, while N1 is not included if index1[-1] != opt.N1 - opt.patch_size: index1[-1] = opt.N1 - opt.patch_size index2 = np.arange(0, opt.N2-opt.patch_size, opt.gap) # 0 is included, while N1 is not included if index2[-1] != opt.N2 - opt.patch_size: index2[-1] = opt.N2 - opt.patch_size indexList = [] for in1 in index1: for in2 in index2: indexList.append([in1,in2]) x_low_batch = opt.Xl_2d x_bic_batch = np.zeros((opt.patch_num, opt.patch_size, opt.patch_size, opt.dimX), dtype='float32') x_rgb_batch = np.zeros((opt.patch_num, opt.patch_size, opt.patch_size, opt.dimXg), dtype='float32') x_pri_batch = np.zeros((opt.patch_num, opt.patch_size, opt.patch_size, opt.dimX), dtype='float32') for j in range(opt.lastTrain+1, opt.Maxiter+1): print('learning ... ...', j) random.shuffle(indexList) loss_1 = 0 loss_2 = 0 begin = time.time() for m in range(len(indexList)//opt.patch_num): for n in range(opt.patch_num): a = indexList[m * opt.patch_num + n][0] b = indexList[m * opt.patch_num + n][1] x_bic_batch[n, :, :, :] = opt.Xl_bicubic[a:a+opt.patch_size,b:b+opt.patch_size,:] x_rgb_batch[n, :, :, :] = opt.Xg_3d[a:a+opt.patch_size,b:b+opt.patch_size,:] x_pri_batch[n, :, :, :] = Xl_big[a:a+opt.patch_size,b:b+opt.patch_size,:] e1 = np.random.normal(0, 1, [opt.num, opt.dimZ]) e2 = np.random.normal(0, 1, [opt.batch_size, opt.dimZ]) _, loss1, loss2 = sess.run([optimizer, Loss1, Loss1 ], feed_dict={x_low: x_low_batch, x_bic: x_bic_batch, x_rgb: x_rgb_batch, x_pri: x_pri_batch, Trans: opt.Trans_data, eps1: e1, eps2: e2}) loss_1 += loss1 loss_2 += loss2 end = time.time() print("Iteration {}, LOGP = {} ,time = {}".format(j, (loss_1+loss_2)/opt.batch_size, end-begin)) print("---- loss1 = {}, loss2 = {}".format(loss_1/opt.num, loss_2/opt.batch_size)) if j % opt.step == 0: saver.save(sess, opt.path + '/params/model_{}.ckpt'.format(j)) begin = end
5,821
45.951613
108
py
RAFnet
RAFnet-main/rnn_attention_model.py
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ @author: lry """ import tensorflow as tf from tensorflow.contrib import rnn import numpy as np class rnn_model(): def __init__(self,opt): self.opt = opt self.rnn_cell_local = rnn.GRUCell(self.opt.hidden_size_local, name='rnn_cell_local') self.rnn_cell_global_fw = rnn.GRUCell(self.opt.hidden_size_global, name='rnn_cell_global_fw') self.rnn_cell_global_bw = rnn.GRUCell(self.opt.hidden_size_global, name='rnn_cell_global_bw') self.enc_W_q = self.weight_variable([self.opt.hidden_size_global*2 , self.opt.enc_q]) self.enc_W_k = self.weight_variable([self.opt.hidden_size_global*2 , self.opt.enc_k]) self.enc_W_v = self.weight_variable([self.opt.hidden_size_global*2 , self.opt.enc_v]) self.dec_W_q = self.weight_variable([self.opt.gener_hidden_size*2 , self.opt.dec_q]) self.enc_W_k_z = self.weight_variable([self.opt.hidden_size_global , self.opt.enc_k_z]) self.enc_W_v_z = self.weight_variable([self.opt.hidden_size_global , self.opt.enc_v_z]) self.w2 = self.weight_variable([self.opt.f_1, self.opt.f_1, self.opt.dimXg, self.opt.filter_num_1]) self.b2 = self.bias_variable([self.opt.filter_num_1]) self.w3 = self.weight_variable([self.opt.f_2, self.opt.f_2, self.opt.filter_num_1, self.opt.filter_num_2]) self.b3 = self.bias_variable([self.opt.filter_num_2]) self.w4 = self.weight_variable([self.opt.f_3, self.opt.f_3, self.opt.filter_num_2, self.opt.filter_num_3]) self.b4 = self.bias_variable([self.opt.filter_num_3]) self.w5 = self.weight_variable([self.opt.dimX,self.opt.dimXg*self.opt.hidden_size_local]) self.b5 = self.bias_variable([self.opt.dimXg*self.opt.hidden_size_local]) self.rnn_cell_xg_fw = rnn.GRUCell(self.opt.hidden_size_global, name='rnn_cell_xg_fw') self.rnn_cell_xg_bw = rnn.GRUCell(self.opt.hidden_size_global, name='rnn_cell_xg_bw') self.w6 = self.weight_variable([self.opt.hidden_size_global * self.opt.dimXg*2, self.opt.dimZ]) self.b6 = self.bias_variable([self.opt.dimZ]) self.w7 = self.weight_variable([self.opt.hidden_size_global * self.opt.dimXg*2, self.opt.dimZ]) self.b7 = self.bias_variable([self.opt.dimZ]) self.w9 = self.weight_variable([self.opt.dimXg*self.opt.hidden_size_global*2, self.opt.dimZ]) self.b9 = self.bias_variable([self.opt.dimZ]) self.w10 = self.weight_variable([self.opt.dimXg*self.opt.hidden_size_global*2, self.opt.dimZ]) self.b10 = self.bias_variable([self.opt.dimZ]) # self.rnn_cell_gener = rnn.LSTMCell(self.opt.gener_hidden_size, name='LSTM_gener') self.rnn_cell_gener_fw = rnn.LSTMCell(self.opt.gener_hidden_size, name='rnn_cell_gener_fw') self.rnn_cell_gener_bw = rnn.LSTMCell(self.opt.gener_hidden_size, name='rnn_cell_gener_bw') self.w_gener_0 = self.weight_variable([self.opt.dec_q, self.opt.sep[0]]) self.w_gener_1 = self.weight_variable([self.opt.dec_q, self.opt.sep[1]-self.opt.sep[0]]) self.w_gener_2 = self.weight_variable([self.opt.dec_q, self.opt.sep[2]-self.opt.sep[1]]) self.w_gener_3 = self.weight_variable([self.opt.dec_q, self.opt.sep[3]-self.opt.sep[2]]) self.b_gener_0 = self.weight_variable([self.opt.sep[0]]) self.b_gener_1 = self.weight_variable([self.opt.sep[1]-self.opt.sep[0]]) self.b_gener_2 = self.weight_variable([self.opt.sep[2]-self.opt.sep[1]]) self.b_gener_3 = self.weight_variable([self.opt.sep[3]-self.opt.sep[2]]) return def inference(self,x_low,x_rgb,x_bic): sep = self.opt.sep hidden_size_local = self.opt.hidden_size_local outputs_1_xl, state_1_xl = tf.nn.dynamic_rnn(self.rnn_cell_local, inputs=tf.reshape(x_low[:, 0:sep[0]], [self.opt.num, sep[0], 1]), dtype=tf.float32) outputs_2_xl, state_2_xl = tf.nn.dynamic_rnn(self.rnn_cell_local, inputs=tf.reshape(x_low[:, sep[0]:sep[1]], [self.opt.num, sep[1]-sep[0], 1]), dtype=tf.float32) outputs_3_xl, state_3_xl = tf.nn.dynamic_rnn(self.rnn_cell_local, inputs=tf.reshape(x_low[:, sep[1]:sep[2]], [self.opt.num, sep[2]-sep[1], 1]), dtype=tf.float32) outputs_4_xl, state_4_xl = tf.nn.dynamic_rnn(self.rnn_cell_local, inputs=tf.reshape(x_low[:, sep[2]:sep[3]], [self.opt.num, sep[3]-sep[2], 1]), dtype=tf.float32) global_input_xl = tf.transpose(tf.reshape(tf.concat( [outputs_1_xl[:, -1, :], outputs_2_xl[:, -1, :], outputs_3_xl[:, -1, :], outputs_4_xl[:, -1, :]], 1), [self.opt.num, hidden_size_local, self.opt.dimXg]), [0, 2, 1]) outputs_global_xl, state_global_xl = tf.nn.bidirectional_dynamic_rnn(self.rnn_cell_global_fw, self.rnn_cell_global_bw, inputs=global_input_xl, dtype=tf.float32) outputs_global_xl = tf.reshape(tf.concat([outputs_global_xl[0],outputs_global_xl[1]], 2), [self.opt.num, -1]) ############# compute the self-attention of encoder ############## outputs_global_xl_2d = tf.reshape(outputs_global_xl, [self.opt.num * self.opt.dimXg, self.opt.hidden_size_global * 2]) self.enc_xl_query = tf.reshape(tf.matmul(outputs_global_xl_2d, self.enc_W_q),[self.opt.num, self.opt.dimXg, self.opt.enc_q]) self.enc_xl_key = tf.reshape(tf.matmul(outputs_global_xl_2d, self.enc_W_k), [self.opt.num , self.opt.dimXg, self.opt.enc_k]) self.enc_xl_value = tf.reshape(tf.matmul(outputs_global_xl_2d, self.enc_W_v), [self.opt.num , self.opt.dimXg, self.opt.enc_v]) self.att_xl_en = self.qk_Attention(self.enc_xl_query, self.enc_xl_key) outputs_global_xl = tf.reshape(tf.matmul(self.att_xl_en, self.enc_xl_value), [self.opt.num, -1]) # fusion x_bic_reshape = tf.reshape(x_bic, [-1, self.opt.dimX]) # h1 = tf.nn.tanh(self.conv2d(x_bic_reshape, self.w1) + self.b1) outputs_1_xb, state_1_xb = tf.nn.dynamic_rnn(self.rnn_cell_local, inputs=tf.reshape(x_bic_reshape[:, 0:sep[0]], [self.opt.batch_size, sep[0], 1]), dtype=tf.float32) outputs_2_xb, state_2_xb = tf.nn.dynamic_rnn(self.rnn_cell_local, inputs=tf.reshape(x_bic_reshape[:, sep[0]:sep[1]], [self.opt.batch_size, sep[1]-sep[0], 1]), dtype=tf.float32) outputs_3_xb, state_3_xb = tf.nn.dynamic_rnn(self.rnn_cell_local, inputs=tf.reshape(x_bic_reshape[:, sep[1]:sep[2]], [self.opt.batch_size, sep[2]-sep[1], 1]), dtype=tf.float32) outputs_4_xb, state_4_xb = tf.nn.dynamic_rnn(self.rnn_cell_local, inputs=tf.reshape(x_bic_reshape[:, sep[2]:sep[3]], [self.opt.batch_size, sep[3]-sep[2], 1]), dtype=tf.float32) global_input_xb = tf.transpose(tf.reshape(tf.concat( [outputs_1_xb[:, -1, :], outputs_2_xb[:, -1, :], outputs_3_xb[:, -1, :], outputs_4_xb[:, -1, :]], 1), [self.opt.batch_size, hidden_size_local, self.opt.dimXg]), [0, 2, 1]) outputs_global_xb, state_global_xb = tf.nn.bidirectional_dynamic_rnn(self.rnn_cell_global_fw, self.rnn_cell_global_bw, inputs=global_input_xb, dtype=tf.float32) outputs_global_xb = tf.reshape(tf.concat([outputs_global_xb[0],outputs_global_xb[1]], 2), [self.opt.batch_size, -1]) outputs_1_xm = tf.nn.tanh(self.conv2d(x_rgb, self.w2) + self.b2) outputs_2_xm = tf.nn.tanh(self.conv2d(outputs_1_xm, self.w3) + self.b3) outputs_3_xm = tf.nn.tanh(self.conv2d(outputs_2_xm, self.w4) + self.b4) outputs_global_xm = tf.reshape(outputs_3_xm, [self.opt.batch_size, -1]) outputs_global_xh = 0.5 * outputs_global_xb + outputs_global_xm # try adding a parameter ############# compute the self-attention of encoder ############## outputs_global_xh_2d = tf.reshape(outputs_global_xh, [self.opt.batch_size * self.opt.dimXg, self.opt.hidden_size_global * 2]) self.enc_xh_query = tf.reshape(tf.matmul(outputs_global_xh_2d, self.enc_W_q),[self.opt.batch_size, self.opt.dimXg, self.opt.enc_q]) self.enc_xh_key = tf.reshape(tf.matmul(outputs_global_xh_2d, self.enc_W_k), [self.opt.batch_size , self.opt.dimXg, self.opt.enc_k]) self.enc_xh_value = tf.reshape(tf.matmul(outputs_global_xh_2d, self.enc_W_v), [self.opt.batch_size , self.opt.dimXg, self.opt.enc_v]) self.att_xh_en = self.qk_Attention(self.enc_xh_query, self.enc_xh_key) outputs_global_xh = tf.reshape(tf.matmul(self.att_xh_en, self.enc_xh_value), [self.opt.batch_size, -1]) return outputs_global_xl, outputs_global_xh def generator(self, eps1, eps2, x_low, x_rgb, x_bic, outputs_xl, outputs_xg, Trans): Z1_mu = tf.matmul(outputs_xl, self.w6) + self.b6 Z1_log_sigma = 0.5 * (tf.matmul(outputs_xl, self.w7) + self.b7) Z1 = Z1_mu + tf.exp(Z1_log_sigma) * eps1 Z2_mu = tf.matmul(outputs_xg, self.w9) + self.b9 Z2_log_sigma = 0.5 * (tf.matmul(tf.reshape(outputs_xg, [self.opt.batch_size, -1]), self.w10) + self.b10) Z2 = Z2_mu + tf.exp(Z2_log_sigma) * eps2 Z1 = tf.reshape(Z1,[self.opt.num, self.opt.dimXg, -1]) Z2 = tf.reshape(Z2,[self.opt.batch_size, self.opt.dimXg, -1]) ############# compute the key and value of encoder ############## Z1_2d = tf.reshape(Z1, [self.opt.num * self.opt.dimXg, self.opt.hidden_size_global]) self.enc_xl_key_zl = tf.reshape(tf.matmul(Z1_2d, self.enc_W_k_z), [self.opt.num , self.opt.dimXg, self.opt.enc_k_z]) self.enc_xl_value_zl = tf.reshape(tf.matmul(Z1_2d, self.enc_W_v_z), [self.opt.num , self.opt.dimXg, self.opt.enc_v_z]) ############# compute the key and value of xb encoder ############## Z2_2d = tf.reshape(Z2, [self.opt.batch_size * self.opt.dimXg, self.opt.hidden_size_global]) self.enc_xh_key_zh = tf.reshape(tf.matmul(Z2_2d, self.enc_W_k_z), [self.opt.batch_size , self.opt.dimXg, self.opt.enc_k_z]) self.enc_xh_value_zh = tf.reshape(tf.matmul(Z2_2d, self.enc_W_v_z), [self.opt.batch_size , self.opt.dimXg, self.opt.enc_v_z]) outputs_gener_xl, state_gener_xl = tf.nn.bidirectional_dynamic_rnn(self.rnn_cell_gener_fw, self.rnn_cell_gener_bw, inputs=Z1, dtype=tf.float32) outputs_gener_xh, state_gener_xh = tf.nn.bidirectional_dynamic_rnn(self.rnn_cell_gener_fw, self.rnn_cell_gener_bw, inputs=Z2, dtype=tf.float32) outputs_gener_xl = tf.concat([outputs_gener_xl[0],outputs_gener_xl[1]], 2) outputs_gener_xh = tf.concat([outputs_gener_xh[0],outputs_gener_xh[1]], 2) # ############# compute the self-attention of encoder ############## # outputs_gener_xl_2d = tf.reshape(outputs_gener_xl, [self.opt.num * self.opt.dimXg, self.opt.gener_hidden_size * 2]) # self.dec_xl_query = tf.reshape(tf.matmul(outputs_gener_xl_2d, self.dec_W_q),[self.opt.num, self.opt.dimXg, self.opt.dec_q]) # self.dec_xl_key = tf.reshape(tf.matmul(outputs_gener_xl_2d, self.dec_W_k), [self.opt.num , self.opt.dimXg, self.opt.dec_k]) # self.dec_xl_value = tf.reshape(tf.matmul(outputs_gener_xl_2d, self.dec_W_v), [self.opt.num , self.opt.dimXg, self.opt.dec_v]) # self.att_xl_de = self.qk_Attention(self.dec_xl_query, self.dec_xl_key) # output_add_atten_xl = tf.matmul(self.att_xl_de, self.dec_xl_value) # # ############# compute the self-attention of encoder ############## # outputs_gener_xh_2d = tf.reshape(outputs_gener_xh, [self.opt.batch_size * self.opt.dimXg, self.opt.gener_hidden_size * 2]) # self.dec_xh_query = tf.reshape(tf.matmul(outputs_gener_xh_2d, self.dec_W_q),[self.opt.batch_size, self.opt.dimXg, self.opt.dec_q]) # self.dec_xh_key = tf.reshape(tf.matmul(outputs_gener_xh_2d, self.dec_W_k), [self.opt.batch_size , self.opt.dimXg, self.opt.dec_k]) # self.dec_xh_value = tf.reshape(tf.matmul(outputs_gener_xh_2d, self.dec_W_v), [self.opt.batch_size , self.opt.dimXg, self.opt.dec_v]) # self.att_xh_de = self.qk_Attention(self.dec_xh_query, self.dec_xh_key) # output_add_atten_xh = tf.matmul(self.att_xh_de, self.dec_xh_value) gener_xl = tf.reshape(outputs_gener_xl,[self.opt.num * self.opt.dimXg, self.opt.gener_hidden_size*2]) self.dec_xl_query = tf.reshape(tf.matmul(gener_xl, self.dec_W_q),[self.opt.num, self.opt.dimXg, self.opt.dec_q]) self.att_xl_de = self.qk_Attention(self.dec_xl_query, self.enc_xl_key_zl) output_add_atten_xl = tf.matmul(self.att_xl_de, self.enc_xl_value_zl) gener_xh = tf.reshape(outputs_gener_xh,[self.opt.batch_size * self.opt.dimXg, self.opt.gener_hidden_size*2]) self.dec_xh_query = tf.reshape(tf.matmul(gener_xh, self.dec_W_q),[self.opt.batch_size, self.opt.dimXg, self.opt.dec_q]) self.att_xh_de = self.qk_Attention(self.dec_xh_query, self.enc_xh_key_zh) output_add_atten_xh = tf.matmul(self.att_xh_de, self.enc_xh_value_zh) xl_outputs_0 = tf.nn.sigmoid(tf.matmul(tf.reshape(output_add_atten_xl[:,0,:],[self.opt.num,-1]),self.w_gener_0) + self.b_gener_0) xl_outputs_1 = tf.nn.sigmoid(tf.matmul(tf.reshape(output_add_atten_xl[:,1,:],[self.opt.num,-1]),self.w_gener_1) + self.b_gener_1) xl_outputs_2 = tf.nn.sigmoid(tf.matmul(tf.reshape(output_add_atten_xl[:,2,:],[self.opt.num,-1]),self.w_gener_2) + self.b_gener_2) xl_outputs_3 = tf.nn.sigmoid(tf.matmul(tf.reshape(output_add_atten_xl[:,3,:],[self.opt.num,-1]),self.w_gener_3) + self.b_gener_3) xh_outputs_0 = tf.nn.sigmoid(tf.matmul(tf.reshape(output_add_atten_xh[:,0,:],[self.opt.batch_size,-1]),self.w_gener_0) + self.b_gener_0) xh_outputs_1 = tf.nn.sigmoid(tf.matmul(tf.reshape(output_add_atten_xh[:,1,:],[self.opt.batch_size,-1]),self.w_gener_1) + self.b_gener_1) xh_outputs_2 = tf.nn.sigmoid(tf.matmul(tf.reshape(output_add_atten_xh[:,2,:],[self.opt.batch_size,-1]),self.w_gener_2) + self.b_gener_2) xh_outputs_3 = tf.nn.sigmoid(tf.matmul(tf.reshape(output_add_atten_xh[:,3,:],[self.opt.batch_size,-1]),self.w_gener_3) + self.b_gener_3) xl_outputs = tf.concat([xl_outputs_0,xl_outputs_1,xl_outputs_2,xl_outputs_3],1) xh_outputs = tf.concat([xh_outputs_0,xh_outputs_1,xh_outputs_2,xh_outputs_3],1) xg_outputs = tf.matmul(xh_outputs, Trans) KL1, KL2 = self.compute_KL(Z1_mu, Z1_log_sigma, Z2_mu, Z2_log_sigma) logpxlow, logpxrgb = self.compute_likelihood(x_low, xl_outputs, x_rgb, xg_outputs) Loss1 = self.opt.patch_num * (0.001 * KL1 + logpxlow) Loss2 = 0.001 * KL2 + logpxrgb return Loss1, Loss2, xh_outputs def compute_KL(self, Zl_mu, Zl_log_sigma, Zh_mu, Zh_log_sigma): KL1 = 0.5 * tf.reduce_sum(1 + 2 * Zl_log_sigma - Zl_mu ** 2 - tf.exp(2 * Zl_log_sigma)) KL2 = 0.5 * tf.reduce_sum(1 + 2 * Zh_log_sigma - Zh_mu ** 2 - tf.exp(2 * Zh_log_sigma)) # KL2 = 0.5 * tf.reduce_sum(1 + 2*Z2_log_sigma - (Z2_mu-Z2_prior)**2 - tf.exp(2*Z2_log_sigma)) return KL1, KL2 def DOT_Attention(self, outputs, inputs): att = tf.nn.softmax(tf.matmul(outputs, tf.transpose(inputs, [0, 2, 1]))) return att def qk_Attention(self, outputs, inputs): att = tf.nn.softmax(tf.matmul(outputs, tf.transpose(inputs, [0, 2, 1]))/ np.sqrt(self.opt.enc_q)) return att def compute_likelihood(self, x_low,X_low_mu,x_rgb,X_rgb_mu): a0 = tf.Variable(tf.truncated_normal([], 0, self.opt.sigmaInit, dtype=tf.float32)) logpxlow = tf.reduce_sum(- (0.5 * tf.log(2 * np.pi)) - 0.5 * ( (tf.reshape(x_low, [self.opt.num, self.opt.dimX]) - X_low_mu)) ** 2) logpxrgb= tf.reduce_sum(- (0.5 * tf.log(2 * np.pi)) - 0.5 * ( (tf.reshape(x_rgb, [self.opt.batch_size, self.opt.dimXg]) - X_rgb_mu) / tf.exp(a0)) ** 2) - self.opt.dimXg * a0 return logpxlow, logpxrgb def conv2d(self, x, w): return tf.nn.conv2d(x, w, strides=[1, 1, 1, 1], padding='SAME') def weight_variable(self, shape): initial = tf.truncated_normal(shape, stddev=self.opt.sigmaInit, dtype=tf.float32) return tf.Variable(initial) def bias_variable(self, shape): initial = tf.constant(0, shape=shape, dtype=tf.float32) return tf.Variable(initial) def get_xl_groups(self, x_low): ##### seperate the input 200 to 6 groups#### sep = int(self.opt.dimX / self.opt.dimXg) x_group = [] for index1 in range(self.opt.dimXg): if index1 == (self.opt.dimXg - 1): x_local = x_low[:, index1 * sep:] else: x_local = x_low[:, index1 * sep:(index1 + 1) * sep] x_group.append(x_local) return x_group def conv_t(self, x, w, s): return tf.nn.conv2d_transpose(x, w, output_shape=s, strides=[1, 1, 1, 1], padding='SAME')
16,667
63.856031
184
py
RAFnet
RAFnet-main/validation_rnn.py
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ @author: lry """ import tensorflow as tf import numpy as np import time import os import opt_rnn_attention as opt from rnn_attention_model import rnn_model import scipy.io as sio opt.patch_size1 = opt.N1 opt.patch_size2 = opt.N2 opt.patch_num = 1 opt.batch_size = opt.patch_size1 * opt.patch_size2 * opt.patch_num index1 = np.arange(0, opt.N1, opt.scale) index2 = np.arange(0, opt.N2, opt.scale) Xl_big = np.zeros((opt.N1, opt.N2, opt.dimX), dtype='float32') # inputs x_low = tf.placeholder('float32', [opt.num, opt.dimX]) x_bic = tf.placeholder('float32', [opt.patch_num, opt.patch_size1, opt.patch_size2, opt.dimX]) x_rgb = tf.placeholder('float32', [opt.patch_num, opt.patch_size1, opt.patch_size2, opt.dimXg]) x_pri = tf.placeholder('float32', [opt.patch_num, opt.patch_size1, opt.patch_size2, opt.dimX]) Trans = tf.placeholder('float32', [opt.dimX, opt.dimXg]) eps1 = tf.placeholder('float32', [opt.num, opt.dimZ]) eps2 = tf.placeholder('float32', [opt.batch_size, opt.dimZ]) # fusion # x_bic_reshape = tf.reshape(x_bic, [batch_size, 1, dimX, 1]) # w6 = weight_variable([1, f2_1, 1, 1]) # b6 = bias_variable([1]) # h3 = tf.nn.tanh(conv2d(x_bic_reshape, w6) + b6) # h42 = tf.reshape(h41, [batch_size, 1, dimX, 1]) # h43 = 0.5*h3 + h42 RNN_model = rnn_model(opt) outputs_xl, outputs_xg = RNN_model.inference(x_low, x_rgb, x_bic) Loss1, Loss2, xh_outputs = RNN_model.generator(eps1, eps2, x_low, x_rgb, x_bic, outputs_xl, outputs_xg, Trans) # att_xl, att_xh, att_xl_2, att_xh_2 = RNN_model.get_att(eps1, eps2, x_low, x_rgb, x_bic, outputs_xl, outputs_xg, Trans) os.environ["CUDA_VISIBLE_DEVICES"] = "0" saver = tf.train.Saver(max_to_keep=int(opt.Maxiter / opt.step)) graph = tf.get_default_graph() # gpu_options = tf.GPUOptions(per_process_gpu_memory_fraction=0.5) # tf.Graph().as_default() # config = tf.ConfigProto(allow_soft_placement=True, gpu_options = gpu_options) config = tf.ConfigProto() config.gpu_options.allow_growth = True iterations = np.arange(100, opt.Maxiter + opt.step, opt.step) with graph.as_default(), tf.Session(config=config) as sess: for iteration in iterations: if os.path.exists(opt.path + '/params/checkpoint'): saver.restore(sess, opt.path + '/params/model_{}.ckpt'.format(iteration)) print('*********Begin testing*********') else: print('*********The model does not exist!*********') if not os.path.exists(opt.path + '/RecImg'): os.mkdir(opt.path + '/RecImg') if not os.path.exists(opt.path + '/attention'): os.mkdir(opt.path + '/attention') index1 = np.arange(0, opt.N1, opt.patch_size1) index2 = np.arange(0, opt.N2, opt.patch_size2) begin = time.time() for i in range(len(index1)): for j in range(len(index2)): print("processing i = {}, j = {}".format(i, j)) x_bic_batch = opt.Xl_bicubic[index1[i]:index1[i] + opt.patch_size1, index2[j]:index2[j] + opt.patch_size2, :] x_rgb_batch = opt.Xg_3d[index1[i]:index1[i] + opt.patch_size1, index2[j]:index2[j] + opt.patch_size2, :] e1 = np.zeros([opt.num, opt.dimZ]) e2 = np.zeros([opt.batch_size, opt.dimZ]) # x_rec = sess.run( x_rec, att_xl_2_, att_xh_2_=sess.run( [xh_outputs, RNN_model.att_xh_en, RNN_model.att_xh_de], # [xh_outputs], feed_dict={x_low: opt.Xl_2d, x_bic: np.reshape(x_bic_batch, [opt.patch_num, opt.patch_size1, opt.patch_size2, opt.dimX]), x_rgb: np.reshape(x_rgb_batch, [opt.patch_num, opt.patch_size1, opt.patch_size2, opt.dimXg]), Trans: opt.Trans_data, eps1: e1, eps2: e2}) sio.savemat(opt.path + '/attention/attention{}.mat'.format(iteration), { 'att_xl_2': np.reshape(att_xl_2_, [opt.num, opt.dimXg, -1]), 'att_xh_2': np.reshape(att_xh_2_, [opt.batch_size, opt.dimXg, -1])}) sio.savemat(opt.path + '/RecImg/rec_{}.mat'.format(iteration), {'Out': x_rec}) end = time.time()
4,622
47.663158
122
py
CayleyNet
CayleyNet-master/utils.py
import gensim import sklearn, sklearn.datasets import sklearn.naive_bayes, sklearn.linear_model, sklearn.svm, sklearn.neighbors, sklearn.ensemble import matplotlib.pyplot as plt import scipy.sparse import numpy as np import time, re # Helpers to process text documents. class TextDataset(object): def clean_text(self, num='substitute'): # TODO: stemming, lemmatisation for i,doc in enumerate(self.documents): # Digits. if num is 'spell': doc = doc.replace('0', ' zero ') doc = doc.replace('1', ' one ') doc = doc.replace('2', ' two ') doc = doc.replace('3', ' three ') doc = doc.replace('4', ' four ') doc = doc.replace('5', ' five ') doc = doc.replace('6', ' six ') doc = doc.replace('7', ' seven ') doc = doc.replace('8', ' eight ') doc = doc.replace('9', ' nine ') elif num is 'substitute': # All numbers are equal. Useful for embedding (countable words) ? doc = re.sub('(\\d+)', ' NUM ', doc) elif num is 'remove': # Numbers are uninformative (they are all over the place). Useful for bag-of-words ? # But maybe some kind of documents contain more numbers, e.g. finance. # Some documents are indeed full of numbers. At least in 20NEWS. doc = re.sub('[0-9]', ' ', doc) # Remove everything except a-z characters and single space. doc = doc.replace('$', ' dollar ') doc = doc.lower() doc = re.sub('[^a-z]', ' ', doc) doc = ' '.join(doc.split()) # same as doc = re.sub('\s{2,}', ' ', doc) self.documents[i] = doc def vectorize(self, **params): # TODO: count or tf-idf. Or in normalize ? vectorizer = sklearn.feature_extraction.text.CountVectorizer(**params) self.data = vectorizer.fit_transform(self.documents) self.vocab = vectorizer.get_feature_names() assert len(self.vocab) == self.data.shape[1] def data_info(self, show_classes=False): N, M = self.data.shape sparsity = self.data.nnz / N / M * 100 print('N = {} documents, M = {} words, sparsity={:.4f}%'.format(N, M, sparsity)) if show_classes: for i in range(len(self.class_names)): num = sum(self.labels == i) print(' {:5d} documents in class {:2d} ({})'.format(num, i, self.class_names[i])) def show_document(self, i): label = self.labels[i] name = self.class_names[label] try: text = self.documents[i] wc = len(text.split()) except AttributeError: text = None wc = 'N/A' print('document {}: label {} --> {}, {} words'.format(i, label, name, wc)) try: vector = self.data[i,:] for j in range(vector.shape[1]): if vector[0,j] != 0: print(' {:.2f} "{}" ({})'.format(vector[0,j], self.vocab[j], j)) except AttributeError: pass return text def keep_documents(self, idx): """Keep the documents given by the index, discard the others.""" self.documents = [self.documents[i] for i in idx] self.labels = self.labels[idx] self.data = self.data[idx,:] def keep_words(self, idx): """Keep the documents given by the index, discard the others.""" self.data = self.data[:,idx] self.vocab = [self.vocab[i] for i in idx] try: self.embeddings = self.embeddings[idx,:] except AttributeError: pass def remove_short_documents(self, nwords, vocab='selected'): """Remove a document if it contains less than nwords.""" if vocab is 'selected': # Word count with selected vocabulary. wc = self.data.sum(axis=1) wc = np.squeeze(np.asarray(wc)) elif vocab is 'full': # Word count with full vocabulary. wc = np.empty(len(self.documents), dtype=np.int) for i,doc in enumerate(self.documents): wc[i] = len(doc.split()) idx = np.argwhere(wc >= nwords).squeeze() self.keep_documents(idx) return wc def keep_top_words(self, M, Mprint=20): """Keep in the vocaluary the M words who appear most often.""" freq = self.data.sum(axis=0) freq = np.squeeze(np.asarray(freq)) idx = np.argsort(freq)[::-1] idx = idx[:M] self.keep_words(idx) print('most frequent words') for i in range(Mprint): print(' {:3d}: {:10s} {:6d} counts'.format(i, self.vocab[i], freq[idx][i])) return freq[idx] def normalize(self, norm='l1'): """Normalize data to unit length.""" # TODO: TF-IDF. data = self.data.astype(np.float64) self.data = sklearn.preprocessing.normalize(data, axis=1, norm=norm) def embed(self, filename=None, size=100): """Embed the vocabulary using pre-trained vectors.""" if filename: model = gensim.models.Word2Vec.load_word2vec_format(filename, binary=True) size = model.vector_size else: class Sentences(object): def __init__(self, documents): self.documents = documents def __iter__(self): for document in self.documents: yield document.split() model = gensim.models.Word2Vec(Sentences(self.documents), size) self.embeddings = np.empty((len(self.vocab), size)) keep = [] not_found = 0 for i,word in enumerate(self.vocab): try: self.embeddings[i,:] = model[word] keep.append(i) except KeyError: not_found += 1 print('{} words not found in corpus'.format(not_found, i)) self.keep_words(keep) class Text20News(TextDataset): def __init__(self, **params): dataset = sklearn.datasets.fetch_20newsgroups(**params) self.documents = dataset.data self.labels = dataset.target self.class_names = dataset.target_names assert max(self.labels) + 1 == len(self.class_names) N, C = len(self.documents), len(self.class_names) print('N = {} documents, C = {} classes'.format(N, C)) class TextRCV1(TextDataset): def __init__(self, **params): dataset = sklearn.datasets.fetch_rcv1(**params) self.data = dataset.data self.target = dataset.target self.class_names = dataset.target_names assert len(self.class_names) == 103 # 103 categories according to LYRL2004 N, C = self.target.shape assert C == len(self.class_names) print('N = {} documents, C = {} classes'.format(N, C)) def remove_classes(self, keep): ## Construct a lookup table for labels. labels_row = [] labels_col = [] class_lookup = {} for i,name in enumerate(self.class_names): class_lookup[name] = i self.class_names = keep # Index of classes to keep. idx_keep = np.empty(len(keep)) for i,cat in enumerate(keep): idx_keep[i] = class_lookup[cat] self.target = self.target[:,idx_keep] assert self.target.shape[1] == len(keep) def show_doc_per_class(self, print_=False): """Number of documents per class.""" docs_per_class = np.array(self.target.astype(np.uint64).sum(axis=0)).squeeze() print('categories ({} assignments in total)'.format(docs_per_class.sum())) if print_: for i,cat in enumerate(self.class_names): print(' {:5s}: {:6d} documents'.format(cat, docs_per_class[i])) plt.figure(figsize=(17,5)) plt.plot(sorted(docs_per_class[::-1]),'.') def show_classes_per_doc(self): """Number of classes per document.""" classes_per_doc = np.array(self.target.sum(axis=1)).squeeze() plt.figure(figsize=(17,5)) plt.plot(sorted(classes_per_doc[::-1]),'.') def select_documents(self): classes_per_doc = np.array(self.target.sum(axis=1)).squeeze() self.target = self.target[classes_per_doc==1] self.data = self.data[classes_per_doc==1, :] # Convert labels from indicator form to single value. N, C = self.target.shape target = self.target.tocoo() self.labels = target.col assert self.labels.min() == 0 assert self.labels.max() == C - 1 # Bruna and Dropout used 2 * 201369 = 402738 documents. Probably the difference btw v1 and v2. #return classes_per_doc ### Helpers to quantify classifier's quality. def baseline(train_data, train_labels, test_data, test_labels, omit=[]): """Train various classifiers to get a baseline.""" clf, train_accuracy, test_accuracy, train_f1, test_f1, exec_time = [], [], [], [], [], [] clf.append(sklearn.neighbors.KNeighborsClassifier(n_neighbors=10)) clf.append(sklearn.linear_model.LogisticRegression()) clf.append(sklearn.naive_bayes.BernoulliNB(alpha=.01)) clf.append(sklearn.ensemble.RandomForestClassifier()) clf.append(sklearn.naive_bayes.MultinomialNB(alpha=.01)) clf.append(sklearn.linear_model.RidgeClassifier()) clf.append(sklearn.svm.LinearSVC()) for i,c in enumerate(clf): if i not in omit: t_start = time.process_time() c.fit(train_data, train_labels) train_pred = c.predict(train_data) test_pred = c.predict(test_data) train_accuracy.append('{:5.2f}'.format(100*sklearn.metrics.accuracy_score(train_labels, train_pred))) test_accuracy.append('{:5.2f}'.format(100*sklearn.metrics.accuracy_score(test_labels, test_pred))) train_f1.append('{:5.2f}'.format(100*sklearn.metrics.f1_score(train_labels, train_pred, average='weighted'))) test_f1.append('{:5.2f}'.format(100*sklearn.metrics.f1_score(test_labels, test_pred, average='weighted'))) exec_time.append('{:5.2f}'.format(time.process_time() - t_start)) print('Train accuracy: {}'.format(' '.join(train_accuracy))) print('Test accuracy: {}'.format(' '.join(test_accuracy))) print('Train F1 (weighted): {}'.format(' '.join(train_f1))) print('Test F1 (weighted): {}'.format(' '.join(test_f1))) print('Execution time: {}'.format(' '.join(exec_time))) def grid_search(params, grid_params, train_data, train_labels, val_data, val_labels, test_data, test_labels, model): """Explore the hyper-parameter space with an exhaustive grid search.""" params = params.copy() train_accuracy, test_accuracy, train_f1, test_f1 = [], [], [], [] grid = sklearn.grid_search.ParameterGrid(grid_params) print('grid search: {} combinations to evaluate'.format(len(grid))) for grid_params in grid: params.update(grid_params) name = '{}'.format(grid) print('\n\n {} \n\n'.format(grid_params)) m = model(params) m.fit(train_data, train_labels, val_data, val_labels) string, accuracy, f1, loss = m.evaluate(train_data, train_labels) train_accuracy.append('{:5.2f}'.format(accuracy)); train_f1.append('{:5.2f}'.format(f1)) print('train {}'.format(string)) string, accuracy, f1, loss = m.evaluate(test_data, test_labels) test_accuracy.append('{:5.2f}'.format(accuracy)); test_f1.append('{:5.2f}'.format(f1)) print('test {}'.format(string)) print('\n\n') print('Train accuracy: {}'.format(' '.join(train_accuracy))) print('Test accuracy: {}'.format(' '.join(test_accuracy))) print('Train F1 (weighted): {}'.format(' '.join(train_f1))) print('Test F1 (weighted): {}'.format(' '.join(test_f1))) for i,grid_params in enumerate(grid): print('{} --> {} {} {} {}'.format(grid_params, train_accuracy[i], test_accuracy[i], train_f1[i], test_f1[i])) class model_perf(object): def __init__(s): s.names, s.params = set(), {} s.fit_accuracies, s.fit_losses, s.fit_time = {}, {}, {} s.train_accuracy, s.train_f1, s.train_loss = {}, {}, {} s.test_accuracy, s.test_f1, s.test_loss = {}, {}, {} def test(s, model, name, params, train_data, train_labels, val_data, val_labels, test_data, test_labels): s.params[name] = params s.fit_accuracies[name], s.fit_losses[name], s.fit_time[name] = \ model.fit(train_data, train_labels, val_data, val_labels) string, s.train_accuracy[name], s.train_f1[name], s.train_loss[name] = \ model.evaluate(train_data, train_labels) print('train {}'.format(string)) string, s.test_accuracy[name], s.test_f1[name], s.test_loss[name] = \ model.evaluate(test_data, test_labels) print('test {}'.format(string)) s.names.add(name) def show(s, fontsize=None): if fontsize: plt.rc('pdf', fonttype=42) plt.rc('ps', fonttype=42) plt.rc('font', size=fontsize) # controls default text sizes plt.rc('axes', titlesize=fontsize) # fontsize of the axes title plt.rc('axes', labelsize=fontsize) # fontsize of the x any y labels plt.rc('xtick', labelsize=fontsize) # fontsize of the tick labels plt.rc('ytick', labelsize=fontsize) # fontsize of the tick labels plt.rc('legend', fontsize=fontsize) # legend fontsize plt.rc('figure', titlesize=fontsize) # size of the figure title print(' accuracy F1 loss time [ms] name') print('test train test train test train') for name in sorted(s.names): print('{:5.2f} {:5.2f} {:5.2f} {:5.2f} {:.2e} {:.2e} {:3.0f} {}'.format( s.test_accuracy[name], s.train_accuracy[name], s.test_f1[name], s.train_f1[name], s.test_loss[name], s.train_loss[name], s.fit_time[name]*1000, name)) fig, ax = plt.subplots(1, 2, figsize=(15, 5)) for name in sorted(s.names): steps = np.arange(len(s.fit_accuracies[name])) + 1 steps *= s.params[name]['eval_frequency'] ax[0].plot(steps, s.fit_accuracies[name], '.-', label=name) ax[1].plot(steps, s.fit_losses[name], '.-', label=name) ax[0].set_xlim(min(steps), max(steps)) ax[1].set_xlim(min(steps), max(steps)) ax[0].set_xlabel('step') ax[1].set_xlabel('step') ax[0].set_ylabel('validation accuracy') ax[1].set_ylabel('training loss') ax[0].legend(loc='lower right') ax[1].legend(loc='upper right') #fig.savefig('training.pdf')
15,024
44.256024
121
py
CayleyNet
CayleyNet-master/graph.py
import sklearn.metrics import sklearn.neighbors import matplotlib.pyplot as plt import scipy.sparse import scipy.sparse.linalg import scipy.spatial.distance import numpy as np def grid(m, dtype=np.float32): """Return the embedding of a grid graph.""" M = m**2 x = np.linspace(0, 1, m, dtype=dtype) y = np.linspace(0, 1, m, dtype=dtype) xx, yy = np.meshgrid(x, y) z = np.empty((M, 2), dtype) z[:, 0] = xx.reshape(M) z[:, 1] = yy.reshape(M) return z def distance_scipy_spatial(z, k=4, metric='euclidean'): """Compute exact pairwise distances.""" d = scipy.spatial.distance.pdist(z, metric) d = scipy.spatial.distance.squareform(d) # k-NN graph. idx = np.argsort(d)[:, 1:k+1] d.sort() d = d[:, 1:k+1] return d, idx def distance_sklearn_metrics(z, k=4, metric='euclidean'): """Compute exact pairwise distances.""" d = sklearn.metrics.pairwise.pairwise_distances( z, metric=metric, n_jobs=-2) # k-NN graph. idx = np.argsort(d)[:, 1:k+1] d.sort() d = d[:, 1:k+1] return d, idx def distance_lshforest(z, k=4, metric='cosine'): """Return an approximation of the k-nearest cosine distances.""" assert metric is 'cosine' lshf = sklearn.neighbors.LSHForest() lshf.fit(z) dist, idx = lshf.kneighbors(z, n_neighbors=k+1) assert dist.min() < 1e-10 dist[dist < 0] = 0 return dist, idx # TODO: other ANNs s.a. NMSLIB, EFANNA, FLANN, Annoy, sklearn neighbors, PANN def adjacency(dist, idx): """Return the adjacency matrix of a kNN graph.""" M, k = dist.shape assert M, k == idx.shape assert dist.min() >= 0 # Weights. sigma2 = np.mean(dist[:, -1])**2 dist = np.exp(- dist**2 / sigma2) # Weight matrix. I = np.arange(0, M).repeat(k) J = idx.reshape(M*k) V = dist.reshape(M*k) W = scipy.sparse.coo_matrix((V, (I, J)), shape=(M, M)) # No self-connections. W.setdiag(0) # Non-directed graph. bigger = W.T > W W = W - W.multiply(bigger) + W.T.multiply(bigger) assert W.nnz % 2 == 0 assert np.abs(W - W.T).mean() < 1e-10 assert type(W) is scipy.sparse.csr.csr_matrix return W def replace_random_edges(A, noise_level): """Replace randomly chosen edges by random edges.""" M, M = A.shape n = int(noise_level * A.nnz // 2) indices = np.random.permutation(A.nnz//2)[:n] rows = np.random.randint(0, M, n) cols = np.random.randint(0, M, n) vals = np.random.uniform(0, 1, n) assert len(indices) == len(rows) == len(cols) == len(vals) A_coo = scipy.sparse.triu(A, format='coo') assert A_coo.nnz == A.nnz // 2 assert A_coo.nnz >= n A = A.tolil() for idx, row, col, val in zip(indices, rows, cols, vals): old_row = A_coo.row[idx] old_col = A_coo.col[idx] A[old_row, old_col] = 0 A[old_col, old_row] = 0 A[row, col] = 1 A[col, row] = 1 A.setdiag(0) A = A.tocsr() A.eliminate_zeros() return A def laplacian(W, normalized=True): """Return the Laplacian of the weigth matrix.""" # Degree matrix. d = W.sum(axis=0) # Laplacian matrix. if not normalized: D = scipy.sparse.diags(d.A.squeeze(), 0) L = D - W else: d += np.spacing(np.array(0, W.dtype)) d = 1 / np.sqrt(d) D = scipy.sparse.diags(d.A.squeeze(), 0) I = scipy.sparse.identity(d.size, dtype=W.dtype) L = I - D * W * D # assert np.abs(L - L.T).mean() < 1e-9 assert type(L) is scipy.sparse.csr.csr_matrix return L def lmax(L, normalized=True): """Upper-bound on the spectrum.""" if normalized: return 2 else: return scipy.sparse.linalg.eigsh( L, k=1, which='LM', return_eigenvectors=False)[0] def fourier(L, algo='eigh', k=1): """Return the Fourier basis, i.e. the EVD of the Laplacian.""" def sort(lamb, U): idx = lamb.argsort() return lamb[idx], U[:, idx] if algo is 'eig': lamb, U = np.linalg.eig(L.toarray()) lamb, U = sort(lamb, U) elif algo is 'eigh': lamb, U = np.linalg.eigh(L.toarray()) elif algo is 'eigs': lamb, U = scipy.sparse.linalg.eigs(L, k=k, which='SM') lamb, U = sort(lamb, U) elif algo is 'eigsh': lamb, U = scipy.sparse.linalg.eigsh(L, k=k, which='SM') return lamb, U def plot_spectrum(L, algo='eig', ymin = 0): """Plot the spectrum of a list of multi-scale Laplacians L.""" # Algo is eig to be sure to get all eigenvalues. plt.figure(figsize=(17, 5)) for i, lap in enumerate(L): lamb, U = fourier(lap, algo) step = 2**i x = range(step//2, L[0].shape[0], step) lb = 'L_{} spectrum in [{:1.2e}, {:1.2e}]'.format(i, lamb[0], lamb[-1]) plt.plot(x, lamb, '.', label=lb) plt.legend(loc='best') plt.xlim(0, L[0].shape[0]) plt.ylim(ymin=ymin) plt.ylabel('Value') plt.xlabel('Eigenvalue ID') def lanczos(L, X, K): """ Given the graph Laplacian and a data matrix, return a data matrix which can be multiplied by the filter coefficients to filter X using the Lanczos polynomial approximation. """ M, N = X.shape assert L.dtype == X.dtype def basis(L, X, K): """ Lanczos algorithm which computes the orthogonal matrix V and the tri-diagonal matrix H. """ a = np.empty((K, N), L.dtype) b = np.zeros((K, N), L.dtype) V = np.empty((K, M, N), L.dtype) V[0, ...] = X / np.linalg.norm(X, axis=0) for k in range(K-1): W = L.dot(V[k, ...]) a[k, :] = np.sum(W * V[k, ...], axis=0) W = W - a[k, :] * V[k, ...] - ( b[k, :] * V[k-1, ...] if k > 0 else 0) b[k+1, :] = np.linalg.norm(W, axis=0) V[k+1, ...] = W / b[k+1, :] a[K-1, :] = np.sum(L.dot(V[K-1, ...]) * V[K-1, ...], axis=0) return V, a, b def diag_H(a, b, K): """Diagonalize the tri-diagonal H matrix.""" H = np.zeros((K*K, N), a.dtype) H[:K**2:K+1, :] = a H[1:(K-1)*K:K+1, :] = b[1:, :] H.shape = (K, K, N) Q = np.linalg.eigh(H.T, UPLO='L')[1] Q = np.swapaxes(Q, 1, 2).T return Q V, a, b = basis(L, X, K) Q = diag_H(a, b, K) Xt = np.empty((K, M, N), L.dtype) for n in range(N): Xt[..., n] = Q[..., n].T.dot(V[..., n]) Xt *= Q[0, :, np.newaxis, :] Xt *= np.linalg.norm(X, axis=0) return Xt # Q[0, ...] def rescale_L(L, lmax=2): """Rescale the Laplacian eigenvalues in [-1,1].""" M, M = L.shape I = scipy.sparse.identity(M, format='csr', dtype=L.dtype) L /= lmax / 2 L -= I return L def chebyshev(L, X, K): """Return T_k X where T_k are the Chebyshev polynomials of order up to K. Complexity is O(KMN).""" M, N = X.shape assert L.dtype == X.dtype # L = rescale_L(L, lmax) # Xt = T @ X: MxM @ MxN. Xt = np.empty((K, M, N), L.dtype) # Xt_0 = T_0 X = I X = X. Xt[0, ...] = X # Xt_1 = T_1 X = L X. if K > 1: Xt[1, ...] = L.dot(X) # Xt_k = 2 L Xt_k-1 - Xt_k-2. for k in range(2, K): Xt[k, ...] = 2 * L.dot(Xt[k-1, ...]) - Xt[k-2, ...] return Xt
7,310
26.90458
79
py
CayleyNet
CayleyNet-master/coarsening.py
import numpy as np import scipy.sparse def coarsen(A, levels, self_connections=False): """ Coarsen a graph, represented by its adjacency matrix A, at multiple levels. """ graphs, parents = metis(A, levels) perms = compute_perm(parents) for i, A in enumerate(graphs): M, M = A.shape if not self_connections: A = A.tocoo() A.setdiag(0) if i < levels: A = perm_adjacency(A, perms[i]) A = A.tocsr() A.eliminate_zeros() graphs[i] = A Mnew, Mnew = A.shape print('Layer {0}: M_{0} = |V| = {1} nodes ({2} added),' '|E| = {3} edges'.format(i, Mnew, Mnew-M, A.nnz//2)) return graphs, perms[0] if levels > 0 else None def metis(W, levels, rid=None): """ Coarsen a graph multiple times using the METIS algorithm. INPUT W: symmetric sparse weight (adjacency) matrix levels: the number of coarsened graphs OUTPUT graph[0]: original graph of size N_1 graph[2]: coarser graph of size N_2 < N_1 graph[levels]: coarsest graph of Size N_levels < ... < N_2 < N_1 parents[i] is a vector of size N_i with entries ranging from 1 to N_{i+1} which indicate the parents in the coarser graph[i+1] nd_sz{i} is a vector of size N_i that contains the size of the supernode in the graph{i} NOTE if "graph" is a list of length k, then "parents" will be a list of length k-1 """ N, N = W.shape if rid is None: rid = np.random.permutation(range(N)) parents = [] degree = W.sum(axis=0) - W.diagonal() graphs = [] graphs.append(W) #supernode_size = np.ones(N) #nd_sz = [supernode_size] #count = 0 #while N > maxsize: for _ in range(levels): #count += 1 # CHOOSE THE WEIGHTS FOR THE PAIRING # weights = ones(N,1) # metis weights weights = degree # graclus weights # weights = supernode_size # other possibility weights = np.array(weights).squeeze() # PAIR THE VERTICES AND CONSTRUCT THE ROOT VECTOR idx_row, idx_col, val = scipy.sparse.find(W) perm = np.argsort(idx_row) rr = idx_row[perm] cc = idx_col[perm] vv = val[perm] cluster_id = metis_one_level(rr,cc,vv,rid,weights) # rr is ordered parents.append(cluster_id) # TO DO # COMPUTE THE SIZE OF THE SUPERNODES AND THEIR DEGREE #supernode_size = full( sparse(cluster_id, ones(N,1) , supernode_size ) ) #print(cluster_id) #print(supernode_size) #nd_sz{count+1}=supernode_size; # COMPUTE THE EDGES WEIGHTS FOR THE NEW GRAPH nrr = cluster_id[rr] ncc = cluster_id[cc] nvv = vv Nnew = cluster_id.max() + 1 # CSR is more appropriate: row,val pairs appear multiple times W = scipy.sparse.csr_matrix((nvv,(nrr,ncc)), shape=(Nnew,Nnew)) W.eliminate_zeros() # Add new graph to the list of all coarsened graphs graphs.append(W) N, N = W.shape # COMPUTE THE DEGREE (OMIT OR NOT SELF LOOPS) degree = W.sum(axis=0) #degree = W.sum(axis=0) - W.diagonal() # CHOOSE THE ORDER IN WHICH VERTICES WILL BE VISTED AT THE NEXT PASS #[~, rid]=sort(ss); # arthur strategy #[~, rid]=sort(supernode_size); # thomas strategy #rid=randperm(N); # metis/graclus strategy ss = np.array(W.sum(axis=0)).squeeze() rid = np.argsort(ss) return graphs, parents # Coarsen a graph given by rr,cc,vv. rr is assumed to be ordered def metis_one_level(rr,cc,vv,rid,weights): nnz = rr.shape[0] N = rr[nnz-1] + 1 marked = np.zeros(N, np.bool) rowstart = np.zeros(N, np.int32) rowlength = np.zeros(N, np.int32) cluster_id = np.zeros(N, np.int32) oldval = rr[0] count = 0 clustercount = 0 for ii in range(nnz): rowlength[count] = rowlength[count] + 1 if rr[ii] > oldval: oldval = rr[ii] rowstart[count+1] = ii count = count + 1 for ii in range(N): tid = rid[ii] if not marked[tid]: wmax = 0.0 rs = rowstart[tid] marked[tid] = True bestneighbor = -1 for jj in range(rowlength[tid]): nid = cc[rs+jj] if marked[nid]: tval = 0.0 else: tval = vv[rs+jj] * (1.0/weights[tid] + 1.0/weights[nid]) if tval > wmax: wmax = tval bestneighbor = nid cluster_id[tid] = clustercount if bestneighbor > -1: cluster_id[bestneighbor] = clustercount marked[bestneighbor] = True clustercount += 1 return cluster_id def compute_perm(parents): """ Return a list of indices to reorder the adjacency and data matrices so that the union of two neighbors from layer to layer forms a binary tree. """ # Order of last layer is random (chosen by the clustering algorithm). indices = [] if len(parents) > 0: M_last = max(parents[-1]) + 1 indices.append(list(range(M_last))) for parent in parents[::-1]: #print('parent: {}'.format(parent)) # Fake nodes go after real ones. pool_singeltons = len(parent) indices_layer = [] for i in indices[-1]: indices_node = list(np.where(parent == i)[0]) assert 0 <= len(indices_node) <= 2 #print('indices_node: {}'.format(indices_node)) # Add a node to go with a singelton. if len(indices_node) is 1: indices_node.append(pool_singeltons) pool_singeltons += 1 #print('new singelton: {}'.format(indices_node)) # Add two nodes as children of a singelton in the parent. elif len(indices_node) is 0: indices_node.append(pool_singeltons+0) indices_node.append(pool_singeltons+1) pool_singeltons += 2 #print('singelton childrens: {}'.format(indices_node)) indices_layer.extend(indices_node) indices.append(indices_layer) # Sanity checks. for i,indices_layer in enumerate(indices): M = M_last*2**i # Reduction by 2 at each layer (binary tree). assert len(indices[0] == M) # The new ordering does not omit an indice. assert sorted(indices_layer) == list(range(M)) return indices[::-1] assert (compute_perm([np.array([4,1,1,2,2,3,0,0,3]),np.array([2,1,0,1,0])]) == [[3,4,0,9,1,2,5,8,6,7,10,11],[2,4,1,3,0,5],[0,1,2]]) def perm_data(x, indices): """ Permute data matrix, i.e. exchange node ids, so that binary unions form the clustering tree. """ if indices is None: return x N, M = x.shape Mnew = len(indices) assert Mnew >= M xnew = np.empty((N, Mnew)) for i,j in enumerate(indices): # Existing vertex, i.e. real data. if j < M: xnew[:,i] = x[:,j] # Fake vertex because of singeltons. # They will stay 0 so that max pooling chooses the singelton. # Or -infty ? else: xnew[:,i] = np.zeros(N) return xnew def perm_adjacency(A, indices): """ Permute adjacency matrix, i.e. exchange node ids, so that binary unions form the clustering tree. """ if indices is None: return A M, M = A.shape Mnew = len(indices) assert Mnew >= M A = A.tocoo() # Add Mnew - M isolated vertices. if Mnew > M: rows = scipy.sparse.coo_matrix((Mnew-M, M), dtype=np.float32) cols = scipy.sparse.coo_matrix((Mnew, Mnew-M), dtype=np.float32) A = scipy.sparse.vstack([A, rows]) A = scipy.sparse.hstack([A, cols]) # Permute the rows and the columns. perm = np.argsort(indices) A.row = np.array(perm)[A.row] A.col = np.array(perm)[A.col] # assert np.abs(A - A.T).mean() < 1e-9 assert type(A) is scipy.sparse.coo.coo_matrix return A
8,239
29.518519
92
py
CayleyNet
CayleyNet-master/data_mnist/__init__.py
0
0
0
py
CG-Detection
CG-Detection-main/train1.py
import math import torch import torch.nn as nn from torch.nn import init import functools from torch.autograd import Variable from torch.optim import lr_scheduler import torch.nn.functional as F from torchvision import transforms, datasets, utils # import matplotlib.pyplot as plt import numpy as np import torch.optim as optim import os import json import time import warnings import torchvision.models as models import torch.utils.model_zoo as model_zoo from PIL import Image from PIL import ImageFile from DualNet import DualNet import pdb ImageFile.LOAD_TRUNCATED_IMAGES = True os.environ['CUDA_VISIBLE_DEVICES'] = '0,1' class Rgb2Gray(object): def __init__(self): '''rgb_image = object.astype(np.float32) if len(rgb_image.shape)!= 3 or rgb_image.shape[2] != 3: raise ValueError("input image is not a rgb image!")''' def __call__(self, img): L_image = img.convert('L') return L_image data_transform = { "train": transforms.Compose( [transforms.CenterCrop(224), transforms.ToTensor() ]), "val": transforms.Compose( [transforms.CenterCrop(224), transforms.ToTensor() ]), "tensor": transforms.Compose( [ transforms.ToTensor() ] ) } image_path = "/data/CG/DsTok/raw" train_dataset = datasets.ImageFolder(root=image_path + '/train', transform=data_transform['train'] # transform1=data_transform['tensor'] ) # print('index of class: ') # print(train_dataset.class_to_idx) # print(train_dataset.imgs[0][0]) train_num = len(train_dataset) train_loader = torch.utils.data.DataLoader(train_dataset, batch_size=64, shuffle=True, drop_last=True) validate_dataset = datasets.ImageFolder(root=image_path + "/val", transform=data_transform['train'] # transform1=data_transform['tensor'] ) val_num = len(validate_dataset) validate_loader = torch.utils.data.DataLoader(validate_dataset, batch_size=64, shuffle=True, drop_last=True) test_dataset = datasets.ImageFolder(root=image_path + '/test', transform=data_transform['val'] # transform1=data_transform['tensor'] ) test_num = len(test_dataset) test_loader = torch.utils.data.DataLoader(test_dataset, batch_size=64, shuffle=True, drop_last=False) # print(xception_modules) save_path = './result/pth/DsTok_raw_DualNet.pth' save_txt = './result/txt/DsTok_raw_DualNet.txt' def train(): net = DualNet() net = nn.DataParallel(net) net = net.cuda() # optimizer = optim.Adam(net.parameters(), lr=0.001) optimizer = optim.SGD(net.parameters(), lr=1e-3, momentum=0.9, weight_decay=1e-3) best_acc = 0.0 new_lr = 1e-3 loss_function = nn.CrossEntropyLoss() for epoch in range(1, 120): if epoch % 20 == 0: new_lr = new_lr * 0.5 optimizer = optim.SGD(net.parameters(), lr=new_lr, momentum=0.9, weight_decay=1e-3) net.train() running_loss = 0.0 running_corrects = 0.0 time_start = time.perf_counter() warnings.filterwarnings('ignore') # count = 0 # if epoch % 50 == 0: print('epoch[%d] ' % epoch) for step, data in enumerate(train_loader, start=0): images, labels = data # optimizer.zero_grad() outputs = net(images.cuda()) preds = torch.max(outputs, dim=1)[1] loss = loss_function(outputs, labels.cuda()) loss.backward() optimizer.step() running_loss += loss.item() running_corrects += (preds == labels.cuda()).sum().item() rate = (step + 1) / len(train_loader) a = "*" * int(rate * 20) b = "." * int((1 - rate) * 20) print("\rtrain loss: {:^3.0f}%[{}->{}]{:.3f}".format(int(rate * 100), a, b, loss), end='') print() print('%f s' % (time.perf_counter() - time_start)) print('train_loss: %.3f train_acc: %.3f' % (running_loss / step, running_corrects / train_num)) f = open(save_txt, mode='a') f.write("epoch[{:.0f}]\ntrain_loss:{:.3f} train_acc:{:.3f}\n".format(epoch, running_loss / step, running_corrects / train_num)) f.close() ########################################### validate ########################################### # net = torch.load('Result2.pth') val_loss = 0.0 net.eval() acc = 0.0 with torch.no_grad(): for step, val_data in enumerate(validate_loader, start=0): val_images, val_labels = val_data outputs= net(val_images.cuda()) loss1 = loss_function(outputs, val_labels.cuda()) result = torch.max(outputs, dim=1)[1] val_loss += loss1.item() acc += (result == val_labels.cuda()).sum().item() val_accurate = acc / val_num print('val_loss: %.3f val_acc: %.3f' % (val_loss / step, val_accurate)) # print() if val_accurate > best_acc: best_acc = val_accurate torch.save(net.state_dict(), save_path) f = open(save_txt, mode='a') f.write("val_loss:{:.3f} val_accurate:{:.3f}\n".format(val_loss / step, val_accurate)) f.close() print('best acc: %.3f' % best_acc) f = open(save_txt, mode='a') f.write(" best_acc:{:.3f}".format(best_acc) + '\n') f.close() print('Finished Training') def test(): net = DualNet() net = nn.DataParallel(net) net.load_state_dict(torch.load(save_path)) net.cuda() net.eval() acc = 0.0 with torch.no_grad(): for test_data in test_loader: test_images, test_labels = test_data outputs = net(test_images.cuda()) result = torch.max(outputs, dim=1)[1] acc += (result == test_labels.cuda()).sum().item() # print('acc of every batch is: %.3f' % (acc/32)) test_accurate = acc / test_num f = open(save_txt, mode='a') f.write(" test_acc:{:.3f}".format(test_accurate) + '\n') f.close() print('acc of val is: %.3f' % (test_accurate)) if __name__ == '__main__': train() test()
6,999
34.532995
110
py
CG-Detection
CG-Detection-main/srm_filter_kernel.py
import numpy as np filter_class_1 = [ np.array([ [1, 0, 0], [0, -1, 0], [0, 0, 0] ], dtype=np.float32), np.array([ [0, 1, 0], [0, -1, 0], [0, 0, 0] ], dtype=np.float32), np.array([ [0, 0, 1], [0, -1, 0], [0, 0, 0] ], dtype=np.float32), np.array([ [0, 0, 0], [1, -1, 0], [0, 0, 0] ], dtype=np.float32), np.array([ [0, 0, 0], [0, -1, 1], [0, 0, 0] ], dtype=np.float32), np.array([ [0, 0, 0], [0, -1, 0], [1, 0, 0] ], dtype=np.float32), np.array([ [0, 0, 0], [0, -1, 0], [0, 1, 0] ], dtype=np.float32), np.array([ [0, 0, 0], [0, -1, 0], [0, 0, 1] ], dtype=np.float32) ] filter_class_2 = [ np.array([ [1, 0, 0], [0, -2, 0], [0, 0, 1] ], dtype=np.float32), np.array([ [0, 1, 0], [0, -2, 0], [0, 1, 0] ], dtype=np.float32), np.array([ [0, 0, 1], [0, -2, 0], [1, 0, 0] ], dtype=np.float32), np.array([ [0, 0, 0], [1, -2, 1], [0, 0, 0] ], dtype=np.float32), ] filter_class_3 = [ np.array([ [-1, 0, 0, 0, 0], [0, 3, 0, 0, 0], [0, 0, -3, 0, 0], [0, 0, 0, 1, 0], [0, 0, 0, 0, 0] ], dtype=np.float32), np.array([ [0, 0, -1, 0, 0], [0, 0, 3, 0, 0], [0, 0, -3, 0, 0], [0, 0, 1, 0, 0], [0, 0, 0, 0, 0] ], dtype=np.float32), np.array([ [0, 0, 0, 0, -1], [0, 0, 0, 3, 0], [0, 0, -3, 0, 0], [0, 1, 0, 0, 0], [0, 0, 0, 0, 0] ], dtype=np.float32), np.array([ [0, 0, 0, 0, 0], [0, 0, 0, 0, 0], [0, 1, -3, 3, -1], [0, 0, 0, 0, 0], [0, 0, 0, 0, 0] ], dtype=np.float32), np.array([ [0, 0, 0, 0, 0], [0, 1, 0, 0, 0], [0, 0, -3, 0, 0], [0, 0, 0, 3, 0], [0, 0, 0, 0, -1] ], dtype=np.float32), np.array([ [0, 0, 0, 0, 0], [0, 0, 1, 0, 0], [0, 0, -3, 0, 0], [0, 0, 3, 0, 0], [0, 0, -1, 0, 0] ], dtype=np.float32), np.array([ [0, 0, 0, 0, 0], [0, 0, 0, 1, 0], [0, 0, -3, 0, 0], [0, 3, 0, 0, 0], [-1, 0, 0, 0, 0] ], dtype=np.float32), np.array([ [0, 0, 0, 0, 0], [0, 0, 0, 0, 0], [-1, 3, -3, 1, 0], [0, 0, 0, 0, 0], [0, 0, 0, 0, 0] ], dtype=np.float32) ] filter_edge_3x3 = [ np.array([ [-1, 2, -1], [2, -4, 2], [0, 0, 0] ], dtype=np.float32), np.array([ [0, 2, -1], [0, -4, 2], [0, 2, -1] ], dtype=np.float32), np.array([ [0, 0, 0], [2, -4, 2], [-1, 2, -1] ], dtype=np.float32), np.array([ [-1, 2, 0], [2, -4, 0], [-1, 2, 0] ], dtype=np.float32), ] filter_edge_5x5 = [ np.array([ [-1, 2, -2, 2, -1], [2, -6, 8, -6, 2], [-2, 8, -12, 8, -2], [0, 0, 0, 0, 0], [0, 0, 0, 0, 0] ], dtype=np.float32), np.array([ [0, 0, -2, 2, -1], [0, 0, 8, -6, 2], [0, 0, -12, 8, -2], [0, 0, 8, -6, 2], [0, 0, -2, 2, -1] ], dtype=np.float32), np.array([ [0, 0, 0, 0, 0], [0, 0, 0, 0, 0], [-2, 8, -12, 8, -2], [2, -6, 8, -6, 2], [-1, 2, -2, 2, -1] ], dtype=np.float32), np.array([ [-1, 2, -2, 0, 0], [2, -6, 8, 0, 0], [-2, 8, -12, 0, 0], [2, -6, 8, 0, 0], [-1, 2, -2, 0, 0] ], dtype=np.float32), ] edge_3x3 = np.array([ [0,-1,0], [-1,4,-1], [0,-1,0] ],dtype=np.float32) square_3x3 = np.array([ [-1, 2, -1], [2, -4, 2], [-1, 2, -1] ], dtype=np.float32) square_5x5 = np.array([ [-1, 2, -2, 2, -1], [2, -6, 8, -6, 2], [-2, 8, -12, 8, -2], [2, -6, 8, -6, 2], [-1, 2, -2, 2, -1] ], dtype=np.float32) all_hpf_list = filter_class_1 + filter_class_2 + filter_class_3 + filter_edge_3x3 + filter_edge_5x5 + [square_3x3, square_5x5] hpf_3x3_list = filter_class_1 + filter_class_2 + filter_edge_3x3 + [square_3x3] hpf_5x5_list = filter_class_3 + filter_edge_5x5 + [square_5x5] normalized_filter_class_2 = [hpf / 2 for hpf in filter_class_2] normalized_filter_class_3 = [hpf / 3 for hpf in filter_class_3] normalized_filter_edge_3x3 = [hpf / 4 for hpf in filter_edge_3x3] normalized_square_3x3 = square_3x3 / 4 normalized_filter_edge_5x5 = [hpf / 12 for hpf in filter_edge_5x5] normalized_square_5x5 = square_5x5 / 12 all_normalized_hpf_list = filter_class_1 + normalized_filter_class_2 + normalized_filter_class_3 + \ normalized_filter_edge_3x3 + normalized_filter_edge_5x5 + [normalized_square_3x3, normalized_square_5x5] #all_normalized_hpf_list = filter_class_1 + filter_class_2 + filter_class_3 + \ # filter_edge_3x3 + filter_edge_5x5 + edge_3x3 + normalized_square_5x5 + [square_3x3, square_5x5] normalized_hpf_3x3_list = filter_class_1 + normalized_filter_class_2 + normalized_filter_edge_3x3 + [normalized_square_3x3] normalized_hpf_5x5_list = normalized_filter_class_3 + normalized_filter_edge_5x5 + [normalized_square_5x5]
4,755
20.232143
126
py
CG-Detection
CG-Detection-main/DualNet.py
import torch import torch.nn as nn import torch.nn.functional as F from srm_filter_kernel import * class SoftPooling2D(torch.nn.Module): def __init__(self,kernel_size,strides=None,padding=0,ceil_mode = False,count_include_pad = True,divisor_override = None): super(SoftPooling2D, self).__init__() self.avgpool = torch.nn.AvgPool2d(kernel_size=kernel_size,stride=strides,padding=padding) def forward(self, x): x_exp = torch.exp(x) x_exp_pool = self.avgpool(x_exp) x = self.avgpool(x_exp*x) return x/x_exp_pool class Block(nn.Module): def __init__(self, in_channels, out_channels): super(Block, self).__init__() self.process = nn.Sequential( nn.Conv2d(in_channels, out_channels, kernel_size=3, stride=1, padding=1, bias=False), nn.BatchNorm2d(out_channels), nn.ReLU(inplace=True), SoftPooling2D(kernel_size=(2,2),strides=(2,2),padding=0) ) def forward(self, x): out = self.process(x) return out class One_Conv(nn.Module): def __init__(self, in_channels): super(One_Conv, self).__init__() self.conv1 = nn.Conv2d(in_channels,in_channels,kernel_size=3,stride=2,padding=1,bias=False) self.bn = nn.BatchNorm2d(in_channels) def forward(self, x): x = self.conv1(x) x = self.bn(x) return x class Pre(nn.Module): def __init__(self): super(Pre, self).__init__() hpf_list = [] for hpf_item in all_normalized_hpf_list: if hpf_item.shape[0] == 3: hpf_item = np.pad(hpf_item, pad_width=((1, 1), (1, 1)), mode='constant') hpf_list.append(hpf_item) # list1 = np.concatenate((all_hpf_list_5, all_hpf_list_5), axis=-2) # hpf_list = np.concatenate((list1, all_hpf_list_5), axis=-2) hpf_weight = nn.Parameter(torch.Tensor(hpf_list).view(30, 1, 5, 5), requires_grad=False) self.hpf = nn.Conv2d(1, 30, kernel_size=5, padding=2, bias=False) self.hpf.weight = hpf_weight def forward(self, x): pre = self.hpf(x) return pre class NoiseModule(nn.Module): def __init__(self): super(NoiseModule, self).__init__() self.pre1 = Pre() self.pre2 = Pre() self.pre3 = Pre() self.block0 = Block(90, 128) self.block1 = Block(128, 128) self.conv1 = One_Conv(128) self.block2 = Block(128, 128) self.conv2 = One_Conv(128) self.block3 = Block(128, 128) self.conv3 = One_Conv(128) self.block4 = Block(128, 128) self.relu = nn.ReLU(inplace=True) self.fc1 = nn.Linear(128, 2) def forward(self, inp): pre1 = self.pre1(inp[:, 0, :, :].view(inp.size(0), 1, 224, 224)) pre2 = self.pre2(inp[:, 1, :, :].view(inp.size(0), 1, 224, 224)) pre3 = self.pre3(inp[:, 2, :, :].view(inp.size(0), 1, 224, 224)) pre = torch.cat((pre1, pre2, pre3), dim=1) x = self.block0(pre) x0 = self.block1(x) x1 = self.conv1(x) x = x0 + x1 x = self.relu(x) x0 = self.block2(x) x1 = self.conv2(x) x = x0 + x1 x = self.relu(x) x0 = self.block3(x) x1 = self.conv3(x) x = x0 + x1 x = self.relu(x) x = self.block4(x) output = F.adaptive_avg_pool2d(x, (1, 1)) output = output.view(output.size(0), -1) output = self.fc1(output) return output class RgbModule(nn.Module): def __init__(self): super(RgbModule, self).__init__() self.block0 = Block(3, 32) self.block1 = Block(32, 64) self.block2 = Block(64, 128) self.block3 = Block(128, 128) self.block4 = Block(128, 128) self.relu = nn.ReLU(inplace=True) self.fc1 = nn.Linear(128, 2) def forward(self, rgb): x = self.block0(rgb) x = self.block1(x) x = self.block2(x) x = self.block3(x) x = self.block4(x) out = F.adaptive_avg_pool2d(x, (1, 1)) out = out.view(out.size(0), -1) out = self.fc1(out) return out class DualNet(nn.Module): def __init__(self): super(DualNet, self).__init__() self.noisemodule = NoiseModule() self.rgbmodule = RgbModule() def forward(self, rgb): noise = self.noisemodule(rgb) rgb = self.rgbmodule(rgb) return noise+rgb
4,463
30.216783
125
py
tiatoolbox
tiatoolbox-master/setup.py
#!/usr/bin/env python """The setup script.""" import sys from pathlib import Path from setuptools import find_packages, setup with open("README.md") as readme_file: readme = readme_file.read() with open("HISTORY.md") as history_file: history = history_file.read() install_requires = [ line for line in Path("requirements/requirements.txt").read_text().splitlines() if line and line[0] not in ("-", "#") ] dependency_links = [] if sys.platform != "darwin": dependency_links = ["https://download.pytorch.org/whl/cu113"] setup_requirements = [ "pytest-runner", ] test_requirements = [ "pytest>=3", ] setup( author="TIA Centre", author_email="[email protected]", python_requires=">=3.8", classifiers=[ "Development Status :: 2 - Pre-Alpha", "Intended Audience :: Developers", "Natural Language :: English", "Programming Language :: Python :: 3", "Programming Language :: Python :: 3.8", "Programming Language :: Python :: 3.9", "Programming Language :: Python :: 3.10", "Programming Language :: Python :: 3.11", ], description="Computational pathology toolbox developed by TIA Centre.", dependency_links=dependency_links, entry_points={ "console_scripts": [ "tiatoolbox=tiatoolbox.cli:main", ], }, install_requires=install_requires, long_description=readme + "\n\n" + history, long_description_content_type="text/markdown", include_package_data=True, keywords="tiatoolbox", name="tiatoolbox", packages=find_packages(include=["tiatoolbox", "tiatoolbox.*"]), setup_requires=setup_requirements, test_suite="tests", tests_require=test_requirements, url="https://github.com/TissueImageAnalytics/tiatoolbox", version="1.4.0", zip_safe=False, )
1,860
25.971014
78
py
tiatoolbox
tiatoolbox-master/benchmarks/annotation_store_alloc.py
"""Simple benchmark to test the memory allocation of annotation stores. This is to be run as a standalone script to avoid inteference from the jupyter notebook environment. Tracking memory allocation in Python is quick tricky and this is not perfect. Two methods are used here for comparison. The first is simply to record the process memory usage before and after the benchmark using psutil. The second is to use the memray tool to track memory allocations. psutil: https://psutil.readthedocs.io/en/latest/ memray: https://github.com/bloomberg/memray (Linux only) Command Line Usage ================== ``` usage: annotation_store_alloc.py [-h] [-S SIZE SIZE] [-s {dict,sqlite}] [-m] optional arguments: -h, --help show this help message and exit -S SIZE SIZE, --size SIZE SIZE The size of the grid of cells to generate. Defaults to (100, 100). -s {dict,sqlite}, --store {dict,sqlite} The type of annotation store to use. Defaults to 'dict'. -m, --in-memory Use an in-memory store. ``` Example Outputs For 100x100 Grid (10,000 Annotations) ===================================================== Peak Memory Usage In MiB (psutil/memray) ---------------------------------------- | store | in-memory | on-disk | | ------ | --------- | --------- | | dict | 21.0/18.0 | 24.2/19.0 | | sqlite | 16.8/6.4 | 6.8/2.7 | ```` dict (in-memory): ################## sqlite (in-memory): ###### sqlite (on-disk): ### ```` File System Usage In MiB (on-disk) ---------------------------------- | store | file-system | | ------ | ----------- | | dict | 9.02 | | sqlite | 5.34 | ``` dict: ######### sqlite: ##### ``` Example Outputs For 200x200 Grid (40,000 Annotations) ===================================================== Peak Memory Usage In MiB (psutil/memray) ---------------------------------------- | store | in-memory | on-disk | | ------ | --------- | --------- | | dict | 74.8/71.4 | 88.9/75.2 | | sqlite | 33.2/23.2 | 9.64/2.7 | ``` dict (mem): ######################################################################## sqlite (mem): ######################## sqlite (dsk): ### ``` File System Usage In MiB (on-disk) ---------------------------------- | store | file-system | | ------ | ----------- | | dict | 35.77 | | sqlite | 21.09 | ``` dict: #################################### sqlite: ##################### ``` """ import argparse import copy import os import re import subprocess import sys import warnings from numbers import Number from pathlib import Path from tempfile import NamedTemporaryFile from typing import Generator, Tuple sys.path.append("../") try: import memray # noqa: E402 except ImportError: class memray: # noqa: N801 No CapWords convention """Dummy memray module for when memray is not installed. A drop-in dummy replacement for the memray module on unsupported platforms. """ dummy: bool = True class Tracker: """Dummy Tracker context manager.""" def __init__(self, *args, **kwargs): warnings.warn("Memray not installed, skipping tracking.", stacklevel=2) def __enter__(self): """Dummy enter method.""" # Intentionally blank. def __exit__(self, *args): """Dummy exit method.""" # Intentionally blank. import numpy as np # noqa: E402 import psutil # noqa: E402 from shapely.geometry import Polygon # noqa: E402 from tqdm import tqdm # noqa: E402 from tiatoolbox.annotation.storage import ( # noqa: E402 Annotation, DictionaryStore, SQLiteStore, ) def cell_polygon( xy: Tuple[Number, Number], n_points: int = 20, radius: Number = 8, noise: Number = 0.01, eccentricity: Tuple[Number, Number] = (1, 3), repeat_first: bool = True, direction: str = "CCW", seed: int = 0, round_coords: bool = False, ) -> Polygon: """Generate a fake cell boundary polygon. Borrowed from tiatoolbox unit tests. Cell boundaries are generated an ellipsoids with randomised eccentricity, added noise, and a random rotation. Args: xy (tuple(int)): The x,y centre point to generate the cell boundary around. n_points (int): Number of points in the boundary. Defaults to 20. radius (float): Radius of the points from the centre. Defaults to 10. noise (float): Noise to add to the point locations. Defaults to 1. eccentricity (tuple(float)): Range of values (low, high) to use for randomised eccentricity. Defaults to (1, 3). repeat_first (bool): Enforce that the last point is equal to the first. direction (str): Ordering of the points. Defaults to "CCW". Valid options are: counter-clockwise "CCW", and clockwise "CW". seed (int): Seed for the random number generator. Defaults to 0. round_coords (bool): Round coordinates to integers. Defaults to False. """ from shapely import affinity rand_state = np.random.get_state() np.random.seed(seed) if repeat_first: n_points -= 1 # Generate points about an ellipse with random eccentricity x, y = xy alpha = np.linspace(0, 2 * np.pi - (2 * np.pi / n_points), n_points) rx = radius * (np.random.rand() + 0.5) ry = np.random.uniform(*eccentricity) * radius - 0.5 * rx x = rx * np.cos(alpha) + x + (np.random.rand(n_points) - 0.5) * noise y = ry * np.sin(alpha) + y + (np.random.rand(n_points) - 0.5) * noise boundary_coords = np.stack([x, y], axis=1).astype(int).tolist() # Copy first coordinate to the end if required if repeat_first: boundary_coords = boundary_coords + [boundary_coords[0]] # Swap direction if direction.strip().lower() == "cw": boundary_coords = boundary_coords[::-1] polygon = Polygon(boundary_coords) # Add random rotation angle = np.random.rand() * 360 polygon = affinity.rotate(polygon, angle, origin="centroid") # Round coordinates to integers if round_coords: polygon = Polygon(np.array(polygon.exterior.coords).round()) # Restore the random state np.random.set_state(rand_state) return polygon # noqa: R504 def cell_grid( size: Tuple[int, int] = (10, 10), spacing: Number = 25 ) -> Generator[Polygon, None, None]: """Generate a grid of cell boundaries.""" return ( cell_polygon(xy=np.multiply(ij, spacing), repeat_first=False, seed=n) for n, ij in enumerate(np.ndindex(size)) ) STORES = { "dict": DictionaryStore, "sqlite": SQLiteStore, } def main( store: str, in_memory: bool, size: Tuple[int, int], ) -> None: """Run the benchmark. Args: store (str): The store to use. Valid options are: - dict: In-memory dictionary store. - sqlite: SQLite store. in_memory (bool): Whether to use in-memory stores. size (tuple(int)): The size of the grid to generate. """ process = psutil.Process(os.getpid()) cls = STORES[store] tracker_filepath = Path(f"{store}-in-mem-{in_memory}.bin".lower()) if tracker_filepath.is_file(): tracker_filepath.unlink() with NamedTemporaryFile(mode="w+") as temp_file, memray.Tracker( tracker_filepath, native_traces=True, follow_fork=True ): io = ":memory:" if in_memory else temp_file # Backing (memory/disk) print(f"Storing {size[0] * size[1]} cells") print(f"Using {cls.__name__}({io})") # Record memory usage before creating the store psutil_m0 = process.memory_info().rss store = cls(io) # Set up a polygon generator grid = cell_grid(size=tuple(size), spacing=35) # Store the grid of polygons for polygon in tqdm(grid, total=size[0] * size[1]): _ = store.append(copy.deepcopy(Annotation(Polygon(polygon)))) # Ensure the store is flushed to disk if using a disk-based store if not in_memory: store.commit() # Print file size in MiB temp_file.seek(0, os.SEEK_END) file_size = temp_file.tell() print(f"File size: {file_size / (1024**2):.2f} MiB") # Print memory usage in MiB psutil_total_mem = process.memory_info().rss - psutil_m0 print(f"Psutil Memory: {psutil_total_mem / (1024**2): .2f} MiB") # Print memory usage in MiB from memray if hasattr(memray, "dummy") and memray.dummy: # Skip memray if not installed return regex = re.compile(r"Total memory allocated:\s*([\d.]+)MB") pipe = subprocess.Popen( [sys.executable, "-m", "memray", "stats", tracker_filepath.name], stdout=subprocess.PIPE, stderr=subprocess.PIPE, ) stdout, stderr = pipe.communicate() if stderr: print(stderr.decode("utf-8")) sys.exit(-1) memray_total_mem_str = regex.search(stdout.decode("utf-8")).group(1).strip() memray_total_mem = float(memray_total_mem_str) print(f"Memray Memory: {memray_total_mem: .2f} MiB") if __name__ == "__main__": PARSER = argparse.ArgumentParser( description=( "Simple benchmark to test the memory allocation of annotation stores." ), ) PARSER.add_argument( "-S", "--size", type=int, nargs=2, default=(100, 100), help="The size of the grid of cells to generate. Defaults to (100, 100).", ) PARSER.add_argument( "-s", "--store", type=str, default="dict", help="The type of annotation store to use. Defaults to 'dict'.", choices=["dict", "sqlite"], ) PARSER.add_argument( "-m", "--in-memory", help="Use an in-memory store.", action="store_true", ) # Parsed CLI arguments ARGS = PARSER.parse_args() # Run the benchmark main( store=ARGS.store, in_memory=ARGS.in_memory, size=ARGS.size, )
10,227
28.994135
87
py
tiatoolbox
tiatoolbox-master/tests/test_stainnorm.py
"""Tests for stain normalization code.""" import pathlib import numpy as np import pytest from click.testing import CliRunner from tiatoolbox import cli from tiatoolbox.data import _local_sample_path, stain_norm_target from tiatoolbox.tools import stainextract from tiatoolbox.tools.stainnorm import get_normalizer from tiatoolbox.utils.misc import imread def test_stain_extract(): """Test stain extraction class.""" stain_matrix = np.array([0.65, 0.70, 0.29]) with pytest.raises( ValueError, match=r"Stain matrix must have shape \(2, 3\) or \(3, 3\)." ): _ = stainextract.CustomExtractor(stain_matrix) def test_vectors_in_right_direction(): """Test if eigenvectors are corrected in the right direction.""" e_vect = np.ones([2, 2]) e_vect = stainextract.vectors_in_correct_direction(e_vectors=e_vect) assert np.all(e_vect == 1) e_vect = np.ones([2, 2]) e_vect[0, 0] = -1 e_vect = stainextract.vectors_in_correct_direction(e_vectors=e_vect) assert np.all(e_vect[:, 1] == 1) assert e_vect[0, 0] == 1 assert e_vect[1, 0] == -1 e_vect = np.ones([2, 2]) e_vect[0, 1] = -1 e_vect = stainextract.vectors_in_correct_direction(e_vectors=e_vect) assert np.all(e_vect[:, 0] == 1) assert e_vect[0, 1] == 1 assert e_vect[1, 1] == -1 def test_h_e_in_correct_order(): """Test if H&E vectors are returned in the correct order.""" v1 = np.ones(3) v2 = np.zeros(3) he = stainextract.h_and_e_in_right_order(v1, v2) assert np.all(he == np.array([v1, v2])) he = stainextract.h_and_e_in_right_order(v1=v2, v2=v1) assert np.all(he == np.array([v1, v2])) def test_dl_output_for_h_and_e(): """Test if correct value for H and E from dictionary learning output is returned.""" dictionary = np.zeros([20, 15]) dictionary1 = stainextract.dl_output_for_h_and_e(dictionary=dictionary) assert np.all(dictionary1 == dictionary) dictionary[1, :] = 1 dictionary2 = stainextract.dl_output_for_h_and_e(dictionary=dictionary) assert dictionary2.shape == (2, 15) assert np.all(dictionary2 == dictionary[[1, 0], :]) def test_reinhard_normalize(source_image, norm_reinhard): """Test for Reinhard colour normalization.""" source_img = imread(pathlib.Path(source_image)) target_img = stain_norm_target() reinhard_img = imread(pathlib.Path(norm_reinhard)) norm = get_normalizer("reinhard") norm.fit(target_img) # get stain information of target image transform = norm.transform(source_img) # transform source image assert np.shape(transform) == np.shape(source_img) assert np.mean(np.absolute(reinhard_img / 255.0 - transform / 255.0)) < 1e-2 def test_custom_normalize(source_image, norm_ruifrok): """Test for stain normalization with user-defined stain matrix.""" source_img = imread(pathlib.Path(source_image)) target_img = stain_norm_target() custom_img = imread(pathlib.Path(norm_ruifrok)) # init class with custom method - test with ruifrok stain matrix stain_matrix = np.array([[0.65, 0.70, 0.29], [0.07, 0.99, 0.11]]) norm = get_normalizer("custom", stain_matrix=stain_matrix) norm.fit(target_img) # get stain information of target image transform = norm.transform(source_img) # transform source image assert np.shape(transform) == np.shape(source_img) assert np.mean(np.absolute(custom_img / 255.0 - transform / 255.0)) < 1e-2 def test_get_normalizer_assertion(): """Test get normalizer assertion error.""" stain_matrix = np.array([[0.65, 0.70, 0.29], [0.07, 0.99, 0.11]]) with pytest.raises( ValueError, match=r"`stain_matrix` is only defined when using `method_name`=\"custom\".", ): _ = get_normalizer("ruifrok", stain_matrix) def test_ruifrok_normalize(source_image, norm_ruifrok): """Test for stain normalization with stain matrix from Ruifrok and Johnston.""" source_img = imread(pathlib.Path(source_image)) target_img = stain_norm_target() ruifrok_img = imread(pathlib.Path(norm_ruifrok)) # init class with Ruifrok & Johnston method norm = get_normalizer("ruifrok") norm.fit(target_img) # get stain information of target image transform = norm.transform(source_img) # transform source image assert np.shape(transform) == np.shape(source_img) assert np.mean(np.absolute(ruifrok_img / 255.0 - transform / 255.0)) < 1e-2 def test_macenko_normalize(source_image, norm_macenko): """Test for stain normalization with stain matrix from Macenko et al.""" source_img = imread(pathlib.Path(source_image)) target_img = stain_norm_target() macenko_img = imread(pathlib.Path(norm_macenko)) # init class with Macenko method norm = get_normalizer("macenko") norm.fit(target_img) # get stain information of target image transform = norm.transform(source_img) # transform source image assert np.shape(transform) == np.shape(source_img) assert np.mean(np.absolute(macenko_img / 255.0 - transform / 255.0)) < 1e-2 def test_vahadane_normalize(source_image, norm_vahadane): """Test for stain normalization with stain matrix from Vahadane et al.""" source_img = imread(pathlib.Path(source_image)) target_img = stain_norm_target() vahadane_img = imread(pathlib.Path(norm_vahadane)) # init class with Vahadane method norm = get_normalizer("vahadane") norm.fit(target_img) # get stain information of target image transform = norm.transform(source_img) # transform source image assert np.shape(transform) == np.shape(source_img) assert np.mean(np.absolute(vahadane_img / 255.0 - transform / 255.0)) < 1e-1 # ------------------------------------------------------------------------------------- # Command Line Interface # ------------------------------------------------------------------------------------- def test_command_line_stainnorm(source_image, tmp_path): """Test for the stain normalization CLI.""" source_img = pathlib.Path(source_image) target_img = _local_sample_path("target_image.png") runner = CliRunner() stainnorm_result = runner.invoke( cli.main, [ "stain-norm", "--img-input", source_img, "--target-input", target_img, "--output-path", str(tmp_path / "stainnorm_output"), "--method", "reinhard", ], ) assert stainnorm_result.exit_code == 0 stainnorm_result = runner.invoke( cli.main, [ "stain-norm", "--img-input", source_img, "--target-input", target_img, "--output-path", str(tmp_path / "stainnorm_output"), "--method", "ruifrok", ], ) assert stainnorm_result.exit_code == 0 stainnorm_result = runner.invoke( cli.main, [ "stain-norm", "--img-input", source_img, "--target-input", target_img, "--output-path", str(tmp_path / "stainnorm_output"), "--method", "macenko", ], ) assert stainnorm_result.exit_code == 0 stainnorm_result = runner.invoke( cli.main, [ "stain-norm", "--img-input", source_img, "--target-input", target_img, "--output-path", str(tmp_path / "stainnorm_output"), "--method", "vahadane", ], ) assert stainnorm_result.exit_code == 0 def test_cli_stainnorm_dir(source_image, tmp_path): """Test directory input for the stain normalization CLI.""" source_img = source_image.parent target_img = _local_sample_path("target_image.png") runner = CliRunner() stainnorm_result = runner.invoke( cli.main, [ "stain-norm", "--img-input", str(source_img), "--target-input", target_img, "--output-path", str(tmp_path / "stainnorm_ouput"), "--method", "vahadane", ], ) assert stainnorm_result.exit_code == 0 def test_cli_stainnorm_file_not_found_error(source_image, tmp_path): """Test file not found error for the stain normalization CLI.""" source_img = pathlib.Path(source_image) target_img = stain_norm_target() runner = CliRunner() stainnorm_result = runner.invoke( cli.main, [ "stain-norm", "--img-input", str(source_img)[:-1], "--target-input", target_img, "--output-path", str(tmp_path / "stainnorm_output"), "--method", "vahadane", ], ) assert stainnorm_result.output == "" assert stainnorm_result.exit_code == 1 assert isinstance(stainnorm_result.exception, FileNotFoundError) def test_cli_stainnorm_method_not_supported(source_image, tmp_path): """Test method not supported for the stain normalization CLI.""" source_img = pathlib.Path(source_image) target_img = stain_norm_target() runner = CliRunner() stainnorm_result = runner.invoke( cli.main, [ "stain-norm", "--img-input", str(source_img), "--target-input", target_img, "--output-path", str(tmp_path / "stainnorm_output"), "--method", "Test", ], ) assert "Invalid value for '--method'" in stainnorm_result.output assert stainnorm_result.exit_code != 0 assert isinstance(stainnorm_result.exception, SystemExit)
9,796
31.121311
88
py
tiatoolbox
tiatoolbox-master/tests/test_docs.py
import ast import doctest import importlib import os import sys from pathlib import Path from typing import List, Optional, Union import pytest @pytest.fixture() def source_files(root_path): """Recursively yield source files from the project.""" ignore = {"__pycache__"} def generator(): for root, dirs, files in os.walk(root_path): files = [f for f in files if f.endswith(".py") and f[0] != "."] dirs[:] = [d for d in dirs if d not in ignore and d[0] != "."] for file in files: yield Path(root, file) return generator() def test_validate_docstring_examples(source_files, root_path): """Test that all docstring examples are valid. Validity checks are: 1. The docstring examples are syntactically valid (can parse an AST). 2. That the imports can be resolved. """ for file in source_files: source = Path(file).read_text() tree = ast.parse(source) parser = doctest.DocTestParser() for node in ast.walk(tree): if not isinstance(node, (ast.FunctionDef, ast.ClassDef)): continue docstring = ast.get_docstring(node) if not docstring: continue doc = parser.get_doctest(docstring, [], node.name, file.name, node.lineno) if not doc.examples: continue # Find how many lines the class/function signature spans # (for accurate line numbers) signature_lines = ( node.body[0].lineno - (node.lineno + len(doc.docstring.splitlines())) - 1 ) doc.lineno += signature_lines - 1 # Check syntax is valid rel_path = file.relative_to(root_path) source_tree = check_ast(doc, rel_path) check_imports(source_tree, doc, rel_path) def check_imports(source_tree: ast.AST, doc: doctest.DocTest, rel_path: Path) -> None: """Check that imports in the source AST are valid.""" if source_tree is None: return imports = [ node for node in ast.walk(source_tree) if isinstance(node, (ast.Import, ast.ImportFrom)) ] for import_node in imports: names = import_node_names(import_node) # Resolve the import for name in names: lineno = doc.lineno + doc.examples[0].lineno + import_node.lineno source = "\n".join(eg.source.strip() for eg in doc.examples) try: spec = importlib.util.find_spec(name) except ModuleNotFoundError as e: raise_source_exception( source, rel_path, import_node.lineno, lineno, import_node.col_offset, e, ) if not (spec or name in sys.modules): raise_source_exception( source, rel_path, import_node.lineno, lineno, import_node.col_offset, ) def raise_source_exception( source: str, rel_path: Path, source_lineno: int, file_lineno: int, source_offset: Optional[int] = None, exception: Optional[Exception] = None, ) -> None: """Raise an exception with the source code and line number highlighted. Args: source (str): The source code. rel_path (Path): The path to the file. source_lineno (int): The line number in the source code snippet. file_lineno (int): The line number in the file. source_offset (int): The offset in the source code snippet. Optional. exception (Exception): The parent exception which was caught. Optional. Raises: SyntaxError: If the source code is invalid. ModuleNotFoundError: If the module cannot be found. """ message = exception.msg if exception else "" source_lines = [ ("...." if n != source_lineno - 1 else " >") + line for n, line in enumerate(source.splitlines()) ] if source_offset: source_lines.insert(source_lineno, f"{' '*(source_offset+3)}^ {message}") annotated_source = "\n".join(source_lines) exception = type(exception) if exception else SyntaxError raise exception( f"{rel_path}:{file_lineno}: {message}\n{annotated_source}" ) from None def import_node_names(import_node: Union[ast.Import, ast.ImportFrom]) -> List[str]: """Get the names being imported by import nodes.""" if isinstance(import_node, ast.ImportFrom): return [import_node.module] if isinstance(import_node, ast.Import): return [name.name for name in import_node.names] raise TypeError("Unknown node type") def check_ast(doc, rel_path) -> ast.AST: """Check that the source syntax is valid.""" source = "".join(eg.source for eg in doc.examples) try: return ast.parse(source, rel_path) except SyntaxError as e: lineno = doc.lineno + doc.examples[0].lineno + e.lineno raise_source_exception(source, rel_path, e.lineno, lineno, e.offset, e) return None
5,305
31.956522
86
py
tiatoolbox
tiatoolbox-master/tests/test_slide_info.py
"""Tests for code related to obtaining slide information.""" import pathlib from click.testing import CliRunner from tiatoolbox import cli # ------------------------------------------------------------------------------------- # Command Line Interface # ------------------------------------------------------------------------------------- def test_command_line_slide_info(sample_all_wsis, tmp_path): """Test the Slide information CLI.""" runner = CliRunner() slide_info_result = runner.invoke( cli.main, [ "slide-info", "--img-input", str(pathlib.Path(sample_all_wsis)), "--mode", "save", "--file-types", "*.ndpi, *.svs", "--output-path", str(tmp_path), "--verbose", "True", ], ) assert slide_info_result.exit_code == 0 assert pathlib.Path(tmp_path, "CMU-1-Small-Region.yaml").exists() assert pathlib.Path(tmp_path, "CMU-1.yaml").exists() assert not pathlib.Path(tmp_path, "test1.yaml").exists() def test_command_line_slide_info_jp2(sample_all_wsis, tmp_path): """Test the Slide information CLI JP2, svs.""" runner = CliRunner() slide_info_result = runner.invoke( cli.main, [ "slide-info", "--img-input", str(pathlib.Path(sample_all_wsis)), "--mode", "save", ], ) output_dir = pathlib.Path(sample_all_wsis).parent assert slide_info_result.exit_code == 0 assert pathlib.Path(output_dir, "meta-data", "CMU-1-Small-Region.yaml").exists() assert pathlib.Path(output_dir, "meta-data", "CMU-1.yaml").exists() assert pathlib.Path(output_dir, "meta-data", "test1.yaml").exists() def test_command_line_slide_info_svs(sample_svs): """Test CLI slide info for single file.""" runner = CliRunner() slide_info_result = runner.invoke( cli.main, [ "slide-info", "--img-input", sample_svs, "--file-types", "*.ndpi, *.svs", "--mode", "show", "--verbose", "True", ], ) assert slide_info_result.exit_code == 0 def test_command_line_slide_info_file_not_found(sample_svs): """Test CLI slide info file not found error.""" runner = CliRunner() slide_info_result = runner.invoke( cli.main, [ "slide-info", "--img-input", str(sample_svs)[:-1], "--file-types", "*.ndpi, *.svs", "--mode", "show", ], ) assert slide_info_result.output == "" assert slide_info_result.exit_code == 1 assert isinstance(slide_info_result.exception, FileNotFoundError) def test_command_line_slide_info_output_none_mode_save(sample_svs): """Test CLI slide info for single file.""" runner = CliRunner() slide_info_result = runner.invoke( cli.main, [ "slide-info", "--img-input", str(sample_svs), "--file-types", "*.ndpi, *.svs", "--mode", "save", "--verbose", "False", ], ) assert slide_info_result.exit_code == 0 assert pathlib.Path( sample_svs.parent, "meta-data", "CMU-1-Small-Region.yaml" ).exists() def test_command_line_slide_info_no_input(): """Test CLI slide info for single file.""" runner = CliRunner() slide_info_result = runner.invoke( cli.main, [ "slide-info", "--file-types", "*.ndpi, *.svs", "--mode", "save", ], ) assert "No image input provided." in slide_info_result.output assert slide_info_result.exit_code != 0
3,874
26.097902
87
py
tiatoolbox
tiatoolbox-master/tests/test_data.py
"""Tests for handling toolbox remote data.""" import os import pathlib import numpy as np import pytest from tiatoolbox.data import _fetch_remote_sample, small_svs, stain_norm_target from tiatoolbox.wsicore.wsireader import WSIReader def test_fetch_sample(tmp_path): """Test for fetching sample via code name.""" # Load a dictionary of sample files data (names and urls) # code name retrieved from TOOLBOX_ROOT/data/remote_samples.yaml tmp_path = pathlib.Path(tmp_path) path = _fetch_remote_sample("stainnorm-source") assert os.path.exists(path) # Test if corrupted WSIReader.open(path) path = _fetch_remote_sample("stainnorm-source", tmp_path) # Assuming Path has no trailing '/' assert os.path.exists(path) assert str(tmp_path) in str(path) # Test not directory path test_path = pathlib.Path(f"{tmp_path}/dummy.npy") np.save(test_path, np.zeros([3, 3, 3])) with pytest.raises(ValueError, match=r".*tmp_path must be a directory.*"): path = _fetch_remote_sample("wsi1_8k_8k_svs", test_path) # Very tiny so temporary hook here also arr = stain_norm_target() assert isinstance(arr, np.ndarray) def test_fetch_sample_skip(tmp_path): """Test skipping fetching sample via code name if already downloaded.""" # Fetch the remote file twice tmp_path = pathlib.Path(tmp_path) path_a = _fetch_remote_sample("wsi1_8k_8k_svs") path_b = _fetch_remote_sample("wsi1_8k_8k_svs") assert os.path.exists(path_a) assert path_a == path_b # Test if corrupted WSIReader.open(path_a) path = _fetch_remote_sample("wsi1_8k_8k_svs", tmp_path) # Assuming Path has no trailing '/' assert os.path.exists(path) assert str(tmp_path) in str(path) # Test not directory path test_path = pathlib.Path(f"{tmp_path}/dummy.npy") np.save(test_path, np.zeros([3, 3, 3])) with pytest.raises(ValueError, match=r".*tmp_path must be a directory.*"): path = _fetch_remote_sample("wsi1_8k_8k_svs", test_path) # Very tiny so temporary hook here also arr = stain_norm_target() assert isinstance(arr, np.ndarray) _ = _fetch_remote_sample("stainnorm-source", tmp_path) def test_small_svs(): """Test for fetching small SVS (CMU-1-Small-Region) sample image.""" path = small_svs() # Check it exists assert path.exists() assert path.is_file() # Test if corrupted WSIReader.open(path)
2,450
31.25
78
py
tiatoolbox
tiatoolbox-master/tests/test_dsl.py
"""Tests for predicate module.""" import json import sqlite3 from numbers import Number from typing import Union import pytest from tiatoolbox.annotation.dsl import ( PY_GLOBALS, SQL_GLOBALS, SQLJSONDictionary, SQLTriplet, json_contains, json_list_sum, py_regexp, ) BINARY_OP_STRINGS = [ "+", "-", "/", "//", "*", "<", ">", "<=", ">=", "==", "!=", "**", "&", "|", "%", ] PREFIX_OP_STRINGS = ["-", "not "] FUNCTION_NAMES = ["abs", "is_none", "is_not_none", "has_key"] SAMPLE_PROPERTIES = { "int": 2, "string": "Hello world!", "null": None, "dict": {"a": 1}, "list": [0, 1, 2, 3], "neg": -1, "bool": True, "nesting": {"fib": [1, 1, 2, 3, 5], "foo": {"bar": "baz"}}, } def test_invalid_sqltriplet(): """Test invalid SQLTriplet.""" with pytest.raises(ValueError, match="Invalid SQLTriplet"): str(SQLTriplet(SQLJSONDictionary())) def test_json_contains(): """Test json_contains function.""" properties = json.dumps(SAMPLE_PROPERTIES) assert json_contains(properties, "int") assert json_contains(json.dumps([1]), 1) assert not json_contains(properties, "foo") def sqlite_eval(query: Union[str, Number]): """Evaluate an SQL predicate on dummy data and return the result. Args: query (Union[str, Number]): SQL predicate to evaluate. Returns: bool: Result of the evaluation. """ with sqlite3.connect(":memory:") as con: con.create_function("REGEXP", 2, py_regexp) con.create_function("REGEXP", 3, py_regexp) con.create_function("LISTSUM", 1, json_list_sum) con.create_function("CONTAINS", 1, json_contains) cur = con.cursor() cur.execute("CREATE TABLE test(properties TEXT)") cur.execute( "INSERT INTO test VALUES(:properties)", {"properties": json.dumps(SAMPLE_PROPERTIES)}, ) con.commit() if isinstance(query, str): assert query.count("(") == query.count(")") assert query.count("[") == query.count("]") cur.execute(f"SELECT {query} FROM test") (result,) = cur.fetchone() return result class TestSQLite: # noqa: PIE798 """Test converting from our DSL to an SQLite backend.""" @staticmethod def test_prop_or_prop(): """Test OR operator between two prop accesses.""" query = eval( # skipcq: PYL-W0123 "(props['int'] == 2) | (props['int'] == 3)", SQL_GLOBALS, {} ) assert str(query) == ( '((json_extract(properties, "$.int") == 2) OR ' '(json_extract(properties, "$.int") == 3))' ) class TestPredicate: """Test predicate statments with various backends.""" scenarios = [ ( "Python", { "eval_globals": PY_GLOBALS, "eval_locals": {"props": SAMPLE_PROPERTIES}, "check": lambda x: x, }, ), ( "SQLite", { "eval_globals": SQL_GLOBALS, "eval_locals": {"props": SQLJSONDictionary()}, "check": sqlite_eval, }, ), ] @staticmethod def test_number_binary_operations(eval_globals, eval_locals, check): """Check that binary operations between ints does not error.""" for op in BINARY_OP_STRINGS: query = f"2 {op} 2" result = eval(query, eval_globals, eval_locals) # skipcq: PYL-W0123 assert isinstance(check(result), Number) @staticmethod def test_property_binary_operations(eval_globals, eval_locals, check): """Check that binary operations between properties does not error.""" for op in BINARY_OP_STRINGS: query = f"props['int'] {op} props['int']" result = eval(query, eval_globals, eval_locals) # skipcq: PYL-W0123 assert isinstance(check(result), Number) @staticmethod def test_r_binary_operations(eval_globals, eval_locals, check): """Test right hand binary operations between numbers and properties.""" for op in BINARY_OP_STRINGS: query = f"2 {op} props['int']" result = eval(query, eval_globals, eval_locals) # skipcq: PYL-W0123 assert isinstance(check(result), Number) @staticmethod def test_number_prefix_operations(eval_globals, eval_locals, check): """Test prefix operations on numbers.""" for op in PREFIX_OP_STRINGS: query = f"{op}1" result = eval(query, eval_globals, eval_locals) # skipcq: PYL-W0123 assert isinstance(check(result), Number) @staticmethod def test_property_prefix_operations(eval_globals, eval_locals, check): """Test prefix operations on properties.""" for op in PREFIX_OP_STRINGS: query = f"{op}props['int']" result = eval(query, eval_globals, eval_locals) # skipcq: PYL-W0123 assert isinstance(check(result), Number) @staticmethod def test_regex_nested_props(eval_globals, eval_locals, check): """Test regex on nested properties.""" query = "props['nesting']['fib'][4]" result = eval(query, eval_globals, eval_locals) # skipcq: PYL-W0123 assert check(result) == 5 @staticmethod def test_regex_str_props(eval_globals, eval_locals, check): """Test regex on string properties.""" query = "regexp('Hello', props['string'])" result = eval(query, eval_globals, eval_locals) # skipcq: PYL-W0123 assert check(result) == "Hello" @staticmethod def test_regex_str_str(eval_globals, eval_locals, check): """Test regex on string and string.""" query = "regexp('Hello', 'Hello world!')" result = eval(query, eval_globals, eval_locals) # skipcq: PYL-W0123 assert check(result) == "Hello" @staticmethod def test_regex_props_str(eval_globals, eval_locals, check): """Test regex on property and string.""" query = "regexp(props['string'], 'Hello world!')" result = eval(query, eval_globals, eval_locals) # skipcq: PYL-W0123 assert check(result) == "Hello world!" @staticmethod def test_regex_ignore_case(eval_globals, eval_locals, check): """Test regex with ignorecase flag.""" query = "regexp('hello', props['string'], re.IGNORECASE)" result = eval(query, eval_globals, eval_locals) # skipcq: PYL-W0123 assert check(result) == "Hello" @staticmethod def test_regex_no_match(eval_globals, eval_locals, check): """Test regex with no match.""" query = "regexp('Yello', props['string'])" result = eval(query, eval_globals, eval_locals) # skipcq: PYL-W0123 assert check(result) is None @staticmethod def test_has_key(eval_globals, eval_locals, check): """Test has_key function.""" query = "has_key(props, 'foo')" result = eval(query, eval_globals, eval_locals) # skipcq: PYL-W0123 assert bool(check(result)) is False @staticmethod def test_is_none(eval_globals, eval_locals, check): """Test is_none function.""" query = "is_none(props['null'])" result = eval(query, eval_globals, eval_locals) # skipcq: PYL-W0123 assert bool(check(result)) is True @staticmethod def test_is_not_none(eval_globals, eval_locals, check): """Test is_not_none function.""" query = "is_not_none(props['int'])" result = eval(query, eval_globals, eval_locals) # skipcq: PYL-W0123 assert bool(check(result)) is True @staticmethod def test_nested_has_key(eval_globals, eval_locals, check): """Test nested has_key function.""" query = "has_key(props['dict'], 'a')" result = eval(query, eval_globals, eval_locals) # skipcq: PYL-W0123 assert bool(check(result)) is True @staticmethod def test_list_sum(eval_globals, eval_locals, check): """Test sum function on a list.""" query = "sum(props['list'])" result = eval(query, eval_globals, eval_locals) # skipcq: PYL-W0123 assert check(result) == sum(SAMPLE_PROPERTIES["list"]) @staticmethod def test_abs(eval_globals, eval_locals, check): """Test abs function.""" query = "abs(props['neg'])" result = eval(query, eval_globals, eval_locals) # skipcq: PYL-W0123 assert check(result) == 1 @staticmethod def test_not(eval_globals, eval_locals, check): """Test not operator.""" query = "not props['bool']" result = eval(query, eval_globals, eval_locals) # skipcq: PYL-W0123 assert bool(check(result)) is False @staticmethod def test_props_int_keys(eval_globals, eval_locals, check): """Test props with int keys.""" query = "props['list'][1]" result = eval(query, eval_globals, eval_locals) # skipcq: PYL-W0123 assert check(result) == 1 @staticmethod def test_props_get(eval_globals, eval_locals, check): """Test props.get function.""" query = "is_none(props.get('foo'))" result = eval(query, eval_globals, eval_locals) # skipcq: PYL-W0123 assert bool(check(result)) is True @staticmethod def test_props_get_default(eval_globals, eval_locals, check): """Test props.get function with default.""" query = "props.get('foo', 42)" result = eval(query, eval_globals, eval_locals) # skipcq: PYL-W0123 assert check(result) == 42 @staticmethod def test_in_list(eval_globals, eval_locals, check): """Test in operator for list.""" query = "1 in props.get('list')" result = eval(query, eval_globals, eval_locals) # skipcq: PYL-W0123 assert bool(check(result)) is True @staticmethod def test_has_key_exception(eval_globals, eval_locals, check): """Test has_key function with exception.""" query = "has_key(1, 'a')" with pytest.raises(TypeError, match="(not iterable)|(Unsupported type)"): _ = eval(query, eval_globals, eval_locals) # skipcq: PYL-W0123 @staticmethod def test_logical_and(eval_globals, eval_locals, check): """Test logical and operator.""" query = "props['bool'] & is_none(props['null'])" result = eval(query, eval_globals, eval_locals) # skipcq: PYL-W0123 assert bool(check(result)) is True @staticmethod def test_logical_or(eval_globals, eval_locals, check): """Test logical or operator.""" query = "props['bool'] | (props['int'] < 2)" result = eval(query, eval_globals, eval_locals) # skipcq: PYL-W0123 assert bool(check(result)) is True @staticmethod def test_nested_logic(eval_globals, eval_locals, check): """Test nested logical operators.""" query = "(props['bool'] | (props['int'] < 2)) & abs(props['neg'])" result = eval(query, eval_globals, eval_locals) # skipcq: PYL-W0123 assert bool(check(result)) is True @staticmethod def test_contains_list(eval_globals, eval_locals, check): """Test contains operator for list.""" query = "1 in props['list']" result = eval(query, eval_globals, eval_locals) # skipcq: PYL-W0123 assert bool(check(result)) is True @staticmethod def test_contains_dict(eval_globals, eval_locals, check): """Test contains operator for dict.""" query = "'a' in props['dict']" result = eval(query, eval_globals, eval_locals) # skipcq: PYL-W0123 assert bool(check(result)) is True @staticmethod def test_contains_str(eval_globals, eval_locals, check): """Test contains operator for str.""" query = "'Hello' in props['string']" result = eval(query, eval_globals, eval_locals) # skipcq: PYL-W0123 assert bool(check(result)) is True
12,040
34.62426
81
py
tiatoolbox
tiatoolbox-master/tests/test_meta_ngff_dataclasses.py
"""Test for NGFF metadata dataclasses.""" from tiatoolbox.wsicore.metadata import ngff class TestDataclassInit: # noqa: PIE798 """Test that initialization paths do not error.""" @staticmethod def test_coordinate_transform_defaults() -> None: """Test :class:`ngff.CoordinateTransform` init with default args.""" ngff.CoordinateTransform() @staticmethod def test_dataset_defaults() -> None: """Test :class:`ngff.Dataset` init with default args.""" ngff.Dataset() @staticmethod def test_dataset() -> None: """Test :class:`ngff.Dataset` init.""" ngff.Dataset( "1", coordinateTransformations=[ngff.CoordinateTransform("scale", scale=0.5)], ) @staticmethod def test_multiscales_defaults() -> None: """Test :class:`ngff.Multiscales` init with default args.""" ngff.Multiscales() @staticmethod def test_omero_defaults() -> None: """Test :class:`ngff.Omero` init with default args.""" ngff.Omero() @staticmethod def test_zattrs_defaults() -> None: """Test :class:`ngff.Zattrs` init with default args.""" ngff.Zattrs()
1,198
28.975
85
py
tiatoolbox
tiatoolbox-master/tests/conftest.py
"""pytest fixtures.""" import pathlib import shutil from pathlib import Path from typing import Callable import pytest from _pytest.tmpdir import TempPathFactory from tiatoolbox.data import _fetch_remote_sample # ------------------------------------------------------------------------------------- # Generate Parameterized Tests # ------------------------------------------------------------------------------------- def pytest_generate_tests(metafunc): """Generate (parameterize) test scenarios. Adapted from pytest documentation. For more information on parameterized tests see: https://docs.pytest.org/en/6.2.x/example/parametrize.html#a-quick-port-of-testscenarios """ # Return if the test is not part of a class or if the class does not # have a scenarios attribute. if metafunc.cls is None or not hasattr(metafunc.cls, "scenarios"): return idlist = [] argvalues = [] for scenario in metafunc.cls.scenarios: idlist.append(scenario[0]) items = scenario[1].items() argnames = [x[0] for x in items] argvalues.append([x[1] for x in items]) metafunc.parametrize(argnames, argvalues, ids=idlist, scope="class") # ------------------------------------------------------------------------------------- # Fixtures # ------------------------------------------------------------------------------------- @pytest.fixture(scope="session") def root_path(request) -> Path: """Return the root path of the project.""" return Path(request.config.rootdir) / "tiatoolbox" @pytest.fixture(scope="session") def remote_sample(tmp_path_factory: TempPathFactory) -> Callable: """Factory fixture for fetching sample files.""" def __remote_sample(key: str) -> pathlib.Path: """Wrapper around tiatoolbox.data._fetch_remote_sample for tests.""" return _fetch_remote_sample(key, tmp_path_factory.mktemp("data")) return __remote_sample @pytest.fixture(scope="session") def sample_ndpi(remote_sample) -> pathlib.Path: """Sample pytest fixture for ndpi images. Download ndpi image for pytest. """ return remote_sample("ndpi-1") @pytest.fixture(scope="session") def sample_ndpi2(remote_sample) -> pathlib.Path: """Sample pytest fixture for ndpi images. Download ndpi image for pytest. Collected from doi:10.5072/zenodo.219445 """ return remote_sample("ndpi-2") @pytest.fixture(scope="session") def sample_svs(remote_sample) -> pathlib.Path: """Sample pytest fixture for svs images. Download svs image for pytest. """ return remote_sample("svs-1-small") @pytest.fixture(scope="session") def sample_ome_tiff(remote_sample) -> pathlib.Path: """Sample pytest fixture for ome-tiff (brightfield pyramid) images. Download ome-tiff image for pytest. """ return remote_sample("ome-brightfield-pyramid-1-small") @pytest.fixture(scope="session") def sample_jp2(remote_sample) -> pathlib.Path: """Sample pytest fixture for JP2 images. Download jp2 image for pytest. """ return remote_sample("jp2-omnyx-1") @pytest.fixture(scope="session") def sample_all_wsis(sample_ndpi, sample_svs, sample_jp2, tmpdir_factory): """Sample wsi(s) of all types supported by tiatoolbox.""" dir_path = pathlib.Path(tmpdir_factory.mktemp("data")) try: dir_path.joinpath(sample_ndpi.name).symlink_to(sample_ndpi) dir_path.joinpath(sample_svs.name).symlink_to(sample_svs) dir_path.joinpath(sample_jp2.name).symlink_to(sample_jp2) except OSError: shutil.copy(sample_ndpi, dir_path.joinpath(sample_ndpi.name)) shutil.copy(sample_svs, dir_path.joinpath(sample_svs.name)) shutil.copy(sample_jp2, dir_path.joinpath(sample_jp2.name)) return dir_path @pytest.fixture(scope="session") def sample_all_wsis2(sample_ndpi2, sample_svs, sample_jp2, tmpdir_factory): """Sample wsi(s) of all types supported by tiatoolbox. Adds sample fluorescence ndpi image. """ dir_path = pathlib.Path(tmpdir_factory.mktemp("data")) try: dir_path.joinpath(sample_ndpi2.name).symlink_to(sample_ndpi2) dir_path.joinpath(sample_svs.name).symlink_to(sample_svs) dir_path.joinpath(sample_jp2.name).symlink_to(sample_jp2) except OSError: shutil.copy(sample_ndpi2, dir_path.joinpath(sample_ndpi2.name)) shutil.copy(sample_svs, dir_path.joinpath(sample_svs.name)) shutil.copy(sample_jp2, dir_path.joinpath(sample_jp2.name)) return dir_path @pytest.fixture(scope="session") def source_image(remote_sample) -> pathlib.Path: """Sample pytest fixture for source image. Download stain normalization source image for pytest. """ return remote_sample("stainnorm-source") @pytest.fixture(scope="session") def norm_macenko(remote_sample) -> pathlib.Path: """Sample pytest fixture for norm_macenko image. Download norm_macenko image for pytest. """ return remote_sample("stainnorm-target-macenko") @pytest.fixture(scope="session") def norm_reinhard(remote_sample) -> pathlib.Path: """Sample pytest fixture for norm_reinhard image. Download norm_reinhard image for pytest. """ return remote_sample("stainnorm-target-reinhard") @pytest.fixture(scope="session") def norm_ruifrok(remote_sample) -> pathlib.Path: """Sample pytest fixture for norm_ruifrok image. Download norm_ruifrok image for pytest. """ return remote_sample("stainnorm-target-ruifrok") @pytest.fixture(scope="session") def norm_vahadane(remote_sample) -> pathlib.Path: """Sample pytest fixture for norm_vahadane image. Download norm_vahadane image for pytest. """ return remote_sample("stainnorm-target-vahadane") @pytest.fixture(scope="session") def sample_visual_fields( source_image, norm_ruifrok, norm_reinhard, norm_macenko, norm_vahadane, tmpdir_factory, ): """Sample visual fields(s) of all types supported by tiatoolbox.""" dir_path = pathlib.Path(tmpdir_factory.mktemp("data")) try: dir_path.joinpath(source_image.name).symlink_to(source_image) dir_path.joinpath(norm_ruifrok.name).symlink_to(norm_ruifrok) dir_path.joinpath(norm_reinhard.name).symlink_to(norm_reinhard) dir_path.joinpath(norm_macenko.name).symlink_to(norm_macenko) dir_path.joinpath(norm_vahadane.name).symlink_to(norm_vahadane) except OSError: shutil.copy(source_image, dir_path.joinpath(source_image.name)) shutil.copy(norm_ruifrok, dir_path.joinpath(norm_ruifrok.name)) shutil.copy(norm_reinhard, dir_path.joinpath(norm_reinhard.name)) shutil.copy(norm_macenko, dir_path.joinpath(norm_macenko.name)) shutil.copy(norm_vahadane, dir_path.joinpath(norm_vahadane.name)) return dir_path @pytest.fixture(scope="session") def patch_extr_vf_image(remote_sample) -> pathlib.Path: """Sample pytest fixture for a visual field image. Download TCGA-HE-7130-01Z-00-DX1 image for pytest. """ return remote_sample("patch-extraction-vf") @pytest.fixture(scope="session") def patch_extr_csv(remote_sample) -> pathlib.Path: """Sample pytest fixture for sample patch extraction csv. Download sample patch extraction csv for pytest. """ return remote_sample("patch-extraction-csv") @pytest.fixture(scope="session") def patch_extr_json(remote_sample) -> pathlib.Path: """Sample pytest fixture for sample patch extraction json. Download sample patch extraction json for pytest. """ return remote_sample("patch-extraction-csv") @pytest.fixture(scope="session") def patch_extr_npy(remote_sample) -> pathlib.Path: """Sample pytest fixture for sample patch extraction npy. Download sample patch extraction npy for pytest. """ return remote_sample("patch-extraction-npy") @pytest.fixture(scope="session") def patch_extr_csv_noheader(remote_sample) -> pathlib.Path: """Sample pytest fixture for sample patch extraction noheader csv. Download sample patch extraction noheader csv for pytest. """ return remote_sample("patch-extraction-csv-noheader") @pytest.fixture(scope="session") def patch_extr_2col_json(remote_sample) -> pathlib.Path: """Sample pytest fixture for sample patch extraction 2col json. Download sample patch extraction 2col json for pytest. """ return remote_sample("patch-extraction-2col-json") @pytest.fixture(scope="session") def patch_extr_2col_npy(remote_sample) -> pathlib.Path: """Sample pytest fixture for sample patch extraction 2col npy. Download sample patch extraction 2col npy for pytest. """ return remote_sample("patch-extraction-2col-npy") @pytest.fixture(scope="session") def patch_extr_jp2_csv(remote_sample) -> pathlib.Path: """Sample pytest fixture for sample patch extraction jp2 csv. Download sample patch extraction jp2 csv for pytest. """ return remote_sample("patch-extraction-jp2-csv") @pytest.fixture(scope="session") def patch_extr_jp2_read(remote_sample) -> pathlib.Path: """Sample pytest fixture for sample patch extraction jp2 read npy. Download sample patch extraction jp2 read npy for pytest. """ return remote_sample("patch-extraction-jp2-read-npy") @pytest.fixture(scope="session") def patch_extr_npy_read(remote_sample) -> pathlib.Path: """Sample pytest fixture for sample patch extraction read npy. Download sample patch extraction read npy for pytest. """ return remote_sample("patch-extraction-read-npy") @pytest.fixture(scope="session") def patch_extr_svs_csv(remote_sample) -> pathlib.Path: """Sample pytest fixture for sample patch extraction svs csv. Download sample patch extraction svs csv for pytest. """ return remote_sample("patch-extraction-svs-csv") @pytest.fixture(scope="session") def patch_extr_svs_header(remote_sample) -> pathlib.Path: """Sample pytest fixture for sample patch extraction svs_header csv. Download sample patch extraction svs_header csv for pytest. """ return remote_sample("patch-extraction-svs-header-csv") @pytest.fixture(scope="session") def patch_extr_svs_npy_read(remote_sample) -> pathlib.Path: """Sample pytest fixture for sample patch extraction svs_read npy. Download sample patch extraction svs_read npy for pytest. """ return remote_sample("patch-extraction-svs-read-npy") @pytest.fixture(scope="session") def sample_patch1(remote_sample) -> pathlib.Path: """Sample pytest fixture for sample patch 1. Download sample patch 1 (Kather100K) for pytest. """ return remote_sample("sample-patch-1") @pytest.fixture(scope="session") def sample_patch2(remote_sample) -> pathlib.Path: """Sample pytest fixture for sample patch 2. Download sample patch 2 (Kather100K) for pytest. """ return remote_sample("sample-patch-2") @pytest.fixture(scope="session") def sample_patch3(remote_sample) -> pathlib.Path: """Sample pytest fixture for sample patch 3. Download sample patch 3 (PCam) for pytest. """ return remote_sample("sample-patch-3") @pytest.fixture(scope="session") def sample_patch4(remote_sample) -> pathlib.Path: """Sample pytest fixture for sample patch 4. Download sample patch 4 (PCam) for pytest. """ return remote_sample("sample-patch-4") @pytest.fixture(scope="session") def dir_sample_patches(sample_patch1, sample_patch2, tmpdir_factory): """Directory of sample image patches for testing.""" dir_path = pathlib.Path(tmpdir_factory.mktemp("data")) try: dir_path.joinpath(sample_patch1.name).symlink_to(sample_patch2) dir_path.joinpath(sample_patch2.name).symlink_to(sample_patch2) except OSError: shutil.copy(sample_patch1, dir_path.joinpath(sample_patch1.name)) shutil.copy(sample_patch2, dir_path.joinpath(sample_patch2.name)) return dir_path @pytest.fixture(scope="session") def sample_wsi_dict(remote_sample): """Sample pytest fixture for torch wsi dataset. Download svs image for pytest. """ file_names = [ "wsi1_8k_8k_svs", "wsi1_8k_8k_jp2", "wsi1_8k_8k_jpg", "wsi2_4k_4k_svs", "wsi2_4k_4k_jp2", "wsi2_4k_4k_jpg", "wsi2_4k_4k_msk", "wsi2_4k_4k_pred", "wsi3_20k_20k_svs", "wsi4_4k_4k_svs", "wsi3_20k_20k_pred", "wsi4_4k_4k_pred", ] return {name: remote_sample(name) for name in file_names} @pytest.fixture(scope="session") def fixed_image(remote_sample) -> pathlib.Path: """Sample pytest fixture for fixed image. Download fixed image for pytest. """ return remote_sample("fixed_image") @pytest.fixture(scope="session") def moving_image(remote_sample) -> pathlib.Path: """Sample pytest fixture for moving image. Download moving image for pytest. """ return remote_sample("moving_image") @pytest.fixture(scope="session") def dfbr_features(remote_sample) -> pathlib.Path: """Sample pytest fixture for DFBR features. Download features used by Deep Feature Based Registration (DFBR) method for pytest. """ return remote_sample("dfbr_features") @pytest.fixture(scope="session") def fixed_mask(remote_sample) -> pathlib.Path: """Sample pytest fixture for fixed mask. Download fixed mask for pytest. """ return remote_sample("fixed_mask") @pytest.fixture(scope="session") def moving_mask(remote_sample) -> pathlib.Path: """Sample pytest fixture for moving mask. Download moving mask for pytest. """ return remote_sample("moving_mask")
13,658
29.01978
91
py
tiatoolbox
tiatoolbox-master/tests/test_patch_extraction.py
"""Tests for code related to patch extraction.""" import pathlib import numpy as np import pytest from tiatoolbox.tools import patchextraction from tiatoolbox.tools.patchextraction import PatchExtractor from tiatoolbox.utils import misc from tiatoolbox.utils.exceptions import FileNotSupported, MethodNotSupported from tiatoolbox.wsicore.wsireader import ( OmnyxJP2WSIReader, OpenSlideWSIReader, VirtualWSIReader, ) def read_points_patches( input_img, locations_list, patch_size=(20, 20), units="level", resolution=0.0, item=2, ): """Read patches with the help of PointsPatchExtractor using different formats.""" patches = patchextraction.get_patch_extractor( input_img=input_img, locations_list=locations_list, method_name="point", patch_size=patch_size, units=units, resolution=resolution, pad_mode="constant", pad_constant_values=255, ) data = np.empty([3, patch_size[0], patch_size[1], 3]) try: data[0] = next(patches) except StopIteration: raise StopIteration("Index out of bounds.") try: data[1] = next(patches) except StopIteration: raise StopIteration("Index out of bounds.") data[2] = patches[item] patches.n = 1870 with pytest.raises(StopIteration): # skipcq next(patches) with pytest.raises(IndexError): print(patches[1870]) with pytest.raises(TypeError): print(patches[1.0]) return data def test_patch_extractor(source_image): """Test base class patch extractor.""" input_img = misc.imread(pathlib.Path(source_image)) patches = patchextraction.PatchExtractor(input_img=input_img, patch_size=(20, 20)) next_patches = iter(patches) assert next_patches.n == 0 def test_get_patch_extractor(source_image, patch_extr_csv): """Test get_patch_extractor returns the right object.""" input_img = misc.imread(pathlib.Path(source_image)) locations_list = pathlib.Path(patch_extr_csv) points = patchextraction.get_patch_extractor( input_img=input_img, locations_list=locations_list, method_name="point", patch_size=(200, 200), ) assert isinstance(points, patchextraction.PointsPatchExtractor) assert len(points) == 1860 sliding_window = patchextraction.get_patch_extractor( input_img=input_img, method_name="slidingwindow", patch_size=(200, 200), ) assert isinstance(sliding_window, patchextraction.SlidingWindowPatchExtractor) with pytest.raises(MethodNotSupported): patchextraction.get_patch_extractor("unknown") def test_points_patch_extractor_image_format( sample_svs, sample_jp2, source_image, patch_extr_csv ): """Test PointsPatchExtractor returns the right object.""" file_parent_dir = pathlib.Path(__file__).parent locations_list = pathlib.Path(patch_extr_csv) points = patchextraction.get_patch_extractor( input_img=pathlib.Path(source_image), locations_list=locations_list, method_name="point", patch_size=(200, 200), ) assert isinstance(points.wsi, VirtualWSIReader) points = patchextraction.get_patch_extractor( input_img=pathlib.Path(sample_svs), locations_list=locations_list, method_name="point", patch_size=(200, 200), ) assert isinstance(points.wsi, OpenSlideWSIReader) points = patchextraction.get_patch_extractor( input_img=pathlib.Path(sample_jp2), locations_list=locations_list, method_name="point", patch_size=(200, 200), ) assert isinstance(points.wsi, OmnyxJP2WSIReader) false_image = pathlib.Path(file_parent_dir.joinpath("data/source_image.test")) with pytest.raises(FileNotSupported): _ = patchextraction.get_patch_extractor( input_img=false_image, locations_list=locations_list, method_name="point", patch_size=(200, 200), ) def test_points_patch_extractor( patch_extr_vf_image, patch_extr_npy_read, patch_extr_csv, patch_extr_npy, patch_extr_2col_npy, patch_extr_json, patch_extr_csv_noheader, ): """Test PointsPatchExtractor for VirtualWSIReader.""" input_img = pathlib.Path(patch_extr_vf_image) saved_data = np.load(str(pathlib.Path(patch_extr_npy_read))) locations_list = pathlib.Path(patch_extr_csv) data = read_points_patches(input_img, locations_list, item=23) assert np.all(data == saved_data) locations_list = pathlib.Path(patch_extr_npy) data = read_points_patches(input_img, locations_list, item=23) assert np.all(data == saved_data) locations_list = pathlib.Path(patch_extr_2col_npy) data = read_points_patches(input_img, locations_list, item=23) assert np.all(data == saved_data) locations_list = pathlib.Path(patch_extr_json) data = read_points_patches(input_img, locations_list, item=23) assert np.all(data == saved_data) locations_list = pathlib.Path(patch_extr_csv_noheader) data = read_points_patches(input_img, locations_list, item=23) assert np.all(data == saved_data) def test_points_patch_extractor_svs( sample_svs, patch_extr_svs_csv, patch_extr_svs_npy_read ): """Test PointsPatchExtractor for svs image.""" locations_list = pathlib.Path(patch_extr_svs_csv) saved_data = np.load(str(pathlib.Path(patch_extr_svs_npy_read))) data = read_points_patches( pathlib.Path(sample_svs), locations_list, item=2, patch_size=(100, 100), units="power", resolution=2, ) assert np.all(data == saved_data) def test_points_patch_extractor_jp2( sample_jp2, patch_extr_jp2_csv, patch_extr_jp2_read ): """Test PointsPatchExtractor for jp2 image.""" locations_list = pathlib.Path(patch_extr_jp2_csv) saved_data = np.load(str(pathlib.Path(patch_extr_jp2_read))) data = read_points_patches( pathlib.Path(sample_jp2), locations_list, item=2, patch_size=(100, 100), units="power", resolution=2.5, ) assert np.all(data == saved_data) def test_sliding_windowpatch_extractor(patch_extr_vf_image): """Test SlidingWindowPatchExtractor for VF.""" input_img = pathlib.Path(patch_extr_vf_image) stride = (20, 20) patch_size = (200, 200) img = misc.imread(input_img) img_h = img.shape[0] img_w = img.shape[1] coord_list = PatchExtractor.get_coordinates( image_shape=(img_w, img_h), patch_input_shape=patch_size, stride_shape=stride, input_within_bound=True, ) num_patches_img = len(coord_list) img_patches = np.zeros( (num_patches_img, patch_size[1], patch_size[0], 3), dtype=img.dtype ) for i, coord in enumerate(coord_list): start_w, start_h, end_w, end_h = coord img_patches[i, :, :, :] = img[start_h:end_h, start_w:end_w, :] patches = patchextraction.get_patch_extractor( input_img=input_img, method_name="slidingwindow", patch_size=patch_size, resolution=0, units="level", stride=stride, within_bound=True, ) assert np.all(img_patches[0] == patches[0]) img_patches_test = [] for patch in patches: img_patches_test.append(patch) img_patches_test = np.array(img_patches_test) assert np.all(img_patches == img_patches_test) def test_get_coordinates(): """Test get tile coordinates functionality.""" expected_output = np.array( [ [0, 0, 4, 4], [4, 0, 8, 4], ] ) output = PatchExtractor.get_coordinates( image_shape=[9, 6], patch_input_shape=[4, 4], stride_shape=[4, 4], input_within_bound=True, ) assert np.sum(expected_output - output) == 0 expected_output = np.array( [ [0, 0, 4, 4], [0, 4, 4, 8], [4, 0, 8, 4], [4, 4, 8, 8], [8, 0, 12, 4], [8, 4, 12, 8], ] ) output = PatchExtractor.get_coordinates( image_shape=[9, 6], patch_input_shape=[4, 4], stride_shape=[4, 4], input_within_bound=False, ) assert np.sum(expected_output - output) == 0 # test when patch shape is larger than image output = PatchExtractor.get_coordinates( image_shape=[9, 6], patch_input_shape=[9, 9], stride_shape=[9, 9], input_within_bound=False, ) # test when output patch shape is out of bound # but input is in bound input_bounds, output_bounds = PatchExtractor.get_coordinates( image_shape=[9, 6], patch_input_shape=[5, 5], patch_output_shape=[4, 4], stride_shape=[4, 4], output_within_bound=True, input_within_bound=False, ) assert len(input_bounds) == 2 assert len(output_bounds) == 2 # test when patch shape is larger than image output = PatchExtractor.get_coordinates( image_shape=[9, 6], patch_input_shape=[9, 9], stride_shape=[9, 8], input_within_bound=True, ) assert len(output) == 0 # test error input form with pytest.raises(ValueError, match=r"Invalid.*shape.*"): PatchExtractor.get_coordinates( image_shape=[9j, 6], patch_input_shape=[4, 4], stride_shape=[4, 4], input_within_bound=False, ) with pytest.raises(ValueError, match=r"Invalid.*shape.*"): PatchExtractor.get_coordinates( image_shape=[9, 6], patch_input_shape=[4, 4], stride_shape=[4, 4j], input_within_bound=False, ) with pytest.raises(ValueError, match=r"Invalid.*shape.*"): PatchExtractor.get_coordinates( image_shape=[9, 6], patch_input_shape=[4j, 4], stride_shape=[4, 4], input_within_bound=False, ) with pytest.raises(ValueError, match=r"Invalid.*shape.*"): PatchExtractor.get_coordinates( image_shape=[9, 6], patch_input_shape=[4, -1], stride_shape=[4, 4], input_within_bound=False, ) with pytest.raises(ValueError, match=r"Invalid.*shape.*"): PatchExtractor.get_coordinates( image_shape=[9, -6], patch_input_shape=[4, -1], stride_shape=[4, 4], input_within_bound=False, ) with pytest.raises(ValueError, match=r"Invalid.*shape.*"): PatchExtractor.get_coordinates( image_shape=[9, 6, 3], patch_input_shape=[4, 4], stride_shape=[4, 4], input_within_bound=False, ) with pytest.raises(ValueError, match=r"Invalid.*shape.*"): PatchExtractor.get_coordinates( image_shape=[9, 6], patch_input_shape=[4, 4, 3], stride_shape=[4, 4], input_within_bound=False, ) with pytest.raises(ValueError, match=r"Invalid.*shape.*"): PatchExtractor.get_coordinates( image_shape=[9, 6], patch_input_shape=[4, 4], stride_shape=[4, 4, 3], input_within_bound=False, ) with pytest.raises(ValueError, match=r"stride.*> 1.*"): PatchExtractor.get_coordinates( image_shape=[9, 6], patch_input_shape=[4, 4], stride_shape=[0, 0], input_within_bound=False, ) # * invalid shape for output with pytest.raises(ValueError, match=r".*input.*larger.*output.*"): PatchExtractor.get_coordinates( image_shape=[9, 6], stride_shape=[4, 4], patch_input_shape=[2, 2], patch_output_shape=[4, 4], input_within_bound=False, ) with pytest.raises(ValueError, match=r"Invalid.*shape.*"): PatchExtractor.get_coordinates( image_shape=[9, 6], stride_shape=[4, 4], patch_input_shape=[4, 4], patch_output_shape=[2, -2], input_within_bound=False, ) def test_filter_coordinates(): """Test different coordinate filtering functions for patch extraction""" bbox_list = np.array( [ [0, 0, 4, 4], [0, 4, 4, 8], [4, 0, 8, 4], [4, 4, 8, 8], [8, 0, 12, 4], [8, 4, 12, 8], ] ) mask = np.zeros([9, 6]) mask[0:4, 3:8] = 1 # will flag first 2 mask_reader = VirtualWSIReader(mask) slide_shape = (6, 9) # slide shape (w, h) at requested resolution ############################################### # Tests for filter_coordinates (new) method _info = mask_reader.info _info.mpp = 1.0 mask_reader._m_info = _info # functionality test flag_list = PatchExtractor.filter_coordinates( mask_reader, bbox_list, slide_shape, ) assert np.sum(flag_list - np.array([1, 1, 0, 0, 0, 0])) == 0 flag_list = PatchExtractor.filter_coordinates(mask_reader, bbox_list, slide_shape) # Test for bad mask input with pytest.raises( ValueError, match="`mask_reader` should be wsireader.VirtualWSIReader." ): PatchExtractor.filter_coordinates( mask, bbox_list, slide_shape, ) # Test for bad bbox coordinate list in the input with pytest.raises(ValueError, match=r".*should be ndarray of integer type.*"): PatchExtractor.filter_coordinates( mask_reader, bbox_list.tolist(), slide_shape, ) # Test for incomplete coordinate list with pytest.raises(ValueError, match=r".*`coordinates_list` must be of shape.*"): PatchExtractor.filter_coordinates( mask_reader, bbox_list[:, :2], slide_shape, ) # Test for put of range min_mask_ratio with pytest.raises(ValueError, match="`min_mask_ratio` must be between 0 and 1."): PatchExtractor.filter_coordinates( mask_reader, bbox_list, slide_shape, min_mask_ratio=-0.5, ) with pytest.raises(ValueError, match="`min_mask_ratio` must be between 0 and 1."): PatchExtractor.filter_coordinates( mask_reader, bbox_list, slide_shape, min_mask_ratio=1.1, ) def test_mask_based_patch_extractor_ndpi(sample_ndpi, caplog): """Test SlidingWindowPatchExtractor with mask for ndpi image.""" res = 0 patch_size = stride = (400, 400) input_img = pathlib.Path(sample_ndpi) wsi = OpenSlideWSIReader(input_img=input_img) slide_dimensions = wsi.info.slide_dimensions # Generating a test mask to read patches from mask_dim = (int(slide_dimensions[0] / 10), int(slide_dimensions[1] / 10)) wsi_mask = np.zeros(mask_dim[::-1], dtype=np.uint8) # reverse as dims are (w, h) # masking two column to extract patch from wsi_mask[:, :2] = 255 # patch extraction based on the column mask patches = patchextraction.get_patch_extractor( input_img=input_img, input_mask=wsi_mask, method_name="slidingwindow", patch_size=patch_size, resolution=res, units="level", stride=None, ) # read the patch from the second row (y) in the first column patch = wsi.read_rect( location=(0, int(patch_size[1])), size=patch_size, resolution=res, units="level", ) # because we are using column mask to extract patches, we can expect # that the patches[1] is the from the second row (y) in the first column. assert np.all(patches[1] == patch) assert patches[0].shape == (patch_size[0], patch_size[1], 3) # Test None option for mask _ = patchextraction.get_patch_extractor( input_img=input_img, input_mask=None, method_name="slidingwindow", patch_size=patch_size, resolution=res, units="level", stride=stride[0], ) # Test passing a VirtualWSI for mask mask_wsi = VirtualWSIReader(wsi_mask, info=wsi._m_info, mode="bool") _ = patchextraction.get_patch_extractor( input_img=wsi, input_mask=mask_wsi, method_name="slidingwindow", patch_size=patch_size, resolution=res, units="level", stride=None, ) # Test `otsu` option for mask _ = patchextraction.get_patch_extractor( input_img=input_img, input_mask="otsu", method_name="slidingwindow", patch_size=patch_size[0], resolution=res, units="level", stride=stride, ) _ = patchextraction.get_patch_extractor( input_img=wsi_mask, # a numpy array to build VirtualSlideReader input_mask="morphological", method_name="slidingwindow", patch_size=patch_size, resolution=res, units="level", stride=stride, ) # Test passing an empty mask wsi_mask = np.zeros(mask_dim, dtype=np.uint8) _ = patchextraction.get_patch_extractor( input_img=input_img, input_mask=wsi_mask, method_name="slidingwindow", patch_size=patch_size, resolution=res, units="level", stride=stride, ) assert "No candidate coordinates left" in caplog.text
17,526
29.063465
86
py
tiatoolbox
tiatoolbox-master/tests/test_pyramid.py
"""Tests for tile pyramid generation.""" import re from pathlib import Path import numpy as np import pytest from PIL import Image from skimage import data from skimage.metrics import peak_signal_noise_ratio from tiatoolbox.tools import pyramid from tiatoolbox.utils.image import imresize from tiatoolbox.wsicore import wsireader def test_zoomify_tile_path(): """Test Zoomify tile path generation.""" array = np.ones((1024, 1024)) wsi = wsireader.VirtualWSIReader(array) dz = pyramid.ZoomifyGenerator(wsi) path = dz.tile_path(0, 0, 0) assert isinstance(path, Path) assert len(path.parts) == 2 assert "TileGroup" in path.parts[0] assert re.match(pattern=r"TileGroup\d+", string=path.parts[0]) is not None assert re.match(pattern=r"\d+-\d+-\d+\.jpg", string=path.parts[1]) is not None def test_zoomify_len(): """Test __len__ for ZoomifyGenerator.""" array = np.ones((1024, 1024)) wsi = wsireader.VirtualWSIReader(array) dz = pyramid.ZoomifyGenerator(wsi, tile_size=256) assert len(dz) == (4 * 4) + (2 * 2) + 1 def test_zoomify_iter(): """Test __iter__ for ZoomifyGenerator.""" array = np.ones((1024, 1024)) wsi = wsireader.VirtualWSIReader(array) dz = pyramid.ZoomifyGenerator(wsi, tile_size=256) for tile in dz: assert isinstance(tile, Image.Image) assert tile.size == (256, 256) def test_tile_grid_size_invalid_level(): """Test tile_grid_size for IndexError on invalid levels.""" array = np.ones((1024, 1024)) wsi = wsireader.VirtualWSIReader(array) dz = pyramid.ZoomifyGenerator(wsi, tile_size=256) with pytest.raises(IndexError): dz.tile_grid_size(level=-1) with pytest.raises(IndexError): dz.tile_grid_size(level=100) dz.tile_grid_size(level=0) def test_get_tile_negative_level(): """Test for IndexError on negative levels.""" array = np.ones((1024, 1024)) wsi = wsireader.VirtualWSIReader(array) dz = pyramid.ZoomifyGenerator(wsi, tile_size=256) with pytest.raises(IndexError): dz.get_tile(-1, 0, 0) def test_get_tile_large_level(): """Test for IndexError on too large a level.""" array = np.ones((1024, 1024)) wsi = wsireader.VirtualWSIReader(array) dz = pyramid.ZoomifyGenerator(wsi, tile_size=256) with pytest.raises(IndexError): dz.get_tile(100, 0, 0) def test_get_tile_large_xy(): """Test for IndexError on too large an xy index.""" array = np.ones((1024, 1024)) wsi = wsireader.VirtualWSIReader(array) dz = pyramid.ZoomifyGenerator(wsi, tile_size=256) with pytest.raises(IndexError): dz.get_tile(0, 100, 100) def test_zoomify_tile_group_index_error(): """Test IndexError for Zoomify tile groups.""" array = np.ones((1024, 1024)) wsi = wsireader.VirtualWSIReader(array) dz = pyramid.ZoomifyGenerator(wsi, tile_size=256) with pytest.raises(IndexError): dz.tile_group(0, 100, 100) def test_zoomify_dump_options_combinations(tmp_path): # noqa: CCR001 """Test for no fatal errors on all option combinations for dump.""" array = data.camera() wsi = wsireader.VirtualWSIReader(array) dz = pyramid.ZoomifyGenerator(wsi, tile_size=64) for container in [None, "zip", "tar"]: compression_methods = [None, "deflate", "gzip", "bz2", "lzma"] if container == "zip": compression_methods.remove("gzip") if container == "tar": compression_methods.remove("deflate") if container is None: compression_methods = [None] for compression in compression_methods: out_path = tmp_path / f"{compression}-pyramid" if container is not None: out_path = out_path.with_suffix(f".{container}") dz.dump(out_path, container=container, compression=compression) assert out_path.exists() def test_zoomify_dump_compression_error(tmp_path): """Test ValueError is raised on invalid compression modes.""" array = data.camera() wsi = wsireader.VirtualWSIReader(array) dz = pyramid.ZoomifyGenerator(wsi, tile_size=64) out_path = tmp_path / "pyramid_dump" with pytest.raises(ValueError, match="Unsupported compression for container None"): dz.dump(out_path, container=None, compression="deflate") with pytest.raises(ValueError, match="Unsupported compression for zip"): dz.dump(out_path, container="zip", compression="gzip") with pytest.raises(ValueError, match="Unsupported compression for tar"): dz.dump(out_path, container="tar", compression="deflate") def test_zoomify_dump_container_error(tmp_path): """Test ValueError is raised on invalid containers.""" array = data.camera() wsi = wsireader.VirtualWSIReader(array) dz = pyramid.ZoomifyGenerator(wsi, tile_size=64) out_path = tmp_path / "pyramid_dump" with pytest.raises(ValueError, match="Unsupported container"): dz.dump(out_path, container="foo") def test_zoomify_dump(tmp_path): """Test dumping to directory.""" array = data.camera() wsi = wsireader.VirtualWSIReader(array) dz = pyramid.ZoomifyGenerator(wsi, tile_size=64) out_path = tmp_path / "pyramid_dump" dz.dump(out_path) assert out_path.exists() assert len(list((out_path / "TileGroup0").glob("0-*"))) == 1 assert Image.open(out_path / "TileGroup0" / "0-0-0.jpg").size == (64, 64) def test_get_thumb_tile(): """Test getting a thumbnail tile (whole WSI in one tile).""" array = data.camera() wsi = wsireader.VirtualWSIReader(array) dz = pyramid.ZoomifyGenerator(wsi, tile_size=224) thumb = dz.get_thumb_tile() assert thumb.size == (224, 224) cv2_thumb = imresize(array, output_size=(224, 224)) psnr = peak_signal_noise_ratio(cv2_thumb, np.array(thumb.convert("L"))) assert np.isinf(psnr) or psnr < 40 def test_sub_tile_levels(): """Test sub-tile level generation.""" array = data.camera() wsi = wsireader.VirtualWSIReader(array) class MockTileGenerator(pyramid.TilePyramidGenerator): def tile_path(self, level: int, x: int, y: int) -> Path: # skipcq: PYL-R0201 return Path(level, x, y) @property def sub_tile_level_count(self): return 1 dz = MockTileGenerator(wsi, tile_size=224) tile = dz.get_tile(0, 0, 0) assert tile.size == (112, 112)
6,408
33.456989
87
py
tiatoolbox
tiatoolbox-master/tests/test_tissuemask.py
"""Tests for code related to tissue mask generation.""" import os import pathlib import cv2 import numpy as np import pytest from click.testing import CliRunner from tiatoolbox import cli from tiatoolbox.tools import tissuemask from tiatoolbox.utils.env_detection import running_on_ci from tiatoolbox.wsicore import wsireader # ------------------------------------------------------------------------------------- # Tests # ------------------------------------------------------------------------------------- def test_otsu_masker(sample_svs): """Test Otsu's thresholding method.""" wsi = wsireader.OpenSlideWSIReader(sample_svs) mpp = 32 thumb = wsi.slide_thumbnail(mpp, "mpp") masker = tissuemask.OtsuTissueMasker() mask_a = masker.fit_transform([thumb])[0] masker.fit([thumb]) mask_b = masker.transform([thumb])[0] assert np.array_equal(mask_a, mask_b) assert masker.threshold is not None assert len(np.unique(mask_a)) == 2 assert mask_a.shape == thumb.shape[:2] def test_otsu_greyscale_masker(sample_svs): """Test Otsu's thresholding method with greyscale inputs.""" wsi = wsireader.OpenSlideWSIReader(sample_svs) mpp = 32 thumb = wsi.slide_thumbnail(mpp, "mpp") thumb = cv2.cvtColor(thumb, cv2.COLOR_RGB2GRAY) inputs = thumb[np.newaxis, ..., np.newaxis] masker = tissuemask.OtsuTissueMasker() mask_a = masker.fit_transform(inputs)[0] masker.fit(inputs) mask_b = masker.transform(inputs)[0] assert np.array_equal(mask_a, mask_b) assert masker.threshold is not None assert len(np.unique(mask_a)) == 2 assert mask_a.shape == thumb.shape[:2] def test_morphological_masker(sample_svs): """Test simple morphological thresholding.""" wsi = wsireader.OpenSlideWSIReader(sample_svs) thumb = wsi.slide_thumbnail() masker = tissuemask.MorphologicalMasker() mask_a = masker.fit_transform([thumb])[0] masker.fit([thumb]) mask_b = masker.transform([thumb])[0] assert np.array_equal(mask_a, mask_b) assert masker.threshold is not None assert len(np.unique(mask_a)) == 2 assert mask_a.shape == thumb.shape[:2] def test_morphological_greyscale_masker(sample_svs): """Test morphological masker with greyscale inputs.""" wsi = wsireader.OpenSlideWSIReader(sample_svs) mpp = 32 thumb = wsi.slide_thumbnail(mpp, "mpp") thumb = cv2.cvtColor(thumb, cv2.COLOR_RGB2GRAY) inputs = thumb[np.newaxis, ..., np.newaxis] masker = tissuemask.MorphologicalMasker() mask_a = masker.fit_transform(inputs)[0] masker.fit(inputs) mask_b = masker.transform(inputs)[0] assert np.array_equal(mask_a, mask_b) assert masker.threshold is not None assert len(np.unique(mask_a)) == 2 assert mask_a.shape == thumb.shape[:2] def test_morphological_masker_int_kernel_size(sample_svs): """Test simple morphological thresholding with mpp with int kernel_size.""" wsi = wsireader.OpenSlideWSIReader(sample_svs) mpp = 32 thumb = wsi.slide_thumbnail(mpp, "mpp") masker = tissuemask.MorphologicalMasker(kernel_size=5) mask_a = masker.fit_transform([thumb])[0] masker.fit([thumb]) mask_b = masker.transform([thumb])[0] assert np.array_equal(mask_a, mask_b) assert masker.threshold is not None assert len(np.unique(mask_a)) == 2 assert mask_a.shape == thumb.shape[:2] def test_morphological_masker_mpp(sample_svs): """Test simple morphological thresholding with mpp.""" wsi = wsireader.OpenSlideWSIReader(sample_svs) mpp = 32 thumb = wsi.slide_thumbnail(mpp, "mpp") kwarg_sets = [ {"mpp": mpp}, {"mpp": [mpp, mpp]}, ] for kwargs in kwarg_sets: masker = tissuemask.MorphologicalMasker(**kwargs) mask_a = masker.fit_transform([thumb])[0] masker.fit([thumb]) mask_b = masker.transform([thumb])[0] assert np.array_equal(mask_a, mask_b) assert masker.threshold is not None assert len(np.unique(mask_a)) == 2 assert mask_a.shape == thumb.shape[:2] def test_morphological_masker_power(sample_svs): """Test simple morphological thresholding with objective power.""" wsi = wsireader.OpenSlideWSIReader(sample_svs) power = 1.25 thumb = wsi.slide_thumbnail(power, "power") masker = tissuemask.MorphologicalMasker(power=power) mask_a = masker.fit_transform([thumb])[0] masker.fit([thumb]) mask_b = masker.transform([thumb])[0] assert np.array_equal(mask_a, mask_b) assert masker.threshold is not None assert len(np.unique(mask_a)) == 2 assert mask_a.shape == thumb.shape[:2] def test_transform_before_fit_otsu(): """Test otsu masker error on transform before fit.""" image = np.ones((1, 10, 10)) masker = tissuemask.OtsuTissueMasker() with pytest.raises(SyntaxError, match="Fit must be called before transform."): masker.transform([image])[0] def test_transform_before_fit_morphological(): """Test morphological masker error on transform before fit.""" image = np.ones((1, 10, 10)) masker = tissuemask.MorphologicalMasker() with pytest.raises(SyntaxError, match="Fit must be called before transform."): masker.transform([image])[0] def test_transform_fit_otsu_wrong_shape(): """Test giving the incorrect input shape to otsu masker.""" image = np.ones((10, 10)) masker = tissuemask.OtsuTissueMasker() with pytest.raises(ValueError, match="Expected 4 dimensional input shape *"): masker.fit([image]) def test_transform_morphological_conflicting_args(): """Test giving conflicting arguments to morphological masker.""" with pytest.raises( ValueError, match="Only one of mpp, power, kernel_size can be given." ): tissuemask.MorphologicalMasker(mpp=32, power=1.25) def test_morphological_kernel_size_none(): """Test giveing a None kernel size for morphological masker.""" tissuemask.MorphologicalMasker(kernel_size=None) def test_morphological_min_region_size(): """Test morphological masker with min_region_size set. Creates a test image (0=foreground, 1=background) and applies the morphological masker with min_region_size=6. This should output only the largest square region as foreground in the mask (0=background, 1=foreground). """ # Create a blank image of ones img = np.ones((10, 10)) # Create a large square region of 9 zeros img[1:4, 1:4] = 0 # Create a row of 5 zeros img[1, 5:10] = 0 # Create a single 0 img[8, 8] = 0 masker = tissuemask.MorphologicalMasker(kernel_size=1, min_region_size=6) output = masker.fit_transform([img[..., np.newaxis]]) assert np.sum(output[0]) == 9 # Create the expected output with just the large square region # but as ones against zeros (the mask is the inverse of the input). expected = np.zeros((10, 10)) expected[1:4, 1:4] = 1 assert np.all(output[0] == expected) @pytest.mark.skipif(running_on_ci(), reason="No display on CI.") @pytest.mark.skipif( not os.environ.get("SHOW_TESTS"), reason="Visual tests disabled, set SHOW_TESTS to enable.", ) def test_cli_tissue_mask_otsu_show(sample_svs): """Test Otsu tissue masking with default input CLI and showing in a window.""" source_img = pathlib.Path(sample_svs) runner = CliRunner() tissue_mask_result = runner.invoke( cli.main, [ "tissue-mask", "--img-input", str(source_img), "--method", "Otsu", "--mode", "show", ], ) assert tissue_mask_result.exit_code == 0 def test_cli_tissue_mask_otsu_save(sample_svs): """Test Otsu tissue masking with default input CLI and saving to a file.""" source_img = pathlib.Path(sample_svs) runner = CliRunner() output_path = str(pathlib.Path(sample_svs.parent, "tissue_mask")) tissue_mask_result = runner.invoke( cli.main, [ "tissue-mask", "--img-input", str(source_img), "--method", "Otsu", "--mode", "save", "--output-path", output_path, ], ) assert tissue_mask_result.exit_code == 0 assert pathlib.Path(output_path, source_img.stem + ".png").is_file() def test_cli_tissue_mask_otsu_dir_save(sample_all_wsis): """Test Otsu tissue masking for multiple files with default input CLI.""" source_img = pathlib.Path(sample_all_wsis) runner = CliRunner() output_path = str(pathlib.Path(source_img, "tissue_mask")) tissue_mask_result = runner.invoke( cli.main, [ "tissue-mask", "--img-input", str(source_img), "--method", "Otsu", "--mode", "save", "--output-path", output_path, ], ) assert tissue_mask_result.exit_code == 0 assert pathlib.Path(output_path, "test1.png").is_file() @pytest.mark.skipif(running_on_ci(), reason="No display on CI.") @pytest.mark.skipif( not os.environ.get("SHOW_TESTS"), reason="Visual tests disabled, set SHOW_TESTS to enable.", ) def test_cli_tissue_mask_morphological_show(sample_svs): """Test Morphological tissue masking with default input CLI.""" source_img = pathlib.Path(sample_svs) runner = CliRunner() tissue_mask_result = runner.invoke( cli.main, [ "tissue-mask", "--img-input", str(source_img), "--method", "Morphological", "--mode", "show", ], ) assert tissue_mask_result.exit_code == 0 def test_cli_tissue_mask_morphological_save(sample_svs): """Test Morphological tissue masking with morphological method CLI.""" source_img = pathlib.Path(sample_svs) runner = CliRunner() output_path = str(pathlib.Path(sample_svs.parent, "tissue_mask")) tissue_mask_result = runner.invoke( cli.main, [ "tissue-mask", "--img-input", str(source_img), "--method", "Morphological", "--mode", "save", "--output-path", output_path, ], ) assert tissue_mask_result.exit_code == 0 assert pathlib.Path(output_path, source_img.stem + ".png").is_file() def test_cli_tissue_mask_morphological_power_resolution_save(sample_svs): """Test Morphological tissue masking with morphological method CLI. Adds option to specify resolution and units in power (appmag). """ source_img = pathlib.Path(sample_svs) runner = CliRunner() output_path = str(pathlib.Path(sample_svs.parent, "tissue_mask")) tissue_mask_result = runner.invoke( cli.main, [ "tissue-mask", "--img-input", str(source_img), "--method", "Morphological", "--mode", "save", "--output-path", output_path, "--resolution", 1.25, "--units", "power", ], ) assert tissue_mask_result.exit_code == 0 assert pathlib.Path(output_path, source_img.stem + ".png").is_file() def test_cli_tissue_mask_morphological_mpp_resolution_save(sample_svs): """Test Morphological tissue masking with morphological method CLI. Adds option to specify resolution and units in mpp (micrometers per pixel). """ source_img = pathlib.Path(sample_svs) runner = CliRunner() output_path = str(pathlib.Path(sample_svs.parent, "tissue_mask")) tissue_mask_result = runner.invoke( cli.main, [ "tissue-mask", "--img-input", str(source_img), "--method", "Morphological", "--mode", "save", "--output-path", output_path, "--resolution", 32, "--units", "mpp", ], ) assert tissue_mask_result.exit_code == 0 assert pathlib.Path(output_path, source_img.stem + ".png").is_file() def test_cli_tissue_mask_morphological_kernel_size_save(sample_svs): """Test Morphological tissue masking with morphological method CLI. Adds option to specify kernel size. """ source_img = pathlib.Path(sample_svs) runner = CliRunner() output_path = str(pathlib.Path(sample_svs.parent, "tissue_mask")) tissue_mask_result = runner.invoke( cli.main, [ "tissue-mask", "--img-input", str(source_img), "--method", "Morphological", "--mode", "save", "--output-path", output_path, "--kernel-size", "1", "1", ], ) assert tissue_mask_result.exit_code == 0 assert pathlib.Path(output_path, source_img.stem + ".png").is_file() def test_cli_tissue_mask_method_not_supported(sample_svs): """Test method not supported for the tissue masking CLI.""" source_img = pathlib.Path(sample_svs) runner = CliRunner() tissue_mask_result = runner.invoke( cli.main, [ "tissue-mask", "--img-input", str(source_img), "--method", "Test", "--mode", "save", ], ) assert "Invalid value for '--method'" in tissue_mask_result.output assert tissue_mask_result.exit_code != 0 assert isinstance(tissue_mask_result.exception, SystemExit) tissue_mask_result = runner.invoke( cli.main, [ "tissue-mask", "--img-input", str(source_img), "--method", "Morphological", "--resolution", 32, "--units", "level", ], ) assert "Invalid value for '--units'" in tissue_mask_result.output assert tissue_mask_result.exit_code != 0 assert isinstance(tissue_mask_result.exception, SystemExit) def test_cli_tissue_mask_file_not_found_error(source_image): """Test file not found error for the tissue masking CLI.""" source_img = pathlib.Path(source_image) runner = CliRunner() tissue_mask_result = runner.invoke( cli.main, [ "tissue-mask", "--img-input", str(source_img)[:-1], "--method", "Otsu", ], ) assert tissue_mask_result.output == "" assert tissue_mask_result.exit_code == 1 assert isinstance(tissue_mask_result.exception, FileNotFoundError)
14,760
29.310062
87
py
tiatoolbox
tiatoolbox-master/tests/test_scale.py
"""Tests for scaling methods.""" import numpy as np import pytest from sklearn.linear_model import LogisticRegression as PlattScaling def test_platt_scaler(): """Test for Platt scaler.""" np.random.seed(5) sample_size = 1000 logit = np.random.rand(sample_size) # binary class label = np.concatenate( [np.full(int(0.9 * sample_size), -1), np.full(int(0.1 * sample_size), 1)] ) scaler = PlattScaling(max_iter=1) scaler._fixer_a = 0.0 scaler._fixer_b = 0.0 scaler.fit(np.array(logit * 0.01, ndmin=2).T, label) _ = scaler.predict_proba(np.array(logit * 0.01, ndmin=2).T) scaler = PlattScaling(max_iter=1) scaler._fixer_a = 0.0 scaler._fixer_b = 1.0 scaler.fit(np.array(logit * 0.01, ndmin=2).T, label) _ = scaler.predict_proba(np.array(logit * 0.01, ndmin=2).T) scaler = PlattScaling(max_iter=10) scaler.fit(np.array(logit * 100, ndmin=2).T, label) _ = scaler.predict_proba(np.array(logit * 0.01, ndmin=2).T) label = np.concatenate([np.full(int(sample_size), -1)]) scaler = PlattScaling(max_iter=1) with pytest.raises(ValueError, match="needs samples of at least 2 classes"): scaler.fit(np.array(logit * 0.01, ndmin=2).T, label) with pytest.raises(ValueError, match="inconsistent"): scaler.fit(np.array(logit, ndmin=2).T, label[:2]) print(scaler)
1,374
32.536585
81
py
tiatoolbox
tiatoolbox-master/tests/test_visualization.py
"""Tests for visualization.""" import copy import pathlib import joblib import matplotlib import matplotlib.pyplot as plt import numpy as np import pytest from tiatoolbox.utils.visualization import ( overlay_prediction_contours, overlay_prediction_mask, overlay_probability_map, plot_graph, ) from tiatoolbox.wsicore.wsireader import WSIReader def test_overlay_prediction_mask(sample_wsi_dict): """Test for overlaying merged patch prediction of wsi.""" mini_wsi_svs = pathlib.Path(sample_wsi_dict["wsi2_4k_4k_svs"]) mini_wsi_pred = pathlib.Path(sample_wsi_dict["wsi2_4k_4k_pred"]) reader = WSIReader.open(mini_wsi_svs) raw, merged = joblib.load(mini_wsi_pred) thumb = reader.slide_thumbnail(resolution=2.77, units="mpp") with pytest.raises(ValueError, match=r".*Mismatch shape.*"): _ = overlay_prediction_mask(thumb, merged) label_info_full = { 0: ("BACKGROUND", (0, 0, 0)), 1: ("01_TUMOR", (255, 0, 0)), 2: ("02_STROMA", (0, 255, 0)), 3: ("03_COMPLEX", (0, 0, 255)), 4: ("04_LYMPHO", (0, 255, 255)), 5: ("05_DEBRIS", (255, 0, 255)), 6: ("06_MUCOSA", (255, 255, 0)), 7: ("07_ADIPOSE", (125, 255, 255)), 8: ("08_EMPTY", (255, 125, 255)), } thumb = reader.slide_thumbnail(resolution=raw["resolution"], units=raw["units"]) with pytest.raises(ValueError, match=r".*float `img` outside.*"): _ = overlay_prediction_mask(thumb.astype(np.float32), merged) label_info_fail = copy.deepcopy(label_info_full) del label_info_fail[1] with pytest.raises(ValueError, match=r".*Missing label.*"): _ = overlay_prediction_mask(thumb, merged, label_info=label_info_fail) label_info_fail = copy.deepcopy(label_info_full) label_info_fail[1] = (1, (255, 255, 255)) with pytest.raises(ValueError, match=r".*Wrong `label_info` format.*"): _ = overlay_prediction_mask(thumb, merged, label_info=label_info_fail) label_info_fail = copy.deepcopy(label_info_full) label_info_fail["ABC"] = ("ABC", (255, 255, 255)) with pytest.raises(ValueError, match=r".*Wrong `label_info` format.*"): _ = overlay_prediction_mask(thumb, merged, label_info=label_info_fail) label_info_fail = copy.deepcopy(label_info_full) label_info_fail[1] = ("ABC", "ABC") with pytest.raises(ValueError, match=r".*Wrong `label_info` format.*"): _ = overlay_prediction_mask(thumb, merged, label_info=label_info_fail) label_info_fail = copy.deepcopy(label_info_full) label_info_fail[1] = ("ABC", (255, 255)) with pytest.raises(ValueError, match=r".*Wrong `label_info` format.*"): _ = overlay_prediction_mask(thumb, merged, label_info=label_info_fail) # Test normal run, should not crash. thumb_float = thumb / 255.0 ax = overlay_prediction_mask(thumb_float, merged, label_info=label_info_full) ax.remove() ax = overlay_prediction_mask(thumb, merged, label_info=label_info_full) ax.remove() ax = plt.subplot(1, 2, 1) _ = overlay_prediction_mask(thumb, merged, ax=ax) _ = overlay_prediction_mask(thumb_float, merged, min_val=0.5, return_ax=False) def test_overlay_probability_map(sample_wsi_dict): """Test functional run for overlaying merged patch prediction of wsi.""" mini_wsi_svs = pathlib.Path(sample_wsi_dict["wsi2_4k_4k_svs"]) reader = WSIReader.open(mini_wsi_svs) thumb = reader.slide_thumbnail(resolution=2.77, units="mpp") # * Test normal run, should not crash. thumb_float = np.mean(thumb, axis=-1) / 255.0 output = overlay_probability_map(thumb, thumb_float, min_val=0.5) output = overlay_probability_map(thumb / 256.0, thumb_float, min_val=0.5) output = overlay_probability_map(thumb, thumb_float, return_ax=False) assert isinstance(output, np.ndarray) output = overlay_probability_map(thumb, thumb_float, return_ax=True) assert isinstance(output, matplotlib.axes.Axes) output = overlay_probability_map(thumb, thumb_float, ax=output) assert isinstance(output, matplotlib.axes.Axes) # * Test crash mode with pytest.raises(ValueError, match=r".*min_val.*0, 1*"): overlay_probability_map(thumb, thumb_float, min_val=-0.5) with pytest.raises(ValueError, match=r".*min_val.*0, 1*"): overlay_probability_map(thumb, thumb_float, min_val=1.5) with pytest.raises(ValueError, match=r".*float `img`.*0, 1*"): overlay_probability_map(np.full_like(thumb, 1.5, dtype=float), thumb_float) with pytest.raises(ValueError, match=r".*float `img`.*0, 1*"): overlay_probability_map(np.full_like(thumb, -0.5, dtype=float), thumb_float) with pytest.raises(ValueError, match=r".*prediction.*0, 1*"): overlay_probability_map(thumb, thumb_float + 1.05, thumb_float) with pytest.raises(ValueError, match=r".*prediction.*0, 1*"): overlay_probability_map(thumb, thumb_float - 1.05, thumb_float) with pytest.raises(ValueError, match=r".*Mismatch shape*"): overlay_probability_map(np.zeros([2, 2, 3]), thumb_float) with pytest.raises(ValueError, match=r".*2-dimensional*"): overlay_probability_map(thumb, thumb_float[..., None]) def test_overlay_instance_prediction(): """Test for overlaying instance predictions on canvas.""" inst_map = np.array( [ [0, 0, 0, 0, 0, 0], [0, 1, 1, 0, 0, 0], [0, 1, 1, 0, 0, 0], [0, 0, 0, 2, 2, 0], [0, 0, 0, 2, 2, 0], [0, 0, 0, 0, 0, 0], ], dtype=np.int32, ) # dummy instance dict type_colours = { 0: ("A", (1, 0, 1)), 1: ("B", (2, 0, 2)), } inst_dict = { 0: { "centroid": [1, 1], "type": 0, "contour": [[1, 1], [1, 2], [2, 2], [2, 1]], }, 1: { "centroid": [3, 3], "type": 1, "contour": [[3, 3], [3, 4], [4, 4], [4, 3]], }, } canvas = np.zeros(inst_map.shape + (3,), dtype=np.uint8) canvas = overlay_prediction_contours( canvas, inst_dict, draw_dot=False, type_colours=type_colours, line_thickness=1 ) assert np.sum(canvas[..., 0].astype(np.int32) - inst_map) == 0 assert np.sum(canvas[..., 1].astype(np.int32) - inst_map) == -12 assert np.sum(canvas[..., 2].astype(np.int32) - inst_map) == 0 canvas = overlay_prediction_contours( canvas, inst_dict, draw_dot=True, type_colours=None, line_thickness=1 ) # test run with randomized colours canvas = overlay_prediction_contours(canvas, inst_dict, inst_colours=None) # test run with custom colour canvas = overlay_prediction_contours(canvas, inst_dict, inst_colours=(0, 0, 1)) # test run with custom colour for each instance inst_colours = [[0, 155, 155] for v in range(len(inst_dict))] canvas = overlay_prediction_contours( canvas, inst_dict, inst_colours=np.array(inst_colours) ) # test crash with pytest.raises(ValueError, match=r"`.*inst_colours`.*tuple.*"): overlay_prediction_contours(canvas, inst_dict, inst_colours=inst_colours) def test_plot_graph(): """Test plotting graph.""" canvas = np.zeros([10, 10]) nodes = np.array([[1, 1], [2, 2], [2, 5]]) edges = np.array([[0, 1], [1, 2], [2, 0]]) node_colors = np.array([[0, 0, 0]] * 3) edge_colors = np.array([[1, 1, 1]] * 3) plot_graph( canvas, nodes, edges, ) plot_graph(canvas, nodes, edges, node_colors=node_colors, edge_colors=edge_colors)
7,574
38.453125
86
py
tiatoolbox
tiatoolbox-master/tests/test_slide_thumbnail.py
"""Tests for code related to obtaining slide thumbnails.""" import os import pathlib import numpy as np import pytest from click.testing import CliRunner from tiatoolbox import cli from tiatoolbox.utils.env_detection import running_on_ci from tiatoolbox.wsicore import wsireader def test_wsireader_get_thumbnail_openslide(sample_svs): """Test for get_thumbnail as a python function.""" wsi = wsireader.OpenSlideWSIReader(sample_svs) slide_thumbnail = wsi.slide_thumbnail() assert isinstance(slide_thumbnail, np.ndarray) assert slide_thumbnail.dtype == "uint8" def test_wsireader_get_thumbnail_jp2(sample_jp2): """Test for get_thumbnail as a python function.""" wsi = wsireader.OmnyxJP2WSIReader(sample_jp2) slide_thumbnail = wsi.slide_thumbnail() assert isinstance(slide_thumbnail, np.ndarray) assert slide_thumbnail.dtype == "uint8" def command_line_slide_thumbnail(runner, sample, tmp_path, mode="save"): """Command line slide thumbnail helper.""" slide_thumb_result = runner.invoke( cli.main, [ "slide-thumbnail", "--img-input", str(pathlib.Path(sample)), "--mode", mode, "--output-path", str(pathlib.Path(tmp_path)), ], ) assert slide_thumb_result.exit_code == 0 if mode == "save": assert (pathlib.Path(tmp_path) / (sample.stem + ".jpg")).is_file() def test_command_line_slide_thumbnail(sample_ndpi, tmp_path): """Test for the slide_thumbnail CLI.""" runner = CliRunner() command_line_slide_thumbnail(runner, sample=sample_ndpi, tmp_path=tmp_path) def test_command_line_slide_thumbnail_output_none(sample_svs, tmp_path): """Test cli slide thumbnail with output dir None.""" runner = CliRunner() slide_thumb_result = runner.invoke( cli.main, [ "slide-thumbnail", "--img-input", str(pathlib.Path(sample_svs)), "--mode", "save", ], ) assert slide_thumb_result.exit_code == 0 assert ( pathlib.Path(sample_svs).parent / "slide-thumbnail" / (sample_svs.stem + ".jpg") ).is_file() def test_command_line_jp2_slide_thumbnail(sample_jp2, tmp_path): """Test for the jp2 slide_thumbnail CLI.""" runner = CliRunner() command_line_slide_thumbnail(runner, sample=sample_jp2, tmp_path=tmp_path) @pytest.mark.skipif(running_on_ci(), reason="No display on CI.") @pytest.mark.skipif( not os.environ.get("SHOW_TESTS"), reason="Visual tests disabled, set SHOW_TESTS to enable.", ) def test_command_line_jp2_slide_thumbnail_mode_show(sample_jp2, tmp_path): """Test for the jp2 slide_thumbnail CLI mode='show'.""" runner = CliRunner() command_line_slide_thumbnail( runner, sample=sample_jp2, tmp_path=tmp_path, mode="show" ) def test_command_line_jp2_slide_thumbnail_file_not_supported(sample_jp2, tmp_path): """Test for the jp2 slide_thumbnail CLI.""" runner = CliRunner() slide_thumb_result = runner.invoke( cli.main, [ "slide-thumbnail", "--img-input", str(pathlib.Path(sample_jp2))[:-1], "--mode", "save", "--output-path", str(pathlib.Path(tmp_path)), ], ) assert slide_thumb_result.output == "" assert slide_thumb_result.exit_code == 1 assert isinstance(slide_thumb_result.exception, FileNotFoundError)
3,503
28.445378
88
py
tiatoolbox
tiatoolbox-master/tests/test_tileserver.py
"""Tests for tileserver.""" import pathlib from pathlib import Path from typing import List, Union import numpy as np import pytest from shapely.geometry import LineString, Polygon from shapely.geometry.point import Point from tests.test_annotation_stores import cell_polygon from tiatoolbox.annotation.storage import Annotation, AnnotationStore, SQLiteStore from tiatoolbox.cli.common import cli_name from tiatoolbox.utils.misc import imwrite from tiatoolbox.visualization.tileserver import TileServer from tiatoolbox.wsicore.wsireader import WSIReader @pytest.fixture(scope="session") def cell_grid() -> List[Polygon]: """Generate a grid of fake cell boundary polygon annotations.""" np.random.seed(0) return [ cell_polygon(((i + 0.5) * 100, (j + 0.5) * 100)) for i, j in np.ndindex(5, 5) ] @pytest.fixture(scope="session") def points_grid(spacing=60) -> List[Point]: """Generate a grid of fake point annotations.""" np.random.seed(0) return [Point((600 + i * spacing, 600 + j * spacing)) for i, j in np.ndindex(7, 7)] @pytest.fixture(scope="session") def fill_store(cell_grid, points_grid): """Factory fixture to fill stores with test data.""" def _fill_store( store_class: AnnotationStore, path: Union[str, pathlib.Path], ): """Fills store with random variety of annotations.""" store = store_class(path) cells = [ Annotation(cell, {"type": "cell", "prob": np.random.rand(1)[0]}) for cell in cell_grid ] points = [ Annotation(point, {"type": "pt", "prob": np.random.rand(1)[0]}) for point in points_grid ] lines = [ Annotation( LineString(((x, x + 500) for x in range(100, 400, 10))), {"type": "line", "prob": 0.75}, ) ] annotations = cells + points + lines keys = store.append_many(annotations) return keys, store return _fill_store @pytest.fixture() def app(sample_ndpi, tmp_path, fill_store) -> TileServer: """Create a testing TileServer WSGI app.""" # Make a low-res .jpg of the right shape to be used as # a low-res overlay. wsi = WSIReader.open(Path(sample_ndpi)) thumb = wsi.slide_thumbnail() thumb_path = tmp_path / "thumb.jpg" imwrite(thumb_path, thumb) _, store = fill_store(SQLiteStore, tmp_path / "test.db") geo_path = tmp_path / "test.geojson" store.to_geojson(geo_path) store.commit() store.close() # make tileserver with layers representing all the types # of things it should be able to handle app = TileServer( "Testing TileServer", [ str(Path(sample_ndpi)), str(thumb_path), np.zeros(wsi.slide_dimensions(1.25, "power"), dtype=np.uint8).T, tmp_path / "test.geojson", str(tmp_path / "test.db"), ], ) app.config.from_mapping({"TESTING": True}) return app def layer_get_tile(app, layer) -> None: """Get a single tile and check the status code and content type.""" with app.test_client() as client: response = client.get(f"/layer/{layer}/zoomify/TileGroup0/0-0-0.jpg") assert response.status_code == 200 assert response.content_type == "image/webp" def test_get_tile(app): """do test on each layer""" layer_get_tile(app, "layer-0") layer_get_tile(app, "layer-1") layer_get_tile(app, "layer-2") layer_get_tile(app, "layer-3") layer_get_tile(app, "layer-4") def layer_get_tile_404(app, layer) -> None: """Request a tile with an index.""" with app.test_client() as client: response = client.get(f"/layer/{layer}/zoomify/TileGroup0/10-0-0.jpg") assert response.status_code == 404 assert response.get_data(as_text=True) == "Tile not found" def test_get_tile_404(app): """do test on each layer""" layer_get_tile_404(app, "layer-0") layer_get_tile_404(app, "layer-1") layer_get_tile_404(app, "layer-2") layer_get_tile_404(app, "layer-3") layer_get_tile_404(app, "layer-4") def test_get_tile_layer_key_error(app) -> None: """Request a tile with an invalid layer key.""" with app.test_client() as client: response = client.get("/layer/foo/zoomify/TileGroup0/0-0-0.jpg") assert response.status_code == 404 assert response.get_data(as_text=True) == "Layer not found" def test_get_index(app) -> None: """Get the index page and check that it is HTML.""" with app.test_client() as client: response = client.get("/") assert response.status_code == 200 assert response.content_type == "text/html; charset=utf-8" def test_create_with_dict(sample_svs): """test initialising with layers dict""" wsi = WSIReader.open(Path(sample_svs)) app = TileServer( "Testing TileServer", {"Test": wsi}, ) app.config.from_mapping({"TESTING": True}) with app.test_client() as client: response = client.get("/layer/Test/zoomify/TileGroup0/0-0-0.jpg") assert response.status_code == 200 assert response.content_type == "image/webp" def test_cli_name_multiple_flag(): """Test cli_name multiple flag.""" @cli_name() def dummy_fn(): """It is empty because it's a dummy function""" assert "Multiple" not in dummy_fn.__click_params__[0].help @cli_name(multiple=True) def dummy_fn(): """It is empty because it's a dummy function""" assert "Multiple" in dummy_fn.__click_params__[0].help
5,599
30.284916
87
py
tiatoolbox
tiatoolbox-master/tests/test_stainaugment.py
"""Tests for stain augmentation code.""" import pathlib import albumentations as alb import numpy as np import pytest from tiatoolbox.data import stain_norm_target from tiatoolbox.tools.stainaugment import StainAugmentor from tiatoolbox.tools.stainnorm import get_normalizer from tiatoolbox.utils.misc import imread def test_stainaugment(source_image, norm_vahadane): """Test functionality of the StainAugmentor class.""" source_img = imread(pathlib.Path(source_image)) target_img = stain_norm_target() vahadane_img = imread(pathlib.Path(norm_vahadane)) # Test invalid method in the input with pytest.raises(ValueError, match=r".*Unsupported stain extractor method.*"): _ = StainAugmentor(method="invalid") # 1. Testing without stain matrix. # Test with macenko stain extractor augmentor = StainAugmentor( method="macenko", sigma1=3.0, sigma2=3.0, augment_background=True ) augmentor.fit(source_img) source_img_aug = augmentor.augment() assert source_img_aug.dtype == source_img.dtype assert np.shape(source_img_aug) == np.shape(source_img) assert np.mean(np.absolute(source_img_aug / 255.0 - source_img / 255.0)) > 1e-2 # 2. Testing with predefined stain matrix # We first extract the stain matrix of the target image and try to augment the # source image with respect to that image. norm = get_normalizer("vahadane") norm.fit(target_img) target_stain_matrix = norm.stain_matrix_target # Now we augment the source image with sigma1=0, sigma2=0 to force the augmentor # to act like a normalizer augmentor = StainAugmentor( method="vahadane", stain_matrix=target_stain_matrix, sigma1=0.0, sigma2=0.0, augment_background=False, ) augmentor.fit(source_img, threshold=0.8) source_img_aug = augmentor.augment() assert np.mean(np.absolute(vahadane_img / 255.0 - source_img_aug / 255.0)) < 1e-1 # 3. Test in albumentation framework # Using the same trick as before, augment the image with pre-defined stain matrix # and sigma1,2 equal to 0. The output should be equal to stain normalized image. aug_pipeline = alb.Compose( [ StainAugmentor( method="vahadane", stain_matrix=target_stain_matrix, sigma1=0.0, sigma2=0.0, always_apply=True, ) ], p=1, ) source_img_aug = aug_pipeline(image=source_img)["image"] assert np.mean(np.absolute(vahadane_img / 255.0 - source_img_aug / 255.0)) < 1e-1 # Test for albumentation helper functions params = augmentor.get_transform_init_args_names() augmentor.get_params_dependent_on_targets(params) assert params == ( "method", "stain_matrix", "sigma1", "sigma2", "augment_background", )
2,908
33.630952
85
py
tiatoolbox
tiatoolbox-master/tests/test_init.py
"""Tests for toolbox global workspace.""" import importlib import logging import os import shutil import subprocess from pathlib import Path import pytest import tiatoolbox from tiatoolbox import DuplicateFilter, logger def test_set_root_dir(): """Test for setting new root dir.""" # skipcq importlib.reload(tiatoolbox) from tiatoolbox import rcParam old_root_dir = rcParam["TIATOOLBOX_HOME"] test_dir_path = os.path.join(os.getcwd(), "tmp_check/") # clean up previous test if os.path.exists(test_dir_path): os.rmdir(test_dir_path) rcParam["TIATOOLBOX_HOME"] = test_dir_path # reimport to see if it overwrites # silence Deep Source because this is an intentional check # skipcq from tiatoolbox import rcParam os.makedirs(rcParam["TIATOOLBOX_HOME"]) if not os.path.exists(test_dir_path): pytest.fail(f"`{rcParam['TIATOOLBOX_HOME']}` != `{test_dir_path}`") shutil.rmtree(rcParam["TIATOOLBOX_HOME"], ignore_errors=True) rcParam["TIATOOLBOX_HOME"] = old_root_dir # reassign for subsequent test def test_set_logger(): """Test for setting new logger.""" logger = logging.getLogger() logger.handlers = [] # reset first to overwrite import handler_1 = logging.StreamHandler() handler_2 = logging.StreamHandler() handler_3 = logging.StreamHandler() logger.addHandler(handler_1) logger.addHandler(handler_2) logger.addHandler(handler_3) assert len(logger.handlers) == 3 # skipcq importlib.reload(tiatoolbox) # should not overwrite, so still have 2 handler assert len(logger.handlers) == 3 logger.handlers = [] # remove all handler # skipcq importlib.reload(tiatoolbox) assert len(logger.handlers) == 2 def helper_logger_test(level: str): """Helper for logger tests.""" if level.lower() in ["debug", "info"]: output = "out" order = (0, 1) else: output = "err" order = (1, 0) run_statement = ( f"from tiatoolbox import logger; " f"import logging; " f"logger.setLevel(logging.{level.upper()}); " f'logger.{level.lower()}("Test if {level.lower()} is written to std{output}.")' ) proc = subprocess.Popen( [ "python", "-c", run_statement, ], stdout=subprocess.PIPE, stderr=subprocess.PIPE, ) assert ( f"[{level.upper()}] Test if {level.lower()} is written to std{output}.".encode() in proc.communicate()[order[0]] ) assert proc.communicate()[order[1]] == b"" def test_logger_output(): """Tests if logger is writing output to correct value.""" # Test DEBUG is written to stdout helper_logger_test(level="debug") # Test INFO is written to stdout helper_logger_test(level="info") # Test WARNING is written to stderr helper_logger_test(level="warning") # Test ERROR is written to stderr helper_logger_test(level="error") # Test CRITICAL is written to stderr helper_logger_test(level="critical") def test_duplicate_filter(caplog): """Tests DuplicateFilter for warnings.""" for _ in range(2): logger.warning("Test duplicate filter warnings.") assert "Test duplicate filter warnings." in caplog.text assert "\n" in caplog.text[:-2] caplog.clear() duplicate_filter = DuplicateFilter() logger.addFilter(duplicate_filter) for _ in range(2): logger.warning("Test duplicate filter warnings.") logger.removeFilter(duplicate_filter) assert "Test duplicate filter warnings." in caplog.text assert "\n" not in caplog.text[:-2] def test_lazy_import(): import sys from tiatoolbox import _lazy_import assert "exceptions" not in sys.modules _lazy_import( "exceptions", Path(__file__).parent.parent / "tiatoolbox" / "utils" / "exceptions.py", ) assert "exceptions" in sys.modules
3,963
26.915493
88
py
tiatoolbox
tiatoolbox-master/tests/test_wsireader.py
"""Tests for reading whole-slide images.""" import copy import json import logging import os import pathlib import random import re import shutil from copy import deepcopy from pathlib import Path from time import time # When no longer supporting Python <3.9 this should be collections.abc.Iterable from typing import Iterable import cv2 import numpy as np import pytest import zarr from click.testing import CliRunner from packaging.version import Version from skimage.filters import threshold_otsu from skimage.metrics import peak_signal_noise_ratio, structural_similarity from skimage.morphology import binary_dilation, disk, remove_small_objects from skimage.registration import phase_cross_correlation from tiatoolbox import cli, rcParam, utils from tiatoolbox.annotation.storage import SQLiteStore from tiatoolbox.data import _fetch_remote_sample from tiatoolbox.utils.exceptions import FileNotSupported from tiatoolbox.utils.misc import imread from tiatoolbox.utils.transforms import imresize, locsize2bounds from tiatoolbox.utils.visualization import AnnotationRenderer from tiatoolbox.wsicore import WSIReader, wsireader from tiatoolbox.wsicore.wsireader import ( AnnotationStoreReader, ArrayView, DICOMWSIReader, NGFFWSIReader, OmnyxJP2WSIReader, OpenSlideWSIReader, TIFFWSIReader, VirtualWSIReader, is_ngff, is_zarr, ) # ------------------------------------------------------------------------------------- # Constants # ------------------------------------------------------------------------------------- NDPI_TEST_TISSUE_BOUNDS = (30400, 11810, 30912, 12322) NDPI_TEST_TISSUE_LOCATION = (30400, 11810) NDPI_TEST_TISSUE_SIZE = (512, 512) SVS_TEST_TISSUE_BOUNDS = (1000, 2000, 2000, 3000) SVS_TEST_TISSUE_LOCATION = (1000, 2000) SVS_TEST_TISSUE_SIZE = (1000, 1000) JP2_TEST_TISSUE_BOUNDS = (32768, 42880, 33792, 43904) JP2_TEST_TISSUE_LOCATION = (32768, 42880) JP2_TEST_TISSUE_SIZE = (1024, 1024) COLOR_DICT = { 0: (200, 0, 0, 255), 1: (0, 200, 0, 255), 2: (0, 0, 200, 255), 3: (155, 155, 0, 255), 4: (155, 0, 155, 255), 5: (0, 155, 155, 255), } # ------------------------------------------------------------------------------------- # Utility Test Functions # ------------------------------------------------------------------------------------- def _get_temp_folder_path(prefix="temp"): """Return unique temp folder path""" return os.path.join(rcParam["TIATOOLBOX_HOME"], f"{prefix}-{int(time())}") def strictly_increasing(sequence: Iterable) -> bool: """Return True if sequence is strictly increasing. Args: sequence (Iterable): Sequence to check. Returns: bool: True if strictly increasing. """ return all(a < b for a, b in zip(sequence, sequence[1:])) def strictly_decreasing(sequence: Iterable) -> bool: """Return True if sequence is strictly decreasing. Args: sequence (Iterable): Sequence to check. Returns: bool: True if strictly decreasing. """ return all(a > b for a, b in zip(sequence, sequence[1:])) def read_rect_objective_power(wsi, location, size): """Read rect objective helper.""" for objective_power in [20, 10, 5, 2.5, 1.25]: im_region = wsi.read_rect( location, size, resolution=objective_power, units="power" ) assert isinstance(im_region, np.ndarray) assert im_region.dtype == "uint8" assert im_region.shape == (*size[::-1], 3) def read_bounds_mpp(wsi, bounds, size, jp2=False): """Read bounds mpp helper.""" slide_mpp = wsi.info.mpp for factor in range(1, 10): mpp = slide_mpp * factor downsample = mpp / slide_mpp im_region = wsi.read_bounds(bounds, resolution=mpp, units="mpp") assert isinstance(im_region, np.ndarray) assert im_region.dtype == "uint8" bounds_shape = np.array(size[::-1]) expected_output_shape = tuple((bounds_shape / downsample).round().astype(int)) if jp2: assert im_region.shape[:2] == pytest.approx(expected_output_shape, abs=1) else: assert im_region.shape[:2] == expected_output_shape assert im_region.shape[2] == 3 def read_bounds_objective_power(wsi, slide_power, bounds, size, jp2=False): """Read bounds objective power helper.""" for objective_power in [20, 10, 5, 2.5, 1.25]: downsample = slide_power / objective_power im_region = wsi.read_bounds( bounds, resolution=objective_power, units="power", ) assert isinstance(im_region, np.ndarray) assert im_region.dtype == "uint8" bounds_shape = np.array(size[::-1]) expected_output_shape = tuple((bounds_shape / downsample).round().astype(int)) if jp2: assert im_region.shape[:2] == pytest.approx( expected_output_shape[:2], abs=1 ) else: assert im_region.shape[:2] == expected_output_shape assert im_region.shape[2] == 3 def read_bounds_level_consistency(wsi, bounds): """Read bounds level consistency helper. Reads the same region at each stored resolution level and compares the resulting image using phase cross correlation to check that they are aligned. """ # Avoid testing very small levels (e.g. as in Omnyx JP2) because # MSE for very small levels is noisy. levels_to_test = [ n for n, downsample in enumerate(wsi.info.level_downsamples) if downsample <= 32 ] imgs = [wsi.read_bounds(bounds, level, "level") for level in levels_to_test] smallest_size = imgs[-1].shape[:2][::-1] resized = [cv2.resize(img, smallest_size) for img in imgs] # Some blurring applied to account for changes in sharpness arising # from interpolation when calculating the downsampled levels. This # adds some tolerance for the comparison. blurred = [cv2.GaussianBlur(img, (5, 5), cv2.BORDER_REFLECT) for img in resized] as_float = [img.astype(np.float_) for img in blurred] # Pair-wise check resolutions for mean squared error for i, a in enumerate(as_float): for b in as_float[i + 1 :]: _, error, phase_diff = phase_cross_correlation(a, b, normalization=None) assert phase_diff < 0.125 assert error < 0.125 # ------------------------------------------------------------------------------------- # Utility Test Classes # ------------------------------------------------------------------------------------- class DummyMutableOpenSlideObject: """Dummy OpenSlide object with mutable properties.""" def __init__(self, openslide_obj) -> None: self.openslide_obj = openslide_obj self._properties = dict(openslide_obj.properties) def __getattr__(self, name: str): return getattr(self.openslide_obj, name) @property def properties(self): """Return the fake properties.""" return self._properties # ------------------------------------------------------------------------------------- # Tests # ------------------------------------------------------------------------------------- def test_wsireader_slide_info(sample_svs, tmp_path): """Test for slide_info in WSIReader class as a python function.""" file_types = ("*.svs",) files_all = utils.misc.grab_files_from_dir( input_path=str(pathlib.Path(sample_svs).parent), file_types=file_types, ) wsi = wsireader.OpenSlideWSIReader(files_all[0]) slide_param = wsi.info out_path = tmp_path / slide_param.file_path.with_suffix(".yaml").name utils.misc.save_yaml(slide_param.as_dict(), out_path) def test_wsireader_slide_info_cache(sample_svs): """Test for caching slide_info in WSIReader class as a python function.""" file_types = ("*.svs",) files_all = utils.misc.grab_files_from_dir( input_path=str(pathlib.Path(sample_svs).parent), file_types=file_types, ) wsi = wsireader.OpenSlideWSIReader(files_all[0]) info = wsi.info cached_info = wsi.info assert info.as_dict() == cached_info.as_dict() def relative_level_scales_baseline(wsi): """Relative level scales for pixels per baseline pixel.""" level_scales = wsi.info.relative_level_scales(0.125, "baseline") level_scales = np.array(level_scales) downsamples = np.array(wsi.info.level_downsamples) expected = downsamples * 0.125 assert strictly_increasing(level_scales[:, 0]) assert strictly_increasing(level_scales[:, 1]) assert np.array_equal(level_scales[:, 0], level_scales[:, 1]) assert np.array_equal(level_scales[:, 0], expected) def test_relative_level_scales_openslide_baseline(sample_ndpi): """Test openslide relative level scales for pixels per baseline pixel.""" wsi = wsireader.OpenSlideWSIReader(sample_ndpi) relative_level_scales_baseline(wsi) def test_relative_level_scales_jp2_baseline(sample_jp2): """Test jp2 relative level scales for pixels per baseline pixel.""" wsi = wsireader.OmnyxJP2WSIReader(sample_jp2) relative_level_scales_baseline(wsi) def test_relative_level_scales_openslide_mpp(sample_ndpi): """Test openslide calculation of relative level scales for mpp.""" wsi = wsireader.OpenSlideWSIReader(sample_ndpi) level_scales = wsi.info.relative_level_scales(0.5, "mpp") level_scales = np.array(level_scales) assert strictly_increasing(level_scales[:, 0]) assert strictly_increasing(level_scales[:, 1]) assert all(level_scales[0] == wsi.info.mpp / 0.5) def test_relative_level_scales_jp2_mpp(sample_jp2): """Test jp2 calculation of relative level scales for mpp.""" wsi = wsireader.OmnyxJP2WSIReader(sample_jp2) level_scales = wsi.info.relative_level_scales(0.5, "mpp") level_scales = np.array(level_scales) assert strictly_increasing(level_scales[:, 0]) assert strictly_increasing(level_scales[:, 1]) assert all(level_scales[0] == wsi.info.mpp / 0.5) def relative_level_scales_power(wsi): """Calculation of relative level scales for objective power.""" level_scales = wsi.info.relative_level_scales(wsi.info.objective_power, "power") level_scales = np.array(level_scales) assert strictly_increasing(level_scales[:, 0]) assert strictly_increasing(level_scales[:, 1]) assert np.array_equal(level_scales[0], [1, 1]) downsamples = np.array(wsi.info.level_downsamples) assert np.array_equal(level_scales[:, 0], level_scales[:, 1]) assert np.array_equal(level_scales[:, 0], downsamples) def test_relative_level_scales_openslide_power(sample_ndpi): """Test openslide calculation of relative level scales for objective power.""" wsi = wsireader.OpenSlideWSIReader(sample_ndpi) relative_level_scales_power(wsi) def test_relative_level_scales_jp2_power(sample_jp2): """Test jp2 calculation of relative level scales for objective power.""" wsi = wsireader.OmnyxJP2WSIReader(sample_jp2) relative_level_scales_power(wsi) def relative_level_scales_level(wsi): """Calculation of relative level scales for level.""" level_scales = wsi.info.relative_level_scales(3, "level") level_scales = np.array(level_scales) assert np.array_equal(level_scales[3], [1, 1]) downsamples = np.array(wsi.info.level_downsamples) expected = downsamples / downsamples[3] assert np.array_equal(level_scales[:, 0], level_scales[:, 1]) assert np.array_equal(level_scales[:, 0], expected) def test_relative_level_scales_openslide_level(sample_ndpi): """Test openslide calculation of relative level scales for level.""" wsi = wsireader.OpenSlideWSIReader(sample_ndpi) relative_level_scales_level(wsi) def test_relative_level_scales_jp2_level(sample_jp2): """Test jp2 calculation of relative level scales for level.""" wsi = wsireader.OmnyxJP2WSIReader(sample_jp2) relative_level_scales_level(wsi) def relative_level_scales_float(wsi): """Calculation of relative level scales for fractional level.""" level_scales = wsi.info.relative_level_scales(1.5, "level") level_scales = np.array(level_scales) assert level_scales[0] == pytest.approx([1 / 3, 1 / 3]) downsamples = np.array(wsi.info.level_downsamples) expected = downsamples / downsamples[0] * (1 / 3) assert np.array_equal(level_scales[:, 0], level_scales[:, 1]) assert np.array_equal(level_scales[:, 0], expected) def test_relative_level_scales_openslide_level_float(sample_ndpi): """Test openslide calculation of relative level scales for fractional level.""" wsi = wsireader.OpenSlideWSIReader(sample_ndpi) relative_level_scales_float(wsi) def test_relative_level_scales_jp2_level_float(sample_jp2): """Test jp2 calculation of relative level scales for fractional level.""" wsi = wsireader.OmnyxJP2WSIReader(sample_jp2) relative_level_scales_float(wsi) def test_relative_level_scales_invalid_units(sample_svs): """Test relative_level_scales with invalid units.""" wsi = wsireader.OpenSlideWSIReader(sample_svs) with pytest.raises(ValueError, match="Invalid units"): wsi.info.relative_level_scales(1.0, "gibberish") def test_relative_level_scales_no_mpp(): """Test relative_level_scales objective when mpp is None.""" class DummyWSI: """Mock WSIReader for testing.""" @property def info(self): return wsireader.WSIMeta((100, 100), axes="YXS") wsi = DummyWSI() with pytest.raises(ValueError, match="MPP is None"): wsi.info.relative_level_scales(1.0, "mpp") def test_relative_level_scales_no_objective_power(): """Test relative_level_scales objective when objective power is None.""" class DummyWSI: """Mock WSIReader for testing.""" @property def info(self): return wsireader.WSIMeta((100, 100), axes="YXS") wsi = DummyWSI() with pytest.raises(ValueError, match="Objective power is None"): wsi.info.relative_level_scales(10, "power") def test_relative_level_scales_level_too_high(sample_svs): """Test relative_level_scales levels set too high.""" wsi = wsireader.OpenSlideWSIReader(sample_svs) with pytest.raises(ValueError, match="levels"): wsi.info.relative_level_scales(100, "level") def test_find_optimal_level_and_downsample_openslide_interpolation_warning( sample_ndpi, caplog, ): """Test finding optimal level for mpp read with scale > 1. This tests the case where the scale is found to be > 1 and interpolation will be applied to the output. A UserWarning should be raised in this case. """ wsi = wsireader.OpenSlideWSIReader(sample_ndpi) _, _ = wsi._find_optimal_level_and_downsample(0.1, "mpp") assert ( "Read: Scale > 1.This means that the desired resolution is higher" in caplog.text ) def test_find_optimal_level_and_downsample_jp2_interpolation_warning( sample_jp2, caplog ): """Test finding optimal level for mpp read with scale > 1. This tests the case where the scale is found to be > 1 and interpolation will be applied to the output. A UserWarning should be raised in this case. """ wsi = wsireader.OmnyxJP2WSIReader(sample_jp2) _, _ = wsi._find_optimal_level_and_downsample(0.1, "mpp") assert ( "Read: Scale > 1.This means that the desired resolution is higher" in caplog.text ) def test_find_optimal_level_and_downsample_mpp(sample_ndpi): """Test finding optimal level for mpp read.""" wsi = wsireader.OpenSlideWSIReader(sample_ndpi) mpps = [0.5, 10] expected_levels = [0, 4] expected_scales = [[0.91282519, 0.91012514], [0.73026016, 0.72810011]] for mpp, expected_level, expected_scale in zip( mpps, expected_levels, expected_scales ): read_level, post_read_scale_factor = wsi._find_optimal_level_and_downsample( mpp, "mpp" ) assert read_level == expected_level assert post_read_scale_factor == pytest.approx(expected_scale) def test_find_optimal_level_and_downsample_power(sample_ndpi): """Test finding optimal level for objective power read.""" wsi = wsireader.OpenSlideWSIReader(sample_ndpi) objective_powers = [20, 10, 5, 2.5, 1.25] expected_levels = [0, 1, 2, 3, 4] for objective_power, expected_level in zip(objective_powers, expected_levels): read_level, post_read_scale_factor = wsi._find_optimal_level_and_downsample( objective_power, "power" ) assert read_level == expected_level assert np.array_equal(post_read_scale_factor, [1.0, 1.0]) def test_find_optimal_level_and_downsample_level(sample_ndpi): """Test finding optimal level for level read. For integer levels, the returned level should always be the same as the input level. """ wsi = wsireader.OpenSlideWSIReader(sample_ndpi) for level in range(wsi.info.level_count): read_level, post_read_scale_factor = wsi._find_optimal_level_and_downsample( level, "level" ) assert read_level == level assert np.array_equal(post_read_scale_factor, [1.0, 1.0]) def test_convert_resolution_units(sample_ndpi, caplog): """Test the resolution unit conversion code.""" wsi = wsireader.WSIReader.open(sample_ndpi) # test for invalid input and output units with pytest.raises(ValueError, match=r".*Invalid input_unit.*"): wsi.convert_resolution_units(0, input_unit="invalid") with pytest.raises(ValueError, match=r".*Invalid output_unit.*"): wsi.convert_resolution_units(0, input_unit="level", output_unit="level") # Test functionality: Assuming a baseline_mpp to be 0.25 at 40x mag gt_mpp = wsi.info.mpp gt_power = wsi.info.objective_power gt_dict = {"mpp": 2 * gt_mpp, "power": gt_power / 2, "baseline": 0.5} # convert input_unit == "mpp" to other formats output = wsi.convert_resolution_units(2 * gt_mpp, input_unit="mpp") assert output["power"] == gt_dict["power"] # convert input_unit == "power" to other formats output = wsi.convert_resolution_units( gt_power / 2, input_unit="power", output_unit="mpp" ) assert all(output == gt_dict["mpp"]) # convert input_unit == "level" to other formats output = wsi.convert_resolution_units(1, input_unit="level") assert all(output["mpp"] == gt_dict["mpp"]) # convert input_unit == "baseline" to other formats output = wsi.convert_resolution_units(0.5, input_unit="baseline") assert output["power"] == gt_dict["power"] # Test for missing information org_info = wsi.info # test when mpp is missing _info = deepcopy(org_info) _info.mpp = None wsi._m_info = _info with pytest.raises(ValueError, match=r".*Missing 'mpp'.*"): wsi.convert_resolution_units(0, input_unit="mpp") _ = wsi.convert_resolution_units(0, input_unit="power") # test when power is missing _info = deepcopy(org_info) _info.objective_power = None wsi._m_info = _info with pytest.raises(ValueError, match=r".*Missing 'objective_power'.*"): wsi.convert_resolution_units(0, input_unit="power") _ = wsi.convert_resolution_units(0, input_unit="mpp") # test when power and mpp are missing _info = deepcopy(org_info) _info.objective_power = None _info.mpp = None wsi._m_info = _info _ = wsi.convert_resolution_units(0, input_unit="baseline") _ = wsi.convert_resolution_units(0, input_unit="level", output_unit="mpp") assert "output_unit is returned as None." in caplog.text def test_find_read_rect_params_power(sample_ndpi): """Test finding read rect parameters for objective power.""" wsi = wsireader.OpenSlideWSIReader(sample_ndpi) location = NDPI_TEST_TISSUE_LOCATION size = NDPI_TEST_TISSUE_SIZE # Test a range of objective powers for target_scale in [1.25, 2.5, 5, 10, 20]: (level, _, read_size, post_read_scale, _) = wsi.find_read_rect_params( location=location, size=size, resolution=target_scale, units="power", ) assert level >= 0 assert level < wsi.info.level_count # Check that read_size * scale == size post_read_downscaled_size = np.round(read_size * post_read_scale).astype(int) assert np.array_equal(post_read_downscaled_size, np.array(size)) def test_find_read_rect_params_mpp(sample_ndpi): """Test finding read rect parameters for objective mpp.""" wsi = wsireader.OpenSlideWSIReader(sample_ndpi) location = NDPI_TEST_TISSUE_LOCATION size = NDPI_TEST_TISSUE_SIZE # Test a range of MPP for target_scale in range(1, 10): (level, _, read_size, post_read_scale, _) = wsi.find_read_rect_params( location=location, size=size, resolution=target_scale, units="mpp", ) assert level >= 0 assert level < wsi.info.level_count # Check that read_size * scale == size post_read_downscaled_size = np.round(read_size * post_read_scale).astype(int) assert np.array_equal(post_read_downscaled_size, np.array(size)) def test_read_rect_openslide_baseline(sample_ndpi): """Test openslide read rect at baseline. Location coordinate is in baseline (level 0) reference frame. """ wsi = wsireader.OpenSlideWSIReader(sample_ndpi) location = NDPI_TEST_TISSUE_LOCATION size = NDPI_TEST_TISSUE_SIZE im_region = wsi.read_rect(location, size, resolution=0, units="level") assert isinstance(im_region, np.ndarray) assert im_region.dtype == "uint8" assert im_region.shape == (*size[::-1], 3) def test_read_rect_jp2_baseline(sample_jp2): """Test jp2 read rect at baseline. Location coordinate is in baseline (level 0) reference frame. """ wsi = wsireader.OmnyxJP2WSIReader(sample_jp2) location = JP2_TEST_TISSUE_LOCATION size = JP2_TEST_TISSUE_SIZE im_region = wsi.read_rect(location, size, resolution=0, units="level") assert isinstance(im_region, np.ndarray) assert im_region.dtype == "uint8" assert im_region.shape == (*size[::-1], 3) def test_read_rect_tiffreader_svs_baseline(sample_svs): """Test TIFFWSIReader.read_rect with an SVS file at baseline.""" wsi = wsireader.TIFFWSIReader(sample_svs) location = SVS_TEST_TISSUE_LOCATION size = SVS_TEST_TISSUE_SIZE im_region = wsi.read_rect(location, size, resolution=0, units="level") assert isinstance(im_region, np.ndarray) assert im_region.dtype == "uint8" assert im_region.shape == (*size[::-1], 3) def test_read_rect_tiffreader_ome_tiff_baseline(sample_ome_tiff): """Test TIFFWSIReader.read_rect with an OME-TIFF file at baseline.""" wsi = wsireader.TIFFWSIReader(sample_ome_tiff) location = SVS_TEST_TISSUE_LOCATION size = SVS_TEST_TISSUE_SIZE im_region = wsi.read_rect(location, size, resolution=0, units="level") assert isinstance(im_region, np.ndarray) assert im_region.dtype == "uint8" assert im_region.shape == (*size[::-1], 3) def test_is_tiled_tiff(source_image): source_image.replace(source_image.with_suffix(".tiff")) assert wsireader.is_tiled_tiff(source_image.with_suffix(".tiff")) is False source_image.with_suffix(".tiff").replace(source_image) def test_read_rect_openslide_levels(sample_ndpi): """Test openslide read rect with resolution in levels. Location coordinate is in baseline (level 0) reference frame. """ wsi = wsireader.OpenSlideWSIReader(sample_ndpi) location = NDPI_TEST_TISSUE_LOCATION size = NDPI_TEST_TISSUE_SIZE for level in range(wsi.info.level_count): im_region = wsi.read_rect(location, size, resolution=level, units="level") assert isinstance(im_region, np.ndarray) assert im_region.dtype == "uint8" assert im_region.shape == (*size[::-1], 3) def test_read_rect_jp2_levels(sample_jp2): """Test jp2 read rect with resolution in levels. Location coordinate is in baseline (level 0) reference frame. """ wsi = wsireader.OmnyxJP2WSIReader(sample_jp2) location = (0, 0) size = JP2_TEST_TISSUE_SIZE width, height = size for level in range(wsi.info.level_count): level_width, level_height = wsi.info.level_dimensions[level] im_region = wsi.read_rect( location, size, resolution=level, units="level", pad_mode=None, ) assert isinstance(im_region, np.ndarray) assert im_region.dtype == "uint8" assert im_region.shape == pytest.approx( ( min(height, level_height), min(width, level_width), 3, ), abs=1, ) def read_rect_mpp(wsi, location, size): """Read rect with resolution in microns per pixel.""" for factor in range(1, 10): mpp = wsi.info.mpp * factor im_region = wsi.read_rect(location, size, resolution=mpp, units="mpp") assert isinstance(im_region, np.ndarray) assert im_region.dtype == "uint8" assert im_region.shape == (*size[::-1], 3) def test_read_rect_openslide_mpp(sample_ndpi): """Test openslide read rect with resolution in microns per pixel. Location coordinate is in baseline (level 0) reference frame. """ wsi = wsireader.OpenSlideWSIReader(sample_ndpi) location = NDPI_TEST_TISSUE_LOCATION size = NDPI_TEST_TISSUE_SIZE read_rect_mpp(wsi, location, size) def test_read_rect_jp2_mpp(sample_jp2): """Test jp2 read rect with resolution in microns per pixel. Location coordinate is in baseline (level 0) reference frame. """ wsi = wsireader.OmnyxJP2WSIReader(sample_jp2) location = JP2_TEST_TISSUE_LOCATION size = JP2_TEST_TISSUE_SIZE read_rect_mpp(wsi, location, size) def test_read_rect_openslide_objective_power(sample_ndpi): """Test openslide read rect with resolution in objective power. Location coordinate is in baseline (level 0) reference frame. """ wsi = wsireader.OpenSlideWSIReader(sample_ndpi) location = NDPI_TEST_TISSUE_LOCATION size = NDPI_TEST_TISSUE_SIZE read_rect_objective_power(wsi, location, size) def test_read_rect_jp2_objective_power(sample_jp2): """Test jp2 read rect with resolution in objective power. Location coordinate is in baseline (level 0) reference frame. """ wsi = wsireader.OmnyxJP2WSIReader(sample_jp2) location = JP2_TEST_TISSUE_LOCATION size = JP2_TEST_TISSUE_SIZE read_rect_objective_power(wsi, location, size) def test_read_bounds_openslide_baseline(sample_ndpi): """Test openslide read bounds at baseline. Coordinates in baseline (level 0) reference frame. """ wsi = wsireader.OpenSlideWSIReader(sample_ndpi) bounds = NDPI_TEST_TISSUE_BOUNDS size = NDPI_TEST_TISSUE_SIZE im_region = wsi.read_bounds(bounds, resolution=0, units="level") assert isinstance(im_region, np.ndarray) assert im_region.dtype == "uint8" assert im_region.shape == (*size[::-1], 3) def test_read_bounds_jp2_baseline(sample_jp2): """Test jp2 read bounds at baseline. Coordinates in baseline (level 0) reference frame. """ wsi = wsireader.OmnyxJP2WSIReader(sample_jp2) bounds = JP2_TEST_TISSUE_BOUNDS size = JP2_TEST_TISSUE_SIZE im_region = wsi.read_bounds(bounds, resolution=0, units="level") assert isinstance(im_region, np.ndarray) assert im_region.dtype == "uint8" assert im_region.shape == (*size[::-1], 3) bounds = (32768, 42880, 33792, 50000) im_region = wsi.read_bounds(bounds, resolution=2.5, units="power") assert im_region.dtype == "uint8" assert im_region.shape == (445, 64, 3) def test_read_bounds_openslide_levels(sample_ndpi): """Test openslide read bounds with resolution in levels. Coordinates in baseline (level 0) reference frame. """ wsi = wsireader.OpenSlideWSIReader(sample_ndpi) bounds = NDPI_TEST_TISSUE_BOUNDS width, height = NDPI_TEST_TISSUE_SIZE for level, downsample in enumerate(wsi.info.level_downsamples): im_region = wsi.read_bounds(bounds, resolution=level, units="level") assert isinstance(im_region, np.ndarray) assert im_region.dtype == "uint8" expected_output_shape = tuple( np.round([height / downsample, width / downsample, 3]).astype(int) ) assert im_region.shape == expected_output_shape def test_read_bounds_jp2_levels(sample_jp2): """Test jp2 read bounds with resolution in levels. Coordinates in baseline (level 0) reference frame. """ wsi = wsireader.OmnyxJP2WSIReader(sample_jp2) bounds = JP2_TEST_TISSUE_BOUNDS width, height = JP2_TEST_TISSUE_SIZE for level, downsample in enumerate(wsi.info.level_downsamples): im_region = wsi.read_bounds(bounds, resolution=level, units="level") assert isinstance(im_region, np.ndarray) assert im_region.dtype == "uint8" expected_output_shape = tuple( np.round([height / downsample, width / downsample]) ) assert im_region.shape[:2] == pytest.approx(expected_output_shape, abs=1) assert im_region.shape[2] == 3 def test_read_bounds_openslide_mpp(sample_ndpi): """Test openslide read bounds with resolution in microns per pixel. Coordinates in baseline (level 0) reference frame. """ wsi = wsireader.OpenSlideWSIReader(sample_ndpi) bounds = NDPI_TEST_TISSUE_BOUNDS size = NDPI_TEST_TISSUE_SIZE read_bounds_mpp(wsi, bounds, size) def test_read_bounds_jp2_mpp(sample_jp2): """Test jp2 read bounds with resolution in microns per pixel. Coordinates in baseline (level 0) reference frame. """ wsi = wsireader.OmnyxJP2WSIReader(sample_jp2) bounds = JP2_TEST_TISSUE_BOUNDS size = JP2_TEST_TISSUE_SIZE read_bounds_mpp(wsi, bounds, size, jp2=True) def test_read_bounds_openslide_objective_power(sample_ndpi): """Test openslide read bounds with resolution in objective power. Coordinates in baseline (level 0) reference frame. """ wsi = wsireader.OpenSlideWSIReader(sample_ndpi) bounds = NDPI_TEST_TISSUE_BOUNDS size = NDPI_TEST_TISSUE_SIZE slide_power = wsi.info.objective_power read_bounds_objective_power(wsi, slide_power, bounds, size) def test_read_bounds_jp2_objective_power(sample_jp2): """Test jp2 read bounds with resolution in objective power. Coordinates in baseline (level 0) reference frame. """ wsi = wsireader.OmnyxJP2WSIReader(sample_jp2) bounds = JP2_TEST_TISSUE_BOUNDS size = JP2_TEST_TISSUE_SIZE slide_power = wsi.info.objective_power read_bounds_objective_power(wsi, slide_power, bounds, size, jp2=True) def test_read_bounds_interpolated(sample_svs): """Test openslide read bounds with interpolated output. Coordinates in baseline (level 0) reference frame. """ wsi = wsireader.OpenSlideWSIReader(sample_svs) bounds = SVS_TEST_TISSUE_BOUNDS size = SVS_TEST_TISSUE_SIZE im_region = wsi.read_bounds( bounds, resolution=0.1, units="mpp", ) assert 0.1 < wsi.info.mpp[0] assert 0.1 < wsi.info.mpp[1] assert isinstance(im_region, np.ndarray) assert im_region.dtype == "uint8" assert im_region.shape[2] == 3 assert all(np.array(im_region.shape[:2]) > size) def test_read_bounds_level_consistency_openslide(sample_ndpi): """Test read_bounds produces the same visual field across resolution levels.""" wsi = wsireader.OpenSlideWSIReader(sample_ndpi) bounds = NDPI_TEST_TISSUE_BOUNDS read_bounds_level_consistency(wsi, bounds) def test_read_bounds_level_consistency_jp2(sample_jp2): """Test read_bounds produces the same visual field across resolution levels.""" bounds = JP2_TEST_TISSUE_BOUNDS wsi = wsireader.OmnyxJP2WSIReader(sample_jp2) read_bounds_level_consistency(wsi, bounds) def test_wsireader_save_tiles(sample_svs, tmp_path): """Test for save_tiles in wsireader as a python function.""" tmp_path = pathlib.Path(tmp_path) file_types = ("*.svs",) files_all = utils.misc.grab_files_from_dir( input_path=str(pathlib.Path(sample_svs).parent), file_types=file_types, ) wsi = wsireader.OpenSlideWSIReader(files_all[0]) wsi.save_tiles( output_dir=str(tmp_path / "test_wsireader_save_tiles"), tile_objective_value=5, tile_read_size=(5000, 5000), verbose=True, ) assert ( tmp_path / "test_wsireader_save_tiles" / "CMU-1-Small-Region.svs" / "Output.csv" ).exists() assert ( tmp_path / "test_wsireader_save_tiles" / "CMU-1-Small-Region.svs" / "slide_thumbnail.jpg" ).exists() assert ( tmp_path / "test_wsireader_save_tiles" / "CMU-1-Small-Region.svs" / "Tile_5_0_0.jpg" ).exists() def test_incompatible_objective_value(sample_svs, tmp_path): """Test for incompatible objective value.""" wsi = wsireader.OpenSlideWSIReader(sample_svs) with pytest.raises(ValueError, match="objective power"): wsi.save_tiles( output_dir=str( pathlib.Path(tmp_path).joinpath("test_wsireader_save_tiles") ), tile_objective_value=3, tile_read_size=(5000, 5000), verbose=True, ) def test_incompatible_level(sample_svs, tmp_path, caplog): """Test for incompatible objective value.""" wsi = wsireader.OpenSlideWSIReader(sample_svs) wsi.save_tiles( output_dir=str(pathlib.Path(tmp_path).joinpath("test_wsireader_save_tiles2")), tile_objective_value=1, tile_read_size=(500, 500), verbose=True, ) assert "Reading at tile_objective_value 1 not allowed" in caplog.text def test_wsireader_jp2_save_tiles(sample_jp2, tmp_path): """Test for save_tiles in wsireader as a python function.""" tmp_path = pathlib.Path(tmp_path) wsi = wsireader.OmnyxJP2WSIReader(sample_jp2) wsi.save_tiles( output_dir=str(tmp_path / "test_wsireader_jp2_save_tiles"), tile_objective_value=5, tile_read_size=(5000, 5000), verbose=True, ) assert ( tmp_path / "test_wsireader_jp2_save_tiles" / "test1.jp2" / "Output.csv" ).exists() assert ( tmp_path / "test_wsireader_jp2_save_tiles" / "test1.jp2" / "slide_thumbnail.jpg" ).exists() assert ( tmp_path / "test_wsireader_jp2_save_tiles" / "test1.jp2" / "Tile_5_0_0.jpg" ).exists() def test_openslide_objective_power_from_mpp(sample_svs, caplog): """Test OpenSlideWSIReader approximation of objective power from mpp.""" wsi = wsireader.OpenSlideWSIReader(sample_svs) wsi.openslide_wsi = DummyMutableOpenSlideObject(wsi.openslide_wsi) props = wsi.openslide_wsi._properties del props["openslide.objective-power"] # skipcq _ = wsi.info assert "Objective power inferred" in caplog.text del props["openslide.mpp-x"] # skipcq del props["openslide.mpp-y"] # skipcq _ = wsi._info() assert "Unable to determine objective power" in caplog.text def test_openslide_mpp_from_tiff_resolution(sample_svs, caplog): """Test OpenSlideWSIReader mpp from TIFF resolution tags.""" wsi = wsireader.OpenSlideWSIReader(sample_svs) wsi.openslide_wsi = DummyMutableOpenSlideObject(wsi.openslide_wsi) props = wsi.openslide_wsi._properties del props["openslide.mpp-x"] # skipcq del props["openslide.mpp-y"] # skipcq props["tiff.ResolutionUnit"] = "centimeter" props["tiff.XResolution"] = 1e4 # Pixels per cm props["tiff.YResolution"] = 1e4 # Pixels per cm _ = wsi.info assert "Falling back to TIFF resolution" in caplog.text assert np.array_equal(wsi.info.mpp, [1, 1]) def test_virtual_wsi_reader(source_image, caplog): """Test VirtualWSIReader""" wsi = wsireader.VirtualWSIReader(pathlib.Path(source_image)) _ = wsi._info() assert "Unknown scale" in caplog.text _ = wsi._info() assert "Raw data is None" in caplog.text assert wsi.img.shape == (256, 256, 3) img = wsi.read_rect(location=(0, 0), size=(100, 50)) assert img.shape == (50, 100, 3) img = wsi.read_region(location=(0, 0), size=(100, 50), level=0) assert img.shape == (50, 100, 3) def test_virtual_wsi_reader_invalid_mode(source_image): """Test creating a VritualWSIReader with an invalid mode.""" with pytest.raises(ValueError, match="Invalid mode"): wsireader.VirtualWSIReader(pathlib.Path(source_image), mode="foo") def test_virtual_wsi_reader_read_bounds(source_image): """Test VirtualWSIReader read bounds""" wsi = wsireader.VirtualWSIReader(pathlib.Path(source_image)) img = wsi.read_bounds(bounds=(0, 0, 50, 100)) assert img.shape == (100, 50, 3) img = wsi.read_bounds(bounds=(0, 0, 50, 100), resolution=1.5, units="baseline") assert img.shape == (150, 75, 3) img = wsi.read_bounds(bounds=(0, 0, 50, 100), resolution=0.5, units="baseline") assert img.shape == (50, 25, 3) with pytest.raises(IndexError): _ = wsi.read_bounds(bounds=(0, 0, 50, 100), resolution=0.5, units="level") with pytest.raises(ValueError, match="level"): _ = wsi.read_bounds(bounds=(0, 0, 50, 100), resolution=1, units="level") def test_virtual_wsi_reader_read_rect(source_image): """Test VirtualWSIReader read rect.""" wsi = wsireader.VirtualWSIReader(pathlib.Path(source_image)) info = wsi.info img = wsi.read_rect(location=(0, 0), size=(50, 100)) assert img.shape == (100, 50, 3) img = wsi.read_rect( location=(0, 0), size=(50, 100), resolution=1.5, units="baseline" ) assert img.shape == (100, 50, 3) img = wsi.read_rect( location=(0, 0), size=(50, 100), resolution=0.5, units="baseline" ) assert img.shape == (100, 50, 3) with pytest.raises(IndexError): _ = wsi.read_rect( location=(0, 0), size=(50, 100), resolution=0.5, units="level" ) with pytest.raises(ValueError, match="level"): _ = wsi.read_rect(location=(0, 0), size=(50, 100), resolution=1, units="level") wsi = wsireader.VirtualWSIReader(pathlib.Path(source_image), info=info) assert info.as_dict() == wsi.info.as_dict() def test_virtual_wsi_reader_read_bounds_virtual_baseline(source_image): """Test VirtualWSIReader read bounds with virtual baseline.""" image_path = pathlib.Path(source_image) img_array = utils.misc.imread(image_path) img_size = np.array(img_array.shape[:2][::-1]) double_size = tuple((img_size * 2).astype(int)) meta = wsireader.WSIMeta(slide_dimensions=double_size, axes="YXS") wsi = wsireader.VirtualWSIReader(image_path, info=meta) location = (0, 0) size = (50, 100) bounds = utils.transforms.locsize2bounds(location, size) region = wsi.read_bounds(bounds, pad_mode="reflect", interpolation="cubic") target_size = tuple(np.round(np.array([25, 50]) * 2).astype(int)) target = cv2.resize( img_array[:50, :25, :], target_size, interpolation=cv2.INTER_CUBIC ) assert np.abs(np.mean(region.astype(int) - target.astype(int))) < 0.1 def test_virtual_wsi_reader_read_rect_virtual_baseline(source_image): """Test VirtualWSIReader read rect with virtual baseline. Creates a virtual slide with a virtualbaseline size which is twice as large as the input image. """ img_array = utils.misc.imread(pathlib.Path(source_image)) img_size = np.array(img_array.shape[:2][::-1]) double_size = tuple((img_size * 2).astype(int)) meta = wsireader.WSIMeta(slide_dimensions=double_size, axes="YXS") wsi = wsireader.VirtualWSIReader(pathlib.Path(source_image), info=meta) region = wsi.read_rect(location=(0, 0), size=(50, 100), pad_mode="reflect") target = cv2.resize( img_array[:50, :25, :], (50, 100), interpolation=cv2.INTER_CUBIC ) assert np.abs(np.median(region.astype(int) - target.astype(int))) == 0 assert np.abs(np.mean(region.astype(int) - target.astype(int))) < 0.2 def test_virtual_wsi_reader_read_rect_virtual_levels(source_image): """Test VirtualWSIReader read rect with vritual levels. Creates a virtual slide with a virtualbaseline size which is twice as large as the input image and the pyramid/resolution levels. Checks that the regions read at each level line up with expected values. """ img_array = utils.misc.imread(pathlib.Path(source_image)) img_size = np.array(img_array.shape[:2][::-1]) double_size = tuple((img_size * 2).astype(int)) meta = wsireader.WSIMeta( slide_dimensions=double_size, level_downsamples=[1, 2, 4], axes="YXS" ) wsi = wsireader.VirtualWSIReader(pathlib.Path(source_image), info=meta) region = wsi.read_rect(location=(0, 0), size=(50, 100), resolution=1, units="level") target = img_array[:100, :50, :] assert np.abs(np.median(region.astype(int) - target.astype(int))) == 0 assert np.abs(np.mean(region.astype(int) - target.astype(int))) < 1 region = wsi.read_rect(location=(0, 0), size=(50, 100), resolution=2, units="level") target = cv2.resize(img_array[:200, :100, :], (50, 100)) assert np.abs(np.median(region.astype(int) - target.astype(int))) == 0 assert np.abs(np.mean(region.astype(int) - target.astype(int))) < 1 def test_virtual_wsi_reader_read_bounds_virtual_levels(source_image): """Test VirtualWSIReader read bounds with vritual levels. Creates a virtual slide with a virtualbaseline size which is twice as large as the input image and the pyramid/resolution levels. Checks that the regions read at each level line up with expected values. """ img_array = utils.misc.imread(pathlib.Path(source_image)) img_size = np.array(img_array.shape[:2][::-1]) double_size = tuple((img_size * 2).astype(int)) meta = wsireader.WSIMeta( slide_dimensions=double_size, level_downsamples=[1, 2, 4], axes="YXS" ) wsi = wsireader.VirtualWSIReader(pathlib.Path(source_image), info=meta) location = (0, 0) size = (50, 100) bounds = utils.transforms.locsize2bounds(location, size) region = wsi.read_bounds(bounds, resolution=1, units="level") target = img_array[:50, :25, :] assert np.abs(np.median(region.astype(int) - target.astype(int))) == 0 assert np.abs(np.mean(region.astype(int) - target.astype(int))) < 1 region = wsi.read_bounds(bounds, resolution=2, units="level") target_size = tuple(np.round(np.array([25, 50]) / 2).astype(int)) target = cv2.resize( img_array[:50, :25, :], target_size, interpolation=cv2.INTER_CUBIC ) offset, error, _ = phase_cross_correlation(target, region, normalization=None) assert all(offset == 0) assert error < 0.1 psnr = peak_signal_noise_ratio(target, region) assert psnr < 50 def test_virtual_wsi_reader_read_rect_virtual_levels_mpp(source_image): """Test VirtualWSIReader read rect with vritual levels and MPP. Creates a virtual slide with a virtualbaseline size which is twice as large as the input image and the pyramid/resolution levels and a baseline MPP specified. Checks that the regions read with specified MPP for each level lines up with expected values. """ img_array = utils.misc.imread(pathlib.Path(source_image)) img_size = np.array(img_array.shape[:2][::-1]) double_size = tuple((img_size * 2).astype(int)) meta = wsireader.WSIMeta( slide_dimensions=double_size, axes="YXS", level_downsamples=[1, 2, 4], mpp=(0.25, 0.25), ) wsi = wsireader.VirtualWSIReader(pathlib.Path(source_image), info=meta) region = wsi.read_rect(location=(0, 0), size=(50, 100), resolution=0.5, units="mpp") target = img_array[:100, :50, :] assert np.abs(np.mean(region.astype(int) - target.astype(int))) < 1 region = wsi.read_rect(location=(0, 0), size=(50, 100), resolution=1, units="mpp") target = cv2.resize( img_array[:200, :100, :], (50, 100), interpolation=cv2.INTER_CUBIC ) offset, error, _ = phase_cross_correlation(target, region, normalization=None) assert all(offset == 0) assert error < 0.1 psnr = peak_signal_noise_ratio(target, region) assert psnr < 50 def test_virtual_wsi_reader_read_bounds_virtual_levels_mpp(source_image): """Test VirtualWSIReader read bounds with vritual levels and MPP. Creates a virtual slide with a virtualbaseline size which is twice as large as the input image and the pyramid/resolution levels. Checks that the regions read at each level line up with expected values. """ img_array = utils.misc.imread(pathlib.Path(source_image)) img_size = np.array(img_array.shape[:2][::-1]) double_size = tuple((img_size * 2).astype(int)) meta = wsireader.WSIMeta( slide_dimensions=double_size, axes="YXS", level_downsamples=[1, 2, 4], mpp=(0.25, 0.25), ) wsi = wsireader.VirtualWSIReader(pathlib.Path(source_image), info=meta) location = (0, 0) size = (50, 100) bounds = utils.transforms.locsize2bounds(location, size) region = wsi.read_bounds(bounds, resolution=0.5, units="mpp") target = img_array[:50, :25, :] assert np.abs(np.median(region.astype(int) - target.astype(int))) == 0 assert np.abs(np.mean(region.astype(int) - target.astype(int))) < 1 region = wsi.read_bounds(bounds, resolution=1, units="mpp") target_size = tuple(np.round(np.array([25, 50]) / 2).astype(int)) target = cv2.resize( img_array[:50, :25, :], target_size, interpolation=cv2.INTER_CUBIC ) offset, error, _ = phase_cross_correlation(target, region, normalization=None) assert all(offset == 0) assert error < 0.1 psnr = peak_signal_noise_ratio(target, region) assert psnr < 50 def test_tissue_mask_otsu(sample_svs): """Test wsi.tissue_mask with Otsu's method.""" wsi = wsireader.OpenSlideWSIReader(sample_svs) tissue_thumb = wsi.slide_thumbnail() grey_thumb = cv2.cvtColor(tissue_thumb, cv2.COLOR_RGB2GRAY) otsu_threhold = threshold_otsu(grey_thumb) otsu_mask = grey_thumb < otsu_threhold mask = wsi.tissue_mask(method="otsu") mask_thumb = mask.slide_thumbnail() assert np.mean(np.logical_xor(mask_thumb, otsu_mask)) < 0.05 def test_tissue_mask_morphological(sample_svs): """Test wsi.tissue_mask with morphological method.""" wsi = wsireader.OpenSlideWSIReader(sample_svs) resolutions = [5, 10] units = ["power", "mpp"] scale_fns = [lambda x: x * 2, lambda x: 32 / x] for unit, scaler in zip(units, scale_fns): for resolution in resolutions: mask = wsi.tissue_mask( method="morphological", resolution=resolution, units=unit ) tissue_thumb = wsi.slide_thumbnail(resolution, unit) grey_thumb = tissue_thumb.mean(axis=-1) mask_thumb = mask.slide_thumbnail(resolution, unit) otsu_threhold = threshold_otsu(grey_thumb) otsu_mask = grey_thumb < otsu_threhold morpho_mask = binary_dilation(otsu_mask, disk(scaler(resolution))) morpho_mask = remove_small_objects(morpho_mask, 100 * scaler(resolution)) assert np.mean(np.logical_xor(mask_thumb, morpho_mask)) < 0.1 def test_tissue_mask_morphological_levels(sample_svs): """Test wsi.tissue_mask with morphological method and resolution in level.""" wsi = wsireader.OpenSlideWSIReader(sample_svs) thumb = wsi.slide_thumbnail(0, "level") grey_thumb = cv2.cvtColor(thumb, cv2.COLOR_RGB2GRAY) threshold = threshold_otsu(grey_thumb) reference = grey_thumb < threshold # Using kernel_size of 1 mask = wsi.tissue_mask("morphological", 0, "level") mask_thumb = mask.slide_thumbnail(0, "level") assert np.mean(mask_thumb == reference) > 0.99 # Custom kernel_size (should still be close to reference) reference = binary_dilation(reference, disk(3)) mask = wsi.tissue_mask("morphological", 0, "level", kernel_size=3) mask_thumb = mask.slide_thumbnail(0, "level") assert np.mean(mask_thumb == reference) > 0.95 def test_tissue_mask_read_bounds_none_interpolation(sample_svs): """Test reading a mask using read_bounds with no interpolation.""" wsi = wsireader.OpenSlideWSIReader(sample_svs) mask = wsi.tissue_mask("otsu") mask_region = mask.read_bounds((0, 0, 512, 512), interpolation="none") assert mask_region.shape[0] == 32 assert mask_region.shape[1] == 32 def test_tissue_mask_read_rect_none_interpolation(sample_svs): """Test reading a mask using read_rect with no interpolation.""" wsi = wsireader.OpenSlideWSIReader(sample_svs) mask = wsi.tissue_mask("otsu") mask_region = mask.read_rect((0, 0), (512, 512), interpolation="none") assert mask_region.shape[0] == 32 assert mask_region.shape[1] == 32 def test_invalid_masker_method(sample_svs): """Test that an invalid masking method string raises a ValueError.""" wsi = wsireader.OpenSlideWSIReader(sample_svs) with pytest.raises(ValueError, match="masking method"): wsi.tissue_mask(method="foo") def test_wsireader_open( sample_svs, sample_ndpi, sample_jp2, sample_ome_tiff, source_image ): """Test WSIReader.open() to return correct object.""" with pytest.raises(FileNotSupported): _ = WSIReader.open("./sample.csv") with pytest.raises(TypeError): _ = WSIReader.open([1, 2]) wsi = WSIReader.open(sample_svs) assert isinstance(wsi, wsireader.OpenSlideWSIReader) wsi = WSIReader.open(sample_ndpi) assert isinstance(wsi, wsireader.OpenSlideWSIReader) wsi = WSIReader.open(sample_jp2) assert isinstance(wsi, wsireader.OmnyxJP2WSIReader) wsi = WSIReader.open(sample_ome_tiff) assert isinstance(wsi, wsireader.TIFFWSIReader) wsi = WSIReader.open(pathlib.Path(source_image)) assert isinstance(wsi, wsireader.VirtualWSIReader) img = utils.misc.imread(str(pathlib.Path(source_image))) wsi = WSIReader.open(input_img=img) assert isinstance(wsi, wsireader.VirtualWSIReader) # test if WSIReader.open can accept a wsireader instance wsi_type = type(wsi) wsi_out = WSIReader.open(input_img=wsi) assert isinstance(wsi_out, wsi_type) # test loading .npy temp_dir = _get_temp_folder_path() os.mkdir(temp_dir) temp_file = f"{temp_dir}/sample.npy" np.save(temp_file, np.random.randint(1, 255, [5, 5, 5])) wsi_out = WSIReader.open(temp_file) assert isinstance(wsi_out, VirtualWSIReader) shutil.rmtree(temp_dir) def test_jp2_missing_cod(sample_jp2, caplog): """Test for warning if JP2 is missing COD segment.""" wsi = wsireader.OmnyxJP2WSIReader(sample_jp2) wsi.glymur_wsi.codestream.segment = [] _ = wsi.info assert "missing COD" in caplog.text def test_read_rect_at_resolution(sample_wsi_dict): """Test for read rect using location at requested.""" mini_wsi2_svs = pathlib.Path(sample_wsi_dict["wsi1_8k_8k_svs"]) mini_wsi2_jpg = pathlib.Path(sample_wsi_dict["wsi1_8k_8k_jpg"]) mini_wsi2_jp2 = pathlib.Path(sample_wsi_dict["wsi1_8k_8k_jp2"]) # * check sync read between Virtual Reader and WSIReader (openslide) (reference) reader_list = [ VirtualWSIReader(mini_wsi2_jpg), OpenSlideWSIReader(mini_wsi2_svs), OmnyxJP2WSIReader(mini_wsi2_jp2), ] for reader_idx, reader in enumerate(reader_list): roi1 = reader.read_rect( np.array([500, 500]), np.array([2000, 2000]), coord_space="baseline", resolution=1.00, units="baseline", ) roi2 = reader.read_rect( np.array([1000, 1000]), np.array([4000, 4000]), coord_space="resolution", resolution=2.00, units="baseline", ) roi2 = imresize(roi2, output_size=[2000, 2000]) cc = np.corrcoef(roi1[..., 0].flatten(), roi2[..., 0].flatten()) # this control the harshness of similarity test, how much should be? assert np.min(cc) > 0.90, reader_idx def test_read_bounds_location_in_requested_resolution(sample_wsi_dict): """Actually a duel test for sync read and read at requested.""" # """Test synchronize read for VirtualReader""" # convert to pathlib Path to prevent wsireader complaint mini_wsi1_msk = pathlib.Path(sample_wsi_dict["wsi2_4k_4k_msk"]) mini_wsi2_svs = pathlib.Path(sample_wsi_dict["wsi1_8k_8k_svs"]) mini_wsi2_jpg = pathlib.Path(sample_wsi_dict["wsi1_8k_8k_jpg"]) mini_wsi2_jp2 = pathlib.Path(sample_wsi_dict["wsi1_8k_8k_jp2"]) def compare_reader(reader1, reader2, read_coord, read_cfg, check_content=True): """Correlation test to compare output of 2 readers.""" requested_size = read_coord[2:] - read_coord[:2] requested_size = requested_size[::-1] # XY to YX roi1 = reader1.read_bounds( read_coord, coord_space="resolution", pad_constant_values=255, **read_cfg, ) roi2 = reader2.read_bounds( read_coord, coord_space="resolution", pad_constant_values=255, **read_cfg, ) # using only reader 1 because it is reference reader shape1 = reader1.slide_dimensions(**read_cfg) assert roi1.shape[0] == requested_size[0], ( read_cfg, requested_size, roi1.shape, ) assert roi1.shape[1] == requested_size[1], ( read_cfg, requested_size, roi1.shape, ) assert roi1.shape[0] == roi2.shape[0], (read_cfg, roi1.shape, roi2.shape) assert roi1.shape[1] == roi2.shape[1], (read_cfg, roi1.shape, roi2.shape) if check_content: cc = np.corrcoef(roi1[..., 0].flatten(), roi2[..., 0].flatten()) # this control the harshness of similarity test, how much should be? assert np.min(cc) > 0.90, (cc, read_cfg, read_coord, shape1) # * now check sync read by comparing the ROI with different base # the output should be at same resolution even if source is of different base msk = imread(mini_wsi1_msk) msk_reader = VirtualWSIReader(msk) bigger_msk = cv2.resize( msk, (0, 0), fx=4.0, fy=4.0, interpolation=cv2.INTER_NEAREST ) bigger_msk_reader = VirtualWSIReader(bigger_msk) # * must set mpp metadata to not None else wont work ref_metadata = bigger_msk_reader.info ref_metadata.mpp = np.array([1.0, 1.0]) ref_metadata.objective_power = 1.0 msk_reader.info = ref_metadata shape2 = bigger_msk_reader.slide_dimensions(resolution=0.75, units="mpp") shape1 = msk_reader.slide_dimensions(resolution=0.75, units="mpp") assert shape1[0] - shape2[0] < 10 # offset may happen if shape is not multiple assert shape1[1] - shape2[1] < 10 # offset may happen if shape is not multiple shape2 = bigger_msk_reader.slide_dimensions(resolution=0.75, units="power") shape1 = msk_reader.slide_dimensions(resolution=0.75, units="power") assert shape1[0] - shape2[0] < 10 # offset may happen if shape is not multiple assert shape1[1] - shape2[1] < 10 # offset may happen if shape is not multiple # * check sync read between Virtual Reader requested_coords = np.array([3500, 3000, 5500, 7000]) # XY, manually pick # baseline value can be think of as scaling factor wrt baseline read_cfg_list = [ # read at strange resolution value so that if it fails, # normal scale will also fail ({"resolution": 0.75, "units": "mpp"}, np.array([10000, 10000, 15000, 15000])), ( {"resolution": 1.56, "units": "power"}, np.array([10000, 10000, 15000, 15000]), ), ({"resolution": 3.00, "units": "mpp"}, np.array([2500, 2500, 4000, 4000])), ({"resolution": 0.30, "units": "baseline"}, np.array([2000, 2000, 3000, 3000])), ] for _, (read_cfg, read_coord) in enumerate(read_cfg_list): read_coord = requested_coords if read_coord is None else read_coord compare_reader(msk_reader, bigger_msk_reader, read_coord, read_cfg) # * check sync read between Virtual Reader and WSIReader (openslide) (reference) requested_coords = np.array([3500, 3000, 4500, 4000]) # XY, manually pick read_cfg_list = [ # read at strange resolution value so that if it fails, # it means normal scale will also fail ({"resolution": 0.35, "units": "mpp"}, np.array([1000, 1000, 2000, 2000])), ({"resolution": 23.5, "units": "power"}, None), ({"resolution": 0.35, "units": "baseline"}, np.array([1000, 1000, 2000, 2000])), ({"resolution": 1.35, "units": "baseline"}, np.array([8000, 8000, 9000, 9000])), ({"resolution": 1.00, "units": "level"}, np.array([1000, 1000, 2000, 2000])), ] wsi_reader = OpenSlideWSIReader(mini_wsi2_svs) tile = imread(mini_wsi2_jpg) tile = imresize(tile, scale_factor=0.76) vrt_reader = VirtualWSIReader(tile) vrt_reader.info = wsi_reader.info for _, (read_cfg, read_coord) in enumerate(read_cfg_list): read_coord = requested_coords if read_coord is None else read_coord compare_reader(wsi_reader, vrt_reader, read_coord, read_cfg, check_content=True) # * check sync read between Virtual Reader and WSIReader (jp2) (reference) requested_coords = np.array([2500, 2500, 4000, 4000]) # XY, manually pick read_cfg_list = [ # read at strange resolution value so that if it fails, # normal scale will also fail ({"resolution": 0.35, "units": "mpp"}, None), ({"resolution": 23.5, "units": "power"}, None), ({"resolution": 0.65, "units": "baseline"}, np.array([3000, 3000, 4000, 4000])), ({"resolution": 1.35, "units": "baseline"}, np.array([4000, 4000, 5000, 5000])), ({"resolution": 1.00, "units": "level"}, np.array([1500, 1500, 2000, 2000])), ] wsi_reader = OmnyxJP2WSIReader(mini_wsi2_jp2) wsi_thumb = wsi_reader.slide_thumbnail(resolution=0.85, units="mpp") vrt_reader = VirtualWSIReader(wsi_thumb) vrt_reader.info = wsi_reader.info for _, (read_cfg, read_coord) in enumerate(read_cfg_list): read_coord = requested_coords if read_coord is None else read_coord compare_reader(wsi_reader, vrt_reader, read_coord, read_cfg) # ------------------------------------------------------------------------------------- # Command Line Interface # ------------------------------------------------------------------------------------- def test_command_line_read_bounds(sample_ndpi, tmp_path): """Test OpenSlide read_bounds CLI.""" runner = CliRunner() read_bounds_result = runner.invoke( cli.main, [ "read-bounds", "--img-input", str(pathlib.Path(sample_ndpi)), "--resolution", "0", "--units", "level", "--mode", "save", "--region", "0", "0", "2000", "2000", "--output-path", str(pathlib.Path(tmp_path).joinpath("im_region.jpg")), ], ) assert read_bounds_result.exit_code == 0 assert pathlib.Path(tmp_path).joinpath("im_region.jpg").is_file() read_bounds_result = runner.invoke( cli.main, [ "read-bounds", "--img-input", str(pathlib.Path(sample_ndpi)), "--resolution", "0", "--units", "level", "--mode", "save", "--output-path", str(pathlib.Path(tmp_path).joinpath("im_region2.jpg")), ], ) assert read_bounds_result.exit_code == 0 assert pathlib.Path(tmp_path).joinpath("im_region2.jpg").is_file() def test_command_line_jp2_read_bounds(sample_jp2, tmp_path): """Test JP2 read_bounds.""" runner = CliRunner() read_bounds_result = runner.invoke( cli.main, [ "read-bounds", "--img-input", str(pathlib.Path(sample_jp2)), "--resolution", "0", "--units", "level", "--mode", "save", ], ) assert read_bounds_result.exit_code == 0 assert pathlib.Path(tmp_path).joinpath("../im_region.jpg").is_file() @pytest.mark.skipif( utils.env_detection.running_on_ci(), reason="No need to display image on travis.", ) def test_command_line_jp2_read_bounds_show(sample_jp2, tmp_path): """Test JP2 read_bounds with mode as 'show'.""" runner = CliRunner() read_bounds_result = runner.invoke( cli.main, [ "read-bounds", "--img-input", str(pathlib.Path(sample_jp2)), "--resolution", "0", "--units", "level", "--mode", "show", ], ) assert read_bounds_result.exit_code == 0 def test_command_line_unsupported_file_read_bounds(sample_svs, tmp_path): """Test unsupported file read bounds.""" runner = CliRunner() read_bounds_result = runner.invoke( cli.main, [ "read-bounds", "--img-input", str(pathlib.Path(sample_svs))[:-1], "--resolution", "0", "--units", "level", "--mode", "save", ], ) assert read_bounds_result.output == "" assert read_bounds_result.exit_code == 1 assert isinstance(read_bounds_result.exception, FileNotSupported) def test_openslide_read_rect_edge_reflect_padding(sample_svs): """Test openslide edge reflect padding for read_rect.""" wsi = wsireader.OpenSlideWSIReader(sample_svs) region = wsi.read_rect((-64, -64), (128, 128), pad_mode="reflect") assert 0 not in region.min(axis=-1) def test_openslide_read_bounds_edge_reflect_padding(sample_svs): """Test openslide edge reflect padding for read_bounds.""" wsi = wsireader.OpenSlideWSIReader(sample_svs) region = wsi.read_bounds((-64, -64, 64, 64), pad_mode="reflect") assert 0 not in region.min(axis=-1) def test_tiffwsireader_invalid_tiff(remote_sample): """Test for TIFF which is not supported by TIFFWSIReader.""" with pytest.raises(ValueError, match="Unsupported TIFF"): _ = wsireader.TIFFWSIReader(remote_sample("two-tiled-pages")) def test_tiffwsireader_invalid_svs_metadata(sample_svs, monkeypatch): """Test for invalid SVS key-value pairs in TIFF escription tag.""" wsi = wsireader.TIFFWSIReader(sample_svs) monkeypatch.setattr( wsi.tiff.pages[0], "description", wsi.tiff.pages[0].description.replace("=", "=="), ) with pytest.raises(ValueError, match="key=value"): _ = wsi._info() def test_tiffwsireader_invalid_ome_metadata(sample_ome_tiff, monkeypatch): """Test exception raised for invalid OME-XML metadata instrument.""" wsi = wsireader.TIFFWSIReader(sample_ome_tiff) monkeypatch.setattr( wsi.tiff.pages[0], "description", wsi.tiff.pages[0].description.replace( '<Objective ID="Objective:0:0" NominalMagnification="20.0"/>', "" ), ) with pytest.raises(KeyError, match="No matching Instrument"): _ = wsi._info() def test_tiffwsireader_ome_metadata_missing_one_mppy( sample_ome_tiff, monkeypatch, caplog ): """Test no exception raised for missing x/y mpp but warning given.""" for dim in "XY": wsi = wsireader.TIFFWSIReader(sample_ome_tiff) monkeypatch.setattr( wsi.tiff.pages[0], "description", re.sub(f'PhysicalSize{dim}="[^"]*"', "", wsi.tiff.pages[0].description), ) _ = wsi._info() assert "Only one MPP" in caplog.text def test_arrayview_unsupported_axes(): """Test unsupported axes in ArrayView.""" array = zarr.ones((128, 128, 3)) array_view = ArrayView(array=array, axes="FOO") with pytest.raises(ValueError, match="Unsupported axes"): array_view[:64, :64, :] def test_arrayview_unsupported_axes_shape(sample_ome_tiff, monkeypatch): """Test accessing an unspported axes in TIFFWSIReader._shape_channels_last.""" wsi = wsireader.TIFFWSIReader(sample_ome_tiff) monkeypatch.setattr(wsi, "_axes", "FOO") with pytest.raises(ValueError, match="Unsupported axes"): _ = wsi._info() def test_arrayview_incomplete_index(): """Test reading from ArrayView without specifying all axes slices.""" array = zarr.array(np.random.rand(128, 128, 3)) array_view = ArrayView(array=array, axes="YXS") view_1 = array_view[:64, :64, :] view_2 = array_view[:64, :64] assert np.array_equal(view_1, view_2) def test_arrayview_single_number_index(): """Test reading a column from ArrayView. I'm not sure why you would want to do this but it is implemented for consistency with other __getitem__ objects. """ array = zarr.array(np.random.rand(128, 128, 3)) array_view = ArrayView(array=array, axes="YXS") view_1 = array_view[0] view_2 = array_view[0] assert np.array_equal(view_1, view_2) def test_manual_mpp_tuple(sample_svs): """Test setting a manual mpp for a WSI.""" wsi = wsireader.OpenSlideWSIReader(sample_svs, mpp=(0.123, 0.123)) assert tuple(wsi.info.mpp) == (0.123, 0.123) def test_manual_mpp_float(sample_svs): """Test setting a manual mpp for a WSI.""" wsi = wsireader.OpenSlideWSIReader(sample_svs, mpp=0.123) assert tuple(wsi.info.mpp) == (0.123, 0.123) def test_manual_mpp_invalid(sample_svs): """Test setting a manual mpp for a WSI.""" with pytest.raises(TypeError, match="mpp"): _ = wsireader.OpenSlideWSIReader(sample_svs, mpp=(0.5,)) with pytest.raises(TypeError, match="mpp"): _ = wsireader.OpenSlideWSIReader(sample_svs, mpp="foo") def test_manual_power_tuple(sample_svs): """Test setting a manual power for a WSI.""" wsi = wsireader.OpenSlideWSIReader(sample_svs, power=42) assert wsi.info.objective_power == 42 def test_manual_power_invalid(sample_svs): """Test setting a manual power for a WSI.""" with pytest.raises(TypeError, match="power"): _ = wsireader.OpenSlideWSIReader(sample_svs, power=(42,)) def test_tiled_tiff_openslide(remote_sample): """Test reading a tiled TIFF file with OpenSlide.""" sample_path = remote_sample("tiled-tiff-1-small-jpeg") # Test with top-level import wsi = WSIReader.open(sample_path) assert isinstance(wsi, wsireader.OpenSlideWSIReader) def test_tiled_tiff_tifffile(remote_sample): """Test fallback to tifffile for files which openslide cannot read. E.G. tiled tiffs with JPEG XL compression. """ sample_path = remote_sample("tiled-tiff-1-small-jp2k") wsi = wsireader.WSIReader.open(sample_path) assert isinstance(wsi, wsireader.TIFFWSIReader) def test_is_zarr_empty_dir(tmp_path): """Test is_zarr is false for an empty .zarr directory.""" zarr_dir = tmp_path / "zarr.zarr" zarr_dir.mkdir() assert not is_zarr(zarr_dir) def test_is_zarr_array(tmp_path): """Test is_zarr is true for a .zarr directory with an array.""" zarr_dir = tmp_path / "zarr.zarr" zarr_dir.mkdir() _zarray_path = zarr_dir / ".zarray" minimal_zarray = { "shape": [1, 1, 1], "dtype": "uint8", "compressor": { "id": "lz4", }, "chunks": [1, 1, 1], "fill_value": 0, "order": "C", "filters": None, "zarr_format": 2, } with open(_zarray_path, "w") as f: json.dump(minimal_zarray, f) assert is_zarr(zarr_dir) def test_is_zarr_group(tmp_path): """Test is_zarr is true for a .zarr directory with an group.""" zarr_dir = tmp_path / "zarr.zarr" zarr_dir.mkdir() _zgroup_path = zarr_dir / ".zgroup" minimal_zgroup = { "zarr_format": 2, } with open(_zgroup_path, "w") as f: json.dump(minimal_zgroup, f) assert is_zarr(zarr_dir) def test_is_ngff_regular_zarr(tmp_path): """Test is_ngff is false for a regular zarr.""" zarr_path = tmp_path / "zarr.zarr" zarr.open(zarr_path, "w") assert is_zarr(zarr_path) assert not is_ngff(zarr_path) # check we get the appropriate error message if we open it with pytest.raises(FileNotSupported, match="does not appear to be a v0.4"): WSIReader.open(zarr_path) def test_store_reader_no_info(tmp_path): """Test AnnotationStoreReader with no info.""" SQLiteStore(tmp_path / "store.db") with pytest.raises(ValueError, match="No metadata found"): AnnotationStoreReader(tmp_path / "store.db") def test_store_reader_explicit_info(remote_sample, tmp_path): """Test AnnotationStoreReader with explicit info.""" SQLiteStore(tmp_path / "store.db") wsi_reader = WSIReader.open(remote_sample("svs-1-small")) reader = AnnotationStoreReader(tmp_path / "store.db", wsi_reader.info) assert reader._info().as_dict() == wsi_reader.info.as_dict() def test_store_reader_from_store(remote_sample, tmp_path): """Test AnnotationStoreReader from an AnnotationStore object.""" store = SQLiteStore(remote_sample("annotation_store_svs_1")) reader = AnnotationStoreReader(store) assert isinstance(reader.store, SQLiteStore) def test_store_reader_base_wsi_str(remote_sample, tmp_path): """Test AnnotationStoreReader with base_wsi as a string.""" store = SQLiteStore(remote_sample("annotation_store_svs_1")) reader = AnnotationStoreReader(store, base_wsi=remote_sample("svs-1-small")) assert isinstance(reader.store, SQLiteStore) assert isinstance(reader.base_wsi, WSIReader) def test_store_reader_alpha(remote_sample): """Test AnnotationStoreReader with alpha channel.""" wsi_reader = WSIReader.open(remote_sample("svs-1-small")) store_reader = AnnotationStoreReader( remote_sample("annotation_store_svs_1"), wsi_reader.info, base_wsi=wsi_reader, ) wsi_thumb = wsi_reader.slide_thumbnail() wsi_tile = wsi_reader.read_rect((500, 500), (1000, 1000)) store_thumb = store_reader.slide_thumbnail() store_tile = store_reader.read_rect((500, 500), (1000, 1000)) store_reader.alpha = 0.2 store_thumb_alpha = store_reader.slide_thumbnail() store_tile_alpha = store_reader.read_rect((500, 500), (1000, 1000)) # the thumbnail with low alpha should be closer to wsi_thumb assert np.mean(np.abs(store_thumb_alpha - wsi_thumb)) < np.mean( np.abs(store_thumb - wsi_thumb) ) # the tile with low alpha should be closer to wsi_tile assert np.mean(np.abs(store_tile_alpha - wsi_tile)) < np.mean( np.abs(store_tile - wsi_tile) ) def test_store_reader_no_types(tmp_path, remote_sample): """Test AnnotationStoreReader with no types.""" SQLiteStore(tmp_path / "store.db") wsi_reader = WSIReader.open(remote_sample("svs-1-small")) reader = AnnotationStoreReader(tmp_path / "store.db", wsi_reader.info) # shouldn't try to color by type if not present assert reader.renderer.score_prop is None def test_store_reader_info_from_base(tmp_path, remote_sample): """Test AnnotationStoreReader with no wsi metadata. Test that AnnotationStoreReader will correctly get metadata from a provided base_wsi if the store has no wsi metadata. """ SQLiteStore(tmp_path / "store.db") wsi_reader = WSIReader.open(remote_sample("svs-1-small")) store_reader = AnnotationStoreReader(tmp_path / "store.db", base_wsi=wsi_reader) # the store reader should have the same metadata as the base wsi assert store_reader.info.mpp[0] == wsi_reader.info.mpp[0] def test_ngff_zattrs_non_micrometer_scale_mpp(tmp_path, caplog): """Test that mpp is None if scale is not in micrometers.""" sample = _fetch_remote_sample("ngff-1") # Create a copy of the sample with a non-micrometer scale sample_copy = tmp_path / "ngff-1" shutil.copytree(sample, sample_copy) with open(sample_copy / ".zattrs", "r") as fh: zattrs = json.load(fh) zattrs["multiscales"][0]["axes"][0]["unit"] = "foo" with open(sample_copy / ".zattrs", "w") as fh: json.dump(zattrs, fh, indent=2) wsi = wsireader.NGFFWSIReader(sample_copy) assert "micrometer" in caplog.text assert wsi.info.mpp is None def test_ngff_zattrs_missing_axes_mpp(tmp_path): """Test that mpp is None if axes are missing.""" sample = _fetch_remote_sample("ngff-1") # Create a copy of the sample with no axes sample_copy = tmp_path / "ngff-1" shutil.copytree(sample, sample_copy) with open(sample_copy / ".zattrs", "r") as fh: zattrs = json.load(fh) zattrs["multiscales"][0]["axes"] = [] with open(sample_copy / ".zattrs", "w") as fh: json.dump(zattrs, fh, indent=2) wsi = wsireader.NGFFWSIReader(sample_copy) assert wsi.info.mpp is None def test_ngff_empty_datasets_mpp(tmp_path): """Test that mpp is None if there are no datasets.""" sample = _fetch_remote_sample("ngff-1") # Create a copy of the sample with no axes sample_copy = tmp_path / "ngff-1" shutil.copytree(sample, sample_copy) with open(sample_copy / ".zattrs", "r") as fh: zattrs = json.load(fh) zattrs["multiscales"][0]["datasets"] = [] with open(sample_copy / ".zattrs", "w") as fh: json.dump(zattrs, fh, indent=2) wsi = wsireader.NGFFWSIReader(sample_copy) assert wsi.info.mpp is None def test_ngff_no_scale_transforms_mpp(tmp_path): """Test that mpp is None if no scale transforms are present.""" sample = _fetch_remote_sample("ngff-1") # Create a copy of the sample with no axes sample_copy = tmp_path / "ngff-1.zarr" shutil.copytree(sample, sample_copy) with open(sample_copy / ".zattrs", "r") as fh: zattrs = json.load(fh) for i, _ in enumerate(zattrs["multiscales"][0]["datasets"]): datasets = zattrs["multiscales"][0]["datasets"][i] datasets["coordinateTransformations"][0]["type"] = "identity" with open(sample_copy / ".zattrs", "w") as fh: json.dump(zattrs, fh, indent=2) wsi = wsireader.NGFFWSIReader(sample_copy) assert wsi.info.mpp is None def test_ngff_missing_omero_version(tmp_path): """Test that the reader can handle missing omero version.""" sample = _fetch_remote_sample("ngff-1") # Create a copy of the sample sample_copy = tmp_path / "ngff-1.zarr" shutil.copytree(sample, sample_copy) with open(sample_copy / ".zattrs", "r") as fh: zattrs = json.load(fh) # Remove the omero version del zattrs["omero"]["version"] with open(sample_copy / ".zattrs", "w") as fh: json.dump(zattrs, fh, indent=2) wsireader.WSIReader.open(sample_copy) def test_ngff_missing_multiscales_returns_false(tmp_path): """Test that missing multiscales key returns False for is_ngff.""" sample = _fetch_remote_sample("ngff-1") # Create a copy of the sample sample_copy = tmp_path / "ngff-1.zarr" shutil.copytree(sample, sample_copy) with open(sample_copy / ".zattrs", "r") as fh: zattrs = json.load(fh) # Remove the multiscales key del zattrs["multiscales"] with open(sample_copy / ".zattrs", "w") as fh: json.dump(zattrs, fh, indent=2) assert not wsireader.is_ngff(sample_copy) def test_ngff_wrong_format_metadata(tmp_path, caplog): """Test that is_ngff is False and logs a warning if metadata is wrong.""" sample = _fetch_remote_sample("ngff-1") # Create a copy of the sample sample_copy = tmp_path / "ngff-1.zarr" shutil.copytree(sample, sample_copy) with open(sample_copy / ".zattrs", "r") as fh: zattrs = json.load(fh) # Change the format to something else zattrs["multiscales"] = "foo" with open(sample_copy / ".zattrs", "w") as fh: json.dump(zattrs, fh, indent=2) with caplog.at_level(logging.WARNING): assert not wsireader.is_ngff(sample_copy) assert "must be present and of the correct type" in caplog.text def test_ngff_omero_below_min_version(tmp_path): """Test for FileNotSupported when omero version is below minimum.""" sample = _fetch_remote_sample("ngff-1") # Create a copy of the sample sample_copy = tmp_path / "ngff-1.zarr" shutil.copytree(sample, sample_copy) with open(sample_copy / ".zattrs", "r") as fh: zattrs = json.load(fh) # Change the format to something else zattrs["omero"]["version"] = "0.0" with open(sample_copy / ".zattrs", "w") as fh: json.dump(zattrs, fh, indent=2) with pytest.raises(FileNotSupported): wsireader.WSIReader.open(sample_copy) def test_ngff_omero_above_max_version(tmp_path, caplog): """Test for FileNotSupported when omero version is above maximum.""" sample = _fetch_remote_sample("ngff-1") # Create a copy of the sample sample_copy = tmp_path / "ngff-1.zarr" shutil.copytree(sample, sample_copy) with open(sample_copy / ".zattrs", "r") as fh: zattrs = json.load(fh) # Change the format to something else zattrs["omero"]["version"] = "10.0" with open(sample_copy / ".zattrs", "w") as fh: json.dump(zattrs, fh, indent=2) # Check that the warning is logged with caplog.at_level(logging.WARNING): wsireader.WSIReader.open(sample_copy) assert "maximum supported version" in caplog.text def test_ngff_multiscales_below_min_version(tmp_path): """Test for FileNotSupported when multiscales version is below minimum.""" sample = _fetch_remote_sample("ngff-1") # Create a copy of the sample sample_copy = tmp_path / "ngff-1.zarr" shutil.copytree(sample, sample_copy) with open(sample_copy / ".zattrs", "r") as fh: zattrs = json.load(fh) # Change the format to something else zattrs["multiscales"][0]["version"] = "0.0" with open(sample_copy / ".zattrs", "w") as fh: json.dump(zattrs, fh, indent=2) with pytest.raises(FileNotSupported): wsireader.WSIReader.open(sample_copy) def test_ngff_multiscales_above_max_version(tmp_path, caplog): """Test for FileNotSupported when multiscales version is above maximum.""" sample = _fetch_remote_sample("ngff-1") # Create a copy of the sample sample_copy = tmp_path / "ngff-1.zarr" shutil.copytree(sample, sample_copy) with open(sample_copy / ".zattrs", "r") as fh: zattrs = json.load(fh) # Change the format to something else zattrs["multiscales"][0]["version"] = "10.0" with open(sample_copy / ".zattrs", "w") as fh: json.dump(zattrs, fh, indent=2) # Check that the warning is logged with caplog.at_level(logging.WARNING): wsireader.WSIReader.open(sample_copy) assert "maximum supported version" in caplog.text def test_ngff_non_numeric_version(tmp_path, monkeypatch): """Test that the reader can handle non-numeric omero versions.""" # Patch the is_ngff function to change the min/max version if_ngff = wsireader.is_ngff # noqa: F841 min_version = Version("0.4") max_version = Version("0.5") def patched_is_ngff( path: Path, min_version: Version = min_version, max_version: Version = max_version, ) -> bool: """Patched is_ngff function with new min/max version.""" return is_ngff(path, min_version, max_version) monkeypatch.setattr(wsireader, "is_ngff", patched_is_ngff) sample = _fetch_remote_sample("ngff-1") # Create a copy of the sample sample_copy = tmp_path / "ngff-1.zarr" shutil.copytree(sample, sample_copy) with open(sample_copy / ".zattrs", "r") as fh: zattrs = json.load(fh) # Set the omero version to a non-numeric string zattrs["omero"]["version"] = "0.5-dev" with open(sample_copy / ".zattrs", "w") as fh: json.dump(zattrs, fh, indent=2) wsireader.WSIReader.open(sample_copy) def test_ngff_inconsistent_multiscales_versions(tmp_path, caplog): """Test that the reader logs a warning inconsistent multiscales versions.""" sample = _fetch_remote_sample("ngff-1") # Create a copy of the sample sample_copy = tmp_path / "ngff-1.zarr" shutil.copytree(sample, sample_copy) with open(sample_copy / ".zattrs", "r") as fh: zattrs = json.load(fh) # Set the versions to be inconsistent multiscales = zattrs["multiscales"] # Needs at least 2 multiscales to be inconsistent if len(multiscales) < 2: multiscales.append(copy.deepcopy(multiscales[0])) for i, _ in enumerate(multiscales): multiscales[i]["version"] = f"0.{i}-dev" zattrs["omero"]["multiscales"] = multiscales with open(sample_copy / ".zattrs", "w") as fh: json.dump(zattrs, fh, indent=2) # Capture logger output to check for warning with caplog.at_level(logging.WARNING), pytest.raises(FileNotSupported): wsireader.WSIReader.open(sample_copy) assert "multiple versions" in caplog.text class TestReader: scenarios = [ ( "AnnotationReaderOverlaid", { "reader_class": AnnotationStoreReader, "sample_key": "annotation_store_svs_1", "kwargs": { "renderer": AnnotationRenderer( "type", COLOR_DICT, ), "base_wsi": WSIReader.open(_fetch_remote_sample("svs-1-small")), "alpha": 0.5, }, }, ), ( "AnnotationReaderMaskOnly", { "reader_class": AnnotationStoreReader, "sample_key": "annotation_store_svs_1", "kwargs": { "renderer": AnnotationRenderer( "type", COLOR_DICT, blur_radius=3, ), }, }, ), ( "TIFFReader", { "reader_class": TIFFWSIReader, "sample_key": "ome-brightfield-pyramid-1-small", "kwargs": {}, }, ), ( "DICOMReader", { "reader_class": DICOMWSIReader, "sample_key": "dicom-1", "kwargs": {}, }, ), ( "NGFFWSIReader", { "reader_class": NGFFWSIReader, "sample_key": "ngff-1", "kwargs": {}, }, ), ( "OpenSlideWSIReader (Small SVS)", { "reader_class": OpenSlideWSIReader, "sample_key": "svs-1-small", "kwargs": {}, }, ), ( "OmnyxJP2WSIReader", { "reader_class": OmnyxJP2WSIReader, "sample_key": "jp2-omnyx-1", "kwargs": {}, }, ), ] @staticmethod def test_base_open(sample_key, reader_class, kwargs): """Checks that WSIReader.open detects the type correctly.""" sample = _fetch_remote_sample(sample_key) wsi = WSIReader.open(sample) assert isinstance(wsi, reader_class) @staticmethod def test_wsimeta_attrs(sample_key, reader_class, kwargs): """Check for expected attrs in .info / WSIMeta. Checks for existence of expected attrs but not their contents. """ sample = _fetch_remote_sample(sample_key) wsi = reader_class(sample, **kwargs) info = wsi.info expected_attrs = [ "slide_dimensions", "axes", "level_dimensions", "level_count", "level_downsamples", "vendor", "mpp", "objective_power", "file_path", ] for attr in expected_attrs: assert hasattr(info, attr) @staticmethod def test_read_rect_level_consistency(sample_key, reader_class, kwargs): """Compare the same region at each stored resolution level. Read the same region at each stored resolution level and compare the resulting image using phase cross correlation to check that they are aligned. """ sample = _fetch_remote_sample(sample_key) wsi = reader_class(sample, **kwargs) location = (0, 0) size = np.array([1024, 1024]) # Avoid testing very small levels (e.g. as in Omnyx JP2) because # MSE for very small levels is noisy. level_downsamples = [ downsample for downsample in wsi.info.level_downsamples if downsample <= 32 ] imgs = [ wsi.read_rect(location, size // downsample, level, "level") for level, downsample in enumerate(level_downsamples) ] smallest_size = imgs[-1].shape[:2][::-1] resized = [imresize(img, output_size=smallest_size) for img in imgs] # Some blurring applied to account for changes in sharpness arising # from interpolation when calculating the downsampled levels. This # adds some tolerance for the comparison. blurred = [cv2.GaussianBlur(img, (5, 5), cv2.BORDER_REFLECT) for img in resized] as_float = [img.astype(np.float_) for img in blurred] # Pair-wise check resolutions for mean squared error for i, a in enumerate(as_float): for b in as_float[i + 1 :]: _, error, phase_diff = phase_cross_correlation(a, b, normalization=None) assert phase_diff < 0.125 assert error < 0.125 @staticmethod def test_read_bounds_level_consistency(sample_key, reader_class, kwargs): """Compare the same region at each stored resolution level. Read the same region at each stored resolution level and compare the resulting image using phase cross correlation to check that they are aligned. """ sample = _fetch_remote_sample(sample_key) wsi = reader_class(sample, **kwargs) bounds = (0, 0, 1024, 1024) # This logic can be moved from the helper to here when other # reader classes have been parameterised into scenarios also. read_bounds_level_consistency(wsi, bounds) @staticmethod def test_fuzz_read_region_baseline_size(sample_key, reader_class, kwargs): """Fuzz test for `read_bounds` output size at level 0 (baseline). - Tests that the output image size matches the input bounds size. - 50 random seeded reads are performed. - All test bounds are within the the slide dimensions. - Bounds sizes are randomised between 1 and 512 in width and height. """ random.seed(123) sample = _fetch_remote_sample(sample_key) wsi = reader_class(sample, **kwargs) width, height = wsi.info.slide_dimensions iterations = 50 for _ in range(iterations): size = (random.randint(1, 512), random.randint(1, 512)) location = ( random.randint(0, width - size[0]), random.randint(0, height - size[1]), ) bounds = locsize2bounds(location, size) region = wsi.read_bounds(bounds, resolution=0, units="level") assert region.shape[:2][::-1] == size @staticmethod def test_read_rect_coord_space_consistency(sample_key, reader_class, kwargs): """Test that read_rect coord_space modes are consistent. Using `read_rect` with `coord_space="baseline"` and `coord_space="resolution"` should produce the same output when the bounds are a multiple of the scale difference between the two modes. I.E. reading at baseline with a set of coordinates should yield the same region as reading at half the resolution and with coordinates which are half the size. Note that the output will not be of the same size, but the field of view will match. """ sample = _fetch_remote_sample(sample_key) reader = reader_class(sample, **kwargs) roi1 = reader.read_rect( np.array([500, 500]), np.array([2000, 2000]), coord_space="baseline", resolution=1.00, units="baseline", ) roi2 = reader.read_rect( np.array([250, 250]), np.array([1000, 1000]), coord_space="resolution", resolution=0.5, units="baseline", ) # Make the regions the same size for comparison of content roi2 = imresize(roi2, output_size=[2000, 2000]) # Check MSE mse = np.mean((roi1 - roi2) ** 2) assert mse < 100 # Check PSNR psnr = peak_signal_noise_ratio(roi1, roi2) assert psnr > 25 # Check SSIM (skip very small roi regions) if np.greater(roi1.shape[2], 16).all(): ssim = structural_similarity(roi1, roi2, multichannel=True) assert ssim > 0.9 @staticmethod def test_file_path_does_not_exist(sample_key, reader_class, kwargs): """Test that FileNotFoundError is raised when file does not exist.""" with pytest.raises(FileNotFoundError): _ = reader_class("./foo.bar") @staticmethod def test_read_mpp(sample_key, reader_class, kwargs): """Test that the mpp is read correctly.""" sample = _fetch_remote_sample(sample_key) wsi = reader_class(sample, **kwargs) assert wsi.info.mpp == pytest.approx(0.25, 1)
90,197
35.326218
88
py
tiatoolbox
tiatoolbox-master/tests/test_save_tiles.py
"""Tests for code related to saving image tiles.""" import os import pathlib from click.testing import CliRunner from tiatoolbox import cli # ------------------------------------------------------------------------------------- # Command Line Interface # ------------------------------------------------------------------------------------- def test_command_line_save_tiles(sample_all_wsis2, tmp_path): """Test for save_tiles CLI.""" runner = CliRunner() save_tiles_result = runner.invoke( cli.main, [ "save-tiles", "--img-input", str(pathlib.Path(sample_all_wsis2)), "--file-types", "*.ndpi, *.svs, *.jp2", "--tile-objective-value", "5", "--output-path", os.path.join(tmp_path, "all_tiles"), ], ) tmp_path = pathlib.Path(tmp_path) cmu_small_region = tmp_path / "all_tiles" / "CMU-1-Small-Region.svs" bioformatspull2759 = tmp_path / "all_tiles" / "bioformatspull2759.ndpi" test1jp2 = tmp_path / "all_tiles" / "test1.jp2" assert save_tiles_result.exit_code == 0 assert (cmu_small_region / "Output.csv").exists() assert (cmu_small_region / "slide_thumbnail.jpg").exists() assert (cmu_small_region / "Tile_5_0_0.jpg").exists() assert (bioformatspull2759 / "Output.csv").exists() assert (bioformatspull2759 / "slide_thumbnail.jpg").exists() assert (bioformatspull2759 / "Tile_5_0_0.jpg").exists() assert (test1jp2 / "Output.csv").exists() assert (test1jp2 / "slide_thumbnail.jpg").exists() assert (test1jp2 / "Tile_5_0_0.jpg").exists() def test_command_line_save_tiles_single_file(sample_svs, tmp_path): """Test for save_tiles CLI single file.""" runner = CliRunner() save_svs_tiles_result = runner.invoke( cli.main, [ "save-tiles", "--img-input", str(sample_svs), "--file-types", "*.ndpi, *.svs", "--tile-objective-value", "5", "--output-path", tmp_path, "--verbose", "True", ], ) assert save_svs_tiles_result.exit_code == 0 assert ( pathlib.Path(tmp_path) .joinpath("CMU-1-Small-Region.svs") .joinpath("Output.csv") .exists() ) assert ( pathlib.Path(tmp_path) .joinpath("CMU-1-Small-Region.svs") .joinpath("slide_thumbnail.jpg") .exists() ) assert ( pathlib.Path(tmp_path) .joinpath("CMU-1-Small-Region.svs") .joinpath("Tile_5_0_0.jpg") .exists() ) def test_command_line_save_tiles_file_not_found(sample_svs, tmp_path): """Test for save_tiles CLI file not found error.""" runner = CliRunner() save_svs_tiles_result = runner.invoke( cli.main, [ "save-tiles", "--img-input", str(sample_svs)[:-1], "--file-types", "*.ndpi, *.svs", "--tile-objective-value", "5", "--output-path", tmp_path, ], ) assert save_svs_tiles_result.output == "" assert save_svs_tiles_result.exit_code == 1 assert isinstance(save_svs_tiles_result.exception, FileNotFoundError)
3,319
28.642857
87
py
tiatoolbox
tiatoolbox-master/tests/__init__.py
"""Unit test package for tiatoolbox."""
40
19.5
39
py
tiatoolbox
tiatoolbox-master/tests/test_metrics.py
"""Tests for metrics package in the toolbox.""" import numpy as np import pytest from tiatoolbox.utils.metrics import dice, f1_detection, pair_coordinates def test_pair_coordinates(): """Test for unique coordinates matching.""" set_a = np.array([[0, 0], [1, 1], [2, 2], [3, 3], [4, 4]]) set_b = np.array([[0.1, 0.1], [1.1, 1.1], [2.1, 2.1], [3.1, 3.1], [4.2, 4.2]]) # 4 in set_a and 4, 5 in set B should be unpaired paired, unpaired_a, unpaired_b = pair_coordinates(set_a, set_b, 0.15) assert len(paired) == 4 assert len(unpaired_a) == 1 assert np.all(set_a[unpaired_a[0]] == np.array([4, 4])) assert len(unpaired_b) == 1 assert np.all(set_b[unpaired_b[0]] == np.array([4.2, 4.2])) def test_f1_detection(): """Test for calculate F1 detection.""" set_a = np.array([[0, 0], [1, 1], [2, 2], [3, 3], [4, 4]]) set_b = np.array([[0.1, 0.1], [1.1, 1.1], [2.1, 2.1], [3.1, 3.1], [4.2, 4.2]]) score = f1_detection(set_a, set_b, 0.2) assert score - 1.0 < 1.0e-6 def test_dice(): """Test to calculate DICE.""" gt_mask = np.random.randint(2, size=(256, 256)) pred_mask = np.random.randint(2, size=(256, 256)) dice_val = dice(gt_mask, pred_mask) assert dice_val >= 0 assert dice_val <= 1.0 gt_mask = np.ones(shape=(256, 256)) pred_mask = np.ones(shape=(256, 256)) dice_val = dice(gt_mask, pred_mask) assert dice_val == 1.0 gt_mask = np.ones(shape=(256, 256)) pred_mask = np.zeros(shape=(256, 256)) dice_val = dice(gt_mask, pred_mask) assert dice_val == 0.0 gt_mask = np.zeros(shape=(256, 256)) pred_mask = np.zeros(shape=(256, 256)) dice_val = dice(gt_mask, pred_mask) assert np.isnan(dice_val) def test_dice_shape_mismatch_error(): """Tests if the shape of inputs does not match.""" gt_mask = np.random.randint(2, size=(256, 256, 1)) pred_mask = np.random.randint(2, size=(256, 256, 3)) with pytest.raises(ValueError, match=r".*Shape mismatch between the two masks.*"): _ = dice(gt_mask, pred_mask)
2,059
31.698413
86
py
tiatoolbox
tiatoolbox-master/tests/test_wsimeta.py
"""Tests for obtaining whole-slide image metadata.""" import numpy as np import pytest from tiatoolbox.wsicore import WSIMeta, wsimeta, wsireader # noinspection PyTypeChecker def test_wsimeta_init_fail(): """Test incorrect init for WSIMeta raises TypeError.""" with pytest.raises(TypeError): wsimeta.WSIMeta(slide_dimensions=(None, None), axes="YXS") @pytest.mark.filterwarnings("ignore") def test_wsimeta_validate_fail(): """Test failure cases for WSIMeta validation.""" meta = wsimeta.WSIMeta(slide_dimensions=(512, 512), axes="YXS", level_dimensions=[]) assert meta.validate() is False meta = wsimeta.WSIMeta( slide_dimensions=(512, 512), axes="YXS", level_dimensions=[(512, 512), (256, 256)], level_count=3, ) assert meta.validate() is False meta = wsimeta.WSIMeta( slide_dimensions=(512, 512), axes="YXS", level_downsamples=[1, 2], ) assert meta.validate() is False meta = wsimeta.WSIMeta( slide_dimensions=(512, 512), axes="YXS", level_downsamples=[1, 2], ) assert meta.validate() is False meta = wsimeta.WSIMeta(slide_dimensions=(512, 512), axes="YXS") meta.level_dimensions = None assert meta.validate() is False meta = wsimeta.WSIMeta(slide_dimensions=(512, 512), axes="YXS") meta.level_downsamples = None assert meta.validate() is False @pytest.mark.filterwarnings("ignore") def test_wsimeta_validate_invalid_axes(): """Test failure cases for WSIMeta validation with invalid axes.""" meta = wsimeta.WSIMeta(slide_dimensions=(512, 512), axes="YXSF") assert meta.validate() is False @pytest.mark.filterwarnings("ignore") def test_wsimeta_validate_pass(): """Test WSIMeta validation.""" meta = wsimeta.WSIMeta(slide_dimensions=(512, 512), axes="YXS") assert meta.validate() # Test with top-level import meta = WSIMeta( slide_dimensions=(512, 512), axes="YXS", level_dimensions=[(512, 512), (256, 256)], level_downsamples=[1, 2], ) assert meta.validate() def test_wsimeta_openslidewsireader_ndpi(sample_ndpi): """Test OpenSlide reader metadata for ndpi.""" wsi_obj = wsireader.OpenSlideWSIReader(sample_ndpi) meta = wsi_obj.info assert meta.validate() def test_wsimeta_openslidewsireader_svs(sample_svs): """Test OpenSlide reader metadata for svs.""" wsi_obj = wsireader.OpenSlideWSIReader(sample_svs) meta = wsi_obj.info assert meta.validate() meta.mpp = None m = meta.as_dict() assert isinstance(m["mpp"], tuple) def test_wsimeta_setter(sample_svs): """Test setter for metadata.""" wsi = wsireader.OpenSlideWSIReader(sample_svs) meta = wsi.info assert not np.array_equal(meta.mpp, np.array([1, 1])) meta.mpp = np.array([1, 1]) wsi.info = meta assert meta.validate() assert np.array_equal(wsi.info.mpp, np.array([1, 1]))
2,968
27.548077
88
py
tiatoolbox
tiatoolbox-master/tests/test_tiffreader.py
import pytest from defusedxml import ElementTree from tiatoolbox.data import _fetch_remote_sample from tiatoolbox.wsicore import wsireader def test_ome_missing_instrument_ref(monkeypatch): """Test that an OME-TIFF can be read without instrument reference.""" sample = _fetch_remote_sample("ome-brightfield-pyramid-1-small") wsi = wsireader.TIFFWSIReader(sample) page = wsi.tiff.pages[0] description = page.description tree = ElementTree.fromstring(description) namespaces = { "ome": "http://www.openmicroscopy.org/Schemas/OME/2016-06", } images = tree.findall("ome:Image", namespaces) for image in images: instruments = image.findall("ome:InstrumentRef", namespaces) for instrument in instruments: image.remove(instrument) new_description = ElementTree.tostring(tree, encoding="unicode") monkeypatch.setattr(page, "description", new_description) monkeypatch.setattr(wsi, "_m_info", None) assert wsi.info.objective_power is None def test_ome_missing_physicalsize(monkeypatch): """Test that an OME-TIFF can be read without physical size.""" sample = _fetch_remote_sample("ome-brightfield-pyramid-1-small") wsi = wsireader.TIFFWSIReader(sample) page = wsi.tiff.pages[0] description = page.description tree = ElementTree.fromstring(description) namespaces = { "ome": "http://www.openmicroscopy.org/Schemas/OME/2016-06", } images = tree.findall("ome:Image", namespaces) for image in images: pixels = image.find("ome:Pixels", namespaces) del pixels.attrib["PhysicalSizeX"] del pixels.attrib["PhysicalSizeY"] new_description = ElementTree.tostring(tree, encoding="unicode") monkeypatch.setattr(page, "description", new_description) monkeypatch.setattr(wsi, "_m_info", None) assert wsi.info.mpp is None def test_ome_missing_physicalsizey(monkeypatch, caplog): """Test that an OME-TIFF can be read without physical size.""" sample = _fetch_remote_sample("ome-brightfield-pyramid-1-small") wsi = wsireader.TIFFWSIReader(sample) page = wsi.tiff.pages[0] description = page.description tree = ElementTree.fromstring(description) namespaces = { "ome": "http://www.openmicroscopy.org/Schemas/OME/2016-06", } images = tree.findall("ome:Image", namespaces) for image in images: pixels = image.find("ome:Pixels", namespaces) del pixels.attrib["PhysicalSizeY"] new_description = ElementTree.tostring(tree, encoding="unicode") monkeypatch.setattr(page, "description", new_description) monkeypatch.setattr(wsi, "_m_info", None) assert pytest.approx(wsi.info.mpp, abs=0.1) == 0.5 assert "Only one MPP value found. Using it for both X and Y" in caplog.text def test_tiffreader_non_tiled_metadata(monkeypatch): """Test that fetching metadata for non-tiled TIFF works.""" sample = _fetch_remote_sample("ome-brightfield-pyramid-1-small") wsi = wsireader.TIFFWSIReader(sample) monkeypatch.setattr(wsi.tiff, "is_ome", False) monkeypatch.setattr( wsi.tiff.pages[0].__class__, "is_tiled", property(lambda _: False), # skipcq: PYL-W0612 ) monkeypatch.setattr(wsi, "_m_info", None) assert pytest.approx(wsi.info.mpp, abs=0.1) == 0.5
3,333
39.168675
80
py
tiatoolbox
tiatoolbox-master/tests/test_annotation_stores.py
"""Tests for annotation store classes.""" import json import pickle import random import sqlite3 import sys from itertools import repeat from numbers import Number from pathlib import Path from timeit import timeit from typing import Any, Dict, Generator, List, Tuple, Union import numpy as np import pandas as pd import pytest from shapely import affinity from shapely.geometry import MultiPoint, Polygon from shapely.geometry.point import Point from tiatoolbox.annotation.storage import ( Annotation, AnnotationStore, DictionaryStore, SQLiteMetadata, SQLiteStore, ) sqlite3.enable_callback_tracebacks(True) # Constants GRID_SIZE = (10, 10) FILLED_LEN = 2 * (GRID_SIZE[0] * GRID_SIZE[1]) # Helper Functions def cell_polygon( xy: Tuple[Number, Number], n_points: int = 20, radius: Number = 10, noise: Number = 0.01, eccentricity: Tuple[Number, Number] = (1, 3), repeat_first: bool = True, direction: str = "CCW", ) -> Polygon: """Generate a fake cell boundary polygon. Cell boundaries are generated an ellipsoids with randomised eccentricity, added noise, and a random rotation. Args: xy (tuple(int)): The x,y centre point to generate the cell boundary around. n_points (int): Number of points in the boundary. Defaults to 20. radius (float): Radius of the points from the centre. Defaults to 10. noise (float): Noise to add to the point locations. Defaults to 1. eccentricity (tuple(float)): Range of values (low, high) to use for randomised eccentricity. Defaults to (1, 3). repeat_first (bool): Enforce that the last point is equal to the first. direction (str): Ordering of the points. Defaults to "CCW". Valid options are: counter-clockwise "CCW", and clockwise "CW". """ if repeat_first: n_points -= 1 # Generate points about an ellipse with random eccentricity x, y = xy alpha = np.linspace(0, 2 * np.pi - (2 * np.pi / n_points), n_points) rx = radius * (np.random.rand() + 0.5) ry = np.random.uniform(*eccentricity) * radius - 0.5 * rx x = rx * np.cos(alpha) + x + (np.random.rand(n_points) - 0.5) * noise y = ry * np.sin(alpha) + y + (np.random.rand(n_points) - 0.5) * noise boundary_coords = np.stack([x, y], axis=1).tolist() # Copy first coordinate to the end if required if repeat_first: boundary_coords = boundary_coords + [boundary_coords[0]] # Swap direction if direction.strip().lower() == "cw": boundary_coords = boundary_coords[::-1] polygon = Polygon(boundary_coords) # Add random rotation angle = np.random.rand() * 360 return affinity.rotate(polygon, angle, origin="centroid") def sample_where_1(props: Dict[str, Any]) -> bool: """Simple example predicate function for tests. Checks for a class = 1. """ return props.get("class") == 1 def sample_where_123(props: Dict[str, Any]) -> bool: """Simple example predicate function for tests. Checks for a class = 123. """ return props.get("class") == 123 def sample_select(props: Dict[str, Any]) -> Tuple[Any]: """Simple example select expression for tests. Gets the class value. """ return props.get("class") def sample_multi_select(props: Dict[str, Any]) -> Tuple[Any]: """Simple example select expression for tests. Gets the class value and the class mod 2. """ return (props.get("class"), props.get("class") % 2) def annotations_center_of_mass(annotations): """Compute the mean of the annotation centroids.""" centroids = [annotation.geometry.centroid for annotation in annotations] return MultiPoint(centroids).centroid def test_annotation_repr(): """Test the repr of an annotation.""" annotation = Annotation(Polygon([(0, 0), (1, 1), (2, 0)])) assert isinstance(repr(annotation), str) assert repr(annotation).startswith("Annotation(") assert "POLYGON" in repr(annotation) assert repr(annotation).endswith(")") # Fixtures @pytest.fixture(scope="session") def cell_grid() -> List[Polygon]: """Generate a grid of fake cell boundary polygon annotations.""" np.random.seed(0) return [cell_polygon((i * 25, j * 25)) for i, j in np.ndindex(*GRID_SIZE)] @pytest.fixture(scope="session") def points_grid() -> List[Polygon]: """Generate a grid of fake point annotations.""" np.random.seed(0) return [Point((i * 25, j * 25)) for i, j in np.ndindex(*GRID_SIZE)] @pytest.fixture(scope="session") def sample_triangle() -> Polygon: """Simple triangle polygon used for testing.""" return Polygon([(0, 0), (1, 1), (2, 0)]) @pytest.fixture() def fill_store(cell_grid, points_grid): """Factory fixture to fill stores with test data.""" def _fill_store( store_class: AnnotationStore, path: Union[str, Path], ): store = store_class(path) annotations = [Annotation(cell) for cell in cell_grid] + [ Annotation(point, properties={"class": random.randint(0, 4)}) for point in points_grid ] keys = store.append_many(annotations) return keys, store return _fill_store # Class Specific Tests def test_sqlite_store_compile_options(): options = SQLiteStore.compile_options() assert all(isinstance(x, str) for x in options) def test_sqlite_store_compile_options_exception(monkeypatch): monkeypatch.setattr(sqlite3, "sqlite_version_info", (3, 37, 0)) monkeypatch.setattr( SQLiteStore, "compile_options", lambda x: ["ENABLE_RTREE", "ENABLE_JSON1"], raising=True, ) SQLiteStore() monkeypatch.setattr(SQLiteStore, "compile_options", lambda x: [], raising=True) with pytest.raises(EnvironmentError, match="RTREE and JSON1"): SQLiteStore() def test_sqlite_store_compile_options_exception_v3_38(monkeypatch): monkeypatch.setattr(sqlite3, "sqlite_version_info", (3, 38, 0)) monkeypatch.setattr( SQLiteStore, "compile_options", lambda x: ["OMIT_JSON"], raising=True ) with pytest.raises(EnvironmentError, match="JSON must not"): SQLiteStore() def test_sqlite_store_compile_options_missing_math(monkeypatch, caplog): """Test that a warning is shown if the sqlite math module is missing.""" monkeypatch.setattr( SQLiteStore, "compile_options", lambda x: ["ENABLE_JSON1", "ENABLE_RTREE"], raising=True, ) SQLiteStore() assert "SQLite math functions are not enabled" in caplog.text def test_sqlite_store_multiple_connection(tmp_path): store = SQLiteStore(tmp_path / "annotations.db") store2 = SQLiteStore(tmp_path / "annotations.db") assert len(store) == len(store2) def test_sqlite_store_index_type_error(): """Test adding an index of invalid type.""" store = SQLiteStore() with pytest.raises(TypeError, match="where"): store.create_index("foo", lambda g, p: "foo" in p) def test_sqlite_store_index_version_error(monkeypatch): """Test adding an index with SQlite <3.9.""" store = SQLiteStore() monkeypatch.setattr(sqlite3, "sqlite_version_info", (3, 8, 0)) with pytest.raises(EnvironmentError, match="Requires sqlite version 3.9.0"): store.create_index("foo", lambda _, p: "foo" in p) def test_sqlite_store_index_str(fill_store, tmp_path): """Test that adding an index improves performance.""" _, store = fill_store(SQLiteStore, tmp_path / "polygon.db") def query(): """Test query.""" return store.iquery((0, 0, 1e4, 1e4), where="props['class'] == 0") def alt_query(): """Alternative query to avoid temporary caches giving unfair advantage.""" return store.iquery((0, 0, 1e4, 1e4), where="has_key(props, 'foo')") # Do an initial bunch of queries to initialise any internal state or # caches. _ = timeit(query, number=10) # Time query without index t1 = timeit(query, number=50) # Create the index properties_predicate = "props['class']" store.create_index("test_index", properties_predicate) # Do another unrelated query _ = timeit(alt_query, number=10) # Time the original query with the index t2 = timeit(query, number=50) assert t2 < t1 def test_sqlite_create_index_no_analyze(fill_store, tmp_path): """Test that creating an index without ANALYZE.""" _, store = fill_store(SQLiteStore, tmp_path / "polygon.db") properties_predicate = "props['class']" store.create_index("test_index", properties_predicate, analyze=False) assert "test_index" in store.indexes() def test_sqlite_pquery_warn_no_index(fill_store, caplog): """Test that querying without an index warns.""" _, store = fill_store(SQLiteStore, ":memory:") store.pquery("*", unique=False) assert "Query is not using an index." in caplog.text # Check that there is no warning after creating the index store.create_index("test_index", "props['class']") with pytest.warns(None) as record: store.pquery("props['class']") assert len(record) == 0 def test_sqlite_store_indexes(fill_store, tmp_path): """Test getting a list of index names.""" _, store = fill_store(SQLiteStore, tmp_path / "polygon.db") store.create_index("test_index", "props['class']") assert "test_index" in store.indexes() def test_sqlite_drop_index_error(fill_store, tmp_path): """Test dropping an index that does not exist.""" _, store = fill_store(SQLiteStore, tmp_path / "polygon.db") with pytest.raises(sqlite3.OperationalError, match="no such index"): store.drop_index("test_index") def test_sqlite_store_unsupported_compression(sample_triangle): """Test that using an unsupported compression str raises error.""" store = SQLiteStore(compression="foo") with pytest.raises(ValueError, match="Unsupported"): _ = store.serialise_geometry(sample_triangle) def test_sqlite_optimize(fill_store, tmp_path): """Test optimizing the database.""" _, store = fill_store(SQLiteStore, tmp_path / "polygon.db") store.optimize() def test_sqlite_store_no_compression(sample_triangle): """Test that using no compression raises no error.""" store = SQLiteStore(compression=None) serialised = store.serialise_geometry(sample_triangle) deserialised = store.deserialize_geometry(serialised) assert deserialised.wkb == sample_triangle.wkb def test_sqlite_store_unsupported_decompression(): """Test that using an unsupported decompression str raises error.""" store = SQLiteStore(compression="foo") with pytest.raises(ValueError, match="Unsupported"): _ = store.deserialize_geometry(bytes()) def test_sqlite_store_wkt_deserialisation(sample_triangle): """Test WKT deserialisation.""" store = SQLiteStore(compression=None) wkt = sample_triangle.wkt geom = store.deserialize_geometry(wkt) assert geom == sample_triangle def test_sqlite_store_wkb_deserialisation(sample_triangle): """Test WKB deserialisation. Test the default stattic method in the ABC. """ wkb = sample_triangle.wkb geom = AnnotationStore.deserialize_geometry(wkb) assert geom == sample_triangle def test_sqlite_store_metadata_get_key(): """Test getting a metadata entry.""" store = SQLiteStore() assert store.metadata["compression"] == "zlib" def test_sqlite_store_metadata_get_keyerror(): """Test getting a metadata entry that does not exists.""" store = SQLiteStore() with pytest.raises(KeyError): store.metadata["foo"] def test_sqlite_store_metadata_delete_keyerror(): """Test deleting a metadata entry that does not exists.""" store = SQLiteStore(compression=None) with pytest.raises(KeyError): del store.metadata["foo"] def test_sqlite_store_metadata_delete(): """Test adding and deleting a metadata entry.""" store = SQLiteStore(compression=None) store.metadata["foo"] = 1 assert "foo" in store.metadata del store.metadata["foo"] assert "foo" not in store.metadata def test_sqlite_store_metadata_iter(): """Test iterating over metadata entries.""" conn = sqlite3.Connection(":memory:") metadata = SQLiteMetadata(conn) metadata["foo"] = 1 metadata["bar"] = 2 assert set(metadata.keys()) == {"foo", "bar"} def test_sqlite_store_metadata_len(): """Test len of metadata entries.""" conn = sqlite3.Connection(":memory:") metadata = SQLiteMetadata(conn) metadata["foo"] = 1 metadata["bar"] = 2 assert len(metadata) == 2 def test_sqlite_drop_index(): """Test creating and dropping an index.""" store = SQLiteStore() store.create_index("foo", "props['class']") assert "foo" in store.indexes() store.drop_index("foo") assert "foo" not in store.indexes() def test_sqlite_drop_index_fail(): """Test dropping an index that does not exist.""" store = SQLiteStore() with pytest.raises(sqlite3.OperationalError): store.drop_index("foo") def test_sqlite_optimize_no_vacuum(fill_store, tmp_path): """Test running the optimize function on an SQLiteStore without VACUUM.""" _, store = fill_store(SQLiteStore, tmp_path / "polygon.db") store.optimize(limit=0, vacuum=False) def test_annotation_to_geojson(): """Test converting an annotation to geojson.""" annotation = Annotation( geometry=Point(0, 0), properties={"foo": "bar", "baz": "qux"}, ) geojson = json.loads(annotation.to_geojson()) assert geojson["type"] == "Feature" assert geojson["geometry"]["type"] == "Point" assert geojson["properties"] == {"foo": "bar", "baz": "qux"} def test_remove_area_column(fill_store): """Test removing an area column.""" _, store = fill_store(SQLiteStore, ":memory:") store.remove_area_column() assert "area" not in store._get_table_columns() result = store.query((0, 0, 1000, 1000)) assert len(result) == 200 store.add_area_column() assert "area" in store.indexes() store.remove_area_column() # Check that the index is removed if its there assert "area" not in store.indexes() def test_remove_area_column_indexed(fill_store): """Test removing an area column if theres an index on it.""" _, store = fill_store(SQLiteStore, ":memory:") store.create_index("area", '"area"') store.remove_area_column() assert "area" not in store._get_table_columns() result = store.query((0, 0, 1000, 1000)) assert len(result) == 200 def test_add_area_column(fill_store): """Test adding an area column.""" _, store = fill_store(SQLiteStore, ":memory:") store.remove_area_column() store.add_area_column() assert "area" in store.indexes() assert "area" in store._get_table_columns() # check the results are properly sorted by area result = store.query((0, 0, 100, 100)) areas = [ann.geometry.area for ann in result.values()] assert areas == sorted(areas, reverse=True) # check add index option of add_area_column _, store = fill_store(SQLiteStore, ":memory:") store.remove_area_column() assert "area" not in store.indexes() store.add_area_column(False) assert "area" not in store.indexes() def test_query_min_area(fill_store): """Test querying with a minimum area.""" _, store = fill_store(SQLiteStore, ":memory:") result = store.query((0, 0, 1000, 1000), min_area=1) assert len(result) == 100 # should only get cells, pts are too small def test_query_min_area_no_area_column(fill_store): """Test querying with a minimum area when there is no area column.""" _, store = fill_store(SQLiteStore, ":memory:") store.remove_area_column() with pytest.raises(ValueError, match="without an area column"): store.query((0, 0, 1000, 1000), min_area=1) def test_auto_commit(fill_store, tmp_path): """Test auto commit. Check that if auto-commit is False, the changes are not committed until commit() is called. """ _, store = fill_store(SQLiteStore, tmp_path / "polygon.db") store.close() store = SQLiteStore(tmp_path / "polygon.db", auto_commit=False) keys = list(store.keys()) store.patch(keys[0], Point(-500, -500)) store.append_many([Annotation(Point(10, 10), {}), Annotation(Point(20, 20), {})]) store.remove_many(keys[5:10]) store.clear() store.close() store = SQLiteStore(tmp_path / "polygon.db") result = store.query((0, 0, 1000, 1000)) assert len(result) == 200 # check none of the changes were committed store = SQLiteStore(tmp_path / "polygon2.db", auto_commit=False) store.append_many([Annotation(Point(10, 10), {}), Annotation(Point(20, 20), {})]) store.commit() store.close() store = SQLiteStore(tmp_path / "polygon2.db") assert len(store) == 2 # check explicitly committing works def test_init_base_class_exception(): """Test that the base class cannot be initialized.""" with pytest.raises(TypeError, match="abstract class"): AnnotationStore() # skipcq: PYL-E0110 # Annotation Store Interface Tests (AnnotationStoreABC) class TestStore: scenarios = [ ("Dictionary", {"store_cls": DictionaryStore}), ("SQLite", {"store_cls": SQLiteStore}), ] @staticmethod def test_open_close(fill_store, tmp_path, store_cls): """Test opening and closing a store.""" path = tmp_path / "polygons" keys, store = fill_store(store_cls, path) store.close() store2 = store.open(path) assert len(store2) == len(keys) @staticmethod def test_append_many(cell_grid, tmp_path, store_cls): """Test bulk append of annotations.""" store = store_cls(tmp_path / "polygons") annotations = [ Annotation(cell, {"class": random.randint(0, 6)}) for cell in cell_grid ] keys = store.append_many(annotations) assert len(keys) == len(cell_grid) @staticmethod def test_append_many_with_keys(cell_grid, tmp_path, store_cls): """Test bulk append of annotations with keys.""" store = store_cls(tmp_path / "polygons") annotations = [ Annotation(cell, {"class": random.randint(0, 6)}) for cell in cell_grid ] keys = [chr(n) for n, _ in enumerate(annotations)] returned_keys = store.append_many(annotations, keys=keys) assert len(returned_keys) == len(cell_grid) assert keys == returned_keys @staticmethod def test_append_many_with_keys_len_mismatch(cell_grid, tmp_path, store_cls): """Test bulk append of annotations with keys of wrong length.""" store = store_cls(tmp_path / "polygons") annotations = [ Annotation(cell, {"class": random.randint(0, 6)}) for cell in cell_grid ] keys = ["foo"] with pytest.raises(ValueError, match="equal"): store.append_many(annotations, keys=keys) @staticmethod def test_query_bbox(fill_store, tmp_path, store_cls): """Test query with a bounding box.""" _, store = fill_store(store_cls, tmp_path / "polygon.db") results = store.query((0, 0, 25, 25)) assert len(results) == 8 @staticmethod def test_iquery_bbox(fill_store, tmp_path, store_cls): """Test iquery with a bounding box.""" _, store = fill_store(store_cls, tmp_path / "polygon.db") results = store.iquery((0, 0, 25, 25)) assert len(results) == 8 assert all(isinstance(key, str) for key in results) @staticmethod def test_query_polygon(fill_store, tmp_path, store_cls): """Test query with a non-rectangular geometry.""" _, store = fill_store(store_cls, tmp_path / "polygon.db") results = store.query(Polygon([(0, 0), (0, 25), (1, 1), (25, 0)])) assert len(results) == 6 assert all(isinstance(ann, Annotation) for ann in results.values()) @staticmethod def test_iquery_polygon(fill_store, tmp_path, store_cls): """Test iquery with a non-rectangular geometry.""" _, store = fill_store(store_cls, tmp_path / "polygon.db") results = store.iquery(Polygon([(0, 0), (0, 25), (1, 1), (25, 0)])) assert len(results) == 6 assert all(isinstance(key, str) for key in results) @staticmethod def test_patch(fill_store, tmp_path, store_cls): """Test patching an annotation.""" keys, store = fill_store(store_cls, tmp_path / "polygon.db") key = keys[0] new_geometry = Polygon([(0, 0), (1, 1), (2, 2)]) # Geometry update store.patch(key, new_geometry) assert store[key].geometry == new_geometry # Properties update store.patch(key, properties={"abc": 123}) assert store[key].properties["abc"] == 123 @staticmethod def test_patch_append(fill_store, tmp_path, store_cls): """Test patching an annotation that does not exist.""" _, store = fill_store(store_cls, tmp_path / "polygon.db") new_geometry = Polygon([(0, 0), (1, 1), (2, 2)]) store.patch("foo", new_geometry) assert store["foo"].geometry == new_geometry @staticmethod def test_patch_many(fill_store, tmp_path, store_cls): """Test bulk patch.""" keys, store = fill_store(store_cls, tmp_path / "polygon.db") new_geometry = Polygon([(0, 0), (1, 1), (2, 2)]) store.patch_many( keys, repeat(new_geometry, len(keys)), repeat({"abc": 123}, len(keys)) ) for _, key in enumerate(keys[:10]): assert store[key].geometry == new_geometry assert store[key].properties["abc"] == 123 @staticmethod def test_patch_many_no_properies(fill_store, tmp_path, store_cls): """Test bulk patch with no properties.""" keys, store = fill_store(store_cls, tmp_path / "polygon.db") new_geometry = Polygon([(0, 0), (1, 1), (2, 2)]) store.patch_many(keys, repeat(new_geometry, len(keys))) for _, key in enumerate(keys[:10]): assert store[key].geometry == new_geometry assert store[key].properties == {} @staticmethod def test_patch_many_no_geometry(fill_store, tmp_path, store_cls): """Test bulk patch with no geometry.""" keys, store = fill_store(store_cls, tmp_path / "polygon.db") store.patch_many(keys, properties_iter=repeat({"abc": 123}, len(keys))) for _, key in enumerate(keys[:10]): assert store[key].geometry is not None assert store[key].properties["abc"] == 123 @staticmethod def test_patch_many_no_geometry_no_properties(fill_store, tmp_path, store_cls): """Test bulk patch with no geometry and no properties.""" keys, store = fill_store(store_cls, tmp_path / "polygon.db") with pytest.raises(ValueError, match="At least one"): store.patch_many(keys) @staticmethod def test_patch_many_append(fill_store, tmp_path, store_cls): """Test bulk patching annotations that do not exist.""" _, store = fill_store(store_cls, tmp_path / "polygon.db") new_geometry = Polygon([(0, 0), (1, 1), (2, 2)]) store.patch_many(["foo", "bar"], repeat(new_geometry, 2)) assert store["foo"].geometry == new_geometry assert store["bar"].geometry == new_geometry @staticmethod def test_patch_many_len_mismatch(fill_store, tmp_path, store_cls): """Test bulk patch with wrong number of keys.""" keys, store = fill_store(store_cls, tmp_path / "polygon.db") new_geometry = Polygon([(0, 0), (1, 1), (2, 2)]) with pytest.raises(ValueError, match="equal"): store.patch_many(keys[1:], repeat(new_geometry, 10)) @staticmethod def test_keys(fill_store, tmp_path, store_cls): """Test getting an keys iterator.""" keys, store = fill_store(store_cls, tmp_path / "polygon.db") keys = list(keys) assert len(list(store.keys())) == len(keys) assert isinstance(list(store.keys())[0], type(keys[0])) @staticmethod def test_remove(fill_store, tmp_path, store_cls): """Test removing an annotation.""" keys, store = fill_store(store_cls, tmp_path / "polygon.db") key = keys[0] store.remove(key) assert len(store) == FILLED_LEN - 1 @staticmethod def test_delitem(fill_store, tmp_path, store_cls): """Test using the delitem syntax.""" keys, store = fill_store(store_cls, tmp_path / "polygon.db") key = keys[0] del store[key] assert len(store) == FILLED_LEN - 1 @staticmethod def test_remove_many(fill_store, tmp_path, store_cls): """Test bulk deletion.""" keys, store = fill_store(store_cls, tmp_path / "polygon.db") store.remove_many(keys) assert len(store) == 0 @staticmethod def test_len(fill_store, tmp_path, store_cls): """Test finding the number of annotation via the len operator.""" _, store = fill_store(store_cls, tmp_path / "polygon.db") assert len(store) == FILLED_LEN @staticmethod def test_contains(fill_store, tmp_path, store_cls): """Test using the contains (in) operator.""" keys, store = fill_store(store_cls, tmp_path / "polygon.db") for key in keys: assert key in store @staticmethod def test_iter(fill_store, tmp_path, store_cls): """Test iterating over the store.""" keys, store = fill_store(store_cls, tmp_path / "polygon.db") for key in store: assert key in keys @staticmethod def test_getitem(fill_store, tmp_path, sample_triangle, store_cls): """Test the getitem syntax.""" _, store = fill_store(store_cls, tmp_path / "polygon.db") key = store.append(Annotation(sample_triangle)) annotation = store[key] assert annotation.geometry == sample_triangle assert annotation.properties == {} @staticmethod def test_setitem(fill_store, tmp_path, sample_triangle, store_cls): """Test the setitem syntax.""" _, store = fill_store(store_cls, tmp_path / "polygon.db") key = store.append(Annotation(sample_triangle)) new_geometry = Polygon([(0, 0), (1, 1), (2, 2)]) new_properties = {"abc": 123} store[key] = Annotation(new_geometry, new_properties) assert store[key] == Annotation(new_geometry, new_properties) @staticmethod def test_getitem_setitem_cycle(fill_store, tmp_path, sample_triangle, store_cls): """Test getting an setting an annotation.""" _, store = fill_store(store_cls, tmp_path / "polygon.db") key = store.append(Annotation(sample_triangle, {"class": 0})) annotation = store[key] store[key] = annotation assert store[key] == annotation @staticmethod def test_from_dataframe(cell_grid, store_cls): """Test loading from to a pandas dataframe.""" df = pd.DataFrame.from_records( [ { "geometry": cell, "row_id": n, } for n, cell in enumerate(cell_grid) ] ) store = store_cls.from_dataframe(df) keys = list(store.keys()) annotation = store[keys[0]] assert "row_id" in annotation.properties @staticmethod def test_to_dataframe(fill_store, tmp_path, store_cls): """Test converting to a pandas dataframe.""" _, store = fill_store(store_cls, tmp_path / "polygon.db") df = store.to_dataframe() assert isinstance(df, pd.DataFrame) assert len(df) == FILLED_LEN assert "geometry" in df.columns assert df.index.name == "key" assert isinstance(df.geometry.iloc[0], Polygon) @staticmethod def test_features(fill_store, tmp_path, store_cls): """Test converting to a features dictionaries.""" _, store = fill_store(store_cls, tmp_path / "polygon.db") features = store.features() assert isinstance(features, Generator) features = list(features) assert len(features) == FILLED_LEN assert isinstance(features[0], dict) assert all( {"type", "geometry", "properties"} == set(f.keys()) for f in features ) @staticmethod def test_to_geodict(fill_store, tmp_path, store_cls): """Test converting to a geodict.""" _, store = fill_store(store_cls, tmp_path / "polygon.db") geodict = store.to_geodict() assert isinstance(geodict, dict) assert "features" in geodict assert "type" in geodict assert geodict["type"] == "FeatureCollection" assert geodict["features"] == list(store.features()) @staticmethod def test_from_geojson_str(fill_store, tmp_path, store_cls): """Test loading from geojson with a file path string.""" _, store = fill_store(store_cls, tmp_path / "polygon.db") geojson = store.to_geojson() store2 = store_cls.from_geojson(geojson) assert len(store) == len(store2) @staticmethod def test_from_geojson_file(fill_store, tmp_path, store_cls): """Test loading from geojson with a file handle.""" _, store = fill_store(store_cls, tmp_path / "polygon.db") store.to_geojson(tmp_path / "polygon.json") with open(tmp_path / "polygon.json", "r") as file_handle: store2 = store_cls.from_geojson(file_handle) assert len(store) == len(store2) @staticmethod def test_from_geojson_path(fill_store, tmp_path, store_cls): """Test loading from geojson with a file path.""" _, store = fill_store(store_cls, tmp_path / "polygon.db") store.to_geojson(tmp_path / "polygon.json") store2 = store_cls.from_geojson(tmp_path / "polygon.json") assert len(store) == len(store2) @staticmethod def test_from_geojson_path_transform(fill_store, tmp_path, store_cls): """Test loading from geojson with a transform.""" _, store = fill_store(store_cls, tmp_path / "polygon.db") com = annotations_center_of_mass(list(store.values())) store.to_geojson(tmp_path / "polygon.json") # load the store translated so that origin is (100,100) and scaled by 2 store2 = store_cls.from_geojson( tmp_path / "polygon.json", scale_factor=(2, 2), origin=(100, 100) ) assert len(store) == len(store2) com2 = annotations_center_of_mass(list(store2.values())) assert com2.x == pytest.approx((com.x - 100) * 2) assert com2.y == pytest.approx((com.y - 100) * 2) @staticmethod def test_transform(fill_store, tmp_path, store_cls): """Test translating a store.""" def test_translation(geom): """Performs a translation of input geometry.""" return affinity.translate(geom, 100, 100) _, store = fill_store(store_cls, tmp_path / "polygon.db") com = annotations_center_of_mass(list(store.values())) store.transform(test_translation) com2 = annotations_center_of_mass(list(store.values())) assert com2.x - com.x == pytest.approx(100) assert com2.y - com.y == pytest.approx(100) @staticmethod def test_to_geojson_str(fill_store, tmp_path, store_cls): """Test exporting to ndjson with a file path string.""" _, store = fill_store(store_cls, tmp_path / "polygon.db") geojson = store.to_geojson() assert isinstance(geojson, str) geodict = json.loads(geojson) assert "features" in geodict assert "type" in geodict assert geodict["type"] == "FeatureCollection" assert len(geodict["features"]) == len(list(store.features())) @staticmethod def test_to_geojson_file(fill_store, tmp_path, store_cls): """Test exporting to ndjson with a file handle.""" _, store = fill_store(store_cls, tmp_path / "polygon.db") with open(tmp_path / "polygon.json", "w") as fh: geojson = store.to_geojson(fp=fh) assert geojson is None with open(tmp_path / "polygon.json", "r") as fh: geodict = json.load(fh) assert "features" in geodict assert "type" in geodict assert geodict["type"] == "FeatureCollection" assert len(geodict["features"]) == len(list(store.features())) @staticmethod def test_to_geojson_path(fill_store, tmp_path, store_cls): """Test exporting to geojson with a file path.""" _, store = fill_store(store_cls, tmp_path / "polygon.db") geojson = store.to_geojson(fp=tmp_path / "polygon.json") assert geojson is None with open(tmp_path / "polygon.json", "r") as fh: geodict = json.load(fh) assert "features" in geodict assert "type" in geodict assert geodict["type"] == "FeatureCollection" assert len(geodict["features"]) == len(list(store.features())) @staticmethod def test_to_ndjson_str(fill_store, tmp_path, store_cls): """Test exporting to ndjson with a file path string.""" _, store = fill_store(store_cls, tmp_path / "polygon.db") ndjson = store.to_ndjson() for line in ndjson.split(): assert isinstance(line, str) feature = json.loads(line) assert "type" in feature assert "geometry" in feature assert "properties" in feature @staticmethod def test_to_ndjson_file(fill_store, tmp_path, store_cls): """Test exporting to ndjson with a file handle.""" _, store = fill_store(store_cls, tmp_path / "polygon.db") with open(tmp_path / "polygon.ndjson", "w") as fh: ndjson = store.to_ndjson(fp=fh) assert ndjson is None with open(tmp_path / "polygon.ndjson", "r") as fh: for line in fh.readlines(): assert isinstance(line, str) feature = json.loads(line) assert "type" in feature assert "geometry" in feature assert "properties" in feature @staticmethod def test_to_ndjson_path(fill_store, tmp_path, store_cls): """Test exporting to ndjson with a file path.""" _, store = fill_store(store_cls, tmp_path / "polygon.db") ndjson = store.to_ndjson(fp=tmp_path / "polygon.ndjson") assert ndjson is None with open(tmp_path / "polygon.ndjson", "r") as fh: for line in fh.readlines(): assert isinstance(line, str) feature = json.loads(line) assert "type" in feature assert "geometry" in feature assert "properties" in feature @staticmethod def test_dump(fill_store, tmp_path, store_cls): """Test dumping to a file path.""" _, store = fill_store(store_cls, ":memory:") store.dump(tmp_path / "dump_test.db") assert (tmp_path / "dump_test.db").stat().st_size > 0 @staticmethod def test_dump_file_handle(fill_store, tmp_path, store_cls): """Test dumping to a file handle.""" _, store = fill_store(store_cls, ":memory:") with open(tmp_path / "dump_test.db", "w") as fh: store.dump(fh) assert (tmp_path / "dump_test.db").stat().st_size > 0 @staticmethod def test_dumps(fill_store, store_cls): """Test dumping by returning a string.""" _, store = fill_store(store_cls, ":memory:") string = store.dumps() assert isinstance(string, str) @staticmethod def test_iquery_predicate_str(fill_store, store_cls): """Test iquering with a predicate string.""" keys, store = fill_store(store_cls, ":memory:") store.patch(keys[0], properties={"class": 123}) results = store.iquery((0, 0, 1024, 1024), where="props.get('class') == 123") assert len(results) == 1 assert results[0] == keys[0] @staticmethod def test_iquery_predicate_callable(fill_store, store_cls): """Test iquering with a predicate function.""" keys, store = fill_store(store_cls, ":memory:") store.patch(keys[0], properties={"class": 123}) results = store.iquery( (0, 0, 1024, 1024), where=lambda props: props.get("class") == 123, ) assert len(results) == 1 assert results[0] == keys[0] @staticmethod def test_iquery_predicate_pickle(fill_store, store_cls): """Test iquering with a pickled predicate function.""" keys, store = fill_store(store_cls, ":memory:") store.patch(keys[0], properties={"class": 123}) results = store.query((0, 0, 1024, 1024), where=pickle.dumps(sample_where_123)) assert len(results) == 1 @staticmethod def test_query_predicate_str(fill_store, store_cls): """Test quering with a predicate string.""" keys, store = fill_store(store_cls, ":memory:") store.patch(keys[0], properties={"class": 123}) results = store.query((0, 0, 1024, 1024), where="props.get('class') == 123") assert len(results) == 1 @staticmethod def test_query_predicate_callable(fill_store, store_cls): """Test quering with a predicate function.""" keys, store = fill_store(store_cls, ":memory:") store.patch(keys[0], properties={"class": 123}) results = store.query( # (0, 0, 1024, 1024), # noqa: E800 where=lambda props: props.get("class") == 123, ) assert len(results) == 1 @staticmethod def test_query_predicate_pickle(fill_store, store_cls): """Test quering with a pickled predicate function.""" keys, store = fill_store(store_cls, ":memory:") store.patch(keys[0], properties={"class": 123}) results = store.query((0, 0, 1024, 1024), where=pickle.dumps(sample_where_123)) assert len(results) == 1 @staticmethod def test_append_invalid_geometry(fill_store, store_cls): """Test that appending invalid geometry raises an exception.""" store = store_cls() with pytest.raises((TypeError, AttributeError)): store.append("point", {}) @staticmethod def test_update_invalid_geometry(fill_store, store_cls): """Test that updating a new key and None geometry raises an exception.""" store = store_cls() key = "foo" with pytest.raises((TypeError, AttributeError)): store.patch(key, geometry=None, properties={"class": 123}) @staticmethod def test_pop_key(fill_store, store_cls): """Test popping an annotation by key.""" keys, store = fill_store(store_cls, ":memory:") assert keys[0] in store annotation = store.pop(keys[0]) assert keys[0] not in store assert annotation not in store.values() @staticmethod def test_pop_key_error(fill_store, store_cls): """Test that popping a key that is not in the store raises an exception.""" store = store_cls() with pytest.raises(KeyError): store.pop("foo") @staticmethod def test_popitem(fill_store, store_cls): """Test popping a key and annotation by key.""" keys, store = fill_store(store_cls, ":memory:") key, annotation = store.popitem() assert key in keys assert key not in store assert annotation not in store.values() @staticmethod def test_popitem_empty_error(fill_store, store_cls): """Test that popping an empty store raises an exception.""" store = store_cls() with pytest.raises(KeyError): store.popitem() @staticmethod def test_setdefault(fill_store, store_cls, sample_triangle): """Test setting a default value for a key.""" store = store_cls() default = Annotation(sample_triangle) assert "foo" not in store assert store.setdefault("foo", default) == default assert "foo" in store assert default in store.values() @staticmethod def test_setdefault_error(fill_store, store_cls, sample_triangle): """Test setting a default value for a key with invalid type.""" store = store_cls() with pytest.raises(TypeError): store.setdefault("foo", {}) @staticmethod def test_get(fill_store, store_cls): """Test getting an annotation by key.""" keys, store = fill_store(store_cls, ":memory:") assert keys[0] in store assert store.get(keys[0]) == store[keys[0]] @staticmethod def test_get_default(fill_store, store_cls): """Test getting a default value for a key.""" store = store_cls() assert "foo" not in store assert store.get("foo") is None @staticmethod def test_eq(fill_store, store_cls): """Test comparing two stores for equality.""" store1 = store_cls() store2 = store_cls() assert store1 == store2 store1 = fill_store(store_cls, ":memory:")[1] assert store1 != store2 for key, value in store1.items(): store2[key] = value assert store1 == store2 @staticmethod def test_ne(fill_store, store_cls): """Test comparing two stores for inequality.""" store1 = fill_store(store_cls, ":memory:")[1] store2 = fill_store(store_cls, ":memory:")[1] assert store1 != store2 @staticmethod def test_clear(fill_store, store_cls): """Test clearing a store.""" keys, store = fill_store(store_cls, ":memory:") store.clear() assert keys[0] not in store assert len(store) == 0 assert not store @staticmethod def test_update(fill_store, store_cls, sample_triangle): """Test updating a store with a dictionary.""" _, store = fill_store(store_cls, ":memory:") annotations = { "foo": Annotation(sample_triangle), } assert "foo" not in store store.update(annotations) assert "foo" in store assert store["foo"] == annotations["foo"] @staticmethod def test_cast_dict(fill_store, store_cls): """Test casting a store to a dictionary.""" keys, store = fill_store(store_cls, ":memory:") store_dict = dict(store) assert keys[0] in store_dict assert store[keys[0]] in store_dict.values() @staticmethod def test_query_invalid_geometry_predicate(fill_store, store_cls): """Test that invalid geometry predicate raises an exception.""" store = store_cls() with pytest.raises(ValueError, match="Invalid geometry predicate"): store.query((0, 0, 1024, 1024), geometry_predicate="foo") @staticmethod def test_query_no_geometry_or_where(fill_store, store_cls): """Test that query raises exception when no geometry or predicate given.""" store = store_cls() with pytest.raises(ValueError, match="At least one of"): store.query() @staticmethod def test_iquery_invalid_geometry_predicate(fill_store, store_cls): """Test that invalid geometry predicate raises an exception.""" store = store_cls() with pytest.raises(ValueError, match="Invalid geometry predicate"): store.iquery((0, 0, 1024, 1024), geometry_predicate="foo") @staticmethod def test_serialise_deseialise_geometry(fill_store, store_cls): """Test that geometry can be serialised and deserialised.""" _, store = fill_store(store_cls, ":memory:") for _, annotation in store.items(): geometry = annotation.geometry serialised = store.serialise_geometry(geometry) deserialised = store.deserialize_geometry(serialised) if isinstance(serialised, str): assert geometry.wkt == deserialised.wkt else: assert geometry.wkb == deserialised.wkb @staticmethod def test_commit(fill_store, store_cls, tmp_path): """Test committing a store.""" store_path = tmp_path / "test_store" test_store = store_cls(store_path) test_store["foo"] = Annotation(Point(0, 0)) test_store.commit() assert store_path.exists() test_store.close() del test_store # skipcq: PTC-W0043 test_store = store_cls(store_path) assert "foo" in test_store @staticmethod def test_load_cases_error(fill_store, store_cls): """Test that loading a store with an invalid file handle raises an exception.""" store = store_cls() with pytest.raises(IOError, match="Invalid file handle or path"): store._load_cases(["foo"], lambda: None, lambda: None) @staticmethod def test_py38_init(fill_store, store_cls, monkeypatch): """Test that __init__ is compatible with Python 3.8.""" py38_version = (3, 8, 0) class Connection(sqlite3.Connection): """Mock SQLite connection.""" def create_function(self, name: str, num_params: int, func: Any) -> None: """Mock create_function without `deterministic` kwarg.""" return self.create_function(self, name, num_params) monkeypatch.setattr(sys, "version_info", py38_version) monkeypatch.setattr(sqlite3, "Connection", Connection) _ = store_cls() @staticmethod def test_bquery(fill_store, store_cls): """Test querying a store with a bounding box.""" _, store = fill_store(store_cls, ":memory:") dictionary = store.bquery((0, 0, 1e10, 1e10)) assert isinstance(dictionary, dict) assert len(dictionary) == len(store) @staticmethod def test_bquery_polygon(fill_store, store_cls): """Test querying a store with a polygon.""" _, store = fill_store(store_cls, ":memory:") dictionary = store.bquery(Polygon.from_bounds(0, 0, 1e10, 1e10)) assert isinstance(dictionary, dict) assert len(dictionary) == len(store) @staticmethod def test_bquery_callable(fill_store, store_cls): """Test querying a store with a bounding box and a callable where.""" keys, store = fill_store(store_cls, ":memory:") store.patch(keys[0], properties={"class": 123}) dictionary = store.bquery( (0, 0, 1e10, 1e10), where=lambda props: props.get("class") == 123 ) assert isinstance(dictionary, dict) assert len(dictionary) == 1 @staticmethod def test_pquery_all(fill_store, store_cls): """Test querying for all properties.""" keys, store = fill_store(store_cls, ":memory:") dictionary = store.pquery("*", unique=False) assert isinstance(dictionary, dict) assert len(dictionary) == len(store) assert isinstance(dictionary[keys[0]], dict) @staticmethod def test_pquery_all_unique_exception(fill_store, store_cls): """Test querying for all properties.""" _, store = fill_store(store_cls, ":memory:") with pytest.raises(ValueError, match="unique"): _ = store.pquery("*", unique=True) @staticmethod def test_pquery_unique(fill_store, store_cls): """Test querying for properties.""" _, store = fill_store(store_cls, ":memory:") result_set = store.pquery(select="props.get('class')") assert isinstance(result_set, set) assert result_set == {0, 1, 2, 3, 4, None} @staticmethod def test_pquery_unique_with_geometry(fill_store, store_cls): """Test querying for properties with a geometry intersection.""" _, store = fill_store(store_cls, ":memory:") result_set = store.pquery( select="props.get('class')", geometry=Polygon.from_bounds(0, 0, 128, 128), ) assert isinstance(result_set, set) assert result_set == {0, 1, 2, 3, 4, None} @staticmethod def test_pquery_unique_with_where(fill_store, store_cls): """Test querying for properties with a where predicate.""" _, store = fill_store(store_cls, ":memory:") result_set = store.pquery( select="props.get('class')", where="props.get('class') == 1", ) assert isinstance(result_set, set) assert result_set == {1} @staticmethod def test_pquery_unique_with_geometry_and_where(fill_store, store_cls): """Test querying for properties with a geometry and where predicate.""" _, store = fill_store(store_cls, ":memory:") result_set = store.pquery( select="props.get('class')", geometry=Polygon.from_bounds(0, 0, 128, 128), where="props.get('class') == 1", ) assert isinstance(result_set, set) assert result_set == {1} @staticmethod def test_pquery_callable_unique(fill_store, store_cls): """Test querying for properties with a callable select and where.""" _, store = fill_store(store_cls, ":memory:") result_set = store.pquery( select=lambda props: (props.get("class"),), where=lambda props: props.get("class") == 1, unique=True, ) assert isinstance(result_set, set) assert result_set == {1} @staticmethod def test_pquery_callable_unique_no_squeeze(fill_store, store_cls): """Test querying for properties with a callable select and where.""" _, store = fill_store(store_cls, ":memory:") result_set = store.pquery( select=sample_select, where=sample_where_1, unique=True, squeeze=False, ) assert isinstance(result_set, list) assert result_set == [{1}] @staticmethod def test_pquery_callable_unique_multi_select(fill_store, store_cls): """Test querying unique properties with a callable select and where.""" _, store = fill_store(store_cls, ":memory:") result_set = store.pquery( select=sample_multi_select, where=sample_where_1, unique=True, ) assert isinstance(result_set, list) assert result_set == [{1}, {1}] @staticmethod def test_pquery_callable(fill_store, store_cls): """Test querying for properties with a callable select and where.""" _, store = fill_store(store_cls, ":memory:") result_set = store.pquery( select=lambda props: props.get("class"), where=lambda props: props.get("class") == 1, unique=False, ) assert isinstance(result_set, dict) assert set(result_set.values()) == {1} @staticmethod def test_pquery_callable_no_where(fill_store, store_cls): """Test querying for properties with callable select, no where.""" _, store = fill_store(store_cls, ":memory:") result_set = store.pquery( select=lambda props: props.get("class"), where=None, unique=False, ) assert isinstance(result_set, dict) assert set(result_set.values()).issubset({0, 1, 2, 3, 4, None}) @staticmethod def test_pquery_pickled(fill_store, store_cls): """Test querying for properties with a pickled select and where.""" _, store = fill_store(store_cls, ":memory:") result_set = store.pquery( select=pickle.dumps(sample_select), where=pickle.dumps(sample_where_1), ) assert isinstance(result_set, set) assert result_set == {1} @staticmethod def test_pquery_pickled_no_squeeze(fill_store, store_cls): """Test querying for properties with a pickled select and where.""" _, store = fill_store(store_cls, ":memory:") result_set = store.pquery( select=pickle.dumps(sample_select), where=pickle.dumps(sample_where_1), squeeze=False, ) assert isinstance(result_set, list) assert result_set == [{1}] @staticmethod def test_pquery_pickled_multi_select(fill_store, store_cls): """Test querying for properties with a pickled select and where.""" _, store = fill_store(store_cls, ":memory:") result_set = store.pquery( select=pickle.dumps(sample_multi_select), where=pickle.dumps(sample_where_1), ) assert isinstance(result_set, list) assert result_set == [{1}, {1}] @staticmethod def test_pquery_invalid_expression_type(fill_store, store_cls): """Test querying for properties with an invalid expression type.""" _, store = fill_store(store_cls, ":memory:") with pytest.raises(TypeError): _ = store.pquery(select=123, where=456) @staticmethod def test_pquery_non_matching_type(fill_store, store_cls): """Test querying with a non-matching type for select and where.""" _, store = fill_store(store_cls, ":memory:") with pytest.raises(TypeError): _ = store.pquery(select=123, where="foo") @staticmethod def test_pquery_dict(fill_store, store_cls): """Test querying for properties.""" _, store = fill_store(store_cls, ":memory:") dictionary = store.pquery(select="props.get('class')", unique=False) assert isinstance(dictionary, dict) assert len(dictionary) == len(store) assert all(key in store for key in dictionary) @staticmethod def test_pquery_dict_with_geometry(fill_store, store_cls): """Test querying for properties with a geometry intersection.""" _, store = fill_store(store_cls, ":memory:") dictionary = store.pquery( select="props.get('class')", unique=False, geometry=Polygon.from_bounds(0, 0, 128, 128), ) assert isinstance(dictionary, dict) assert len(dictionary) < len(store) assert all(key in store for key in dictionary) @staticmethod def test_is_rectangle(store_cls): """Test that _is_rectangle returns True only for rectangles.""" store = store_cls() # Clockwise assert store._is_rectangle( *[ (1, 0), (0, 0), (0, 1), (1, 1), ] ) # Counter-clockwise assert store._is_rectangle( *[ (1, 1), (0, 1), (0, 0), (1, 0), ] ) # From shapely box = Polygon.from_bounds(0, 0, 10, 10) assert store._is_rectangle(*box.exterior.coords) # Fuzz for _ in range(100): box = Polygon.from_bounds(*np.random.randint(0, 100, 4)) assert store._is_rectangle(*box.exterior.coords) # Failure case assert not store._is_rectangle( *[ (1, 1.5), (0, 1), (0, 0), (1, 0), ] ) @staticmethod def test_is_rectangle_invalid_input(store_cls): """Test that _is_rectangle returns False for invalid input.""" store = store_cls() assert not store._is_rectangle(1, 2, 3, 4) assert not store._is_rectangle((0, 0), (0, 1), (1, 1), (1, 0), (2, 0)) @staticmethod def test_is_right_angle(store_cls): """Test that _is_right_angle returns True only for right angles.""" store = store_cls() # skipcq r""" c | | b-----a """ assert store._is_right_angle( *[ (1, 0), (0, 0), (0, 1), ] ) # skipcq r""" a | | b-----c """ assert store._is_right_angle( *[ (0, 1), (0, 0), (1, 0), ] ) # skipcq r""" c \ \ a-----b """ assert not store._is_right_angle( *[ (0, 0), (1, 0), (0, 1), ] ) assert not store._is_right_angle( *[ (1, 0.2), (0, 0), (0.2, 1), ] ) @staticmethod def test_box_query_polygon_intersection(store_cls): """Test that a box query correctly checks intersections with polygons.""" store = store_cls() # Add a triangle annotation store["foo"] = Annotation(Polygon([(0, 10), (10, 10), (10, 0)])) # ASCII diagram of the annotation with points labeled from a to # c: # skipcq r""" a-----b \ | \ | \ | \ | \| c """ # Query where the bounding boxes overlap but the geometries do # not. Should return an empty result. # ASCII diagram of the query: # skipcq r""" a-----b \ | \ | \ | +--+\ | | | \| +--+ c """ result = store.query([0, 0, 4.9, 4.9], geometry_predicate="intersects") assert len(result) == 0 # Query where the bounding boxes overlap and the geometries do. # Should return the annotation. # ASCII diagram of the query: # skipcq r""" +------+ a-----b| |\ || | \ || | \ || | \ || | \|| +-----c+ """ result = store.query([0, 0, 11, 11], geometry_predicate="intersects") assert len(result) == 1 @staticmethod def test_bquery_bounds(fill_store, store_cls): """Test querying a store with a bounding box iterable.""" _, store = fill_store(store_cls, ":memory:") dictionary = store.bquery((0, 0, 1e10, 1e10)) assert isinstance(dictionary, dict) assert len(dictionary) == len(store) @staticmethod def test_validate_equal_lengths(store_cls): """Test that equal length lists are valid.""" store_cls._validate_equal_lengths([1, 2, 3], [1, 2, 3]) store_cls._validate_equal_lengths() with pytest.raises(ValueError, match="equal length"): store_cls._validate_equal_lengths([1, 2, 3], [1, 2]) @staticmethod def test_connection_to_path_memory(store_cls): """Test converting a :memory: connection to a path.""" path = store_cls._connection_to_path(":memory:") assert path == Path(":memory:") @staticmethod def test_connection_to_path_type_error(store_cls): """Test converting an invalid type connection to a path.""" with pytest.raises(TypeError): _ = store_cls._connection_to_path(123) @staticmethod def test_connection_to_path_io(store_cls, tmp_path): """Test converting a named file connection to a path.""" path = tmp_path / "foo" with open(path, "w") as fh: store_cls._connection_to_path(fh) assert path == Path(fh.name) @staticmethod def test_nquery_boxpoint_boxpoint(store_cls): """Test simple querying within a neighbourhood. Test that a neighbourhood query returns the correct results for a simple data store with two points. .. code-block:: text ^ 3|--****-----C |* * | 2| * | | B *| 1| A * | *| 0+---------*--> 0 1 2 3 Query for all points within a distance of 2 from A. Should return a dictionary with a single key, "A", and a value of {"B": B}. """ store: AnnotationStore = store_cls() ann_a = Annotation( Point(1, 1), {"class": "A"}, ) store["A"] = ann_a ann_b = Annotation( Point(1.4, 1.4), {"class": "B"}, ) store["B"] = ann_b # C is inside the bounding box of the radius around A but is not # returned because it is not inside of the radius. ann_c = Annotation( Point(2.9, 2.9), {"class": "C"}, ) store["C"] = ann_c result = store.nquery( where="props['class'] == 'A'", n_where="props['class'] != 'A'", distance=2, mode="boxpoint-boxpoint", ) assert isinstance(result, dict) assert len(result) == 1 assert "A" in result assert result["A"] == {"B": ann_b} @staticmethod def test_nquery_boxpoint_boxpoint_no_results(store_cls): """Test querying within a neighbourhood with no results. Test that a neighbourhood query returns an empty dictionary when there are no results. .. code-block:: text 3^ 2| 1| 0+-----> 0 1 2 3 Query for all points within a distance of 2 from A. Should return an empty dictionary. """ store: AnnotationStore = store_cls() ann_a = Annotation( Point(1, 1), {"class": "A"}, ) store["A"] = ann_a result = store.nquery( where="props['class'] == 'A'", n_where="props['class'] == 'B'", distance=2, mode="boxpoint-boxpoint", ) assert isinstance(result, dict) assert len(result) == 0 @staticmethod def test_nquery_boxpoint_boxpoint_multiple(store_cls): """Test querying within a neighbourhood with multiple results. Test that a neighbourhood query returns the correct results for a simple data store with four points. .. code-block:: text 3^ 2| B 1| A C D <-- D is outside the neighbourhood 0+------> 0 1 2 3 Query for all points within a distance of 2 from A. Should return a dictionary with a single key, "A", and a value of {"B": B, "C": C}. """ store: AnnotationStore = store_cls() ann_a = Annotation( Point(1, 1), {"class": "A"}, ) store["A"] = ann_a ann_b = Annotation( Point(2, 2), {"class": "B"}, ) store["B"] = ann_b ann_c = Annotation( Point(2, 1), {"class": "C"}, ) store["C"] = ann_c ann_d = Annotation( Point(3, 1), {"class": "D"}, ) store["D"] = ann_d result = store.nquery( where="props['class'] == 'A'", n_where="(props['class'] == 'B') | (props['class'] == 'C')", distance=2, mode="boxpoint-boxpoint", ) assert isinstance(result, dict) assert len(result) == 1 assert "A" in result assert result["A"] == {"B": ann_b, "C": ann_c} @staticmethod def test_nquery_poly_poly(store_cls): """Test querying within a neighbourhood with multiple results. Test that a neighbourhood query returns the correct results for a simple data store with two polygons. .. code-block:: text 3^ 2| B 1| A 0+------> 0 1 2 3 """ store: AnnotationStore = store_cls() ann_a = Annotation( # Triangle Polygon([(0, 0), (0, 1), (1, 0)]), {"class": "A"}, ) store["A"] = ann_a ann_b = Annotation( # Square Polygon.from_bounds(1, 1, 2, 2), {"class": "B"}, ) store["B"] = ann_b result = store.nquery( where="props['class'] == 'A'", n_where="props['class'] == 'B'", distance=2, mode="poly-poly", ) assert isinstance(result, dict) assert len(result) == 1 @staticmethod def test_nquery_poly_poly_vs_boxpoint_boxpoint(store_cls): """Test querying within a neighbourhood with two polygons. Test that a full polygon neighbourhood query returns results where a centroid query would return no results. .. code-block:: text ^ 3| | <----2----> 2| +-----+ +-----+ | | + |<-1->| + | 1| +-----+ +-----+ | 0+------------------------> 0 1 2 3 4 """ store: AnnotationStore = store_cls() ann_a = Annotation( Polygon.from_bounds(1, 1, 2, 2), {"class": "A"}, ) store["A"] = ann_a ann_b = Annotation( Polygon.from_bounds(3, 1, 4, 2), {"class": "B"}, ) store["B"] = ann_b distance = 1.25 result = store.nquery( where="props['class'] == 'A'", n_where="props['class'] == 'B'", distance=distance, mode="boxpoint-boxpoint", ) assert isinstance(result, dict) assert len(result) == 0 result = store.nquery( where="props['class'] == 'A'", n_where="props['class'] == 'B'", distance=distance, mode=("poly", "poly"), ) assert isinstance(result, dict) assert len(result) == 1 @staticmethod def test_nquery_polygon_boundary_alt(store_cls): """Test querying within a neighbourhood with two polygons. This test is similar to test_nquery_polygon_boundary, but the centroids are closer than the boundaries. .. code-block:: text ^ 5| +-----------------+ | +---------------+ | 4| <-----2----->| | centroid-boundary = 2 | <--1--> | | centroid-centroid = 1 3| +-----+ | | | | + | + ^ | | centroid-boundary = 2 2| +-----+ | | | | ^ |2 | | 1| v1.5 v | | boundary-boundary = 1.5 | +---------------+ | 0+-----+-----------------+--> 0 1 2 3 4 """ store: AnnotationStore = store_cls() # Annotation A: A 1x1 box ann_a = Annotation( Polygon.from_bounds(1, 2, 2, 3), {"class": "A"}, ) store["A"] = ann_a # C shaped polygon around annotation A ann_b = Annotation( Polygon( [ (1, 0), (4, 0), (4, 5), (1, 5), (1, 4.5), (3.5, 4.5), (3.5, 0.5), (1, 0.5), ] ), {"class": "B"}, ) store["B"] = ann_b distance = 1.75 centroid = Polygon.from_bounds(*ann_b.geometry.bounds).centroid print(centroid) print(ann_a.geometry.centroid) print( centroid.buffer(distance) .intersection(ann_a.geometry.centroid.buffer(distance)) .area ) result = store.nquery( where="props['class'] == 'A'", n_where="props['class'] == 'B'", distance=distance, mode="boxpoint-boxpoint", ) assert isinstance(result, dict) assert len(result) == 1 @staticmethod def test_nquery_overlapping_grid_box_box(store_cls): """Find duplicate (overlapping) cell boundaries via bounding boxes. This generates an :math:`n \\times n` (where :math:`n=10`) grid of overlapping fake cell boundary polygons, where each polygon has radius of 5 and the grid has a spacing of 30. The grid is then queried with a "box-box" neighbourhood query (intersection of bounding boxes) and a `distance` paramete of 0 (no expansion of bounding boxes). """ store: AnnotationStore = store_cls() grid_size = 10 spacing = 30 radius = 5 grid = np.ndindex((grid_size, grid_size)) for x, y in grid: cell_a = cell_polygon( (x * spacing + radius, y * spacing + radius), radius=radius ) ann_a = Annotation(cell_a, {"class": "A"}) cell_b = cell_polygon( (x * spacing + radius, y * spacing + radius), radius=radius ) ann_b = Annotation(cell_b, {"class": "B"}) store[f"A_{x}_{y}"] = ann_a store[f"B_{x}_{y}"] = ann_b result = store.nquery( where="props['class'] == 'A'", n_where="props['class'] == 'B'", distance=0, mode="box-box", ) assert isinstance(result, dict) assert len(result) == grid_size**2 for v in result.values(): assert len(v) == 1 @staticmethod def test_nquery_overlapping_grid_boxpoint_boxpoint(store_cls): """Find duplicate (overlapping) cell boundaries via bbox centroid distance. This generates an :math:`n \\times n` (where :math:`n=10`) grid of overlapping fake cell boundary polygons, where each polygon has radius of 5 and the grid has a spacing of 30. The grid is then queried with a "boxpoint-boxpoint" neighbourhood query and a `distance` of 2 (use a buffer of 2 around the point). """ store: AnnotationStore = store_cls() grid_size = 10 spacing = 10 radius = 5 grid = np.ndindex((grid_size, grid_size)) for x, y in grid: cell_a = cell_polygon( (x * spacing + radius, y * spacing + radius), radius=radius ) ann_a = Annotation(cell_a, {"class": "A"}) cell_b = cell_polygon( (x * spacing + radius, y * spacing + radius), radius=radius ) ann_b = Annotation(cell_b, {"class": "B"}) store[f"A_{x}_{y}"] = ann_a store[f"B_{x}_{y}"] = ann_b result = store.nquery( where="props['class'] == 'A'", n_where="props['class'] == 'B'", distance=2, mode="boxpoint-boxpoint", ) assert isinstance(result, dict) assert len(result) == grid_size**2 for v in result.values(): assert len(v) == 1 @staticmethod def test_nquery_overlapping_grid_poly_poly(store_cls): """Find duplicate (overlapping) cell boundaries via polygon intersection. This generates an :math:`n \\times n` (where :math:`n=10`) grid of overlapping fake cell boundary polygons, where each polygon has radius of 5 and the grid has a spacing of 30. The grid is then queried with a "poly-poly" neighbourhood query (intersection of polygons) and a `distance` parameter of 2. """ store: AnnotationStore = store_cls() grid_size = 10 spacing = 30 radius = 5 grid = np.ndindex((grid_size, grid_size)) for x, y in grid: cell_a = cell_polygon( (x * spacing + radius, y * spacing + radius), radius=radius ) ann_a = Annotation(cell_a, {"class": "A"}) cell_b = cell_polygon( (x * spacing + radius, y * spacing + radius), radius=radius ) ann_b = Annotation(cell_b, {"class": "B"}) store[f"A_{x}_{y}"] = ann_a store[f"B_{x}_{y}"] = ann_b result = store.nquery( where="props['class'] == 'A'", n_where="props['class'] == 'B'", distance=2, mode="poly-poly", ) assert isinstance(result, dict) assert len(result) == grid_size**2 for v in result.values(): assert len(v) == 1 @staticmethod def test_invalid_mode_type(store_cls): store: AnnotationStore = store_cls() with pytest.raises(TypeError, match="string or tuple of strings"): store.nquery( where="props['class'] == 'A'", n_where="props['class'] == 'B'", distance=2, mode=123, ) @staticmethod def test_invalid_mode_format(store_cls): store: AnnotationStore = store_cls() with pytest.raises(ValueError, match="must be one of"): store.nquery( where="props['class'] == 'A'", n_where="props['class'] == 'B'", distance=2, mode="invalid-invalid-invalid", ) @staticmethod def test_invalid_mode(store_cls): store: AnnotationStore = store_cls() with pytest.raises(ValueError, match="must be one of"): store.nquery( where="props['class'] == 'A'", n_where="props['class'] == 'B'", distance=2, mode="invalid", ) @staticmethod def test_bquery_only_where(store_cls): """Test that bquery when only a where predicate is given. This simply checks for no exceptions raised about None values. """ store = store_cls() assert store.bquery(where="props['foo'] == 'bar'") == {}
74,022
33.638746
88
py
tiatoolbox
tiatoolbox-master/tests/test_exceptions.py
"""Tests for exceptions used in the toolbox.""" import pytest from tiatoolbox.tools.stainnorm import get_normalizer from tiatoolbox.utils.exceptions import MethodNotSupported def test_exception_tests(): """Test for Exceptions.""" with pytest.raises(MethodNotSupported): get_normalizer(method_name="invalid_normalizer") with pytest.raises( ValueError, match="`stain_matrix` is only defined when using.*custom" ): get_normalizer(method_name="reinhard", stain_matrix="[1, 2]")
519
27.888889
77
py
tiatoolbox
tiatoolbox-master/tests/test_graph.py
"""Tests for graph construction tools.""" import numpy as np import pytest import torch from matplotlib import pyplot as plt from tiatoolbox.tools.graph import ( SlideGraphConstructor, affinity_to_edge_index, delaunay_adjacency, edge_index_to_triangles, triangle_signed_area, ) def test_delaunay_adjacency_dthresh_type(): """Test empty input raises a TypeError if dthresh is not a Number.""" with pytest.raises(TypeError, match="number"): delaunay_adjacency(points=[[0, 0]], dthresh=None) def test_delaunay_adjacency_empty(): """Test empty input raises a ValueError.""" points = np.array([]) with pytest.raises(ValueError, match="Points must have length >= 4"): delaunay_adjacency(points, 10) def test_delaunay_adjacency_invalid_shape(): """Test points with invalid shape (not NxM) raises a ValueError.""" points = np.random.rand(4, 4, 4) with pytest.raises(ValueError, match="NxM"): delaunay_adjacency(points, 10) def test_delaunay_adjacency_nothing_connected(): """Test delaunay_adjacency does not connect points further than dthresh. Nothing should connect for this case as all points are further apart than dthresh. """ # Simple convex hull with the minimum of 4 points points = np.array( [ [0, 0], [1, 1], [1, 3], [1, 6], ] ) adjacency_matrix = delaunay_adjacency(points=points, dthresh=0.5) assert np.sum(adjacency_matrix) == 0 def test_delaunay_adjacency_connected(): """Test delaunay_adjacency connects expects points in handcrafted input.""" # Simple convex hull with the minimum of 4 points points = np.array( [ [0, 0], [1, 1], [1, 3], [1, 6], ] ) adjacency_matrix = delaunay_adjacency(points=points, dthresh=1.5) # Expect 1 connection, symmetrical so dividing by 2 assert np.sum(adjacency_matrix) / 2 == 1 def test_affinity_to_edge_index_fuzz_output_shape(): """Fuzz test that output shape is 2xM for affinity_to_edge. Output is 2xM, where M is the number of edges in the graph, i.e. the number of connections between nodes with a value > threshold. """ np.random.seed(123) for _ in range(1000): # Generate some random square inputs input_shape = [np.random.randint(2, 10)] * 2 affinity_matrix = np.random.sample(input_shape) threshold = np.random.rand() # Convert to torch randomly if np.random.rand() > 0.5: affinity_matrix = torch.tensor(affinity_matrix) edge_index = affinity_to_edge_index(affinity_matrix, threshold=threshold) # noqa Check the output has shape (2, M) assert len(edge_index.shape) == 2 n = len(affinity_matrix) two, m = edge_index.shape assert two == 2 assert 0 <= m <= n**2 def test_affinity_to_edge_index_invalid_fuzz_input_shape(): """Test that affinity_to_edge fails with non-square input.""" # Generate some random square inputs np.random.seed(123) for _ in range(100): input_shape = [np.random.randint(2, 10)] * 2 input_shape[1] -= 1 affinity_matrix = np.random.sample(input_shape) threshold = np.random.rand() # Convert to torch randomly if np.random.rand() > 0.5: affinity_matrix = torch.tensor(affinity_matrix) with pytest.raises(ValueError, match="square"): _ = affinity_to_edge_index(affinity_matrix, threshold=threshold) def test_edge_index_to_triangles_invalid_input(): """Test edge_index_to_triangles fails with invalid input.""" edge_index = torch.tensor([[0, 1], [0, 2], [1, 2]]) with pytest.raises(ValueError, match="must be a 2xM"): edge_index_to_triangles(edge_index) def test_triangle_signed_area(): """Test that the signed area of a triangle is correct.""" # Triangle with positive area points = np.array([[0, 0], [1, 0], [0, 1]]) area = triangle_signed_area(points) assert area == 0.5 # Triangle with negative area points = np.array([[0, 0], [1, 0], [0, -1]]) area = triangle_signed_area(points) assert area == -0.5 # Triangle with co-linear points points = np.array([[0, 0], [1, 1], [2, 2]]) area = triangle_signed_area(points) assert area == 0 # Triangle with larger area points = np.array([[0, 0], [2, 0], [0, 2]]) area = triangle_signed_area(points) assert area == 2 def test_triangle_signed_area_invalid_input(): """Test that the signed area of a triangle with invalid input fails.""" points = np.random.rand(3, 3) with pytest.raises(ValueError, match="3x2"): triangle_signed_area(points) def test_edge_index_to_trainangles_single(): """Test edge_index_to_triangles with a simple 2XM input matrix. Basic test case for a single triangle. 0 -- 1 | / | / 2 """ edge_index = np.array([[0, 1], [0, 2], [1, 2]]).T triangles = edge_index_to_triangles(edge_index) assert triangles.shape == (1, 3) assert np.array_equal(triangles, np.array([[0, 1, 2]])) def test_edge_index_to_trainangles_many(): """Test edge_index_to_triangles with a simple 2XM input matrix. Moderate test case for a few trainangles. 4 -- 3 | / | |/ | 0 -- 1 | / | / 2 """ edge_index = np.array([[0, 1], [0, 2], [1, 2], [0, 3], [1, 3], [0, 4], [4, 3]]).T triangles = edge_index_to_triangles(edge_index) assert triangles.shape == (3, 3) def test_slidegraph_build_feature_range_thresh_none(): """Test SlideGraphConstructor builds a graph without removing features.""" # Generate random points and features np.random.seed(0) points = np.random.rand(100, 2) features = np.random.rand(100, 100) / 1e-5 # Build the graph graph = SlideGraphConstructor.build( points=points, features=features, feature_range_thresh=None ) assert graph["x"].shape[1] == 100 class TestConstructor: scenarios = [ ("SlideGraph", {"graph_constructor": SlideGraphConstructor}), ] @staticmethod def test_build(graph_constructor): """Test that build outputs are in an expected format. Check the lengths and ranges of outputs with random data as input. """ np.random.seed(123) points = np.concatenate( [np.random.rand(25, 2) * 100 + (offset * 1000) for offset in range(10)] ) features = np.concatenate( [np.random.rand(25, 100) * 100 + (offset * 1000) for offset in range(10)] ) graph = graph_constructor.build(points, features) x = graph["x"] assert len(x) > 0 assert len(x) <= len(points) edge_index = graph["edge_index"] two, m = edge_index.shape n = len(x) assert two == 2 assert 0 <= m <= n**2 @staticmethod def test_visualise(graph_constructor): """Test visualising a graph.""" np.random.seed(123) points = np.concatenate( [np.random.rand(25, 2) * 100 + (offset * 1000) for offset in range(10)] ) features = np.concatenate( [np.random.rand(25, 100) * 100 + (offset * 1000) for offset in range(10)] ) graph = graph_constructor.build(points, features) graph_constructor.visualise(graph) plt.close() @staticmethod def test_visualise_ax(graph_constructor): """Test visualising a graph on a given axis.""" np.random.seed(123) points = np.concatenate( [np.random.rand(25, 2) * 100 + (offset * 1000) for offset in range(10)] ) features = np.concatenate( [np.random.rand(25, 100) * 100 + (offset * 1000) for offset in range(10)] ) _, ax = plt.subplots() graph = graph_constructor.build(points, features) graph_constructor.visualise(graph, ax=ax) plt.close() @staticmethod def test_visualise_custom_color_function(graph_constructor): """Test visualising a graph with a custom color function.""" np.random.seed(123) points = np.concatenate( [np.random.rand(25, 2) * 100 + (offset * 1000) for offset in range(10)] ) features = np.concatenate( [np.random.rand(25, 100) * 100 + (offset * 1000) for offset in range(10)] ) graph = graph_constructor.build(points, features) cmap = plt.get_cmap("viridis") graph_constructor.visualise( graph, color=lambda g: cmap(np.mean(g["x"], axis=1)) ) plt.close() @staticmethod def test_visualise_static_color(graph_constructor): """Test visualising a graph with a custom color function.""" np.random.seed(123) points = np.concatenate( [np.random.rand(25, 2) * 100 + (offset * 1000) for offset in range(10)] ) features = np.concatenate( [np.random.rand(25, 100) * 100 + (offset * 1000) for offset in range(10)] ) graph = graph_constructor.build(points, features) graph_constructor.visualise(graph, color="orange") plt.close() @staticmethod def test_visualise_invalid_input(graph_constructor): """Test visualising a graph with invalid input.""" with pytest.raises(ValueError, match="must contain key `x`"): graph_constructor.visualise({}) with pytest.raises(ValueError, match="must contain key `edge_index`"): graph_constructor.visualise({"x": []}) with pytest.raises(ValueError, match="must contain key `coordinates`"): graph_constructor.visualise({"x": [], "edge_index": []})
9,810
32.03367
85
py
tiatoolbox
tiatoolbox-master/tests/test_wsi_registration.py
import pathlib import cv2 import numpy as np import pytest from tiatoolbox.tools.registration.wsi_registration import ( AffineWSITransformer, DFBRegister, apply_affine_transformation, apply_bspline_transform, estimate_bspline_transform, match_histograms, prealignment, ) from tiatoolbox.utils.metrics import dice from tiatoolbox.utils.misc import imread from tiatoolbox.wsicore.wsireader import WSIReader def test_extract_features(dfbr_features): """Test for CNN based feature extraction function.""" df = DFBRegister() fixed_img = np.repeat( np.expand_dims( np.repeat( np.expand_dims(np.arange(0, 64, 1, dtype=np.uint8), axis=1), 64, axis=1 ), axis=2, ), 3, axis=2, ) output = df.extract_features(fixed_img, fixed_img) pool3_feat = output["block3_pool"][0, :].detach().numpy() pool4_feat = output["block4_pool"][0, :].detach().numpy() pool5_feat = output["block5_pool"][0, :].detach().numpy() _pool3_feat, _pool4_feat, _pool5_feat = np.load( str(dfbr_features), allow_pickle=True ) assert np.mean(np.abs(pool3_feat - _pool3_feat)) < 1.0e-4 assert np.mean(np.abs(pool4_feat - _pool4_feat)) < 1.0e-4 assert np.mean(np.abs(pool5_feat - _pool5_feat)) < 1.0e-4 def test_feature_mapping(fixed_image, moving_image): """Test for CNN based feature matching function.""" fixed_img = imread(fixed_image) moving_img = imread(moving_image) pre_transform = np.array([[-1, 0, 337.8], [0, -1, 767.7], [0, 0, 1]]) moving_img = cv2.warpAffine( moving_img, pre_transform[0:-1][:], fixed_img.shape[:2][::-1] ) df = DFBRegister() features = df.extract_features(fixed_img, moving_img) fixed_matched_points, moving_matched_points, _ = df.feature_mapping(features) output = df.estimate_affine_transform(fixed_matched_points, moving_matched_points) expected = np.array( [[0.98843, 0.00184, 1.75437], [-0.00472, 0.96973, 5.38854], [0, 0, 1]] ) assert np.mean(output - expected) < 1.0e-6 def test_dfbr_features(): """Test for feature input to feature_mapping function.""" df = DFBRegister() fixed_img = np.repeat( np.expand_dims( np.repeat( np.expand_dims(np.arange(0, 64, 1, dtype=np.uint8), axis=1), 64, axis=1 ), axis=2, ), 3, axis=2, ) features = df.extract_features(fixed_img, fixed_img) del features["block5_pool"] with pytest.raises( ValueError, match=r".*The feature mapping step expects 3 blocks of features.*", ): _, _, _ = df.feature_mapping(features) def test_prealignment_mask(): """Test for mask inputs to prealignment function.""" fixed_img = np.random.rand(10, 10) moving_img = np.random.rand(10, 10) no_fixed_mask = np.zeros(shape=fixed_img.shape, dtype=int) no_moving_mask = np.zeros(shape=moving_img.shape, dtype=int) with pytest.raises(ValueError, match=r".*The foreground is missing in the mask.*"): _ = prealignment(fixed_img, moving_img, no_fixed_mask, no_moving_mask) def test_prealignment_input_shape(): """Test for inputs to prealignment function.""" fixed_img = np.random.rand(10, 10) moving_img = np.random.rand(15, 10) fixed_mask = np.random.choice([0, 1], size=(15, 10)) moving_mask = np.random.choice([0, 1], size=(10, 10)) with pytest.raises( ValueError, match=r".*Mismatch of shape between image and its corresponding mask.*", ): _ = prealignment(fixed_img, moving_img, fixed_mask, moving_mask) def test_prealignment_rotation_step(): """Test for rotation step input to prealignment function.""" fixed_img = np.random.rand(10, 10) moving_img = np.random.rand(10, 10) fixed_mask = np.random.choice([0, 1], size=(10, 10)) moving_mask = np.random.choice([0, 1], size=(10, 10)) with pytest.raises( ValueError, match=r".*Please select the rotation step in between 10 and 20.*" ): _ = prealignment( fixed_img, moving_img, fixed_mask, moving_mask, rotation_step=9 ) with pytest.raises( ValueError, match=r".*Please select the rotation step in between 10 and 20.*" ): _ = prealignment( fixed_img, moving_img, fixed_mask, moving_mask, rotation_step=21 ) def test_prealignment_output(fixed_image, moving_image, fixed_mask, moving_mask): """Test for prealignment of an image pair""" fixed_img = imread(fixed_image) moving_img = imread(moving_image) fixed_mask = imread(fixed_mask) moving_mask = imread(moving_mask) expected = np.array([[-1, 0, 337.8], [0, -1, 767.7], [0, 0, 1]]) output, _, _, _ = prealignment( fixed_img, moving_img, fixed_mask, moving_mask, dice_overlap=0.5, rotation_step=10, ) assert np.linalg.norm(expected[:2, :2] - output[:2, :2]) < 0.1 assert np.linalg.norm(expected[:2, 2] - output[:2, 2]) < 10 fixed_img, moving_img = fixed_img[:, :, 0], moving_img[:, :, 0] output, _, _, _ = prealignment( fixed_img, moving_img, fixed_mask, moving_mask, dice_overlap=0.5, rotation_step=10, ) assert np.linalg.norm(expected - output) < 0.2 def test_dice_overlap_range(): """Test if the value of dice_overlap is within the range.""" fixed_img = np.random.randint(20, size=(256, 256)) moving_img = np.random.randint(20, size=(256, 256)) fixed_mask = np.random.randint(2, size=(256, 256)) moving_mask = np.random.randint(2, size=(256, 256)) with pytest.raises( ValueError, match=r".*The dice_overlap should be in between 0 and 1.0.*" ): _ = prealignment(fixed_img, moving_img, fixed_mask, moving_mask, dice_overlap=2) with pytest.raises( ValueError, match=r".*The dice_overlap should be in between 0 and 1.0.*" ): _ = prealignment( fixed_img, moving_img, fixed_mask, moving_mask, dice_overlap=-1 ) def test_warning( fixed_image, moving_image, fixed_mask, moving_mask, caplog, ): """Test for displaying warning in prealignment function.""" fixed_img = imread(pathlib.Path(fixed_image)) moving_img = imread(pathlib.Path(moving_image)) fixed_mask = imread(pathlib.Path(fixed_mask)) moving_mask = imread(pathlib.Path(moving_mask)) fixed_img, moving_img = fixed_img[:, :, 0], moving_img[:, :, 0] _ = prealignment(fixed_img, moving_img, fixed_mask, moving_mask, dice_overlap=0.9) assert "Not able to find the best transformation" in caplog.text def test_match_histogram_inputs(): """Test for inputs to match_histogram function.""" image_a = np.random.randint(256, size=(256, 256, 3)) image_b = np.random.randint(256, size=(256, 256, 3)) with pytest.raises( ValueError, match=r".*The input images should be grayscale images.*" ): _, _ = match_histograms(image_a, image_b) def test_match_histograms(): """Test for preprocessing/normalization of an image pair.""" image_a = np.random.randint(256, size=(256, 256)) image_b = np.zeros(shape=(256, 256), dtype=int) out_a, out_b = match_histograms(image_a, image_b, 3) assert np.all(out_a == image_a) assert np.all(out_b == 255) out_a, out_b = match_histograms(image_b, image_a, 3) assert np.all(out_a == 255) assert np.all(out_b == image_a) image_a = np.random.randint(256, size=(256, 256, 1)) image_b = np.random.randint(256, size=(256, 256, 1)) _, _ = match_histograms(image_a, image_b) image_a = np.array( [ [129, 134, 195, 241, 168], [231, 91, 145, 91, 0], [64, 87, 194, 112, 99], [138, 111, 99, 124, 86], [164, 127, 167, 222, 100], ], dtype=np.uint8, ) image_b = np.array( [ [25, 91, 177, 212, 114], [62, 86, 83, 31, 17], [13, 16, 191, 19, 149], [58, 127, 22, 111, 255], [164, 7, 110, 76, 222], ], dtype=np.uint8, ) expected_output = np.array( [ [91, 110, 191, 255, 164], [222, 22, 114, 22, 7], [13, 17, 177, 76, 31], [111, 62, 31, 83, 16], [127, 86, 149, 212, 58], ] ) norm_image_a, norm_image_b = match_histograms(image_a, image_b) assert np.all(norm_image_a == expected_output) assert np.all(norm_image_b == image_b) def test_filtering_duplicate_matching_points(): """Test filtering_matching_points function with duplicate matching points.""" fixed_mask = np.zeros((50, 50)) fixed_mask[20:40, 20:40] = 255 moving_mask = np.zeros((50, 50)) moving_mask[20:40, 20:40] = 255 fixed_points = np.array( [[25, 25], [25, 25], [25, 25], [30, 25], [25, 30], [30, 35], [21, 37]] ) moving_points = np.array( [[30, 25], [32, 36], [31, 20], [30, 35], [30, 35], [30, 35], [26, 27]] ) quality = np.ones((7, 1)) df = DFBRegister() _ = df.filtering_matching_points( fixed_mask, moving_mask, fixed_points, moving_points, quality ) def test_filtering_no_duplicate_matching_points(): """Test filtering_matching_points function with no duplicate matching points.""" fixed_mask = np.zeros((50, 50)) fixed_mask[20:40, 20:40] = 255 moving_mask = np.zeros((50, 50)) moving_mask[20:40, 20:40] = 255 fixed_points = np.array( [[25, 25], [25, 28], [15, 25], [30, 25], [25, 30], [30, 35], [21, 37]] ) moving_points = np.array( [[30, 25], [32, 36], [31, 20], [20, 35], [30, 15], [34, 35], [26, 27]] ) quality = np.ones((7, 1)) df = DFBRegister() _ = df.filtering_matching_points( fixed_mask, moving_mask, fixed_points, moving_points, quality ) def test_register_input(): """Test for inputs to register function.""" fixed_img = np.random.rand(32, 32) moving_img = np.random.rand(32, 32) fixed_mask = np.random.choice([0, 1], size=(32, 32)) moving_mask = np.random.choice([0, 1], size=(32, 32)) df = DFBRegister() with pytest.raises( ValueError, match=r".*The required shape for fixed and moving images is n x m x 3.*", ): _ = df.register(fixed_img, moving_img, fixed_mask, moving_mask) def test_register_input_channels(): """Test for checking inputs' number of channels for register function.""" fixed_img = np.random.rand(32, 32, 1) moving_img = np.random.rand(32, 32, 1) fixed_mask = np.random.choice([0, 1], size=(32, 32)) moving_mask = np.random.choice([0, 1], size=(32, 32)) df = DFBRegister() with pytest.raises( ValueError, match=r".*The input images are expected to have 3 channels.*" ): _ = df.register( fixed_img[:, :, :1], moving_img[:, :, :1], fixed_mask, moving_mask ) def test_register_output_with_initializer( fixed_image, moving_image, fixed_mask, moving_mask ): """Test for register function with initializer.""" fixed_img = imread(fixed_image) moving_img = imread(moving_image) fixed_msk = imread(fixed_mask) moving_msk = imread(moving_mask) df = DFBRegister() pre_transform = np.array([[-1, 0, 337.8], [0, -1, 767.7], [0, 0, 1]]) expected = np.array( [[-0.98454, -0.00708, 397.95628], [-0.01024, -0.99752, 684.81131], [0, 0, 1]] ) output = df.register( fixed_img, moving_img, fixed_msk, moving_msk, transform_initializer=pre_transform, ) assert np.linalg.norm(expected[:2, :2] - output[:2, :2]) < 0.1 assert np.linalg.norm(expected[:2, 2] - output[:2, 2]) < 10 def test_register_output_without_initializer( fixed_image, moving_image, fixed_mask, moving_mask ): """Test for register function without initializer.""" fixed_img = imread(fixed_image) moving_img = imread(moving_image) fixed_msk = imread(fixed_mask) moving_msk = imread(moving_mask) df = DFBRegister() expected = np.array( [[-0.99863, 0.00189, 389.79039], [0.00691, -0.99810, 874.98081], [0, 0, 1]] ) output = df.register( fixed_img, moving_img, fixed_msk, moving_msk, ) assert np.linalg.norm(expected[:2, :2] - output[:2, :2]) < 0.1 assert np.linalg.norm(expected[:2, 2] - output[:2, 2]) < 10 _ = df.register( fixed_img, moving_img, fixed_msk[:, :, 0], moving_msk[:, :, 0], ) def test_register_tissue_transform(fixed_image, moving_image, fixed_mask, moving_mask): """Test for the estimated tissue and block-wise transform in register function.""" fixed_img = imread(fixed_image) moving_img = imread(moving_image) fixed_msk = imread(fixed_mask) moving_msk = imread(moving_mask) df = DFBRegister() pre_transform = np.eye(3) _ = df.register( fixed_img, moving_img, fixed_msk, moving_msk, transform_initializer=pre_transform, ) def test_estimate_bspline_transform_inputs(): """Test input dimensions for estimate_bspline_transform function.""" fixed_img = np.random.rand(32, 32, 32, 3) moving_img = np.random.rand(32, 32, 32, 3) fixed_mask = np.random.choice([0, 1], size=(32, 32)) moving_mask = np.random.choice([0, 1], size=(32, 32)) with pytest.raises( ValueError, match=r".*The input images can only be grayscale or RGB images.*" ): _, _ = estimate_bspline_transform( fixed_img, moving_img, fixed_mask, moving_mask ) def test_estimate_bspline_transform_rgb_input(): """Test inputs' number of channels for estimate_bspline_transform function.""" fixed_img = np.random.rand(32, 32, 32) moving_img = np.random.rand(32, 32, 32) fixed_mask = np.random.choice([0, 1], size=(32, 32)) moving_mask = np.random.choice([0, 1], size=(32, 32)) with pytest.raises( ValueError, match=r".*The input images can only have 3 channels.*" ): _, _ = estimate_bspline_transform( fixed_img, moving_img, fixed_mask, moving_mask ) def test_bspline_transform(fixed_image, moving_image, fixed_mask, moving_mask): """Test for estimate_bspline_transform function.""" fixed_img = imread(fixed_image) moving_img = imread(moving_image) fixed_mask_ = imread(fixed_mask) moving_mask_ = imread(moving_mask) rigid_transform = np.array( [[-0.99683, -0.00333, 338.69983], [-0.03201, -0.98420, 770.22941], [0, 0, 1]] ) moving_img = apply_affine_transformation(fixed_img, moving_img, rigid_transform) moving_mask_ = apply_affine_transformation(fixed_img, moving_mask_, rigid_transform) # Grayscale images as input transform = estimate_bspline_transform( fixed_img[:, :, 0], moving_img[:, :, 0], fixed_mask_[:, :, 0], moving_mask_[:, :, 0], ) _ = apply_bspline_transform(fixed_img[:, :, 0], moving_img[:, :, 0], transform) # RGB images as input transform = estimate_bspline_transform( fixed_img, moving_img, fixed_mask_, moving_mask_ ) _ = apply_bspline_transform(fixed_img, moving_img, transform) registered_msk = apply_bspline_transform(fixed_mask_, moving_mask_, transform) mask_overlap = dice(fixed_mask_, registered_msk) assert mask_overlap > 0.75 def test_affine_wsi_transformer(sample_ome_tiff): test_locations = [(1001, 600), (1000, 500), (800, 701)] # at base level 0 resolution = 0 size = (100, 100) for location in test_locations: wsi_reader = WSIReader.open(input_img=sample_ome_tiff) expected = wsi_reader.read_rect( location, size, resolution=resolution, units="level" ) transform_level0 = np.array( [ [0, -1, location[0] + location[1] + size[1]], [1, 0, location[1] - location[0]], [0, 0, 1], ] ) tfm = AffineWSITransformer(wsi_reader, transform_level0) output = tfm.read_rect(location, size, resolution=resolution, units="level") expected = cv2.rotate(expected, cv2.ROTATE_90_CLOCKWISE) assert np.sum(expected - output) == 0
16,424
31.719124
88
py
tiatoolbox
tiatoolbox-master/tests/test_tiatoolbox.py
#!/usr/bin/env python """Pytests for `tiatoolbox` package.""" from click.testing import CliRunner from tiatoolbox import __version__, cli # ------------------------------------------------------------------------------------- # Command Line Interface # ------------------------------------------------------------------------------------- def test_command_line_help_interface(): """Test the CLI help.""" runner = CliRunner() result = runner.invoke(cli.main) assert result.exit_code == 0 help_result = runner.invoke(cli.main, ["--help"]) assert help_result.exit_code == 0 assert "Computational pathology toolbox by TIA Centre." in help_result.output def test_command_line_version(): """Test for version check.""" runner = CliRunner() version_result = runner.invoke(cli.main, ["-v"]) assert __version__ in version_result.output version_result = runner.invoke(cli.main, ["--version"]) assert __version__ in version_result.output
985
31.866667
87
py
tiatoolbox
tiatoolbox-master/tests/test_annotation_tilerendering.py
"""tests for annotation rendering using AnnotationRenderer and AnnotationTileGenerator """ from pathlib import Path from typing import List, Union import matplotlib.pyplot as plt import numpy as np import pytest from matplotlib import colormaps from PIL import Image, ImageFilter from scipy.ndimage import label from shapely.geometry import LineString, MultiPoint, MultiPolygon, Polygon from shapely.geometry.point import Point from skimage import data from tests.test_annotation_stores import cell_polygon from tiatoolbox.annotation.storage import Annotation, AnnotationStore, SQLiteStore from tiatoolbox.tools.pyramid import AnnotationTileGenerator from tiatoolbox.utils.env_detection import running_on_travis from tiatoolbox.utils.visualization import AnnotationRenderer from tiatoolbox.wsicore import wsireader @pytest.fixture(scope="session") def cell_grid() -> List[Polygon]: """Generate a grid of fake cell boundary polygon annotations.""" np.random.seed(0) return [ cell_polygon(((i + 0.5) * 100, (j + 0.5) * 100)) for i, j in np.ndindex(5, 5) ] @pytest.fixture(scope="session") def points_grid(spacing=60) -> List[Point]: """Generate a grid of fake point annotations.""" np.random.seed(0) return [Point((600 + i * spacing, 600 + j * spacing)) for i, j in np.ndindex(7, 7)] @pytest.fixture(scope="session") def fill_store(cell_grid, points_grid): """Factory fixture to fill stores with test data.""" def _fill_store( store_class: AnnotationStore, path: Union[str, Path], ): """Fills store with random variety of annotations.""" store = store_class(path) cells = [ Annotation( cell, {"type": "cell", "prob": np.random.rand(1)[0], "color": (0, 1, 0)} ) for cell in cell_grid ] points = [ Annotation( point, {"type": "pt", "prob": np.random.rand(1)[0], "color": (1, 0, 0)} ) for point in points_grid ] lines = [ Annotation( LineString(((x, x + 500) for x in range(100, 400, 10))), {"type": "line", "prob": 0.75, "color": (0, 0, 1)}, ) ] annotations = cells + points + lines keys = store.append_many(annotations) return keys, store return _fill_store def test_tile_generator_len(fill_store, tmp_path): """Test __len__ for AnnotationTileGenerator.""" array = np.ones((1024, 1024)) wsi = wsireader.VirtualWSIReader(array, mpp=(1, 1)) _, store = fill_store(SQLiteStore, tmp_path / "test.db") tg = AnnotationTileGenerator(wsi.info, store, tile_size=256) assert len(tg) == (4 * 4) + (2 * 2) + 1 def test_tile_generator_iter(fill_store, tmp_path): """Test __iter__ for AnnotationTileGenerator.""" array = np.ones((1024, 1024)) wsi = wsireader.VirtualWSIReader(array, mpp=(1, 1)) _, store = fill_store(SQLiteStore, tmp_path / "test.db") tg = AnnotationTileGenerator(wsi.info, store, tile_size=256) for tile in tg: assert isinstance(tile, Image.Image) assert tile.size == (256, 256) @pytest.mark.skipif(running_on_travis(), reason="no display on travis.") def test_show_generator_iter(fill_store, tmp_path): """Show tiles with example annotations (if not travis).""" array = np.ones((1024, 1024)) wsi = wsireader.VirtualWSIReader(array, mpp=(1, 1)) _, store = fill_store(SQLiteStore, tmp_path / "test.db") renderer = AnnotationRenderer("prob") tg = AnnotationTileGenerator(wsi.info, store, renderer, tile_size=256) for i, tile in enumerate(tg): if i > 5: break assert isinstance(tile, Image.Image) assert tile.size == (256, 256) plt.imshow(tile) plt.show(block=False) def test_correct_number_rendered(fill_store, tmp_path): """Test that the expected number of annotations are rendered.""" array = np.ones((1024, 1024)) wsi = wsireader.VirtualWSIReader(array, mpp=(1, 1)) _, store = fill_store(SQLiteStore, tmp_path / "test.db") renderer = AnnotationRenderer(edge_thickness=0) tg = AnnotationTileGenerator(wsi.info, store, renderer) thumb = tg.get_thumb_tile() _, num = label(np.array(thumb)[:, :, 1]) # default colour is green assert num == 75 # expect 75 rendered objects def test_correct_colour_rendered(fill_store, tmp_path): """Test colour mapping.""" array = np.ones((1024, 1024)) wsi = wsireader.VirtualWSIReader(array, mpp=(1, 1)) _, store = fill_store(SQLiteStore, tmp_path / "test.db") renderer = AnnotationRenderer( "type", {"cell": (1, 0, 0, 1), "pt": (0, 1, 0, 1), "line": (0, 0, 1, 1)}, edge_thickness=0, ) tg = AnnotationTileGenerator(wsi.info, store, renderer, tile_size=256) thumb = tg.get_thumb_tile() _, num = label(np.array(thumb)[:, :, 1]) assert num == 49 # expect 49 green objects _, num = label(np.array(thumb)[:, :, 0]) assert num == 25 # expect 25 red objects _, num = label(np.array(thumb)[:, :, 2]) assert num == 1 # expect 1 blue objects def test_filter_by_expression(fill_store, tmp_path): """Test filtering using a where expression.""" array = np.ones((1024, 1024)) wsi = wsireader.VirtualWSIReader(array, mpp=(1, 1)) _, store = fill_store(SQLiteStore, tmp_path / "test.db") renderer = AnnotationRenderer(where='props["type"] == "cell"', edge_thickness=0) tg = AnnotationTileGenerator(wsi.info, store, renderer, tile_size=256) thumb = tg.get_thumb_tile() _, num = label(np.array(thumb)[:, :, 1]) assert num == 25 # expect 25 cell objects, as the added one is too small def test_zoomed_out_rendering(fill_store, tmp_path): """Test that the expected number of annotations are rendered.""" array = np.ones((1024, 1024)) wsi = wsireader.VirtualWSIReader(array, mpp=(1, 1)) _, store = fill_store(SQLiteStore, tmp_path / "test.db") small_annotation = Annotation( Polygon([(9, 9), (9, 10), (10, 10), (10, 9)]), {"type": "cell", "prob": 0.75, "color": (0, 0, 1)}, ) store.append(small_annotation) renderer = AnnotationRenderer( max_scale=1, edge_thickness=0, zoomed_out_strat="scale" ) tg = AnnotationTileGenerator(wsi.info, store, renderer, tile_size=256) thumb = tg.get_tile(1, 0, 0) _, num = label(np.array(thumb)[:, :, 1]) # default colour is green assert num == 25 # expect 25 cells in top left quadrant def test_decimation(fill_store, tmp_path): """Test decimation.""" array = np.ones((1024, 1024)) wsi = wsireader.VirtualWSIReader(array, mpp=(1, 1)) _, store = fill_store(SQLiteStore, tmp_path / "test.db") renderer = AnnotationRenderer(max_scale=1, zoomed_out_strat="decimate") tg = AnnotationTileGenerator(wsi.info, store, renderer, tile_size=256) thumb = tg.get_tile(1, 1, 1) plt.imshow(thumb) plt.show(block=False) _, num = label(np.array(thumb)[:, :, 1]) # default colour is green assert num == 17 # expect 17 pts in bottom right quadrant def test_get_tile_negative_level(fill_store, tmp_path): """Test for IndexError on negative levels.""" array = np.ones((1024, 1024)) wsi = wsireader.VirtualWSIReader(array) _, store = fill_store(SQLiteStore, tmp_path / "test.db") renderer = AnnotationRenderer(max_scale=1, edge_thickness=0) tg = AnnotationTileGenerator(wsi.info, store, renderer, tile_size=256) with pytest.raises(IndexError): tg.get_tile(-1, 0, 0) def test_get_tile_large_level(fill_store, tmp_path): """Test for IndexError on too large a level.""" array = np.ones((1024, 1024)) wsi = wsireader.VirtualWSIReader(array) _, store = fill_store(SQLiteStore, tmp_path / "test.db") renderer = AnnotationRenderer(max_scale=1, edge_thickness=0) tg = AnnotationTileGenerator(wsi.info, store, renderer, tile_size=256) with pytest.raises(IndexError): tg.get_tile(100, 0, 0) def test_get_tile_large_xy(fill_store, tmp_path): """Test for IndexError on too large an xy index.""" array = np.ones((1024, 1024)) wsi = wsireader.VirtualWSIReader(array) _, store = fill_store(SQLiteStore, tmp_path / "test.db") renderer = AnnotationRenderer(max_scale=1) tg = AnnotationTileGenerator(wsi.info, store, renderer, tile_size=256) with pytest.raises(IndexError): tg.get_tile(0, 100, 100) def test_sub_tile_levels(fill_store, tmp_path): """Test sub-tile level generation.""" array = data.camera() wsi = wsireader.VirtualWSIReader(array) class MockTileGenerator(AnnotationTileGenerator): """Mock generator with specific subtile_level.""" def tile_path(self, level: int, x: int, y: int) -> Path: # skipcq: PYL-R0201 """Tile path.""" return Path(level, x, y) @property def sub_tile_level_count(self): return 1 _, store = fill_store(SQLiteStore, tmp_path / "test.db") tg = MockTileGenerator(wsi.info, store, tile_size=224) tile = tg.get_tile(0, 0, 0) assert tile.size == (112, 112) def test_unknown_geometry(fill_store, tmp_path, caplog): """ Test warning when unknown geometries are present that cannot be rendered. """ array = np.ones((1024, 1024)) wsi = wsireader.VirtualWSIReader(array) _, store = fill_store(SQLiteStore, tmp_path / "test.db") store.append( Annotation(geometry=MultiPoint([(5.0, 5.0), (10.0, 10.0)]), properties={}) ) store.commit() renderer = AnnotationRenderer(max_scale=8, edge_thickness=0) tg = AnnotationTileGenerator(wsi.info, store, renderer, tile_size=256) tg.get_tile(0, 0, 0) assert "Unknown geometry" in caplog.text def test_interp_pad_warning(fill_store, tmp_path, caplog): """Test warning when providing unused options.""" array = np.ones((1024, 1024)) wsi = wsireader.VirtualWSIReader(array) _, store = fill_store(SQLiteStore, tmp_path / "test.db") tg = AnnotationTileGenerator(wsi.info, store, tile_size=256) tg.get_tile(0, 0, 0, pad_mode="constant") assert "interpolation, pad_mode are unused" in caplog.text def test_user_provided_cm(fill_store, tmp_path): """Test correct color mapping for user-provided cm name.""" array = np.ones((1024, 1024)) wsi = wsireader.VirtualWSIReader(array, mpp=(1, 1)) _, store = fill_store(SQLiteStore, tmp_path / "test.db") renderer = AnnotationRenderer( "prob", "viridis", edge_thickness=0, ) tg = AnnotationTileGenerator(wsi.info, store, renderer, tile_size=256) tile = np.array(tg.get_tile(1, 0, 1)) # line here with prob=0.75 color = tile[np.any(tile, axis=2), :3] color = color[0, :] viridis_mapper = colormaps["viridis"] assert np.all( np.equal(color, (np.array(viridis_mapper(0.75)) * 255)[:3].astype(np.uint8)) ) # expect rendered color to be viridis(0.75) def test_random_mapper(): """Test random colour map dict for list.""" test_list = ["line", "pt", "cell"] renderer = AnnotationRenderer(mapper=test_list) # check all the colours are valid rgba values for ann_type in test_list: rgba = renderer.mapper(ann_type) assert isinstance(rgba, tuple) assert len(rgba) == 4 for val in rgba: assert 0 <= val <= 1 def test_categorical_mapper(fill_store, tmp_path): """Test categorical mapper option to ease cli usage.""" array = np.ones((1024, 1024)) wsi = wsireader.VirtualWSIReader(array, mpp=(1, 1)) _, store = fill_store(SQLiteStore, tmp_path / "test.db") renderer = AnnotationRenderer(score_prop="type", mapper="categorical") AnnotationTileGenerator(wsi.info, store, renderer, tile_size=256) # check correct keys exist and all colours are valid rgba values for ann_type in ["line", "pt", "cell"]: rgba = renderer.mapper(ann_type) assert isinstance(rgba, tuple) assert len(rgba) == 4 for val in rgba: assert 0 <= val <= 1 def test_colour_prop_warning(fill_store, tmp_path, caplog): """ Test warning when rendering annotations in which the provided score_prop does not exist. """ array = np.ones((1024, 1024)) wsi = wsireader.VirtualWSIReader(array, mpp=(1, 1)) _, store = fill_store(SQLiteStore, tmp_path / "test.db") renderer = AnnotationRenderer(score_prop="nonexistant_prop") tg = AnnotationTileGenerator(wsi.info, store, renderer, tile_size=256) tg.get_tile(1, 0, 0) assert "not found in properties" in caplog.text def test_blur(fill_store, tmp_path): """Test blur.""" array = np.ones((1024, 1024)) wsi = wsireader.VirtualWSIReader(array, mpp=(1, 1)) _, store = fill_store(SQLiteStore, tmp_path / "test.db") renderer = AnnotationRenderer(blur_radius=5, edge_thickness=0) tg = AnnotationTileGenerator(wsi.info, store, renderer, tile_size=256) tile_blurred = tg.get_tile(1, 0, 0) renderer = AnnotationRenderer(edge_thickness=0) tg = AnnotationTileGenerator(wsi.info, store, renderer, tile_size=256) tile = tg.get_tile(1, 0, 0) blur_filter = ImageFilter.GaussianBlur(5) # blurring our un-blurred tile should give almost same result assert np.allclose(tile_blurred, tile.filter(blur_filter), atol=1) def test_direct_color(fill_store, tmp_path): """Test direct color.""" array = np.ones((1024, 1024)) wsi = wsireader.VirtualWSIReader(array, mpp=(1, 1)) _, store = fill_store(SQLiteStore, tmp_path / "test.db") renderer = AnnotationRenderer(score_prop="color", edge_thickness=0) tg = AnnotationTileGenerator(wsi.info, store, renderer, tile_size=256) thumb = tg.get_thumb_tile() _, num = label(np.array(thumb)[:, :, 1]) assert num == 25 # expect 25 green objects _, num = label(np.array(thumb)[:, :, 0]) assert num == 49 # expect 49 red objects _, num = label(np.array(thumb)[:, :, 2]) assert num == 1 # expect 1 blue objects def test_secondary_cmap(fill_store, tmp_path): """Test secondary cmap.""" array = np.ones((1024, 1024)) wsi = wsireader.VirtualWSIReader(array, mpp=(1, 1)) _, store = fill_store(SQLiteStore, tmp_path / "test.db") cmap_dict = {"type": "line", "score_prop": "prob", "mapper": colormaps["viridis"]} renderer = AnnotationRenderer( score_prop="type", secondary_cmap=cmap_dict, edge_thickness=0 ) tg = AnnotationTileGenerator(wsi.info, store, renderer, tile_size=256) tile = np.array(tg.get_tile(1, 0, 1)) # line here with prob=0.75 color = tile[np.any(tile, axis=2), :3] color = color[0, :] viridis_mapper = colormaps["viridis"] assert np.all( np.equal(color, (np.array(viridis_mapper(0.75)) * 255)[:3].astype(np.uint8)) ) # expect rendered color to be viridis(0.75) def test_unfilled_polys(fill_store, tmp_path): """Test unfilled polygons.""" array = np.ones((1024, 1024)) wsi = wsireader.VirtualWSIReader(array, mpp=(1, 1)) _, store = fill_store(SQLiteStore, tmp_path / "test.db") renderer = AnnotationRenderer(thickness=1) tg = AnnotationTileGenerator(wsi.info, store, renderer, tile_size=256) tile_outline = np.array(tg.get_tile(1, 0, 0)) tg.renderer.edge_thickness = -1 tile_filled = np.array(tg.get_tile(1, 0, 0)) # expect sum of filled polys to be much greater than sum of outlines assert np.sum(tile_filled) > 2 * np.sum(tile_outline) def test_multipolygon_render(cell_grid, tmp_path): """Test multipolygon rendering.""" array = np.ones((1024, 1024)) wsi = wsireader.VirtualWSIReader(array, mpp=(1, 1)) store = SQLiteStore(tmp_path / "test.db") # add a multi-polygon store.append(Annotation(MultiPolygon(cell_grid), {"color": (1, 0, 0)})) renderer = AnnotationRenderer(score_prop="color", edge_thickness=0) tg = AnnotationTileGenerator(wsi.info, store, renderer, tile_size=256) tile = np.array(tg.get_tile(1, 0, 0)) _, num = label(np.array(tile)[:, :, 0]) assert num == 25 # expect 25 red objects
16,157
37.198582
88
py
tiatoolbox
tiatoolbox-master/tests/test_utils.py
"""Tests for utils.""" import hashlib import os import random import shutil from pathlib import Path from typing import Tuple import cv2 import joblib import numpy as np import pandas as pd import pytest from PIL import Image from shapely.geometry import Polygon from tests.test_annotation_stores import cell_polygon from tiatoolbox import rcParam, utils from tiatoolbox.utils import misc from tiatoolbox.utils.exceptions import FileNotSupported from tiatoolbox.utils.transforms import locsize2bounds def sub_pixel_read(test_image, pillow_test_image, bounds, ow, oh): """sub_pixel_read test helper function.""" output = utils.image.sub_pixel_read(test_image, bounds, (ow, oh)) assert (ow, oh) == tuple(output.shape[:2][::-1]) output = utils.image.sub_pixel_read( pillow_test_image, bounds, (ow, oh), stride=[1, 1] ) assert (ow, oh) == tuple(output.shape[:2][::-1]) def test_imresize(): """Test for imresize.""" img = np.zeros((2000, 1000, 3)) resized_img = utils.transforms.imresize(img, scale_factor=0.5) assert resized_img.shape == (1000, 500, 3) resized_img = utils.transforms.imresize(resized_img, scale_factor=2.0) assert resized_img.shape == (2000, 1000, 3) resized_img = utils.transforms.imresize( img, scale_factor=0.5, interpolation=cv2.INTER_CUBIC, ) assert resized_img.shape == (1000, 500, 3) # test for dtype conversion, pairs of # (original type, converted type) test_dtypes = [ (np.bool_, np.uint8), (np.int8, np.int16), (np.int16, np.int16), (np.int32, np.float32), (np.uint8, np.uint8), (np.uint16, np.uint16), (np.uint32, np.float32), (np.int64, np.float64), (np.uint64, np.float64), (np.float16, np.float32), (np.float32, np.float32), (np.float64, np.float64), ] img = np.zeros((100, 100, 3)) for original_dtype, converted_dtype in test_dtypes: resized_img = utils.transforms.imresize( img.astype(original_dtype), scale_factor=0.5, interpolation=cv2.INTER_CUBIC, ) assert resized_img.shape == (50, 50, 3) assert resized_img.dtype == converted_dtype # test resizing multiple channels img = np.random.randint(0, 256, (4, 4, 16)) resized_img = utils.transforms.imresize( img, scale_factor=4, interpolation=cv2.INTER_CUBIC, ) assert resized_img.shape == (16, 16, 16) # test for not supporting dtype img = np.random.randint(0, 256, (4, 4, 16)) with pytest.raises((AttributeError, ValueError), match=r".*float128.*"): resized_img = utils.transforms.imresize( img.astype(np.float128), scale_factor=4, interpolation=cv2.INTER_CUBIC, ) def test_imresize_1x1(): """Test imresize with 1x1 image.""" img = np.zeros((1, 1, 3)) resized_img = utils.transforms.imresize(img, scale_factor=10) assert resized_img.shape == (10, 10, 3) def test_imresize_no_scale_factor(): """Test for imresize with no scale_factor given.""" img = np.zeros((2000, 1000, 3)) resized_img = utils.transforms.imresize(img, output_size=(50, 100)) assert resized_img.shape == (100, 50, 3) def test_imresize_no_scale_factor_or_output_size(): """Test imresize with no scale_factor or output_size.""" img = np.zeros((2000, 1000, 3)) with pytest.raises(TypeError, match="One of scale_factor and output_size"): utils.transforms.imresize(img) def test_background_composite(): """Test for background composite.""" new_im = np.zeros((2000, 2000, 4)).astype("uint8") new_im[:1000, :, 3] = 255 im = utils.transforms.background_composite(new_im) assert np.all(im[1000:, :, :] == 255) assert np.all(im[:1000, :, :] == 0) im = utils.transforms.background_composite(new_im, alpha=True) assert np.all(im[:, :, 3] == 255) new_im = Image.fromarray(new_im) im = utils.transforms.background_composite(new_im, alpha=True) assert np.all(im[:, :, 3] == 255) def test_mpp2common_objective_power(sample_svs): """Test approximate conversion of mpp to objective power.""" mapping = [ (0.05, 100), (0.07, 100), (0.10, 100), (0.12, 90), (0.15, 60), (0.29, 40), (0.30, 40), (0.49, 20), (0.60, 20), (1.00, 10), (1.20, 10), (2.00, 5), (2.40, 4), (3.00, 4), (4.0, 2.5), (4.80, 2), (8.00, 1.25), (9.00, 1), ] for mpp, result in mapping: assert utils.misc.mpp2common_objective_power(mpp) == result assert np.array_equal( utils.misc.mpp2common_objective_power([mpp] * 2), [result] * 2 ) def test_ppu2mpp_invalid_units(): """Test ppu2mpp with invalid units.""" with pytest.raises(ValueError, match="Invalid units"): utils.misc.ppu2mpp(1, units="invalid") def test_ppu2mpp(): """Test converting pixels-per-unit to mpp with ppu2mpp.""" assert utils.misc.ppu2mpp(1, units="in") == 25_400 assert utils.misc.ppu2mpp(1, units="inch") == 25_400 assert utils.misc.ppu2mpp(1, units="mm") == 1_000 assert utils.misc.ppu2mpp(1, units="cm") == 10_000 assert utils.misc.ppu2mpp(1, units=2) == 25_400 # inch assert utils.misc.ppu2mpp(1, units=3) == 10_000 # cm assert utils.misc.ppu2mpp(72, units="in") == pytest.approx(352.8, abs=0.1) assert utils.misc.ppu2mpp(50_000, units="in") == pytest.approx(0.508, abs=0.1) def test_assert_dtype_int(): """Test AssertionError for dtype test.""" utils.misc.assert_dtype_int(input_var=np.array([1, 2])) with pytest.raises(AssertionError): utils.misc.assert_dtype_int( input_var=np.array([1.0, 2]), message="Bounds must be integers." ) def test_safe_padded_read_non_int_bounds(): """Test safe_padded_read with non-integer bounds.""" data = np.zeros((16, 16)) bounds = (1.5, 1, 5, 5) with pytest.raises(ValueError, match="integer"): utils.image.safe_padded_read(data, bounds) def test_safe_padded_read_negative_padding(): """Test safe_padded_read with negative bounds.""" data = np.zeros((16, 16)) bounds = (1, 1, 5, 5) with pytest.raises(ValueError, match="negative"): utils.image.safe_padded_read(data, bounds, padding=-1) def test_safe_padded_read_pad_mode_none(): """Test safe_padded_read with pad_mode=None.""" data = np.zeros((16, 16)) bounds = (-5, -5, 5, 5) region = utils.image.safe_padded_read(data, bounds, pad_mode=None) assert region.shape == (5, 5) def test_safe_padded_read_padding_formats(): """Test safe_padded_read with different padding argument formats.""" data = np.zeros((16, 16)) bounds = (0, 0, 8, 8) stride = (1, 1) for padding in [1, [1], (1,), [1, 1], (1, 1), [1] * 4]: region = utils.image.safe_padded_read( data, bounds, padding=padding, stride=stride, ) assert region.shape == (8 + 2, 8 + 2) def test_safe_padded_read_pad_kwargs(source_image): """Test passing extra kwargs to safe_padded_read for np.pad.""" data = utils.misc.imread(str(source_image)) bounds = (0, 0, 8, 8) padding = 2 region = utils.image.safe_padded_read( data, bounds, pad_mode="reflect", padding=padding, ) even_region = utils.image.safe_padded_read( data, bounds, pad_mode="reflect", padding=padding, pad_kwargs={ "reflect_type": "even", }, ) assert np.all(region == even_region) odd_region = utils.image.safe_padded_read( data, bounds, pad_mode="reflect", padding=padding, pad_kwargs={ "reflect_type": "odd", }, ) assert not np.all(region == odd_region) def test_safe_padded_read_pad_constant_values(): """Test safe_padded_read with custom pad constant values. This test creates an image of zeros and reads the whole image with a padding of 1 and constant values of 10 for padding. It then checks for a 1px border of 10s all the way around the zeros. """ for side_len in range(1, 5): data = np.zeros((side_len, side_len)) bounds = (0, 0, side_len, side_len) padding = 1 region = utils.image.safe_padded_read( data, bounds, padding=padding, pad_constant_values=10, ) assert np.sum(region == 10) == (4 * side_len) + 4 def test_fuzz_safe_padded_read_edge_padding(): """Fuzz test for padding at edges of an image. This test creates a 16x16 image with a gradient from 1 to 17 across it. A region is read using safe_padded_read with a constant padding of 0 and an offset by some random 'shift' amount between 1 and 16. The resulting image is checked for the correct number of 0 values. """ random.seed(0) for _ in range(1000): data = np.repeat([range(1, 17)], 16, axis=0) # Create bounds to fit the image and shift off by one # randomly in x or y sign = (-1) ** np.random.randint(0, 1) axis = random.randint(0, 1) shift = np.tile([1 - axis, axis], 2) shift_magnitude = random.randint(1, 16) bounds = np.array([0, 0, 16, 16]) + (shift * sign * shift_magnitude) region = utils.image.safe_padded_read(data, bounds) assert np.sum(region == 0) == (16 * shift_magnitude) def test_fuzz_safe_padded_read(): """Fuzz test for safe_padded_read.""" random.seed(0) for _ in range(1000): data = np.random.randint(0, 255, (16, 16)) loc = np.random.randint(0, 16, 2) size = (16, 16) bounds = locsize2bounds(loc, size) padding = np.random.randint(0, 16) region = utils.image.safe_padded_read(data, bounds, padding=padding) assert all(np.array(region.shape) == 16 + 2 * padding) def test_safe_padded_read_padding_shape(): """Test safe_padded_read for invalid padding shape.""" data = np.zeros((16, 16)) bounds = (1, 1, 5, 5) with pytest.raises(ValueError, match="size 3"): utils.image.safe_padded_read(data, bounds, padding=(1, 1, 1)) def test_safe_padded_read_stride_shape(): """Test safe_padded_read for invalid stride size.""" data = np.zeros((16, 16)) bounds = (1, 1, 5, 5) with pytest.raises(ValueError, match="size 1 or 2"): utils.image.safe_padded_read(data, bounds, stride=(1, 1, 1)) def test_sub_pixel_read(source_image): """Test sub-pixel numpy image reads with known tricky parameters.""" image_path = Path(source_image) assert image_path.exists() test_image = utils.misc.imread(image_path) pillow_test_image = Image.fromarray(test_image) x = 6 y = -4 w = 21.805648705868652 h = 0.9280264518437986 bounds = (x, y, x + w, y + h) ow = 88 oh = 98 sub_pixel_read(test_image, pillow_test_image, bounds, ow, oh) x = 13 y = 15 w = 29.46 h = 6.92 bounds = (x, y, x + w, y + h) ow = 93 oh = 34 sub_pixel_read(test_image, pillow_test_image, bounds, ow, oh) def test_aligned_padded_sub_pixel_read(source_image): """Test sub-pixel numpy image reads with pixel-aligned bounds.""" image_path = Path(source_image) assert image_path.exists() test_image = utils.misc.imread(image_path) x = 1 y = 1 w = 5 h = 5 padding = 1 bounds = (x, y, x + w, y + h) ow = 4 oh = 4 output = utils.image.sub_pixel_read(test_image, bounds, (ow, oh), padding=padding) assert (ow + 2 * padding, oh + 2 * padding) == tuple(output.shape[:2][::-1]) def test_sub_pixel_read_with_pad_kwargs(source_image): """Test sub-pixel numpy image reads with pad kwargs.""" image_path = Path(source_image) assert image_path.exists() test_image = utils.misc.imread(image_path) x = 1 y = 1 w = 5 h = 5 padding = 1 bounds = (x, y, x + w, y + h) ow = 4 oh = 4 output = utils.image.sub_pixel_read( test_image, bounds, (ow, oh), padding=padding, pad_mode="reflect", pad_kwargs={"reflect_type": "even"}, ) assert (ow + 2 * padding, oh + 2 * padding) == tuple(output.shape[:2][::-1]) def test_non_aligned_padded_sub_pixel_read(source_image): """Test sub-pixel numpy image reads with non-pixel-aligned bounds.""" image_path = Path(source_image) assert image_path.exists() test_image = utils.misc.imread(image_path) x = 0.5 y = 0.5 w = 4 h = 4 for padding in [1, 2, 3]: bounds = (x, y, x + w, y + h) ow = 4 oh = 4 output = utils.image.sub_pixel_read( test_image, bounds, (ow, oh), padding=padding ) assert (ow + 2 * padding, oh + 2 * padding) == tuple(output.shape[:2][::-1]) def test_non_baseline_padded_sub_pixel_read(source_image): """Test sub-pixel numpy image reads with baseline padding.""" image_path = Path(source_image) assert image_path.exists() test_image = utils.misc.imread(image_path) x = 0.5 y = 0.5 w = 4 h = 4 for padding in [1, 2, 3]: bounds = (x, y, x + w, y + h) ow = 8 oh = 8 output = utils.image.sub_pixel_read( test_image, bounds, (ow, oh), padding=padding, pad_at_baseline=True ) assert (ow + 2 * 2 * padding, oh + 2 * 2 * padding) == tuple( output.shape[:2][::-1] ) def test_sub_pixel_read_pad_mode_none(): """Test sub_pixel_read with invalid interpolation.""" data = np.ones((16, 16)) bounds = (-1, -1, 5, 5) region = utils.image.sub_pixel_read(data, bounds, (6, 6), pad_mode="none") assert region.shape[:2] == (5, 5) def test_sub_pixel_read_invalid_interpolation(): """Test sub_pixel_read with invalid interpolation.""" data = np.zeros((16, 16)) out_size = data.shape bounds = (1.5, 1, 5, 5) with pytest.raises(ValueError, match="interpolation"): utils.image.sub_pixel_read(data, bounds, out_size, interpolation="fizz") def test_sub_pixel_read_invalid_bounds(): """Test sub_pixel_read with invalid bounds.""" data = np.zeros((16, 16)) out_size = data.shape bounds = (0, 0, 0, 0) with pytest.raises(ValueError, match="Bounds must have non-zero size"): utils.image.sub_pixel_read(data, bounds, out_size) bounds = (1.5, 1, 1.5, 0) with pytest.raises(ValueError, match="Bounds must have non-zero size"): utils.image.sub_pixel_read(data, bounds, out_size) def test_sub_pixel_read_pad_at_baseline(): """Test sub_pixel_read with baseline padding.""" data = np.zeros((16, 16)) out_size = data.shape bounds = (0, 0, 8, 8) for padding in range(3): region = utils.image.sub_pixel_read( data, bounds, output_size=out_size, padding=padding, pad_at_baseline=True ) assert region.shape == (16 + 4 * padding, 16 + 4 * padding) region = utils.image.sub_pixel_read( data, bounds, out_size, pad_at_baseline=True, read_func=utils.image.safe_padded_read, ) assert region.shape == (16, 16) def test_sub_pixel_read_bad_read_func(): """Test sub_pixel_read with read_func returning None.""" data = np.zeros((16, 16)) out_size = data.shape bounds = (0, 0, 8, 8) def bad_read_func(img, bounds, *kwargs): return None with pytest.raises(ValueError, match="None"): utils.image.sub_pixel_read( data, bounds, out_size, read_func=bad_read_func, ) def test_sub_pixel_read_padding_formats(): """Test sub_pixel_read with different padding argument formats.""" data = np.zeros((16, 16)) out_size = data.shape bounds = (0, 0, 8, 8) for padding in [1, [1], (1,), [1, 1], (1, 1), [1] * 4]: region = utils.image.sub_pixel_read( data, bounds, out_size, padding=padding, pad_at_baseline=True ) assert region.shape == (16 + 4, 16 + 4) region = utils.image.sub_pixel_read(data, bounds, out_size, padding=padding) assert region.shape == (16 + 2, 16 + 2) def test_sub_pixel_read_negative_size_bounds(source_image): """Test sub_pixel_read with different padding argument formats.""" image_path = Path(source_image) assert image_path.exists() test_image = utils.misc.imread(image_path) ow = 25 oh = 25 x = 5 y = 5 w = -4.5 h = -4.5 bounds = locsize2bounds((x, y), (w, h)) output = utils.image.sub_pixel_read(test_image, bounds, (ow, oh)) x = 0.5 y = 0.5 w = 4.5 h = 4.5 bounds = locsize2bounds((x, y), (w, h)) print(bounds) flipped_output = utils.image.sub_pixel_read(test_image, bounds, (ow, oh)) assert np.all(np.fliplr(np.flipud(flipped_output)) == output) def test_fuzz_sub_pixel_read(source_image): """Fuzz test for numpy sub-pixel image reads.""" random.seed(0) image_path = Path(source_image) assert image_path.exists() test_image = utils.misc.imread(image_path) for _ in range(10000): x = random.randint(-5, 32 - 5) y = random.randint(-5, 32 - 5) w = random.random() * random.randint(1, 32) h = random.random() * random.randint(1, 32) bounds = (x, y, x + w, y + h) ow = random.randint(4, 128) oh = random.randint(4, 128) output = utils.image.sub_pixel_read( test_image, bounds, (ow, oh), interpolation="linear", ) assert (ow, oh) == tuple(output.shape[:2][::-1]) def test_fuzz_padded_sub_pixel_read(source_image): """Fuzz test for numpy sub-pixel image reads with padding.""" random.seed(0) image_path = Path(source_image) assert image_path.exists() test_image = utils.misc.imread(image_path) for _ in range(10000): x = random.randint(-5, 32 - 5) y = random.randint(-5, 32 - 5) w = 4 + random.random() * random.randint(1, 32) h = 4 + random.random() * random.randint(1, 32) padding = random.randint(0, 2) bounds = (x, y, x + w, y + h) ow = random.randint(4, 128) oh = random.randint(4, 128) output = utils.image.sub_pixel_read( test_image, bounds, (ow, oh), interpolation="linear", padding=padding, pad_kwargs={"constant_values": 0}, ) assert (ow + 2 * padding, oh + 2 * padding) == tuple(output.shape[:2][::-1]) def test_sub_pixel_read_interpolation_modes(): """Test sub_pixel_read with different padding argument formats.""" data = np.mgrid[:16:1, :16:1].sum(0).astype(np.uint8) out_size = data.shape bounds = (0, 0, 8, 8) for mode in ["nearest", "linear", "cubic", "lanczos"]: output = utils.image.sub_pixel_read(data, bounds, out_size, interpolation=mode) assert output.shape == out_size def test_sub_pixel_read_incorrect_read_func_return(): """Test for sub pixel reading with incorrect read func return.""" bounds = (0, 0, 8, 8) image = np.ones((10, 10)) def read_func(*args, **kwargs): return np.ones((5, 5)) with pytest.raises(ValueError, match="incorrect size"): utils.image.sub_pixel_read( image, bounds=bounds, output_size=(10, 10), read_func=read_func, ) def test_sub_pixel_read_empty_read_func_return(): """Test for sub pixel reading with empty read func return.""" bounds = (0, 0, 8, 8) image = np.ones((10, 10)) def read_func(*args, **kwargs): return np.ones((0, 0)) with pytest.raises(ValueError, match="is empty"): utils.image.sub_pixel_read( image, bounds=bounds, output_size=(10, 10), read_func=read_func, ) def test_sub_pixel_read_empty_bounds(): """Test for sub pixel reading with empty bounds.""" bounds = (0, 0, 2, 2) image = np.ones((10, 10)) with pytest.raises(ValueError, match="Bounds have zero size after padding."): utils.image.sub_pixel_read( image, bounds=bounds, output_size=(2, 2), padding=-1, ) def test_fuzz_bounds2locsize(): """Fuzz test for bounds2size.""" random.seed(0) for _ in range(1000): size = (random.randint(-1000, 1000), random.randint(-1000, 1000)) location = (random.randint(-1000, 1000), random.randint(-1000, 1000)) bounds = (*location, *(sum(x) for x in zip(size, location))) assert utils.transforms.bounds2locsize(bounds)[1] == pytest.approx(size) def test_fuzz_bounds2locsize_lower(): """Fuzz test for bounds2size with origin lower.""" random.seed(0) for _ in range(1000): loc = (np.random.rand(2) - 0.5) * 1000 size = (np.random.rand(2) - 0.5) * 1000 bounds = np.tile(loc, 2) + [ 0, *size[::-1], 0, ] # L T R B _, s = utils.transforms.bounds2locsize(bounds, origin="lower") assert s == pytest.approx(size) def test_fuzz_roundtrip_bounds2size(): """Fuzz roundtrip bounds2locsize and locsize2bounds.""" random.seed(0) for _ in range(1000): loc = (np.random.rand(2) - 0.5) * 1000 size = (np.random.rand(2) - 0.5) * 1000 assert utils.transforms.bounds2locsize( utils.transforms.locsize2bounds(loc, size) ) def test_bounds2size_value_error(): """Test bounds to size ValueError.""" with pytest.raises(ValueError, match="Invalid origin"): utils.transforms.bounds2locsize((0, 0, 1, 1), origin="middle") def test_bounds2slices_invalid_stride(): """Test bounds2slices raises ValueError with invalid stride.""" bounds = (0, 0, 10, 10) with pytest.raises(ValueError, match="Invalid stride"): utils.transforms.bounds2slices(bounds, stride=(1, 1, 1)) def test_pad_bounds_sample_cases(): """Test sample inputs for pad_bounds.""" output = utils.transforms.pad_bounds([0] * 4, 1) assert np.array_equal(output, (-1, -1, 1, 1)) output = utils.transforms.pad_bounds((0, 0, 10, 10), (1, 2)) assert np.array_equal(output, (-1, -2, 11, 12)) def test_pad_bounds_invalid_inputs(): """Test invalid inputs for pad_bounds.""" with pytest.raises(ValueError, match="even"): utils.transforms.pad_bounds(bounds=(0, 0, 10), padding=1) with pytest.raises(ValueError, match="Invalid number of padding"): utils.transforms.pad_bounds(bounds=(0, 0, 10, 10), padding=(1, 1, 1)) # Normal case for control utils.transforms.pad_bounds(bounds=(0, 0, 10, 10), padding=1) def test_contrast_enhancer(): """Test contrast enhancement functionality.""" # input array to the contrast_enhancer function input_array = np.array( [ [[37, 244, 193], [106, 235, 128], [71, 140, 47]], [[103, 184, 72], [20, 188, 238], [126, 7, 0]], [[137, 195, 204], [32, 203, 170], [101, 77, 133]], ], dtype=np.uint8, ) # expected output of the contrast_enhancer result_array = np.array( [ [[35, 255, 203], [110, 248, 133], [72, 146, 46]], [[106, 193, 73], [17, 198, 251], [131, 3, 0]], [[143, 205, 215], [30, 214, 178], [104, 78, 139]], ], dtype=np.uint8, ) with pytest.raises(AssertionError): # Contrast_enhancer requires image input to be of dtype uint8 utils.misc.contrast_enhancer(np.float32(input_array), low_p=2, high_p=98) # Calculating the contrast enhanced version of input_array output_array = utils.misc.contrast_enhancer(input_array, low_p=2, high_p=98) # The out_put array should be equal to expected result_array assert np.all(result_array == output_array) def test_load_stain_matrix(tmp_path): """Test to load stain matrix.""" with pytest.raises(FileNotSupported): utils.misc.load_stain_matrix("/samplefile.xlsx") with pytest.raises(TypeError): # load_stain_matrix requires numpy array as input providing list here utils.misc.load_stain_matrix([1, 2, 3]) stain_matrix = np.array([[0.65, 0.70, 0.29], [0.07, 0.99, 0.11]]) pd.DataFrame(stain_matrix).to_csv(Path(tmp_path).joinpath("sm.csv"), index=False) out_stain_matrix = utils.misc.load_stain_matrix(Path(tmp_path).joinpath("sm.csv")) assert np.all(out_stain_matrix == stain_matrix) np.save(str(Path(tmp_path).joinpath("sm.npy")), stain_matrix) out_stain_matrix = utils.misc.load_stain_matrix(Path(tmp_path).joinpath("sm.npy")) assert np.all(out_stain_matrix == stain_matrix) def test_get_luminosity_tissue_mask(): """Test get luminosity tissue mask.""" with pytest.raises(ValueError, match="Empty tissue mask"): utils.misc.get_luminosity_tissue_mask(img=np.zeros((100, 100, 3)), threshold=0) def test_read_point_annotations( tmp_path, patch_extr_csv, patch_extr_csv_noheader, patch_extr_svs_csv, patch_extr_svs_header, patch_extr_npy, patch_extr_json, patch_extr_2col_json, ): """Test read point annotations reads csv, ndarray, npy and json correctly.""" labels = Path(patch_extr_csv) labels_table = pd.read_csv(labels) # Test csv read with header out_table = utils.misc.read_locations(labels) assert all(labels_table == out_table) assert out_table.shape[1] == 3 # Test csv read without header labels = Path(patch_extr_csv_noheader) out_table = utils.misc.read_locations(labels) assert all(labels_table == out_table) assert out_table.shape[1] == 3 labels = Path(patch_extr_svs_csv) out_table = utils.misc.read_locations(labels) assert out_table.shape[1] == 3 labels = Path(patch_extr_svs_header) out_table = utils.misc.read_locations(labels) assert out_table.shape[1] == 3 # Test npy read labels = Path(patch_extr_npy) out_table = utils.misc.read_locations(labels) assert all(labels_table == out_table) assert out_table.shape[1] == 3 # Test pd dataframe read out_table = utils.misc.read_locations(labels_table) assert all(labels_table == out_table) assert out_table.shape[1] == 3 labels_table_2 = labels_table.drop("class", axis=1) out_table = utils.misc.read_locations(labels_table_2) assert all(labels_table == out_table) assert out_table.shape[1] == 3 # Test json read labels = Path(patch_extr_json) out_table = utils.misc.read_locations(labels) assert all(labels_table == out_table) assert out_table.shape[1] == 3 # Test json read 2 columns labels = Path(patch_extr_2col_json) out_table = utils.misc.read_locations(labels) assert all(labels_table == out_table) assert out_table.shape[1] == 3 # Test numpy array out_table = utils.misc.read_locations(labels_table.to_numpy()) assert all(labels_table == out_table) assert out_table.shape[1] == 3 out_table = utils.misc.read_locations(labels_table.to_numpy()[:, 0:2]) assert all(labels_table == out_table) assert out_table.shape[1] == 3 # Test if input array does not have 2 or 3 columns with pytest.raises(ValueError, match="Numpy table should be of format"): _ = utils.misc.read_locations(labels_table.to_numpy()[:, 0:1]) # Test if input npy does not have 2 or 3 columns labels = tmp_path.joinpath("test_gt_3col.npy") with open(labels, "wb") as f: np.save(f, np.zeros((3, 4))) with pytest.raises(ValueError, match="Numpy table should be of format"): _ = utils.misc.read_locations(labels) # Test if input pd DataFrame does not have 2 or 3 columns with pytest.raises(ValueError, match="Input table must have 2 or 3 columns"): _ = utils.misc.read_locations(labels_table.drop(["y", "class"], axis=1)) labels = Path("./samplepatch_extraction.test") with pytest.raises(FileNotSupported): _ = utils.misc.read_locations(labels) with pytest.raises(TypeError): _ = utils.misc.read_locations(["a", "b", "c"]) def test_grab_files_from_dir(sample_visual_fields): """Test grab files from dir utils.misc.""" file_parent_dir = Path(__file__).parent input_path = file_parent_dir.joinpath("data") file_types = "*.tif, *.png, *.jpg" out = utils.misc.grab_files_from_dir( input_path=sample_visual_fields, file_types=file_types ) assert len(out) == 5 out = utils.misc.grab_files_from_dir( input_path=input_path.parent, file_types="test_utils*" ) assert len(out) == 1 assert str(Path(__file__)) == str(out[0]) out = utils.misc.grab_files_from_dir(input_path=input_path, file_types="*.py") assert len(out) == 0 def test_download_unzip_data(): """Test download and unzip data from utils.misc.""" url = "https://tiatoolbox.dcs.warwick.ac.uk/testdata/utils/test_directory.zip" save_dir_path = os.path.join(rcParam["TIATOOLBOX_HOME"], "tmp/") if os.path.exists(save_dir_path): shutil.rmtree(save_dir_path, ignore_errors=True) os.makedirs(save_dir_path) save_zip_path = os.path.join(save_dir_path, "test_directory.zip") misc.download_data(url, save_zip_path) misc.download_data(url, save_zip_path, overwrite=True) # do overwrite misc.unzip_data(save_zip_path, save_dir_path, del_zip=False) # not remove assert os.path.exists(save_zip_path) misc.unzip_data(save_zip_path, save_dir_path) extracted_path = os.path.join(save_dir_path, "test_directory") # to avoid hidden files in case of MAC-OS or Windows (?) extracted_dirs = [f for f in os.listdir(extracted_path) if not f.startswith(".")] extracted_dirs.sort() # ensure same ordering assert extracted_dirs == ["dir1", "dir2", "dir3"] shutil.rmtree(save_dir_path, ignore_errors=True) def test_download_data(): """Test download data from utils.misc.""" url = "https://tiatoolbox.dcs.warwick.ac.uk/testdata/utils/test_directory.zip" save_dir_path = os.path.join(rcParam["TIATOOLBOX_HOME"], "tmp/") if os.path.exists(save_dir_path): shutil.rmtree(save_dir_path, ignore_errors=True) save_zip_path = os.path.join(save_dir_path, "test_directory.zip") misc.download_data(url, save_zip_path, overwrite=True) # overwrite with open(save_zip_path, "rb") as handle: old_hash = hashlib.md5(handle.read()).hexdigest() # modify the content with open(save_zip_path, "wb") as fptr: fptr.write(b"dataXXX") # random data with open(save_zip_path, "rb") as handle: bad_hash = hashlib.md5(handle.read()).hexdigest() assert old_hash != bad_hash misc.download_data(url, save_zip_path, overwrite=True) # overwrite with open(save_zip_path, "rb") as handle: new_hash = hashlib.md5(handle.read()).hexdigest() assert new_hash == old_hash # Test not overwriting # Modify the content with open(save_zip_path, "wb") as handle: handle.write(b"dataXXX") # random data with open(save_zip_path, "rb") as handle: bad_hash = hashlib.md5(handle.read()).hexdigest() assert old_hash != bad_hash misc.download_data(url, save_zip_path, overwrite=False) # data already exists with open(save_zip_path, "rb") as handle: new_hash = hashlib.md5(handle.read()).hexdigest() assert new_hash == bad_hash shutil.rmtree(save_dir_path, ignore_errors=True) # remove data misc.download_data(url, save_zip_path) # to test skip download assert os.path.exists(save_zip_path) shutil.rmtree(save_dir_path, ignore_errors=True) # URL not valid # shouldn't use save_path if test runs correctly save_path = os.path.join(save_dir_path, "temp") with pytest.raises(ConnectionError): misc.download_data( "https://tiatoolbox.dcs.warwick.ac.uk/invalid-url", save_path ) def test_parse_cv2_interpolaton(): """Test parsing interpolation modes for cv2.""" cases = [str.upper, str.lower, str.capitalize] mode_strings = ["cubic", "linear", "area", "lanczos"] mode_enums = [cv2.INTER_CUBIC, cv2.INTER_LINEAR, cv2.INTER_AREA, cv2.INTER_LANCZOS4] for string, cv2_enum in zip(mode_strings, mode_enums): for case in cases: assert utils.misc.parse_cv2_interpolaton(case(string)) == cv2_enum assert utils.misc.parse_cv2_interpolaton(cv2_enum) == cv2_enum with pytest.raises(ValueError, match="interpolation"): assert utils.misc.parse_cv2_interpolaton(1337) def test_make_bounds_size_positive(): """Test make_bounds_size_positive outputs positive bounds.""" # Horizontal only bounds = (0, 0, -10, 10) pos_bounds, fliplr, flipud = utils.image.make_bounds_size_positive(bounds) _, size = utils.transforms.bounds2locsize(pos_bounds) assert len(size) == 2 assert size[0] > 0 assert size[1] > 0 assert fliplr is True assert flipud is False # Vertical only bounds = (0, 0, 10, -10) pos_bounds, fliplr, flipud = utils.image.make_bounds_size_positive(bounds) _, size = utils.transforms.bounds2locsize(pos_bounds) assert len(size) == 2 assert size[0] > 0 assert size[1] > 0 assert fliplr is False assert flipud is True # Both bounds = (0, 0, -10, -10) pos_bounds, fliplr, flipud = utils.image.make_bounds_size_positive(bounds) _, size = utils.transforms.bounds2locsize(pos_bounds) assert len(size) == 2 assert size[0] > 0 assert size[1] > 0 assert fliplr is True assert flipud is True def test_crop_and_pad_edges(): """Test crop and pad util function.""" slide_dimensions = (1024, 1024) def edge_mask(bounds: Tuple[int, int, int, int]) -> np.ndarray: """Produce a mask of regions outside of the slide dimensions.""" l, t, r, b = bounds slide_width, slide_height = slide_dimensions x, y = np.meshgrid(np.arange(l, r), np.arange(t, b), indexing="ij") under = np.logical_or(x < 0, y < 0).astype(np.int_) over = np.logical_or(x >= slide_width, y >= slide_height).astype(np.int_) return under, over loc = (-5, -5) size = (10, 10) bounds = utils.transforms.locsize2bounds(loc, size) under, over = edge_mask(bounds) region = -under + over region = np.sum(np.meshgrid(np.arange(10, 20), np.arange(10, 20)), axis=0) output = utils.image.crop_and_pad_edges( bounds=bounds, max_dimensions=slide_dimensions, region=region, pad_mode="constant", ) assert np.all(np.logical_or(output >= 10, output == 0)) assert output.shape == region.shape slide_width, slide_height = slide_dimensions loc = (slide_width - 5, slide_height - 5) bounds = utils.transforms.locsize2bounds(loc, size) under, over = edge_mask(bounds) region = np.sum(np.meshgrid(np.arange(10, 20), np.arange(10, 20)), axis=0) output = utils.image.crop_and_pad_edges( bounds=bounds, max_dimensions=slide_dimensions, region=region, pad_mode="constant", ) assert np.all(np.logical_or(output >= 10, output == 0)) assert output.shape == region.shape def test_crop_and_pad_edges_common_fail_cases(): """Test common failure cases for crop_and_pad_edges.""" bounds = (15, -5, 25, 5) slide_dimensions = (10, 10) region = np.sum(np.meshgrid(np.arange(10, 20), np.arange(10, 20)), axis=0) output = utils.image.crop_and_pad_edges( bounds=bounds, max_dimensions=slide_dimensions, region=region, pad_mode="constant", ) assert output.shape == (10, 10) def test_fuzz_crop_and_pad_edges_output_size(): """Fuzz test crop and pad util function output size.""" random.seed(0) region = np.sum(np.meshgrid(np.arange(10, 20), np.arange(10, 20)), axis=0) for _ in range(1000): slide_dimensions = (random.randint(0, 50), random.randint(0, 50)) loc = tuple(random.randint(-5, slide_dimensions[dim] + 5) for dim in range(2)) size = (10, 10) bounds = utils.transforms.locsize2bounds(loc, size) output = utils.image.crop_and_pad_edges( bounds=bounds, max_dimensions=slide_dimensions, region=region, pad_mode="constant", ) assert output.shape == size def test_fuzz_crop_and_pad_edges_output_size_no_padding(): """Fuzz test crop and pad util function output size with no padding.""" random.seed(0) for _ in range(1000): slide_dimensions = np.array([random.randint(5, 50) for _ in range(2)]) loc = np.array( [random.randint(-5, slide_dimensions[dim] + 5) for dim in range(2)] ) size = np.array([10, 10]) expected = np.maximum( size + np.minimum(loc, 0) - np.maximum(loc + size - slide_dimensions, 0), 0, ) expected = tuple(expected[::-1]) bounds = utils.transforms.locsize2bounds(loc, size) region = np.sum(np.meshgrid(np.arange(10, 20), np.arange(10, 20)), axis=0) output = utils.image.crop_and_pad_edges( bounds=bounds, max_dimensions=slide_dimensions, region=region, pad_mode=random.choice(["none", None]), ) assert output.shape == expected def test_crop_and_pad_edges_negative_max_dims(): """Test crop and pad edges for negative max dims.""" for max_dims in [(-1, 1), (1, -1), (-1, -1)]: with pytest.raises(ValueError, match="must be >= 0"): utils.image.crop_and_pad_edges( bounds=(0, 0, 1, 1), max_dimensions=max_dims, region=np.zeros((10, 10)), pad_mode="constant", ) # Zero dimensions utils.image.crop_and_pad_edges( bounds=(0, 0, 1, 1), max_dimensions=(0, 0), region=np.zeros((10, 10)), pad_mode="constant", ) def test_crop_and_pad_edges_non_positive_bounds_size(): """Test crop and pad edges for non positive bound size.""" with pytest.raises(ValueError, match="[bB]ounds.*> 0"): # Zero dimensions and negative bounds size utils.image.crop_and_pad_edges( bounds=(0, 0, -1, -1), max_dimensions=(0, 0), region=np.zeros((10, 10)), pad_mode="constant", ) with pytest.raises(ValueError, match="dimensions must be >= 0"): # Zero dimensions and negative bounds size utils.image.crop_and_pad_edges( bounds=(0, 0, 0, 0), max_dimensions=(-1, -1), region=np.zeros((10, 10)), pad_mode="constant", ) def test_normalize_padding_input_dims(): """Test that normalize padding error with input dimensions > 1.""" with pytest.raises(ValueError, match="1 dimensional"): utils.image.normalize_padding_size(((0, 0), (0, 0))) def test_select_device(): """Test if correct device is selected for models.""" device = misc.select_device(on_gpu=True) assert device == "cuda" device = misc.select_device(on_gpu=False) assert device == "cpu" def test_model_to(): """Test for placing model on device.""" import torch.nn as nn import torchvision.models as torch_models # Test on GPU # no GPU on Travis so this will crash if not utils.env_detection.has_gpu(): model = torch_models.resnet18() with pytest.raises(RuntimeError): _ = misc.model_to(on_gpu=True, model=model) # Test on CPU model = torch_models.resnet18() model = misc.model_to(on_gpu=False, model=model) assert isinstance(model, nn.Module) def test_save_as_json(tmp_path): """Test save data to json.""" # This should be broken up into separate tests! import json # dict with nested dict, list, and np.array key_dict = { "a1": {"name": "John", "age": 23, "sex": "male"}, "a2": {"name": "John", "age": 23, "sex": "male"}, } sample = { # noqa: ECE001 "a": [1, 1, 3, np.random.rand(2, 2, 2, 2), key_dict], "b": ["a1", "b1", "c1", {"a3": [1.0, 1, 3, np.random.rand(2, 2, 2, 2)]}], "c": { "a4": {"a5": {"a6": "a7", "c": [1, 1, 3, np.array([4, 5, 6.0])]}}, "b1": {}, "c1": [], True: [False, None], }, "d": [key_dict, np.random.rand(2, 2)], "e": np.random.rand(16, 2), } not_jsonable = {"x86": lambda x: x} not_jsonable.update(sample) # should fail because key is not of primitive type [str, int, float, bool] with pytest.raises(ValueError, match=r".*Key.*.*not jsonified.*"): misc.save_as_json( {frozenset(key_dict): sample}, tmp_path / "sample_json.json", exist_ok=True ) with pytest.raises(ValueError, match=r".*Value.*.*not jsonified.*"): misc.save_as_json(not_jsonable, tmp_path / "sample_json.json", exist_ok=True) with pytest.raises(ValueError, match=r".*Value.*.*not jsonified.*"): misc.save_as_json( list(not_jsonable.values()), tmp_path / "sample_json.json", exist_ok=True ) with pytest.raises(ValueError, match=r"Type.*`data`.*.*must.*dict, list.*"): misc.save_as_json( np.random.rand(2, 2), tmp_path / "sample_json.json", exist_ok=True ) # test complex nested dict print(sample) misc.save_as_json(sample, tmp_path / "sample_json.json", exist_ok=True) with open(tmp_path / "sample_json.json", "r") as fptr: read_sample = json.load(fptr) # test read because == is useless when value is mutable assert read_sample["c"]["a4"]["a5"]["a6"] == "a7" assert read_sample["c"]["a4"]["a5"]["c"][-1][-1] == 6 # noqa: ECE001 # Allow parent directories misc.save_as_json(sample, tmp_path / "foo" / "sample_json.json", parents=True) with open(tmp_path / "foo" / "sample_json.json", "r") as fptr: read_sample = json.load(fptr) # test read because == is useless when value is mutable assert read_sample["c"]["a4"]["a5"]["a6"] == "a7" assert read_sample["c"]["a4"]["a5"]["c"][-1][-1] == 6 # noqa: ECE001 # test complex list of data misc.save_as_json( list(sample.values()), tmp_path / "sample_json.json", exist_ok=True ) # test read because == is useless when value is mutable with open(tmp_path / "sample_json.json", "r") as fptr: read_sample = json.load(fptr) assert read_sample[-3]["a4"]["a5"]["a6"] == "a7" assert read_sample[-3]["a4"]["a5"]["c"][-1][-1] == 6 # noqa: ECE001 # test numpy generic misc.save_as_json( [np.int32(1), np.float32(2)], tmp_path / "sample_json.json", exist_ok=True ) misc.save_as_json( {"a": np.int32(1), "b": np.float32(2)}, tmp_path / "sample_json.json", exist_ok=True, ) def test_save_as_json_exists(tmp_path): """Test save data to json which already exists.""" dictionary = {"a": 1, "b": 2} misc.save_as_json(dictionary, tmp_path / "sample_json.json") with pytest.raises(FileExistsError, match="File already exists"): misc.save_as_json(dictionary, tmp_path / "sample_json.json") misc.save_as_json(dictionary, tmp_path / "sample_json.json", exist_ok=True) def test_save_as_json_parents(tmp_path): """Test save data to json where parents need to be created and parents is False.""" dictionary = {"a": 1, "b": 2} with pytest.raises(FileNotFoundError, match="No such file or directory"): misc.save_as_json(dictionary, tmp_path / "foo" / "sample_json.json") def test_save_yaml_exists(tmp_path): """Test save data to yaml which already exists.""" dictionary = {"a": 1, "b": 2} misc.save_yaml(dictionary, tmp_path / "sample_yaml.yaml") with pytest.raises(FileExistsError, match="File already exists"): misc.save_yaml(dictionary, tmp_path / "sample_yaml.yaml") misc.save_yaml(dictionary, tmp_path / "sample_yaml.yaml", exist_ok=True) def test_save_yaml_parents(tmp_path): """Test save data to yaml where parents need to be created.""" dictionary = {"a": 1, "b": 2} with pytest.raises(FileNotFoundError, match="No such file or directory"): misc.save_yaml(dictionary, tmp_path / "foo" / "sample_yaml.yaml") misc.save_yaml(dictionary, tmp_path / "foo" / "sample_yaml.yaml", parents=True) def test_imread_none_args(): img = np.zeros((10, 10, 3)) with pytest.raises(TypeError): utils.misc.imread(img) def test_detect_pixman(): """Test detection of the pixman version. Simply check it passes without exception or that it raises an EnvironmentError if the version is not detected. Any other exception should fail this test. """ try: versions, using = utils.env_detection.pixman_versions() assert isinstance(using, str) assert isinstance(versions, list) assert len(versions) > 0 except EnvironmentError: pass def test_detect_gpu(): """Test detection of GPU in the current runtime environment. Simply check it passes without exception. """ _ = utils.env_detection.has_gpu() def make_simple_dat(centroids=((0, 0), (100, 100))): polys = [cell_polygon(cent) for cent in centroids] return { f"ann{i}": { "box": poly.bounds, "centroid": [poly.centroid.x, poly.centroid.y], "contour": np.array(poly.exterior.coords).tolist(), "type": i, } for i, poly in enumerate(polys) } def test_from_dat(tmp_path): """Test generating an annotation store from a .dat file.""" data = make_simple_dat() joblib.dump(data, tmp_path / "test.dat") store = utils.misc.store_from_dat(tmp_path / "test.dat") assert len(store) == 2 def test_from_dat_type_dict(tmp_path): """Test generating an annotation store from a .dat file with a type dict.""" data = make_simple_dat() joblib.dump(data, tmp_path / "test.dat") store = utils.misc.store_from_dat( tmp_path / "test.dat", typedict={0: "cell0", 1: "cell1"} ) result = store.query(where="props['type'] == 'cell1'") assert len(result) == 1 def test_from_dat_transformed(tmp_path): """Test generating an annotation store from a .dat file with a transform.""" data = make_simple_dat() joblib.dump(data, tmp_path / "test.dat") store = utils.misc.store_from_dat( tmp_path / "test.dat", scale_factor=2, origin=(50, 50) ) result = store.query(where="props['type'] == 1") # check centroid is at 150,150 poly = next(iter(result.values())) assert np.rint(poly.geometry.centroid.x) == 150 assert np.rint(poly.geometry.centroid.y) == 150 def test_from_multi_head_dat(tmp_path): """Test generating an annotation store from a .dat file with multiple heads.""" head_a = make_simple_dat() head_b = make_simple_dat([(200, 200), (300, 300)]) data = { "A": head_a, "B": head_b, "resolution": 0.5, "other_meta_data": {"foo": "bar"}, } joblib.dump(data, tmp_path / "test.dat") store = utils.misc.store_from_dat(tmp_path / "test.dat") assert len(store) == 4 result = store.query(where="props['type'] == 'A: 1'") assert len(result) == 1 def test_invalid_poly(tmp_path, caplog): """Test that invalid polygons are dealt with correctly.""" coords = [(0, 0), (0, 2), (1, 1), (2, 2), (2, 0), (1, 1), (0, 0)] poly = Polygon(coords) data = make_simple_dat() data["invalid"] = { "box": poly.bounds, "centroid": [poly.centroid.x, poly.centroid.y], "contour": np.array(poly.exterior.coords).tolist(), "type": 2, } joblib.dump(data, tmp_path / "test.dat") store = utils.misc.store_from_dat(tmp_path / "test.dat") assert "Invalid geometry found, fix" in caplog.text result = store.query(where="props['type'] == 2") assert next(iter(result.values())).geometry.is_valid def test_from_multi_head_dat_type_dict(tmp_path): """Test generating a store from a .dat file with multiple heads, with typedict.""" head_a = make_simple_dat() head_b = make_simple_dat([(200, 200), (300, 300)]) data = {"A": head_a, "B": head_b} joblib.dump(data, tmp_path / "test.dat") store = utils.misc.store_from_dat( tmp_path / "test.dat", typedict={"A": {0: "cell0", 1: "cell1"}, "B": {0: "gland0", 1: "gland1"}}, ) assert len(store) == 4 result = store.query(where="props['type'] == 'gland1'") assert len(result) == 1 result = store.query(where=lambda x: x["type"][0:4] == "cell") assert len(result) == 2
49,055
32.280868
88
py
tiatoolbox
tiatoolbox-master/tests/models/test_dataset.py
"""Tests for predefined dataset within toolbox.""" import os import shutil import numpy as np import pytest from tiatoolbox import rcParam from tiatoolbox.models.dataset import DatasetInfoABC, KatherPatchDataset, PatchDataset from tiatoolbox.utils import env_detection as toolbox_env from tiatoolbox.utils.misc import download_data, unzip_data class Proto1(DatasetInfoABC): """Intentionally created to check error with new attribute a.""" def __init__(self): self.a = "a" class Proto2(DatasetInfoABC): """Intentionally created to check error with attribute inputs.""" def __init__(self): self.inputs = "a" class Proto3(DatasetInfoABC): """Intentionally created to check error with attribute inputs and labels.""" def __init__(self): self.inputs = "a" self.labels = "a" class Proto4(DatasetInfoABC): """Intentionally created to check error with attribute inputs and label names.""" def __init__(self): self.inputs = "a" self.label_names = "a" def test_dataset_abc(): """Test for ABC.""" # test defining a subclass of dataset info but not defining # enforcing attributes - should crash with pytest.raises(TypeError): Proto1() # skipcq with pytest.raises(TypeError): Proto2() # skipcq with pytest.raises(TypeError): Proto3() # skipcq with pytest.raises(TypeError): Proto4() # skipcq @pytest.mark.skipif(toolbox_env.running_on_ci(), reason="Local test on local machine.") def test_kather_dataset_default(tmp_path): """Test for kather patch dataset with default parameters.""" # test kather with default init _ = KatherPatchDataset() # kather with default data path skip download _ = KatherPatchDataset() # remove generated data shutil.rmtree(rcParam["TIATOOLBOX_HOME"]) def test_kather_nonexisting_dir(): """pytest for not exist dir.""" with pytest.raises( ValueError, match=r".*not exist.*", ): _ = KatherPatchDataset(save_dir_path="non-existing-path") def test_kather_dataset(tmp_path): """Test for kather patch dataset.""" save_dir_path = tmp_path # save to temporary location # remove previously generated data if os.path.exists(save_dir_path): shutil.rmtree(save_dir_path, ignore_errors=True) url = ( "https://tiatoolbox.dcs.warwick.ac.uk/datasets" "/kather100k-train-nonorm-subset-90.zip" ) save_zip_path = os.path.join(save_dir_path, "Kather.zip") download_data(url, save_zip_path) unzip_data(save_zip_path, save_dir_path) extracted_dir = os.path.join(save_dir_path, "NCT-CRC-HE-100K-NONORM/") dataset = KatherPatchDataset(save_dir_path=extracted_dir) assert dataset.inputs is not None assert dataset.labels is not None assert dataset.label_names is not None assert len(dataset.inputs) == len(dataset.labels) # to actually get the image, we feed it to PatchDataset actual_ds = PatchDataset(dataset.inputs, dataset.labels) sample_patch = actual_ds[89] assert isinstance(sample_patch["image"], np.ndarray) assert sample_patch["label"] is not None # remove generated data shutil.rmtree(save_dir_path, ignore_errors=True)
3,272
28.754545
87
py
tiatoolbox
tiatoolbox-master/tests/models/test_arch_nuclick.py
"""Unit test package for NuClick.""" import pathlib import numpy as np import torch from tiatoolbox.models import NuClick from tiatoolbox.models.architecture import fetch_pretrained_weights from tiatoolbox.utils.misc import imread ON_GPU = False # Test pretrained Model ============================= def test_functional_nuclick(remote_sample, tmp_path, caplog): """Tests for NuClick.""" # convert to pathlib Path to prevent wsireader complaint tile_path = pathlib.Path(remote_sample("patch-extraction-vf")) img = imread(tile_path) _pretrained_path = f"{tmp_path}/weights.pth" fetch_pretrained_weights("nuclick_original-pannuke", _pretrained_path) # test creation _ = NuClick(num_input_channels=5, num_output_channels=1) # test inference # create image patch, inclusion and exclusion maps patch = img[63:191, 750:878, :] inclusion_map = np.zeros((128, 128)) inclusion_map[64, 64] = 1 exclusion_map = np.zeros((128, 128)) exclusion_map[68, 82] = 1 exclusion_map[72, 102] = 1 exclusion_map[52, 48] = 1 patch = np.float32(patch) / 255.0 patch = np.moveaxis(patch, -1, 0) batch = np.concatenate( (patch, inclusion_map[np.newaxis, ...], exclusion_map[np.newaxis, ...]), axis=0 ) batch = torch.from_numpy(batch[np.newaxis, ...]) model = NuClick(num_input_channels=5, num_output_channels=1) pretrained = torch.load(_pretrained_path, map_location="cpu") model.load_state_dict(pretrained) output = model.infer_batch(model, batch, on_gpu=ON_GPU) postproc_masks = model.postproc( output, do_reconstruction=True, nuc_points=inclusion_map[np.newaxis, ...] ) gt_path = pathlib.Path(remote_sample("nuclick-output")) gt_mask = np.load(gt_path) assert ( np.count_nonzero(postproc_masks * gt_mask) / np.count_nonzero(gt_mask) > 0.999 ) # test post-processing without reconstruction _ = model.postproc(output) # test failed reconstruction in post-processing inclusion_map = np.zeros((128, 128)) inclusion_map[0, 0] = 1 _ = model.postproc( output, do_reconstruction=True, nuc_points=inclusion_map[np.newaxis, ...] ) assert "Nuclei reconstruction was not done" in caplog.text
2,264
30.027397
87
py
tiatoolbox
tiatoolbox-master/tests/models/test_arch_micronet.py
"""Unit test package for MicroNet.""" import pathlib import numpy as np import pytest import torch from tiatoolbox import utils from tiatoolbox.models import MicroNet from tiatoolbox.models.architecture import fetch_pretrained_weights from tiatoolbox.models.engine.semantic_segmentor import SemanticSegmentor from tiatoolbox.utils import env_detection as toolbox_env from tiatoolbox.wsicore.wsireader import WSIReader def test_functionality(remote_sample, tmp_path): """Functionality test.""" tmp_path = str(tmp_path) sample_wsi = str(remote_sample("wsi1_2k_2k_svs")) reader = WSIReader.open(sample_wsi) # * test fast mode (architecture used in PanNuke paper) patch = reader.read_bounds( (0, 0, 252, 252), resolution=0.25, units="mpp", coord_space="resolution" ) model = MicroNet() patch = model.preproc(patch) batch = torch.from_numpy(patch)[None] fetch_pretrained_weights("micronet-consep", f"{tmp_path}/weights.pth") map_location = utils.misc.select_device(utils.env_detection.has_gpu()) pretrained = torch.load(f"{tmp_path}/weights.pth", map_location=map_location) model.load_state_dict(pretrained) output = model.infer_batch(model, batch, on_gpu=False) output, _ = model.postproc(output[0]) assert np.max(np.unique(output)) == 46 def test_value_error(): """Test to generate value error is num_output_channels < 2.""" with pytest.raises(ValueError, match="Number of classes should be >=2"): _ = MicroNet(num_output_channels=1) @pytest.mark.skipif( toolbox_env.running_on_ci() or not toolbox_env.has_gpu(), reason="Local test on machine with GPU.", ) def test_micronet_output(remote_sample, tmp_path): """Tests the output of MicroNet.""" svs_1_small = pathlib.Path(remote_sample("svs-1-small")) micronet_output = pathlib.Path(remote_sample("micronet-output")) pretrained_model = "micronet-consep" batch_size = 5 num_loader_workers = 0 num_postproc_workers = 0 predictor = SemanticSegmentor( pretrained_model=pretrained_model, batch_size=batch_size, num_loader_workers=num_loader_workers, num_postproc_workers=num_postproc_workers, ) output = predictor.predict( imgs=[ svs_1_small, ], save_dir=tmp_path / "output", ) output = np.load(output[0][1] + ".raw.0.npy") output_on_server = np.load(str(micronet_output)) output_on_server = np.round(output_on_server, decimals=3) new_output = np.round(output[500:1000, 1000:1500, :], decimals=3) diff = new_output - output_on_server assert diff.mean() < 1e-5
2,651
32.56962
81
py
tiatoolbox
tiatoolbox-master/tests/models/test_patch_predictor.py
"""Tests for Patch Predictor.""" import copy import os import pathlib import shutil import cv2 import numpy as np import pytest import torch from click.testing import CliRunner from tiatoolbox import cli, rcParam from tiatoolbox.models.architecture.vanilla import CNNModel from tiatoolbox.models.dataset import ( PatchDataset, PatchDatasetABC, WSIPatchDataset, predefined_preproc_func, ) from tiatoolbox.models.engine.patch_predictor import ( IOPatchPredictorConfig, PatchPredictor, ) from tiatoolbox.utils import env_detection as toolbox_env from tiatoolbox.utils.misc import download_data, imread, imwrite from tiatoolbox.wsicore.wsireader import WSIReader ON_GPU = toolbox_env.has_gpu() def _rm_dir(path): """Helper func to remove directory.""" if os.path.exists(path): shutil.rmtree(path, ignore_errors=True) # ------------------------------------------------------------------------------------- # Dataloader # ------------------------------------------------------------------------------------- def test_patch_dataset_path_imgs(sample_patch1, sample_patch2): """Test for patch dataset with a list of file paths as input.""" size = (224, 224, 3) dataset = PatchDataset([pathlib.Path(sample_patch1), pathlib.Path(sample_patch2)]) for _, sample_data in enumerate(dataset): sampled_img_shape = sample_data["image"].shape assert sampled_img_shape[0] == size[0] assert sampled_img_shape[1] == size[1] assert sampled_img_shape[2] == size[2] def test_patch_dataset_list_imgs(tmp_path): """Test for patch dataset with a list of images as input.""" save_dir_path = tmp_path size = (5, 5, 3) img = np.random.randint(0, 255, size=size) list_imgs = [img, img, img] dataset = PatchDataset(list_imgs) dataset.preproc_func = lambda x: x for _, sample_data in enumerate(dataset): sampled_img_shape = sample_data["image"].shape assert sampled_img_shape[0] == size[0] assert sampled_img_shape[1] == size[1] assert sampled_img_shape[2] == size[2] # test for changing to another preproc dataset.preproc_func = lambda x: x - 10 item = dataset[0] assert np.sum(item["image"] - (list_imgs[0] - 10)) == 0 # * test for loading npy # remove previously generated data if os.path.exists(save_dir_path): shutil.rmtree(save_dir_path, ignore_errors=True) os.makedirs(save_dir_path) np.save( os.path.join(save_dir_path, "sample2.npy"), np.random.randint(0, 255, (4, 4, 3)) ) imgs = [ os.path.join(save_dir_path, "sample2.npy"), ] _ = PatchDataset(imgs) assert imgs[0] is not None # test for path object imgs = [ pathlib.Path(os.path.join(save_dir_path, "sample2.npy")), ] _ = PatchDataset(imgs) _rm_dir(save_dir_path) def test_patch_datasetarray_imgs(): """Test for patch dataset with a numpy array of a list of images.""" size = (5, 5, 3) img = np.random.randint(0, 255, size=size) list_imgs = [img, img, img] labels = [1, 2, 3] array_imgs = np.array(list_imgs) # test different setter for label dataset = PatchDataset(array_imgs, labels=labels) an_item = dataset[2] assert an_item["label"] == 3 dataset = PatchDataset(array_imgs, labels=None) an_item = dataset[2] assert "label" not in an_item dataset = PatchDataset(array_imgs) for _, sample_data in enumerate(dataset): sampled_img_shape = sample_data["image"].shape assert sampled_img_shape[0] == size[0] assert sampled_img_shape[1] == size[1] assert sampled_img_shape[2] == size[2] def test_patch_dataset_crash(tmp_path): """Test to make sure patch dataset crashes with incorrect input.""" # all below examples below should fail when input to PatchDataset save_dir_path = tmp_path # not supported input type imgs = {"a": np.random.randint(0, 255, (4, 4, 4))} with pytest.raises( ValueError, match=r".*Input must be either a list/array of images.*" ): _ = PatchDataset(imgs) # ndarray of mixed dtype imgs = np.array( [np.random.randint(0, 255, (4, 5, 3)), "Should crash"], dtype=object ) with pytest.raises(ValueError, match="Provided input array is non-numerical."): _ = PatchDataset(imgs) # ndarray(s) of NHW images imgs = np.random.randint(0, 255, (4, 4, 4)) with pytest.raises(ValueError, match=r".*array of the form HWC*"): _ = PatchDataset(imgs) # list of ndarray(s) with different sizes imgs = [ np.random.randint(0, 255, (4, 4, 3)), np.random.randint(0, 255, (4, 5, 3)), ] with pytest.raises(ValueError, match="Images must have the same dimensions."): _ = PatchDataset(imgs) # list of ndarray(s) with HW and HWC mixed up imgs = [ np.random.randint(0, 255, (4, 4, 3)), np.random.randint(0, 255, (4, 4)), ] with pytest.raises( ValueError, match="Each sample must be an array of the form HWC." ): _ = PatchDataset(imgs) # list of mixed dtype imgs = [np.random.randint(0, 255, (4, 4, 3)), "you_should_crash_here", 123, 456] with pytest.raises( ValueError, match="Input must be either a list/array of images or a list of " "valid image paths.", ): _ = PatchDataset(imgs) # list of mixed dtype imgs = ["you_should_crash_here", 123, 456] with pytest.raises( ValueError, match="Input must be either a list/array of images or a list of " "valid image paths.", ): _ = PatchDataset(imgs) # list not exist paths with pytest.raises( ValueError, match=r".*valid image paths.*", ): _ = PatchDataset(["img.npy"]) # ** test different extension parser # save dummy data to temporary location # remove prev generated data _rm_dir(save_dir_path) os.makedirs(save_dir_path) torch.save({"a": "a"}, os.path.join(save_dir_path, "sample1.tar")) np.save( os.path.join(save_dir_path, "sample2.npy"), np.random.randint(0, 255, (4, 4, 3)) ) imgs = [ os.path.join(save_dir_path, "sample1.tar"), os.path.join(save_dir_path, "sample2.npy"), ] with pytest.raises( ValueError, match="Cannot load image data from", ): _ = PatchDataset(imgs) _rm_dir(rcParam["TIATOOLBOX_HOME"]) # preproc func for not defined dataset with pytest.raises( ValueError, match=r".* preprocessing .* does not exist.", ): predefined_preproc_func("secret-dataset") def test_wsi_patch_dataset(sample_wsi_dict, tmp_path): """A test for creation and bare output.""" # convert to pathlib Path to prevent wsireader complaint mini_wsi_svs = pathlib.Path(sample_wsi_dict["wsi2_4k_4k_svs"]) mini_wsi_jpg = pathlib.Path(sample_wsi_dict["wsi2_4k_4k_jpg"]) mini_wsi_msk = pathlib.Path(sample_wsi_dict["wsi2_4k_4k_msk"]) def reuse_init(img_path=mini_wsi_svs, **kwargs): """Testing function.""" return WSIPatchDataset(img_path=img_path, **kwargs) def reuse_init_wsi(**kwargs): """Testing function.""" return reuse_init(mode="wsi", **kwargs) # test for ABC validate # intentionally created to check error # skipcq class Proto(PatchDatasetABC): def __init__(self): super().__init__() self.inputs = "CRASH" self._check_input_integrity("wsi") # skipcq def __getitem__(self, idx): pass with pytest.raises( ValueError, match=r".*`inputs` should be a list of patch coordinates.*" ): Proto() # skipcq # invalid path input with pytest.raises(ValueError, match=r".*`img_path` must be a valid file path.*"): WSIPatchDataset( img_path="aaaa", mode="wsi", patch_input_shape=[512, 512], stride_shape=[256, 256], auto_get_mask=False, ) # invalid mask path input with pytest.raises(ValueError, match=r".*`mask_path` must be a valid file path.*"): WSIPatchDataset( img_path=mini_wsi_svs, mask_path="aaaa", mode="wsi", patch_input_shape=[512, 512], stride_shape=[256, 256], resolution=1.0, units="mpp", auto_get_mask=False, ) # invalid mode with pytest.raises(ValueError, match="`X` is not supported."): reuse_init(mode="X") # invalid patch with pytest.raises(ValueError, match="Invalid `patch_input_shape` value None."): reuse_init() with pytest.raises( ValueError, match=r"Invalid `patch_input_shape` value \[512 512 512\]." ): reuse_init_wsi(patch_input_shape=[512, 512, 512]) with pytest.raises( ValueError, match=r"Invalid `patch_input_shape` value \['512' 'a'\]." ): reuse_init_wsi(patch_input_shape=[512, "a"]) with pytest.raises(ValueError, match="Invalid `stride_shape` value None."): reuse_init_wsi(patch_input_shape=512) # invalid stride with pytest.raises( ValueError, match=r"Invalid `stride_shape` value \['512' 'a'\]." ): reuse_init_wsi(patch_input_shape=[512, 512], stride_shape=[512, "a"]) with pytest.raises( ValueError, match=r"Invalid `stride_shape` value \[512 512 512\]." ): reuse_init_wsi(patch_input_shape=[512, 512], stride_shape=[512, 512, 512]) # negative with pytest.raises( ValueError, match=r"Invalid `patch_input_shape` value \[ 512 -512\]." ): reuse_init_wsi(patch_input_shape=[512, -512], stride_shape=[512, 512]) with pytest.raises( ValueError, match=r"Invalid `stride_shape` value \[ 512 -512\]." ): reuse_init_wsi(patch_input_shape=[512, 512], stride_shape=[512, -512]) # * for wsi # dummy test for analysing the output # stride and patch size should be as expected patch_size = [512, 512] stride_size = [256, 256] ds = reuse_init_wsi( patch_input_shape=patch_size, stride_shape=stride_size, resolution=1.0, units="mpp", auto_get_mask=False, ) reader = WSIReader.open(mini_wsi_svs) # tiling top to bottom, left to right ds_roi = ds[2]["image"] step_idx = 2 # manually calibrate start = (step_idx * stride_size[1], 0) end = (start[0] + patch_size[0], start[1] + patch_size[1]) rd_roi = reader.read_bounds( start + end, resolution=1.0, units="mpp", coord_space="resolution" ) correlation = np.corrcoef( cv2.cvtColor(ds_roi, cv2.COLOR_RGB2GRAY).flatten(), cv2.cvtColor(rd_roi, cv2.COLOR_RGB2GRAY).flatten(), ) assert ds_roi.shape[0] == rd_roi.shape[0] assert ds_roi.shape[1] == rd_roi.shape[1] assert np.min(correlation) > 0.9, correlation # test creation with auto mask gen and input mask ds = reuse_init_wsi( patch_input_shape=patch_size, stride_shape=stride_size, resolution=1.0, units="mpp", auto_get_mask=True, ) assert len(ds) > 0 ds = WSIPatchDataset( img_path=mini_wsi_svs, mask_path=mini_wsi_msk, mode="wsi", patch_input_shape=[512, 512], stride_shape=[256, 256], auto_get_mask=False, resolution=1.0, units="mpp", ) negative_mask = imread(mini_wsi_msk) negative_mask = np.zeros_like(negative_mask) negative_mask_path = tmp_path / "negative_mask.png" imwrite(negative_mask_path, negative_mask) with pytest.raises(ValueError, match="No patch coordinates remain after filtering"): ds = WSIPatchDataset( img_path=mini_wsi_svs, mask_path=negative_mask_path, mode="wsi", patch_input_shape=[512, 512], stride_shape=[256, 256], auto_get_mask=False, resolution=1.0, units="mpp", ) # * for tile reader = WSIReader.open(mini_wsi_jpg) tile_ds = WSIPatchDataset( img_path=mini_wsi_jpg, mode="tile", patch_input_shape=patch_size, stride_shape=stride_size, auto_get_mask=False, ) step_idx = 3 # manually calibrate start = (step_idx * stride_size[1], 0) end = (start[0] + patch_size[0], start[1] + patch_size[1]) roi2 = reader.read_bounds( start + end, resolution=1.0, units="baseline", coord_space="resolution" ) roi1 = tile_ds[3]["image"] # match with step_index correlation = np.corrcoef( cv2.cvtColor(roi1, cv2.COLOR_RGB2GRAY).flatten(), cv2.cvtColor(roi2, cv2.COLOR_RGB2GRAY).flatten(), ) assert roi1.shape[0] == roi2.shape[0] assert roi1.shape[1] == roi2.shape[1] assert np.min(correlation) > 0.9, correlation def test_patch_dataset_abc(): """Test for ABC methods. Test missing definition for abstract intentionally created to check error. """ # skipcq class Proto(PatchDatasetABC): # skipcq def __init__(self): super().__init__() # crash due to undefined __getitem__ with pytest.raises(TypeError): Proto() # skipcq # skipcq class Proto(PatchDatasetABC): # skipcq def __init__(self): super().__init__() # skipcq def __getitem__(self, idx): pass ds = Proto() # skipcq # test setter and getter assert ds.preproc_func(1) == 1 ds.preproc_func = lambda x: x - 1 # skipcq: PYL-W0201 assert ds.preproc_func(1) == 0 assert ds.preproc(1) == 1, "Must be unchanged!" ds.preproc_func = None # skipcq: PYL-W0201 assert ds.preproc_func(2) == 2 # test assign uncallable to preproc_func/postproc_func with pytest.raises(ValueError, match=r".*callable*"): ds.preproc_func = 1 # skipcq: PYL-W0201 # ------------------------------------------------------------------------------------- # Dataloader # ------------------------------------------------------------------------------------- def test_io_patch_predictor_config(): """Test for IOConfig.""" # test for creating cfg = IOPatchPredictorConfig( patch_input_shape=[224, 224], stride_shape=[224, 224], input_resolutions=[{"resolution": 0.5, "units": "mpp"}], # test adding random kwarg and they should be accessible as kwargs crop_from_source=True, ) assert cfg.crop_from_source # ------------------------------------------------------------------------------------- # Engine # ------------------------------------------------------------------------------------- def test_predictor_crash(): """Test for crash when making predictor.""" # without providing any model with pytest.raises(ValueError, match=r"Must provide.*"): PatchPredictor() # provide wrong unknown pretrained model with pytest.raises(ValueError, match=r"Pretrained .* does not exist"): PatchPredictor(pretrained_model="secret_model-kather100k") # provide wrong model of unknown type, deprecated later with type hint with pytest.raises(ValueError, match=r".*must be a string.*"): PatchPredictor(pretrained_model=123) # test predict crash predictor = PatchPredictor(pretrained_model="resnet18-kather100k", batch_size=32) with pytest.raises(ValueError, match=r".*not a valid mode.*"): predictor.predict("aaa", mode="random") # remove previously generated data if os.path.exists("output"): _rm_dir("output") with pytest.raises(ValueError, match=r".*must be a list of file paths.*"): predictor.predict("aaa", mode="wsi") # remove previously generated data _rm_dir("output") with pytest.raises(ValueError, match=r".*masks.*!=.*imgs.*"): predictor.predict([1, 2, 3], masks=[1, 2], mode="wsi") with pytest.raises(ValueError, match=r".*labels.*!=.*imgs.*"): predictor.predict([1, 2, 3], labels=[1, 2], mode="patch") # remove previously generated data _rm_dir("output") def test_io_config_delegation(remote_sample, tmp_path): """Tests for delegating args to io config.""" mini_wsi_svs = pathlib.Path(remote_sample("wsi2_4k_4k_svs")) # test not providing config / full input info for not pretrained models model = CNNModel("resnet50") predictor = PatchPredictor(model=model) with pytest.raises(ValueError, match=r".*Must provide.*`ioconfig`.*"): predictor.predict([mini_wsi_svs], mode="wsi", save_dir=f"{tmp_path}/dump") _rm_dir(f"{tmp_path}/dump") kwargs = { "patch_input_shape": [512, 512], "resolution": 1.75, "units": "mpp", } for key, _ in kwargs.items(): _kwargs = copy.deepcopy(kwargs) _kwargs.pop(key) with pytest.raises(ValueError, match=r".*Must provide.*`ioconfig`.*"): predictor.predict( [mini_wsi_svs], mode="wsi", save_dir=f"{tmp_path}/dump", on_gpu=ON_GPU, **_kwargs, ) _rm_dir(f"{tmp_path}/dump") # test providing config / full input info for not pretrained models ioconfig = IOPatchPredictorConfig( patch_input_shape=[512, 512], stride_shape=[256, 256], input_resolutions=[{"resolution": 1.35, "units": "mpp"}], ) predictor.predict( [mini_wsi_svs], ioconfig=ioconfig, mode="wsi", save_dir=f"{tmp_path}/dump", on_gpu=ON_GPU, ) _rm_dir(f"{tmp_path}/dump") predictor.predict( [mini_wsi_svs], mode="wsi", save_dir=f"{tmp_path}/dump", on_gpu=ON_GPU, **kwargs ) _rm_dir(f"{tmp_path}/dump") # test overwriting pretrained ioconfig predictor = PatchPredictor(pretrained_model="resnet18-kather100k", batch_size=1) predictor.predict( [mini_wsi_svs], patch_input_shape=[300, 300], mode="wsi", on_gpu=ON_GPU, save_dir=f"{tmp_path}/dump", ) assert predictor._ioconfig.patch_input_shape == [300, 300] _rm_dir(f"{tmp_path}/dump") predictor.predict( [mini_wsi_svs], stride_shape=[300, 300], mode="wsi", on_gpu=ON_GPU, save_dir=f"{tmp_path}/dump", ) assert predictor._ioconfig.stride_shape == [300, 300] _rm_dir(f"{tmp_path}/dump") predictor.predict( [mini_wsi_svs], resolution=1.99, mode="wsi", on_gpu=ON_GPU, save_dir=f"{tmp_path}/dump", ) assert predictor._ioconfig.input_resolutions[0]["resolution"] == 1.99 _rm_dir(f"{tmp_path}/dump") predictor.predict( [mini_wsi_svs], units="baseline", mode="wsi", on_gpu=ON_GPU, save_dir=f"{tmp_path}/dump", ) assert predictor._ioconfig.input_resolutions[0]["units"] == "baseline" _rm_dir(f"{tmp_path}/dump") predictor = PatchPredictor(pretrained_model="resnet18-kather100k") predictor.predict( [mini_wsi_svs], mode="wsi", merge_predictions=True, save_dir=f"{tmp_path}/dump", on_gpu=ON_GPU, ) _rm_dir(f"{tmp_path}/dump") def test_patch_predictor_api(sample_patch1, sample_patch2, tmp_path): """Helper function to get the model output using API 1.""" save_dir_path = tmp_path # convert to pathlib Path to prevent reader complaint inputs = [pathlib.Path(sample_patch1), pathlib.Path(sample_patch2)] predictor = PatchPredictor(pretrained_model="resnet18-kather100k", batch_size=1) # don't run test on GPU output = predictor.predict( inputs, on_gpu=ON_GPU, ) assert sorted(output.keys()) == ["predictions"] assert len(output["predictions"]) == 2 output = predictor.predict( inputs, labels=[1, "a"], return_labels=True, on_gpu=ON_GPU, ) assert sorted(output.keys()) == sorted(["labels", "predictions"]) assert len(output["predictions"]) == len(output["labels"]) assert output["labels"] == [1, "a"] output = predictor.predict( inputs, return_probabilities=True, on_gpu=ON_GPU, ) assert sorted(output.keys()) == sorted(["predictions", "probabilities"]) assert len(output["predictions"]) == len(output["probabilities"]) output = predictor.predict( inputs, return_probabilities=True, labels=[1, "a"], return_labels=True, on_gpu=ON_GPU, ) assert sorted(output.keys()) == sorted(["labels", "predictions", "probabilities"]) assert len(output["predictions"]) == len(output["labels"]) assert len(output["predictions"]) == len(output["probabilities"]) # test saving output, should have no effect output = predictor.predict( inputs, on_gpu=ON_GPU, save_dir="special_dir_not_exist", ) assert not os.path.isdir("special_dir_not_exist") # test loading user weight pretrained_weights_url = ( "https://tiatoolbox.dcs.warwick.ac.uk/models/pc/resnet18-kather100k.pth" ) # remove prev generated data _rm_dir(save_dir_path) os.makedirs(save_dir_path) pretrained_weights = os.path.join( rcParam["TIATOOLBOX_HOME"], "tmp_pretrained_weigths", "resnet18-kather100k.pth", ) download_data(pretrained_weights_url, pretrained_weights) predictor = PatchPredictor( pretrained_model="resnet18-kather100k", pretrained_weights=pretrained_weights, batch_size=1, ) # --- test different using user model model = CNNModel(backbone="resnet18", num_classes=9) # test prediction predictor = PatchPredictor(model=model, batch_size=1, verbose=False) output = predictor.predict( inputs, return_probabilities=True, labels=[1, "a"], return_labels=True, on_gpu=ON_GPU, ) assert sorted(output.keys()) == sorted(["labels", "predictions", "probabilities"]) assert len(output["predictions"]) == len(output["labels"]) assert len(output["predictions"]) == len(output["probabilities"]) def test_wsi_predictor_api(sample_wsi_dict, tmp_path): """Test normal run of wsi predictor.""" save_dir_path = tmp_path # convert to pathlib Path to prevent wsireader complaint mini_wsi_svs = pathlib.Path(sample_wsi_dict["wsi2_4k_4k_svs"]) mini_wsi_jpg = pathlib.Path(sample_wsi_dict["wsi2_4k_4k_jpg"]) mini_wsi_msk = pathlib.Path(sample_wsi_dict["wsi2_4k_4k_msk"]) patch_size = np.array([224, 224]) predictor = PatchPredictor(pretrained_model="resnet18-kather100k", batch_size=32) # wrapper to make this more clean kwargs = { "return_probabilities": True, "return_labels": True, "on_gpu": ON_GPU, "patch_input_shape": patch_size, "stride_shape": patch_size, "resolution": 1.0, "units": "baseline", } # ! add this test back once the read at `baseline` is fixed # sanity check, both output should be the same with same resolution read args wsi_output = predictor.predict( [mini_wsi_svs], masks=[mini_wsi_msk], mode="wsi", **kwargs, ) tile_output = predictor.predict( [mini_wsi_jpg], masks=[mini_wsi_msk], mode="tile", **kwargs, ) wpred = np.array(wsi_output[0]["predictions"]) tpred = np.array(tile_output[0]["predictions"]) diff = tpred == wpred accuracy = np.sum(diff) / np.size(wpred) assert accuracy > 0.9, np.nonzero(~diff) # remove previously generated data save_dir = f"{save_dir_path}/model_wsi_output" _rm_dir(save_dir) kwargs = { "return_probabilities": True, "return_labels": True, "on_gpu": ON_GPU, "patch_input_shape": patch_size, "stride_shape": patch_size, "resolution": 0.5, "save_dir": save_dir, "merge_predictions": True, # to test the api coverage "units": "mpp", } _kwargs = copy.deepcopy(kwargs) _kwargs["merge_predictions"] = False # test reading of multiple whole-slide images output = predictor.predict( [mini_wsi_svs, mini_wsi_svs], masks=[mini_wsi_msk, mini_wsi_msk], mode="wsi", **_kwargs, ) for output_info in output.values(): assert os.path.exists(output_info["raw"]) assert "merged" not in output_info _rm_dir(_kwargs["save_dir"]) # coverage test _kwargs = copy.deepcopy(kwargs) _kwargs["merge_predictions"] = True # test reading of multiple whole-slide images predictor.predict( [mini_wsi_svs, mini_wsi_svs], masks=[mini_wsi_msk, mini_wsi_msk], mode="wsi", **_kwargs, ) _kwargs = copy.deepcopy(kwargs) with pytest.raises(FileExistsError): predictor.predict( [mini_wsi_svs, mini_wsi_svs], masks=[mini_wsi_msk, mini_wsi_msk], mode="wsi", **_kwargs, ) # remove previously generated data _rm_dir(_kwargs["save_dir"]) _rm_dir("output") # test reading of multiple whole-slide images _kwargs = copy.deepcopy(kwargs) _kwargs["save_dir"] = None # default coverage _kwargs["return_probabilities"] = False output = predictor.predict( [mini_wsi_svs, mini_wsi_svs], masks=[mini_wsi_msk, mini_wsi_msk], mode="wsi", **_kwargs, ) assert os.path.exists("output") for output_info in output.values(): assert os.path.exists(output_info["raw"]) assert "merged" in output_info assert os.path.exists(output_info["merged"]) # remove previously generated data _rm_dir("output") def test_wsi_predictor_merge_predictions(sample_wsi_dict): """Test normal run of wsi predictor with merge predictions option.""" # convert to pathlib Path to prevent reader complaint mini_wsi_svs = pathlib.Path(sample_wsi_dict["wsi2_4k_4k_svs"]) mini_wsi_jpg = pathlib.Path(sample_wsi_dict["wsi2_4k_4k_jpg"]) mini_wsi_msk = pathlib.Path(sample_wsi_dict["wsi2_4k_4k_msk"]) # blind test # pseudo output dict from model with 2 patches output = { "resolution": 1.0, "units": "baseline", "probabilities": [[0.45, 0.55], [0.90, 0.10]], "predictions": [1, 0], "coordinates": [[0, 0, 2, 2], [2, 2, 4, 4]], } merged = PatchPredictor.merge_predictions( np.zeros([4, 4]), output, resolution=1.0, units="baseline" ) _merged = np.array([[2, 2, 0, 0], [2, 2, 0, 0], [0, 0, 1, 1], [0, 0, 1, 1]]) assert np.sum(merged - _merged) == 0 # blind test for merging probabilities merged = PatchPredictor.merge_predictions( np.zeros([4, 4]), output, resolution=1.0, units="baseline", return_raw=True, ) _merged = np.array( [[0.45, 0.45, 0, 0], [0.45, 0.45, 0, 0], [0, 0, 0.90, 0.90], [0, 0, 0.90, 0.90]] ) assert merged.shape == (4, 4, 2) assert np.mean(np.abs(merged[..., 0] - _merged)) < 1.0e-6 # integration test predictor = PatchPredictor(pretrained_model="resnet18-kather100k", batch_size=1) kwargs = { "return_probabilities": True, "return_labels": True, "on_gpu": ON_GPU, "patch_input_shape": np.array([224, 224]), "stride_shape": np.array([224, 224]), "resolution": 1.0, "units": "baseline", "merge_predictions": True, } # sanity check, both output should be the same with same resolution read args wsi_output = predictor.predict( [mini_wsi_svs], masks=[mini_wsi_msk], mode="wsi", **kwargs, ) # mock up to change the preproc func and # force to use the default in merge function # still should have the same results kwargs["merge_predictions"] = False tile_output = predictor.predict( [mini_wsi_jpg], masks=[mini_wsi_msk], mode="tile", **kwargs, ) merged_tile_output = predictor.merge_predictions( mini_wsi_jpg, tile_output[0], resolution=kwargs["resolution"], units=kwargs["units"], ) tile_output.append(merged_tile_output) # first make sure nothing breaks with predictions wpred = np.array(wsi_output[0]["predictions"]) tpred = np.array(tile_output[0]["predictions"]) diff = tpred == wpred accuracy = np.sum(diff) / np.size(wpred) assert accuracy > 0.9, np.nonzero(~diff) merged_wsi = wsi_output[1] merged_tile = tile_output[1] # ensure shape of merged predictions of tile and wsi input are the same assert merged_wsi.shape == merged_tile.shape # ensure consistent predictions between tile and wsi mode diff = merged_tile == merged_wsi accuracy = np.sum(diff) / np.size(merged_wsi) assert accuracy > 0.9, np.nonzero(~diff) def _test_predictor_output( inputs, pretrained_model, probabilities_check=None, predictions_check=None, on_gpu=ON_GPU, ): """Test the predictions of multiple models included in tiatoolbox.""" predictor = PatchPredictor( pretrained_model=pretrained_model, batch_size=32, verbose=False ) # don't run test on GPU output = predictor.predict( inputs, return_probabilities=True, return_labels=False, on_gpu=on_gpu, ) predictions = output["predictions"] probabilities = output["probabilities"] for idx, probabilities_ in enumerate(probabilities): probabilities_max = max(probabilities_) assert np.abs(probabilities_max - probabilities_check[idx]) <= 1e-3, ( pretrained_model, probabilities_max, probabilities_check[idx], predictions[idx], predictions_check[idx], ) assert predictions[idx] == predictions_check[idx], ( pretrained_model, probabilities_max, probabilities_check[idx], predictions[idx], predictions_check[idx], ) def test_patch_predictor_kather100k_output(sample_patch1, sample_patch2): """Test the output of patch prediction models on Kather100K dataset.""" inputs = [pathlib.Path(sample_patch1), pathlib.Path(sample_patch2)] pretrained_info = { "alexnet-kather100k": [1.0, 0.9999735355377197], "resnet18-kather100k": [1.0, 0.9999911785125732], "resnet34-kather100k": [1.0, 0.9979840517044067], "resnet50-kather100k": [1.0, 0.9999986886978149], "resnet101-kather100k": [1.0, 0.9999932050704956], "resnext50_32x4d-kather100k": [1.0, 0.9910059571266174], "resnext101_32x8d-kather100k": [1.0, 0.9999971389770508], "wide_resnet50_2-kather100k": [1.0, 0.9953408241271973], "wide_resnet101_2-kather100k": [1.0, 0.9999831914901733], "densenet121-kather100k": [1.0, 1.0], "densenet161-kather100k": [1.0, 0.9999959468841553], "densenet169-kather100k": [1.0, 0.9999934434890747], "densenet201-kather100k": [1.0, 0.9999983310699463], "mobilenet_v2-kather100k": [0.9999998807907104, 0.9999126195907593], "mobilenet_v3_large-kather100k": [0.9999996423721313, 0.9999878406524658], "mobilenet_v3_small-kather100k": [0.9999998807907104, 0.9999997615814209], "googlenet-kather100k": [1.0, 0.9999639987945557], } for pretrained_model, expected_prob in pretrained_info.items(): _test_predictor_output( inputs, pretrained_model, probabilities_check=expected_prob, predictions_check=[6, 3], on_gpu=ON_GPU, ) # only test 1 on travis to limit runtime if toolbox_env.running_on_ci(): break def test_patch_predictor_pcam_output(sample_patch3, sample_patch4): """Test the output of patch prediction models on PCam dataset.""" inputs = [pathlib.Path(sample_patch3), pathlib.Path(sample_patch4)] pretrained_info = { "alexnet-pcam": [0.999980092048645, 0.9769067168235779], "resnet18-pcam": [0.999992847442627, 0.9466130137443542], "resnet34-pcam": [1.0, 0.9976525902748108], "resnet50-pcam": [0.9999270439147949, 0.9999996423721313], "resnet101-pcam": [1.0, 0.9997289776802063], "resnext50_32x4d-pcam": [0.9999996423721313, 0.9984435439109802], "resnext101_32x8d-pcam": [0.9997072815895081, 0.9969086050987244], "wide_resnet50_2-pcam": [0.9999837875366211, 0.9959040284156799], "wide_resnet101_2-pcam": [1.0, 0.9945427179336548], "densenet121-pcam": [0.9999251365661621, 0.9997479319572449], "densenet161-pcam": [0.9999969005584717, 0.9662821292877197], "densenet169-pcam": [0.9999998807907104, 0.9993504881858826], "densenet201-pcam": [0.9999942779541016, 0.9950824975967407], "mobilenet_v2-pcam": [0.9999876022338867, 0.9942564368247986], "mobilenet_v3_large-pcam": [0.9999922513961792, 0.9719613790512085], "mobilenet_v3_small-pcam": [0.9999963045120239, 0.9747149348258972], "googlenet-pcam": [0.9999929666519165, 0.8701475858688354], } for pretrained_model, expected_prob in pretrained_info.items(): _test_predictor_output( inputs, pretrained_model, probabilities_check=expected_prob, predictions_check=[1, 0], on_gpu=ON_GPU, ) # only test 1 on travis to limit runtime if toolbox_env.running_on_ci(): break # ------------------------------------------------------------------------------------- # Command Line Interface # ------------------------------------------------------------------------------------- def test_command_line_models_file_not_found(sample_svs, tmp_path): """Test for models CLI file not found error.""" runner = CliRunner() model_file_not_found_result = runner.invoke( cli.main, [ "patch-predictor", "--img-input", str(sample_svs)[:-1], "--file-types", '"*.ndpi, *.svs"', "--output-path", str(tmp_path.joinpath("output")), ], ) assert model_file_not_found_result.output == "" assert model_file_not_found_result.exit_code == 1 assert isinstance(model_file_not_found_result.exception, FileNotFoundError) def test_command_line_models_incorrect_mode(sample_svs, tmp_path): """Test for models CLI mode not in wsi, tile.""" runner = CliRunner() mode_not_in_wsi_tile_result = runner.invoke( cli.main, [ "patch-predictor", "--img-input", str(sample_svs), "--file-types", '"*.ndpi, *.svs"', "--mode", '"patch"', "--output-path", str(tmp_path.joinpath("output")), ], ) assert "Invalid value for '--mode'" in mode_not_in_wsi_tile_result.output assert mode_not_in_wsi_tile_result.exit_code != 0 assert isinstance(mode_not_in_wsi_tile_result.exception, SystemExit) def test_cli_model_single_file(sample_svs, tmp_path): """Test for models CLI single file.""" runner = CliRunner() models_wsi_result = runner.invoke( cli.main, [ "patch-predictor", "--img-input", str(sample_svs), "--mode", "wsi", "--output-path", str(tmp_path.joinpath("output")), ], ) assert models_wsi_result.exit_code == 0 assert tmp_path.joinpath("output/0.merged.npy").exists() assert tmp_path.joinpath("output/0.raw.json").exists() assert tmp_path.joinpath("output/results.json").exists() def test_cli_model_single_file_mask(remote_sample, tmp_path): """Test for models CLI single file with mask.""" mini_wsi_svs = pathlib.Path(remote_sample("svs-1-small")) sample_wsi_msk = remote_sample("small_svs_tissue_mask") sample_wsi_msk = np.load(sample_wsi_msk).astype(np.uint8) imwrite(f"{tmp_path}/small_svs_tissue_mask.jpg", sample_wsi_msk) sample_wsi_msk = f"{tmp_path}/small_svs_tissue_mask.jpg" runner = CliRunner() models_tiles_result = runner.invoke( cli.main, [ "patch-predictor", "--img-input", str(mini_wsi_svs), "--mode", "wsi", "--masks", str(sample_wsi_msk), "--output-path", str(tmp_path.joinpath("output")), ], ) assert models_tiles_result.exit_code == 0 assert tmp_path.joinpath("output/0.merged.npy").exists() assert tmp_path.joinpath("output/0.raw.json").exists() assert tmp_path.joinpath("output/results.json").exists() def test_cli_model_multiple_file_mask(remote_sample, tmp_path): """Test for models CLI multiple file with mask.""" mini_wsi_svs = pathlib.Path(remote_sample("svs-1-small")) sample_wsi_msk = remote_sample("small_svs_tissue_mask") sample_wsi_msk = np.load(sample_wsi_msk).astype(np.uint8) imwrite(f"{tmp_path}/small_svs_tissue_mask.jpg", sample_wsi_msk) mini_wsi_msk = tmp_path.joinpath("small_svs_tissue_mask.jpg") # Make multiple copies for test dir_path = tmp_path.joinpath("new_copies") dir_path.mkdir() dir_path_masks = tmp_path.joinpath("new_copies_masks") dir_path_masks.mkdir() try: dir_path.joinpath("1_" + mini_wsi_svs.name).symlink_to(mini_wsi_svs) dir_path.joinpath("2_" + mini_wsi_svs.name).symlink_to(mini_wsi_svs) dir_path.joinpath("3_" + mini_wsi_svs.name).symlink_to(mini_wsi_svs) except OSError: shutil.copy(mini_wsi_svs, dir_path.joinpath("1_" + mini_wsi_svs.name)) shutil.copy(mini_wsi_svs, dir_path.joinpath("2_" + mini_wsi_svs.name)) shutil.copy(mini_wsi_svs, dir_path.joinpath("3_" + mini_wsi_svs.name)) try: dir_path_masks.joinpath("1_" + mini_wsi_msk.name).symlink_to(mini_wsi_msk) dir_path_masks.joinpath("2_" + mini_wsi_msk.name).symlink_to(mini_wsi_msk) dir_path_masks.joinpath("3_" + mini_wsi_msk.name).symlink_to(mini_wsi_msk) except OSError: shutil.copy(mini_wsi_msk, dir_path_masks.joinpath("1_" + mini_wsi_msk.name)) shutil.copy(mini_wsi_msk, dir_path_masks.joinpath("2_" + mini_wsi_msk.name)) shutil.copy(mini_wsi_msk, dir_path_masks.joinpath("3_" + mini_wsi_msk.name)) tmp_path = tmp_path.joinpath("output") runner = CliRunner() models_tiles_result = runner.invoke( cli.main, [ "patch-predictor", "--img-input", str(dir_path), "--mode", "wsi", "--masks", str(dir_path_masks), "--output-path", str(tmp_path), ], ) assert models_tiles_result.exit_code == 0 assert tmp_path.joinpath("0.merged.npy").exists() assert tmp_path.joinpath("0.raw.json").exists() assert tmp_path.joinpath("1.merged.npy").exists() assert tmp_path.joinpath("1.raw.json").exists() assert tmp_path.joinpath("2.merged.npy").exists() assert tmp_path.joinpath("2.raw.json").exists() assert tmp_path.joinpath("results.json").exists()
39,420
32.779777
88
py
tiatoolbox
tiatoolbox-master/tests/models/test_nucleus_instance_segmentor.py
"""Tests for Nucleus Instance Segmentor.""" import copy # ! The garbage collector import gc import pathlib import shutil import joblib import numpy as np import pytest import yaml from click.testing import CliRunner from tiatoolbox import cli from tiatoolbox.models import ( IOSegmentorConfig, NucleusInstanceSegmentor, SemanticSegmentor, ) from tiatoolbox.models.architecture import fetch_pretrained_weights from tiatoolbox.models.engine.nucleus_instance_segmentor import ( _process_tile_predictions, ) from tiatoolbox.utils import env_detection as toolbox_env from tiatoolbox.utils.metrics import f1_detection from tiatoolbox.utils.misc import imwrite from tiatoolbox.wsicore.wsireader import WSIReader ON_GPU = toolbox_env.has_gpu() # The value is based on 2 TitanXP each with 12GB BATCH_SIZE = 1 if not ON_GPU else 16 # ---------------------------------------------------- def _rm_dir(path): """Helper func to remove directory.""" shutil.rmtree(path, ignore_errors=True) def _crash_func(x): """Helper to induce crash.""" raise ValueError("Propataion Crash.") def helper_tile_info(): """Helper function for tile information.""" predictor = NucleusInstanceSegmentor(model="A") # ! assuming the tiles organized as follows (coming out from # ! PatchExtractor). If this is broken, need to check back # ! PatchExtractor output ordering first # left to right, top to bottom # --------------------- # | 0 | 1 | 2 | 3 | # --------------------- # | 4 | 5 | 6 | 7 | # --------------------- # | 8 | 9 | 10 | 11 | # --------------------- # | 12 | 13 | 14 | 15 | # --------------------- # ! assume flag index ordering: left right top bottom ioconfig = IOSegmentorConfig( input_resolutions=[{"units": "mpp", "resolution": 0.25}], output_resolutions=[ {"units": "mpp", "resolution": 0.25}, {"units": "mpp", "resolution": 0.25}, {"units": "mpp", "resolution": 0.25}, ], margin=1, tile_shape=[4, 4], stride_shape=[4, 4], patch_input_shape=[4, 4], patch_output_shape=[4, 4], ) return predictor._get_tile_info([16, 16], ioconfig) # ---------------------------------------------------- def test_get_tile_info(): """Test for getting tile info.""" info = helper_tile_info() _, flag = info[0] # index 0 should be full grid, removal # removal flag at top edges assert ( np.sum( np.nonzero(flag[:, 0]) != np.array([4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15]) ) == 0 ), "Fail Top" # removal flag at bottom edges assert ( np.sum( np.nonzero(flag[:, 1]) != np.array([0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11]) ) == 0 ), "Fail Bottom" # removal flag at left edges assert ( np.sum( np.nonzero(flag[:, 2]) != np.array([1, 2, 3, 5, 6, 7, 9, 10, 11, 13, 14, 15]) ) == 0 ), "Fail Left" # removal flag at right edges assert ( np.sum( np.nonzero(flag[:, 3]) != np.array([0, 1, 2, 4, 5, 6, 8, 9, 10, 12, 13, 14]) ) == 0 ), "Fail Right" def test_vertical_boundary_boxes(): """Test for vertical boundary boxes.""" info = helper_tile_info() _boxes = np.array( [ [3, 0, 5, 4], [7, 0, 9, 4], [11, 0, 13, 4], [3, 4, 5, 8], [7, 4, 9, 8], [11, 4, 13, 8], [3, 8, 5, 12], [7, 8, 9, 12], [11, 8, 13, 12], [3, 12, 5, 16], [7, 12, 9, 16], [11, 12, 13, 16], ] ) _flag = np.array( [ [0, 1, 0, 0], [0, 1, 0, 0], [0, 1, 0, 0], [1, 1, 0, 0], [1, 1, 0, 0], [1, 1, 0, 0], [1, 1, 0, 0], [1, 1, 0, 0], [1, 1, 0, 0], [1, 0, 0, 0], [1, 0, 0, 0], [1, 0, 0, 0], ] ) boxes, flag = info[1] assert np.sum(_boxes - boxes) == 0, "Wrong Vertical Bounds" assert np.sum(flag - _flag) == 0, "Fail Vertical Flag" def test_horizontal_boundary_boxes(): """Test for horizontal boundary boxes.""" info = helper_tile_info() _boxes = np.array( [ [0, 3, 4, 5], [4, 3, 8, 5], [8, 3, 12, 5], [12, 3, 16, 5], [0, 7, 4, 9], [4, 7, 8, 9], [8, 7, 12, 9], [12, 7, 16, 9], [0, 11, 4, 13], [4, 11, 8, 13], [8, 11, 12, 13], [12, 11, 16, 13], ] ) _flag = np.array( [ [0, 0, 0, 1], [0, 0, 1, 1], [0, 0, 1, 1], [0, 0, 1, 0], [0, 0, 0, 1], [0, 0, 1, 1], [0, 0, 1, 1], [0, 0, 1, 0], [0, 0, 0, 1], [0, 0, 1, 1], [0, 0, 1, 1], [0, 0, 1, 0], ] ) boxes, flag = info[2] assert np.sum(_boxes - boxes) == 0, "Wrong Horizontal Bounds" assert np.sum(flag - _flag) == 0, "Fail Horizontal Flag" def test_cross_section_boundary_boxes(): """Test for cross-section boundary boxes.""" info = helper_tile_info() _boxes = np.array( [ [2, 2, 6, 6], [6, 2, 10, 6], [10, 2, 14, 6], [2, 6, 6, 10], [6, 6, 10, 10], [10, 6, 14, 10], [2, 10, 6, 14], [6, 10, 10, 14], [10, 10, 14, 14], ] ) _flag = np.array( [ [1, 1, 1, 1], [1, 1, 1, 1], [1, 1, 1, 1], [1, 1, 1, 1], [1, 1, 1, 1], [1, 1, 1, 1], [1, 1, 1, 1], [1, 1, 1, 1], [1, 1, 1, 1], ] ) boxes, flag = info[3] assert np.sum(boxes - _boxes) == 0, "Wrong Cross Section Bounds" assert np.sum(flag - _flag) == 0, "Fail Cross Section Flag" def test_crash_segmentor(remote_sample, tmp_path): """Test engine crash when given malformed input.""" root_save_dir = pathlib.Path(tmp_path) sample_wsi_svs = pathlib.Path(remote_sample("svs-1-small")) sample_wsi_msk = remote_sample("small_svs_tissue_mask") sample_wsi_msk = np.load(sample_wsi_msk).astype(np.uint8) imwrite(f"{tmp_path}/small_svs_tissue_mask.jpg", sample_wsi_msk) sample_wsi_msk = tmp_path.joinpath("small_svs_tissue_mask.jpg") save_dir = f"{root_save_dir}/instance/" # resolution for travis testing, not the correct ones resolution = 4.0 ioconfig = IOSegmentorConfig( input_resolutions=[{"units": "mpp", "resolution": resolution}], output_resolutions=[ {"units": "mpp", "resolution": resolution}, {"units": "mpp", "resolution": resolution}, {"units": "mpp", "resolution": resolution}, ], margin=128, tile_shape=[512, 512], patch_input_shape=[256, 256], patch_output_shape=[164, 164], stride_shape=[164, 164], ) instance_segmentor = NucleusInstanceSegmentor( batch_size=BATCH_SIZE, num_postproc_workers=2, pretrained_model="hovernet_fast-pannuke", ) # * Test crash propagation when parallelize post processing _rm_dir(save_dir) instance_segmentor.model.postproc_func = _crash_func with pytest.raises(ValueError, match=r"Propataion Crash."): instance_segmentor.predict( [sample_wsi_svs], masks=[sample_wsi_msk], mode="wsi", ioconfig=ioconfig, on_gpu=ON_GPU, crash_on_exception=True, save_dir=save_dir, ) _rm_dir(tmp_path) def test_functionality_travis(remote_sample, tmp_path): """Functionality test for nuclei instance segmentor.""" gc.collect() root_save_dir = pathlib.Path(tmp_path) mini_wsi_svs = pathlib.Path(remote_sample("wsi4_512_512_svs")) resolution = 2.0 reader = WSIReader.open(mini_wsi_svs) thumb = reader.slide_thumbnail(resolution=resolution, units="mpp") mini_wsi_jpg = f"{tmp_path}/mini_svs.jpg" imwrite(mini_wsi_jpg, thumb) save_dir = f"{root_save_dir}/instance/" # * test run on wsi, test run with worker # resolution for travis testing, not the correct ones ioconfig = IOSegmentorConfig( input_resolutions=[{"units": "mpp", "resolution": resolution}], output_resolutions=[ {"units": "mpp", "resolution": resolution}, {"units": "mpp", "resolution": resolution}, ], margin=128, tile_shape=[1024, 1024], patch_input_shape=[256, 256], patch_output_shape=[164, 164], stride_shape=[164, 164], ) _rm_dir(save_dir) inst_segmentor = NucleusInstanceSegmentor( batch_size=1, num_loader_workers=0, num_postproc_workers=0, pretrained_model="hovernet_fast-pannuke", ) inst_segmentor.predict( [mini_wsi_svs], mode="wsi", ioconfig=ioconfig, on_gpu=ON_GPU, crash_on_exception=True, save_dir=save_dir, ) # clean up _rm_dir(tmp_path) def test_functionality_merge_tile_predictions_travis(remote_sample, tmp_path): """Functional tests for merging tile predictions.""" gc.collect() # Force clean up everything on hold save_dir = pathlib.Path(f"{tmp_path}/output") mini_wsi_svs = pathlib.Path(remote_sample("wsi4_512_512_svs")) resolution = 0.5 ioconfig = IOSegmentorConfig( input_resolutions=[{"units": "mpp", "resolution": resolution}], output_resolutions=[ {"units": "mpp", "resolution": resolution}, {"units": "mpp", "resolution": resolution}, {"units": "mpp", "resolution": resolution}, ], margin=128, tile_shape=[512, 512], patch_input_shape=[256, 256], patch_output_shape=[164, 164], stride_shape=[164, 164], ) # mainly to hook the merge prediction function inst_segmentor = NucleusInstanceSegmentor( batch_size=BATCH_SIZE, num_postproc_workers=0, pretrained_model="hovernet_fast-pannuke", ) _rm_dir(save_dir) semantic_segmentor = SemanticSegmentor( pretrained_model="hovernet_fast-pannuke", batch_size=BATCH_SIZE, num_postproc_workers=0, ) output = semantic_segmentor.predict( [mini_wsi_svs], mode="wsi", on_gpu=ON_GPU, ioconfig=ioconfig, crash_on_exception=True, save_dir=save_dir, ) raw_maps = [np.load(f"{output[0][1]}.raw.{head_idx}.npy") for head_idx in range(3)] raw_maps = [[v] for v in raw_maps] # mask it as patch output dummy_reference = {i: {"box": np.array([0, 0, 32, 32])} for i in range(1000)} dummy_flag_mode_list = [ [[1, 1, 0, 0], 1], [[0, 0, 1, 1], 2], [[1, 1, 1, 1], 3], [[0, 0, 0, 0], 0], ] inst_segmentor._wsi_inst_info = copy.deepcopy(dummy_reference) inst_segmentor._futures = [[dummy_reference, dummy_reference.keys()]] inst_segmentor._merge_post_process_results() assert len(inst_segmentor._wsi_inst_info) == 0 blank_raw_maps = [np.zeros_like(v) for v in raw_maps] _process_tile_predictions( ioconfig=ioconfig, tile_bounds=np.array([0, 0, 512, 512]), tile_flag=dummy_flag_mode_list[0][0], tile_mode=dummy_flag_mode_list[0][1], tile_output=[[np.array([0, 0, 512, 512]), blank_raw_maps]], ref_inst_dict=dummy_reference, postproc=semantic_segmentor.model.postproc_func, merge_predictions=semantic_segmentor.merge_prediction, ) for tile_flag, tile_mode in dummy_flag_mode_list: _process_tile_predictions( ioconfig=ioconfig, tile_bounds=np.array([0, 0, 512, 512]), tile_flag=tile_flag, tile_mode=tile_mode, tile_output=[[np.array([0, 0, 512, 512]), raw_maps]], ref_inst_dict=dummy_reference, postproc=semantic_segmentor.model.postproc_func, merge_predictions=semantic_segmentor.merge_prediction, ) # test exception flag tile_flag = [0, 0, 0, 0] with pytest.raises(ValueError, match=r".*Unknown tile mode.*"): _process_tile_predictions( ioconfig=ioconfig, tile_bounds=np.array([0, 0, 512, 512]), tile_flag=tile_flag, tile_mode=-1, tile_output=[[np.array([0, 0, 512, 512]), raw_maps]], ref_inst_dict=dummy_reference, postproc=semantic_segmentor.model.postproc_func, merge_predictions=semantic_segmentor.merge_prediction, ) _rm_dir(tmp_path) @pytest.mark.skipif( toolbox_env.running_on_ci() or not ON_GPU, reason="Local test on machine with GPU.", ) def test_functionality_local(remote_sample, tmp_path): """Local functionality test for nuclei instance segmentor.""" root_save_dir = pathlib.Path(tmp_path) save_dir = pathlib.Path(f"{tmp_path}/output") mini_wsi_svs = pathlib.Path(remote_sample("wsi4_1k_1k_svs")) # * generate full output w/o parallel post processing worker first _rm_dir(save_dir) inst_segmentor = NucleusInstanceSegmentor( batch_size=8, num_postproc_workers=0, pretrained_model="hovernet_fast-pannuke", ) output = inst_segmentor.predict( [mini_wsi_svs], mode="wsi", on_gpu=True, crash_on_exception=True, save_dir=save_dir, ) inst_dict_a = joblib.load(f"{output[0][1]}.dat") # * then test run when using workers, will then compare results # * to ensure the predictions are the same _rm_dir(save_dir) inst_segmentor = NucleusInstanceSegmentor( pretrained_model="hovernet_fast-pannuke", batch_size=BATCH_SIZE, num_postproc_workers=2, ) assert inst_segmentor.num_postproc_workers == 2 output = inst_segmentor.predict( [mini_wsi_svs], mode="wsi", on_gpu=True, crash_on_exception=True, save_dir=save_dir, ) inst_dict_b = joblib.load(f"{output[0][1]}.dat") inst_coords_a = np.array([v["centroid"] for v in inst_dict_a.values()]) inst_coords_b = np.array([v["centroid"] for v in inst_dict_b.values()]) score = f1_detection(inst_coords_b, inst_coords_a, radius=1.0) assert score > 0.95, "Heavy loss of precision!" # ** # To evaluate the precision of doing post processing on tile # then re-assemble without using full image prediction maps, # we compare its output with the output when doing # post processing on the entire images save_dir = f"{root_save_dir}/semantic/" _rm_dir(save_dir) semantic_segmentor = SemanticSegmentor( pretrained_model="hovernet_fast-pannuke", batch_size=BATCH_SIZE, num_postproc_workers=2, ) output = semantic_segmentor.predict( [mini_wsi_svs], mode="wsi", on_gpu=True, crash_on_exception=True, save_dir=save_dir, ) raw_maps = [np.load(f"{output[0][1]}.raw.{head_idx}.npy") for head_idx in range(3)] _, inst_dict_b = semantic_segmentor.model.postproc(raw_maps) inst_coords_a = np.array([v["centroid"] for v in inst_dict_a.values()]) inst_coords_b = np.array([v["centroid"] for v in inst_dict_b.values()]) score = f1_detection(inst_coords_b, inst_coords_a, radius=1.0) assert score > 0.9, "Heavy loss of precision!" _rm_dir(tmp_path) def test_cli_nucleus_instance_segment_ioconfig(remote_sample, tmp_path): """Test for nucleus segmentation with IOconfig.""" mini_wsi_svs = pathlib.Path(remote_sample("wsi4_512_512_svs")) output_path = tmp_path / "output" resolution = 2.0 reader = WSIReader.open(mini_wsi_svs) thumb = reader.slide_thumbnail(resolution=resolution, units="mpp") mini_wsi_jpg = f"{tmp_path}/mini_svs.jpg" imwrite(mini_wsi_jpg, thumb) fetch_pretrained_weights( "hovernet_fast-pannuke", str(tmp_path.joinpath("hovernet_fast-pannuke.pth")) ) # resolution for travis testing, not the correct ones config = { "input_resolutions": [{"units": "mpp", "resolution": resolution}], "output_resolutions": [ {"units": "mpp", "resolution": resolution}, {"units": "mpp", "resolution": resolution}, {"units": "mpp", "resolution": resolution}, ], "margin": 128, "tile_shape": [512, 512], "patch_input_shape": [256, 256], "patch_output_shape": [164, 164], "stride_shape": [164, 164], "save_resolution": {"units": "mpp", "resolution": 8.0}, } with open(tmp_path.joinpath("config.yaml"), "w") as fptr: yaml.dump(config, fptr) runner = CliRunner() nucleus_instance_segment_result = runner.invoke( cli.main, [ "nucleus-instance-segment", "--img-input", str(mini_wsi_jpg), "--pretrained-weights", str(tmp_path.joinpath("hovernet_fast-pannuke.pth")), "--num-loader-workers", str(0), "--num-postproc-workers", str(0), "--mode", "tile", "--output-path", str(output_path), "--yaml-config-path", tmp_path.joinpath("config.yaml"), ], ) assert nucleus_instance_segment_result.exit_code == 0 assert output_path.joinpath("0.dat").exists() assert output_path.joinpath("file_map.dat").exists() assert output_path.joinpath("results.json").exists() _rm_dir(tmp_path) def test_cli_nucleus_instance_segment(remote_sample, tmp_path): """Test for nucleus segmentation.""" mini_wsi_svs = pathlib.Path(remote_sample("wsi4_512_512_svs")) output_path = tmp_path / "output" runner = CliRunner() nucleus_instance_segment_result = runner.invoke( cli.main, [ "nucleus-instance-segment", "--img-input", str(mini_wsi_svs), "--mode", "wsi", "--num-loader-workers", str(0), "--num-postproc-workers", str(0), "--output-path", str(output_path), ], ) assert nucleus_instance_segment_result.exit_code == 0 assert output_path.joinpath("0.dat").exists() assert output_path.joinpath("file_map.dat").exists() assert output_path.joinpath("results.json").exists() _rm_dir(tmp_path)
18,765
30.172757
88
py
tiatoolbox
tiatoolbox-master/tests/models/test_arch_unet.py
"""Unit test package for Unet.""" import pathlib import numpy as np import pytest import torch from tiatoolbox.models.architecture import fetch_pretrained_weights from tiatoolbox.models.architecture.unet import UNetModel from tiatoolbox.wsicore.wsireader import WSIReader ON_GPU = False # Test pretrained Model ============================= def test_functional_unet(remote_sample, tmp_path): """Tests for unet.""" # convert to pathlib Path to prevent wsireader complaint mini_wsi_svs = pathlib.Path(remote_sample("wsi2_4k_4k_svs")) _pretrained_path = f"{tmp_path}/weights.pth" fetch_pretrained_weights("fcn-tissue_mask", _pretrained_path) reader = WSIReader.open(mini_wsi_svs) with pytest.raises(ValueError, match=r".*Unknown encoder*"): model = UNetModel(3, 2, encoder="resnet101", decoder_block=[3]) with pytest.raises(ValueError, match=r".*Unknown type of skip connection*"): model = UNetModel(3, 2, encoder="unet", skip_type="attention") # test creation model = UNetModel(5, 5, encoder="resnet50") model = UNetModel(3, 2, encoder="resnet50") model = UNetModel(3, 2, encoder="unet") # test inference read_kwargs = {"resolution": 2.0, "units": "mpp", "coord_space": "resolution"} batch = np.array( [ # noqa reader.read_bounds([0, 0, 1024, 1024], **read_kwargs), reader.read_bounds([1024, 1024, 2048, 2048], **read_kwargs), ] ) batch = torch.from_numpy(batch) model = UNetModel(3, 2, encoder="resnet50", decoder_block=[3]) pretrained = torch.load(_pretrained_path, map_location="cpu") model.load_state_dict(pretrained) output = model.infer_batch(model, batch, on_gpu=ON_GPU) output = output[0] # run untrained network to test for architecture model = UNetModel( 3, 2, encoder="unet", decoder_block=[3], encoder_levels=[32, 64], skip_type="concat", ) output = model.infer_batch(model, batch, on_gpu=ON_GPU)
2,041
30.415385
82
py
tiatoolbox
tiatoolbox-master/tests/models/test_arch_sccnn.py
"""Unit test package for SCCNN.""" import numpy as np import torch from tiatoolbox import utils from tiatoolbox.models import SCCNN from tiatoolbox.models.architecture import fetch_pretrained_weights from tiatoolbox.wsicore.wsireader import WSIReader def _load_sccnn(tmp_path, name): """Loads SCCNN model with specified weights.""" model = SCCNN() fetch_pretrained_weights(name, f"{tmp_path}/weights.pth") map_location = utils.misc.select_device(utils.env_detection.has_gpu()) pretrained = torch.load(f"{tmp_path}/weights.pth", map_location=map_location) model.load_state_dict(pretrained) return model def test_functionality(remote_sample, tmp_path): """Functionality test for SCCNN. Tests the functionality of SCCNN model for inference at the patch level. """ tmp_path = str(tmp_path) sample_wsi = str(remote_sample("wsi1_2k_2k_svs")) reader = WSIReader.open(sample_wsi) # * test fast mode (architecture used in PanNuke paper) patch = reader.read_bounds( (30, 30, 61, 61), resolution=0.25, units="mpp", coord_space="resolution" ) batch = torch.from_numpy(patch)[None] model = _load_sccnn(tmp_path=tmp_path, name="sccnn-crchisto") output = model.infer_batch(model, batch, on_gpu=False) output = model.postproc(output[0]) assert np.all(output == [[8, 7]]) model = _load_sccnn(tmp_path=tmp_path, name="sccnn-conic") output = model.infer_batch(model, batch, on_gpu=False) output = model.postproc(output[0]) assert np.all(output == [[7, 8]])
1,556
32.847826
81
py
tiatoolbox
tiatoolbox-master/tests/models/test_multi_task_segmentor.py
"""Unit test package for HoVerNet+.""" import copy # ! The garbage collector import gc import multiprocessing import os import pathlib import shutil import joblib import numpy as np import pytest from tiatoolbox.models import IOSegmentorConfig, MultiTaskSegmentor, SemanticSegmentor from tiatoolbox.utils import env_detection as toolbox_env from tiatoolbox.utils.metrics import f1_detection from tiatoolbox.utils.misc import imwrite ON_GPU = toolbox_env.has_gpu() BATCH_SIZE = 1 if not ON_GPU else 8 # 16 try: NUM_POSTPROC_WORKERS = multiprocessing.cpu_count() except NotImplementedError: NUM_POSTPROC_WORKERS = 2 # ---------------------------------------------------- def _rm_dir(path): """Helper func to remove directory.""" shutil.rmtree(path, ignore_errors=True) def _crash_func(_): """Helper to induce crash.""" raise ValueError("Propagation Crash.") def semantic_postproc_func(raw_output): """ Function to post process semantic segmentations to form one map as an output. """ return np.argmax(raw_output, axis=-1) @pytest.mark.skipif( toolbox_env.running_on_ci() or not ON_GPU, reason="Local test on machine with GPU.", ) def test_functionality_local(remote_sample, tmp_path): """Local functionality test for multi task segmentor.""" gc.collect() root_save_dir = pathlib.Path(tmp_path) mini_wsi_svs = pathlib.Path(remote_sample("svs-1-small")) save_dir = f"{root_save_dir}/multitask/" _rm_dir(save_dir) # * generate full output w/o parallel post-processing worker first multi_segmentor = MultiTaskSegmentor( pretrained_model="hovernetplus-oed", batch_size=BATCH_SIZE, num_postproc_workers=0, ) output = multi_segmentor.predict( [mini_wsi_svs], mode="wsi", on_gpu=ON_GPU, crash_on_exception=True, save_dir=save_dir, ) inst_dict_a = joblib.load(f"{output[0][1]}.0.dat") # * then test run when using workers, will then compare results # * to ensure the predictions are the same _rm_dir(save_dir) multi_segmentor = MultiTaskSegmentor( pretrained_model="hovernetplus-oed", batch_size=BATCH_SIZE, num_postproc_workers=NUM_POSTPROC_WORKERS, ) assert multi_segmentor.num_postproc_workers == NUM_POSTPROC_WORKERS output = multi_segmentor.predict( [mini_wsi_svs], mode="wsi", on_gpu=ON_GPU, crash_on_exception=True, save_dir=save_dir, ) inst_dict_b = joblib.load(f"{output[0][1]}.0.dat") layer_map_b = np.load(f"{output[0][1]}.1.npy") assert len(inst_dict_b) > 0, "Must have some nuclei" assert layer_map_b is not None, "Must have some layers." inst_coords_a = np.array([v["centroid"] for v in inst_dict_a.values()]) inst_coords_b = np.array([v["centroid"] for v in inst_dict_b.values()]) score = f1_detection(inst_coords_b, inst_coords_a, radius=1.0) assert score > 0.95, "Heavy loss of precision!" _rm_dir(tmp_path) def test_functionality_hovernetplus(remote_sample, tmp_path): """Functionality test for multitask segmentor.""" root_save_dir = pathlib.Path(tmp_path) mini_wsi_svs = pathlib.Path(remote_sample("wsi4_512_512_svs")) required_dims = (258, 258) # above image is 512 x 512 at 0.252 mpp resolution. This is 258 x 258 at 0.500 mpp. save_dir = f"{root_save_dir}/multi/" _rm_dir(save_dir) multi_segmentor = MultiTaskSegmentor( pretrained_model="hovernetplus-oed", batch_size=BATCH_SIZE, num_postproc_workers=NUM_POSTPROC_WORKERS, ) output = multi_segmentor.predict( [mini_wsi_svs], mode="wsi", on_gpu=ON_GPU, crash_on_exception=True, save_dir=save_dir, ) inst_dict = joblib.load(f"{output[0][1]}.0.dat") layer_map = np.load(f"{output[0][1]}.1.npy") assert len(inst_dict) > 0, "Must have some nuclei." assert layer_map is not None, "Must have some layers." assert ( layer_map.shape == required_dims ), "Output layer map dimensions must be same as the expected output shape" _rm_dir(tmp_path) def test_functionality_hovernet(remote_sample, tmp_path): """Functionality test for multitask segmentor.""" root_save_dir = pathlib.Path(tmp_path) mini_wsi_svs = pathlib.Path(remote_sample("wsi4_512_512_svs")) save_dir = f"{root_save_dir}/multi/" _rm_dir(save_dir) multi_segmentor = MultiTaskSegmentor( pretrained_model="hovernet_fast-pannuke", batch_size=BATCH_SIZE, num_postproc_workers=NUM_POSTPROC_WORKERS, ) output = multi_segmentor.predict( [mini_wsi_svs], mode="wsi", on_gpu=ON_GPU, crash_on_exception=True, save_dir=save_dir, ) inst_dict = joblib.load(f"{output[0][1]}.0.dat") assert len(inst_dict) > 0, "Must have some nuclei." _rm_dir(tmp_path) def test_masked_segmentor(remote_sample, tmp_path): """Test segmentor when image is masked.""" root_save_dir = pathlib.Path(tmp_path) sample_wsi_svs = pathlib.Path(remote_sample("svs-1-small")) sample_wsi_msk = remote_sample("small_svs_tissue_mask") sample_wsi_msk = np.load(sample_wsi_msk).astype(np.uint8) imwrite(f"{tmp_path}/small_svs_tissue_mask.jpg", sample_wsi_msk) sample_wsi_msk = tmp_path.joinpath("small_svs_tissue_mask.jpg") save_dir = root_save_dir / "instance" # resolution for travis testing, not the correct ones resolution = 4.0 ioconfig = IOSegmentorConfig( input_resolutions=[{"units": "mpp", "resolution": resolution}], output_resolutions=[ {"units": "mpp", "resolution": resolution}, {"units": "mpp", "resolution": resolution}, {"units": "mpp", "resolution": resolution}, ], margin=128, tile_shape=[512, 512], patch_input_shape=[256, 256], patch_output_shape=[164, 164], stride_shape=[164, 164], ) multi_segmentor = MultiTaskSegmentor( batch_size=BATCH_SIZE, num_postproc_workers=2, pretrained_model="hovernet_fast-pannuke", ) output = multi_segmentor.predict( [sample_wsi_svs], masks=[sample_wsi_msk], mode="wsi", ioconfig=ioconfig, on_gpu=ON_GPU, crash_on_exception=True, save_dir=save_dir, ) inst_dict = joblib.load(f"{output[0][1]}.0.dat") assert len(inst_dict) > 0, "Must have some nuclei." _rm_dir(tmp_path) def test_functionality_process_instance_predictions(remote_sample, tmp_path): root_save_dir = pathlib.Path(tmp_path) mini_wsi_svs = pathlib.Path(remote_sample("wsi4_512_512_svs")) save_dir = root_save_dir / "semantic" _rm_dir(save_dir) semantic_segmentor = SemanticSegmentor( pretrained_model="hovernetplus-oed", batch_size=BATCH_SIZE, num_postproc_workers=0, ) multi_segmentor = MultiTaskSegmentor( pretrained_model="hovernetplus-oed", batch_size=BATCH_SIZE, num_postproc_workers=0, ) output = semantic_segmentor.predict( [mini_wsi_svs], mode="wsi", on_gpu=ON_GPU, crash_on_exception=True, save_dir=save_dir, ) raw_maps = [np.load(f"{output[0][1]}.raw.{head_idx}.npy") for head_idx in range(4)] dummy_reference = [{i: {"box": np.array([0, 0, 32, 32])} for i in range(1000)}] dummy_tiles = [np.zeros((512, 512))] dummy_bounds = np.array([0, 0, 512, 512]) multi_segmentor.wsi_layers = [np.zeros_like(raw_maps[0][..., 0])] multi_segmentor._wsi_inst_info = copy.deepcopy(dummy_reference) multi_segmentor._futures = [ [dummy_reference, [dummy_reference[0].keys()], dummy_tiles, dummy_bounds] ] multi_segmentor._merge_post_process_results() assert len(multi_segmentor._wsi_inst_info[0]) == 0 _rm_dir(tmp_path) def test_empty_image(tmp_path): root_save_dir = pathlib.Path(tmp_path) sample_patch = np.ones((256, 256, 3), dtype="uint8") * 255 sample_patch_path = os.path.join(root_save_dir, "sample_tile.png") imwrite(sample_patch_path, sample_patch) save_dir = root_save_dir / "hovernetplus" multi_segmentor = MultiTaskSegmentor( pretrained_model="hovernetplus-oed", batch_size=BATCH_SIZE, num_postproc_workers=0, ) _ = multi_segmentor.predict( [sample_patch_path], mode="tile", on_gpu=ON_GPU, crash_on_exception=True, save_dir=save_dir, ) save_dir = root_save_dir / "hovernet" multi_segmentor = MultiTaskSegmentor( pretrained_model="hovernet_fast-pannuke", batch_size=BATCH_SIZE, num_postproc_workers=0, ) _ = multi_segmentor.predict( [sample_patch_path], mode="tile", on_gpu=ON_GPU, crash_on_exception=True, save_dir=save_dir, ) save_dir = root_save_dir / "semantic" multi_segmentor = MultiTaskSegmentor( pretrained_model="fcn_resnet50_unet-bcss", batch_size=BATCH_SIZE, num_postproc_workers=0, output_types=["semantic"], ) bcc_wsi_ioconfig = IOSegmentorConfig( input_resolutions=[{"units": "mpp", "resolution": 0.25}], output_resolutions=[{"units": "mpp", "resolution": 0.25}], tile_shape=2048, patch_input_shape=[1024, 1024], patch_output_shape=[512, 512], stride_shape=[512, 512], margin=128, save_resolution={"units": "mpp", "resolution": 2}, ) _ = multi_segmentor.predict( [sample_patch_path], mode="tile", on_gpu=ON_GPU, crash_on_exception=True, save_dir=save_dir, ioconfig=bcc_wsi_ioconfig, ) def test_functionality_semantic(remote_sample, tmp_path): """Functionality test for multitask segmentor.""" root_save_dir = pathlib.Path(tmp_path) save_dir = f"{root_save_dir}/multi/" _rm_dir(save_dir) with pytest.raises( ValueError, match=r"Output type must be specified for instance or semantic segmentation.", ): MultiTaskSegmentor( pretrained_model="fcn_resnet50_unet-bcss", batch_size=BATCH_SIZE, num_postproc_workers=NUM_POSTPROC_WORKERS, ) mini_wsi_svs = pathlib.Path(remote_sample("wsi4_512_512_svs")) save_dir = f"{root_save_dir}/multi/" _rm_dir(tmp_path) multi_segmentor = MultiTaskSegmentor( pretrained_model="fcn_resnet50_unet-bcss", batch_size=BATCH_SIZE, num_postproc_workers=NUM_POSTPROC_WORKERS, output_types=["semantic"], ) bcc_wsi_ioconfig = IOSegmentorConfig( input_resolutions=[{"units": "mpp", "resolution": 0.25}], output_resolutions=[{"units": "mpp", "resolution": 0.25}], tile_shape=2048, patch_input_shape=[1024, 1024], patch_output_shape=[512, 512], stride_shape=[512, 512], margin=128, save_resolution={"units": "mpp", "resolution": 2}, ) multi_segmentor.model.postproc_func = semantic_postproc_func output = multi_segmentor.predict( [mini_wsi_svs], mode="wsi", on_gpu=ON_GPU, crash_on_exception=True, save_dir=save_dir, ioconfig=bcc_wsi_ioconfig, ) layer_map = np.load(f"{output[0][1]}.0.npy") assert layer_map is not None, "Must have some segmentations." _rm_dir(tmp_path) def test_crash_segmentor(remote_sample, tmp_path): """Test engine crash when given malformed input.""" root_save_dir = pathlib.Path(tmp_path) sample_wsi_svs = pathlib.Path(remote_sample("svs-1-small")) sample_wsi_msk = remote_sample("small_svs_tissue_mask") sample_wsi_msk = np.load(sample_wsi_msk).astype(np.uint8) imwrite(f"{tmp_path}/small_svs_tissue_mask.jpg", sample_wsi_msk) sample_wsi_msk = tmp_path.joinpath("small_svs_tissue_mask.jpg") save_dir = f"{root_save_dir}/multi/" # resolution for travis testing, not the correct ones resolution = 4.0 ioconfig = IOSegmentorConfig( input_resolutions=[{"units": "mpp", "resolution": resolution}], output_resolutions=[ {"units": "mpp", "resolution": resolution}, {"units": "mpp", "resolution": resolution}, {"units": "mpp", "resolution": resolution}, ], margin=128, tile_shape=[512, 512], patch_input_shape=[256, 256], patch_output_shape=[164, 164], stride_shape=[164, 164], ) multi_segmentor = MultiTaskSegmentor( batch_size=BATCH_SIZE, num_postproc_workers=2, pretrained_model="hovernetplus-oed", ) # * Test crash propagation when parallelize post-processing _rm_dir(save_dir) multi_segmentor.model.postproc_func = _crash_func with pytest.raises(ValueError, match=r"Crash."): multi_segmentor.predict( [sample_wsi_svs], masks=[sample_wsi_msk], mode="wsi", ioconfig=ioconfig, on_gpu=ON_GPU, crash_on_exception=True, save_dir=save_dir, ) _rm_dir(tmp_path)
13,194
29.901639
87
py
tiatoolbox
tiatoolbox-master/tests/models/test_feature_extractor.py
"""Tests for feature extractor.""" import os import pathlib import shutil import numpy as np import torch from tiatoolbox.models.architecture.vanilla import CNNBackbone from tiatoolbox.models.engine.semantic_segmentor import ( DeepFeatureExtractor, IOSegmentorConfig, ) from tiatoolbox.utils import env_detection as toolbox_env from tiatoolbox.wsicore.wsireader import WSIReader ON_GPU = not toolbox_env.running_on_ci() and toolbox_env.has_gpu() # ---------------------------------------------------- def _rm_dir(path): """Helper func to remove directory.""" if os.path.exists(path): shutil.rmtree(path, ignore_errors=True) # ------------------------------------------------------------------------------------- # Engine # ------------------------------------------------------------------------------------- def test_functional(remote_sample, tmp_path): """Test for feature extraction.""" save_dir = pathlib.Path(f"{tmp_path}/output/") # # convert to pathlib Path to prevent wsireader complaint mini_wsi_svs = pathlib.Path(remote_sample("wsi4_1k_1k_svs")) # * test providing pretrained from torch vs pretrained_model.yaml _rm_dir(save_dir) # default output dir test extractor = DeepFeatureExtractor(batch_size=1, pretrained_model="fcn-tissue_mask") output_list = extractor.predict( [mini_wsi_svs], mode="wsi", on_gpu=ON_GPU, crash_on_exception=True, save_dir=save_dir, ) wsi_0_root_path = output_list[0][1] positions = np.load(f"{wsi_0_root_path}.position.npy") features = np.load(f"{wsi_0_root_path}.features.0.npy") assert len(features.shape) == 4 # * test same output between full infer and engine # pre-emptive clean up _rm_dir(save_dir) # default output dir test ioconfig = IOSegmentorConfig( input_resolutions=[ {"units": "mpp", "resolution": 0.25}, ], output_resolutions=[ {"units": "mpp", "resolution": 0.25}, ], patch_input_shape=[512, 512], patch_output_shape=[512, 512], stride_shape=[256, 256], save_resolution={"units": "mpp", "resolution": 8.0}, ) model = CNNBackbone("resnet50") extractor = DeepFeatureExtractor(batch_size=4, model=model) # should still run because we skip exception output_list = extractor.predict( [mini_wsi_svs], mode="wsi", ioconfig=ioconfig, on_gpu=ON_GPU, crash_on_exception=True, save_dir=save_dir, ) wsi_0_root_path = output_list[0][1] positions = np.load(f"{wsi_0_root_path}.position.npy") features = np.load(f"{wsi_0_root_path}.features.0.npy") reader = WSIReader.open(mini_wsi_svs) patches = [ reader.read_bounds( positions[patch_idx], resolution=0.25, units="mpp", pad_constant_values=0, coord_space="resolution", ) for patch_idx in range(4) ] patches = np.array(patches) patches = torch.from_numpy(patches) # NHWC patches = patches.permute(0, 3, 1, 2) # NCHW patches = patches.type(torch.float32) model = model.to("cpu") # Inference mode model.eval() with torch.inference_mode(): _features = model(patches).numpy() # ! must maintain same batch size and likely same ordering # ! else the output values will not exactly be the same (still < 1.0e-4 # ! of epsilon though) assert np.mean(np.abs(features[:4] - _features)) < 1.0e-1 _rm_dir(save_dir)
3,572
30.619469
87
py
tiatoolbox
tiatoolbox-master/tests/models/test_hovernet.py
"""Unit test package for HoVerNet.""" import numpy as np import pytest import torch import torch.nn as nn from tiatoolbox.models import HoVerNet from tiatoolbox.models.architecture import fetch_pretrained_weights from tiatoolbox.models.architecture.hovernet import ( DenseBlock, ResidualBlock, TFSamepaddingLayer, ) from tiatoolbox.wsicore.wsireader import WSIReader def test_functionality(remote_sample, tmp_path): """Functionality test.""" tmp_path = str(tmp_path) sample_wsi = str(remote_sample("wsi1_2k_2k_svs")) reader = WSIReader.open(sample_wsi) # * test fast mode (architecture used in PanNuke paper) patch = reader.read_bounds( (0, 0, 256, 256), resolution=0.25, units="mpp", coord_space="resolution" ) batch = torch.from_numpy(patch)[None] model = HoVerNet(num_types=6, mode="fast") fetch_pretrained_weights("hovernet_fast-pannuke", f"{tmp_path}/weights.pth") pretrained = torch.load(f"{tmp_path}/weights.pth") model.load_state_dict(pretrained) output = model.infer_batch(model, batch, on_gpu=False) output = [v[0] for v in output] output = model.postproc(output) assert len(output[1]) > 0, "Must have some nuclei." # * test fast mode (architecture used for MoNuSAC data) patch = reader.read_bounds( (0, 0, 256, 256), resolution=0.25, units="mpp", coord_space="resolution" ) batch = torch.from_numpy(patch)[None] model = HoVerNet(num_types=5, mode="fast") fetch_pretrained_weights("hovernet_fast-monusac", f"{tmp_path}/weights.pth") pretrained = torch.load(f"{tmp_path}/weights.pth") model.load_state_dict(pretrained) output = model.infer_batch(model, batch, on_gpu=False) output = [v[0] for v in output] output = model.postproc(output) assert len(output[1]) > 0, "Must have some nuclei." # * test original mode on CoNSeP dataset (architecture used in HoVerNet paper) patch = reader.read_bounds( (0, 0, 270, 270), resolution=0.25, units="mpp", coord_space="resolution" ) batch = torch.from_numpy(patch)[None] model = HoVerNet(num_types=5, mode="original") fetch_pretrained_weights("hovernet_original-consep", f"{tmp_path}/weights.pth") pretrained = torch.load(f"{tmp_path}/weights.pth") model.load_state_dict(pretrained) output = model.infer_batch(model, batch, on_gpu=False) output = [v[0] for v in output] output = model.postproc(output) assert len(output[1]) > 0, "Must have some nuclei." # * test original mode on Kumar dataset (architecture used in HoVerNet paper) patch = reader.read_bounds( (0, 0, 270, 270), resolution=0.25, units="mpp", coord_space="resolution" ) batch = torch.from_numpy(patch)[None] model = HoVerNet(num_types=None, mode="original") fetch_pretrained_weights("hovernet_original-kumar", f"{tmp_path}/weights.pth") pretrained = torch.load(f"{tmp_path}/weights.pth") model.load_state_dict(pretrained) output = model.infer_batch(model, batch, on_gpu=False) output = [v[0] for v in output] output = model.postproc(output) assert len(output[1]) > 0, "Must have some nuclei." # test crash when providing exotic mode with pytest.raises(ValueError, match=r".*Invalid mode.*"): model = HoVerNet(num_types=None, mode="super") def test_unit_blocks(): """Tests for blocks within HoVerNet.""" # padding model = nn.Sequential(TFSamepaddingLayer(7, 1), nn.Conv2d(3, 3, 7, 1, padding=0)) sample = torch.rand((1, 3, 14, 14), dtype=torch.float32) output = model(sample) assert np.sum(output.shape - np.array([1, 3, 14, 14])) == 0, f"{output.shape}" # padding with stride and odd shape model = nn.Sequential(TFSamepaddingLayer(7, 2), nn.Conv2d(3, 3, 7, 2, padding=0)) sample = torch.rand((1, 3, 15, 15), dtype=torch.float32) output = model(sample) assert np.sum(output.shape - np.array([1, 3, 8, 8])) == 0, f"{output.shape}" # * sample = torch.rand((1, 16, 15, 15), dtype=torch.float32) block = ResidualBlock(16, [1, 3, 1], [16, 16, 16], 3) assert block.shortcut is None output = block(sample) assert np.sum(output.shape - np.array([1, 16, 15, 15])) == 0, f"{output.shape}" block = ResidualBlock(16, [1, 3, 1], [16, 16, 32], 3) assert block.shortcut is not None output = block(sample) assert np.sum(output.shape - np.array([1, 32, 15, 15])) == 0, f"{output.shape}" # block = DenseBlock(16, [1, 3], [16, 16], 3) output = block(sample) assert output.shape[1] == 16 * 4, f"{output.shape}" # test crash when providing exotic mode with pytest.raises(ValueError, match=r".*Unbalance Unit Info.*"): _ = DenseBlock(16, [1, 3, 1], [16, 16], 3) with pytest.raises(ValueError, match=r".*Unbalance Unit Info.*"): _ = ResidualBlock(16, [1, 3, 1], [16, 16], 3)
4,878
38.666667
85
py
tiatoolbox
tiatoolbox-master/tests/models/test_arch_mapde.py
"""Unit test package for SCCNN.""" import numpy as np import torch from tiatoolbox import utils from tiatoolbox.models import MapDe from tiatoolbox.models.architecture import fetch_pretrained_weights from tiatoolbox.wsicore.wsireader import WSIReader def _load_mapde(tmp_path, name): """Loads MapDe model with specified weights.""" model = MapDe() fetch_pretrained_weights(name, f"{tmp_path}/weights.pth") map_location = utils.misc.select_device(utils.env_detection.has_gpu()) pretrained = torch.load(f"{tmp_path}/weights.pth", map_location=map_location) model.load_state_dict(pretrained) return model def test_functionality(remote_sample, tmp_path): """Functionality test for MapDe. Tests the functionality of MapDe model for inference at the patch level. """ tmp_path = str(tmp_path) sample_wsi = str(remote_sample("wsi1_2k_2k_svs")) reader = WSIReader.open(sample_wsi) # * test fast mode (architecture used in PanNuke paper) patch = reader.read_bounds( (0, 0, 252, 252), resolution=0.50, units="mpp", coord_space="resolution" ) model = _load_mapde(tmp_path=tmp_path, name="mapde-crchisto") patch = model.preproc(patch) batch = torch.from_numpy(patch)[None] output = model.infer_batch(model, batch, on_gpu=False) output = model.postproc(output[0]) assert np.all(output[0:2] == [[99, 178], [64, 218]]) model = _load_mapde(tmp_path=tmp_path, name="mapde-conic") output = model.infer_batch(model, batch, on_gpu=False) output = model.postproc(output[0]) assert np.all(output[0:2] == [[19, 171], [53, 89]])
1,627
32.916667
81
py
tiatoolbox
tiatoolbox-master/tests/models/test_semantic_segmentation.py
"""Tests for Semantic Segmentor.""" import copy # ! The garbage collector import gc import multiprocessing import os import pathlib import shutil import numpy as np import pytest import torch import torch.multiprocessing as torch_mp import torch.nn as nn import torch.nn.functional as F # noqa: N812 import yaml from click.testing import CliRunner from tiatoolbox import cli from tiatoolbox.models.architecture import fetch_pretrained_weights from tiatoolbox.models.architecture.utils import centre_crop from tiatoolbox.models.engine.semantic_segmentor import ( IOSegmentorConfig, SemanticSegmentor, WSIStreamDataset, ) from tiatoolbox.models.models_abc import ModelABC from tiatoolbox.utils import env_detection as toolbox_env from tiatoolbox.utils.misc import imread, imwrite from tiatoolbox.wsicore.wsireader import WSIReader ON_GPU = toolbox_env.has_gpu() # The value is based on 2 TitanXP each with 12GB BATCH_SIZE = 1 if not ON_GPU else 16 try: NUM_POSTPROC_WORKERS = multiprocessing.cpu_count() except NotImplementedError: NUM_POSTPROC_WORKERS = 2 # ---------------------------------------------------- def _rm_dir(path): """Helper func to remove directory.""" if os.path.exists(path): shutil.rmtree(path, ignore_errors=True) def _crash_func(x): """Helper to induce crash.""" raise ValueError("Propagation Crash.") class _CNNTo1(ModelABC): """Contains a convolution. Simple model to test functionality, this contains a single convolution layer which has weight=0 and bias=1. """ def __init__(self): super().__init__() self.conv = nn.Conv2d(3, 1, 3, padding=1) self.conv.weight.data.fill_(0) self.conv.bias.data.fill_(1) def forward(self, img): """Define how to use layer.""" return self.conv(img) @staticmethod def infer_batch(model, batch_data, on_gpu): """Run inference on an input batch. Contains logic for forward operation as well as i/o aggregation for a single data batch. Args: model (nn.Module): PyTorch defined model. batch_data (ndarray): A batch of data generated by torch.utils.data.DataLoader. on_gpu (bool): Whether to run inference on a GPU. """ device = "cuda" if on_gpu else "cpu" #### model.eval() # infer mode #### img_list = batch_data img_list = img_list.to(device).type(torch.float32) img_list = img_list.permute(0, 3, 1, 2) # to NCHW hw = np.array(img_list.shape[2:]) with torch.inference_mode(): # do not compute gradient logit_list = model(img_list) logit_list = centre_crop(logit_list, hw // 2) logit_list = logit_list.permute(0, 2, 3, 1) # to NHWC prob_list = F.relu(logit_list) prob_list = prob_list.cpu().numpy() return [prob_list] # ------------------------------------------------------------------------------------- # IOConfig # ------------------------------------------------------------------------------------- def test_segmentor_ioconfig(): """Test for IOConfig.""" default_config = { "input_resolutions": [ {"units": "mpp", "resolution": 0.25}, {"units": "mpp", "resolution": 0.50}, {"units": "mpp", "resolution": 0.75}, ], "output_resolutions": [ {"units": "mpp", "resolution": 0.25}, {"units": "mpp", "resolution": 0.50}, ], "patch_input_shape": [2048, 2048], "patch_output_shape": [1024, 1024], "stride_shape": [512, 512], } # error when uniform resolution units are not uniform xconfig = copy.deepcopy(default_config) xconfig["input_resolutions"] = [ {"units": "mpp", "resolution": 0.25}, {"units": "power", "resolution": 0.50}, ] with pytest.raises(ValueError, match=r".*Invalid resolution units.*"): _ = IOSegmentorConfig(**xconfig) # error when uniform resolution units are not supported xconfig = copy.deepcopy(default_config) xconfig["input_resolutions"] = [ {"units": "alpha", "resolution": 0.25}, {"units": "alpha", "resolution": 0.50}, ] with pytest.raises(ValueError, match=r".*Invalid resolution units.*"): _ = IOSegmentorConfig(**xconfig) ioconfig = IOSegmentorConfig( input_resolutions=[ {"units": "mpp", "resolution": 0.25}, {"units": "mpp", "resolution": 0.50}, {"units": "mpp", "resolution": 0.75}, ], output_resolutions=[ {"units": "mpp", "resolution": 0.25}, {"units": "mpp", "resolution": 0.50}, ], patch_input_shape=[2048, 2048], patch_output_shape=[1024, 1024], stride_shape=[512, 512], ) assert ioconfig.highest_input_resolution == {"units": "mpp", "resolution": 0.25} ioconfig = ioconfig.to_baseline() assert ioconfig.input_resolutions[0]["resolution"] == 1.0 assert ioconfig.input_resolutions[1]["resolution"] == 0.5 assert ioconfig.input_resolutions[2]["resolution"] == 1 / 3 ioconfig = IOSegmentorConfig( input_resolutions=[ {"units": "power", "resolution": 20}, {"units": "power", "resolution": 40}, ], output_resolutions=[ {"units": "power", "resolution": 20}, {"units": "power", "resolution": 40}, ], patch_input_shape=[2048, 2048], patch_output_shape=[1024, 1024], stride_shape=[512, 512], save_resolution={"units": "power", "resolution": 8.0}, ) assert ioconfig.highest_input_resolution == {"units": "power", "resolution": 40} ioconfig = ioconfig.to_baseline() assert ioconfig.input_resolutions[0]["resolution"] == 0.5 assert ioconfig.input_resolutions[1]["resolution"] == 1.0 assert ioconfig.save_resolution["resolution"] == 8.0 / 40.0 resolutions = [ {"units": "mpp", "resolution": 0.25}, {"units": "mpp", "resolution": 0.50}, {"units": "mpp", "resolution": 0.75}, ] with pytest.raises(ValueError, match=r".*Unknown units.*"): ioconfig.scale_to_highest(resolutions, "axx") # ------------------------------------------------------------------------------------- # Dataset # ------------------------------------------------------------------------------------- def test_functional_wsi_stream_dataset(remote_sample): """Functional test for WSIStreamDataset.""" gc.collect() # Force clean up everything on hold mini_wsi_svs = pathlib.Path(remote_sample("wsi4_512_512_svs")) ioconfig = IOSegmentorConfig( input_resolutions=[ {"units": "mpp", "resolution": 0.25}, {"units": "mpp", "resolution": 0.50}, {"units": "mpp", "resolution": 0.75}, ], output_resolutions=[ {"units": "mpp", "resolution": 0.25}, {"units": "mpp", "resolution": 0.50}, ], patch_input_shape=[2048, 2048], patch_output_shape=[1024, 1024], stride_shape=[512, 512], ) mp_manager = torch_mp.Manager() mp_shared_space = mp_manager.Namespace() sds = WSIStreamDataset(ioconfig, [mini_wsi_svs], mp_shared_space) # test for collate out = sds.collate_fn([None, 1, 2, 3]) assert np.sum(out.numpy() != np.array([1, 2, 3])) == 0 # artificial data injection mp_shared_space.wsi_idx = torch.tensor(0) # a scalar mp_shared_space.patch_inputs = torch.from_numpy( np.array( [ [0, 0, 256, 256], [256, 256, 512, 512], ] ) ) mp_shared_space.patch_outputs = torch.from_numpy( np.array( [ [0, 0, 256, 256], [256, 256, 512, 512], ] ) ) # test read for _, sample in enumerate(sds): patch_data, _ = sample (patch_resolution1, patch_resolution2, patch_resolution3) = patch_data assert np.round(patch_resolution1.shape[0] / patch_resolution2.shape[0]) == 2 assert np.round(patch_resolution1.shape[0] / patch_resolution3.shape[0]) == 3 # ------------------------------------------------------------------------------------- # Engine # ------------------------------------------------------------------------------------- def test_crash_segmentor(remote_sample): """Functional crash tests for segmentor.""" # # convert to pathlib Path to prevent wsireader complaint mini_wsi_svs = pathlib.Path(remote_sample("wsi2_4k_4k_svs")) mini_wsi_jpg = pathlib.Path(remote_sample("wsi2_4k_4k_jpg")) mini_wsi_msk = pathlib.Path(remote_sample("wsi2_4k_4k_msk")) model = _CNNTo1() semantic_segmentor = SemanticSegmentor(batch_size=BATCH_SIZE, model=model) # fake injection to trigger Segmentor to create parallel # post processing workers because baseline Semantic Segmentor does not support # post processing out of the box. It only contains condition to create it # for any subclass semantic_segmentor.num_postproc_workers = 1 # * test basic crash _rm_dir("output") # default output dir test with pytest.raises(ValueError, match=r".*`mask_reader`.*"): semantic_segmentor.filter_coordinates(mini_wsi_msk, np.array(["a", "b", "c"])) with pytest.raises(ValueError, match=r".*ndarray.*integer.*"): semantic_segmentor.filter_coordinates( WSIReader.open(mini_wsi_msk), np.array([1.0, 2.0]) ) semantic_segmentor.get_reader(mini_wsi_svs, None, "wsi", True) with pytest.raises(ValueError, match=r".*must be a valid file path.*"): semantic_segmentor.get_reader(mini_wsi_msk, "not_exist", "wsi", True) _rm_dir("output") # default output dir test with pytest.raises(ValueError, match=r".*provide.*"): SemanticSegmentor() with pytest.raises(ValueError, match=r".*valid mode.*"): semantic_segmentor.predict([], mode="abc") # * test not providing any io_config info when not using pretrained model with pytest.raises(ValueError, match=r".*provide either `ioconfig`.*"): semantic_segmentor.predict( [mini_wsi_jpg], mode="tile", on_gpu=ON_GPU, crash_on_exception=True, ) with pytest.raises(ValueError, match=r".*already exists.*"): semantic_segmentor.predict([], mode="tile", patch_input_shape=[2048, 2048]) _rm_dir("output") # default output dir test # * test not providing any io_config info when not using pretrained model with pytest.raises(ValueError, match=r".*provide either `ioconfig`.*"): semantic_segmentor.predict( [mini_wsi_jpg], mode="tile", on_gpu=ON_GPU, crash_on_exception=True, ) _rm_dir("output") # default output dir test # * Test crash propagation when parallelize post processing _rm_dir("output") semantic_segmentor.num_postproc_workers = 2 semantic_segmentor.model.forward = _crash_func with pytest.raises(ValueError, match=r"Propagation Crash."): semantic_segmentor.predict( [mini_wsi_svs], patch_input_shape=[2048, 2048], mode="wsi", on_gpu=ON_GPU, crash_on_exception=True, ) _rm_dir("output") # test ignore crash semantic_segmentor.predict( [mini_wsi_svs], patch_input_shape=[2048, 2048], mode="wsi", on_gpu=ON_GPU, crash_on_exception=False, ) _rm_dir("output") def test_functional_segmentor_merging(tmp_path): """Functional test for assmebling output.""" save_dir = pathlib.Path(tmp_path) model = _CNNTo1() semantic_segmentor = SemanticSegmentor(batch_size=BATCH_SIZE, model=model) _rm_dir(save_dir) os.mkdir(save_dir) # predictions with HW _output = np.array( [ [1, 1, 0, 0], [1, 1, 0, 0], [0, 0, 2, 2], [0, 0, 2, 2], ] ) canvas = semantic_segmentor.merge_prediction( [4, 4], [np.full((2, 2), 1), np.full((2, 2), 2)], [[0, 0, 2, 2], [2, 2, 4, 4]], save_path=f"{save_dir}/raw.py", cache_count_path=f"{save_dir}/count.py", ) assert np.sum(canvas - _output) < 1.0e-8 # a second rerun to test overlapping count, # should still maintain same result canvas = semantic_segmentor.merge_prediction( [4, 4], [np.full((2, 2), 1), np.full((2, 2), 2)], [[0, 0, 2, 2], [2, 2, 4, 4]], save_path=f"{save_dir}/raw.py", cache_count_path=f"{save_dir}/count.py", ) assert np.sum(canvas - _output) < 1.0e-8 # else will leave hanging file pointer # and hence cant remove its folder later del canvas # skipcq # * predictions with HWC _rm_dir(save_dir) os.mkdir(save_dir) canvas = semantic_segmentor.merge_prediction( [4, 4], [np.full((2, 2, 1), 1), np.full((2, 2, 1), 2)], [[0, 0, 2, 2], [2, 2, 4, 4]], save_path=f"{save_dir}/raw.py", cache_count_path=f"{save_dir}/count.py", ) del canvas # skipcq # * test crashing when switch to image having larger # * shape but still provide old links semantic_segmentor.merge_prediction( [8, 8], [np.full((2, 2, 1), 1), np.full((2, 2, 1), 2)], [[0, 0, 2, 2], [2, 2, 4, 4]], save_path=f"{save_dir}/raw.1.py", cache_count_path=f"{save_dir}/count.1.py", ) with pytest.raises(ValueError, match=r".*`save_path` does not match.*"): semantic_segmentor.merge_prediction( [4, 4], [np.full((2, 2, 1), 1), np.full((2, 2, 1), 2)], [[0, 0, 2, 2], [2, 2, 4, 4]], save_path=f"{save_dir}/raw.1.py", cache_count_path=f"{save_dir}/count.py", ) with pytest.raises(ValueError, match=r".*`cache_count_path` does not match.*"): semantic_segmentor.merge_prediction( [4, 4], [np.full((2, 2, 1), 1), np.full((2, 2, 1), 2)], [[0, 0, 2, 2], [2, 2, 4, 4]], save_path=f"{save_dir}/raw.py", cache_count_path=f"{save_dir}/count.1.py", ) # * test non HW predictions with pytest.raises(ValueError, match=r".*Prediction is no HW or HWC.*"): semantic_segmentor.merge_prediction( [4, 4], [np.full((2,), 1), np.full((2,), 2)], [[0, 0, 2, 2], [2, 2, 4, 4]], save_path=f"{save_dir}/raw.py", cache_count_path=f"{save_dir}/count.1.py", ) _rm_dir(save_dir) os.mkdir(save_dir) # * with out of bound location canvas = semantic_segmentor.merge_prediction( [4, 4], [ np.full((2, 2), 1), np.full((2, 2), 2), np.full((2, 2), 3), np.full((2, 2), 4), ], [[0, 0, 2, 2], [2, 2, 4, 4], [0, 4, 2, 6], [4, 0, 6, 2]], save_path=None, ) assert np.sum(canvas - _output) < 1.0e-8 del canvas # skipcq _rm_dir(save_dir) os.mkdir(save_dir) def test_functional_segmentor(remote_sample, tmp_path): """Functional test for segmentor.""" save_dir = pathlib.Path(f"{tmp_path}/dump") # # convert to pathlib Path to prevent wsireader complaint resolution = 2.0 mini_wsi_svs = pathlib.Path(remote_sample("wsi4_1k_1k_svs")) reader = WSIReader.open(mini_wsi_svs) thumb = reader.slide_thumbnail(resolution=resolution, units="baseline") mini_wsi_jpg = f"{tmp_path}/mini_svs.jpg" imwrite(mini_wsi_jpg, thumb) mini_wsi_msk = f"{tmp_path}/mini_mask.jpg" imwrite(mini_wsi_msk, (thumb > 0).astype(np.uint8)) # preemptive clean up _rm_dir("output") # default output dir test model = _CNNTo1() semantic_segmentor = SemanticSegmentor(batch_size=BATCH_SIZE, model=model) # fake injection to trigger Segmentor to create parallel # post processing workers because baseline Semantic Segmentor does not support # post processing out of the box. It only contains condition to create it # for any subclass semantic_segmentor.num_postproc_workers = 1 # should still run because we skip exception semantic_segmentor.predict( [mini_wsi_jpg], mode="tile", on_gpu=ON_GPU, patch_input_shape=(512, 512), resolution=resolution, units="mpp", crash_on_exception=False, ) _rm_dir("output") # default output dir test semantic_segmentor.predict( [mini_wsi_jpg], mode="tile", on_gpu=ON_GPU, patch_input_shape=[512, 512], resolution=1 / resolution, units="baseline", crash_on_exception=True, ) _rm_dir("output") # default output dir test # * check exception bypass in the log # there should be no exception, but how to check the log? semantic_segmentor.predict( [mini_wsi_jpg], mode="tile", on_gpu=ON_GPU, patch_input_shape=(512, 512), patch_output_shape=(512, 512), stride_shape=(512, 512), resolution=1 / resolution, units="baseline", crash_on_exception=False, ) _rm_dir("output") # default output dir test # * test basic running and merging prediction # * should dumping all 1 in the output ioconfig = IOSegmentorConfig( input_resolutions=[{"units": "baseline", "resolution": 1.0}], output_resolutions=[{"units": "baseline", "resolution": 1.0}], patch_input_shape=[512, 512], patch_output_shape=[512, 512], stride_shape=[512, 512], ) _rm_dir(save_dir) file_list = [ mini_wsi_jpg, mini_wsi_jpg, ] output_list = semantic_segmentor.predict( file_list, mode="tile", on_gpu=ON_GPU, ioconfig=ioconfig, crash_on_exception=True, save_dir=f"{save_dir}/raw/", ) pred_1 = np.load(output_list[0][1] + ".raw.0.npy") pred_2 = np.load(output_list[1][1] + ".raw.0.npy") assert len(output_list) == 2 assert np.sum(pred_1 - pred_2) == 0 # due to overlapping merge and division, will not be # exactly 1, but should be approximately so assert np.sum((pred_1 - 1) > 1.0e-6) == 0 _rm_dir(save_dir) # * test running with mask and svs # * also test merging prediction at designated resolution ioconfig = IOSegmentorConfig( input_resolutions=[{"units": "mpp", "resolution": resolution}], output_resolutions=[{"units": "mpp", "resolution": resolution}], save_resolution={"units": "mpp", "resolution": resolution}, patch_input_shape=[512, 512], patch_output_shape=[256, 256], stride_shape=[512, 512], ) _rm_dir(save_dir) output_list = semantic_segmentor.predict( [mini_wsi_svs], masks=[mini_wsi_msk], mode="wsi", on_gpu=ON_GPU, ioconfig=ioconfig, crash_on_exception=True, save_dir=f"{save_dir}/raw/", ) reader = WSIReader.open(mini_wsi_svs) expected_shape = reader.slide_dimensions(**ioconfig.save_resolution) expected_shape = np.array(expected_shape)[::-1] # to YX pred_1 = np.load(output_list[0][1] + ".raw.0.npy") saved_shape = np.array(pred_1.shape[:2]) assert np.sum(expected_shape - saved_shape) == 0 assert np.sum((pred_1 - 1) > 1.0e-6) == 0 _rm_dir(save_dir) # check normal run with auto get mask semantic_segmentor = SemanticSegmentor( batch_size=BATCH_SIZE, model=model, auto_generate_mask=True ) output_list = semantic_segmentor.predict( [mini_wsi_svs], masks=[mini_wsi_msk], mode="wsi", on_gpu=ON_GPU, ioconfig=ioconfig, crash_on_exception=True, save_dir=f"{save_dir}/raw/", ) _rm_dir(save_dir) def test_subclass(remote_sample, tmp_path): """Create subclass and test parallel processing setup.""" save_dir = pathlib.Path(tmp_path) mini_wsi_jpg = pathlib.Path(remote_sample("wsi2_4k_4k_jpg")) model = _CNNTo1() class XSegmentor(SemanticSegmentor): """Dummy class to test subclassing.""" def __init__(self): super().__init__(model=model) self.num_postproc_worker = 2 semantic_segmentor = XSegmentor() _rm_dir(save_dir) # default output dir test semantic_segmentor.predict( [mini_wsi_jpg], mode="tile", on_gpu=ON_GPU, patch_input_shape=(1024, 1024), patch_output_shape=(512, 512), stride_shape=(256, 256), resolution=1.0, units="baseline", crash_on_exception=False, save_dir=f"{save_dir}/raw/", ) # specifically designed for travis def test_functional_pretrained(remote_sample, tmp_path): """Test for load up pretrained and over-writing tile mode ioconfig.""" save_dir = pathlib.Path(f"{tmp_path}/output") mini_wsi_svs = pathlib.Path(remote_sample("wsi4_512_512_svs")) reader = WSIReader.open(mini_wsi_svs) thumb = reader.slide_thumbnail(resolution=1.0, units="baseline") mini_wsi_jpg = f"{tmp_path}/mini_svs.jpg" imwrite(mini_wsi_jpg, thumb) semantic_segmentor = SemanticSegmentor( batch_size=BATCH_SIZE, pretrained_model="fcn-tissue_mask" ) _rm_dir(save_dir) semantic_segmentor.predict( [mini_wsi_svs], mode="wsi", on_gpu=ON_GPU, crash_on_exception=True, save_dir=f"{save_dir}/raw/", ) _rm_dir(save_dir) # mainly to test prediction on tile semantic_segmentor.predict( [mini_wsi_jpg], mode="tile", on_gpu=ON_GPU, crash_on_exception=True, save_dir=f"{save_dir}/raw/", ) assert save_dir.joinpath("raw/0.raw.0.npy").exists() assert save_dir.joinpath("raw/file_map.dat").exists() _rm_dir(tmp_path) @pytest.mark.skipif( toolbox_env.running_on_ci() or not ON_GPU, reason="Local test on machine with GPU.", ) def test_behavior_tissue_mask_local(remote_sample, tmp_path): """Contain test for behavior of the segmentor and pretrained models.""" save_dir = pathlib.Path(tmp_path) wsi_with_artifacts = pathlib.Path(remote_sample("wsi3_20k_20k_svs")) mini_wsi_jpg = pathlib.Path(remote_sample("wsi2_4k_4k_jpg")) semantic_segmentor = SemanticSegmentor( batch_size=BATCH_SIZE, pretrained_model="fcn-tissue_mask" ) _rm_dir(save_dir) semantic_segmentor.predict( [wsi_with_artifacts], mode="wsi", on_gpu=True, crash_on_exception=True, save_dir=f"{save_dir}/raw/", ) # load up the raw prediction and perform precision check _cache_pred = imread(pathlib.Path(remote_sample("wsi3_20k_20k_pred"))) _test_pred = np.load(f"{save_dir}/raw/0.raw.0.npy") _test_pred = (_test_pred[..., 1] > 0.75) * 255 # divide 255 to binarize assert np.mean(_cache_pred[..., 0] == _test_pred) > 0.99 _rm_dir(save_dir) # mainly to test prediction on tile semantic_segmentor.predict( [mini_wsi_jpg], mode="tile", on_gpu=True, crash_on_exception=True, save_dir=f"{save_dir}/raw/", ) _rm_dir(save_dir) @pytest.mark.skipif( toolbox_env.running_on_ci() or not ON_GPU, reason="Local test on machine with GPU.", ) def test_behavior_bcss_local(remote_sample, tmp_path): """Contain test for behavior of the segmentor and pretrained models.""" save_dir = pathlib.Path(tmp_path) _rm_dir(save_dir) wsi_breast = pathlib.Path(remote_sample("wsi4_4k_4k_svs")) semantic_segmentor = SemanticSegmentor( num_loader_workers=4, batch_size=BATCH_SIZE, pretrained_model="fcn_resnet50_unet-bcss", ) semantic_segmentor.predict( [wsi_breast], mode="wsi", on_gpu=True, crash_on_exception=True, save_dir=f"{save_dir}/raw/", ) # load up the raw prediction and perform precision check _cache_pred = np.load(pathlib.Path(remote_sample("wsi4_4k_4k_pred"))) _test_pred = np.load(f"{save_dir}/raw/0.raw.0.npy") _test_pred = np.argmax(_test_pred, axis=-1) assert np.mean(np.abs(_cache_pred - _test_pred)) < 1.0e-2 _rm_dir(save_dir) # ------------------------------------------------------------------------------------- # Command Line Interface # ------------------------------------------------------------------------------------- def test_cli_semantic_segment_out_exists_error(remote_sample, tmp_path): """Test for semantic segmentation if output path exists.""" mini_wsi_svs = pathlib.Path(remote_sample("svs-1-small")) sample_wsi_msk = remote_sample("small_svs_tissue_mask") sample_wsi_msk = np.load(sample_wsi_msk).astype(np.uint8) imwrite(f"{tmp_path}/small_svs_tissue_mask.jpg", sample_wsi_msk) sample_wsi_msk = f"{tmp_path}/small_svs_tissue_mask.jpg" runner = CliRunner() semantic_segment_result = runner.invoke( cli.main, [ "semantic-segment", "--img-input", str(mini_wsi_svs), "--mode", "wsi", "--masks", str(sample_wsi_msk), "--output-path", tmp_path, ], ) assert semantic_segment_result.output == "" assert semantic_segment_result.exit_code == 1 assert isinstance(semantic_segment_result.exception, FileExistsError) def test_cli_semantic_segmentation_ioconfig(remote_sample, tmp_path): """Test for semantic segmentation single file custom ioconfig.""" mini_wsi_svs = pathlib.Path(remote_sample("svs-1-small")) sample_wsi_msk = remote_sample("small_svs_tissue_mask") sample_wsi_msk = np.load(sample_wsi_msk).astype(np.uint8) imwrite(f"{tmp_path}/small_svs_tissue_mask.jpg", sample_wsi_msk) sample_wsi_msk = f"{tmp_path}/small_svs_tissue_mask.jpg" fetch_pretrained_weights( "fcn-tissue_mask", str(tmp_path.joinpath("fcn-tissue_mask.pth")) ) config = { "input_resolutions": [{"units": "mpp", "resolution": 2.0}], "output_resolutions": [{"units": "mpp", "resolution": 2.0}], "patch_input_shape": [1024, 1024], "patch_output_shape": [512, 512], "stride_shape": [256, 256], "save_resolution": {"units": "mpp", "resolution": 8.0}, } with open(tmp_path.joinpath("config.yaml"), "w") as fptr: yaml.dump(config, fptr) runner = CliRunner() semantic_segment_result = runner.invoke( cli.main, [ "semantic-segment", "--img-input", str(mini_wsi_svs), "--pretrained-weights", str(tmp_path.joinpath("fcn-tissue_mask.pth")), "--mode", "wsi", "--masks", str(sample_wsi_msk), "--output-path", tmp_path.joinpath("output"), "--yaml-config-path", tmp_path.joinpath("config.yaml"), ], ) assert semantic_segment_result.exit_code == 0 assert tmp_path.joinpath("output/0.raw.0.npy").exists() assert tmp_path.joinpath("output/file_map.dat").exists() assert tmp_path.joinpath("output/results.json").exists() def test_cli_semantic_segmentation_multi_file(remote_sample, tmp_path): """Test for models CLI multiple file with mask.""" mini_wsi_svs = pathlib.Path(remote_sample("svs-1-small")) sample_wsi_msk = remote_sample("small_svs_tissue_mask") sample_wsi_msk = np.load(sample_wsi_msk).astype(np.uint8) imwrite(f"{tmp_path}/small_svs_tissue_mask.jpg", sample_wsi_msk) sample_wsi_msk = tmp_path.joinpath("small_svs_tissue_mask.jpg") # Make multiple copies for test dir_path = tmp_path.joinpath("new_copies") dir_path.mkdir() dir_path_masks = tmp_path.joinpath("new_copies_masks") dir_path_masks.mkdir() try: dir_path.joinpath("1_" + mini_wsi_svs.name).symlink_to(mini_wsi_svs) dir_path.joinpath("2_" + mini_wsi_svs.name).symlink_to(mini_wsi_svs) except OSError: shutil.copy(mini_wsi_svs, dir_path.joinpath("1_" + mini_wsi_svs.name)) shutil.copy(mini_wsi_svs, dir_path.joinpath("2_" + mini_wsi_svs.name)) try: dir_path_masks.joinpath("1_" + sample_wsi_msk.name).symlink_to(sample_wsi_msk) dir_path_masks.joinpath("2_" + sample_wsi_msk.name).symlink_to(sample_wsi_msk) except OSError: shutil.copy(sample_wsi_msk, dir_path_masks.joinpath("1_" + sample_wsi_msk.name)) shutil.copy(sample_wsi_msk, dir_path_masks.joinpath("2_" + sample_wsi_msk.name)) tmp_path = tmp_path.joinpath("output") runner = CliRunner() semantic_segment_result = runner.invoke( cli.main, [ "semantic-segment", "--img-input", str(dir_path), "--mode", "wsi", "--masks", str(dir_path_masks), "--output-path", str(tmp_path), ], ) assert semantic_segment_result.exit_code == 0 assert tmp_path.joinpath("0.raw.0.npy").exists() assert tmp_path.joinpath("1.raw.0.npy").exists() assert tmp_path.joinpath("file_map.dat").exists() assert tmp_path.joinpath("results.json").exists() # load up the raw prediction and perform precision check _cache_pred = imread(pathlib.Path(remote_sample("small_svs_tissue_mask"))) _test_pred = np.load(str(tmp_path.joinpath("0.raw.0.npy"))) _test_pred = (_test_pred[..., 1] > 0.50) * 255 assert np.mean(np.abs(_cache_pred - _test_pred) / 255) < 1e-3
29,697
33.174914
88
py
tiatoolbox
tiatoolbox-master/tests/models/test_hovernetplus.py
"""Unit test package for HoVerNet+.""" import torch from tiatoolbox.models import HoVerNetPlus from tiatoolbox.models.architecture import fetch_pretrained_weights from tiatoolbox.utils.misc import imread from tiatoolbox.utils.transforms import imresize def test_functionality(remote_sample, tmp_path): """Functionality test.""" tmp_path = str(tmp_path) sample_patch = str(remote_sample("stainnorm-source")) patch_pre = imread(sample_patch) patch_pre = imresize(patch_pre, scale_factor=0.5) patch = patch_pre[0:256, 0:256] batch = torch.from_numpy(patch)[None] # Test functionality with both nuclei and layer segmentation model = HoVerNetPlus(num_types=3, num_layers=5) # Test decoder as expected assert len(model.decoder["np"]) > 0, "Decoder must contain np branch." assert len(model.decoder["hv"]) > 0, "Decoder must contain hv branch." assert len(model.decoder["tp"]) > 0, "Decoder must contain tp branch." assert len(model.decoder["ls"]) > 0, "Decoder must contain ls branch." fetch_pretrained_weights("hovernetplus-oed", f"{tmp_path}/weigths.pth") pretrained = torch.load(f"{tmp_path}/weigths.pth") model.load_state_dict(pretrained) output = model.infer_batch(model, batch, on_gpu=False) assert len(output) == 4, "Must contain predictions for: np, hv, tp and ls branches." output = [v[0] for v in output] output = model.postproc(output) assert len(output[1]) > 0, "Must have some nuclei." assert len(output[3]) > 0, "Must have some layers."
1,542
41.861111
88
py
tiatoolbox
tiatoolbox-master/tests/models/__init__.py
"""Unit test package for tiatoolbox models."""
47
23
46
py
tiatoolbox
tiatoolbox-master/tests/models/test_arch_idars.py
"""Functional unit test package for IDARS.""" import torch from tiatoolbox.models import IDaRS def test_functional(): """Functional test for architectures.""" # test forward samples = torch.rand(4, 3, 224, 224, dtype=torch.float32) model = IDaRS("resnet18") model(samples) model = IDaRS("resnet34") model(samples) # test preproc function img = torch.rand(224, 224, 3, dtype=torch.float32) img_ = IDaRS.preproc(img.numpy()) assert tuple(img_.shape) == (224, 224, 3) img_ = IDaRS.preproc(img.numpy()) assert tuple(img_.shape) == (224, 224, 3) # dummy to make runtime crash img_ = IDaRS.preproc(img.numpy() / 0.0) assert tuple(img_.shape) == (224, 224, 3)
723
25.814815
61
py
tiatoolbox
tiatoolbox-master/tests/models/test_arch_vanilla.py
"""Unit test package for vanilla CNN within toolbox.""" import numpy as np import pytest import torch from tiatoolbox.models.architecture.vanilla import CNNModel from tiatoolbox.utils.misc import model_to ON_GPU = False def test_functional(): """Test for creating backbone.""" backbones = [ "alexnet", "resnet18", "resnet34", "resnet50", "resnet101", "resnext50_32x4d", "resnext101_32x8d", "wide_resnet50_2", "wide_resnet101_2", "densenet121", "densenet161", "densenet169", "densenet201", "googlenet", "mobilenet_v2", "mobilenet_v3_large", "mobilenet_v3_small", ] assert CNNModel.postproc([1, 2]) == 1 b = 4 h = w = 512 samples = torch.from_numpy(np.random.rand(b, h, w, 3)) for backbone in backbones: try: model = CNNModel(backbone, num_classes=1) model_ = model_to(on_gpu=ON_GPU, model=model) model.infer_batch(model_, samples, on_gpu=ON_GPU) except ValueError: raise AssertionError(f"Model {backbone} failed.") # skipcq with pytest.raises(ValueError, match=r".*Backbone.*not supported.*"): CNNModel("shiny_model_to_crash", num_classes=2)
1,296
24.94
73
py
tiatoolbox
tiatoolbox-master/tests/models/test_arch_utils.py
"""Unit test package for architecture utilities""" import numpy as np import pytest import torch from tiatoolbox.models.architecture.utils import ( UpSample2x, centre_crop, centre_crop_to_shape, ) def test_all(): """Contains all tests for now.""" layer = UpSample2x() sample = np.array([[1, 2], [3, 4]])[..., None] batch = torch.from_numpy(sample)[None] batch = batch.permute(0, 3, 1, 2).type(torch.float32) output = layer(batch).permute(0, 2, 3, 1)[0].numpy() _output = np.array( [ [1, 1, 2, 2], [1, 1, 2, 2], [3, 3, 4, 4], [3, 3, 4, 4], ] ) assert np.sum(_output - output) == 0 # with pytest.raises(ValueError, match=r".*Unknown.*format.*"): centre_crop(_output[None, :, :, None], [2, 2], "NHWCT") x = centre_crop(_output[None, :, :, None], [2, 2], "NHWC") assert np.sum(x[0, :, :, 0] - sample) == 0 x = centre_crop(_output[None, None, :, :], [2, 2], "NCHW") assert np.sum(x[0, 0, :, :] - sample) == 0 def test_centre_crop_operators(): """Test for crop et. al. .""" sample = torch.rand((1, 3, 15, 15), dtype=torch.float32) output = centre_crop(sample, [3, 3], data_format="NCHW") assert torch.sum(output - sample[:, :, 1:13, 1:13]) == 0, f"{output.shape}" sample = torch.rand((1, 15, 15, 3), dtype=torch.float32) output = centre_crop(sample, [3, 3], data_format="NHWC") assert torch.sum(output - sample[:, 1:13, 1:13, :]) == 0, f"{output.shape}" # * x = torch.rand((1, 3, 15, 15), dtype=torch.float32) y = x[:, :, 6:9, 6:9] output = centre_crop_to_shape(x, y, data_format="NCHW") assert torch.sum(output - y) == 0, f"{output.shape}" x = torch.rand((1, 15, 15, 3), dtype=torch.float32) y = x[:, 6:9, 6:9, :] output = centre_crop_to_shape(x, y, data_format="NHWC") assert torch.sum(output - y) == 0, f"{output.shape}" with pytest.raises(ValueError, match=r".*Unknown.*format.*"): centre_crop_to_shape(x, y, data_format="NHWCT") x = torch.rand((1, 3, 15, 15), dtype=torch.float32) y = x[:, :, 6:9, 6:9] with pytest.raises(ValueError, match=r".*Height.*smaller than `y`*"): centre_crop_to_shape(y, x, data_format="NCHW")
2,272
31.942029
79
py
tiatoolbox
tiatoolbox-master/tests/models/test_abc.py
"""Unit test package for ABC and __init__ .""" import pytest from tiatoolbox import rcParam from tiatoolbox.models.architecture import get_pretrained_model from tiatoolbox.models.models_abc import ModelABC from tiatoolbox.utils import env_detection as toolbox_env @pytest.mark.skipif( toolbox_env.running_on_ci() or not toolbox_env.has_gpu(), reason="Local test on machine with GPU.", ) def test_get_pretrained_model(): """Test for downloading and creating pretrained models.""" pretrained_info = rcParam["pretrained_model_info"] for pretrained_name in pretrained_info.keys(): get_pretrained_model(pretrained_name, overwrite=True) def test_model_abc(): """Test API in model ABC.""" # test missing definition for abstract with pytest.raises(TypeError): # crash due to not defining forward, infer_batch, postproc ModelABC() # skipcq # intentionally created to check error # skipcq class Proto(ModelABC): # skipcq def __init__(self): super().__init__() @staticmethod # skipcq def infer_batch(): pass # base class definition pass # skipcq with pytest.raises(TypeError): # crash due to not defining forward and postproc Proto() # skipcq # intentionally create to check inheritance # skipcq class Proto(ModelABC): # skipcq def forward(self): pass # base class definition pass @staticmethod # skipcq def infer_batch(): pass # base class definition pass model = Proto() assert model.preproc(1) == 1, "Must be unchanged!" assert model.postproc(1) == 1, "Must be unchanged!" # intentionally created to check error # skipcq class Proto(ModelABC): # skipcq def __init__(self): super().__init__() @staticmethod # skipcq def postproc(image): return image - 2 # skipcq def forward(self): pass # base class definition pass @staticmethod # skipcq def infer_batch(): pass # base class definition pass model = Proto() # skipcq # test assign un-callable to preproc_func/postproc_func with pytest.raises(ValueError, match=r".*callable*"): model.postproc_func = 1 # skipcq: PYL-W0201 with pytest.raises(ValueError, match=r".*callable*"): model.preproc_func = 1 # skipcq: PYL-W0201 # test setter/getter/initial of preproc_func/postproc_func assert model.preproc_func(1) == 1 model.preproc_func = lambda x: x - 1 # skipcq: PYL-W0201 assert model.preproc_func(1) == 0 assert model.preproc(1) == 1, "Must be unchanged!" assert model.postproc(1) == -1, "Must be unchanged!" model.preproc_func = None # skipcq: PYL-W0201 assert model.preproc_func(2) == 2 # repeat the setter test for postproc assert model.postproc_func(2) == 0 model.postproc_func = lambda x: x - 1 # skipcq: PYL-W0201 assert model.postproc_func(1) == 0 assert model.preproc(1) == 1, "Must be unchanged!" assert model.postproc(2) == 0, "Must be unchanged!" # coverage setter check model.postproc_func = None # skipcq: PYL-W0201 assert model.postproc_func(2) == 0
3,319
29.740741
66
py
tiatoolbox
tiatoolbox-master/docs/conf.py
#!/usr/bin/env python # flake8: noqa # # tiatoolbox documentation build configuration file, created by # sphinx-quickstart on Fri Jun 9 13:47:02 2017. # # This file is execfile()d with the current directory set to its # containing dir. # # Note that not all possible configuration values are present in this # auto generated file. # # All configuration values have a default; values that are commented out # serve to show the default. # If extensions (or modules to document with autodoc) are in another # directory, add these directories to sys.path here. If the directory is # relative to the documentation root, use os.path.abspath to make it # absolute, like shown here. # import os import pathlib import shutil import sys sys.path.insert(0, os.path.abspath("..")) import tiatoolbox # noqa: E402 # -- General configuration --------------------------------------------- # If your documentation needs a minimal Sphinx version, state it here. # # requires sphinx = '1.0' # Add any Sphinx extension module names here, as strings. They can be # extensions coming with Sphinx (named 'sphinx.ext.*') or your custom ones. extensions = [ "sphinx.ext.autodoc", "sphinx.ext.autosummary", # Create neat summary tables "sphinx.ext.viewcode", "sphinx.ext.napoleon", "sphinx.ext.intersphinx", "sphinx.ext.mathjax", "sphinx_copybutton", "sphinx_toolbox.collapse", "myst_nb", "sphinx_design", ] autosummary_generate = True # Turn on sphinx.ext.autosummary autodoc_inherit_docstrings = False autoclass_content = "both" # Add __init__ doc (i.e., params) to class summaries # Remove 'view source code' from top of page (for html, not python) html_show_sourcelink = False # If no docstring, inherit from base class # ! only nice for our ABC but it looks ridiculous when inherit from # ! grand-nth ancestors autodoc_inherit_docstrings = False add_module_names = False # Remove namespaces from class/method signatures # Add any paths that contain templates here, relative to this directory. templates_path = ["_templates"] # The suffix(es) of source filenames. # You can specify multiple suffix as a list of string: # source_suffix = { ".rst": "restructuredtext", ".txt": "myst-nb", ".md": "myst-nb", ".ipynb": "myst-nb", ".myst": "myst-nb", } suppress_warnings = ["misc.highlighting_failure"] myst_commonmark_only = True myst_enable_extensions = ["colon_fence"] nb_execution_mode = "off" # The master toctree document. master_doc = "index" # General information about the project. project = "TIA Toolbox" copyright = "2023, TIA Lab" author = "TIA Lab" # The version info for the project you're documenting, acts as replacement # for |version| and |release|, also used in various other places throughout # the built documents. # # The short X.Y version. version = tiatoolbox.__version__ # The full version, including alpha/beta/rc tags. release = tiatoolbox.__version__ # The language for content autogenerated by Sphinx. Refer to documentation # for a list of supported languages. # # This is also used if you do content translation via gettext catalogs. # Usually you set "language" from the command line for these cases. language = "en" # List of patterns, relative to source directory, that match files and # directories to ignore when looking for source files. # These patterns also affect html_static_path and html_extra_path exclude_patterns = [ "_build", "Thumbs.db", ".DS_Store", "requirements/requirements*.txt", ] # The name of the Pygments (syntax highlighting) style to use. pygments_style = "sphinx" # If true, `todo` and `todoList` produce output, else they produce nothing. todo_include_todos = False # -- Options for HTML output ------------------------------------------- # The theme to use for HTML and HTML Help pages. See the documentation for # a list of builtin themes. # html_theme = "furo" html_title = f"TIA Toolbox {tiatoolbox.__version__} Documentation" # Theme options are theme-specific and customize the look and feel of a # theme further. For a list of options available for each theme, see the # documentation. # html_theme_options = { "navigation_with_keys": True, "top_of_page_button": None, "footer_icons": [ { "name": "TIA", "url": "https://warwick.ac.uk/fac/cross_fac/tia/", "html": """ <svg version="1.1" id="Layer_1" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" x="0px" y="0px" viewBox="0 0 173 175" style="enable-background:new 0 0 173 175;" xml:space="preserve"> <image style="overflow:visible;" width="519" height="525" xlink:href="data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAgcAAAINCAYAAACqOtxdAAABemlDQ1BJQ0MgUHJvZmlsZQAAKJF9 kE0rRFEYx38GjbxEsbCwuHlbDTFKbJSZNKYsNChvmzvXnRllrtudK2RjoWwVJTbeFnwCNhbKWilF Sna+ALGRrufMjMZLeeo5z+885zn/zvmDL6Db9lxJB6Qt14lFQtr4xKTmf8KHnxqqqNeNjN0/PDyE xFf9GW+3FKl606a0/p7/GxUzZsaAojLhPsN2XOFB4aZF11as9OoceZTwquJkjrcUx3N8kp0ZjYWF z4U1I6XPCD8IB4yUkwaf0m+Of5tJfuP03IKRf4/6SaVpjY1IbZRsIEOMCCE0ogwQpptOemXtpo0g 7bLDNZdcdTk8by87s8mUq/WLE6YWtYz2gBbsCMqM8vW3X4Xe/D70vELxRqEX34azdai/L/Sa96B6 DU4vbd3Rs61iSV8iAc/HUDUBtddQPpVJdAVzP6oMQemj5720gH8TPjY87/3A8z4O5bJ4dGHlPMpr cXQHoyswdAU7u9Aq2tXTn9MNZwWYZzn0AAAAeGVYSWZNTQAqAAAACAAFARIAAwAAAAEAAQAAARoA BQAAAAEAAABKARsABQAAAAEAAABSASgAAwAAAAEAAgAAh2kABAAAAAEAAABaAAAAAAAAANgAAAAB AAAA2AAAAAEAAqACAAQAAAABAAACB6ADAAQAAAABAAACDQAAAADINjxfAAAACXBIWXMAACE4AAAh OAFFljFgAAABWWlUWHRYTUw6Y29tLmFkb2JlLnhtcAAAAAAAPHg6eG1wbWV0YSB4bWxuczp4PSJh ZG9iZTpuczptZXRhLyIgeDp4bXB0az0iWE1QIENvcmUgNi4w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gBM2AGzIAZMANmwAyY ATNgBsyAGTADZsAMmAEzYAbMgBkwA2bADJgBM2AGzIAZMANmwAyYATNgBsyAGTADZsAMmAEzYAbM gBkwA2bADJgBM2AGzIAZMANmwAyYATNgBsyAGTADZsAMmAEzYAbMgBkwA2bADJgBM9AXA/8PWdS2 u3nWIdEAAAAASUVORK5CYII=" transform="matrix(0.3333 0 0 0.3333 0 0)"> </image> </svg> """, "class": "only-dark", }, { "name": "TIA", "url": "https://warwick.ac.uk/fac/cross_fac/tia/", "html": """ <svg version="1.1" id="Layer_1" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" x="0px" y="0px" viewBox="0 0 178 171.89" style="enable-background:new 0 0 178 171.89;" xml:space="preserve"> <image style="overflow:visible;" width="518" height="525" xlink:href="data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAgYAAAINCAYAAABF+LdjAAABfWlDQ1BJQ0MgUHJvZmlsZQAAKJF9 kM9LAkEUx7+uhVGGQR06dBjKOqnYBlKXQCVM8CBmkNVlXVcNdF12Nyq6dAi6CgVRl34d6i+oS4eg cxAERRDd+geKuoRsb1xDK+gNM+8zb958mfkCgk/StFJbECirpp6KRdhcZp65XiDAhR4aTJINLZxM JkDxnX/Gxz0cPN/5udbf83+jK6cYMuDoIJ6UNd0kniYeWjE1zlyvT6dHEW9wLti8wzlr81m9J52K El8SM7ko5YifiH1yUS8DAtf3Zlt6Ci1cLi3Ljffwn7gVdXaG8iDNARhIIYYIGOKYQhQhjGKC1hD8 EBGgHUxl1eSXoxVtTV8qFE0WJicUFlflgI+JQZF6uK+//WrWKofA+DvgrDZr2V3gYgvof2zWvAeA ZxM4v9YkXaqXnDSFfB54PQW6M0DvLdC5YOTHRPtH7gjQ/mxZb8OAaxuoVS3r88iyasd0mTy6Um2P Glo4eQDS60DiBtjbB0ZI27P4Bel2ZxC/xa5BAAAAeGVYSWZNTQAqAAAACAAFARIAAwAAAAEAAQAA ARoABQAAAAEAAABKARsABQAAAAEAAABSASgAAwAAAAEAAgAAh2kABAAAAAEAAABaAAAAAAAAANgA AAABAAAA2AAAAAEAAqACAAQAAAABAAACBqADAAQAAAABAAACDQAAAABPkPccAAAACXBIWXMAACE4 AAAhOAFFljFgAAABWWlUWHRYTUw6Y29tLmFkb2JlLnhtcAAAAAAAPHg6eG1wbWV0YSB4bWxuczp4 PSJhZG9iZTpuczptZXRhLyIgeDp4bXB0az0iWE1QIENvcmUgNi4wLjAiPgogICA8cmRmOlJERiB4 bWxuczpyZGY9Imh0dHA6Ly93d3cudzMub3JnLzE5OTkvMDIvMjItcmRmLXN5bnRheC1ucyMiPgog ICAgICA8cmRmOkRlc2NyaXB0aW9uIHJkZjphYm91dD0iIgogICAgICAgICAgICB4bWxuczp0aWZm PSJodHRwOi8vbnMuYWRvYmUuY29tL3RpZmYvMS4wLyI+CiAgICAgICAgIDx0aWZmOk9yaWVudGF0 aW9uPjE8L3RpZmY6T3JpZW50YXRpb24+CiAgICAgIDwvcmRmOkRlc2NyaXB0aW9uPgogICA8L3Jk ZjpSREY+CjwveDp4bXBtZXRhPgoZXuEHAABAAElEQVR4AexdCXwURdav6plMwimQSSYgSggBD1y8 j/VYkoAXXusBnoTggbpen3cSRKOSBBV1PdebAJ7geq83JHiuq+6uKKtAAogYkswEUK4kM931/SuA hpBjuqeP6pmqH0Nmuqvee/Wv7q7Xr957RYgsEgGJgERAIiARkAhIBCQCEgGJgERAIiARkAhIBCQC EgGJgERAIiARkAhIBCQCEgGJgERAIiARkAhIBCQCEgGJgERAIiARkAhIBCQCEgGJgERAIiARkAhI BCQCEgGJgERAIiARkAhIBCQCEgGJgERAIiARkAhIBCQCEgGJgERAIiARkAhIBCQCEgGJgERAIiAR kAhIBCQCEgGJgERAIiARkAhIBCQCEgGJgERAIiARkAhIBCQCEgGJgERAIiARkAhIBCQCEgGJgERA IiARkAhIBCQCEgGJgERAIiARkAhIBCQCEgGJgERAIiARkAhIBCQCEgGJgERAIiARkAhIBCQCEgGJ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HLsRYvxlr8WKtRWDidAgOc NwnZsBzQdA2//G3gKIOgUfgM61DnB7GtR3AeX7mRAAl4TYCKgdfEWR8JTJLAArEg3D2jptoxTiWi 9pVrBCmCYR0MHmU53qA4NuV4lVoDyJHvI8aQXq2cSECGPjxQYPA3HNwphpALfQoBnmw6DDRjWom+ sNCxIVnU03nk5CEhmp1JouBlJEACLhKgYuAiXBZNAn4TsC6g41KXqiIdEUMqqkIIhKRUVDj4lE5U aBWFQoFgSQrfTVTbY7sZFVc2uJIycaFlQoRM3NhPreMiJBPawXGRjushlSgV/af39Taf9rutrJ8E SIAESIAESIAESIAESIAESIAESIAESIAESIAESIAESIAESIAESIAESIAESIAESIAESIAESIAESIAE SIAESIAESIAESIAESIAESIAESIAESIAESIAESIAESIAESIAESIAESIAESIAESIAESIAESIAESIAE SIAESIAESIAESIAESIAESIAESIAESIAESIAESIAESIAESIAESIAESIAESIAESIAESIAESIAESIAE SIAESIAESIAESIAESIAESIAESIAESIAESIAESIAESIAESIAESIAESIAESIAESIAESIAESIAESIAE SIAESIAESIAESIAESIAESIAESIAESIAESIAESIAESIAESIAESIAESIAESIAESIAESIAESIAESIAE SIAESIAESIAESIAESIAESIAESIAESIAESIAESIAE0iPwfxKOnjvVcLCDAAAAAElFTkSuQmCC" transform="matrix(0.3333 0 0 0.3333 0 -3.11)"> </image> </svg> """, "class": "only-light", }, { "name": "GitHub", "url": "https://github.com/TissueImageAnalytics/tiatoolbox", "html": """ <svg height="32" aria-hidden="true" viewBox="0 0 16 16" version="1.1" width="32" data-view-component="true" class="octicon octicon-mark-github v-align-middle"> <path fill-rule="evenodd" d="M8 0C3.58 0 0 3.58 0 8c0 3.54 2.29 6.53 5.47 7.59.4.07.55-.17.55-.38 0-.19-.01-.82-.01-1.49-2.01.37-2.53-.49-2.69-.94-.09-.23-.48-.94-.82-1.13-.28-.15-.68-.52-.01-.53.63-.01 1.08.58 1.23.82.72 1.21 1.87.87 2.33.66.07-.52.28-.87.51-1.07-1.78-.2-3.64-.89-3.64-3.95 0-.87.31-1.59.82-2.15-.08-.2-.36-1.02.08-2.12 0 0 .67-.21 2.2.82.64-.18 1.32-.27 2-.27.68 0 1.36.09 2 .27 1.53-1.04 2.2-.82 2.2-.82.44 1.1.16 1.92.08 2.12.51.56.82 1.27.82 2.15 0 3.07-1.87 3.75-3.65 3.95.29.25.54.73.54 1.48 0 1.07-.01 1.93-.01 2.2 0 .21.15.46.55.38A8.013 8.013 0 0016 8c0-4.42-3.58-8-8-8z"></path> </svg> """, "class": "only-light", }, { "name": "GitHub", "url": "https://github.com/TissueImageAnalytics/tiatoolbox", "html": """ <svg height="32" aria-hidden="true" viewBox="0 0 16 16" version="1.1" width="32" data-view-component="true" class="octicon octicon-mark-github v-align-middle"> <path fill="#ffffff" fill-rule="evenodd" d="M8 0C3.58 0 0 3.58 0 8c0 3.54 2.29 6.53 5.47 7.59.4.07.55-.17.55-.38 0-.19-.01-.82-.01-1.49-2.01.37-2.53-.49-2.69-.94-.09-.23-.48-.94-.82-1.13-.28-.15-.68-.52-.01-.53.63-.01 1.08.58 1.23.82.72 1.21 1.87.87 2.33.66.07-.52.28-.87.51-1.07-1.78-.2-3.64-.89-3.64-3.95 0-.87.31-1.59.82-2.15-.08-.2-.36-1.02.08-2.12 0 0 .67-.21 2.2.82.64-.18 1.32-.27 2-.27.68 0 1.36.09 2 .27 1.53-1.04 2.2-.82 2.2-.82.44 1.1.16 1.92.08 2.12.51.56.82 1.27.82 2.15 0 3.07-1.87 3.75-3.65 3.95.29.25.54.73.54 1.48 0 1.07-.01 1.93-.01 2.2 0 .21.15.46.55.38A8.013 8.013 0 0016 8c0-4.42-3.58-8-8-8z"></path> </svg> """, "class": "only-dark", }, ], "announcement": "Paper available at " "<a href='https://doi.org/10.1038/s43856-022-00186-5'>" "https://doi.org/10.1038/s43856-022-00186-5</a>", } # Add any paths that contain custom static files (such as style sheets) here, # relative to this directory. They are copied after the builtin static files, # so a file named "default.css" will overwrite the builtin "default.css". html_static_path = [] # These paths are either relative to html_static_path # or fully qualified paths (eg. https://...) # html_css_files = [] # -- Options for HTMLHelp output --------------------------------------- # Output file base name for HTML help builder. htmlhelp_basename = "tiatoolboxdoc" # -- Options for LaTeX output ------------------------------------------ latex_elements = {} # Grouping the document tree into LaTeX files. List of tuples # (source start file, target name, title, author, documentclass # [howto, manual, or own class]). latex_documents = [ (master_doc, "tiatoolbox.tex", "TIA Toolbox Documentation", "TIA Lab", "manual"), ] # -- Options for manual page output ------------------------------------ # One entry per manual page. List of tuples # (source start file, name, description, authors, manual section). man_pages = [(master_doc, "tiatoolbox", "TIA Toolbox Documentation", [author], 1)] # -- Options for Tex info output ---------------------------------------- latex_engine = "xelatex" # Grouping the document tree into Tex info files. List of tuples # (source start file, target name, title, author, # dir menu entry, description, category) texinfo_documents = [ ( master_doc, "tiatoolbox", "TIA Toolbox Documentation", author, "tiatoolbox", "One line description of project.", "Miscellaneous", ), ] # -- Options for InterSphinx (Reference Other Docs) -------------------- intersphinx_mapping = { "python": ("https://docs.python.org/3", None), "numpy": ("https://numpy.org/doc/stable/", None), "scipy": ("https://docs.scipy.org/doc/scipy/", None), "matplotlib": ("https://matplotlib.org/stable/", None), "sklearn": ("https://scikit-learn.org/stable/", None), "torch": ("https://pytorch.org/docs/stable/", None), "click": ("https://click.palletsprojects.com/", None), "h5py": ("https://docs.h5py.org/en/latest/", None), "pandas": ("https://pandas.pydata.org/docs/", None), "Sphinx": ("https://www.sphinx-doc.org/en/stable/", None), } # create latex preamble so that we can build arbitrary nested depth fh = open("latex_preamble.tex", "r+") PREAMBLE = fh.read() fh.close() latex_elements = { # Additional stuff for the LaTeX preamble. "preamble": PREAMBLE, } # -- Options for autodoc ----------------------------------------------- autodoc_typehints = "description" autodoc_type_aliases = { "Iterable": "Iterable", "ArrayLike": "ArrayLike", } print("=" * 43) print("Copy example notebooks into docs/_notebooks") print("=" * 43) def all_but_ipynb(dir_path, contents): """Helper to copy all .ipynb""" result = [] for c in contents: flag = os.path.isfile(os.path.join(dir_path, c)) and (not c.endswith(".ipynb")) if flag: result += [c] return result DOC_ROOT = os.path.dirname(os.path.realpath(__file__)) PROJ_ROOT = pathlib.Path(DOC_ROOT).parent shutil.rmtree(os.path.join(PROJ_ROOT, "docs/_notebooks"), ignore_errors=True) shutil.copytree( os.path.join(PROJ_ROOT, "examples"), os.path.join(PROJ_ROOT, "docs/_notebooks/jnb"), ignore=all_but_ipynb, ) # shutil.copy( # os.path.join(PROJ_ROOT, "docs/notebooks.rst"), # os.path.join(PROJ_ROOT, "docs/_notebooks/notebooks.rst"), # ) # Read in the file with open("../examples/README.md", "r") as file: file_data = file.read() # Replace the target string file_data = file_data.replace(".rst", ".html") file_data = file_data.replace(".ipynb", ".html") file_data = file_data.replace("../docs/", "../") file_data = file_data.replace("](./", "](./jnb/") # Write the file out again with open("_notebooks/README.md", "w") as file: file.write(file_data)
170,772
83.332346
641
py
tiatoolbox
tiatoolbox-master/pre-commit/notebook_urls.py
"""Simple check to ensure each code cell in a notebook is valid Python.""" import argparse import json import re import subprocess import sys from dataclasses import dataclass from pathlib import Path from typing import List, Set, Tuple def git_branch_name() -> str: """Get the current branch name.""" return ( subprocess.check_output(["/usr/bin/git", "rev-parse", "--abbrev-ref", "HEAD"]) .decode() .strip() ) def git_branch_modified_paths(from_ref: str, to_ref: str) -> Set[Path]: """Get a set of file paths modified on this branch vs develop.""" from_to = f"{from_ref}...{to_ref}" return { Path(p) for p in subprocess.check_output( [ "/usr/bin/git", "diff", "--name-only", from_to, ] ) .decode() .strip() .splitlines() } def git_previous_commit_modified_paths() -> Set[Path]: """Get a set of file paths modified in the previous commit.""" return { Path(p) for p in subprocess.check_output( ["/usr/bin/git", "diff", "--name-only", "HEAD~"] ) .decode() .strip() .splitlines() } @dataclass(frozen=True) class PatternReplacement: """Replacement dataclass. Attributes: pattern: Regex pattern to match. replacement: Replacement string. main_replacement: Replacement string for main branch. """ pattern: str replacement: str main_replacement: str = None MAIN_BRANCHES = ("master", "main") def main(files: List[Path], from_ref: str, to_ref: str) -> bool: """Check that URLs in the notebook are relative to the current branch. Args: files: List of files to check. from_ref: Reference to diff from. to_ref: Reference to diff to. """ replacements = [ PatternReplacement( pattern=( r"(^\s*[!%]\s*)pip install " r"(git\+https://github\.com/TissueImageAnalytics/" r"tiatoolbox\.git@[\S]*|tiatoolbox)" ), replacement=( r"\1pip install " f"git+https://github.com/TissueImageAnalytics/tiatoolbox.git@{to_ref}" ), main_replacement=r"\1pip install tiatoolbox", ), PatternReplacement( pattern=( r"https://github\.com/TissueImageAnalytics/tiatoolbox/(blob|tree)/" r"(.*)" r"/examples/(.*)\.ipynb\)\\]" r"\\\[\[Colab]" ), replacement=( r"https://github.com/TissueImageAnalytics/tiatoolbox/blob/" f"{to_ref}" r"/examples/\g<3>.ipynb)\\]" r"\\[[Colab]" ), main_replacement=( r"https://github.com/TissueImageAnalytics/tiatoolbox/blob/" f"{to_ref}" r"/examples/\g<3>.ipynb)\\]" r"\\[[Colab]" ), ), PatternReplacement( pattern=( r"https://colab.research.google.com/" r"github/TissueImageAnalytics/tiatoolbox/(blob|tree)/" r"(.*)" r"/examples/(.*)\.ipynb" ), replacement=( r"https://colab.research.google.com/" r"github/TissueImageAnalytics/tiatoolbox/blob/" f"{to_ref}" r"/examples/\g<3>.ipynb" ), main_replacement=( r"https://colab.research.google.com/" r"github/TissueImageAnalytics/tiatoolbox/blob/" f"{to_ref}" r"/examples/\g<3>.ipynb" ), ), ] passed = True print(f"From ref '{from_ref}' to ref '{to_ref}'") for path in files: if path.suffix != ".ipynb": print(f"Skipping {path} (not a Jupyter Notebook).") return passed changed, notebook = check_notebook(path, to_ref, replacements) passed = passed and not changed # Write the file if it has changed if changed: print(f"Updating {path}") with open(path, "w", encoding="utf-8") as fh: json.dump(notebook, fh, indent=1, ensure_ascii=False) fh.write("\n") else: print(f"Skipping {path} (no changes).") return passed def check_notebook( path: Path, to_ref: str, replacements: List[PatternReplacement] ) -> Tuple[bool, dict]: """Check the notebook for URL replacements. Args: path: Path to notebook. to_ref: Reference to diff to. replacements: List of replacements to perform. Returns: Tuple of whether the file was changed and the notebook object. """ project_root = Path(__file__).parent.parent changed = False # Check if the path is inside the project root if project_root.resolve() not in list(path.resolve().parents): print(f"\nSkipping {path} (not inside the project directory)") return changed, None # Load the notebook with open(path, encoding="utf-8") as fh: notebook = json.load(fh) # Check each cell for cell_num, cell in enumerate(notebook["cells"]): # Check each line for line_num, line in enumerate(cell["source"]): new_line = replace_line(line, to_ref, replacements) if new_line != line: print(f"{path.name}: Changed (cell {cell_num+1}, line {line_num+1})") changed = True cell["source"][line_num] = new_line return changed, notebook def replace_line(line: str, to_ref: str, replacements: List[PatternReplacement]) -> str: """Perform pattern replacements in the line. Args: line: Line to replace. to_ref: Reference to diff to. replacements: List of replacements to perform. """ for rep in replacements: if re.search(rep.pattern, line): # Replace matches if to_ref in MAIN_BRANCHES: line = re.sub(rep.pattern, rep.main_replacement, line) else: line = re.sub(rep.pattern, rep.replacement, line) print(line) return line if __name__ == "__main__": parser = argparse.ArgumentParser(description="Check notebook URLs") parser.add_argument( "files", nargs="+", help="Path to notebook(s)", type=Path, default=list(Path.cwd().rglob("*.ipynb")), ) parser.add_argument( "-f", "--from-ref", help="Reference to diff from", type=str, default="develop" ) parser.add_argument( "-t", "--to-ref", help="Reference to diff to", type=str, default=git_branch_name(), ) args = parser.parse_args() sys.exit(main(args.files, args.from_ref, args.to_ref))
7,127
28.213115
88
py
tiatoolbox
tiatoolbox-master/pre-commit/missing_imports.py
"""Static analysis of requirements files and import statements. Imports which are not found in the requirements files are considered bad. Any found bad imports will be printed and the script will exit with a non-zero status. """ import argparse import ast import importlib import os import sys import tokenize from pathlib import Path from typing import Dict, List, Tuple, Union from requirements_consistency import parse_requirements # Mapping from package name (pip/anaconda) to import name # This is to avoid pinging PyPI KNOWN_ALIASES = { "pillow": ["PIL"], "umap-learn": ["umap"], "pyyaml": ["yaml"], "openslide-python": ["openslide"], "opencv-python": ["cv2"], "opencv": ["cv2"], "setuptools": ["setuptools", "pkg_resources"], "scikit-learn": ["sklearn"], "scikit-image": ["skimage"], "pytorch": ["torch"], "ipython": ["IPython"], } REQUIREMENTS_FILES = ( "requirements/requirements.txt", "requirements/requirements_dev.txt", "requirements/requirements.conda.yml", "requirements/requirements.dev.conda.yml", "requirements/requirements.win64.conda.yml", "setup.py", ) def find_source_files(base_dir: Path) -> List[Path]: """Recursively find all source files in the given directory. Args: base_dir (Path): Path to the directory to find source files in. Returns: list: List of paths to source files. """ ignore = ["venv", "build", "dist", "__pycache__"] source_files = [] for root, dirs, files in os.walk(base_dir): dirs[:] = [d for d in dirs if not (d in ignore or d[0] in (".", "_"))] files = [f for f in files if f.endswith(".py") and f[0] not in (".",)] source_files.extend(Path(root) / f for f in files) return source_files def find_imports(py_source_path: Path) -> List[str]: """Find all imports in the given Python source file. Args: py_source_path (Path): Path to the Python source file. Returns: list: List of AST import nodes (ast.Import or ast.ImportFrom) in the file. """ with open( # This file could be any python file anywhere, skipcq py_source_path, "r" ) as fh: source = fh.read() tree = ast.parse(source) return [ node for node in ast.walk(tree) if isinstance(node, (ast.Import, ast.ImportFrom)) ] def std_spec(fullname: str) -> str: """Return True if in the standard library or a built-in. Args: fullname (str): Full name of the module. Returns: str: True if the name is in the standard library or a built-in. """ if fullname in sys.builtin_module_names: return True path_finder = importlib.machinery.PathFinder() spec = path_finder.find_spec(fullname) if spec is None: return False origin = Path(spec.origin) return "site-packages" not in origin.parts and "dist-packages" not in origin.parts def stems(node: Union[ast.Import, ast.ImportFrom]) -> List[Tuple[str, str]]: """Return the stem of each alias in the given import node. Args: node (ast.Import or ast.ImportFrom): Import node to get stems from. Returns: list: List of tuples of the alias name and the stem. """ if isinstance(node, ast.Import): return [(alias.name, alias.name.split(".")[0]) for alias in node.names] if isinstance(node, ast.ImportFrom): return [(node.module, node.module.split(".")[0])] raise TypeError( f"Unexpected node type: {type(node)}. Should be ast.Import or ast.ImportFrom." ) def main(): """Main entry point.""" parser = argparse.ArgumentParser( description="Static analysis of requirements files and import statements." ) parser.add_argument( "files", nargs="*", help=( "Paths to source files to check. If not specified, all files in" " the tiatoolbox directory are checked." ), type=Path, ) args = parser.parse_args() root = Path(__file__).parent.parent source_root = root / "tiatoolbox" requirements_paths = [root / name for name in REQUIREMENTS_FILES] source_files = args.files or find_source_files(source_root) passed = True for req_path in requirements_paths: bad_imports = find_bad_imports(root, source_files, req_path) if bad_imports: passed = False sys.exit(1 - passed) def find_bad_imports( root: Path, source_files: List[Path], requirements_path: Path ) -> List[Tuple[Union[ast.Import, ast.ImportFrom], ast.alias]]: """Find bad imports in the given requirements file. Args: root (pathlib.Path): Root directory of the project. source_root (pathlib.Path): Root directory of the source code. requirements_path (pathlib.Path): Path to the requirements file. Returns: list: List of bad imports as tuples of the import AST node and the alias. """ result = [] # Parse the requirements file reqs = parse_requirements(requirements_path) # Apply the mapping from known package names to import names req_imports = {subkey for key in reqs for subkey in KNOWN_ALIASES.get(key, [key])} for path in source_files: file_import_nodes = find_imports(path) # Mapping of import alias names and stems to nodes stem_to_node_alias: Dict[Tuple[ast.alias, str], ast.Import] = { stem: (node, alias) for node in file_import_nodes for alias, stem in stems(node) if not std_spec(stem) } bad_imports = { stem: (node, alias) for stem, (node, alias) in stem_to_node_alias.items() if stem not in req_imports.union({"tiatoolbox"}) } if bad_imports: for stem, (node, alias) in bad_imports.items(): # Tokenize the line to check for noqa comments comments = find_comments(path, node.lineno) if "# noqa" in comments: continue result.append((node, alias)) print( f"{path.relative_to(root)}:{node.lineno}:" f" Import not in {requirements_path.name}:" f" {stem}" + (f" ({alias})" if alias != stem else "") ) return result def find_comments(path, line_num: int): """Find comments on the given line. Args: path: Path to the file. line_num: Line number to find comments on. Returns: list: List of comments on the line. """ with open(path, "rb") as fh: # This file could be any python file anywhere, skipcq tokens = tokenize.tokenize(fh.readline) return [ t.string for t in tokens if t.type == tokenize.COMMENT and t.start[0] == line_num ] if __name__ == "__main__": main()
7,134
28.605809
87
py
tiatoolbox
tiatoolbox-master/pre-commit/notebook_check_ast.py
"""Simple check to ensure each code cell in a notebook is valid Python.""" import argparse import ast import json import sys from pathlib import Path from typing import List def main(files: List[Path]) -> bool: """Check each file in the list of files for valid Python.""" passed = True for path in files: with open(path, encoding="utf-8") as fh: notebook = json.load(fh) for n, cell in enumerate(notebook["cells"]): if cell["cell_type"] != "code": continue source = "".join([x for x in cell["source"] if x[0] not in r"#%!"]) try: ast.parse(source) except SyntaxError as e: passed = False print(f"{path.name}: {e.msg} (cell {n}, line {e.lineno})") break return passed # noqa: R504 if __name__ == "__main__": parser = argparse.ArgumentParser(description="Check notebook AST") parser.add_argument("files", nargs="+", help="Path to notebook(s)", type=Path) args = parser.parse_args() sys.exit(1 - main(args.files))
1,104
31.5
82
py
tiatoolbox
tiatoolbox-master/pre-commit/notebook_markdown_format.py
"""Check markdown cells in notebooks for common mistakes.""" from __future__ import annotations import argparse import copy import json from pathlib import Path from typing import Any, Dict, List import mdformat def format_notebook(notebook: Dict[str, Any]) -> Dict[str, Any]: """Format a notebook in MyST style. Args: notebook (dict): A notebook dictionary (parsed from JSON). Returns: dict: The notebook dictionary with the markdown cells formatted. """ for cell in notebook["cells"]: if cell.get("cell_type") != "markdown": continue cell["source"] = [ f"{line}\n" for line in mdformat.text( "".join(cell["source"]), extensions={"myst"}, codeformatters={"python"}, ).split("\n") ] return notebook def main(files: List[Path]) -> None: """Check markdown cells in notebooks for common mistakes. Args: files (list): A list of notebook files to check. Returns: bool: True if all notebooks pass, False otherwise. """ for path in files: notebook = json.loads(path.read_text()) formatted_notebook = format_notebook(copy.deepcopy(notebook)) changed = any( cell != formatted_cell for cell, formatted_cell in zip( notebook["cells"], formatted_notebook["cells"] ) ) if not changed: continue print("Formatting notebook", path) with open(path, "w") as fh: json.dump(formatted_notebook, fh, indent=1, ensure_ascii=False) fh.write("\n") if __name__ == "__main__": parser = argparse.ArgumentParser(description="Lint notebook markdown files.") parser.add_argument( "files", nargs="*", help="Notebook markdown files to lint.", type=Path ) args = parser.parse_args() main(sorted(args.files))
2,004
25.733333
81
py
tiatoolbox
tiatoolbox-master/pre-commit/requirements_consistency.py
"""Test for ensuring that requirements files are valid and consistent.""" import importlib import sys from pathlib import Path from typing import Dict, List, Tuple import yaml from pkg_resources import Requirement REQUIREMENTS_FILES = [ ("requirements/requirements.txt", "requirements/requirements_dev.txt"), ("requirements/requirements.conda.yml", "requirements/requirements.dev.conda.yml"), ("requirements/requirements.win64.conda.yml", None), ("docs/requirements.txt", None), ("setup.py", None), ] def parse_pip( file_path: Path = None, lines: List[str] = None ) -> Dict[str, Requirement]: """Parse a pip requirements file. Note that package names are case insensitive and underscores and dashes are considered equivalent. Args: file_path (pathlib.Path): Path to the requirements file. lines (list): List of lines to parse. Returns: dict: A dictionary mapping package names to :class:`pkg_resources.Requirement`. """ if lines and file_path: raise ValueError("Only one of file_path or lines may be specified") if not lines: with file_path.open("r") as fh: lines = fh.readlines() packages = {} for line in lines: line = line.strip() # Skip comment lines if line.startswith("#"): continue # Skip blank lines if not line: continue # Parse requirement requirement = Requirement.parse(line) # Check for duplicate packages if requirement.key in packages: raise ValueError( f"Duplicate dependency: {requirement.name} in {file_path.name}" ) packages[requirement.key] = requirement return packages def parse_conda(file_path: Path) -> Dict[str, Requirement]: """Parse a conda requirements file. Args: file_path (pathlib.Path): Path to the requirements file. Returns: dict: A dictionary mapping package names to :class:`pkg_resources.Requirement`. """ with file_path.open("r") as fh: config = yaml.safe_load(fh) dependencies: List[str] = config["dependencies"] packages = {} for dependency in dependencies: # pip-style dependency if isinstance(dependency, dict): pip = parse_pip(lines=dependency["pip"]) for package_name, requirement in pip.items(): packages[package_name] = requirement continue requirement = Requirement.parse(dependency) # Check for duplicate packages if requirement.key in packages: raise ValueError( f"Duplicate dependency: {requirement.key} in {file_path.name}" ) packages[requirement.key] = requirement return packages def parse_setup_py(file_path) -> Dict[str, Requirement]: """Parse a setup.py file. Args: file_path (pathlib.Path): Path to the setup.py file. Returns: dict: A dictionary mapping package names to pkg_resources.Requirement. """ mock_setup = {} import setuptools setuptools.setup = lambda **kw: mock_setup.update(kw) spec = importlib.util.spec_from_file_location("setup", str(file_path)) setup = importlib.util.module_from_spec(spec) spec.loader.exec_module(setup) del setup, setuptools # skipcq requirements = mock_setup.get("install_requires", []) return parse_pip(lines=requirements) def test_files_exist(root_dir: Path) -> None: """Test that all requirements files exist. Args: root_dir (pathlib.Path): Path to the root directory of the project. Raises: FileNotFoundError: If a requirements file is missing. """ for sub_name, super_name in REQUIREMENTS_FILES: sub_path = root_dir / sub_name if not sub_path.exists(): raise FileNotFoundError(f"Missing file: {sub_path}") if super_name: super_path = root_dir / super_name if not super_path.exists(): raise FileNotFoundError(f"Missing file: {super_path}") def parse_requirements( file_path: Path = None, lines: List[str] = None ) -> Dict[str, Tuple[str, Tuple[str, ...], str]]: """Parse a requirements file (pip or conda). Args: file_path (pathlib.Path): Path to the requirements file. lines (list): List of lines to parse. Returns: dict: A dictionary mapping package names to pkg_resources.Requirement. """ if lines and file_path: raise ValueError("Only one of file_path or lines may be specified") if file_path.name == "setup.py": return parse_setup_py(file_path) if file_path.suffix == ".yml": return parse_conda(file_path) if file_path.suffix == ".txt": return parse_pip(file_path, lines) raise ValueError(f"Unsupported file type: {file_path.suffix}") def in_common_consistent(all_requirements: Dict[Path, Dict[str, Requirement]]) -> bool: """Test that in-common requirements are consistent. Args: all_requirements (dict): Dictionary mapping requirements files to dictionaries mapping package names to pkg_resources.Requirement. Returns: bool: True if the requirements are consistent. """ consistent = True # Check that requirements are consistent across files # First find a set of all requirement keys requirement_key_sets = [set(x.keys()) for x in all_requirements.values()] requirement_keys = requirement_key_sets[0].union(*requirement_key_sets[1:]) # Iterate over the keys for key in requirement_keys: # Find the specs for the requirement and which files it is in zipped_file_specs = [ ( path, *( # Unpack the (constraint, version) tuple requirements[key].specs[0] # Get the first spec if requirements[key].specs # Check that there are specs else ("", "None") # Default if no specs ), ) for path, requirements in all_requirements.items() if key in requirements # Filter out files that don't have the key ] # Unzip the specs to get a list of constraints and versions _, constraints, versions = zip(*zipped_file_specs) # Check that the constraints and versions are the same across files formatted_reqs = [f"{c}{v} ({p.name})" for p, c, v in zipped_file_specs] if any(x != constraints[0] for x in constraints): print( f"{key} has inconsistent constraints:" f" {', '.join(formatted_reqs)}." ) consistent = False if any(x != versions[0] for x in versions): print(f"{key} has inconsistent versions:" f" {', '.join(formatted_reqs)}.") consistent = False return consistent # noqa: R504 def main(): """Main entry point for the hook.""" root = Path(__file__).parent.parent test_files_exist(root) passed = True # Keep track of all parsed files all_requirements: Dict[Path, Dict[str, Requirement]] = {} # Check that packages in main are also in super (dev) for sub_name, super_name in REQUIREMENTS_FILES: # Get the main requirements sub_path = root / sub_name sub_reqs = parse_requirements(sub_path) all_requirements[sub_path] = sub_reqs # Skip comparison if there is no superset (dev) file if not super_name: continue # Get the superset of (dev) requirements super_path = root / super_name super_reqs = parse_requirements(super_path) all_requirements[super_path] = super_reqs # Check that all sub requirements are in the super (dev) file sub_keys = set(sub_reqs.keys()) super_keys = set(super_reqs.keys()) super_missing = sub_keys - super_keys if super_missing: # sub is not a subset of super print(f"{super_name} is missing {', '.join(super_missing)} from {sub_name}") passed = False passed &= in_common_consistent(all_requirements) if not passed: sys.exit(1) print("All tests passed") sys.exit(0) if __name__ == "__main__": main()
8,534
30.611111
88
py
tiatoolbox
tiatoolbox-master/tiatoolbox/__main__.py
"""__main__ file invoked with `python -m tiatoolbox` command""" from tiatoolbox.cli import main main()
105
16.666667
63
py
tiatoolbox
tiatoolbox-master/tiatoolbox/tiatoolbox.py
"""Main module."""
19
9
18
py
tiatoolbox
tiatoolbox-master/tiatoolbox/__init__.py
"""Top-level package for TIA Toolbox.""" import importlib.util import os import sys from pathlib import Path import pkg_resources import yaml __author__ = """TIA Lab""" __email__ = "[email protected]" __version__ = "1.4.0" # This will set the tiatoolbox external data # default to be the user home folder, should work on both Window and Unix/Linux # C:\Users\USER\.tiatoolbox # /home/USER/.tiatoolbox # Initialize internal logging facilities, such that models etc. # can have reporting mechanism, may need to change protocol import logging # We only create a logger if root has no handler to prevent overwriting use existing # logging logging.captureWarnings(True) if not logging.getLogger().hasHandlers(): formatter = logging.Formatter( "|%(asctime)s.%(msecs)03d| [%(levelname)s] %(message)s", datefmt="%Y-%m-%d|%H:%M:%S", ) stdout_handler = logging.StreamHandler(sys.stdout) stdout_handler.setFormatter(formatter) stdout_handler.addFilter(lambda record: record.levelno <= logging.INFO) stderr_handler = logging.StreamHandler() stderr_handler.setFormatter(formatter) stderr_handler.setLevel(logging.WARNING) logger = logging.getLogger() # get root logger logger.setLevel(logging.INFO) logger.addHandler(stdout_handler) logger.addHandler(stderr_handler) else: logger = logging.getLogger() class DuplicateFilter(logging.Filter): def filter(self, record): current_log = (record.module, record.levelno, record.msg) if current_log != getattr(self, "last_log", None): self.last_log = current_log return True return False # runtime context parameters rcParam = {"TIATOOLBOX_HOME": os.path.join(os.path.expanduser("~"), ".tiatoolbox")} # Load a dictionary of sample files data (names and urls) PRETRAINED_FILES_REGISTRY_PATH = pkg_resources.resource_filename( "tiatoolbox", "data/pretrained_model.yaml" ) with open(PRETRAINED_FILES_REGISTRY_PATH) as registry_handle: PRETRAINED_INFO = yaml.safe_load(registry_handle) rcParam["pretrained_model_info"] = PRETRAINED_INFO def _lazy_import(name: str, module_location: Path): spec = importlib.util.spec_from_file_location(name, module_location) loader = importlib.util.LazyLoader(spec.loader) spec.loader = loader module = importlib.util.module_from_spec(spec) sys.modules[name] = module loader.exec_module(module) return module if __name__ == "__main__": print("tiatoolbox version:" + str(__version__)) location = Path(__file__).parent annotation = _lazy_import("annotation", location) models = _lazy_import("models", location) tiatoolbox = _lazy_import("tiatoolbox", location) tools = _lazy_import("tools", location) utils = _lazy_import("utils", location) wsicore = _lazy_import("wsicore", location)
2,853
31.431818
84
py
tiatoolbox
tiatoolbox-master/tiatoolbox/cli/show_wsi.py
"""Command line interface for TileServer""" import click from tiatoolbox.cli.common import cli_img_input, cli_name, tiatoolbox_cli @tiatoolbox_cli.command() @cli_img_input(usage_help="Path to an image to be displayed.", multiple=True) @cli_name(usage_help="Name to be assigned to a layer.", multiple=True) @click.option( "--colour-by", "-c", default=None, help="""A property to colour by. Must also define a colour map if this option is used, using --colour-map (or -m). Will only affect layers rendered from a store.""", ) @click.option( "--colour-map", "-m", default=None, help="""A colour map to use. Must be a matplotlib colour map string or 'categorical' (random colours will be generated for each possible value of property).""", ) def show_wsi(img_input, name, colour_by, colour_map): # pragma: no cover """Show a slide together with any overlays.""" from tiatoolbox.utils.visualization import AnnotationRenderer from tiatoolbox.visualization.tileserver import TileServer renderer = AnnotationRenderer() if colour_by is not None: if colour_map is None: raise ValueError( "If colouring by a property, must also define a colour map." ) renderer = AnnotationRenderer(score_prop=colour_by, mapper=colour_map) if len(img_input) == 0: raise ValueError("At least one image path must be provided.") if len(name) == 0: app = TileServer("TileServer", list(img_input), renderer=renderer) elif len(name) == len(img_input): app = TileServer("TileServer", dict(zip(name, img_input)), renderer=renderer) else: raise ( ValueError("if names are provided, must match the number of paths provided") ) app.run(threaded=False)
1,816
34.627451
88
py
tiatoolbox
tiatoolbox-master/tiatoolbox/cli/slide_info.py
"""Command line interface for slide_info.""" import logging import pathlib from tiatoolbox import logger from tiatoolbox.cli.common import ( cli_file_type, cli_img_input, cli_mode, cli_output_path, cli_verbose, prepare_file_dir_cli, tiatoolbox_cli, ) @tiatoolbox_cli.command() @cli_img_input() @cli_output_path( usage_help="Path to output directory to save the output. " "default=img_input/../meta-data" ) @cli_file_type(default="*.ndpi, *.svs, *.mrxs, *.jp2") @cli_mode(default="show") @cli_verbose(default=False) def slide_info(img_input, output_path, file_types, mode, verbose): """Displays or saves WSI metadata depending on the mode argument.""" from tiatoolbox import utils, wsicore files_all, output_path = prepare_file_dir_cli( img_input, output_path, file_types, mode, "meta-data" ) for curr_file in files_all: curr_file = pathlib.Path(curr_file) wsi = wsicore.wsireader.WSIReader.open(input_img=curr_file) if verbose: logger.setLevel(logging.DEBUG) logger.debug(curr_file.name) if mode == "show": logger.info(wsi.info.as_dict()) if mode == "save": out_path = pathlib.Path( output_path, wsi.info.file_path.with_suffix(".yaml").name ) utils.misc.save_yaml( wsi.info.as_dict(), out_path, ) logger.info("Meta files saved at %s.", str(output_path))
1,510
26.981481
73
py
tiatoolbox
tiatoolbox-master/tiatoolbox/cli/save_tiles.py
"""Command line interface for save_tiles.""" import logging from tiatoolbox import logger from tiatoolbox.cli.common import ( cli_file_type, cli_img_input, cli_output_path, cli_tile_format, cli_tile_objective, cli_tile_read_size, cli_verbose, prepare_file_dir_cli, tiatoolbox_cli, ) @tiatoolbox_cli.command() @cli_img_input() @cli_output_path( usage_help="Path to output directory to save the output.", default="tiles" ) @cli_file_type() @cli_tile_objective() @cli_tile_read_size() @cli_tile_format() @cli_verbose(default=False) def save_tiles( img_input, output_path, file_types, tile_objective_value, tile_read_size, tile_format, verbose=False, ): """Display or save WSI metadata.""" from tiatoolbox.wsicore.wsireader import WSIReader files_all, output_path = prepare_file_dir_cli( img_input, output_path, file_types, "save", "tiles" ) if verbose: logger.setLevel(logging.DEBUG) for curr_file in files_all: wsi = WSIReader.open(curr_file) wsi.save_tiles( output_dir=output_path, tile_objective_value=tile_objective_value, tile_read_size=tile_read_size, tile_format=tile_format, )
1,267
22.481481
78
py
tiatoolbox
tiatoolbox-master/tiatoolbox/cli/stain_norm.py
"""Command line interface for stain_norm.""" import os import click from tiatoolbox.cli.common import ( cli_file_type, cli_img_input, cli_method, cli_output_path, prepare_file_dir_cli, tiatoolbox_cli, ) @tiatoolbox_cli.command() @cli_img_input( usage_help="Input path to the source image or a directory of source images." ) @cli_output_path(default="stainnorm_output") @cli_file_type(default="*.png, *.jpg, *.tif, *.tiff") @cli_method( usage_help="Stain normalization method to use.", default="reinhard", input_type=click.Choice( ["reinhard", "custom", "ruifrok", "macenko", "vahadane"], case_sensitive=False ), ) # inputs specific to this function @click.option("--target-input", help="Input path to the target image") @click.option( "--stain-matrix", help="stain matrix to use in custom normalizer. This can either be a numpy array" ", a path to a npy file or a path to a csv file. If using a path to a csv file, " "there must not be any column headers.", default=None, ) def stain_norm(img_input, target_input, method, stain_matrix, output_path, file_types): """Stain normalize an input image/directory of input images.""" from tiatoolbox.tools import stainnorm as sn from tiatoolbox.utils.misc import imread, imwrite files_all, output_path = prepare_file_dir_cli( img_input, output_path, file_types, "save", "stainnorm_output" ) # init stain normalization method norm = sn.get_normalizer(method, stain_matrix) # get stain information of target image norm.fit(imread(target_input)) for curr_file in files_all: basename = os.path.basename(curr_file) # transform source image transform = norm.transform(imread(curr_file)) imwrite(os.path.join(output_path, basename), transform)
1,839
30.724138
87
py
tiatoolbox
tiatoolbox-master/tiatoolbox/cli/read_bounds.py
"""Command line interface for read_bounds.""" import pathlib from tiatoolbox.cli.common import ( cli_img_input, cli_mode, cli_output_path, cli_region, cli_resolution, cli_units, no_input_message, tiatoolbox_cli, ) @tiatoolbox_cli.command() @cli_img_input(usage_help="Path to WSI file.") @cli_output_path( usage_help="Path to output file in save mode. " "default=img_input_dir/../im_region.jpg" ) @cli_region( usage_help="Image region in the whole slide image to read from. " "default=0 0 2000 2000" ) @cli_resolution() @cli_units() @cli_mode(default="show") def read_bounds(img_input, region, resolution, units, output_path, mode): """Read a region in a whole slide image as specified.""" from PIL import Image from tiatoolbox.utils.misc import imwrite from tiatoolbox.wsicore.wsireader import WSIReader no_input_message(input_file=img_input) if not region: region = [0, 0, 2000, 2000] if output_path is None and mode == "save": input_dir = pathlib.Path(img_input).parent output_path = str(input_dir.parent / "im_region.jpg") wsi = WSIReader.open(input_img=img_input) im_region = wsi.read_bounds( region, resolution=resolution, units=units, ) if mode == "show": # pragma: no cover # Skipped on CI, and unless SHOW_TESTS is set im_region = Image.fromarray(im_region) im_region.show() return # the only other option left for mode is "save". imwrite(output_path, im_region)
1,562
25.05
73
py
tiatoolbox
tiatoolbox-master/tiatoolbox/cli/nucleus_instance_segment.py
"""Command line interface for nucleus instance segmentation.""" import click from tiatoolbox.cli.common import ( cli_auto_generate_mask, cli_batch_size, cli_file_type, cli_img_input, cli_masks, cli_mode, cli_num_loader_workers, cli_num_postproc_workers, cli_on_gpu, cli_output_path, cli_pretrained_model, cli_pretrained_weights, cli_verbose, cli_yaml_config_path, prepare_ioconfig_seg, prepare_model_cli, tiatoolbox_cli, ) @tiatoolbox_cli.command() @cli_img_input() @cli_output_path( usage_help="Output directory where model predictions will be saved.", default="nucleus_instance_segmentation", ) @cli_file_type( default="*.png, *.jpg, *.jpeg, *.tif, *.tiff, *.svs, *.ndpi, *.jp2, *.mrxs" ) @cli_mode( usage_help="Type of input file to process.", default="wsi", input_type=click.Choice(["patch", "wsi", "tile"], case_sensitive=False), ) @cli_pretrained_model(default="hovernet_fast-pannuke") @cli_pretrained_weights(default=None) @cli_on_gpu() @cli_batch_size() @cli_masks(default=None) @cli_yaml_config_path(default=None) @cli_num_loader_workers() @cli_verbose() @cli_num_postproc_workers(default=0) @cli_auto_generate_mask(default=False) def nucleus_instance_segment( pretrained_model, pretrained_weights, img_input, file_types, masks, mode, output_path, batch_size, yaml_config_path, num_loader_workers, num_postproc_workers, auto_generate_mask, on_gpu, verbose, ): """Process an image/directory of input images with a patch classification CNN.""" from tiatoolbox.models.engine.nucleus_instance_segmentor import ( IOSegmentorConfig, NucleusInstanceSegmentor, ) from tiatoolbox.utils.misc import save_as_json files_all, masks_all, output_path = prepare_model_cli( img_input=img_input, output_path=output_path, masks=masks, file_types=file_types, ) ioconfig = prepare_ioconfig_seg( IOSegmentorConfig, pretrained_weights, yaml_config_path ) predictor = NucleusInstanceSegmentor( pretrained_model=pretrained_model, pretrained_weights=pretrained_weights, batch_size=batch_size, num_loader_workers=num_loader_workers, num_postproc_workers=num_postproc_workers, auto_generate_mask=auto_generate_mask, verbose=verbose, ) output = predictor.predict( imgs=files_all, masks=masks_all, mode=mode, on_gpu=on_gpu, save_dir=output_path, ioconfig=ioconfig, ) save_as_json(output, str(output_path.joinpath("results.json")))
2,678
25.009709
85
py
tiatoolbox
tiatoolbox-master/tiatoolbox/cli/slide_thumbnail.py
"""Command line interface for slide_thumbnail.""" import pathlib from tiatoolbox.cli.common import ( cli_file_type, cli_img_input, cli_mode, cli_output_path, prepare_file_dir_cli, tiatoolbox_cli, ) @tiatoolbox_cli.command() @cli_img_input() @cli_output_path( usage_help="Path to output directory to save the output. " "default=img_input/../slide-thumbnail" ) @cli_file_type(default="*.ndpi, *.svs, *.mrxs, *.jp2") @cli_mode(default="save") def slide_thumbnail(img_input, output_path, file_types, mode): """Reads whole slide image thumbnail and shows or saves based on mode argument. The default inputs are: img-input='', output-path=img-input-path/../meta-data, mode="save", file-types="*.ndpi, *.svs, *.mrxs, *.jp2". """ from PIL import Image from tiatoolbox.utils.misc import imwrite from tiatoolbox.wsicore.wsireader import WSIReader files_all, output_path = prepare_file_dir_cli( img_input, output_path, file_types, mode, "slide-thumbnail" ) for curr_file in files_all: wsi = WSIReader.open(input_img=curr_file) slide_thumb = wsi.slide_thumbnail() if mode == "show": # pragma: no cover # Skipped on CI, and unless SHOW_TESTS is set im_region = Image.fromarray(slide_thumb) im_region.show() # the only other option left for mode is "save". imwrite(output_path / (pathlib.Path(curr_file).stem + ".jpg"), slide_thumb)
1,492
28.27451
83
py
tiatoolbox
tiatoolbox-master/tiatoolbox/cli/semantic_segment.py
"""Command line interface for semantic segmentation.""" import click from tiatoolbox.cli.common import ( cli_batch_size, cli_file_type, cli_img_input, cli_masks, cli_mode, cli_num_loader_workers, cli_on_gpu, cli_output_path, cli_pretrained_model, cli_pretrained_weights, cli_verbose, cli_yaml_config_path, prepare_ioconfig_seg, prepare_model_cli, tiatoolbox_cli, ) @tiatoolbox_cli.command() @cli_img_input() @cli_output_path( usage_help="Output directory where model predictions will be saved.", default="semantic_segmentation", ) @cli_file_type( default="*.png, *.jpg, *.jpeg, *.tif, *.tiff, *.svs, *.ndpi, *.jp2, *.mrxs" ) @cli_mode( usage_help="Type of input file to process.", default="wsi", input_type=click.Choice(["patch", "wsi", "tile"], case_sensitive=False), ) @cli_pretrained_model(default="fcn-tissue_mask") @cli_pretrained_weights(default=None) @cli_on_gpu() @cli_batch_size() @cli_masks(default=None) @cli_yaml_config_path() @cli_num_loader_workers() @cli_verbose() def semantic_segment( pretrained_model, pretrained_weights, img_input, file_types, masks, mode, output_path, batch_size, yaml_config_path, num_loader_workers, on_gpu, verbose, ): """Process an image/directory of input images with a patch classification CNN.""" from tiatoolbox.models.engine.semantic_segmentor import ( IOSegmentorConfig, SemanticSegmentor, ) from tiatoolbox.utils.misc import save_as_json files_all, masks_all, output_path = prepare_model_cli( img_input=img_input, output_path=output_path, masks=masks, file_types=file_types, ) ioconfig = prepare_ioconfig_seg( IOSegmentorConfig, pretrained_weights, yaml_config_path ) predictor = SemanticSegmentor( pretrained_model=pretrained_model, pretrained_weights=pretrained_weights, batch_size=batch_size, num_loader_workers=num_loader_workers, verbose=verbose, ) output = predictor.predict( imgs=files_all, masks=masks_all, mode=mode, on_gpu=on_gpu, save_dir=output_path, ioconfig=ioconfig, ) save_as_json(output, str(output_path.joinpath("results.json")))
2,332
23.557895
85
py
tiatoolbox
tiatoolbox-master/tiatoolbox/cli/patch_predictor.py
"""Command line interface for patch_predictor.""" import click from tiatoolbox.cli.common import ( cli_batch_size, cli_file_type, cli_img_input, cli_masks, cli_merge_predictions, cli_mode, cli_num_loader_workers, cli_on_gpu, cli_output_path, cli_pretrained_model, cli_pretrained_weights, cli_resolution, cli_return_labels, cli_return_probabilities, cli_units, cli_verbose, prepare_model_cli, tiatoolbox_cli, ) @tiatoolbox_cli.command() @cli_img_input() @cli_output_path( usage_help="Output directory where model predictions will be saved.", default="patch_prediction", ) @cli_file_type( default="*.png, *.jpg, *.jpeg, *.tif, *.tiff, *.svs, *.ndpi, *.jp2, *.mrxs" ) @cli_mode( usage_help="Type of input file to process.", default="wsi", input_type=click.Choice(["patch", "wsi", "tile"], case_sensitive=False), ) @cli_pretrained_model(default="resnet18-kather100k") @cli_pretrained_weights() @cli_return_probabilities(default=False) @cli_merge_predictions(default=True) @cli_return_labels(default=True) @cli_on_gpu(default=False) @cli_batch_size(default=1) @cli_resolution(default=0.5) @cli_units(default="mpp") @cli_masks(default=None) @cli_num_loader_workers(default=0) @cli_verbose() def patch_predictor( pretrained_model, pretrained_weights, img_input, file_types, masks, mode, output_path, batch_size, resolution, units, return_probabilities, return_labels, merge_predictions, num_loader_workers, on_gpu, verbose, ): """Process an image/directory of input images with a patch classification CNN.""" from tiatoolbox.models.engine.patch_predictor import PatchPredictor from tiatoolbox.utils.misc import save_as_json files_all, masks_all, output_path = prepare_model_cli( img_input=img_input, output_path=output_path, masks=masks, file_types=file_types, ) predictor = PatchPredictor( pretrained_model=pretrained_model, pretrained_weights=pretrained_weights, batch_size=batch_size, num_loader_workers=num_loader_workers, verbose=verbose, ) output = predictor.predict( imgs=files_all, masks=masks_all, mode=mode, return_probabilities=return_probabilities, merge_predictions=merge_predictions, labels=None, return_labels=return_labels, resolution=resolution, units=units, on_gpu=on_gpu, save_dir=output_path, save_output=True, ) save_as_json(output, str(output_path.joinpath("results.json")))
2,665
24.390476
85
py
tiatoolbox
tiatoolbox-master/tiatoolbox/cli/common.py
"""Defines common code required for cli.""" import os import pathlib import click def add_default_to_usage_help( usage_help: str, default: str or int or float or bool ) -> str: """Adds default value to usage help string. Args: usage_help (str): usage help for click option. default (str or int or float): default value as string for click option. Returns: str: New usage_help value. """ if default is not None: return f"{usage_help} default={default}" return usage_help def cli_img_input( usage_help: str = "Path to WSI or directory containing WSIs.", multiple: bool = False, ) -> callable: """Enables --img-input option for cli.""" if multiple: usage_help = usage_help + " Multiple instances may be provided." return click.option("--img-input", help=usage_help, type=str, multiple=multiple) def cli_name( usage_help: str = "User defined name to be used as an identifier.", multiple: bool = False, ) -> callable: """enables --name option for cli""" if multiple: usage_help = usage_help + " Multiple instances may be provided." return click.option("--name", help=usage_help, type=str, multiple=multiple) def cli_output_path( usage_help: str = "Path to output directory to save the output.", default: str = None, ) -> callable: """Enables --output-path option for cli.""" return click.option( "--output-path", help=add_default_to_usage_help(usage_help, default), type=str, default=default, ) def cli_file_type( usage_help: str = "File types to capture from directory.", default: str = "*.ndpi, *.svs, *.mrxs, *.jp2", ) -> callable: """Enables --file-types option for cli.""" return click.option( "--file-types", help=add_default_to_usage_help(usage_help, default), default=default, type=str, ) def cli_mode( usage_help: str = "Selected mode to show or save the required information.", default: str = "save", input_type: click.Choice = None, ) -> callable: """Enables --mode option for cli.""" if input_type is None: input_type = click.Choice(["show", "save"], case_sensitive=False) return click.option( "--mode", help=add_default_to_usage_help(usage_help, default), default=default, type=input_type, ) def cli_region( usage_help: str = "Image region in the whole slide image to read from. " "default=0 0 2000 2000", ) -> callable: """Enables --region option for cli.""" return click.option( "--region", type=int, nargs=4, help=usage_help, ) def cli_units( usage_help: str = "Image resolution units to read the image.", default: str = "level", input_type: click.Choice = None, ) -> callable: """Enables --units option for cli.""" if input_type is None: input_type = click.Choice( ["mpp", "power", "level", "baseline"], case_sensitive=False ) return click.option( "--units", default=default, type=input_type, help=add_default_to_usage_help(usage_help, default), ) def cli_resolution( usage_help: str = "Image resolution to read the image.", default: float = 0 ) -> callable: """Enables --resolution option for cli.""" return click.option( "--resolution", type=float, default=default, help=add_default_to_usage_help(usage_help, default), ) def cli_tile_objective( usage_help: str = "Objective value for the saved tiles.", default: int = 20 ) -> callable: """Enables --tile-objective-value option for cli.""" return click.option( "--tile-objective-value", type=int, default=default, help=add_default_to_usage_help(usage_help, default), ) def cli_tile_read_size( usage_help: str = "Width and Height of saved tiles. default=5000 5000", ) -> callable: """Enables --tile-read-size option for cli.""" return click.option( "--tile-read-size", type=int, nargs=2, default=[5000, 5000], help=usage_help, ) def cli_tile_format( usage_help: str = "File format to save image tiles, defaults = '.jpg'", ) -> callable: """Enables --tile-format option for cli.""" return click.option( "--tile-format", type=str, default=".jpg", help=usage_help, ) def cli_method( usage_help: str = "Select method of for tissue masking.", default: str = "Otsu", input_type: click.Choice = None, ) -> callable: """Enables --method option for cli.""" if input_type is None: input_type = click.Choice(["Otsu", "Morphological"], case_sensitive=True) return click.option( "--method", type=input_type, default=default, help=add_default_to_usage_help(usage_help, default), ) def cli_pretrained_model( usage_help: str = "Name of the predefined model used to process the data. " "The format is <model_name>_<dataset_trained_on>. For example, " "`resnet18-kather100K` is a resnet18 model trained on the Kather dataset. " "Please see " "https://tia-toolbox.readthedocs.io/en/latest/usage.html#deep-learning-models " "for a detailed list of available pretrained models." "By default, the corresponding pretrained weights will also be" "downloaded. However, you can override with your own set of weights" "via the `pretrained_weights` argument. Argument is case insensitive.", default: str = "resnet18-kather100k", ) -> callable: """Enables --pretrained-model option for cli.""" return click.option( "--pretrained-model", help=add_default_to_usage_help(usage_help, default), default=default, ) def cli_pretrained_weights( usage_help: str = "Path to the model weight file. If not supplied, the default " "pretrained weight will be used.", default: str = None, ) -> callable: """Enables --pretrained-weights option for cli.""" return click.option( "--pretrained-weights", help=add_default_to_usage_help(usage_help, default), default=default, ) def cli_return_probabilities( usage_help: str = "Whether to return raw model probabilities.", default: bool = False, ) -> callable: """Enables --return-probabilities option for cli.""" return click.option( "--return-probabilities", type=bool, help=add_default_to_usage_help(usage_help, default), default=default, ) def cli_merge_predictions( usage_help: str = "Whether to merge the predictions to form a 2-dimensional map.", default: bool = True, ) -> callable: """Enables --merge-predictions option for cli.""" return click.option( "--merge-predictions", type=bool, default=default, help=add_default_to_usage_help(usage_help, default), ) def cli_return_labels( usage_help: str = "Whether to return raw model output as labels.", default: bool = True, ) -> callable: """Enables --return-labels option for cli.""" return click.option( "--return-labels", type=bool, help=add_default_to_usage_help(usage_help, default), default=default, ) def cli_batch_size( usage_help: str = "Number of image patches to feed into the model each time.", default: int = 1, ) -> callable: """Enables --batch-size option for cli.""" return click.option( "--batch-size", help=add_default_to_usage_help(usage_help, default), default=default, ) def cli_masks( usage_help: str = "Path to the input directory containing masks to process " "corresponding to image tiles and whole-slide images. " "Patches are only processed if they are within a masked area. " "If masks are not provided, then a tissue mask will be " "automatically generated for whole-slide images or the entire image is " "processed for image tiles. Supported file types are jpg, png and npy.", default: str = None, ) -> callable: """Enables --masks option for cli.""" return click.option( "--masks", help=add_default_to_usage_help(usage_help, default), default=default, ) def cli_auto_generate_mask( usage_help: str = "Automatically generate tile/WSI tissue mask.", default: bool = False, ) -> callable: """Enables --auto-generate-mask option for cli.""" return click.option( "--auto-generate-mask", help=add_default_to_usage_help(usage_help, default), type=bool, default=default, ) def cli_yaml_config_path( usage_help: str = "Path to ioconfig file. Sample yaml file can be viewed in " "tiatoolbox.data.pretrained_model.yaml. " "if pretrained_model is used the ioconfig is automatically set.", default: str = None, ) -> callable: """Enables --yaml-config-path option for cli.""" return click.option( "--yaml-config-path", help=add_default_to_usage_help(usage_help, default), default=default, ) def cli_on_gpu( usage_help: str = "Run the model on GPU.", default: bool = False ) -> callable: """Enables --on-gpu option for cli.""" return click.option( "--on-gpu", type=bool, default=default, help=add_default_to_usage_help(usage_help, default), ) def cli_num_loader_workers( usage_help: str = "Number of workers to load the data. Please note that they will " "also perform preprocessing.", default: int = 0, ) -> callable: """Enables --num-loader-workers option for cli.""" return click.option( "--num-loader-workers", help=add_default_to_usage_help(usage_help, default), type=int, default=default, ) def cli_num_postproc_workers( usage_help: str = "Number of workers to post-process the network output.", default: int = 0, ) -> callable: """Enables --num-postproc-workers option for cli.""" return click.option( "--num-postproc-workers", help=add_default_to_usage_help(usage_help, default), type=int, default=default, ) def cli_verbose( usage_help: str = "Prints the console output.", default: bool = True ) -> callable: """Enables --verbose option for cli.""" return click.option( "--verbose", type=bool, help=add_default_to_usage_help(usage_help, str(default)), default=default, ) class TIAToolboxCLI(click.Group): """Defines TIAToolbox Commandline Interface Click group.""" def __init__(self, *args, **kwargs): super(TIAToolboxCLI, self).__init__(*args, **kwargs) self.help = "Computational pathology toolbox by TIA Centre." self.add_help_option = {"help_option_names": ["-h", "--help"]} def no_input_message( input_file: str or pathlib.Path = None, message: str = "No image input provided.\n" ) -> None: """This function is called if no input is provided. Args: input_file (str or pathlib.Path): Path to input file. message (str): Error message to display. """ if input_file is None: ctx = click.get_current_context() ctx.fail(message=message) def prepare_file_dir_cli( img_input: str or pathlib.Path, output_path: str or pathlib.Path, file_types: str, mode: str, sub_dirname: str, ) -> [list, pathlib.Path]: """Prepares CLI for running code on multiple files or a directory. Checks for existing directories to run tests. Converts file path to list of file paths or creates list of file paths if input is a directory. Args: img_input (str or pathlib.Path): file path to images. output_path (str or pathlib.Path): output directory path. file_types (str): file types to process using cli. mode (str): wsi or tile mode. sub_dirname (str): name of subdirectory to save output. Returns: list: list of file paths to process. pathlib.Path: updated output path. """ from tiatoolbox.utils.misc import grab_files_from_dir, string_to_tuple no_input_message(input_file=img_input) file_types = string_to_tuple(in_str=file_types) if isinstance(output_path, str): output_path = pathlib.Path(output_path) if not os.path.exists(img_input): raise FileNotFoundError files_all = [ img_input, ] if os.path.isdir(img_input): files_all = grab_files_from_dir(input_path=img_input, file_types=file_types) if output_path is None and mode == "save": input_dir = pathlib.Path(img_input).parent output_path = input_dir / sub_dirname if mode == "save": output_path.mkdir(parents=True, exist_ok=True) return [files_all, output_path] def prepare_model_cli( img_input: str or pathlib.Path, output_path: str or pathlib.Path, masks: str or pathlib.Path, file_types: str, ) -> [list, list, pathlib.Path]: """Prepares cli for running models. Checks for existing directories to run tests. Converts file path to list of file paths or creates list of file paths if input is a directory. Args: img_input (str or pathlib.Path): file path to images. output_path (str or pathlib.Path): output directory path. masks (str or pathlib.Path): file path to masks. file_types (str): file types to process using cli. Returns: list: list of file paths to process. list: list of masks corresponding to input files. pathlib.Path: output path """ from tiatoolbox.utils.misc import grab_files_from_dir, string_to_tuple no_input_message(input_file=img_input) output_path = pathlib.Path(output_path) file_types = string_to_tuple(in_str=file_types) if output_path.exists(): raise FileExistsError("Path already exists.") if not os.path.exists(img_input): raise FileNotFoundError files_all = [ img_input, ] if masks is None: masks_all = None else: masks_all = [ masks, ] if os.path.isdir(img_input): files_all = grab_files_from_dir(input_path=img_input, file_types=file_types) if os.path.isdir(str(masks)): masks_all = grab_files_from_dir(input_path=masks, file_types=("*.jpg", "*.png")) return [files_all, masks_all, output_path] tiatoolbox_cli = TIAToolboxCLI() def prepare_ioconfig_seg(segment_config_class, pretrained_weights, yaml_config_path): """Prepare ioconfig for segmentation.""" import yaml if pretrained_weights is not None: with open(yaml_config_path) as registry_handle: ioconfig = yaml.safe_load(registry_handle) return segment_config_class(**ioconfig) return None
14,940
28.068093
88
py
tiatoolbox
tiatoolbox-master/tiatoolbox/cli/__init__.py
"""Console script for tiatoolbox.""" import platform import sys import click from tiatoolbox import __version__ from tiatoolbox.cli.common import tiatoolbox_cli from tiatoolbox.cli.nucleus_instance_segment import nucleus_instance_segment from tiatoolbox.cli.patch_predictor import patch_predictor from tiatoolbox.cli.read_bounds import read_bounds from tiatoolbox.cli.save_tiles import save_tiles from tiatoolbox.cli.semantic_segment import semantic_segment from tiatoolbox.cli.show_wsi import show_wsi from tiatoolbox.cli.slide_info import slide_info from tiatoolbox.cli.slide_thumbnail import slide_thumbnail from tiatoolbox.cli.stain_norm import stain_norm from tiatoolbox.cli.tissue_mask import tissue_mask def version_msg(): """Return a string with tiatoolbox package version and python version.""" return f"tiatoolbox {__version__} (Python {platform.python_version()}) on {platform.platform()}." @tiatoolbox_cli.group(context_settings={"help_option_names": ["-h", "--help"]}) @click.version_option( __version__, "--version", "-v", help="Show the tiatoolbox version", message=version_msg(), ) def main(): """Computational pathology toolbox by TIA Centre.""" return 0 main.add_command(nucleus_instance_segment) main.add_command(patch_predictor) main.add_command(read_bounds) main.add_command(save_tiles) main.add_command(semantic_segment) main.add_command(slide_info) main.add_command(slide_thumbnail) main.add_command(tissue_mask) main.add_command(stain_norm) main.add_command(show_wsi) if __name__ == "__main__": sys.exit(main()) # pragma: no cover
1,606
29.320755
101
py
tiatoolbox
tiatoolbox-master/tiatoolbox/cli/tissue_mask.py
"""Command line interface for tissue_mask.""" import pathlib import click from tiatoolbox.cli.common import ( cli_file_type, cli_img_input, cli_method, cli_mode, cli_output_path, cli_resolution, cli_units, prepare_file_dir_cli, tiatoolbox_cli, ) def get_masker(method, kernel_size, units, resolution): """Get Tissue Masker.""" from tiatoolbox.tools import tissuemask if method == "Otsu": return tissuemask.OtsuTissueMasker() if kernel_size: return tissuemask.MorphologicalMasker(kernel_size=kernel_size) if units == "mpp": return tissuemask.MorphologicalMasker(mpp=resolution) return tissuemask.MorphologicalMasker(power=resolution) @tiatoolbox_cli.command() @cli_img_input() @cli_output_path(default="tissue_mask") @cli_method(default="Otsu") @cli_resolution(default=1.25) @cli_units( default="power", input_type=click.Choice(["mpp", "power"], case_sensitive=False) ) @cli_mode(default="show") @cli_file_type(default="*.svs, *.ndpi, *.jp2, *.png, *.jpg, *.tif, *.tiff") # inputs specific to this function @click.option( "--kernel-size", type=int, nargs=2, help="kernel size for morphological dilation, default=1, 1", ) def tissue_mask( img_input, output_path, method, resolution, units, kernel_size, mode, file_types ): """Generate tissue mask for a WSI.""" import numpy as np from PIL import Image from tiatoolbox.utils.misc import imwrite from tiatoolbox.wsicore.wsireader import WSIReader files_all, output_path = prepare_file_dir_cli( img_input, output_path, file_types, mode, "meta-data" ) masker = get_masker(method, kernel_size, units, resolution) for curr_file in files_all: wsi = WSIReader.open(input_img=curr_file) wsi_thumb = wsi.slide_thumbnail(resolution=1.25, units="power") mask = masker.fit_transform(wsi_thumb[np.newaxis, :]) if mode == "show": # pragma: no cover # Skipped on CI, and unless SHOW_TESTS is set im_region = Image.fromarray(mask[0]) im_region.show() continue # Else, save (the only other option for mode) imwrite( output_path.joinpath(pathlib.Path(curr_file).stem + ".png"), mask[0].astype(np.uint8) * 255, )
2,338
26.845238
84
py
tiatoolbox
tiatoolbox-master/tiatoolbox/tools/patchextraction.py
"""This file defines patch extraction methods for deep learning models.""" from abc import ABC, abstractmethod from pathlib import Path from typing import Callable, Tuple, Union import numpy as np from pandas import DataFrame from tiatoolbox import logger from tiatoolbox.utils import misc from tiatoolbox.utils.exceptions import MethodNotSupported from tiatoolbox.wsicore import wsireader class PatchExtractorABC(ABC): """Abstract base class for Patch Extraction in tiatoolbox.""" @abstractmethod def __iter__(self): raise NotImplementedError @abstractmethod def __next__(self): raise NotImplementedError @abstractmethod def __getitem__(self, item: int): raise NotImplementedError class PatchExtractor(PatchExtractorABC): """Class for extracting and merging patches in standard and whole-slide images. Args: input_img(str, pathlib.Path, :class:`numpy.ndarray`): Input image for patch extraction. patch_size(int or tuple(int)): Patch size tuple (width, height). input_mask(str, pathlib.Path, :class:`numpy.ndarray`, or :obj:`WSIReader`): Input mask that is used for position filtering when extracting patches i.e., patches will only be extracted based on the highlighted regions in the input_mask. input_mask can be either path to the mask, a numpy array, :class:`VirtualWSIReader`, or one of 'otsu' and 'morphological' options. In case of 'otsu' or 'morphological', a tissue mask is generated for the input_image using tiatoolbox :class:`TissueMasker` functionality. resolution (int or float or tuple of float): Resolution at which to read the image, default = 0. Either a single number or a sequence of two numbers for x and y are valid. This value is in terms of the corresponding units. For example: resolution=0.5 and units="mpp" will read the slide at 0.5 microns per-pixel, and resolution=3, units="level" will read at level at pyramid level / resolution layer 3. units (str): Units of resolution, default = "level". Supported units are: microns per pixel (mpp), objective power (power), pyramid / resolution level (level), Only pyramid / resolution levels (level) embedded in the whole slide image are supported. pad_mode (str): Method for padding at edges of the WSI. Default to 'constant'. See :func:`numpy.pad` for more information. pad_constant_values (int or tuple(int)): Values to use with constant padding. Defaults to 0. See :func:`numpy.pad` for more. within_bound (bool): Whether to extract patches beyond the input_image size limits. If False, extracted patches at margins will be padded appropriately based on `pad_constant_values` and `pad_mode`. If False, patches at the margin that their bounds exceed the mother image dimensions would be neglected. Default is False. min_mask_ratio (float): Area in percentage that a patch needs to contain of positive mask to be included. Defaults to 0. Attributes: wsi(WSIReader): Input image for patch extraction of type :obj:`WSIReader`. patch_size(tuple(int)): Patch size tuple (width, height). resolution(tuple(int)): Resolution at which to read the image. units (str): Units of resolution. n (int): Current state of the iterator. locations_df (pd.DataFrame): A table containing location and/or type of patches in `(x_start, y_start, class)` format. coordinate_list (:class:`numpy.ndarray`): An array containing coordinates of patches in `(x_start, y_start, x_end, y_end)` format to be used for `slidingwindow` patch extraction. pad_mode (str): Method for padding at edges of the WSI. See :func:`numpy.pad` for more information. pad_constant_values (int or tuple(int)): Values to use with constant padding. Defaults to 0. See :func:`numpy.pad` for more. stride (tuple(int)): Stride in (x, y) direction for patch extraction. Not used for :obj:`PointsPatchExtractor` min_mask_ratio (float): Only patches with positive area percentage above this value are included """ def __init__( self, input_img: Union[str, Path, np.ndarray], patch_size: Union[int, Tuple[int, int]], input_mask: Union[str, Path, np.ndarray, wsireader.WSIReader] = None, resolution: Union[int, float, Tuple[float, float]] = 0, units: str = "level", pad_mode: str = "constant", pad_constant_values: Union[int, Tuple[int, int]] = 0, within_bound: bool = False, min_mask_ratio: float = 0, ): if isinstance(patch_size, (tuple, list)): self.patch_size = (int(patch_size[0]), int(patch_size[1])) else: self.patch_size = (int(patch_size), int(patch_size)) self.resolution = resolution self.units = units self.pad_mode = pad_mode self.pad_constant_values = pad_constant_values self.n = 0 self.wsi = wsireader.WSIReader.open(input_img=input_img) self.locations_df = None self.coordinate_list = None self.stride = None self.min_mask_ratio = min_mask_ratio if input_mask is None: self.mask = None elif isinstance(input_mask, str) and input_mask in {"otsu", "morphological"}: if isinstance(self.wsi, wsireader.VirtualWSIReader): self.mask = None else: self.mask = self.wsi.tissue_mask( method=input_mask, resolution=1.25, units="power" ) elif isinstance(input_mask, wsireader.VirtualWSIReader): self.mask = input_mask else: self.mask = wsireader.VirtualWSIReader( input_mask, info=self.wsi.info, mode="bool" ) self.within_bound = within_bound def __iter__(self): self.n = 0 return self def __len__(self): return self.locations_df.shape[0] if self.locations_df is not None else 0 def __next__(self): n = self.n if n >= self.locations_df.shape[0]: raise StopIteration self.n = n + 1 return self[n] def __getitem__(self, item: int): if not isinstance(item, int): raise TypeError("Index should be an integer.") if item >= self.locations_df.shape[0]: raise IndexError x = self.locations_df["x"][item] y = self.locations_df["y"][item] return self.wsi.read_rect( location=(int(x), int(y)), size=self.patch_size, resolution=self.resolution, units=self.units, pad_mode=self.pad_mode, pad_constant_values=self.pad_constant_values, coord_space="resolution", ) def _generate_location_df(self): """Generate location list based on slide dimension. The slide dimension is calculated using units and resolution. """ slide_dimension = self.wsi.slide_dimensions(self.resolution, self.units) self.coordinate_list = self.get_coordinates( image_shape=(slide_dimension[0], slide_dimension[1]), patch_input_shape=(self.patch_size[0], self.patch_size[1]), stride_shape=(self.stride[0], self.stride[1]), input_within_bound=self.within_bound, ) if self.mask is not None: selected_coord_indices = self.filter_coordinates( self.mask, self.coordinate_list, wsi_shape=slide_dimension, min_mask_ratio=self.min_mask_ratio, ) self.coordinate_list = self.coordinate_list[selected_coord_indices] if len(self.coordinate_list) == 0: logger.warning( "No candidate coordinates left after " "filtering by `input_mask` positions.", stacklevel=2, ) data = self.coordinate_list[:, :2] # only use the x_start and y_start self.locations_df = misc.read_locations(input_table=np.array(data)) return self @staticmethod def filter_coordinates( mask_reader: wsireader.VirtualWSIReader, coordinates_list: np.ndarray, wsi_shape: Tuple[int, int], min_mask_ratio: float = 0, func: Callable = None, ): """Validate patch extraction coordinates based on the input mask. This function indicates which coordinate is valid for mask-based patch extraction based on checks in low resolution. Args: mask_reader (:class:`.VirtualReader`): A virtual pyramidal reader of the mask related to the WSI from which we want to extract the patches. coordinates_list (ndarray and np.int32): Coordinates to be checked via the `func`. They must be at the same resolution as requested `resolution` and `units`. The shape of `coordinates_list` is (N, K) where N is the number of coordinate sets and K is either 2 for centroids or 4 for bounding boxes. When using the default `func=None`, K should be 4, as we expect the `coordinates_list` to be bounding boxes in `[start_x, start_y, end_x, end_y]` format. wsi_shape (tuple(int, int)): Shape of the WSI in the requested `resolution` and `units`. min_mask_ratio (float): Only patches with positive area percentage above this value are included. Defaults to 0. Has no effect if `func` is not `None`. func (callable): Function to be used to validate the coordinates. The function must take a `numpy.ndarray` of the mask and a `numpy.ndarray` of the coordinates as input and return a bool indicating whether the coordinate is valid or not. If `None`, a default function that accepts patches with positive area proportion above `min_mask_ratio` is used. Returns: :class:`numpy.ndarray`: list of flags to indicate which coordinate is valid. """ if not isinstance(mask_reader, wsireader.VirtualWSIReader): raise ValueError("`mask_reader` should be wsireader.VirtualWSIReader.") if not isinstance(coordinates_list, np.ndarray) or not np.issubdtype( coordinates_list.dtype, np.integer ): raise ValueError("`coordinates_list` should be ndarray of integer type.") if coordinates_list.shape[-1] != 4: raise ValueError("`coordinates_list` must be of shape [N, 4].") if not 0 <= min_mask_ratio <= 1: raise ValueError("`min_mask_ratio` must be between 0 and 1.") # the tissue mask exists in the reader already, no need to generate it tissue_mask = mask_reader.img # Scaling the coordinates_list to the `tissue_mask` array resolution scale_factors = np.array(tissue_mask.shape[::-1]) / np.array(wsi_shape) scaled_coords = coordinates_list.copy().astype(np.float32) scaled_coords[:, [0, 2]] *= scale_factors[0] scaled_coords[:, [0, 2]] = np.clip( scaled_coords[:, [0, 2]], 0, tissue_mask.shape[1] ) scaled_coords[:, [1, 3]] *= scale_factors[1] scaled_coords[:, [1, 3]] = np.clip( scaled_coords[:, [1, 3]], 0, tissue_mask.shape[0] ) scaled_coords = list(np.int32(scaled_coords)) def default_sel_func(tissue_mask, coord): """Default selection function to filter coordinates. This function selects a coordinate if the proportion of positive mask in the corresponding patch is greater than `min_mask_ratio`. """ this_part = tissue_mask[coord[1] : coord[3], coord[0] : coord[2]] patch_area = np.prod(this_part.shape) pos_area = np.count_nonzero(this_part) return ( (pos_area == patch_area) or (pos_area > patch_area * min_mask_ratio) ) and (pos_area > 0 and patch_area > 0) func = default_sel_func if func is None else func flag_list = [] for coord in scaled_coords: flag_list.append(func(tissue_mask, coord)) return np.array(flag_list) @staticmethod def get_coordinates( image_shape: Union[Tuple[int, int], np.ndarray] = None, patch_input_shape: Union[Tuple[int, int], np.ndarray] = None, patch_output_shape: Union[Tuple[int, int], np.ndarray] = None, stride_shape: Union[Tuple[int, int], np.ndarray] = None, input_within_bound: bool = False, output_within_bound: bool = False, ): """Calculate patch tiling coordinates. Args: image_shape (tuple (int, int) or :class:`numpy.ndarray`): This argument specifies the shape of mother image (the image we want to extract patches from) at requested `resolution` and `units` and it is expected to be in (width, height) format. patch_input_shape (tuple (int, int) or :class:`numpy.ndarray`): Specifies the input shape of requested patches to be extracted from mother image at desired `resolution` and `units`. This argument is also expected to be in (width, height) format. patch_output_shape (tuple (int, int) or :class:`numpy.ndarray`): Specifies the output shape of requested patches to be extracted from mother image at desired `resolution` and `units`. This argument is also expected to be in (width, height) format. If this is not provided, `patch_output_shape` will be the same as `patch_input_shape`. stride_shape (tuple (int, int) or :class:`numpy.ndarray`): The stride that is used to calculate the patch location during the patch extraction. If `patch_output_shape` is provided, next stride location will base on the output rather than the input. input_within_bound (bool): Whether to include the patches where their `input` location exceed the margins of mother image. If `True`, the patches with input location exceeds the `image_shape` would be neglected. Otherwise, those patches would be extracted with `Reader` function and appropriate padding. output_within_bound (bool): Whether to include the patches where their `output` location exceed the margins of mother image. If `True`, the patches with output location exceeds the `image_shape` would be neglected. Otherwise, those patches would be extracted with `Reader` function and appropriate padding. Return: coord_list: A list of coordinates in `[start_x, start_y, end_x, end_y]` format to be used for patch extraction. """ return_output_bound = patch_output_shape is not None image_shape = np.array(image_shape) patch_input_shape = np.array(patch_input_shape) if patch_output_shape is None: output_within_bound = False patch_output_shape = patch_input_shape patch_output_shape = np.array(patch_output_shape) stride_shape = np.array(stride_shape) def validate_shape(shape): """Tests if the shape is valid for an image.""" return ( not np.issubdtype(shape.dtype, np.integer) or np.size(shape) > 2 or np.any(shape < 0) ) if validate_shape(image_shape): raise ValueError(f"Invalid `image_shape` value {image_shape}.") if validate_shape(patch_input_shape): raise ValueError(f"Invalid `patch_input_shape` value {patch_input_shape}.") if validate_shape(patch_output_shape): raise ValueError( f"Invalid `patch_output_shape` value {patch_output_shape}." ) if validate_shape(stride_shape): raise ValueError(f"Invalid `stride_shape` value {stride_shape}.") if np.any(patch_input_shape < patch_output_shape): raise ValueError( ( f"`patch_input_shape` must larger than `patch_output_shape`" f" {patch_input_shape} must > {patch_output_shape}." ) ) if np.any(stride_shape < 1): raise ValueError(f"`stride_shape` value {stride_shape} must > 1.") def flat_mesh_grid_coord(x, y): """Helper function to obtain coordinate grid.""" x, y = np.meshgrid(x, y) return np.stack([x.flatten(), y.flatten()], axis=-1) output_x_end = ( np.ceil(image_shape[0] / patch_output_shape[0]) * patch_output_shape[0] ) output_x_list = np.arange(0, int(output_x_end), stride_shape[0]) output_y_end = ( np.ceil(image_shape[1] / patch_output_shape[1]) * patch_output_shape[1] ) output_y_list = np.arange(0, int(output_y_end), stride_shape[1]) output_tl_list = flat_mesh_grid_coord(output_x_list, output_y_list) output_br_list = output_tl_list + patch_output_shape[None] io_diff = patch_input_shape - patch_output_shape input_tl_list = output_tl_list - (io_diff // 2)[None] input_br_list = input_tl_list + patch_input_shape[None] sel = np.zeros(input_tl_list.shape[0], dtype=bool) if output_within_bound: sel |= np.any(output_br_list > image_shape[None], axis=1) if input_within_bound: sel |= np.any(input_br_list > image_shape[None], axis=1) sel |= np.any(input_tl_list < 0, axis=1) #### input_bound_list = np.concatenate( [input_tl_list[~sel], input_br_list[~sel]], axis=-1 ) output_bound_list = np.concatenate( [output_tl_list[~sel], output_br_list[~sel]], axis=-1 ) if return_output_bound: return input_bound_list, output_bound_list return input_bound_list class SlidingWindowPatchExtractor(PatchExtractor): """Extract patches using sliding fixed sized window for images and labels. Args: input_img(str, pathlib.Path, :class:`numpy.ndarray`): Input image for patch extraction. patch_size(int or tuple(int)): Patch size tuple (width, height). input_mask(str, pathlib.Path, :class:`numpy.ndarray`, or :obj:`WSIReader`): Input mask that is used for position filtering when extracting patches i.e., patches will only be extracted based on the highlighted regions in the `input_mask`. `input_mask` can be either path to the mask, a numpy array, :class:`VirtualWSIReader`, or one of 'otsu' and 'morphological' options. In case of 'otsu' or 'morphological', a tissue mask is generated for the input_image using tiatoolbox :class:`TissueMasker` functionality. resolution (int or float or tuple of float): Resolution at which to read the image, default = 0. Either a single number or a sequence of two numbers for x and y are valid. This value is in terms of the corresponding units. For example: resolution=0.5 and units="mpp" will read the slide at 0.5 microns per-pixel, and resolution=3, units="level" will read at level at pyramid level / resolution layer 3. units (str): The units of resolution, default = "level". Supported units are: microns per pixel (mpp), objective power (power), pyramid / resolution level (level), Only pyramid / resolution levels (level) embedded in the whole slide image are supported. pad_mode (str): Method for padding at edges of the WSI. Default to 'constant'. See :func:`numpy.pad` for more information. pad_constant_values (int or tuple(int)): Values to use with constant padding. Defaults to 0. See :func:`numpy.pad` for more information. within_bound (bool): Whether to extract patches beyond the input_image size limits. If False, extracted patches at margins will be padded appropriately based on `pad_constant_values` and `pad_mode`. If False, patches at the margin that their bounds exceed the mother image dimensions would be neglected. Default is False. stride(int or tuple(int)): Stride in (x, y) direction for patch extraction, default = `patch_size`. min_mask_ratio (float): Only patches with positive area percentage above this value are included. Defaults to 0. Attributes: stride(tuple(int)): Stride in (x, y) direction for patch extraction. """ def __init__( self, input_img: Union[str, Path, np.ndarray], patch_size: Union[int, Tuple[int, int]], input_mask: Union[str, Path, np.ndarray, wsireader.WSIReader] = None, resolution: Union[int, float, Tuple[float, float]] = 0, units: str = "level", stride: Union[int, Tuple[int, int]] = None, pad_mode: str = "constant", pad_constant_values: Union[int, Tuple[int, int]] = 0, within_bound: bool = False, min_mask_ratio: float = 0, ): super().__init__( input_img=input_img, input_mask=input_mask, patch_size=patch_size, resolution=resolution, units=units, pad_mode=pad_mode, pad_constant_values=pad_constant_values, within_bound=within_bound, min_mask_ratio=min_mask_ratio, ) if stride is None: self.stride = self.patch_size else: if isinstance(stride, (tuple, list)): self.stride = (int(stride[0]), int(stride[1])) else: self.stride = (int(stride), int(stride)) self._generate_location_df() class PointsPatchExtractor(PatchExtractor): """Extracting patches with specified points as a centre. Args: input_img(str, pathlib.Path, :class:`numpy.ndarray`): Input image for patch extraction. locations_list(ndarray, pd.DataFrame, str, pathlib.Path): Contains location and/or type of patch. This can be path to csv, npy or json files. Input can also be a :class:`numpy.ndarray` or :class:`pandas.DataFrame`. NOTE: value of location $(x,y)$ is expected to be based on the specified `resolution` and `units` (not the `'baseline'` resolution). patch_size(int or tuple(int)): Patch size tuple (width, height). resolution (int or float or tuple of float): Resolution at which to read the image, default = 0. Either a single number or a sequence of two numbers for x and y are valid. This value is in terms of the corresponding units. For example: resolution=0.5 and units="mpp" will read the slide at 0.5 microns per-pixel, and resolution=3, units="level" will read at level at pyramid level / resolution layer 3. units (str): The units of resolution, default = "level". Supported units are: microns per pixel (mpp), objective power (power), pyramid / resolution level (level), Only pyramid / resolution levels (level) embedded in the whole slide image are supported. pad_mode (str): Method for padding at edges of the WSI. Default to 'constant'. See :func:`numpy.pad` for more information. pad_constant_values (int or tuple(int)): Values to use with constant padding. Defaults to 0. See :func:`numpy.pad` for more. within_bound (bool): Whether to extract patches beyond the input_image size limits. If False, extracted patches at margins will be padded appropriately based on `pad_constant_values` and `pad_mode`. If False, patches at the margin that their bounds exceed the mother image dimensions would be neglected. Default is False. """ def __init__( self, input_img: Union[str, Path, np.ndarray], locations_list: Union[np.ndarray, DataFrame, str, Path], patch_size: Union[int, Tuple[int, int]] = (224, 224), resolution: Union[int, float, Tuple[float, float]] = 0, units: str = "level", pad_mode: str = "constant", pad_constant_values: Union[int, Tuple[int, int]] = 0, within_bound: bool = False, ): super().__init__( input_img=input_img, patch_size=patch_size, resolution=resolution, units=units, pad_mode=pad_mode, pad_constant_values=pad_constant_values, within_bound=within_bound, ) self.locations_df = misc.read_locations(input_table=locations_list) self.locations_df["x"] = self.locations_df["x"] - int( (self.patch_size[1] - 1) / 2 ) self.locations_df["y"] = self.locations_df["y"] - int( (self.patch_size[1] - 1) / 2 ) def get_patch_extractor( method_name: str, **kwargs: Union[ Path, wsireader.WSIReader, None, str, int, Tuple[int, int], float, Tuple[float, float], ], ): """Return a patch extractor object as requested. Args: method_name (str): Name of patch extraction method, must be one of "point" or "slidingwindow". The method name is case-insensitive. **kwargs: Keyword arguments passed to :obj:`PatchExtractor`. Returns: PatchExtractor: An object with base :obj:`PatchExtractor` as base class. Examples: >>> from tiatoolbox.tools.patchextraction import get_patch_extractor >>> # PointsPatchExtractor with default values >>> patch_extract = get_patch_extractor( ... 'point', img_patch_h=200, img_patch_w=200) """ if method_name.lower() not in ["point", "slidingwindow"]: raise MethodNotSupported( f"{method_name.lower()} method is not currently supported." ) if method_name.lower() == "point": return PointsPatchExtractor(**kwargs) return SlidingWindowPatchExtractor(**kwargs)
27,806
40.941176
87
py
tiatoolbox
tiatoolbox-master/tiatoolbox/tools/graph.py
"""Construction and visualisation of graphs for WSI prediction.""" from __future__ import annotations from collections import defaultdict from numbers import Number from typing import Callable, Dict, Optional, Union import numpy as np import torch import umap from matplotlib import pyplot as plt from matplotlib.axes import Axes from numpy.typing import ArrayLike from scipy.cluster import hierarchy from scipy.spatial import Delaunay, cKDTree def delaunay_adjacency(points: ArrayLike, dthresh: Number) -> list: """Create an adjacency matrix via Delaunay triangulation from a list of coordinates. Points which are further apart than dthresh will not be connected. See https://en.wikipedia.org/wiki/Adjacency_matrix. Args: points (ArrayLike): An nxm list of coordinates. dthresh (int): Distance threshold for triangulation. Returns: ArrayLike: Adjacency matrix of shape NxN where 1 indicates connected and 0 indicates unconnected. Example: >>> points = np.random.rand(100, 2) >>> adjacency = delaunay_adjacency(points) """ # Validate inputs if not isinstance(dthresh, Number): raise TypeError("dthresh must be a number.") if len(points) < 4: raise ValueError("Points must have length >= 4.") if len(np.shape(points)) != 2: raise ValueError("Points must have an NxM shape.") # Apply Delaunay triangulation to the coordinates to get a # tessellation of triangles. tessellation = Delaunay(points) # Find all connected neighbours for each point in the set of # triangles. Starting with an empty dictionary. triangle_neighbours = defaultdict(set) # Iterate over each triplet of point indexes which denotes a # triangle within the tessellation. for index_triplet in tessellation.simplices: for index in index_triplet: connected = set(index_triplet) connected.remove(index) # Do not allow connection to itself. triangle_neighbours[index] = triangle_neighbours[index].union(connected) # Initialise the nxn adjacency matrix with zeros. adjacency = np.zeros((len(points), len(points))) # Fill the adjacency matrix: for index in triangle_neighbours: neighbours = triangle_neighbours[index] neighbours = np.array(list(neighbours), dtype=int) kdtree = cKDTree(points[neighbours, :]) nearby_neighbours = kdtree.query_ball_point( x=points[index], r=dthresh, ) neighbours = neighbours[nearby_neighbours] adjacency[index, neighbours] = 1.0 adjacency[neighbours, index] = 1.0 # Return neighbours of each coordinate as an affinity (adjacency # in this case) matrix. return adjacency def triangle_signed_area(triangle: ArrayLike) -> int: """Determine the signed area of a triangle. Args: triangle (ArrayLike): A 3x2 list of coordinates. Returns: int: The signed area of the triangle. It will be negative if the triangle has a clockwise winding, negative if the triangle has a counter-clockwise winding, and zero if the triangles points are collinear. """ # Validate inputs triangle = np.asarray(triangle) if triangle.shape != (3, 2): raise ValueError("Input triangle must be a 3x2 array.") # Calculate the area of the triangle return 0.5 * ( # noqa: ECE001 triangle[0, 0] * (triangle[1, 1] - triangle[2, 1]) + triangle[1, 0] * (triangle[2, 1] - triangle[0, 1]) + triangle[2, 0] * (triangle[0, 1] - triangle[1, 1]) ) def edge_index_to_triangles(edge_index: ArrayLike) -> ArrayLike: """Convert an edged index to triangle simplices (triplets of coordinate indices). Args: edge_index (ArrayLike): An Nx2 array of edges. Returns: ArrayLike: An Nx3 array of triangles. Example: >>> points = np.random.rand(100, 2) >>> adjacency = delaunay_adjacency(points) >>> edge_index = affinity_to_edge_index(adjacency) >>> triangles = edge_index_to_triangles(edge_index) """ # Validate inputs edge_index_shape = np.shape(edge_index) if edge_index_shape[0] != 2 or len(edge_index_shape) != 2: raise ValueError("Input edge_index must be a 2xM matrix.") nodes = np.unique(edge_index).tolist() neighbours = defaultdict(set) edges = edge_index.T.tolist() # Find the neighbours of each node for a, b in edges: neighbours[a].add(b) neighbours[b].add(a) # Remove any nodes with less than two neighbours nodes = [node for node in nodes if len(neighbours[node]) >= 2] # Find the triangles triangles = set() for node in nodes: for neighbour in neighbours[node]: overlap = neighbours[node].intersection(neighbours[neighbour]) while overlap: triangles.add(frozenset({node, neighbour, overlap.pop()})) return np.array([list(tri) for tri in triangles], dtype=np.int32, order="C") def affinity_to_edge_index( affinity_matrix: Union[torch.Tensor, ArrayLike], threshold: Number = 0.5, ) -> Union[torch.tensor, ArrayLike]: """Convert an affinity matrix (similarity matrix) to an edge index. Converts an NxN affinity matrix to a 2xM edge index, where M is the number of node pairs with a similarity greater than the threshold value (defaults to 0.5). Args: affinity_matrix: An NxN matrix of affinities between nodes. threshold (Number): Threshold above which to be considered connected. Defaults to 0.5. Returns: ArrayLike or torch.Tensor: The edge index of shape (2, M). Example: >>> points = np.random.rand(100, 2) >>> adjacency = delaunay_adjacency(points) >>> edge_index = affinity_to_edge_index(adjacency) """ # Validate inputs input_shape = np.shape(affinity_matrix) if len(input_shape) != 2 or len(np.unique(input_shape)) != 1: raise ValueError("Input affinity_matrix must be square (NxN).") # Handle cases for pytorch and numpy inputs if isinstance(affinity_matrix, torch.Tensor): return (affinity_matrix > threshold).nonzero().t().contiguous() return np.ascontiguousarray( np.stack((affinity_matrix > threshold).nonzero(), axis=1).T ) class SlideGraphConstructor: # noqa: PIE798 """Construct a graph using the SlideGraph+ (Liu et al. 2021) method. This uses a hybrid agglomerative clustering which uses a weighted combination of spatial distance (within the WSI) and feature-space distance to group patches into nodes. See the `build` function for more details on the graph construction method. """ @staticmethod def _umap_reducer(graph: Dict[str, ArrayLike]) -> ArrayLike: """Default reduction which reduces `graph["x"]` to 3D values. Reduces graph features to 3D values using UMAP which are suitable for plotting as RGB values. Args: graph (dict): A graph with keys "x", "edge_index", and optionally "coordinates". Returns: ArrayLike: A UMAP embedding of `graph["x"]` with shape (N, 3) and values ranging from 0 to 1. """ reducer = umap.UMAP(n_components=3) reduced = reducer.fit_transform(graph["x"]) reduced -= reduced.min(axis=0) reduced /= reduced.max(axis=0) return reduced @staticmethod def build( points: ArrayLike, features: ArrayLike, lambda_d: Number = 3.0e-3, lambda_f: Number = 1.0e-3, lambda_h: Number = 0.8, connectivity_distance: Number = 4000, neighbour_search_radius: Number = 2000, feature_range_thresh: Optional[Number] = 1e-4, ) -> Dict[str, ArrayLike]: """Build a graph via hybrid clustering in spatial and feature space. The graph is constructed via hybrid hierarchical clustering followed by Delaunay triangulation of these cluster centroids. This is part of the SlideGraph pipeline but may be used to construct a graph in general from point coordinates and features. The clustering uses a distance kernel, ranging between 0 and 1, which is a weighted product of spatial distance (distance between coordinates in `points`, e.g. WSI location) and feature-space distance (e.g. ResNet features). Points which are spatially further apart than `neighbour_search_radius` are given a similarity of 1 (most dissimilar). This significantly speeds up computation. This distance metric is then used to form clusters via hierarchical/agglomerative clustering. Next, a Delaunay triangulation is applied to the clusters to connect the neighouring clusters. Only clusters which are closer than `connectivity_distance` in the spatial domain will be connected. Args: points (ArrayLike): A list of (x, y) spatial coordinates, e.g. pixel locations within a WSI. features (ArrayLike): A list of features associated with each coordinate in `points`. Must be the same length as `points`. lambda_d (Number): Spatial distance (d) weighting. lambda_f (Number): Feature distance (f) weighting. lambda_h (Number): Clustering distance threshold. Applied to the similarity kernel (1-fd). Ranges between 0 and 1. Defaults to 0.8. A good value for this parameter will depend on the intra-cluster variance. connectivity_distance (Number): Spatial distance threshold to consider points as connected during the Delaunay triangulation step. neighbour_search_radius (Number): Search radius (L2 norm) threshold for points to be considered as similar for clustering. Points with a spatial distance above this are not compared and have a similarity set to 1 (most dissimilar). feature_range_thresh (Number): Minimal range for which a feature is considered significant. Features which have a range less than this are ignored. Defaults to 1e-4. If falsy (None, False, 0, etc.), then no features are removed. Returns: dict: A dictionary defining a graph for serialisation (e.g. JSON or msgpack) or converting into a torch-geometric Data object where each node is the centroid (mean) of the features in a cluster. The dictionary has the following entries: - :class:`numpy.ndarray` - x: Features of each node (mean of features in a cluster). Required for torch-geometric Data. - :class:`numpy.ndarray` - edge_index: Edge index matrix defining connectivity. Required for torch-geometric Data. - :py:obj:`numpy.ndarray` - coords: Coordinates of each node within the WSI (mean of point in a cluster). Useful for visualisation over the WSI. Example: >>> points = np.random.rand(99, 2) * 1000 >>> features = np.array([ ... np.random.rand(11) * n ... for n, _ in enumerate(points) ... ]) >>> graph_dict = SlideGraphConstructor.build(points, features) """ # Remove features which do not change significantly between patches if feature_range_thresh: feature_ranges = np.max(features, axis=0) - np.min(features, axis=0) where_significant = feature_ranges > feature_range_thresh features = features[:, where_significant] # Build a kd-tree and rank neighbours according to the euclidean # distance (nearest -> farthest). kd_tree = cKDTree(points) neighbour_distances_ckd, neighbour_indexes_ckd = kd_tree.query( x=points, k=len(points) ) # Initialise an empty 1-D condensed distance matrix. # For information on condensed distance matrices see: # noqa - https://docs.scipy.org/doc/scipy/reference/generated/scipy.spatial.distance.pdist # noqa - https://docs.scipy.org/doc/scipy/reference/generated/scipy.cluster.hierarchy.linkage.html condensed_distance_matrix = np.zeros(int(len(points) * (len(points) - 1) / 2)) # Find the similarity between pairs of patches index = 0 for i in range(len(points) - 1): # Only consider neighbours which are inside the radius # (neighbour_search_radius). neighbour_distances_single_point = neighbour_distances_ckd[i][ neighbour_distances_ckd[i] < neighbour_search_radius ] neighbour_indexes_single_point = neighbour_indexes_ckd[i][ : len(neighbour_distances_single_point) ] # Called f in the paper neighbour_feature_similarities = np.exp( -lambda_f * np.linalg.norm( features[i] - features[neighbour_indexes_single_point], axis=1 ) ) # Called d in paper neighbour_distance_similarities = np.exp( -lambda_d * neighbour_distances_single_point ) # 1 - product of similarities (1 - fd) # (1 = most un-similar 0 = most similar) neighbour_similarities = ( 1 - neighbour_feature_similarities * neighbour_distance_similarities ) # Initialise similarity of coordinate i vs all coordinates to 1 # (most un-similar). i_vs_all_similarities = np.ones(len(points)) # Set the neighbours similarity to calculated values (similarity/fd) i_vs_all_similarities[ neighbour_indexes_single_point ] = neighbour_similarities i_vs_all_similarities = i_vs_all_similarities[i + 1 :] condensed_distance_matrix[ index : index + len(i_vs_all_similarities) ] = i_vs_all_similarities index = index + len(i_vs_all_similarities) # Perform hierarchical clustering (using similarity as distance) linkage_matrix = hierarchy.linkage(condensed_distance_matrix, method="average") clusters = hierarchy.fcluster(linkage_matrix, lambda_h, criterion="distance") # Finding the xy centroid and average features for each cluster unique_clusters = list(set(clusters)) point_centroids = [] feature_centroids = [] for c in unique_clusters: (idx,) = np.where(clusters == c) # Find the xy and feature space averages of the cluster point_centroids.append(np.round(points[idx, :].mean(axis=0))) feature_centroids.append(features[idx, :].mean(axis=0)) point_centroids = np.array(point_centroids) feature_centroids = np.array(feature_centroids) adjacency_matrix = delaunay_adjacency( points=point_centroids, dthresh=connectivity_distance, ) edge_index = affinity_to_edge_index(adjacency_matrix) return { "x": feature_centroids, "edge_index": edge_index, "coordinates": point_centroids, } @classmethod def visualise( cls, graph: Dict[str, ArrayLike], color: Union[ArrayLike, str, Callable] = None, node_size: Union[Number, ArrayLike, Callable] = 25, edge_color: Union[str, ArrayLike] = (0, 0, 0, 0.33), ax: Axes = None, ) -> Axes: """Visualise a graph. The visualisation is a scatter plot of the graph nodes and the connections between them. By default, nodes are coloured according to the features of the graph via a UMAP embedding to the sRGB color space. This can be customised by passing a color argument which can be a single color, a list of colors, or a function which takes the graph and returns a list of colors for each node. The edge color(s) can be customised in the same way. Args: graph (dict): The graph to visualise as a dictionary with the following entries: - :class:`numpy.ndarray` - x: Features of each node (mean of features in a cluster). Required - :class:`numpy.ndarray` - edge_index: Edge index matrix defining connectivity. Required - :class:`numpy.ndarray` - coordinates: Coordinates of each node within the WSI (mean of point in a cluster). Required color (np.array or str or callable): Colours of the nodes in the plot. If it is a callable, it should take a graph as input and return a numpy array of matplotlib colours. If `None` then a default function is used (UMAP on `graph["x"]`). node_size (int or np.ndarray or callable): Size of the nodes in the plot. If it is a function then it is called with the graph as an argument. edge_color (str): Colour of edges in the graph plot. ax (:class:`matplotlib.axes.Axes`): The axes which were plotted on. Returns: matplotlib.axes.Axes: The axes object to plot the graph on. Example: >>> points = np.random.rand(99, 2) * 1000 >>> features = np.array([ ... np.random.rand(11) * n ... for n, _ in enumerate(points) ... ]) >>> graph_dict = SlideGraphConstructor.build(points, features) >>> fig, ax = plt.subplots() >>> slide_dims = wsi.info.slide_dimensions >>> ax.imshow(wsi.get_thumbnail(), extent=(0, *slide_dims, 0)) >>> SlideGraphConstructor.visualise(graph_dict, ax=ax) >>> plt.show() """ from matplotlib import collections as mc # Check that the graph is valid if "x" not in graph: raise ValueError("Graph must contain key `x`.") if "edge_index" not in graph: raise ValueError("Graph must contain key `edge_index`.") if "coordinates" not in graph: raise ValueError("Graph must contain key `coordinates`") if ax is None: _, ax = plt.subplots() if color is None: color = cls._umap_reducer nodes = graph["coordinates"] edges = graph["edge_index"] # Plot the edges line_segments = nodes[edges.T] edge_collection = mc.LineCollection( line_segments, colors=edge_color, linewidths=1 ) ax.add_collection(edge_collection) # Plot the nodes plt.scatter( *nodes.T, c=color(graph) if isinstance(color, Callable) else color, s=node_size(graph) if isinstance(node_size, Callable) else node_size, zorder=2, ) return ax
19,823
38.807229
106
py