question_id
int64
59.5M
79.7M
creation_date
stringdate
2020-01-01 00:00:00
2025-06-13 00:00:00
link
stringlengths
60
163
question
stringlengths
53
28.9k
accepted_answer
stringlengths
26
29.3k
question_vote
int64
1
410
answer_vote
int64
-9
482
79,663,680
2025-6-12
https://stackoverflow.com/questions/79663680/plotting-the-components-of-a-general-solution-returned-by-sympy
I have written the following code that returns a solution. import sympy as sym import numpy as np z = sym.Symbol('z') e = sym.Symbol('e') f = sym.Function('f') edo = sym.diff(f(z), z , 2) + e * f(z) soln = sym.dsolve(edo, f(z)) print(soln.rhs) the above code returns: C1*exp(-z*sqrt(-e)) + C2*exp(z*sqrt(-e)) I want to be able to access the elements of this 'soln.rhs' directly and plot them. I could copy and paste the results, but I want to do something like: plot(x, soln.rhs[0]) which would plot exp(-z*sqrt(-e)) The reason for this is that I am analysing many different types of ODE, some of which return solutions which are combinations of Airy functions like C1*airyai(-e + z) + C2*airybi(-e + z) Does anyone know how to access the elements of the general solution? I have looked through the documentation and nothing really pops out.
What you are looking for is the args attribute of a Sympy's symbolic expression. For example: print(soln.rhs.args[0]) # C1*exp(-z*sqrt(-e)) print(soln.rhs.args[1]) # C2*exp(z*sqrt(-e)) You might also want to insert appropriate values for the integrations constants by using the subs method: C1, C2 = symbols("C1, C2") soln.rhs.subs({C1: 2, C2: 3}) # random numeric values to show how to do it. Then, you can plot it: # plot the solution for z in [0, 10] plot(soln.rhs.subs({C1: 2, C2: 3}), (z, 0, 10))
1
2
79,663,153
2025-6-12
https://stackoverflow.com/questions/79663153/correct-way-to-embed-and-bundle-python-in-c-to-avoid-modulenotfounderror-enc
I am trying to embed Python inside my C++ DLL. The idea is that the DLL, once distributed, should be sufficient and not rely on other installations and downloads. Interestingly, the below "sort of" works, only in my solution directory, since that is where my vcpkg_installed is. How can I make my DLL not be required to be near vcpkg_installed? Code py_wrap.cpp (the DLL): void assertPyInit() { if (!Py_IsInitialized()) { PyConfig config; PyConfig_InitPythonConfig(&config); // Get the executable path instead of current working directory wchar_t exePath[MAX_PATH]; GetModuleFileNameW(NULL, exePath, MAX_PATH); // Remove the executable name to get the directory std::wstring exeDir = exePath; size_t lastSlash = exeDir.find_last_of(L"\\"); if (lastSlash != std::wstring::npos) { exeDir = exeDir.substr(0, lastSlash); } // Now build Python path relative to executable location std::wstring pythonHome = exeDir + L"\\..\\..\\vcpkg_installed\\x64-windows-static-md\\x64-windows-static-md\\tools\\python3"; // Resolve the full path to eliminate .. references wchar_t resolvedPath[MAX_PATH]; GetFullPathNameW(pythonHome.c_str(), MAX_PATH, resolvedPath, NULL); pythonHome = resolvedPath; std::wstring pythonLib = pythonHome + L"\\Lib"; std::wstring pythonSitePackages = pythonLib + L"\\site-packages"; std::wstring pythonDLLs = pythonHome + L"\\DLLs"; // Set the Python home directory PyConfig_SetString(&config, &config.home, pythonHome.c_str()); // Set the module search paths std::wstring pythonPathEnv = pythonLib + L";" + pythonSitePackages + L";" + pythonDLLs; PyConfig_SetString(&config, &config.pythonpath_env, pythonPathEnv.c_str()); PyStatus status = Py_InitializeFromConfig(&config); PyConfig_Clear(&config); if (PyStatus_Exception(status)) { PyErr_Print(); return; } PyRun_SimpleString("import sys"); PyRun_SimpleString("sys.path.append(\".\")"); } } void MY_DLL pyPrint(const char* message) { assertPyInit(); PyObject* pyStr = PyUnicode_FromString(message); if (pyStr) { PyObject* builtins = PyEval_GetBuiltins(); PyObject* printFunc = PyDict_GetItemString(builtins, "print"); if (printFunc && PyCallable_Check(printFunc)) { PyObject* args = PyTuple_Pack(1, pyStr); PyObject_CallObject(printFunc, args); Py_DECREF(args); } Py_DECREF(pyStr); } } DLLTester.cpp (client app): #include <iostream> #include "py_wrap.h" int main() { std::cout << "Hello\n"; pyPrint("Hello from python:D !"); } File structure and IO PS D: \RedactedLabs\Dev > ls AsyncDLLMQL\x64\Release\ Directory: D: \RedactedLabs\Dev\AsyncDLLMQL\x64\Release Mode LastWriteTime Length Name ---- ------------- ------ ---- -a---- 6/11/2025 10:48 PM 476672 AsyncDLLMQL.dll -a---- 6/11/2025 10:48 PM 4297 AsyncDLLMQL.exp -a---- 6/11/2025 10:26 PM 7752 AsyncDLLMQL.lib -a---- 6/11/2025 10:48 PM 7376896 AsyncDLLMQL.pdb -a---- 6/11/2025 10:48 PM 12288 DLLTester.exe -a---- 6/11/2025 10:48 PM 790528 DLLTester.pdb -a---- 6/6/2025 4: 39 PM 56320 python3.dll -a---- 6/6/2025 4: 39 PM 7273984 python312.dll PS D: \RedactedLabs\Dev > ls AsyncDLLMQL\x64\Release\ Directory: D: \RedactedLabs\Dev\AsyncDLLMQL\x64\Release Mode LastWriteTime Length Name ---- ------------- ------ ---- -a---- 6/11/2025 10:48 PM 476672 AsyncDLLMQL.dll -a---- 6/11/2025 10:48 PM 4297 AsyncDLLMQL.exp -a---- 6/11/2025 10:26 PM 7752 AsyncDLLMQL.lib -a---- 6/11/2025 10:48 PM 7376896 AsyncDLLMQL.pdb -a---- 6/11/2025 10:48 PM 12288 DLLTester.exe -a---- 6/11/2025 10:48 PM 790528 DLLTester.pdb -a---- 6/6/2025 4: 39 PM 56320 python3.dll -a---- 6/6/2025 4: 39 PM 7273984 python312.dll PS D: \RedactedLabs\Dev > ls .\scraps\ Directory: D: \RedactedLabs\Dev\scraps Mode LastWriteTime Length Name ---- ------------- ------ ---- -a---- 6/11/2025 10:48 PM 476672 AsyncDLLMQL.dll -a---- 6/11/2025 10:48 PM 4297 AsyncDLLMQL.exp -a---- 6/11/2025 10:26 PM 7752 AsyncDLLMQL.lib -a---- 6/11/2025 10:48 PM 7376896 AsyncDLLMQL.pdb -a---- 6/11/2025 10:48 PM 12288 DLLTester.exe -a---- 6/11/2025 10:48 PM 790528 DLLTester.pdb -a---- 6/6/2025 4: 39 PM 56320 python3.dll -a---- 6/6/2025 4: 39 PM 7273984 python312.dll PS D: \RedactedLabs\Dev > .\AsyncDLLMQL\x64\Release\DLLTester.exe Hello Hello from python: D ! PS D: \RedactedLabs\Dev > .\scraps\DLLTester.exe Hello Python path configuration: PYTHONHOME= 'D:\RedactedLabs\vcpkg_installed\x64-windows-static-md\x64-windows-static-md\tools\python3' PYTHONPATH = 'D:\RedactedLabs\vcpkg_installed\x64-windows-static-md\x64-windows-static-md\tools\python3\Lib;D:\RedactedLabs\vcpkg_installed\x64-windows-static-md\x64-windows-static-md\tools\python3\Lib\site-packages;D:\RedactedLabs\vcpkg_installed\x64-windows-static-md\x64-windows-static-md\tools\python3\DLLs' program name = 'python' isolated = 0 environment = 1 user site = 1 safe_path = 0 import site = 1 is in build tree = 0 stdlib dir = 'D:\RedactedLabs\vcpkg_installed\x64-windows-static-md\x64-windows-static-md\tools\python3\Lib' sys._base_executable = 'D:\\RedactedLabs\\Dev\\scraps\\DLLTester.exe' sys.base_prefix = 'D:\\RedactedLabs\\vcpkg_installed\\x64-windows-static-md\\x64-windows-static-md\\tools\\python3' sys.base_exec_prefix = 'D:\\RedactedLabs\\vcpkg_installed\\x64-windows-static-md\\x64-windows-static-md\\tools\\python3' sys.platlibdir = 'DLLs' sys.executable = 'D:\\RedactedLabs\\Dev\\scraps\\DLLTester.exe' sys.prefix = 'D:\\RedactedLabs\\vcpkg_installed\\x64-windows-static-md\\x64-windows-static-md\\tools\\python3' sys.exec_prefix = 'D:\\RedactedLabs\\vcpkg_installed\\x64-windows-static-md\\x64-windows-static-md\\tools\\python3' sys.path = [ 'D:\\RedactedLabs\\vcpkg_installed\\x64-windows-static-md\\x64-windows-static-md\\tools\\python3\\Lib', 'D:\\RedactedLabs\\vcpkg_installed\\x64-windows-static-md\\x64-windows-static-md\\tools\\python3\\Lib\\site-packages', 'D:\\RedactedLabs\\vcpkg_installed\\x64-windows-static-md\\x64-windows-static-md\\tools\\python3\\DLLs', 'D:\\RedactedLabs\\Dev\\scraps\\python312.zip', 'D:\\RedactedLabs\\vcpkg_installed\\x64-windows-static-md\\x64-windows-static-md\\tools\\python3\\DLLs', 'D:\\RedactedLabs\\vcpkg_installed\\x64-windows-static-md\\x64-windows-static-md\\tools\\python3\\Lib', 'D:\\RedactedLabs\\Dev\\scraps', ] ModuleNotFoundError: No module named 'encodings' Finally, my linker settings and other useful info: Platform: Windows IDE: Visual Studio Use Vcpkg Manifest: Yes Target triplet: "x64-windows-static-md" Additional include directories: $(SolutionDir)vcpkg_installed\x64-windows-static-md\x64-windows-static-md\include\python3.12 Additional Library Directories: $(VcpkgInstalledDir)\x64-windows-static-md\lib
CPython needs its standard library to exist at the PYTHONHOME directory, (which you can override in the config). If you need a standalone python interpreter to just parse python syntax (for game scripting) then you can use other implementations of python like RustPython or IronPython or JYThon or pocketpy, but you won't be able to use any C/C++ libraries like numpy. If security is not a concern then you can do as popular apps like blender do and package the interpreter with your application and set PYTHONHOME before initializing the interpreter with Py_InitializeFromConfig as in the following structure. . └── app_root/ ├── app.exe ├── python311.dll └── python/ ├── DLLs/ │ ├── _ctypes.pyd │ └── ... ├── Lib/ │ ├── site_packages/ │ │ └── numpy, etc... │ ├── os.py │ └── ... └── bin (optional)/ ├── python311.dll (see note below) └── python.exe (see note below) If you place python311.dll in a subdirectory then you must do extra steps to set the PATH to its location or use LoadLibrary instead and not link it directly. packing python.exe allows your user to install extra libraries using pip by doing python.exe -m pip install ... keep in mind that users will be able to modify everything, so if security is a concern then my recommendation is not to use Python ... but you can create a custom importer and static link everything and get it to work. note that a game did this before as well as create custom byte-code for the interpreter and was still completely reverse engineered, so this is not really fool-proof.
1
2
79,663,207
2025-6-12
https://stackoverflow.com/questions/79663207/matplotlib-slider-not-working-when-plot-is-updated-in-separate-function
I am using matplotlib's Slider to do a simple dynamic plot of a sine curve. I want to change the frequency using a slider. The code looks like this: import numpy as np import matplotlib.pyplot as plt from matplotlib.widgets import Slider x = np.linspace(400, 800, 400) fig, ax = plt.subplots() fig.subplots_adjust(bottom=0.25) mod = 1. lambda_plot, = ax.plot(x, np.sin(mod*x*2*np.pi/500)) ax_mod_slider = fig.add_axes([0.3, 0.1, 0.5, 0.04]) mod_slider = Slider( ax = ax_mod_slider, label = "modulation", valmin = 0, valmax = 20, valinit = 1., orientation = "horizontal") def update_mod(val): mod = mod_slider.val redraw() fig.canvas.draw_idle() def redraw(): lambda_plot.set_ydata(np.sin(mod*x*2*np.pi/500)) mod_slider.on_changed(update_mod) plt.show() This does only work if I put the code in redraw() directly in update_mod(), like this: def update_mod(val): mod = mod_slider.val lambda_plot.set_ydata(np.sin(mod*x*2*np.pi/500)) fig.canvas.draw_idle() Why can I not call another function for changing the plot? In this example, I could put it all into update_mod(), but as I do more complicated calculations, I thought it might be good to be able to split update_mod() into separate functions.
In the redraw() function: def redraw(): lambda_plot.set_ydata(np.sin(mod * x * 2 * np.pi / 500)) You're using the variable mod, but this mod is not defined in the local scope of redraw(), nor is it properly declared as global or passed as an argument. So Python looks for it in the outer scope and finds the mod = 1. you defined at the beginning of the script which never changes. When update_mod() changes mod, it does so in its local scope, and that doesn't affect the mod that redraw() sees. Just pass the mod value and it should work properly: def redraw(mod): lambda_plot.set_ydata(np.sin(mod * x * 2 * np.pi / 500))
2
2
79,664,893
2025-6-13
https://stackoverflow.com/questions/79664893/average-distance-of-any-point-of-a-disk-to-its-boundary
I was wondering what was the average distance "d" of any point in a ball to its boundary (not specifically the closest point). I made a simple monte carlo computation using Muller's method to get a uniform distribution - see linked answer : Python Uniform distribution of points on 4 dimensional sphere : def sample_within(radius, dim, nb_points=1, ): # Gaussian-distributed points x = np.random.normal(size=(nb_points, dim)) # Normalize to unit length (points on the surface of the n-sphere) x /= np.linalg.norm(x, axis=1)[:, np.newaxis] # Random radii with distribution ~ r^(1/n) => uniform volumic distribution in the ball r = np.random.rand(nb_points) ** (1/dim) # Scale by radius points = radius * x * r[:, np.newaxis] return points Note: I also used a "stupid" sampling in a box and discarding what ever points lies out of the sphere, everything I say in this post is true wiht both sampling method as they produce the same outcome. And using (the same method) : def sample_on_border(radius, dim:int, nb_points:int): # Gaussian-distributed points x = np.random.normal(size=(nb_points, dim)) # Normalize to unit length (points on the surface of the dim-sphere) x /= np.linalg.norm(x, axis=1)[:, np.newaxis] # Scale by radius points = radius * x return points The distances are calculated using (which I have checked manually): def calc_average_distance(radius: float, dim: int, nb_in_points: int, nb_border_points: int)->float: border_points = sample_on_border(radius, dim, nb_border_points) in_points = sample_within(radius, dim, nb_in_points) # in_points = border_points #specific case R=1 distances = np.sqrt(np.sum((border_points[:, np.newaxis, :] - in_points[np.newaxis, :, :])**2, axis=2)) average_distance_to_border = np.mean(distances) return average_distance_to_border From now on, I will speak in dimension 2 (disk) and with a radius of 1. Note: It is easy to demonstrate that the average distance between 2 points of the circle is 4/pi (1.27), and using only sampled points on the border in my Monte Carlo computation yield the same result. Also, the average distance between the center of the circle and the points of the circle is obviously 1 (since R=1). Therefore, I would expect the average distance d to be between 1 and 1.27 (it is just intuition though). The computed average distance d is : d = 1.13182 ± 0.00035 (with 5 sigma confidence) which is indeed between 1 and 1.27 (seems to even be the average). Now, I was also interest to find if there is an analytical solution to this problem, and I found the paper "The Average Directional Distance To The Boundary Of A Ball Or Disk" at https://www.emis.de/journals/AMEN/2024/AMEN-A230614.pdf This paper adress the problem in n-dimension, but its first section specifically deal with the case in dimension 2. Note: For the average distance between two points on the unit circle (i.e., when R=1), the paper gives the result 2/pi . However, unless I am mistaken, the correct value should be 4/π as previously stated and this can even be derived from the paper formula by taking r=R=1. However, I cannot find any (other) mistake in the paper and the analytical solution (which I have checked several times) yields 8/3pi so around 0.85 which is obvisouly different from the 1.13 I get when using my monte carlo code (and also not between 1 and 4/pi). Also, just to be sure, I tried: sampling non-uniformly (using uniform distribution to sample radius instead of using normal distribution), and I get another answer (1.088) but still not 0.85. or by sampling only along the segment [0, 1] (exploiting the problem symmetries) which gives 1.13 again or 1.088 again (depending if uniformly distributed or not). Using polar coordinates in 2D, also gives 1.13. Can anyone help me identify a mistake in my reasoning/code ? Edit: I failed to mention, that this post https://math.stackexchange.com/questions/875011/average-distance-from-a-point-in-a-ball-to-a-point-on-its-boundary gives 6/5 for a 3d-ball which is the result I get by Monte-Carlo but differs from the paper's result (3/4). I am too bad at math to understand their results, but by pure annalogy I figured that 1.13.. is in fact 32/(9pi) which is the value of the double integral between 0 and 1 and 0 and 2pi of r*sqrt(r**2 - 2rcos(theta)+1). Thanks
The error you are doing is to compute the average distance between a point within the disk and a point within the border. This is not what the article describes. The article describe the average distance between a point within a disk and the intersection of the border for a direction This may seem to be the same. Since choosing Φ randomly results into choosing randomly a point in the border. But it is not. Because the border point is this way not uniformly chosen on the border (it is the direction Φ from the inner point that is uniformly chosen) Trying to maintain as much as I can your code, using the same sample_within and sample_on_border (to ease generalization to other dimensions), what would be the distance d(P,Φ), if not (as you did) just ||P-(cos Φ, sin Φ)| P being points returned by sample_within, and (cos Φ, sin Φ) the points returned by sample_on_border (that is a strange way to choose Φ, sure, rather than just a uniform choosing in [0, 2π], but that way I reuse sample_on_border, and that way, it may be usable for more than 2D). To make notation lighter, and in that spirit "I am not just choosing an angle, but a point on a unit sphere", let's call u=(cos Φ, sin Φ) One way to figure out that distance is to say that distance is α such as P+α.u is on the unit circle (or sphere for higher dimensions), with α≥0 (α<0 is also counted, but with direction -Φ) That is ||P+α.u|| = 1 That is <P+αu, P+αu> = 1 That is <P,P>+2α<P,u>+α²<u,u> Since u is on the unit sphere, <u,u>=1. <P,P>=ρ² if ρ is the distance to the center of P. That is just a 2nd degree equation to solve with unknown α α² + 2<P,U>α + ρ²-1 = 0 Δ = 4<P,U>² + 4 - 4ρ² So we have two solutions α = (-2<P,U> ± √Δ)/2 = ±√(<P,U>²+1-ρ²) - <P,U> Since 1-ρ² is positive, √(<P,U>²+1-ρ²) is slightly more that |<P,U>|, so is positive only for solution α = √(<P,U>²+1-ρ²) - <P,U> So, that is your distance. Let's revise now your last function with that distance in mind def calc_average_distance2(dim: int, nb_in_points: int, nb_border_points: int)->float: # Just rename `border_points` to `direction_point`, since it is a direction we are choosing here # That is what I called u direction_point = sample_on_border(1, dim, nb_border_points) # And this, what I called P in_points = sample_within(1, dim, nb_in_points) # I mention later why I tried with this line #in_points = sample_on_border(1, dim, nb_in_points) # <P,u> scal = (direction_point[:,None,:] * in_points[None,:,:]).sum(axis=2) ρ = np.linalg.norm(in_points, axis=1)[None,:] dist = np.sqrt(scal**2+1-ρ**2)-scal # And this comment of yours, I realize only now, while copying this to # stack overflow, has the exact same purpose, probably that my own commented line # in_points = border_points #specific case R=1 return dist.mean() Because I did my reasoning on a unit sphere, and was too lazy to redo it with a radius, I removed the radius parameter and use a fixed 1 The result on my machine, with 5000 points × 1000 directions is 0.8490785129084816 which is close enough to 8/(3π)≈0.8488263631567751 And if I uncomment the line chosing in_points on the border, to compute what is called P₁ in the article (I suspect that was also the role of your commented line), I get 0.6368585804371621 which is close enough to 2/π≈0.6366197723675814 So, I am not 100% positive that this is what you wanted to do, and if that is what you meant by "average distance of any points of a dist to its boundary". Reason why I used conditional about you wanting to use this code to generalize to higher dimensions. But I am 100% positive that this is what the article is doing. A simpler version Earlier, I said "α>0. -α case will be counted when direction will be -Φ". But after all, what would happen if we used both α solution for average? That is just counting average for both Φ and -Φ (or u, and -u, if with think "direction" rather than "angle"). So, it would have worked without that α>0 restriction, and counting both α solution, negative and positive in the average. But of course it is |α| that is the distance then But what is the average of both |α| solutions? Well, it is It is ½ ( |√(<P,U>²+1-ρ²) - <P,U>| + |-√(<P,U>²+1-ρ²) - <P,U>| ) And since the first is clearly positive (as we already said) and second clearly negative, absolute values can be resolved directly. It is ½ ( √(<P,U>²+1-ρ²) - <P,U> + √(<P,U>²+1-ρ²) + <P,U>| ) = √(<P,U>²+1-ρ²) So, not a huge simplification, sure. that mean that we can drop the -<P,u> term dist = np.sqrt(scal**2+1-ρ**2)-scal ⇒ dist = np.sqrt(scal**2+1-ρ**2) works as well
2
1
79,664,331
2025-6-13
https://stackoverflow.com/questions/79664331/why-does-numpy-assign-different-string-dtypes-when-mixing-types-in-np-array
I'm trying to understand how NumPy determines the dtype when creating an array with mixed types. I noticed that the inferred dtype for strings can vary significantly depending on the order and type of elements in the list. print(np.array([1.0, True, 'is'])) # Output: array(['1.0', 'True', 'is'], dtype='<U32') print(np.array(['1.0', True, 'is'])) # Output: array(['1.0', 'True', 'is'], dtype='<U5') print(np.array(['1.0', 'True', 'is'])) # Output: array(['1.0', 'True', 'is'], dtype='<U4') I understand that NumPy upcasts everything to a common type, usually the most general one, and that strings tend to dominate. But why does the resulting dtype (<U32, <U5, <U4) differ so much when the content looks almost the same? Specifically: Why does np.array([1.0, True, 'is']) result in <U32? What determines the exact length in the dtype (e.g., <U4 vs <U5)? Is there a consistent rule for how NumPy infers the dtype and string length in such cases?
Looking at your array contents and the NumPy type promotion rules, I guess the following applies: For some purposes NumPy will promote almost any other datatype to strings. This applies to array creation or concatenation. This leaves us with the question about the string lengths. For the complete array, we need to choose a string length so that all values can be represented without loss of information. In your examples, the contents have the following data types: Strings ('is', 'True', '1.0'): for these, NumPy just needs to reserve their actual length (thus, if there are multiple strings in the same array, the maximum length of all occurring strings). Booleans (True): for converting them to a string, NumPy reserves a string length of 5, since all possible converted values are 'True' (length 4) and 'False' (length 5). We can easily verify this: np.array(True).astype(str) # >>> array('True', dtype='<U5') Floats (1.0): for converting them to a string, NumPy reserves a string length of 32. I assume this is for round-trip safety (i.e. to get the exact same value when converting the string representation back to float). I would have expected that a shorter length (somewhere between 20 and 30) should be enough, but maybe 32, a power of 2, has been chosen for better memory alignment properties. In any case, again, we can verify this: np.array(1.).astype(str) # >>> array('1.0', dtype='<U32') Now to your examples: np.array([1.0, True, 'is']): we have a float 1.0 (→ string length 32), a boolean True (→ string length 5), and a string 'is' of length 2: The maximum length to represent all values is 32. np.array(['1.0', True, 'is']): we have a string '1.0' of length 3, a boolean True (→ string length 5), and a string 'is' of length 2: The maximum length to represent all values is 5. np.array(['1.0', 'True', 'is']): we have a string '1.0' of length 3, a string 'True' of length 4, and a string 'is' of length 2: The maximum length to represent all values is 4.
2
1
79,664,217
2025-6-13
https://stackoverflow.com/questions/79664217/arbitrary-stencil-slicing-in-numpy
Is there a simple syntax for creating references to an arbitrary number of neighbouring array elements in numpy? The syntax is relatively straightforward when the number of neighbours is hard-coded. A stencil width of three for example is import numpy as np x = np.arange(8) # Hard-coded stencil width of 3 x_neighbours = ( x[ :-2] x[ 1:-1] x[ 2: ] ) However, my attempt at arbitrary width stencils is not particularly readable nStencil = 3 x_neighbours = ( x[indexStart:indexStop] for indexStart, indexStop in zip( (None, *range(1,nStencil)), (*range(1-nStencil,0), None), ) ) Is there a better approach?
I'd recommend using sliding_window_view. Change: nStencil = 3 x_neighbours = ( x[indexStart:indexStop] for indexStart, indexStop in zip( (None, *range(1,nStencil)), (*range(1-nStencil,0), None), ) ) To: nStencil = 3 sliding_view = sliding_window_view(x, nStencil) x_neighbours = tuple(sliding_view[:, i] for i in range(nStencil))
1
3