Transforming a for loop into a sliced operation on a NumPy array

I am working on a loop to calculate the elements of a 3D numpy array. The code looks like this:

A = np.zeros((N - 2, N - 2, N - 2))
for i in range(1, N - 1):
    for j in range(1, N - 1):
        for k in range(1, N - 1):
            A[i - 1, j - 1, k - 1] = (B[i,j,k] * dy[j] * dz[k] + B[i,j-1,k] * dy[j-1] * dz[k]
                                        + B[i,j,k-1] * dy[j] * dz[k-1] + B[i,j-1,k-1] * dy[j-1] * dz[k-1]) / (4 * dx[i])

The above method is becoming slow for large values of N, so I attempted a different approach:

A = (B[1:-1, 1:-1, 1:-1] * dy[1:] * dz[1:] + B[1:-1, :-2, 1:-1] * dy[:-1] * dz[1:]
                                        + B[1:-1, 1:-1, :-2] * dy[1:] * dz[:-1] + B[1:-1, :-2, :-2] * dy[:-1] * dz[:-1]) / (4 * dx[1:])

However, the alternate method fails when dx, dy, and dz are not constant. I also experimented with the following approach:

dX, dY, dZ = np.meshgrid(dx, dy, dz)
A = (B[1:-1, 1:-1, 1:-1] *  dY[1:, 1:, 1:] * dZ[1:, 1:, 1:] + B[1:-1, :-2, 1:-1] * dY[:-1, :-1, :-1] * dZ[1:, 1:, 1:]
                            + B[1:-1, 1:-1, :-2] * dY[1:, 1:, 1:] * dZ[:-1, :-1, :-1] + B[1:-1, :-2, :-2] * dY[:-1, :-1, :-1] * dZ[:-1, :-1, :-1]) / (4 * dX[:-1, :-1, :-1])

Unfortunately, this approach also failed to produce the desired result.

If anyone has any ideas or suggestions on how to improve this calculation, I would greatly appreciate it.

Answer №1

A[i - 1, j - 1, k - 1] = (B[i,j,k] * dy[j] * dz[k] + B[i,j-1,k] * dy[j-1] * dz[k]
                                    + B[i,j,k-1] * dy[j] * dz[k-1] + B[i,j-1,k-1] * dy[j-1] * dz[k-1]) / (4 * dx[i])

Let's adjust the iterations to be from 0 to N-2.

A[i, j, k] = (B[i+1,j+1,k+1] * dy[j+1] * dz[k+1] + B[i+1,j,k+1] * dy[j] * dz[k+1]
                                    + B[i+1,j+1,k] * dy[j+1] * dz[k] + B[i+1,j,k] * dy[j] * dz[k]) / (4 * dx[i+1])

Now, let's handle the 4 terms individually.

B[1:,1:,1:]*dy[None,1:,None]*dz[None,None,1:]

B[1:,:-1,1:]*dy[None,:-1,None]*dz[None,None,1:]

etc

I formulated these equations without testing, so there might be mistakes, but this should give you a good starting point.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Executing a for loop asynchronously on an AsyncGenerator

When working with an asynchronous generator, the expectation is to be able to iterate through it asynchronously. However, after running the code below, a synchronous for loop is produced instead: import asyncio async def time_consuming(t): print(f"G ...

"Exploring Python in the wild beauty of Yosemite

Recently received a new Mac running Yosemite and utilized the Migration Assistant to transfer files from my previous computer. However, I now have an outdated version (2.7.2) of Python that is incompatible with Yosemite, causing crashes at the second line ...

Django REST FrameWork JWT prohibits the provision of data and self-decoding

I currently have these API endpoints set up: urlpatterns += [ path('api-token-auth/', obtain_jwt_token), path('api-token-verify/', verify_jwt_token), path('api-token-refresh/', refresh_jwt_token), path('a ...

Isn't it surprising that selenium + BeautifulSoup combination doesn't always find everything?

I'm currently working on an automation project to track match scores. Although I am using selenium and BeautifulSoup, the script is only retrieving the first 10 matches and not the rest. How can I rectify this issue? from bs4 import BeautifulSoup impo ...

The presence of a comma within numerical values is leading to difficulties in parsing CSV

After attempting to read a csv file, I encountered the following error message: ParserError: Error tokenizing data. C error: Expected 1 fields in line 12, saw 2 I examined my csv file and pinpointed the issue to one of the numbers containing decimals sep ...

What is the best way to handle a text file when using Python in the command line?

For running the program, follow these steps: Python LinkState < test1.txt The file name is called Linkstate.py. The text file to be used as input is named test1.txt. My question is how should I handle the txt file in my code for this setup? It seems l ...

Troubleshooting: JavaScript code not functioning properly with variable input instead of fixed value

I have encountered an issue with a JS function that I'm using. The function is shown below: // A simple array where we keep track of things that are filed. filed = []; function fileIt(thing) { // Dynamically call the file method of whatever ' ...

My Discord Python Bot Keeps Disrupting My Commands While Running Background Tasks

I've been developing a Python Discord bot that sends scheduled messages in a server at specific times every day, along with other functionalities. However, after implementing the scheduled messaging feature, the bot commands have stopped working - lea ...

Is there a way to add a pause between typed characters when using .send_keys()?

I've been working on automating an online application and I'm looking for a way to make the ".send_keys()" function more authentic. Instead of inputting "[email protected]" rapidly into the text field, I want to introduce a slight delay betw ...

Determine the number of items in a Python list

To perform a string count of the letter "O" in my list, I have created a top_board variable. After adding elements like "O" and "X", the updated version of top_board array will be displayed. top_board = [ ["O", None, None, None, None, None, None, None ...

How can we group data by minute, hour, day, month, and year?

I've been trying to find a resolution for my current issue, but I seem to be stuck. I'm really hoping that you can assist me. The Issue: My goal is to determine the number of tweets per minute. Data Set: time sentime ...

Exploring the potential of Django to efficiently implement multiple listviews on a single webpage

Recently started working with Python and Django, but I may have bitten off more than I can chew. If anyone has the time to help educate me, I would greatly appreciate it. My main model deals with "work orders," each of which is linked to subsets of data. I ...

Saving a Python list to a CSV file will empty the list

I'm currently experimenting with lists, the enumerate() method, and CSV files. In my process, I am using the writerows() method to store an enumerate object in a .csv file. However, once the writing is complete, the list/enumerate object ends up empt ...

Why does virtualenv default to using the global python installation instead of the local one after it has been pulled?

After cloning a python project from Git that was originally created by me on another computer using virtualenv, I noticed that the python library is located in a local directory (fila_env/bin/python) within the project. Despite activating the environment w ...

What are the steps to implement OpenCV for a real-time application?

When it comes to real time systems, a quick and efficient platform is essential. I'm curious about which combination would be best for real time image processing: OpenCV-Python, OpenCV-MVStudio (C++), OpenCV-Matlab, or OpenCV-Java? I've heard abo ...

Guide on how to activate a hyperlink on a webpage using Python Selenium?

Having trouble clicking a specific link on a webpage using Python Selenium and encountering this issue: no such element: Unable to locate element: Tried different methods like find_element_by_xpath, find_element_by_partial_link_text, and find_element_by ...

Python : Retrieving file from the URL associated with PHP functionality

I'm attempting to download a file from a webpage. The file is linked using php:~/download.php?id=~ To download the file, you can either click the link or right-click and choose the option "save this file" in your web browser. Initially, I tried usin ...

Perform a filtering operation on the sorted array output and generate a fresh array

Yesterday, I had an issue sorting XML results into an associative array, but I managed to resolve it. (you can view my code here) <?php $xmlData = 'http://xml.betfred.com/Horse-Racing-Daily.xml'; $xml = simplexml ...

Error encountered in Colab when importing keras.utils: "to_categorical" name cannot be imported

Currently utilizing Google's Colab to execute the Deep Learning scripts from François Chollet's book "Deep Learning with python." The initial exercise involves using the mnist dataset, but encountering an error: ImportError: cannot import name & ...

Error message: ngRepeat does not allow duplicate elements in an array

Upon review, I discovered this particular piece of code: <!DOCTYPE html> <html> <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.4/angular.min.js"></script> <body> <script> var app = angular.module("myS ...