How to create the matrix AxB in Python? [duplicate] - python

This question already exists:
Python - Make an Array: n by n [duplicate]
Closed 6 years ago.
I am trying to create this matrix AxB with a specific pattern in Python :
[1.0, 0.0, 0.0],
[-1.0, 0.0, 0.0],
[0.0, 1.0, 0.0],
[0.0, -1.0, 0.0],
[0.0, 0.0, 1.0],
[0.0, 0.0, -1.0]
The problem is that I want to create this matrix without having to resort to hard coding it. Can someone help me to isolate the pattern, and fill the matrix dynamically?
Here is what I've tried so far :
matrix_test = [[0.0 for i in range(3)] for i in range(6)]
for x in range(3):
matrix_test [x][x] = 1.0

matrix_test = [[0.0 for i in range(3)] for i in range(6)]
for x in range(3):
matrix_test [2 * x][x] = 1.0
matrix_test [2 * x + 1][x] = -1.0

Related

How to calculate a deformation gradient in Python. (On a cube in 3D) [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
We don’t allow questions seeking recommendations for books, tools, software libraries, and more. You can edit the question so it can be answered with facts and citations.
Closed 3 years ago.
Improve this question
I am trying to calculate Large(Langrangian/Green) Strains in python on a cube I have artificially deformed. I am having trouble calculating the deformation matix, F:
Non-deformed Cube:
Deformed Cube:
Cube coordinates are x1 and x2
x1 = [[0.0, 0.0, 0.0], [1.0, 0.0, 0.0], [0.0, 1.0, 0.0], [1.0, 1.0, 0.0], [0.0, 0.0, 1.0], [1.0, 0.0, 1.0],[0.0, 1.0, 1.0], [1.0, 1.0, 1.0]]
x2 = [[0.0, 0.0, 0.0], [1.0, 0.0, 0.0], [0.0, 1.0, 0.0], [1.0, 1.0, 0.0], [0.0, 0.0, 1.0], [1.5, 0.0, 1.5],[0.0, 1.5, 1.5], [2.0, 2.0, 2.0]]
global_coords[0] = x1
global_coords[1] = x2
def positions_at_t(global_coords, t):
gc = np.array(global_coords)
new_coords = gc[0] + t*(gc[1] - gc[0])
return list(new_coords)
gc[1]-g[2] works as a gradient over time as we can see above. But the problem is it is defined in a 8x3 matrix as we would expect a 3x3 for a deformation gradient.
Side note/question:
On this site he generates equations that define the movement of points in (x,y,z) to then differentiate with respect to (X,Y,Z) to get F. Is there a library I can use to get these equations? (or the gradients?)
Deformation Gradient, F
The deformation gradient is described as:
So solving for F will be:
F = dX\dx
Where '\' is left matrix division, roughly equivalent to inv(A) * B.
This is a linear algebra problem with 9 variables and 9 equations.
Green Strain, E
From http://www.continuummechanics.org/greenstrain.html:
Implementing this in python using numpy looks like:
dx = x1
dX = x2
F = np.linalg.solve(dX[5:],dx[5:])
C = F.T # F
E = .5*(C-np.identity(3))
E
(output:)array([[ 1.5 , 0.125, -0.125],
[ 0.125, 1.5 , -0.125],
[-0.125, -0.125, 0. ]])

Plot and fill 3D volumes in Python

I am working with some 3D (volumetric) data using Python, and for every tetrahedron, I have not only the vertices's coordinates but also a fourth dimension which is the value of some parameter for that tetrahedron volume.
For example:
# nodes coordinates that defines a tetrahedron volume:
x = [0.0, 1.0, 0.0, 0.0]
y = [0.0, 0.0, 1.0, 0.0]
z = [0.0, 0.0, 0.0, 1.0]
# Scaler value of the potential for the given volume:
c = 100.0
I would like to plot a 3D volume (given by the nodes coordinates) filled with some solid color, which would represent the given value C.
How could I do that in Python 3.6 using its plotting libraries?
You can use mayavi.mlab.triangular_mesh():
from mayavi import mlab
from itertools import combinations, chain
x = [0.0, 1.0, 0.0, 0.0, 2.0, 3.0, 0.0, 0.0]
y = [0.0, 0.0, 1.0, 0.0, 2.0, 0.0, 3.0, 0.0]
z = [0.0, 0.0, 0.0, 1.0, 2.0, 0.0, 0.0, 3.0]
c = [20, 30]
triangles = list(chain.from_iterable(combinations(range(s, s+4), 3) for s in range(0, len(x), 4)))
c = np.repeat(c, 4)
mlab.triangular_mesh(x, y, z, triangles, scalars=c)

Build a dataframe from a filtered list of tuple

I have a two lists
kuid -> ['LOdRTFfn', 'Lckq4LkU', 'LcsYHodm']
And NN that is a list of tuple where the first element is a list of indexs of kuid and the other element is an array of values
NN -> [([0, 1, 2], [0.0, 1.2, 1.4]), ([1, 0, 2], [0.0, 1.4, 1.4]), ([2, 0, 1], [0.0, 1.1, 1.4])]
I'd like to keep only the indexes where the values are less then 1.3 for example:
[([0, 1], [0.0, 1.2]), ([1], [0.0]), ([2, 0], [0.0, 1.1])]
and then get the correct value of kuid and build a dataframe:
kuid la lametric
0 LOdRTFfn [LOdRTFfn, Lckq4LkU] [0.0, 1.2]
1 Lckq4LkU [Lckq4LkU] [0.0]
2 LcsYHodm [LcsYHodm, LOdRTFfn] [0.0, 1.1]
Is it possible to do this with list of comprehensions (or other fast solution) avoiding looping? The array could be very large....
Thank you
Here's one way
In [1789]: df = pd.DataFrame(dict(kuid=kuid, NN=[np.array(x) for x in NN]))
In [1790]: df['lametric'] = df.NN.apply(lambda x: x[1][x[1] < 1.3])
In [1791]: df['la'] = df.NN.apply(lambda x: [kuid[int(i)] for i in x[0][x[1] < 1.3]])
In [1792]: df
Out[1792]:
NN kuid lametric \
0 [[0.0, 1.0, 2.0], [0.0, 1.2, 1.4]] LOdRTFfn [0.0, 1.2]
1 [[1.0, 0.0, 2.0], [0.0, 1.4, 1.4]] Lckq4LkU [0.0]
2 [[2.0, 0.0, 1.0], [0.0, 1.1, 1.4]] LcsYHodm [0.0, 1.1]
la
0 [LOdRTFfn, Lckq4LkU]
1 [Lckq4LkU]
2 [LcsYHodm, LOdRTFfn]

Plotting mesh data from vtk python using matplotlib

The following questions makes use of vtk python but what I am attempting to do should not require any knowledge of vtk because I have converted the data I wish to plot into numpy arrays described below. If anyone does know of an improvement to the way I go about actually processing the vtk data into numpy, please let me know!
I have some data that I have extracted using vtk python. The data consists of a 3D unstructured grid and has several 'blocks'. The block I am interested in is block0. The data is contained at each cell rather than at each point. I wish to plot a contourf plot of a scalar variable on this grid using matplotlib. In essence my problem comes down to the following:
Given a set of cell faces with known vertices in space and a known scalar field variable, create a contour plot as one would get if one had created a numpy.meshgrid and used plt.contourf/plt.pcolormesh etc. Basically I post process my vtk data like so:
numCells = block0.GetCells().GetNumberOfCells()
# Array of the 8 vertices that make up a cell in 3D
cellPtsArray = np.zeros((numCells,8,3))
# Array of the 4 vertices that make up a cell face
facePtsArray = np.zeros((numCells,4,3))
#Array to store scalar field value from each cell
valueArray = np.zeros((numCells,1))
for i in xrange(numCells):
cell = block0.GetCell(i)
numCellPts = cell.GetNumberOfPoints()
for j in xrange(numCellPts):
cellPtsArray[i,j,:] = block0.GetPoint(cell.GetPointId(j))
valueArray[i] = block0.GetCellData().GetArray(3).GetValue(i)
xyFacePts = cell.GetFaceArray(3)
facePtsArray[i,:,:] = cellPtsArray[i,xyFacePts,:]
Now I wish to create a contour plot of this data (fill each cell in space according to an appropriate colormap of the scalar field variable). Is there a good built in function in matplotlib to do this? Note that I cannot use any form of automatic triangulation-the connectivity of the mesh is already specified by facePtsArray by the fact that connections between points of a cell have been ordered correctly (see my plot below)
Here is some test data:
import numpy as np
import matplotlib.pyplot as plt
# An example of the array containing the mesh information: In this case the
# dimensionality is (9,4,3) denoting 9 adjacent cells, each with 4 vertices and
# each vertex having (x,y,z) coordinates.
facePtsArray = np.asarray([[[0.0, 0.0, 0.0 ],
[1.0, 0.0, 0.0 ],
[1.0, 0.5, 0.0 ],
[0.0, 0.5, 0.0 ]],
[[0.0, 0.5, 0.0 ],
[1.0, 0.5, 0.0 ],
[1.0, 1.0, 0.0 ],
[0.0, 1.0, 0.0 ]],
[[0.0, 1.0, 0.0 ],
[1.0, 1.0, 0.0 ],
[1.0, 1.5, 0.0 ],
[0.0, 1.5, 0.0 ]],
[[1.0, 0.0, 0.0 ],
[2.0, -0.25, 0.0],
[2.0, 0.25, 0.0],
[1.0, 0.5, 0.0]],
[[1.0, 0.5, 0.0],
[2.0, 0.25, 0.0],
[2.0, 0.75, 0.0],
[1.0, 1.0, 0.0]],
[[1.0, 1.0, 0.0],
[2.0, 0.75, 0.0],
[2.0, 1.25, 0.0],
[1.0, 1.5, 0.0]],
[[2.0, -0.25, 0.0],
[2.5, -0.75, 0.0],
[2.5, -0.25, 0.0 ],
[2.0, 0.25, 0.0]],
[[2.0, 0.25, 0.0],
[2.5, -0.25,0.0],
[2.5, 0.25, 0.0],
[2.0, 0.75, 0.0]],
[[2.0, 0.75, 0.0],
[2.5, 0.25, 0.0],
[2.5, 0.75, 0.0],
[2.0, 1.25, 0.0]]])
valueArray = np.random.rand(9) # Scalar field values for each cell
plt.figure()
for i in xrange(9):
plt.plot(facePtsArray[i,:,0], facePtsArray[i,:,1], 'ko-')
plt.show()

Accessing elements in a nested list

I have elements in a nested list called "train_data" like in the example:
[0] [0.935897, 1.0, 1.0, 0.928772, 0.053629, 0.0, 39.559883, 0.009494, 0]
[1] [0.467681, 1.0, 1.0, 0.778987, 0.069336, 0.0, 56.571999, 0.024675, 0]
[2] [0.393258, 1.0, 1.0, 0.843201, 0.068779, 0.0, 66.866669, 0.069206, 1]
I would like to access all rows with the first 8 columns (all but the last one), and all rows with only the last column. I need to this without for loops, in a single line of code.
I tried something like this:
print train_data[0][:]
print train_data[:][0]
but this gives me the same result:
[0.935897, 1.0, 1.0, 0.928772, 0.053629, 0.0, 39.559883, 0.009494, 0]
[0.935897, 1.0, 1.0, 0.928772, 0.053629, 0.0, 39.559883, 0.009494, 0]
Could someone help me please?
Edit:
Sorry, the expected output for the first query is:
[0.935897, 1.0, 1.0, 0.928772, 0.053629, 0.0, 39.559883, 0.009494]
[0.467681, 1.0, 1.0, 0.778987, 0.069336, 0.0, 56.571999, 0.024675]
[0.393258, 1.0, 1.0, 0.843201, 0.068779, 0.0, 66.866669, 0.069206]
and for the second query is:
[0]
[0]
[1]
you can use [:-1] slicing for get all elements except the last one !
>>> l1=[0.935897, 1.0, 1.0, 0.928772, 0.053629, 0.0, 39.559883, 0.009494, 0]
>>> l2=[0.467681, 1.0, 1.0, 0.778987, 0.069336, 0.0, 56.571999, 0.024675, 0]
>>> l3=[0.393258, 1.0, 1.0, 0.843201, 0.068779, 0.0, 66.866669, 0.069206, 1]
>>> l=[l1,l2,l3]
>>> [i[:-1] for i in l]
[[0.935897, 1.0, 1.0, 0.928772, 0.053629, 0.0, 39.559883, 0.009494], [0.467681, 1.0, 1.0, 0.778987, 0.069336, 0.0, 56.571999, 0.024675], [0.393258, 1.0, 1.0, 0.843201, 0.068779, 0.0, 66.866669, 0.069206]]
Is there really a good reason to do this in a oneliner? I mean why is that a requirement?
print [i[:-1] for i in l] # All rows with all cols - 1
print [i[-1] for i in l] # All rows with last col
But even if the loop is not explicit with a for, it's implicit as a comprehensive list...
edit: 1 → -1 for second line of code, my mistake
I think you are expecting this
L1 = [x[0:-1] for x in train_data]
L2 = [x[-1] for x in train_data]
for x in L1:
print x
for x in L2:
print [x]

Categories

Resources