Making grid triangular mesh quickly with Numpy

2024/10/6 8:27:55

Consider a regular matrix that represents nodes numbered as shown in the figure:

NodesAndTriangles

I want to make a list with all the triangles represented in the figure. Which would result in the following 2 dimensional list:[[0,1,4],[1,5,4],[1,2,5],[2,6,5],...,[11,15,14]]

Assuming that the dimensions of the matrix are (NrXNc) ((4X4) in this case), I was able to achieve this result with the following code:

def MakeFaces(Nr,Nc):Nfaces=(Nr-1)*(Nc-1)*2Faces=np.zeros((Nfaces,3),dtype=np.int32)for r in range(Nr-1):for c in range(Nc-1):fi=(r*(Nc-1)+c)*2l1=r*Nc+cl2=l1+1l3=l1+Ncl4=l3+1Faces[fi]=[l1,l2,l3]Faces[fi+1]=[l2,l4,l3]return Faces

However, the double loop operations make this approach quite slow. Is there a way of using numpy in a smart way to do this faster?

Answer

We could play a multi-dimensional game based on slicing and multi-dim assignment that are perfect in NumPy environment on efficiency -

def MakeFacesVectorized1(Nr,Nc):out = np.empty((Nr-1,Nc-1,2,3),dtype=int)r = np.arange(Nr*Nc).reshape(Nr,Nc)out[:,:, 0,0] = r[:-1,:-1]out[:,:, 1,0] = r[:-1,1:]out[:,:, 0,1] = r[:-1,1:]out[:,:, 1,1] = r[1:,1:]out[:,:, :,2] = r[1:,:-1,None]out.shape =(-1,3)return out

Runtime test and verification -

In [226]: Nr,Nc = 100, 100In [227]: np.allclose(MakeFaces(Nr, Nc), MakeFacesVectorized1(Nr, Nc))
Out[227]: TrueIn [228]: %timeit MakeFaces(Nr, Nc)
100 loops, best of 3: 11.9 ms per loopIn [229]: %timeit MakeFacesVectorized1(Nr, Nc)
10000 loops, best of 3: 133 µs per loopIn [230]: 11900/133.0
Out[230]: 89.47368421052632

Around 90x speedup for Nr, Nc = 100, 100!

https://en.xdnf.cn/q/70390.html

Related Q&A

df [X].unique() and TypeError: unhashable type: numpy.ndarray

all,I have a column in a dataframe that looks like this:allHoldingsFund[BrokerMixed] Out[419]: 78 ML 81 CITI 92 ML 173 CITI 235 ML 262 ML 264 ML 25617 …

Python pandas idxmax for multiple indexes in a dataframe

I have a series that looks like this:delivery 2007-04-26 706 23 2007-04-27 705 10706 1089708 83710 13712 51802 4806 181…

No of Pairs of consecutive prime numbers having difference of 6 like (23,29) from 1 to 2 billion

How to find number of pairs of consecutive prime numbers having difference of 6 like (23,29) from 1 to 2 billion (using any programming language and without using any external libraries) with consideri…

Building a docker image for a flask app fails in pip

from alpine:latest RUN apk add --no-cache python3-dev \&& pip3 install --upgrade pipWORKDIR /backend COPY . /backendRUN pip --no-cache-dir install -r requirements.txt EXPOSE 5000 ENTRYPOINT [py…

Why is numba so fast?

I want to write a function which will take an index lefts of shape (N_ROWS,) I want to write a function which will create a matrix out = (N_ROWS, N_COLS) matrix such that out[i, j] = 1 if and only if j…

How to create a field with a list of foreign keys in SQLAlchemy?

I am trying to store a list of models within the field of another model. Here is a trivial example below, where I have an existing model, Actor, and I want to create a new model, Movie, with the field …

Implementing a recursive algorithm in pyspark to find pairings within a dataframe

I have a spark dataframe (prof_student_df) that lists student/professor pair for a timestamp. There are 4 professors and 4 students for each timestamp and each professor-student pair has a “score” (s…

Python Delegate Pattern - How to avoid circular reference?

I would to ask if using the Delegate Pattern in Python would lead to circular references and if so, what would be the best way to implement it to ensure the object and its delegate will be garbage coll…

Render Jinja after jQuery AJAX request to Flask

I have a web application that gets dynamic data from Flask when a select element from HTML is changed. of course that is done via jquery ajax. No probs here I got that.The problem is, the dynamic data …

shape-preserving piecewise cubic interpolation for 3D curve in python

I have a curve in 3D space. I want to use a shape-preserving piecewise cubic interpolation on it similar to pchip in matlab. I researched functions provided in scipy.interpolate, e.g. interp2d, but …