### Example intro-install_plan.json Entry Source: https://docs.scipy.org/doc/scipy/building/introspecting_a_build.html This snippet shows a typical entry from `intro-install_plan.json`, detailing the installation destination and tag for a build artifact. ```json "/home/username/code/scipy/build/scipy/linalg/_decomp_update.cpython-310-x86_64-linux-gnu.so":{ "destination":"{py_platlib}/scipy/linalg/_decomp_update.cpython-310-x86_64-linux-gnu.so", "tag":"runtime" }, ``` -------------------------------- ### Setup for probability plots Source: https://docs.scipy.org/doc/scipy/reference/generated/scipy.stats.probplot.html Import necessary libraries and initialize a random number generator for subsequent examples. ```python import numpy as np from scipy import stats import matplotlib.pyplot as plt nsample = 100 rng = np.random.default_rng() ``` -------------------------------- ### Import modules and define utility function for remez examples Source: https://docs.scipy.org/doc/scipy/reference/generated/scipy.signal.remez.html Setup imports and helper function for plotting frequency responses in remez filter design examples. Required for all subsequent examples. ```python >>> import numpy as np >>> from scipy import signal >>> import matplotlib.pyplot as plt ``` ```python >>> fs = 22050 # Sample rate, Hz ``` ```python >>> def plot_response(w, h, title): ... "Utility function to plot response functions" ... fig = plt.figure() ... ax = fig.add_subplot(111) ... ax.plot(w, 20*np.log10(np.abs(h))) ... ax.set_ylim(-40, 5) ... ax.grid(True) ... ax.set_xlabel('Frequency (Hz)') ... ax.set_ylabel('Gain (dB)') ... ax.set_title(title) ``` -------------------------------- ### Get example .mat file path Source: https://docs.scipy.org/doc/scipy/reference/generated/scipy.io.loadmat.html Construct the full path to an example .mat file from the scipy test data directory. ```python >>> data_dir = pjoin(dirname(sio.__file__), 'matlab', 'tests', 'data') >>> mat_fname = pjoin(data_dir, 'testdouble_7.4_GLNX86.mat') ``` -------------------------------- ### 2-D Interpolation Setup and Imports Source: https://docs.scipy.org/doc/scipy/tutorial/interpolate/ND_unstructured.html Import required modules for 2-D scattered data interpolation example. ```python >>> import numpy as np >>> from scipy.interpolate import RBFInterpolator >>> import matplotlib.pyplot as plt ``` -------------------------------- ### Initialize Environment for invgamma Examples (Python) Source: https://docs.scipy.org/doc/scipy/reference/generated/scipy.stats.invgamma.html Imports necessary libraries and sets up a matplotlib figure for plotting `invgamma` distribution examples. ```python import numpy as np from scipy.stats import invgamma import matplotlib.pyplot as plt fig, ax = plt.subplots(1, 1) ``` -------------------------------- ### Initialize `ncf` distribution and plot setup Source: https://docs.scipy.org/doc/scipy/reference/generated/scipy.stats.ncf.html Import necessary libraries and set up a matplotlib figure for plotting `ncf` distribution examples. ```python >>> import numpy as np >>> from scipy.stats import ncf >>> import matplotlib.pyplot as plt >>> fig, ax = plt.subplots(1, 1) ``` -------------------------------- ### Example: Run Tests for test_linprog.py Source: https://docs.scipy.org/doc/scipy/dev/contributor/devpy_test.html This example demonstrates how to run all tests within the `scipy/optimize/tests/test_linprog.py` file. ```bash spin test -t scipy.optimize.tests.test_linprog ``` -------------------------------- ### Example: Run test_unknown_solvers_and_options Source: https://docs.scipy.org/doc/scipy/dev/contributor/devpy_test.html This example demonstrates running the specific test function `test_unknown_solvers_and_options` from `test_linprog.py`. ```bash spin test -t scipy.optimize.tests.test_linprog::test_unknown_solvers_and_options ``` -------------------------------- ### Example: Run TestLinprogRSCommon Class Tests Source: https://docs.scipy.org/doc/scipy/dev/contributor/devpy_test.html This example shows how to run all tests within the `TestLinprogRSCommon` class from `test_linprog.py`. ```bash spin test -t scipy.optimize.tests.test_linprog::TestLinprogRSCommon ``` -------------------------------- ### Perform and Plot Short-Time Fourier Transform (STFT) with SciPy Source: https://docs.scipy.org/doc/scipy/reference/generated/scipy.signal.ShortTimeFFT.html This example demonstrates how to generate a signal with varying frequency, apply a Gaussian window, compute its STFT using `ShortTimeFFT`, and visualize the magnitude spectrogram. It covers signal generation, STFT parameter setup, and plotting the time-frequency representation. ```python >>> import numpy as np >>> import matplotlib.pyplot as plt >>> from scipy.signal import ShortTimeFFT >>> from scipy.signal.windows import gaussian ... >>> T_x, N = 1 / 20, 1000 # 20 Hz sampling rate for 50 s signal >>> t_x = np.arange(N) * T_x # time indexes for signal >>> f_i = 1 * np.arctan((t_x - t_x[N // 2]) / 2) + 5 # varying frequency >>> x = np.sin(2*np.pi*np.cumsum(f_i)*T_x) # the signal ``` ```python >>> g_std = 8 # standard deviation for Gaussian window in samples >>> w = gaussian(50, std=g_std, sym=True) # symmetric Gaussian window >>> SFT = ShortTimeFFT(w, hop=10, fs=1/T_x, mfft=200, scale_to='magnitude') >>> Sx = SFT.stft(x) # perform the STFT ``` ```python >>> fig1, ax1 = plt.subplots(figsize=(6., 4.)) # enlarge plot a bit >>> t_lo, t_hi = SFT.extent(N)[:2] # time range of plot >>> ax1.set_title(rf"STFT ({SFT.m_num*SFT.T:g}$\,s$ Gaussian window, " + ... rf"$\sigma_t={g_std*SFT.T}\,s$)") >>> ax1.set(xlabel=f"Time $t$ in seconds ({SFT.p_num(N)} slices, " + ... rf"$\Delta t = {SFT.delta_t:g}\,s$)", ... ylabel=f"Freq. $f$ in Hz ({SFT.f_pts} bins, " + ... rf"$\Delta f = {SFT.delta_f:g}\,Hz$)", ... xlim=(t_lo, t_hi)) ... >>> im1 = ax1.imshow(abs(Sx), origin='lower', aspect='auto', ... extent=SFT.extent(N), cmap='viridis') >>> ax1.plot(t_x, f_i, 'r--', alpha=.5, label='$f_i(t)$') >>> fig1.colorbar(im1, label="Magnitude $|S_x(t, f)|$") ... >>> # Shade areas where window slices stick out to the side: >>> for t0_, t1_ in [(t_lo, SFT.lower_border_end[0] * SFT.T), ... (SFT.upper_border_begin(N)[0] * SFT.T, t_hi)]: ``` -------------------------------- ### Initialize environment for lognormal distribution examples Source: https://docs.scipy.org/doc/scipy/reference/generated/scipy.stats.lognorm.html Imports necessary libraries and sets up a matplotlib figure for plotting lognormal distribution examples. ```python >>> import numpy as np >>> from scipy.stats import lognorm >>> import matplotlib.pyplot as plt >>> fig, ax = plt.subplots(1, 1) ``` -------------------------------- ### Initial QR Decomposition Setup Source: https://docs.scipy.org/doc/scipy/reference/generated/scipy.linalg.qr_insert.html Import required libraries and compute the initial QR factorization of a matrix that will be updated. ```python >>> import numpy as np >>> from scipy import linalg >>> a = np.array([[ 3., -2., -2.], ... [ 6., -7., 4.], ... [ 7., 8., -6.]]) >>> q, r = linalg.qr(a) ``` -------------------------------- ### Get example .sav file path from test data Source: https://docs.scipy.org/doc/scipy/reference/generated/scipy.io.readsav.html Construct the full path to an example .sav file located in the scipy test data directory. ```python >>> data_dir = pjoin(dirname(sio.__file__), 'tests', 'data') >>> sav_fname = pjoin(data_dir, 'array_float32_1d.sav') ``` -------------------------------- ### Example intro-dependencies.json Content Source: https://docs.scipy.org/doc/scipy/building/introspecting_a_build.html This snippet illustrates the structure of `intro-dependencies.json`, listing detected build dependencies along with their versions and associated compile/link arguments. ```json [ { "name":"python", "version":"3.10", "compile_args":[ "-I/home/username/anaconda3/envs/scipy-dev/include/python3.10" ], "link_args":[ ] }, { "name":"openblas", "version":"0.3.20", "compile_args":[ "-I/home/username/anaconda3/envs/scipy-dev/include" ], "link_args":[ "/home/username/anaconda3/envs/scipy-dev/lib/libopenblas.so" ] }, { "name":"threads", "version":"unknown", "compile_args":[ "-pthread" ], "link_args":[ "-pthread" ] } ] ``` -------------------------------- ### Initialize Environment for nbinom Examples Source: https://docs.scipy.org/doc/scipy/reference/generated/scipy.stats.nbinom.html Imports necessary libraries and sets up a plot for visualizing the distribution. ```python import numpy as np from scipy.stats import nbinom import matplotlib.pyplot as plt fig, ax = plt.subplots(1, 1) ``` -------------------------------- ### Initialize and Display a Continuous StateSpace System Source: https://docs.scipy.org/doc/scipy/reference/generated/scipy.signal.StateSpace.html This example demonstrates importing necessary libraries, defining state-space matrices (A, B, C, D) for a continuous system, and then creating and printing the `StateSpace` object. ```python from scipy import signal import numpy as np a = np.array([[0, 1], [0, 0]]) b = np.array([[0], [1]]) c = np.array([[1, 0]]) d = np.array([[0]]) ``` ```python sys = signal.StateSpace(a, b, c, d) print(sys) ``` -------------------------------- ### Import scipy datasets and matplotlib for visualization Source: https://docs.scipy.org/doc/scipy/reference/generated/scipy.ndimage.gaussian_filter.html Setup imports for loading example datasets and creating visualizations with matplotlib. ```python >>> from scipy import datasets >>> import matplotlib.pyplot as plt ``` -------------------------------- ### Enable interactive examples on the release server Source: https://docs.scipy.org/doc/scipy/dev/core-dev/index.html Access the server via SSH to modify the 'try_examples.json' configuration file. ```bash $ ssh your-username@docs.scipy.org $ cd /srv/docs_scipy_org/doc/scipy-1.13.1 $ vim try_examples.json # edit the ignore list to remove: ".*" ``` -------------------------------- ### Set up grid parameters and boundary conditions Source: https://docs.scipy.org/doc/scipy/tutorial/optimize.html Initialize grid dimensions, spacing, and boundary values for a 2D domain problem. ```Python # parameters nx, ny = 75, 75 hx, hy = 1./(nx-1), 1./(ny-1) P_left, P_right = 0, 0 P_top, P_bottom = 1, 0 ``` -------------------------------- ### Basic softmax computation with NumPy Source: https://docs.scipy.org/doc/scipy/reference/generated/scipy.special.softmax.html Import scipy.special.softmax and set NumPy print options for readable output. This is the setup for all following examples. ```python >>> import numpy as np >>> from scipy.special import softmax >>> np.set_printoptions(precision=5) ``` -------------------------------- ### Configure build with Meson Source: https://docs.scipy.org/doc/scipy/building/understanding_meson.html Run the configure stage to detect compilers and set the installation prefix. ```bash meson setup build --prefix=$PWD/build-install ``` -------------------------------- ### Import Nakagami distribution and dependencies Source: https://docs.scipy.org/doc/scipy/reference/generated/scipy.stats.nakagami.html Import NumPy, SciPy's Nakagami distribution, and Matplotlib for visualization. Required setup for all subsequent examples. ```python >>> import numpy as np >>> from scipy.stats import nakagami >>> import matplotlib.pyplot as plt >>> fig, ax = plt.subplots(1, 1) ``` -------------------------------- ### Run module tests with spin Source: https://docs.scipy.org/doc/scipy/building/compilers_and_options.html Builds, installs, and tests a specific SciPy module. Meson remembers configuration options from the initial setup. ```bash spin -s linalg ``` -------------------------------- ### Build and run Fortran reproducer with Meson Source: https://docs.scipy.org/doc/scipy/dev/contributor/debugging_linalg_issues.html Commands to set up PKG_CONFIG_PATH, build with Meson, and execute the Fortran reproducer. Output shows workspace query, eigenvalue computation, and results including inf and NaN values. ```bash $ export PKG_CONFIG_PATH=~/code/tmp/flexiblas-setup/built-libs/lib/pkgconfig/ $ meson setup build $ ninja -C build $ ./build/repro_f90 # output may vary workspace query: lwork = -1 info = 0 opt lwork = 156 info = 0 alphar = 1.0204501477442456 11.707793036240817 3.7423579363517347E-014 -1.1492523608519701E-014 alphai = 0.0000000000000000 0.0000000000000000 0.0000000000000000 0.0000000000000000 beta = 0.25511253693606051 1.4634741295300704 0.0000000000000000 0.0000000000000000 Re(eigv) = 4.0000000000000142 8.0000000000001741 Infinity -Infinity Im(eigv) = 0.0000000000000000 0.0000000000000000 NaN NaN ``` -------------------------------- ### Initialize betanbinom and plot setup Source: https://docs.scipy.org/doc/scipy/reference/generated/scipy.stats.betanbinom.html Import necessary libraries and set up a matplotlib figure for plotting the distribution. ```python >>> import numpy as np >>> from scipy.stats import betanbinom >>> import matplotlib.pyplot as plt >>> fig, ax = plt.subplots(1, 1) ``` -------------------------------- ### FFT of prime length array Source: https://docs.scipy.org/doc/scipy/reference/generated/scipy.fftpack.next_fast_len.html This example demonstrates the setup for an FFT on an array with a prime length, which typically represents a worst-case scenario for computation speed. ```python from scipy import fftpack import numpy as np rng = np.random.default_rng() min_len = 10007 # prime length is worst case for speed a = rng.standard_normal(min_len) b = fftpack.fft(a) ``` -------------------------------- ### Prepare Data for Object Measurements in SciPy Source: https://docs.scipy.org/doc/scipy/tutorial/ndimage.html Initializes an image, a mask, and labels, then uses `find_objects` to get slices for subsequent object measurement examples. ```python >>> image = np.arange(4 * 6).reshape(4, 6) >>> mask = np.array([[0,1,1,0,0,0],[0,1,1,0,1,0],[0,0,0,1,1,1],[0,0,0,0,1,0]]) >>> labels = label(mask)[0] >>> slices = find_objects(labels) ``` -------------------------------- ### Compute confidence interval for binomial test result Source: https://docs.scipy.org/doc/scipy/reference/generated/scipy.stats._result_classes.BinomTestResult.proportion_ci.html This example demonstrates how to use `proportion_ci` on a `BinomTestResult` object to get the confidence interval for the estimated proportion. ```python >>> from scipy.stats import binomtest >>> result = binomtest(k=7, n=50, p=0.1) >>> result.statistic 0.14 >>> result.proportion_ci() ConfidenceInterval(low=0.05819170033997342, high=0.26739600249700846) ``` -------------------------------- ### Instantiate Distribution and Evaluate PDF Source: https://docs.scipy.org/doc/scipy/reference/generated/scipy.stats.Normal.pdf.html This example demonstrates how to initialize a `scipy.stats.Uniform` distribution and then calculate its Probability Density Function (PDF) at a specific point. The first part sets up the distribution, and the second part calls the `pdf` method. ```python from scipy import stats X = stats.Uniform(a=-1., b=1.) ``` ```python X.pdf(0.25) 0.5 ``` -------------------------------- ### Get length of a RigidTransform from an N-dimensional array Source: https://docs.scipy.org/doc/scipy/reference/generated/scipy.spatial.transform.RigidTransform.__len__.html This example demonstrates how `len()` returns the size of the first dimension when a RigidTransform is initialized from an N-dimensional array of transformations. ```python >>> t = np.ones((5, 2, 3, 1, 3)) >>> tf = Tf.from_translation(t) >>> len(tf) 5 ``` -------------------------------- ### Build and run C reproducer with Meson Source: https://docs.scipy.org/doc/scipy/dev/contributor/debugging_linalg_issues.html Commands to set up PKG_CONFIG_PATH, build with Meson, and execute the C reproducer. Output shows eigenvalue computation results including inf and -nan values. ```bash $ export PKG_CONFIG_PATH=~/code/tmp/flexiblas-setup/built-libs/lib/pkgconfig/ $ meson setup build $ ninja -C build $ ./build/repro_c # output may vary info = 0 Re(eigv) = 4.000000 , 8.000000 , inf , -inf , Im(eigv = 0.000000 , 0.000000 , -nan , -nan , ``` -------------------------------- ### Get Nonzero Indices from a CSR Array Source: https://docs.scipy.org/doc/scipy/reference/generated/scipy.sparse.dok_matrix.nonzero.html This example demonstrates how to use the `nonzero()` method on a `csr_array` to retrieve the row and column indices of its non-zero elements. ```python from scipy.sparse import csr_array A = csr_array([[1, 2, 0], [0, 0, 3], [4, 0, 5]]) A.nonzero() (array([0, 0, 1, 2, 2], dtype=int32), array([0, 1, 2, 0, 2], dtype=int32)) ``` -------------------------------- ### Run `svds` with Matrix-Free LinearOperator Source: https://docs.scipy.org/doc/scipy/reference/generated/scipy.sparse.linalg.svds.html After validating the `LinearOperator` setup, this example demonstrates how to call `svds` using the matrix-free `LinearOperator` to compute singular values and vectors. ```python n = 100 diff0_func_aslo = diff0_func_aslo_def(n) u, s, vT = svds(diff0_func_aslo, k=3, which='SM') ``` -------------------------------- ### Setup and compute trimmed mean with scipy.stats.trim_mean Source: https://docs.scipy.org/doc/scipy/tutorial/stats/outliers.html Demonstrates basic setup with environment configuration and computing a trimmed mean on a simple array. Shows the legacy convenience function approach that combines trimming with statistic computation. ```python import os os.environ['SCIPY_ARRAY_API'] = '1' import numpy as np from scipy import stats np.set_printoptions(linewidth=120) x = np.arange(20.) stats.trim_mean(x, proportiontocut=0.1) ``` -------------------------------- ### Initialize KDTree with Sample Data Source: https://docs.scipy.org/doc/scipy/reference/generated/scipy.spatial.KDTree.query.html Initializes a KDTree instance with sample 2D data for subsequent nearest neighbor queries. This setup is used by all following examples. ```python import numpy as np from scipy.spatial import KDTree x, y = np.mgrid[0:5, 2:8] tree = KDTree(np.c_[x.ravel(), y.ravel()]) ``` -------------------------------- ### Initialize `genexpon` and Plotting Environment Source: https://docs.scipy.org/doc/scipy/reference/generated/scipy.stats.genexpon.html Import necessary libraries and set up a matplotlib figure for plotting examples. ```python import numpy as np from scipy.stats import genexpon import matplotlib.pyplot as plt fig, ax = plt.subplots(1, 1) ``` -------------------------------- ### Solve nonlinear system using scipy.optimize.anderson Source: https://docs.scipy.org/doc/scipy/reference/generated/scipy.optimize.anderson.html This example demonstrates how to use `scipy.optimize.anderson` to find the root of the previously defined nonlinear function, starting with an initial guess. ```python from scipy import optimize sol = optimize.anderson(fun, [0, 0]) sol ``` -------------------------------- ### Initialize DiscreteGuideTable with a Distribution Object Source: https://docs.scipy.org/doc/scipy/reference/generated/scipy.stats.sampling.DiscreteGuideTable.html Shows how to initialize `DiscreteGuideTable` using a distribution object (e.g., `scipy.stats.binom`) that has a PMF method and a finite domain. ```python >>> urng = np.random.default_rng() >>> from scipy.stats import binom >>> n, p = 10, 0.2 >>> dist = binom(n, p) >>> rng = DiscreteGuideTable(dist, random_state=urng) ``` -------------------------------- ### Setup for Truncated SVD Examples (NumPy, SciPy) Source: https://docs.scipy.org/doc/scipy/reference/generated/scipy.sparse.linalg.svds.html Initializes a dense matrix `A` with known singular values and vectors using `numpy` and `scipy.stats.ortho_group` for subsequent `svds` demonstrations. ```python >>> rng = np.random.default_rng() >>> orthogonal = stats.ortho_group.rvs(10, random_state=rng) >>> s = [1e-3, 1, 2, 3, 4] # non-zero singular values >>> u = orthogonal[:, :5] # left singular vectors >>> vT = orthogonal[:, 5:].T # right singular vectors >>> A = u @ np.diag(s) @ vT ``` -------------------------------- ### DiscreteGuideTable.__init__ Source: https://docs.scipy.org/doc/scipy/reference/generated/scipy.stats.sampling.DiscreteGuideTable.html Initialize a DiscreteGuideTable sampler for discrete distributions. Accepts either a probability vector or a distribution object with a pmf method. The guide_factor parameter controls the trade-off between setup time and sampling speed. ```APIDOC ## DiscreteGuideTable(dist, *, domain=None, guide_factor=1, random_state=None) ### Description Initialize a Discrete Guide Table sampler for sampling from arbitrary finite probability distributions. ### Parameters - **dist** (array_like or object) - Required - Probability vector (PV) of the distribution as a 1-dimensional array of non-negative floats, or an instance of a class with a `pmf` method. The PMF signature must be `def pmf(self, k: int) -> float`. - **domain** (int, optional) - Optional - Support of the PMF as a tuple (start, end). Required when using a PMF without a support method. When used with a probability vector, domain[0] relocates the distribution from (0, len(pv)) to (domain[0], domain[0]+len(pv)). Default is None. - **guide_factor** (int, optional) - Optional - Size of the guide table relative to the length of the probability vector. Larger values result in faster sampling but slower setup. Values larger than 3 are not recommended. Set to 0 for sequential search. Default is 1. - **random_state** ({None, int, numpy.random.Generator, numpy.random.RandomState}, optional) - Optional - Random number generator or seed. If None, uses numpy.random.RandomState singleton. If int, creates new RandomState seeded with that value. If Generator or RandomState instance, uses that directly. ### Notes - The probability vector must contain only non-negative floats without inf or nan values - At least one non-zero entry must exist in the probability vector - By default, the probability vector is indexed starting at 0 - Setup time is O(N) where N is the length of the probability vector - Expected sampling time is constant with guide table size equal to probability vector length ``` -------------------------------- ### Install SciPy build dependencies on macOS Source: https://docs.scipy.org/doc/scipy/building/index.html Setup the Apple Developer Tools and Homebrew dependencies. Run the brew info command to obtain the necessary PKG_CONFIG_PATH export. ```bash xcode-select --install ``` ```bash brew install gfortran openblas pkg-config ``` ```bash brew info openblas | grep PKG_CONFIG_PATH ``` -------------------------------- ### Install All Python Dependencies Source: https://docs.scipy.org/doc/scipy/building/index.html Installs all build, test, doc, and optional dependencies from PyPI. Run this in an activated virtual environment after venv creation. ```bash # All dependencies python -m pip install -r requirements/all.txt ``` -------------------------------- ### Initialize matrix and perform QR decomposition Source: https://docs.scipy.org/doc/scipy/reference/generated/scipy.linalg.qr_delete.html Sets up a sample matrix `a` and computes its initial QR factorization using `scipy.linalg.qr`. ```python >>> import numpy as np >>> from scipy import linalg >>> a = np.array([[ 3., -2., -2.], ... [ 6., -9., -3.], ... [ -3., 10., 1.], ... [ 6., -7., 4.], ... [ 7., 8., -6.]]) >>> q, r = linalg.qr(a) ``` -------------------------------- ### Basic Fisher's Exact Test Usage Source: https://docs.scipy.org/doc/scipy/reference/generated/scipy.stats.fisher_exact.html A simple example demonstrating how to use `fisher_exact` for a 2x2 contingency table to get the odds ratio statistic and p-value. ```python from scipy.stats import fisher_exact res = fisher_exact([[8, 2], [1, 5]]) res.statistic res.pvalue ``` -------------------------------- ### Get leaf node order from hierarchical clustering Source: https://docs.scipy.org/doc/scipy/reference/generated/scipy.cluster.hierarchy.leaves_list.html This example demonstrates how to use `leaves_list` to retrieve the order of leaf nodes from a hierarchical clustering linkage matrix, and visualize the dendrogram. ```python from scipy.cluster.hierarchy import ward, dendrogram, leaves_list from scipy.spatial.distance import pdist from matplotlib import pyplot as plt ``` ```python X = [[0, 0], [0, 1], [1, 0], [0, 4], [0, 3], [1, 4], [4, 0], [3, 0], [4, 1], [4, 4], [3, 4], [4, 3]] ``` ```python Z = ward(pdist(X)) ``` ```python leaves_list(Z) array([ 2, 0, 1, 5, 3, 4, 8, 6, 7, 11, 9, 10], dtype=int32) ``` ```python fig = plt.figure(figsize=(25, 10)) dn = dendrogram(Z) plt.show() ``` -------------------------------- ### Locate an example WAV file Source: https://docs.scipy.org/doc/scipy/reference/generated/scipy.io.wavfile.read.html This code constructs the path to an example WAV file (`test-44100Hz-2ch-32bit-float-be.wav`) located within SciPy's test data directory, which is useful for demonstration purposes. ```python >>> data_dir = pjoin(dirname(scipy.io.__file__), 'tests', 'data') >>> wav_fname = pjoin(data_dir, 'test-44100Hz-2ch-32bit-float-be.wav') ``` -------------------------------- ### Constructing a Sparse Matrix for SVD Examples in Python Source: https://docs.scipy.org/doc/scipy/reference/sparse.linalg.svds-lobpcg.html This snippet demonstrates how to create a sparse matrix `A` from predefined singular values and orthogonal vectors, which serves as a setup for subsequent SVD computations. ```python import numpy as np from scipy.stats import ortho_group from scipy.sparse import csc_array, diags_array from scipy.sparse.linalg import svds rng = np.random.default_rng() orthogonal = csc_array(ortho_group.rvs(10, random_state=rng)) s = [0.0001, 0.001, 3, 4, 5] # singular values u = orthogonal[:, :5] # left singular vectors vT = orthogonal[:, 5:].T # right singular vectors A = u @ diags_array(s) @ vT ``` -------------------------------- ### svds(A, k, which) Source: https://docs.scipy.org/doc/scipy/reference/generated/scipy.sparse.linalg.svds.html Computes the singular value decomposition (SVD) for a sparse matrix or a `LinearOperator`. This example demonstrates its use with a matrix-free `LinearOperator` setup to find the smallest magnitude singular values. ```APIDOC ## svds(A, k, which) ### Description Computes the singular value decomposition (SVD) for a sparse matrix or a `LinearOperator`. This function is part of `scipy.sparse.linalg` and is designed for efficient computation of a subset of singular values and vectors. The provided example demonstrates its use with a matrix-free `LinearOperator` setup to find the smallest magnitude singular values. ### Parameters - **A** (LinearOperator) - Required - The linear operator representing the matrix for which to compute the SVD. In the example, `diff0_func_aslo` is used, which is a matrix-free representation of a difference operator. - **k** (int) - Required - The number of singular values and vectors to compute. The example uses `k=3`. - **which** (str) - Required - Specifies which singular values to find. Common options include 'LM' (Largest Magnitude), 'SM' (Smallest Magnitude), etc. The example uses `'SM'`. ### Returns - **u** (array) - The left singular vectors. - **s** (array) - The singular values, sorted by magnitude. - **vT** (array) - The transpose of the right singular vectors. ### Example Usage ```python n = 100 diff0_func_aslo = diff0_func_aslo_def(n) # Assuming diff0_func_aslo_def is defined as in the source u, s, vT = svds(diff0_func_aslo, k=3, which='SM') ``` ``` -------------------------------- ### Clone Repositories for FlexiBLAS Setup Source: https://docs.scipy.org/doc/scipy/dev/contributor/debugging_linalg_issues.html Initialize the FlexiBLAS setup by creating a directory and cloning the OpenBLAS and FlexiBLAS repositories, along with a directory for built libraries. ```bash cd .. # starting from the root of the local `scipy` repo mkdir flexiblas-setup && cd flexiblas-setup git clone https://github.com/OpenMathLib/OpenBLAS.git openblas git clone https://github.com/mpimd-csc/flexiblas.git mkdir built-libs # our local prefix to install everything to ``` -------------------------------- ### Count neighbors between two KDTrees Source: https://docs.scipy.org/doc/scipy/reference/generated/scipy.spatial.KDTree.count_neighbors.html Basic example showing how to create two KDTrees from random points and count neighbors between them within a distance. This demonstrates the setup required before calling count_neighbors. ```python >>> import numpy as np >>> from scipy.spatial import KDTree >>> rng = np.random.default_rng() >>> points1 = rng.random((5, 2)) >>> points2 = rng.random((5, 2)) >>> kd_tree1 = KDTree(points1) >>> kd_tree2 = KDTree(points2) ``` -------------------------------- ### Example .git/config File Content Source: https://docs.scipy.org/doc/scipy/dev/gitwash/development_setup.html Illustrates the expected content of the `.git/config` file after successfully configuring remotes and branch tracking for SciPy development. ```ini [core] repositoryformatversion = 0 filemode = true bare = false logallrefupdates = true ignorecase = true precomposeunicode = false [remote "origin"] url = https://github.com/your-user-name/scipy.git fetch = +refs/heads/*:refs/remotes/origin/* [remote "upstream"] url = https://github.com/scipy/scipy.git fetch = +refs/heads/*:refs/remotes/upstream/* [branch "main"] remote = upstream merge = refs/heads/main ``` -------------------------------- ### Setup Second Example for Edge Cases Source: https://docs.scipy.org/doc/scipy/reference/generated/scipy.signal.peak_prominences.html Defines a simple array `x` and a single peak at index 5 to illustrate how `peak_prominences` handles specific array structures and edge cases. ```python >>> x = np.array([0, 1, 0, 3, 1, 3, 0, 4, 0]) >>> peaks = np.array([5]) >>> plt.plot(x) >>> plt.plot(peaks, x[peaks], "x") >>> plt.show() ``` -------------------------------- ### Initialize Environment for Lomax Distribution Examples, Python Source: https://docs.scipy.org/doc/scipy/reference/generated/scipy.stats.lomax.html Import necessary libraries and set up a matplotlib figure for plotting Lomax distribution examples. ```python >>> import numpy as np >>> from scipy.stats import lomax >>> import matplotlib.pyplot as plt >>> fig, ax = plt.subplots(1, 1) ``` -------------------------------- ### Instantiate a Uniform Distribution for Median Demonstration Source: https://docs.scipy.org/doc/scipy/reference/generated/scipy.stats.Binomial.median.html This example initializes a `scipy.stats.Uniform` distribution with specified lower and upper bounds, which is then used to demonstrate median computation. ```python from scipy import stats X = stats.Uniform(a=0., b=10.) ``` -------------------------------- ### Find roots of a PPoly object Source: https://docs.scipy.org/doc/scipy/reference/generated/scipy.interpolate.Akima1DInterpolator.solve.html This example demonstrates how to find the real solutions (roots) of a piecewise polynomial defined by a `PPoly` object. It shows the setup of a `PPoly` instance and the use of the `solve()` method. ```python import numpy as np from scipy.interpolate import PPoly pp = PPoly(np.array([[1, -4, 3], [1, 0, 0]]).T, [-2, 1, 2]) pp.solve() ``` -------------------------------- ### Get Nonzero Indices of a CSR Array Source: https://docs.scipy.org/doc/scipy/reference/generated/scipy.sparse.coo_matrix.nonzero.html This example demonstrates how to use the `nonzero()` method on a `csr_array` to retrieve the row and column indices of its non-zero elements. The method returns a tuple of NumPy arrays. ```python from scipy.sparse import csr_array >>> A = csr_array([[1, 2, 0], [0, 0, 3], [4, 0, 5]]) >>> A.nonzero() (array([0, 0, 1, 2, 2], dtype=int32), array([0, 1, 2, 0, 2], dtype=int32)) ``` -------------------------------- ### 1-D Interpolation Setup and Imports Source: https://docs.scipy.org/doc/scipy/tutorial/interpolate/ND_unstructured.html Import required modules and prepare 1-D sample data for interpolation comparison. ```python >>> import numpy as np >>> from scipy.interpolate import RBFInterpolator, InterpolatedUnivariateSpline >>> import matplotlib.pyplot as plt ``` -------------------------------- ### Minimizing Rosenbrock function using Nelder-Mead method in Python Source: https://docs.scipy.org/doc/scipy/reference/generated/scipy.optimize.minimize.html This example demonstrates a basic application of the Nelder-Mead simplex algorithm to find the minimum of the Rosenbrock function, starting from an initial guess `x0`. ```python x0 = [1.3, 0.7, 0.8, 1.9, 1.2] res = minimize(rosen, x0, method='Nelder-Mead', tol=1e-6) res.x array([ 1., 1., 1., 1., 1.]) ```