diff --git a/.pre-commit-config.yaml b/.pre-commit-config.yaml index 213d5dfd0..78fe86fd1 100644 --- a/.pre-commit-config.yaml +++ b/.pre-commit-config.yaml @@ -38,6 +38,38 @@ repos: args: ["--fix", "--show-fixes", "--exit-non-zero-on-fix"] - id: ruff-format + - repo: https://github.com/pre-commit/mirrors-mypy + rev: "v1.10.0" + hooks: + - id: mypy + additional_dependencies: + - types-aiofiles + - types-requests + - pandas-stubs + - types-pillow + - matplotlib + exclude: | + (?x)( + ^build/ + | ^pyximages/ + | conf\.py$ + | .*/setup.*\.py$ + | .*/demo.py$ + | .*/auto_examples/ + | advanced/mathematical_optimization/examples/plot_gradient_descent\.py$ + | advanced/mathematical_optimization/examples/helper/compare_optimizers\.py$ + | advanced/advanced_numpy/examples/view-colors\.py$ + | advanced/advanced_numpy/examples/stride-diagonals\.py$ + | advanced/interfacing_with_c/cython_numpy/test_cos_doubles\.py$ + | advanced/interfacing_with_c/numpy_shared/test_cos_doubles\.py$ + | advanced/interfacing_with_c/swig.*\.py$ + | advanced/advanced_numpy/examples/myobject_test\.py$ + | advanced/interfacing_with_c/numpy_shared/test_cos_doubles\.py$ + | advanced/interfacing_with_c/numpy_c_api/test_cos_module_np\.py$ + | intro/numpy/solutions/2_a_call_fortran\.py$ + | advanced/advanced_numpy/examples/mandelplot\.py$ + ) + - repo: https://github.com/codespell-project/codespell rev: 193cd7d27cd571f79358af09a8fb8997e54f8fff # frozen: v2.3.0 hooks: diff --git a/advanced/advanced_numpy/examples/pilbuffer-answer.py b/advanced/advanced_numpy/examples/pilbuffer-answer.py index 62e6255e8..694256df4 100644 --- a/advanced/advanced_numpy/examples/pilbuffer-answer.py +++ b/advanced/advanced_numpy/examples/pilbuffer-answer.py @@ -7,13 +7,13 @@ """ import numpy as np -import Image +from PIL import Image # Let's make a sample image, RGBA format -x = np.zeros((200, 200, 4), dtype=np.int8) +x = np.zeros((200, 200, 4), dtype=np.uint8) -x[:, :, 0] = 254 # red +x[:, :, 0] = 255 # red x[:, :, 3] = 255 # opaque data = x.view(np.int32) # Check that you understand why this is OK! @@ -21,12 +21,7 @@ img = Image.frombuffer("RGBA", (200, 200), data) img.save("test.png") -# # Modify the original data, and save again. -# -# It turns out that PIL, which knows next to nothing about NumPy, -# happily shares the same data. -# -x[:, :, 1] = 254 +x[:, :, 1] = 255 img.save("test2.png") diff --git a/advanced/advanced_numpy/examples/pilbuffer.py b/advanced/advanced_numpy/examples/pilbuffer.py index d1a60a960..1e5b63834 100644 --- a/advanced/advanced_numpy/examples/pilbuffer.py +++ b/advanced/advanced_numpy/examples/pilbuffer.py @@ -1,21 +1,23 @@ """ -Exercise: using the buffer protocole -==================================== +Exercise: using the buffer protocol +=================================== -Skeletton of the code to do an exercise using the buffer protocole. +Skeleton of the code to do an exercise using the buffer protocole. """ import numpy as np -import Image +from PIL import Image # Let's make a sample image, RGBA format -x = np.zeros((200, 200, 4), dtype=np.int8) +x = np.zeros((200, 200, 4), dtype=np.uint8) -# TODO: fill `x` with fully opaque red [255, 0, 0, 255] +# TODO: fill `data` with fully opaque red [255, 0, 0, 255] -# TODO: RGBA images consist of 32-bit integers whose bytes are [RR,GG,BB,AA] -# How to get that from ``x``? +# TODO: `x` is an array of bytes (8-bit integers) +# What we need for PIL to understand this data is RGBA array, +# where each element is a 32-bit integer, with bytes [RR,GG,BB,AA]. +# How do we convert `x` to such an array, called `data`? data = ... diff --git a/advanced/advanced_numpy/examples/plots/plot_maskedstats.py b/advanced/advanced_numpy/examples/plots/plot_maskedstats.py index e6c4198d5..8b015217d 100644 --- a/advanced/advanced_numpy/examples/plots/plot_maskedstats.py +++ b/advanced/advanced_numpy/examples/plots/plot_maskedstats.py @@ -10,7 +10,7 @@ import matplotlib.pyplot as plt data = np.loadtxt("../../../../data/populations.txt") -populations = np.ma.masked_array(data[:, 1:]) +populations = np.ma.masked_array(data[:, 1:]) # type: ignore[var-annotated] year = data[:, 0] bad_years = ((year >= 1903) & (year <= 1910)) | ((year >= 1917) & (year <= 1918)) diff --git a/advanced/debugging/to_debug_solution.py b/advanced/debugging/to_debug_solution.py index 53a600e96..48d929396 100644 --- a/advanced/debugging/to_debug_solution.py +++ b/advanced/debugging/to_debug_solution.py @@ -57,11 +57,7 @@ def compare_optimizers(optimizers): """ random_a = -1.3 + rng.random(size=100) random_b = 0.3 + rng.random(size=100) - param_grid = product(FUNCTIONS, random_a, random_b) - values = [] - for value in param_grid: - values.append(value) - param_grid = values + param_grid = list(product(FUNCTIONS, random_a, random_b)) print("Benching 1D root-finder optimizers from scipy.optimize:") for optimizer in OPTIMIZERS: print( diff --git a/advanced/debugging/wiener_filtering.py b/advanced/debugging/wiener_filtering.py index 6e805b0ea..ae7f247bb 100644 --- a/advanced/debugging/wiener_filtering.py +++ b/advanced/debugging/wiener_filtering.py @@ -46,10 +46,10 @@ def iterated_wiener(noisy_img, size=3): face = sp.datasets.face(gray=True) noisy_face = face + 20 * rng.integers(3, size=face.shape) - 30 -plt.matshow(face[cut], cmap=plt.cm.gray) -plt.matshow(noisy_face[cut], cmap=plt.cm.gray) +plt.matshow(face[cut], cmap="gray") +plt.matshow(noisy_face[cut], cmap="gray") denoised_face = iterated_wiener(noisy_face) -plt.matshow(denoised_face[cut], cmap=plt.cm.gray) +plt.matshow(denoised_face[cut], cmap="gray") plt.show() diff --git a/advanced/image_processing/examples/plot_GMM.py b/advanced/image_processing/examples/plot_GMM.py index 53cc84ee2..afc85be62 100644 --- a/advanced/image_processing/examples/plot_GMM.py +++ b/advanced/image_processing/examples/plot_GMM.py @@ -47,7 +47,7 @@ plt.text(0.57, 0.8, "histogram", fontsize=20, transform=plt.gca().transAxes) plt.yticks([]) plt.subplot(133) -plt.imshow(binary_img, cmap=plt.cm.gray, interpolation="nearest") +plt.imshow(binary_img, cmap="gray", interpolation="nearest") plt.axis("off") plt.subplots_adjust(wspace=0.02, hspace=0.3, top=1, bottom=0.1, left=0, right=1) diff --git a/advanced/image_processing/examples/plot_block_mean.py b/advanced/image_processing/examples/plot_block_mean.py index bfd491a35..4cc4d6ef3 100644 --- a/advanced/image_processing/examples/plot_block_mean.py +++ b/advanced/image_processing/examples/plot_block_mean.py @@ -19,7 +19,7 @@ block_mean.shape = (sx // 4, sy // 6) plt.figure(figsize=(5, 5)) -plt.imshow(block_mean, cmap=plt.cm.gray) +plt.imshow(block_mean, cmap="gray") plt.axis("off") plt.show() diff --git a/advanced/image_processing/examples/plot_blur.py b/advanced/image_processing/examples/plot_blur.py index c54649764..cfb6f5759 100644 --- a/advanced/image_processing/examples/plot_blur.py +++ b/advanced/image_processing/examples/plot_blur.py @@ -15,13 +15,13 @@ plt.figure(figsize=(9, 3)) plt.subplot(131) -plt.imshow(blurred_face, cmap=plt.cm.gray) +plt.imshow(blurred_face, cmap="gray") plt.axis("off") plt.subplot(132) -plt.imshow(very_blurred, cmap=plt.cm.gray) +plt.imshow(very_blurred, cmap="gray") plt.axis("off") plt.subplot(133) -plt.imshow(local_mean, cmap=plt.cm.gray) +plt.imshow(local_mean, cmap="gray") plt.axis("off") plt.subplots_adjust(wspace=0, hspace=0.0, top=0.99, bottom=0.01, left=0.01, right=0.99) diff --git a/advanced/image_processing/examples/plot_clean_morpho.py b/advanced/image_processing/examples/plot_clean_morpho.py index 2fc05c358..cdcd1dc49 100644 --- a/advanced/image_processing/examples/plot_clean_morpho.py +++ b/advanced/image_processing/examples/plot_clean_morpho.py @@ -36,16 +36,16 @@ l = 128 plt.subplot(141) -plt.imshow(binary_img[:l, :l], cmap=plt.cm.gray) +plt.imshow(binary_img[:l, :l], cmap="gray") plt.axis("off") plt.subplot(142) -plt.imshow(open_img[:l, :l], cmap=plt.cm.gray) +plt.imshow(open_img[:l, :l], cmap="gray") plt.axis("off") plt.subplot(143) -plt.imshow(close_img[:l, :l], cmap=plt.cm.gray) +plt.imshow(close_img[:l, :l], cmap="gray") plt.axis("off") plt.subplot(144) -plt.imshow(mask[:l, :l], cmap=plt.cm.gray) +plt.imshow(mask[:l, :l], cmap="gray") plt.contour(close_img[:l, :l], [0.5], linewidths=2, colors="r") plt.axis("off") diff --git a/advanced/image_processing/examples/plot_denoising.py b/advanced/image_processing/examples/plot_denoising.py index f20443720..c460290a4 100644 --- a/advanced/image_processing/examples/plot_denoising.py +++ b/advanced/image_processing/examples/plot_denoising.py @@ -34,7 +34,7 @@ plt.axis("off") plt.title("Median filter", fontsize=20) plt.subplot(144) -plt.imshow(np.abs(im - im_med), cmap=plt.cm.hot, interpolation="nearest") +plt.imshow(np.abs(im - im_med), cmap="hot", interpolation="nearest") plt.axis("off") plt.title("Error", fontsize=20) diff --git a/advanced/image_processing/examples/plot_display_face.py b/advanced/image_processing/examples/plot_display_face.py index 1175f043a..4e4ff948a 100644 --- a/advanced/image_processing/examples/plot_display_face.py +++ b/advanced/image_processing/examples/plot_display_face.py @@ -13,14 +13,14 @@ plt.figure(figsize=(10, 3.6)) plt.subplot(131) -plt.imshow(f, cmap=plt.cm.gray) +plt.imshow(f, cmap="gray") plt.subplot(132) -plt.imshow(f, cmap=plt.cm.gray, vmin=30, vmax=200) +plt.imshow(f, cmap="gray", vmin=30, vmax=200) plt.axis("off") plt.subplot(133) -plt.imshow(f, cmap=plt.cm.gray) +plt.imshow(f, cmap="gray") plt.contour(f, [50, 200]) plt.axis("off") diff --git a/advanced/image_processing/examples/plot_face_denoise.py b/advanced/image_processing/examples/plot_face_denoise.py index c6760596c..29601d2a4 100644 --- a/advanced/image_processing/examples/plot_face_denoise.py +++ b/advanced/image_processing/examples/plot_face_denoise.py @@ -23,15 +23,15 @@ plt.figure(figsize=(12, 2.8)) plt.subplot(131) -plt.imshow(noisy, cmap=plt.cm.gray, vmin=40, vmax=220) +plt.imshow(noisy, cmap="gray", vmin=40, vmax=220) plt.axis("off") plt.title("noisy", fontsize=20) plt.subplot(132) -plt.imshow(gauss_denoised, cmap=plt.cm.gray, vmin=40, vmax=220) +plt.imshow(gauss_denoised, cmap="gray", vmin=40, vmax=220) plt.axis("off") plt.title("Gaussian filter", fontsize=20) plt.subplot(133) -plt.imshow(med_denoised, cmap=plt.cm.gray, vmin=40, vmax=220) +plt.imshow(med_denoised, cmap="gray", vmin=40, vmax=220) plt.axis("off") plt.title("Median filter", fontsize=20) diff --git a/advanced/image_processing/examples/plot_face_tv_denoise.py b/advanced/image_processing/examples/plot_face_tv_denoise.py index 2f0e2c187..e1522f00c 100644 --- a/advanced/image_processing/examples/plot_face_tv_denoise.py +++ b/advanced/image_processing/examples/plot_face_tv_denoise.py @@ -24,17 +24,17 @@ plt.figure(figsize=(12, 2.8)) plt.subplot(131) -plt.imshow(noisy, cmap=plt.cm.gray, vmin=40, vmax=220) +plt.imshow(noisy, cmap="gray", vmin=40, vmax=220) plt.axis("off") plt.title("noisy", fontsize=20) plt.subplot(132) -plt.imshow(tv_denoised, cmap=plt.cm.gray, vmin=40, vmax=220) +plt.imshow(tv_denoised, cmap="gray", vmin=40, vmax=220) plt.axis("off") plt.title("TV denoising", fontsize=20) tv_denoised = denoise_tv_chambolle(noisy, weight=50) plt.subplot(133) -plt.imshow(tv_denoised, cmap=plt.cm.gray, vmin=40, vmax=220) +plt.imshow(tv_denoised, cmap="gray", vmin=40, vmax=220) plt.axis("off") plt.title("(more) TV denoising", fontsize=20) diff --git a/advanced/image_processing/examples/plot_find_edges.py b/advanced/image_processing/examples/plot_find_edges.py index bd3d77fe9..02816698d 100644 --- a/advanced/image_processing/examples/plot_find_edges.py +++ b/advanced/image_processing/examples/plot_find_edges.py @@ -23,7 +23,7 @@ plt.figure(figsize=(16, 5)) plt.subplot(141) -plt.imshow(im, cmap=plt.cm.gray) +plt.imshow(im, cmap="gray") plt.axis("off") plt.title("square", fontsize=20) plt.subplot(142) diff --git a/advanced/image_processing/examples/plot_find_object.py b/advanced/image_processing/examples/plot_find_object.py index 0a0e351c1..9531bd253 100644 --- a/advanced/image_processing/examples/plot_find_object.py +++ b/advanced/image_processing/examples/plot_find_object.py @@ -35,7 +35,7 @@ roi = im[slice_x, slice_y] plt.figure(figsize=(4, 2)) -plt.axes([0, 0, 1, 1]) +plt.axes((0, 0, 1, 1)) plt.imshow(roi) plt.axis("off") diff --git a/advanced/image_processing/examples/plot_geom_face.py b/advanced/image_processing/examples/plot_geom_face.py index b388f069e..e824c4f99 100644 --- a/advanced/image_processing/examples/plot_geom_face.py +++ b/advanced/image_processing/examples/plot_geom_face.py @@ -23,19 +23,19 @@ plt.subplot(151) -plt.imshow(face, cmap=plt.cm.gray) +plt.imshow(face, cmap="gray") plt.axis("off") plt.subplot(152) -plt.imshow(crop_face, cmap=plt.cm.gray) +plt.imshow(crop_face, cmap="gray") plt.axis("off") plt.subplot(153) -plt.imshow(flip_ud_face, cmap=plt.cm.gray) +plt.imshow(flip_ud_face, cmap="gray") plt.axis("off") plt.subplot(154) -plt.imshow(rotate_face, cmap=plt.cm.gray) +plt.imshow(rotate_face, cmap="gray") plt.axis("off") plt.subplot(155) -plt.imshow(rotate_face_noreshape, cmap=plt.cm.gray) +plt.imshow(rotate_face_noreshape, cmap="gray") plt.axis("off") plt.subplots_adjust(wspace=0.02, hspace=0.3, top=1, bottom=0.1, left=0, right=1) diff --git a/advanced/image_processing/examples/plot_granulo.py b/advanced/image_processing/examples/plot_granulo.py index d6989bb58..215e0344a 100644 --- a/advanced/image_processing/examples/plot_granulo.py +++ b/advanced/image_processing/examples/plot_granulo.py @@ -44,7 +44,7 @@ def granulometry(data, sizes=None): plt.figure(figsize=(6, 2.2)) plt.subplot(121) -plt.imshow(mask, cmap=plt.cm.gray) +plt.imshow(mask, cmap="gray") opened = sp.ndimage.binary_opening(mask, structure=disk_structure(10)) opened_more = sp.ndimage.binary_opening(mask, structure=disk_structure(14)) plt.contour(opened, [0.5], colors="b", linewidths=2) diff --git a/advanced/image_processing/examples/plot_greyscale_dilation.py b/advanced/image_processing/examples/plot_greyscale_dilation.py index 39289756c..2ede10a98 100644 --- a/advanced/image_processing/examples/plot_greyscale_dilation.py +++ b/advanced/image_processing/examples/plot_greyscale_dilation.py @@ -23,16 +23,16 @@ plt.figure(figsize=(12.5, 3)) plt.subplot(141) -plt.imshow(im, interpolation="nearest", cmap=plt.cm.nipy_spectral) +plt.imshow(im, interpolation="nearest", cmap="nipy_spectral") plt.axis("off") plt.subplot(142) -plt.imshow(bigger_points, interpolation="nearest", cmap=plt.cm.nipy_spectral) +plt.imshow(bigger_points, interpolation="nearest", cmap="nipy_spectral") plt.axis("off") plt.subplot(143) -plt.imshow(dist, interpolation="nearest", cmap=plt.cm.nipy_spectral) +plt.imshow(dist, interpolation="nearest", cmap="nipy_spectral") plt.axis("off") plt.subplot(144) -plt.imshow(dilate_dist, interpolation="nearest", cmap=plt.cm.nipy_spectral) +plt.imshow(dilate_dist, interpolation="nearest", cmap="nipy_spectral") plt.axis("off") plt.subplots_adjust(wspace=0, hspace=0.02, top=0.99, bottom=0.01, left=0.01, right=0.99) diff --git a/advanced/image_processing/examples/plot_histo_segmentation.py b/advanced/image_processing/examples/plot_histo_segmentation.py index c2be12baf..81d225f2d 100644 --- a/advanced/image_processing/examples/plot_histo_segmentation.py +++ b/advanced/image_processing/examples/plot_histo_segmentation.py @@ -39,7 +39,7 @@ plt.text(0.57, 0.8, "histogram", fontsize=20, transform=plt.gca().transAxes) plt.yticks([]) plt.subplot(133) -plt.imshow(binary_img, cmap=plt.cm.gray, interpolation="nearest") +plt.imshow(binary_img, cmap="gray", interpolation="nearest") plt.axis("off") plt.subplots_adjust(wspace=0.02, hspace=0.3, top=1, bottom=0.1, left=0, right=1) diff --git a/advanced/image_processing/examples/plot_interpolation_face.py b/advanced/image_processing/examples/plot_interpolation_face.py index 0b6406e83..e89f25a99 100644 --- a/advanced/image_processing/examples/plot_interpolation_face.py +++ b/advanced/image_processing/examples/plot_interpolation_face.py @@ -13,11 +13,11 @@ plt.figure(figsize=(8, 4)) plt.subplot(1, 2, 1) -plt.imshow(f[320:340, 510:530], cmap=plt.cm.gray) +plt.imshow(f[320:340, 510:530], cmap="gray") plt.axis("off") plt.subplot(1, 2, 2) -plt.imshow(f[320:340, 510:530], cmap=plt.cm.gray, interpolation="nearest") +plt.imshow(f[320:340, 510:530], cmap="gray", interpolation="nearest") plt.axis("off") plt.subplots_adjust(wspace=0.02, hspace=0.02, top=1, bottom=0, left=0, right=1) diff --git a/advanced/image_processing/examples/plot_measure_data.py b/advanced/image_processing/examples/plot_measure_data.py index f18ed1a3e..91ef02b87 100644 --- a/advanced/image_processing/examples/plot_measure_data.py +++ b/advanced/image_processing/examples/plot_measure_data.py @@ -33,10 +33,10 @@ plt.figure(figsize=(6, 3)) plt.subplot(121) -plt.imshow(label_im, cmap=plt.cm.nipy_spectral) +plt.imshow(label_im, cmap="nipy_spectral") plt.axis("off") plt.subplot(122) -plt.imshow(label_clean, vmax=nb_labels, cmap=plt.cm.nipy_spectral) +plt.imshow(label_clean, vmax=nb_labels, cmap="nipy_spectral") plt.axis("off") plt.subplots_adjust(wspace=0.01, hspace=0.01, top=1, bottom=0, left=0, right=1) diff --git a/advanced/image_processing/examples/plot_numpy_array.py b/advanced/image_processing/examples/plot_numpy_array.py index 3837a94b3..4a8a32417 100644 --- a/advanced/image_processing/examples/plot_numpy_array.py +++ b/advanced/image_processing/examples/plot_numpy_array.py @@ -22,8 +22,8 @@ face[range(400), range(400)] = 255 plt.figure(figsize=(3, 3)) -plt.axes([0, 0, 1, 1]) -plt.imshow(face, cmap=plt.cm.gray) +plt.axes((0, 0, 1, 1)) +plt.imshow(face, cmap="gray") plt.axis("off") plt.show() diff --git a/advanced/image_processing/examples/plot_propagation.py b/advanced/image_processing/examples/plot_propagation.py index a0598a09c..9a98c2636 100644 --- a/advanced/image_processing/examples/plot_propagation.py +++ b/advanced/image_processing/examples/plot_propagation.py @@ -22,13 +22,13 @@ plt.figure(figsize=(9.5, 3)) plt.subplot(131) -plt.imshow(square, cmap=plt.cm.gray, interpolation="nearest") +plt.imshow(square, cmap="gray", interpolation="nearest") plt.axis("off") plt.subplot(132) -plt.imshow(open_square, cmap=plt.cm.gray, interpolation="nearest") +plt.imshow(open_square, cmap="gray", interpolation="nearest") plt.axis("off") plt.subplot(133) -plt.imshow(reconstruction, cmap=plt.cm.gray, interpolation="nearest") +plt.imshow(reconstruction, cmap="gray", interpolation="nearest") plt.axis("off") plt.subplots_adjust(wspace=0, hspace=0.02, top=0.99, bottom=0.01, left=0.01, right=0.99) diff --git a/advanced/image_processing/examples/plot_radial_mean.py b/advanced/image_processing/examples/plot_radial_mean.py index 9e36962c6..6f8373d44 100644 --- a/advanced/image_processing/examples/plot_radial_mean.py +++ b/advanced/image_processing/examples/plot_radial_mean.py @@ -20,8 +20,8 @@ radial_mean = sp.ndimage.mean(f, labels=rbin, index=np.arange(1, rbin.max() + 1)) plt.figure(figsize=(5, 5)) -plt.axes([0, 0, 1, 1]) -plt.imshow(rbin, cmap=plt.cm.nipy_spectral) +plt.axes((0, 0, 1, 1)) +plt.imshow(rbin, cmap="nipy_spectral") plt.axis("off") plt.show() diff --git a/advanced/image_processing/examples/plot_sharpen.py b/advanced/image_processing/examples/plot_sharpen.py index 07816f296..8f8e65a5a 100644 --- a/advanced/image_processing/examples/plot_sharpen.py +++ b/advanced/image_processing/examples/plot_sharpen.py @@ -20,13 +20,13 @@ plt.figure(figsize=(12, 4)) plt.subplot(131) -plt.imshow(f, cmap=plt.cm.gray) +plt.imshow(f, cmap="gray") plt.axis("off") plt.subplot(132) -plt.imshow(blurred_f, cmap=plt.cm.gray) +plt.imshow(blurred_f, cmap="gray") plt.axis("off") plt.subplot(133) -plt.imshow(sharpened, cmap=plt.cm.gray) +plt.imshow(sharpened, cmap="gray") plt.axis("off") plt.tight_layout() diff --git a/advanced/image_processing/examples/plot_spectral_clustering.py b/advanced/image_processing/examples/plot_spectral_clustering.py index 9f72018ad..69d58341e 100644 --- a/advanced/image_processing/examples/plot_spectral_clustering.py +++ b/advanced/image_processing/examples/plot_spectral_clustering.py @@ -52,10 +52,10 @@ plt.figure(figsize=(6, 3)) plt.subplot(121) -plt.imshow(img, cmap=plt.cm.nipy_spectral, interpolation="nearest") +plt.imshow(img, cmap="nipy_spectral", interpolation="nearest") plt.axis("off") plt.subplot(122) -plt.imshow(label_im, cmap=plt.cm.nipy_spectral, interpolation="nearest") +plt.imshow(label_im, cmap="nipy_spectral", interpolation="nearest") plt.axis("off") plt.subplots_adjust(wspace=0, hspace=0.0, top=0.99, bottom=0.01, left=0.01, right=0.99) diff --git a/advanced/image_processing/examples/plot_synthetic_data.py b/advanced/image_processing/examples/plot_synthetic_data.py index 31059bb56..1c5e47ce0 100644 --- a/advanced/image_processing/examples/plot_synthetic_data.py +++ b/advanced/image_processing/examples/plot_synthetic_data.py @@ -27,10 +27,10 @@ plt.imshow(im) plt.axis("off") plt.subplot(132) -plt.imshow(mask, cmap=plt.cm.gray) +plt.imshow(mask, cmap="gray") plt.axis("off") plt.subplot(133) -plt.imshow(label_im, cmap=plt.cm.nipy_spectral) +plt.imshow(label_im, cmap="nipy_spectral") plt.axis("off") plt.subplots_adjust(wspace=0.02, hspace=0.02, top=1, bottom=0, left=0, right=1) diff --git a/advanced/interfacing_with_c/ctypes/cos_module.py b/advanced/interfacing_with_c/ctypes/cos_module.py index 23e60a624..6ca63a8f1 100644 --- a/advanced/interfacing_with_c/ctypes/cos_module.py +++ b/advanced/interfacing_with_c/ctypes/cos_module.py @@ -7,7 +7,10 @@ # OSX or linux from ctypes.util import find_library -libm = ctypes.cdll.LoadLibrary(find_library("m")) +libm_name = find_library("m") +assert libm_name is not None, "Cannot find libm (math) on this system :/ That's bad." + +libm = ctypes.cdll.LoadLibrary(libm_name) # Windows # from ctypes import windll diff --git a/advanced/mathematical_optimization/examples/plot_1d_optim.py b/advanced/mathematical_optimization/examples/plot_1d_optim.py index cedc15395..6b0ad89c9 100644 --- a/advanced/mathematical_optimization/examples/plot_1d_optim.py +++ b/advanced/mathematical_optimization/examples/plot_1d_optim.py @@ -19,7 +19,7 @@ def f(x): for epsilon in (0, 1): plt.figure(figsize=(3, 2.5)) - plt.axes([0, 0, 1, 1]) + plt.axes((0, 0, 1, 1)) # A convex function plt.plot(x, f(x), linewidth=2) @@ -47,7 +47,7 @@ def f(x): plt.text( this_x - 0.05 * np.sign(this_x) - 0.05, f(this_x) + 1.2 * (0.3 - iter % 2), - iter + 1, + str(iter + 1), size=12, ) diff --git a/advanced/mathematical_optimization/examples/plot_compare_optimizers.py b/advanced/mathematical_optimization/examples/plot_compare_optimizers.py index 2e75f75f8..034106cbf 100644 --- a/advanced/mathematical_optimization/examples/plot_compare_optimizers.py +++ b/advanced/mathematical_optimization/examples/plot_compare_optimizers.py @@ -10,6 +10,8 @@ import sys import numpy as np + +import matplotlib import matplotlib.pyplot as plt results = pickle.load( @@ -23,7 +25,8 @@ plt.figure(1, figsize=(10, 4)) plt.clf() -colors = plt.cm.nipy_spectral(np.linspace(0, 1, n_dims))[:, :3] +nipy_spectral = matplotlib.colormaps["nipy_spectral"] +colors = nipy_spectral(np.linspace(0, 1, n_dims))[:, :3] method_names = list(list(results.values())[0]["Rosenbrock "].keys()) method_names.sort(key=lambda x: x[::-1], reverse=True) diff --git a/advanced/mathematical_optimization/examples/plot_constraints.py b/advanced/mathematical_optimization/examples/plot_constraints.py index d1388d15b..05d55e079 100644 --- a/advanced/mathematical_optimization/examples/plot_constraints.py +++ b/advanced/mathematical_optimization/examples/plot_constraints.py @@ -9,7 +9,7 @@ import matplotlib.pyplot as plt import scipy as sp -x, y = np.mgrid[-2.9:5.8:0.05, -2.5:5:0.05] +x, y = np.mgrid[-2.9:5.8:0.05, -2.5:5:0.05] # type: ignore[misc] x = x.T y = y.T @@ -18,12 +18,12 @@ # path plt.figure(i, figsize=(3, 2.5)) plt.clf() - plt.axes([0, 0, 1, 1]) + plt.axes((0, 0, 1, 1)) contours = plt.contour( np.sqrt((x - 3) ** 2 + (y - 2) ** 2), extent=[-3, 6, -2.5, 5], - cmap=plt.cm.gnuplot, + cmap="gnuplot", ) plt.clabel(contours, inline=1, fmt="%1.1f", fontsize=14) plt.plot( diff --git a/advanced/mathematical_optimization/examples/plot_exercise_flat_minimum.py b/advanced/mathematical_optimization/examples/plot_exercise_flat_minimum.py index 56cb87ac8..a8cc42199 100644 --- a/advanced/mathematical_optimization/examples/plot_exercise_flat_minimum.py +++ b/advanced/mathematical_optimization/examples/plot_exercise_flat_minimum.py @@ -48,11 +48,9 @@ def g_prime(x): plt.figure(1) plt.clf() -X, Y = np.mgrid[-1.5:1.5:100j, -1.1:1.1:100j] -plt.imshow( - f([X, Y]).T, cmap=plt.cm.gray_r, extent=[-1.5, 1.5, -1.1, 1.1], origin="lower" -) -plt.contour(X, Y, f([X, Y]), cmap=plt.cm.gnuplot) +X, Y = np.mgrid[-1.5:1.5:100j, -1.1:1.1:100j] # type: ignore[misc] +plt.imshow(f([X, Y]).T, cmap="gray_r", extent=(-1.5, 1.5, -1.1, 1.1), origin="lower") +plt.contour(X, Y, f([X, Y]), cmap="gnuplot") # Plot the gradient dX, dY = g_prime([0.1 * X[::5, ::5], Y[::5, ::5]]) diff --git a/advanced/mathematical_optimization/examples/plot_exercise_ill_conditioned.py b/advanced/mathematical_optimization/examples/plot_exercise_ill_conditioned.py index dbffbcc07..c2a557ddb 100644 --- a/advanced/mathematical_optimization/examples/plot_exercise_ill_conditioned.py +++ b/advanced/mathematical_optimization/examples/plot_exercise_ill_conditioned.py @@ -37,14 +37,14 @@ def hessian(x): plt.figure(1) plt.clf() -Z = X, Y = np.mgrid[-1.5:1.5:100j, -1.1:1.1:100j] +Z = X, Y = np.mgrid[-1.5:1.5:100j, -1.1:1.1:100j] # type: ignore[misc] # Complete in the additional dimensions with zeros Z = np.reshape(Z, (2, -1)).copy() Z.resize((100, Z.shape[-1])) Z = np.apply_along_axis(f, 0, Z) Z = np.reshape(Z, X.shape) -plt.imshow(Z.T, cmap=plt.cm.gray_r, extent=[-1.5, 1.5, -1.1, 1.1], origin="lower") -plt.contour(X, Y, Z, cmap=plt.cm.gnuplot) +plt.imshow(Z.T, cmap="gray_r", extent=(-1.5, 1.5, -1.1, 1.1), origin="lower") +plt.contour(X, Y, Z, cmap="gnuplot") # A reference but slow solution: t0 = time.time() diff --git a/advanced/mathematical_optimization/examples/plot_gradient_descent.py b/advanced/mathematical_optimization/examples/plot_gradient_descent.py index b508af989..edc08683c 100644 --- a/advanced/mathematical_optimization/examples/plot_gradient_descent.py +++ b/advanced/mathematical_optimization/examples/plot_gradient_descent.py @@ -10,6 +10,7 @@ import matplotlib.pyplot as plt import scipy as sp +import collections import sys import os diff --git a/advanced/mathematical_optimization/examples/plot_non_bounds_constraints.py b/advanced/mathematical_optimization/examples/plot_non_bounds_constraints.py index 08af6f4d5..a694dddfe 100644 --- a/advanced/mathematical_optimization/examples/plot_non_bounds_constraints.py +++ b/advanced/mathematical_optimization/examples/plot_non_bounds_constraints.py @@ -10,18 +10,18 @@ import matplotlib.pyplot as plt import scipy as sp -x, y = np.mgrid[-2.03:4.2:0.04, -1.6:3.2:0.04] +x, y = np.mgrid[-2.03:4.2:0.04, -1.6:3.2:0.04] # type: ignore[misc] x = x.T y = y.T plt.figure(1, figsize=(3, 2.5)) plt.clf() -plt.axes([0, 0, 1, 1]) +plt.axes((0, 0, 1, 1)) contours = plt.contour( np.sqrt((x - 3) ** 2 + (y - 2) ** 2), extent=[-2.03, 4.2, -1.6, 3.2], - cmap=plt.cm.gnuplot, + cmap="gnuplot", ) plt.clabel(contours, inline=1, fmt="%1.1f", fontsize=14) plt.plot([-1.5, 0, 1.5, 0, -1.5], [0, 1.5, 0, -1.5, 0], "k", linewidth=2) diff --git a/advanced/optimizing/ica.py b/advanced/optimizing/ica.py index 298ee703c..06ceb0361 100644 --- a/advanced/optimizing/ica.py +++ b/advanced/optimizing/ica.py @@ -280,7 +280,7 @@ def gprime(x, fun_args): "w_init": w_init, } - func = algorithm_funcs.get(algorithm, "parallel") + func = algorithm_funcs[algorithm] W = func(X1, **kwargs) del X1 diff --git a/advanced/scipy_sparse/examples/lobpcg_sakurai.py b/advanced/scipy_sparse/examples/lobpcg_sakurai.py index 1ab2618b7..33445ade1 100644 --- a/advanced/scipy_sparse/examples/lobpcg_sakurai.py +++ b/advanced/scipy_sparse/examples/lobpcg_sakurai.py @@ -43,7 +43,7 @@ def sakurai(n): A, B, w_ex = sakurai(n) # Mikota pair X = np.random.random((n, m)) data = [] -tt = time.time() +tt = time.perf_counter() eigs, vecs, resnh = sp.sparse.linalg.lobpcg( A, X, @@ -53,7 +53,7 @@ def sakurai(n): maxiter=2000, retResidualNormsHistory=1, ) -data.append(time.time() - tt) +data.append(time.perf_counter() - tt) print("Results by LOBPCG for n=" + str(n)) print() print(eigs) diff --git a/conf.py b/conf.py index 464943baf..5327cfbf1 100644 --- a/conf.py +++ b/conf.py @@ -95,7 +95,7 @@ # have indented line wrapping -class MyHtmlFormatter(formatters.HtmlFormatter): +class MyHtmlFormatter(formatters.HtmlFormatter): # type: ignore[misc] def __init__(self, **options): options["lineseparator"] = '\n
' formatters.HtmlFormatter.__init__(self, **options) diff --git a/intro/matplotlib/examples/options/plot_aliased.py b/intro/matplotlib/examples/options/plot_aliased.py index 8db95c61e..5804307c8 100644 --- a/intro/matplotlib/examples/options/plot_aliased.py +++ b/intro/matplotlib/examples/options/plot_aliased.py @@ -13,7 +13,7 @@ fig = plt.figure(figsize=figsize, dpi=dpi) fig.patch.set_alpha(0) -plt.axes([0, 0, 1, 1], frameon=False) +plt.axes((0, 0, 1, 1), frameon=False) plt.rcParams["text.antialiased"] = False plt.text(0.5, 0.5, "Aliased", ha="center", va="center") diff --git a/intro/matplotlib/examples/options/plot_alpha.py b/intro/matplotlib/examples/options/plot_alpha.py index e905fb3b5..9b036555a 100644 --- a/intro/matplotlib/examples/options/plot_alpha.py +++ b/intro/matplotlib/examples/options/plot_alpha.py @@ -12,7 +12,7 @@ figsize = size[0] / float(dpi), size[1] / float(dpi) fig = plt.figure(figsize=figsize, dpi=dpi) fig.patch.set_alpha(0) -plt.axes([0, 0.1, 1, 0.8], frameon=False) +plt.axes((0, 0.1, 1, 0.8), frameon=False) for i in range(1, 11): plt.axvline(i, linewidth=1, color="blue", alpha=0.25 + 0.75 * i / 10.0) diff --git a/intro/matplotlib/examples/options/plot_antialiased.py b/intro/matplotlib/examples/options/plot_antialiased.py index ff3fac266..e7ae8d2e8 100644 --- a/intro/matplotlib/examples/options/plot_antialiased.py +++ b/intro/matplotlib/examples/options/plot_antialiased.py @@ -12,7 +12,7 @@ figsize = size[0] / float(dpi), size[1] / float(dpi) fig = plt.figure(figsize=figsize, dpi=dpi) fig.patch.set_alpha(0) -plt.axes([0, 0, 1, 1], frameon=False) +plt.axes((0, 0, 1, 1), frameon=False) plt.rcParams["text.antialiased"] = True plt.text(0.5, 0.5, "Anti-aliased", ha="center", va="center") diff --git a/intro/matplotlib/examples/options/plot_color.py b/intro/matplotlib/examples/options/plot_color.py index ddc76f69d..e85ab03cc 100644 --- a/intro/matplotlib/examples/options/plot_color.py +++ b/intro/matplotlib/examples/options/plot_color.py @@ -12,7 +12,7 @@ figsize = size[0] / float(dpi), size[1] / float(dpi) fig = plt.figure(figsize=figsize, dpi=dpi) fig.patch.set_alpha(0) -plt.axes([0, 0.1, 1, 0.8], frameon=False) +plt.axes((0, 0.1, 1, 0.8), frameon=False) for i in range(1, 11): plt.plot([i, i], [0, 1], lw=1.5) diff --git a/intro/matplotlib/examples/options/plot_colormaps.py b/intro/matplotlib/examples/options/plot_colormaps.py index 46ee73b25..fb4a98800 100644 --- a/intro/matplotlib/examples/options/plot_colormaps.py +++ b/intro/matplotlib/examples/options/plot_colormaps.py @@ -6,14 +6,17 @@ """ import numpy as np + +import matplotlib import matplotlib.pyplot as plt + plt.rc("text", usetex=False) a = np.outer(np.arange(0, 1, 0.01), np.ones(10)) plt.figure(figsize=(10, 5)) plt.subplots_adjust(top=0.8, bottom=0.05, left=0.01, right=0.99) -maps = [m for m in plt.cm.datad if not m.endswith("_r")] +maps = [m for m in matplotlib.colormaps if not m.endswith("_r")] maps.sort() l = len(maps) + 1 diff --git a/intro/matplotlib/examples/options/plot_dash_capstyle.py b/intro/matplotlib/examples/options/plot_dash_capstyle.py index 4224a0d84..b12b5b84b 100644 --- a/intro/matplotlib/examples/options/plot_dash_capstyle.py +++ b/intro/matplotlib/examples/options/plot_dash_capstyle.py @@ -13,7 +13,7 @@ figsize = size[0] / float(dpi), size[1] / float(dpi) fig = plt.figure(figsize=figsize, dpi=dpi) fig.patch.set_alpha(0) -plt.axes([0, 0, 1, 1], frameon=False) +plt.axes((0, 0, 1, 1), frameon=False) plt.plot( np.arange(4), diff --git a/intro/matplotlib/examples/options/plot_dash_joinstyle.py b/intro/matplotlib/examples/options/plot_dash_joinstyle.py index 84a7847c7..ec488f989 100644 --- a/intro/matplotlib/examples/options/plot_dash_joinstyle.py +++ b/intro/matplotlib/examples/options/plot_dash_joinstyle.py @@ -13,7 +13,7 @@ figsize = size[0] / float(dpi), size[1] / float(dpi) fig = plt.figure(figsize=figsize, dpi=dpi) fig.patch.set_alpha(0) -plt.axes([0, 0, 1, 1], frameon=False) +plt.axes((0, 0, 1, 1), frameon=False) plt.plot( np.arange(3), diff --git a/intro/matplotlib/examples/options/plot_linestyles.py b/intro/matplotlib/examples/options/plot_linestyles.py index 6ab9e38be..58d691e0c 100644 --- a/intro/matplotlib/examples/options/plot_linestyles.py +++ b/intro/matplotlib/examples/options/plot_linestyles.py @@ -58,7 +58,7 @@ def linestyle(ls, i): dpi = 72.0 figsize = size[0] / float(dpi), size[1] / float(dpi) fig = plt.figure(figsize=figsize, dpi=dpi) -plt.axes([0, 0.01, 1, 0.9], frameon=False) +plt.axes((0, 0.01, 1, 0.9), frameon=False) for i, ls in enumerate(linestyles): linestyle(ls, i) diff --git a/intro/matplotlib/examples/options/plot_linewidth.py b/intro/matplotlib/examples/options/plot_linewidth.py index 5da21e97b..819aff36c 100644 --- a/intro/matplotlib/examples/options/plot_linewidth.py +++ b/intro/matplotlib/examples/options/plot_linewidth.py @@ -12,7 +12,7 @@ figsize = size[0] / float(dpi), size[1] / float(dpi) fig = plt.figure(figsize=figsize, dpi=dpi) fig.patch.set_alpha(0) -plt.axes([0, 0.1, 1, 0.8], frameon=False) +plt.axes((0, 0.1, 1, 0.8), frameon=False) for i in range(1, 11): plt.plot([i, i], [0, 1], color="b", lw=i / 2.0) diff --git a/intro/matplotlib/examples/options/plot_markers.py b/intro/matplotlib/examples/options/plot_markers.py index e694f6b94..77da9cb96 100644 --- a/intro/matplotlib/examples/options/plot_markers.py +++ b/intro/matplotlib/examples/options/plot_markers.py @@ -58,7 +58,7 @@ def marker(m, i): dpi = 72.0 figsize = size[0] / float(dpi), size[1] / float(dpi) fig = plt.figure(figsize=figsize, dpi=dpi) -plt.axes([0, 0.01, 1, 0.9], frameon=False) +plt.axes((0, 0.01, 1, 0.9), frameon=False) for i, m in enumerate(markers): marker(m, i) diff --git a/intro/matplotlib/examples/options/plot_mec.py b/intro/matplotlib/examples/options/plot_mec.py index 598cd9418..09c562c1f 100644 --- a/intro/matplotlib/examples/options/plot_mec.py +++ b/intro/matplotlib/examples/options/plot_mec.py @@ -13,7 +13,7 @@ figsize = size[0] / float(dpi), size[1] / float(dpi) fig = plt.figure(figsize=figsize, dpi=dpi) fig.patch.set_alpha(0) -plt.axes([0, 0, 1, 1], frameon=False) +plt.axes((0, 0, 1, 1), frameon=False) rng = np.random.default_rng() diff --git a/intro/matplotlib/examples/options/plot_mew.py b/intro/matplotlib/examples/options/plot_mew.py index 5f6bf1754..5e78b176b 100644 --- a/intro/matplotlib/examples/options/plot_mew.py +++ b/intro/matplotlib/examples/options/plot_mew.py @@ -12,7 +12,7 @@ figsize = size[0] / float(dpi), size[1] / float(dpi) fig = plt.figure(figsize=figsize, dpi=dpi) fig.patch.set_alpha(0) -plt.axes([0, 0, 1, 1], frameon=False) +plt.axes((0, 0, 1, 1), frameon=False) for i in range(1, 11): plt.plot( diff --git a/intro/matplotlib/examples/options/plot_mfc.py b/intro/matplotlib/examples/options/plot_mfc.py index d50661199..e14cdea2b 100644 --- a/intro/matplotlib/examples/options/plot_mfc.py +++ b/intro/matplotlib/examples/options/plot_mfc.py @@ -13,7 +13,7 @@ figsize = size[0] / float(dpi), size[1] / float(dpi) fig = plt.figure(figsize=figsize, dpi=dpi) fig.patch.set_alpha(0) -plt.axes([0, 0, 1, 1], frameon=False) +plt.axes((0, 0, 1, 1), frameon=False) rng = np.random.default_rng() diff --git a/intro/matplotlib/examples/options/plot_ms.py b/intro/matplotlib/examples/options/plot_ms.py index 3e2858e34..ac55f8e06 100644 --- a/intro/matplotlib/examples/options/plot_ms.py +++ b/intro/matplotlib/examples/options/plot_ms.py @@ -12,7 +12,7 @@ figsize = size[0] / float(dpi), size[1] / float(dpi) fig = plt.figure(figsize=figsize, dpi=dpi) fig.patch.set_alpha(0) -plt.axes([0, 0, 1, 1], frameon=False) +plt.axes((0, 0, 1, 1), frameon=False) for i in range(1, 11): plt.plot( diff --git a/intro/matplotlib/examples/options/plot_solid_capstyle.py b/intro/matplotlib/examples/options/plot_solid_capstyle.py index 3d8b8caa7..4f17e0a12 100644 --- a/intro/matplotlib/examples/options/plot_solid_capstyle.py +++ b/intro/matplotlib/examples/options/plot_solid_capstyle.py @@ -13,7 +13,7 @@ figsize = size[0] / float(dpi), size[1] / float(dpi) fig = plt.figure(figsize=figsize, dpi=dpi) fig.patch.set_alpha(0) -plt.axes([0, 0, 1, 1], frameon=False) +plt.axes((0, 0, 1, 1), frameon=False) plt.plot(np.arange(4), np.ones(4), color="blue", linewidth=8, solid_capstyle="butt") diff --git a/intro/matplotlib/examples/options/plot_solid_joinstyle.py b/intro/matplotlib/examples/options/plot_solid_joinstyle.py index dbb82fc4e..c254acfba 100644 --- a/intro/matplotlib/examples/options/plot_solid_joinstyle.py +++ b/intro/matplotlib/examples/options/plot_solid_joinstyle.py @@ -13,7 +13,7 @@ figsize = size[0] / float(dpi), size[1] / float(dpi) fig = plt.figure(figsize=figsize, dpi=dpi) fig.patch.set_alpha(0) -plt.axes([0, 0, 1, 1], frameon=False) +plt.axes((0, 0, 1, 1), frameon=False) plt.plot(np.arange(3), [0, 1, 0], color="blue", linewidth=8, solid_joinstyle="miter") plt.plot( diff --git a/intro/matplotlib/examples/options/plot_ticks.py b/intro/matplotlib/examples/options/plot_ticks.py index 6fd3f5925..9bb7baae0 100644 --- a/intro/matplotlib/examples/options/plot_ticks.py +++ b/intro/matplotlib/examples/options/plot_ticks.py @@ -7,6 +7,8 @@ """ import numpy as np + +from matplotlib import ticker import matplotlib.pyplot as plt @@ -19,19 +21,19 @@ def tickline(): ax.xaxis.set_ticks_position("bottom") ax.spines["bottom"].set_position(("data", 0)) ax.yaxis.set_ticks_position("none") - ax.xaxis.set_minor_locator(plt.MultipleLocator(0.1)) + ax.xaxis.set_minor_locator(ticker.MultipleLocator(0.1)) ax.plot(np.arange(11), np.zeros(11)) return ax locators = [ - "plt.NullLocator()", - "plt.MultipleLocator(1.0)", - "plt.FixedLocator([0, 2, 8, 9, 10])", - "plt.IndexLocator(3, 1)", - "plt.LinearLocator(5)", - "plt.LogLocator(2, [1.0])", - "plt.AutoLocator()", + "ticker.NullLocator()", + "ticker.MultipleLocator(1.0)", + "ticker.FixedLocator([0, 2, 8, 9, 10])", + "ticker.IndexLocator(3, 1)", + "ticker.LinearLocator(5)", + "ticker.LogLocator(2, [1.0])", + "ticker.AutoLocator()", ] n_locators = len(locators) @@ -47,7 +49,7 @@ def tickline(): plt.subplot(n_locators, 1, i + 1) ax = tickline() ax.xaxis.set_major_locator(eval(locator)) - plt.text(5, 0.3, locator[3:], ha="center") + plt.text(5, 0.3, locator[7:], ha="center") plt.subplots_adjust(bottom=0.01, top=0.99, left=0.01, right=0.99) plt.show() diff --git a/intro/matplotlib/examples/plot_axes-2.py b/intro/matplotlib/examples/plot_axes-2.py index db4822727..97a33dc02 100644 --- a/intro/matplotlib/examples/plot_axes-2.py +++ b/intro/matplotlib/examples/plot_axes-2.py @@ -8,32 +8,32 @@ import matplotlib.pyplot as plt -plt.axes([0.1, 0.1, 0.5, 0.5]) +plt.axes((0.1, 0.1, 0.5, 0.5)) plt.xticks([]) plt.yticks([]) plt.text( - 0.1, 0.1, "axes([0.1, 0.1, 0.5, 0.5])", ha="left", va="center", size=16, alpha=0.5 + 0.1, 0.1, "axes((0.1, 0.1, 0.5, 0.5))", ha="left", va="center", size=16, alpha=0.5 ) -plt.axes([0.2, 0.2, 0.5, 0.5]) +plt.axes((0.2, 0.2, 0.5, 0.5)) plt.xticks([]) plt.yticks([]) plt.text( - 0.1, 0.1, "axes([0.2, 0.2, 0.5, 0.5])", ha="left", va="center", size=16, alpha=0.5 + 0.1, 0.1, "axes((0.2, 0.2, 0.5, 0.5))", ha="left", va="center", size=16, alpha=0.5 ) -plt.axes([0.3, 0.3, 0.5, 0.5]) +plt.axes((0.3, 0.3, 0.5, 0.5)) plt.xticks([]) plt.yticks([]) plt.text( - 0.1, 0.1, "axes([0.3, 0.3, 0.5, 0.5])", ha="left", va="center", size=16, alpha=0.5 + 0.1, 0.1, "axes((0.3, 0.3, 0.5, 0.5))", ha="left", va="center", size=16, alpha=0.5 ) -plt.axes([0.4, 0.4, 0.5, 0.5]) +plt.axes((0.4, 0.4, 0.5, 0.5)) plt.xticks([]) plt.yticks([]) plt.text( - 0.1, 0.1, "axes([0.4, 0.4, 0.5, 0.5])", ha="left", va="center", size=16, alpha=0.5 + 0.1, 0.1, "axes((0.4, 0.4, 0.5, 0.5))", ha="left", va="center", size=16, alpha=0.5 ) plt.show() diff --git a/intro/matplotlib/examples/plot_axes.py b/intro/matplotlib/examples/plot_axes.py index afd0fce58..422c4c0e4 100644 --- a/intro/matplotlib/examples/plot_axes.py +++ b/intro/matplotlib/examples/plot_axes.py @@ -8,14 +8,14 @@ import matplotlib.pyplot as plt -plt.axes([0.1, 0.1, 0.8, 0.8]) +plt.axes((0.1, 0.1, 0.8, 0.8)) plt.xticks([]) plt.yticks([]) plt.text( 0.6, 0.6, "axes([0.1, 0.1, 0.8, 0.8])", ha="center", va="center", size=20, alpha=0.5 ) -plt.axes([0.2, 0.2, 0.3, 0.3]) +plt.axes((0.2, 0.2, 0.3, 0.3)) plt.xticks([]) plt.yticks([]) plt.text( diff --git a/intro/matplotlib/examples/plot_bad.py b/intro/matplotlib/examples/plot_bad.py index 00755bd6a..a59fef36a 100644 --- a/intro/matplotlib/examples/plot_bad.py +++ b/intro/matplotlib/examples/plot_bad.py @@ -12,7 +12,7 @@ import matplotlib.pyplot as plt fig = plt.figure(figsize=(5, 4), dpi=72) -axes = fig.add_axes([0.01, 0.01, 0.98, 0.98]) +axes = fig.add_axes((0.01, 0.01, 0.98, 0.98)) x = np.linspace(0, 2, 200) y = np.sin(2 * np.pi * x) plt.plot(x, y, lw=0.25, c="k") diff --git a/intro/matplotlib/examples/plot_bar.py b/intro/matplotlib/examples/plot_bar.py index c1ff47a15..eef014d20 100644 --- a/intro/matplotlib/examples/plot_bar.py +++ b/intro/matplotlib/examples/plot_bar.py @@ -14,7 +14,7 @@ Y1 = (1 - X / float(n)) * rng.uniform(0.5, 1.0, n) Y2 = (1 - X / float(n)) * rng.uniform(0.5, 1.0, n) -plt.axes([0.025, 0.025, 0.95, 0.95]) +plt.axes((0.025, 0.025, 0.95, 0.95)) plt.bar(X, +Y1, facecolor="#9999ff", edgecolor="white") plt.bar(X, -Y2, facecolor="#ff9999", edgecolor="white") diff --git a/intro/matplotlib/examples/plot_contour.py b/intro/matplotlib/examples/plot_contour.py index 90441e2cd..ce3081038 100644 --- a/intro/matplotlib/examples/plot_contour.py +++ b/intro/matplotlib/examples/plot_contour.py @@ -19,9 +19,9 @@ def f(x, y): y = np.linspace(-3, 3, n) X, Y = np.meshgrid(x, y) -plt.axes([0.025, 0.025, 0.95, 0.95]) +plt.axes((0.025, 0.025, 0.95, 0.95)) -plt.contourf(X, Y, f(X, Y), 8, alpha=0.75, cmap=plt.cm.hot) +plt.contourf(X, Y, f(X, Y), 8, alpha=0.75, cmap="hot") C = plt.contour(X, Y, f(X, Y), 8, colors="black", linewidths=0.5) plt.clabel(C, inline=1, fontsize=10) diff --git a/intro/matplotlib/examples/plot_good.py b/intro/matplotlib/examples/plot_good.py index 4a3486f60..3d4c385fd 100644 --- a/intro/matplotlib/examples/plot_good.py +++ b/intro/matplotlib/examples/plot_good.py @@ -12,7 +12,7 @@ import matplotlib.pyplot as plt fig = plt.figure(figsize=(5, 4), dpi=72) -axes = fig.add_axes([0.01, 0.01, 0.98, 0.98]) +axes = fig.add_axes((0.01, 0.01, 0.98, 0.98)) X = np.linspace(0, 2, 200) Y = np.sin(2 * np.pi * X) plt.plot(X, Y, lw=2) diff --git a/intro/matplotlib/examples/plot_grid.py b/intro/matplotlib/examples/plot_grid.py index c65839c5d..aa94d0547 100644 --- a/intro/matplotlib/examples/plot_grid.py +++ b/intro/matplotlib/examples/plot_grid.py @@ -6,15 +6,16 @@ """ import matplotlib.pyplot as plt +from matplotlib import ticker -ax = plt.axes([0.025, 0.025, 0.95, 0.95]) +ax = plt.axes((0.025, 0.025, 0.95, 0.95)) ax.set_xlim(0, 4) ax.set_ylim(0, 3) -ax.xaxis.set_major_locator(plt.MultipleLocator(1.0)) -ax.xaxis.set_minor_locator(plt.MultipleLocator(0.1)) -ax.yaxis.set_major_locator(plt.MultipleLocator(1.0)) -ax.yaxis.set_minor_locator(plt.MultipleLocator(0.1)) +ax.xaxis.set_major_locator(ticker.MultipleLocator(1.0)) +ax.xaxis.set_minor_locator(ticker.MultipleLocator(0.1)) +ax.yaxis.set_major_locator(ticker.MultipleLocator(1.0)) +ax.yaxis.set_minor_locator(ticker.MultipleLocator(0.1)) ax.grid(which="major", axis="x", linewidth=0.75, linestyle="-", color="0.75") ax.grid(which="minor", axis="x", linewidth=0.25, linestyle="-", color="0.75") ax.grid(which="major", axis="y", linewidth=0.75, linestyle="-", color="0.75") diff --git a/intro/matplotlib/examples/plot_imshow.py b/intro/matplotlib/examples/plot_imshow.py index d196da2db..624428b21 100644 --- a/intro/matplotlib/examples/plot_imshow.py +++ b/intro/matplotlib/examples/plot_imshow.py @@ -19,7 +19,7 @@ def f(x, y): X, Y = np.meshgrid(x, y) Z = f(X, Y) -plt.axes([0.025, 0.025, 0.95, 0.95]) +plt.axes((0.025, 0.025, 0.95, 0.95)) plt.imshow(Z, interpolation="nearest", cmap="bone", origin="lower") plt.colorbar(shrink=0.92) diff --git a/intro/matplotlib/examples/plot_pie.py b/intro/matplotlib/examples/plot_pie.py index 3bd1f63c7..0eaf8e855 100644 --- a/intro/matplotlib/examples/plot_pie.py +++ b/intro/matplotlib/examples/plot_pie.py @@ -12,7 +12,7 @@ Z = np.ones(n) Z[-1] *= 2 -plt.axes([0.025, 0.025, 0.95, 0.95]) +plt.axes((0.025, 0.025, 0.95, 0.95)) plt.pie(Z, explode=Z * 0.05, colors=[f"{i / float(n):f}" for i in range(n)]) plt.axis("equal") diff --git a/intro/matplotlib/examples/plot_plot.py b/intro/matplotlib/examples/plot_plot.py index 7a2cd4fe0..2932069ac 100644 --- a/intro/matplotlib/examples/plot_plot.py +++ b/intro/matplotlib/examples/plot_plot.py @@ -12,7 +12,7 @@ X = np.linspace(-np.pi, np.pi, n) Y = np.sin(2 * X) -plt.axes([0.025, 0.025, 0.95, 0.95]) +plt.axes((0.025, 0.025, 0.95, 0.95)) plt.plot(X, Y + 1, color="blue", alpha=1.00) plt.fill_between(X, 1, Y + 1, color="blue", alpha=0.25) diff --git a/intro/matplotlib/examples/plot_plot3d-2.py b/intro/matplotlib/examples/plot_plot3d-2.py index 58668ca3c..e2c17c2c4 100644 --- a/intro/matplotlib/examples/plot_plot3d-2.py +++ b/intro/matplotlib/examples/plot_plot3d-2.py @@ -6,10 +6,10 @@ """ import matplotlib.pyplot as plt -from mpl_toolkits.mplot3d import axes3d +from mpl_toolkits.mplot3d.axes3d import Axes3D, get_test_data -ax = plt.figure().add_subplot(projection="3d") -X, Y, Z = axes3d.get_test_data(0.05) +ax: Axes3D = plt.figure().add_subplot(projection="3d") +X, Y, Z = get_test_data(0.05) cset = ax.contourf(X, Y, Z) ax.clabel(cset, fontsize=9, inline=1) diff --git a/intro/matplotlib/examples/plot_plot3d.py b/intro/matplotlib/examples/plot_plot3d.py index 3576bc318..019f1ada1 100644 --- a/intro/matplotlib/examples/plot_plot3d.py +++ b/intro/matplotlib/examples/plot_plot3d.py @@ -9,15 +9,15 @@ import matplotlib.pyplot as plt from mpl_toolkits.mplot3d import Axes3D -ax = plt.figure().add_subplot(projection="3d") +ax: Axes3D = plt.figure().add_subplot(projection="3d") X = np.arange(-4, 4, 0.25) Y = np.arange(-4, 4, 0.25) X, Y = np.meshgrid(X, Y) R = np.sqrt(X**2 + Y**2) Z = np.sin(R) -ax.plot_surface(X, Y, Z, rstride=1, cstride=1, cmap=plt.cm.hot) -ax.contourf(X, Y, Z, zdir="z", offset=-2, cmap=plt.cm.hot) +ax.plot_surface(X, Y, Z, rstride=1, cstride=1, cmap="hot") +ax.contourf(X, Y, Z, zdir="z", offset=-2, cmap="hot") ax.set_zlim(-2, 2) plt.show() diff --git a/intro/matplotlib/examples/plot_polar.py b/intro/matplotlib/examples/plot_polar.py index b610e962c..91cc4236b 100644 --- a/intro/matplotlib/examples/plot_polar.py +++ b/intro/matplotlib/examples/plot_polar.py @@ -7,9 +7,14 @@ """ import numpy as np + +import matplotlib import matplotlib.pyplot as plt -ax = plt.axes([0.025, 0.025, 0.95, 0.95], polar=True) + +jet = matplotlib.colormaps["jet"] + +ax = plt.axes((0.025, 0.025, 0.95, 0.95), polar=True) N = 20 theta = np.arange(0.0, 2 * np.pi, 2 * np.pi / N) @@ -19,7 +24,7 @@ bars = plt.bar(theta, radii, width=width, bottom=0.0) for r, bar in zip(radii, bars, strict=True): - bar.set_facecolor(plt.cm.jet(r / 10.0)) + bar.set_facecolor(jet(r / 10.0)) bar.set_alpha(0.5) ax.set_xticklabels([]) diff --git a/intro/matplotlib/examples/plot_quiver.py b/intro/matplotlib/examples/plot_quiver.py index 9634d7109..694be2506 100644 --- a/intro/matplotlib/examples/plot_quiver.py +++ b/intro/matplotlib/examples/plot_quiver.py @@ -15,7 +15,7 @@ R = 10 + np.sqrt((Y - n / 2.0) ** 2 + (X - n / 2.0) ** 2) U, V = R * np.cos(T), R * np.sin(T) -plt.axes([0.025, 0.025, 0.95, 0.95]) +plt.axes((0.025, 0.025, 0.95, 0.95)) plt.quiver(X, Y, U, V, R, alpha=0.5) plt.quiver(X, Y, U, V, edgecolor="k", facecolor="None", linewidth=0.5) diff --git a/intro/matplotlib/examples/plot_scatter.py b/intro/matplotlib/examples/plot_scatter.py index 853ef4532..c27f599b5 100644 --- a/intro/matplotlib/examples/plot_scatter.py +++ b/intro/matplotlib/examples/plot_scatter.py @@ -14,7 +14,7 @@ Y = rng.normal(0, 1, n) T = np.arctan2(Y, X) -plt.axes([0.025, 0.025, 0.95, 0.95]) +plt.axes((0.025, 0.025, 0.95, 0.95)) plt.scatter(X, Y, s=75, c=T, alpha=0.5) plt.xlim(-1.5, 1.5) diff --git a/intro/matplotlib/examples/plot_text.py b/intro/matplotlib/examples/plot_text.py index 0871b7833..8b119b11e 100644 --- a/intro/matplotlib/examples/plot_text.py +++ b/intro/matplotlib/examples/plot_text.py @@ -20,7 +20,7 @@ eqs.append(r"$E = mc^2 = \sqrt{{m_0}^2c^4 + p^2c^2}$") eqs.append(r"$F_G = G\frac{m_1m_2}{r^2}$") -plt.axes([0.025, 0.025, 0.95, 0.95]) +plt.axes((0.025, 0.025, 0.95, 0.95)) rng = np.random.default_rng() diff --git a/intro/matplotlib/examples/plot_ugly.py b/intro/matplotlib/examples/plot_ugly.py index ad4ddcc4e..e3910fab2 100644 --- a/intro/matplotlib/examples/plot_ugly.py +++ b/intro/matplotlib/examples/plot_ugly.py @@ -14,7 +14,7 @@ matplotlib.rc("grid", color="black", linestyle="-", linewidth=1) fig = plt.figure(figsize=(5, 4), dpi=72) -axes = fig.add_axes([0.01, 0.01, 0.98, 0.98], facecolor=".75") +axes = fig.add_axes((0.01, 0.01, 0.98, 0.98), facecolor=".75") X = np.linspace(0, 2, 40) Y = np.sin(2 * np.pi * X) plt.plot(X, Y, lw=0.05, c="b", antialiased=False) diff --git a/intro/matplotlib/examples/pretty_plots/plot_contour_ext.py b/intro/matplotlib/examples/pretty_plots/plot_contour_ext.py index f64f9784b..70aae462c 100644 --- a/intro/matplotlib/examples/pretty_plots/plot_contour_ext.py +++ b/intro/matplotlib/examples/pretty_plots/plot_contour_ext.py @@ -20,7 +20,7 @@ def f(x, y): y = np.linspace(-3, 3, n) X, Y = np.meshgrid(x, y) -plt.contourf(X, Y, f(X, Y), 8, alpha=0.75, cmap=plt.cm.hot) +plt.contourf(X, Y, f(X, Y), 8, alpha=0.75, cmap="hot") C = plt.contour(X, Y, f(X, Y), 8, colors="black", linewidth=0.5) plt.clabel(C, inline=1, fontsize=10) plt.xticks([]) diff --git a/intro/matplotlib/examples/pretty_plots/plot_plot3d_ext.py b/intro/matplotlib/examples/pretty_plots/plot_plot3d_ext.py index 595dd8351..dab3b16e9 100644 --- a/intro/matplotlib/examples/pretty_plots/plot_plot3d_ext.py +++ b/intro/matplotlib/examples/pretty_plots/plot_plot3d_ext.py @@ -17,8 +17,8 @@ R = np.sqrt(X**2 + Y**2) Z = np.sin(R) -ax.plot_surface(X, Y, Z, rstride=1, cstride=1, cmap=plt.cm.hot) -ax.contourf(X, Y, Z, zdir="z", offset=-2, cmap=plt.cm.hot) +ax.plot_surface(X, Y, Z, rstride=1, cstride=1, cmap="hot") +ax.contourf(X, Y, Z, zdir="z", offset=-2, cmap="hot") ax.set_zlim(-2, 2) plt.xticks([]) plt.yticks([]) diff --git a/intro/matplotlib/examples/pretty_plots/plot_polar_ext.py b/intro/matplotlib/examples/pretty_plots/plot_polar_ext.py index 7d5765b64..bceb0595f 100644 --- a/intro/matplotlib/examples/pretty_plots/plot_polar_ext.py +++ b/intro/matplotlib/examples/pretty_plots/plot_polar_ext.py @@ -7,8 +7,11 @@ """ import numpy as np + +import matplotlib import matplotlib.pyplot as plt + plt.subplot(1, 1, 1, polar=True) N = 20 @@ -17,8 +20,10 @@ radii = 10 * rng.random(N) width = np.pi / 4 * rng.random(N) bars = plt.bar(theta, radii, width=width, bottom=0.0) +jet = matplotlib.colormaps["jet"] + for r, bar in zip(radii, bars, strict=True): - bar.set_facecolor(plt.cm.jet(r / 10.0)) + bar.set_facecolor(jet(r / 10.0)) bar.set_alpha(0.5) plt.gca().set_xticklabels([]) plt.gca().set_yticklabels([]) diff --git a/intro/numpy/examples/plot_basic2dplot.py b/intro/numpy/examples/plot_basic2dplot.py index 050a91bec..1cb4465ab 100644 --- a/intro/numpy/examples/plot_basic2dplot.py +++ b/intro/numpy/examples/plot_basic2dplot.py @@ -11,6 +11,6 @@ rng = np.random.default_rng() image = rng.random((30, 30)) -plt.imshow(image, cmap=plt.cm.hot) +plt.imshow(image, cmap="hot") plt.colorbar() plt.show() diff --git a/intro/numpy/examples/plot_elephant.py b/intro/numpy/examples/plot_elephant.py index 60c3696fc..ad3f7b827 100644 --- a/intro/numpy/examples/plot_elephant.py +++ b/intro/numpy/examples/plot_elephant.py @@ -23,7 +23,7 @@ plt.figure() img_red = img[:, :, 0] -plt.imshow(img_red, cmap=plt.cm.gray) +plt.imshow(img_red, cmap="gray") ################################# # lower resolution diff --git a/intro/numpy/examples/plot_mandelbrot.py b/intro/numpy/examples/plot_mandelbrot.py index bf0921d26..84382e8ec 100644 --- a/intro/numpy/examples/plot_mandelbrot.py +++ b/intro/numpy/examples/plot_mandelbrot.py @@ -36,6 +36,6 @@ def compute_mandelbrot(N_max, some_threshold, nx, ny): mandelbrot_set = compute_mandelbrot(50, 50.0, 601, 401) -plt.imshow(mandelbrot_set.T, extent=[-2, 1, -1.5, 1.5]) +plt.imshow(mandelbrot_set.T, extent=(-2, 1, -1.5, 1.5)) plt.gray() plt.show() diff --git a/intro/numpy/examples/plot_populations.py b/intro/numpy/examples/plot_populations.py index f918ac3a1..22d25a0e7 100644 --- a/intro/numpy/examples/plot_populations.py +++ b/intro/numpy/examples/plot_populations.py @@ -12,7 +12,7 @@ data = np.loadtxt("../../../data/populations.txt") year, hares, lynxes, carrots = data.T -plt.axes([0.2, 0.1, 0.5, 0.8]) +plt.axes((0.2, 0.1, 0.5, 0.8)) plt.plot(year, hares, year, lynxes, year, carrots) plt.legend(("Hare", "Lynx", "Carrot"), loc=(1.05, 0.5)) plt.show() diff --git a/intro/numpy/solutions/2_4_mandelbrot.py b/intro/numpy/solutions/2_4_mandelbrot.py index 415ca0e25..c7b942ada 100644 --- a/intro/numpy/solutions/2_4_mandelbrot.py +++ b/intro/numpy/solutions/2_4_mandelbrot.py @@ -29,6 +29,6 @@ def compute_mandelbrot(N_max, some_threshold, nx, ny): mandelbrot_set = compute_mandelbrot(50, 50.0, 601, 401) -plt.imshow(mandelbrot_set.T, extent=[-2, 1, -1.5, 1.5]) +plt.imshow(mandelbrot_set.T, extent=[-2, 1, -1.5, 1.5]) # type: ignore[arg-type] plt.gray() plt.savefig("mandelbrot.png") diff --git a/intro/numpy/solutions/2_5_markov_chain.py b/intro/numpy/solutions/2_5_markov_chain.py index de27945a2..c6656a3f5 100644 --- a/intro/numpy/solutions/2_5_markov_chain.py +++ b/intro/numpy/solutions/2_5_markov_chain.py @@ -7,7 +7,7 @@ tolerance = 1e-5 # Random transition matrix and state vector -P = rng.random(n_states, n_states) +P = rng.random(size=(n_states, n_states)) p = rng.random(n_states) # Normalize rows in P diff --git a/intro/scipy/examples/plot_2d_minimization.py b/intro/scipy/examples/plot_2d_minimization.py index 97965464f..9fa0b009e 100644 --- a/intro/scipy/examples/plot_2d_minimization.py +++ b/intro/scipy/examples/plot_2d_minimization.py @@ -20,8 +20,8 @@ def sixhump(x): # Make a grid to evaluate the function (for plotting) xlim = [-2, 2] ylim = [-1, 1] -x = np.linspace(*xlim) -y = np.linspace(*ylim) +x = np.linspace(*xlim) # type: ignore[call-overload] +y = np.linspace(*ylim) # type: ignore[call-overload] xg, yg = np.meshgrid(x, y) ############################################################ @@ -31,7 +31,7 @@ def sixhump(x): import matplotlib.pyplot as plt plt.figure() -plt.imshow(sixhump([xg, yg]), extent=xlim + ylim, origin="lower") +plt.imshow(sixhump([xg, yg]), extent=xlim + ylim, origin="lower") # type: ignore[arg-type] plt.colorbar() ############################################################ @@ -40,14 +40,14 @@ def sixhump(x): from mpl_toolkits.mplot3d import Axes3D fig = plt.figure() -ax = fig.add_subplot(111, projection="3d") +ax: Axes3D = fig.add_subplot(111, projection="3d") surf = ax.plot_surface( xg, yg, sixhump([xg, yg]), rstride=1, cstride=1, - cmap=plt.cm.viridis, + cmap="viridis", linewidth=0, antialiased=False, ) @@ -70,7 +70,7 @@ def sixhump(x): plt.figure() # Show the function in 2D -plt.imshow(sixhump([xg, yg]), extent=xlim + ylim, origin="lower") +plt.imshow(sixhump([xg, yg]), extent=xlim + ylim, origin="lower") # type: ignore[arg-type] plt.colorbar() # Mark the minima plt.scatter(res_local.x[0], res_local.x[1], label="local minimizer") diff --git a/intro/scipy/examples/plot_connect_measurements.py b/intro/scipy/examples/plot_connect_measurements.py index 2bfa3bfff..1a3223c42 100644 --- a/intro/scipy/examples/plot_connect_measurements.py +++ b/intro/scipy/examples/plot_connect_measurements.py @@ -26,7 +26,7 @@ plt.title("sig") plt.subplot(1, 2, 2) -plt.imshow(mask, cmap=plt.cm.gray) +plt.imshow(mask, cmap="gray") plt.axis("off") plt.title("mask") plt.subplots_adjust(wspace=0.05, left=0.01, bottom=0.01, right=0.99, top=0.9) diff --git a/intro/scipy/examples/plot_fftpack.py b/intro/scipy/examples/plot_fftpack.py index fd171ca51..476a373ff 100644 --- a/intro/scipy/examples/plot_fftpack.py +++ b/intro/scipy/examples/plot_fftpack.py @@ -62,7 +62,7 @@ np.allclose(peak_freq, 1.0 / period) # An inner plot to show the peak frequency -axes = plt.axes([0.55, 0.3, 0.3, 0.5]) +axes = plt.axes((0.55, 0.3, 0.3, 0.5)) plt.title("Peak frequency") plt.plot(freqs[:8], power[pos_mask][:8]) plt.setp(axes, yticks=[]) diff --git a/intro/scipy/examples/plot_image_filters.py b/intro/scipy/examples/plot_image_filters.py index 52a3764b8..a2d33d22c 100644 --- a/intro/scipy/examples/plot_image_filters.py +++ b/intro/scipy/examples/plot_image_filters.py @@ -26,22 +26,22 @@ plt.figure(figsize=(12, 3.5)) plt.subplot(141) -plt.imshow(noisy_face, cmap=plt.cm.gray) +plt.imshow(noisy_face, cmap="gray") plt.axis("off") plt.title("noisy") plt.subplot(142) -plt.imshow(blurred_face, cmap=plt.cm.gray) +plt.imshow(blurred_face, cmap="gray") plt.axis("off") plt.title("Gaussian filter") plt.subplot(143) -plt.imshow(median_face, cmap=plt.cm.gray) +plt.imshow(median_face, cmap="gray") plt.axis("off") plt.title("median filter") plt.subplot(144) -plt.imshow(wiener_face, cmap=plt.cm.gray) +plt.imshow(wiener_face, cmap="gray") plt.title("Wiener filter") plt.axis("off") diff --git a/intro/scipy/examples/plot_image_transform.py b/intro/scipy/examples/plot_image_transform.py index add66b4aa..c2978faed 100644 --- a/intro/scipy/examples/plot_image_transform.py +++ b/intro/scipy/examples/plot_image_transform.py @@ -23,23 +23,23 @@ plt.figure(figsize=(15, 3)) plt.subplot(151) -plt.imshow(shifted_face, cmap=plt.cm.gray) +plt.imshow(shifted_face, cmap="gray") plt.axis("off") plt.subplot(152) -plt.imshow(shifted_face2, cmap=plt.cm.gray) +plt.imshow(shifted_face2, cmap="gray") plt.axis("off") plt.subplot(153) -plt.imshow(rotated_face, cmap=plt.cm.gray) +plt.imshow(rotated_face, cmap="gray") plt.axis("off") plt.subplot(154) -plt.imshow(cropped_face, cmap=plt.cm.gray) +plt.imshow(cropped_face, cmap="gray") plt.axis("off") plt.subplot(155) -plt.imshow(zoomed_face, cmap=plt.cm.gray) +plt.imshow(zoomed_face, cmap="gray") plt.axis("off") plt.subplots_adjust(wspace=0.05, left=0.01, bottom=0.01, right=0.99, top=0.99) diff --git a/intro/scipy/examples/plot_mathematical_morpho.py b/intro/scipy/examples/plot_mathematical_morpho.py index 6c3e6ebe2..d802a736f 100644 --- a/intro/scipy/examples/plot_mathematical_morpho.py +++ b/intro/scipy/examples/plot_mathematical_morpho.py @@ -26,22 +26,22 @@ plt.figure(figsize=(12, 3.5)) plt.subplot(141) -plt.imshow(a, cmap=plt.cm.gray) +plt.imshow(a, cmap="gray") plt.axis("off") plt.title("a") plt.subplot(142) -plt.imshow(mask, cmap=plt.cm.gray) +plt.imshow(mask, cmap="gray") plt.axis("off") plt.title("mask") plt.subplot(143) -plt.imshow(opened_mask, cmap=plt.cm.gray) +plt.imshow(opened_mask, cmap="gray") plt.axis("off") plt.title("opened_mask") plt.subplot(144) -plt.imshow(closed_mask, cmap=plt.cm.gray) +plt.imshow(closed_mask, cmap="gray") plt.title("closed_mask") plt.axis("off") diff --git a/intro/scipy/examples/plot_t_test.py b/intro/scipy/examples/plot_t_test.py index 77258b6fd..b72461326 100644 --- a/intro/scipy/examples/plot_t_test.py +++ b/intro/scipy/examples/plot_t_test.py @@ -19,7 +19,7 @@ histogram2, bins = np.histogram(samples2, bins=bins, density=True) plt.figure(figsize=(6, 4)) -plt.hist(samples1, bins=bins, density=True, label="Samples 1") -plt.hist(samples2, bins=bins, density=True, label="Samples 2") +plt.hist(samples1, bins=bins, density=True, label="Samples 1") # type: ignore[arg-type] +plt.hist(samples2, bins=bins, density=True, label="Samples 2") # type: ignore[arg-type] plt.legend(loc="best") plt.show() diff --git a/intro/scipy/examples/solutions/plot_fft_image_denoise.py b/intro/scipy/examples/solutions/plot_fft_image_denoise.py index ec06081d9..a0c4890a2 100644 --- a/intro/scipy/examples/solutions/plot_fft_image_denoise.py +++ b/intro/scipy/examples/solutions/plot_fft_image_denoise.py @@ -27,7 +27,7 @@ im = plt.imread("../../../../data/moonlanding.png").astype(float) plt.figure() -plt.imshow(im, plt.cm.gray) +plt.imshow(im, "gray") plt.title("Original image") @@ -91,7 +91,7 @@ def plot_spectrum(im_fft): im_new = sp.fft.ifft2(im_fft2).real plt.figure() -plt.imshow(im_new, plt.cm.gray) +plt.imshow(im_new, "gray") plt.title("Reconstructed Image") @@ -105,7 +105,7 @@ def plot_spectrum(im_fft): im_blur = sp.ndimage.gaussian_filter(im, 4) plt.figure() -plt.imshow(im_blur, plt.cm.gray) +plt.imshow(im_blur, "gray") plt.title("Blurred image") plt.show() diff --git a/intro/scipy/solutions/pi_wallis.py b/intro/scipy/solutions/pi_wallis.py index 9ae0472b8..4e9fab6cd 100644 --- a/intro/scipy/solutions/pi_wallis.py +++ b/intro/scipy/solutions/pi_wallis.py @@ -2,6 +2,9 @@ The correction for the calculation of pi using the Wallis formula. """ +from functools import reduce + + pi = 3.14159265358979312 my_pi = 1.0 @@ -31,7 +34,7 @@ print(abs(my_pi - better_pi)) ############################################################################### -# Solution in a single line using more adcanved constructs (reduce, lambda, +# Solution in a single line using more advanced constructs (reduce, lambda, # list comprehensions print( 2 diff --git a/packages/scikit-learn/examples/plot_bias_variance.py b/packages/scikit-learn/examples/plot_bias_variance.py index 16a54b54c..b3cb2822c 100644 --- a/packages/scikit-learn/examples/plot_bias_variance.py +++ b/packages/scikit-learn/examples/plot_bias_variance.py @@ -86,7 +86,7 @@ def generating_func(x, rng=None, error=0.5): # Plot a validation curve from sklearn.model_selection import validation_curve -degrees = np.arange(1, 21) +degrees = list(range(1, 21)) model = make_pipeline(PolynomialFeatures(), LinearRegression()) diff --git a/packages/scikit-learn/examples/plot_digits_simple_classif.py b/packages/scikit-learn/examples/plot_digits_simple_classif.py index 0f823dd54..75ea9e7b3 100644 --- a/packages/scikit-learn/examples/plot_digits_simple_classif.py +++ b/packages/scikit-learn/examples/plot_digits_simple_classif.py @@ -22,7 +22,7 @@ for i in range(64): ax = fig.add_subplot(8, 8, i + 1, xticks=[], yticks=[]) - ax.imshow(digits.images[i], cmap=plt.cm.binary, interpolation="nearest") + ax.imshow(digits.images[i], cmap="binary", interpolation="nearest") # label the image with the target value ax.text(0, 7, str(digits.target[i])) @@ -66,7 +66,7 @@ # plot the digits: each image is 8x8 pixels for i in range(64): ax = fig.add_subplot(8, 8, i + 1, xticks=[], yticks=[]) - ax.imshow(X_test.reshape(-1, 8, 8)[i], cmap=plt.cm.binary, interpolation="nearest") + ax.imshow(X_test.reshape(-1, 8, 8)[i], cmap="binary", interpolation="nearest") # label the image with the target value if predicted[i] == expected[i]: diff --git a/packages/scikit-learn/examples/plot_eigenfaces.py b/packages/scikit-learn/examples/plot_eigenfaces.py index aa808dd66..04d224740 100644 --- a/packages/scikit-learn/examples/plot_eigenfaces.py +++ b/packages/scikit-learn/examples/plot_eigenfaces.py @@ -29,7 +29,7 @@ # plot several images for i in range(15): ax = fig.add_subplot(3, 5, i + 1, xticks=[], yticks=[]) - ax.imshow(faces.images[i], cmap=plt.cm.bone) + ax.imshow(faces.images[i], cmap="bone") ############################################################ # .. tip:: @@ -72,7 +72,7 @@ # One interesting part of PCA is that it computes the "mean" face, which # can be interesting to examine: -plt.imshow(pca.mean_.reshape(faces.images[0].shape), cmap=plt.cm.bone) +plt.imshow(pca.mean_.reshape(faces.images[0].shape), cmap="bone") ############################################################ # The principal components measure deviations about this mean along @@ -86,7 +86,7 @@ fig = plt.figure(figsize=(16, 6)) for i in range(30): ax = fig.add_subplot(3, 10, i + 1, xticks=[], yticks=[]) - ax.imshow(pca.components_[i].reshape(faces.images[0].shape), cmap=plt.cm.bone) + ax.imshow(pca.components_[i].reshape(faces.images[0].shape), cmap="bone") ############################################################ # The components ("eigenfaces") are ordered by their importance from @@ -129,7 +129,7 @@ fig = plt.figure(figsize=(8, 6)) for i in range(15): ax = fig.add_subplot(3, 5, i + 1, xticks=[], yticks=[]) - ax.imshow(X_test[i].reshape(faces.images[0].shape), cmap=plt.cm.bone) + ax.imshow(X_test[i].reshape(faces.images[0].shape), cmap="bone") y_pred = clf.predict(X_test_pca[i, np.newaxis])[0] color = "black" if y_pred == y_test[i] else "red" ax.set_title(y_pred, fontsize="small", color=color) diff --git a/packages/scikit-learn/examples/plot_iris_scatter.py b/packages/scikit-learn/examples/plot_iris_scatter.py index 388ea4c7a..54c738314 100644 --- a/packages/scikit-learn/examples/plot_iris_scatter.py +++ b/packages/scikit-learn/examples/plot_iris_scatter.py @@ -13,6 +13,7 @@ iris = load_iris() +from matplotlib import ticker import matplotlib.pyplot as plt # The indices of the features that we are plotting @@ -20,7 +21,7 @@ y_index = 1 # this formatter will label the colorbar with the correct target names -formatter = plt.FuncFormatter(lambda i, *args: iris.target_names[int(i)]) +formatter = ticker.FuncFormatter(lambda i, *args: iris.target_names[int(i)]) plt.figure(figsize=(5, 4)) plt.scatter(iris.data[:, x_index], iris.data[:, y_index], c=iris.target) diff --git a/packages/scikit-learn/examples/plot_separator.py b/packages/scikit-learn/examples/plot_separator.py index abd4c4c6e..c44d6bcba 100644 --- a/packages/scikit-learn/examples/plot_separator.py +++ b/packages/scikit-learn/examples/plot_separator.py @@ -35,7 +35,7 @@ ax.contour( X1, X2, Z, [-1.0, 0.0, 1.0], colors="k", linestyles=["dashed", "solid", "dashed"] ) -ax.scatter(X[:, 0], X[:, 1], c=Y, cmap=plt.cm.Paired) +ax.scatter(X[:, 0], X[:, 1], c=Y, cmap="Paired") ax.axis("tight") diff --git a/packages/scikit-learn/examples/plot_svm_non_linear.py b/packages/scikit-learn/examples/plot_svm_non_linear.py index e71e8dff2..f5c246b42 100644 --- a/packages/scikit-learn/examples/plot_svm_non_linear.py +++ b/packages/scikit-learn/examples/plot_svm_non_linear.py @@ -38,7 +38,7 @@ def linear_model(rseed=42, n_samples=30): plt.figure(figsize=(6, 4)) ax = plt.subplot(111, xticks=[], yticks=[]) -ax.scatter(X[:, 0], X[:, 1], c=y, cmap=plt.cm.bone) +ax.scatter(X[:, 0], X[:, 1], c=y, cmap="bone") ax.scatter( clf.support_vectors_[:, 0], @@ -92,7 +92,7 @@ def nonlinear_model(rseed=27446968, n_samples=30): plt.figure(figsize=(6, 4)) ax = plt.subplot(1, 1, 1, xticks=[], yticks=[]) -ax.scatter(X[:, 0], X[:, 1], c=y, cmap=plt.cm.bone, zorder=2) +ax.scatter(X[:, 0], X[:, 1], c=y, cmap="bone", zorder=2) ax.scatter( clf.support_vectors_[:, 0], diff --git a/packages/statistics/examples/plot_airfare.py b/packages/statistics/examples/plot_airfare.py index 0b757f527..f4d1cc0f0 100644 --- a/packages/statistics/examples/plot_airfare.py +++ b/packages/statistics/examples/plot_airfare.py @@ -71,7 +71,9 @@ ["city1", "city2", "pop1", "pop2", "dist", "fare_2000", "nb_passengers_2000"] ] # Rename the columns -data_2000.columns = ["city1", "city2", "pop1", "pop2", "dist", "fare", "nb_passengers"] +data_2000.columns = pandas.Index( + ["city1", "city2", "pop1", "pop2", "dist", "fare", "nb_passengers"] +) # Add a column with the year data_2000.insert(0, "year", 2000) @@ -79,7 +81,9 @@ ["city1", "city2", "pop1", "pop2", "dist", "fare_2001", "nb_passengers_2001"] ] # Rename the columns -data_2001.columns = ["city1", "city2", "pop1", "pop2", "dist", "fare", "nb_passengers"] +data_2001.columns = pandas.Index( + ["city1", "city2", "pop1", "pop2", "dist", "fare", "nb_passengers"] +) # Add a column with the year data_2001.insert(0, "year", 2001) diff --git a/packages/statistics/examples/plot_regression_3d.py b/packages/statistics/examples/plot_regression_3d.py index 95f7a343b..21b096cc5 100644 --- a/packages/statistics/examples/plot_regression_3d.py +++ b/packages/statistics/examples/plot_regression_3d.py @@ -36,8 +36,8 @@ Z = -5 + 3 * X - 0.5 * Y + 8 * np.random.normal(size=X.shape) # Plot the data -ax = plt.figure().add_subplot(projection="3d") -surf = ax.plot_surface(X, Y, Z, cmap=plt.cm.coolwarm, rstride=1, cstride=1) +ax: Axes3D = plt.figure().add_subplot(projection="3d") +surf = ax.plot_surface(X, Y, Z, cmap="coolwarm", rstride=1, cstride=1) ax.view_init(20, -120) ax.set_xlabel("X") ax.set_ylabel("Y") diff --git a/packages/statistics/examples/plot_wage_data.py b/packages/statistics/examples/plot_wage_data.py index 055c679be..f7b2b0811 100644 --- a/packages/statistics/examples/plot_wage_data.py +++ b/packages/statistics/examples/plot_wage_data.py @@ -50,7 +50,7 @@ data = pandas.read_csv( "wages.txt", skiprows=27, skipfooter=6, sep=None, header=None, engine="python" ) -data.columns = short_names +data.columns = pandas.Index(short_names) # Log-transform the wages, because they typically are increased with # multiplicative factors diff --git a/packages/statistics/examples/plot_wage_education_gender.py b/packages/statistics/examples/plot_wage_education_gender.py index e29e97117..6818895a3 100644 --- a/packages/statistics/examples/plot_wage_education_gender.py +++ b/packages/statistics/examples/plot_wage_education_gender.py @@ -17,12 +17,14 @@ # Load and massage the data import pandas -import urllib +import urllib.request import os if not os.path.exists("wages.txt"): # Download the file if it is not present - urllib.urlretrieve("http://lib.stat.cmu.edu/datasets/CPS_85_Wages", "wages.txt") + url = "http://lib.stat.cmu.edu/datasets/CPS_85_Wages" + with urllib.request.urlopen(url) as r, open("wages.txt", "wb") as f: + f.write(r.read()) # EDUCATION: Number of years of education # SEX: 1=Female, 0=Male diff --git a/packages/statistics/examples/solutions/plot_brain_size.py b/packages/statistics/examples/solutions/plot_brain_size.py index b95b2ca2e..5bb9eb710 100644 --- a/packages/statistics/examples/solutions/plot_brain_size.py +++ b/packages/statistics/examples/solutions/plot_brain_size.py @@ -36,7 +36,7 @@ import matplotlib.pyplot as plt # Fill in the missing values for Height for plotting -data["Height"].fillna(method="pad", inplace=True) +data["Height"] = data["Height"].ffill() # The parameter 'c' is passed to plt.scatter and will control the color # The same holds for parameters 'marker', 'alpha' and 'cmap', that diff --git a/pyproject.toml b/pyproject.toml index d2f38f4cd..5f762cae3 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -1,3 +1,63 @@ +[tool.mypy] +strict = true +enable_error_code = ["ignore-without-code", "redundant-expr", "truthy-bool"] +warn_unreachable = true +# Sync with .pre-commit-config.yaml +exclude = ''' +(?x)( + ^build/ + | ^pyximages/ + | conf\.py$ + | .*/setup.*\.py$ + | .*/demo.py$ + | .*/auto_examples/ + | advanced/mathematical_optimization/examples/plot_gradient_descent\.py$ + | advanced/mathematical_optimization/examples/helper/compare_optimizers\.py$ + | advanced/advanced_numpy/examples/view-colors\.py$ + | advanced/advanced_numpy/examples/stride-diagonals\.py$ + | advanced/interfacing_with_c/cython_numpy/test_cos_doubles\.py$ + | advanced/interfacing_with_c/numpy_shared/test_cos_doubles\.py$ + | advanced/interfacing_with_c/swig.*\.py$ + | advanced/advanced_numpy/examples/myobject_test\.py$ + | advanced/interfacing_with_c/numpy_shared/test_cos_doubles\.py$ + | advanced/interfacing_with_c/numpy_c_api/test_cos_module_np\.py$ + | intro/numpy/solutions/2_a_call_fortran\.py$ + | advanced/advanced_numpy/examples/mandelplot\.py$ +) +''' + +# Can make these more strict over time +allow_untyped_defs = true +allow_untyped_calls = true + +[[tool.mypy.overrides]] +module = "scipy" +ignore_missing_imports = true + +[[tool.mypy.overrides]] +module = "matplotlib.pyplot.*" +disable_error_code = ["arg-type"] + +[[tool.mypy.overrides]] +module = "mpl_toolkits.mplot3d.*" +ignore_missing_imports = true + +[[tool.mypy.overrides]] +module = "sklearn.*" +ignore_missing_imports = true + +[[tool.mypy.overrides]] +module = "seaborn.*" +ignore_missing_imports = true + +[[tool.mypy.overrides]] +module = "statsmodels.*" +ignore_missing_imports = true + +[[tool.mypy.overrides]] +module = "pyamg.*" +ignore_missing_imports = true + [tool.pytest.ini_options] minversion = "8.2" doctest_optionflags = "NUMBER NORMALIZE_WHITESPACE ELLIPSIS"