    

 ## On this page

  

 

 # Linear Algebra 

 Last update: 16.07.2025 

Use the tmath module to perform custom linear algebra operations in your SoS analysis. Here, we calculate the mean and variance of field designs provided with the lsdyna metal forming example.

-- load example data:

sdbfile = sos.currentScriptPath() .. "/../lsdyna/metal_forming__eroded_elements/sos_demo.sdb"

local settings = sos.LoadDataBaseSettings(sdbfile);

sos.loadDataBase(sos.database(), settings);







-- get all active samples of 'pstrain':

local pstrain_objects = sos.database():data():filterQuantity("pstrain"):samples():active()



-- now compute mean and variance



-- create data vectors with value zero and with appropriate dimension

numElements = sos.numElements(sos.database())

mean = tmath.ZeroMatrix(numElements,1);

variance = tmath.ZeroMatrix(numElements,1);



-- loop over all active samples:

--info(pstrain_objects,1)

N = pstrain_objects:size()

print("There are " .. N .. " samples to be analyzed.")

for i=0,N-1 do

 -- convert field data to a vector:

 -- if there are 'missing items' then the field data vector contains the interpolated values

 local vec = pstrain_objects[i]:getData()

 mean = mean + vec

 variance = variance + vec:CW()^2 -- CW() -&gt; component-wise operator "^2"

end

mean = mean/N

variance = variance/(N-1) - mean:CW()^2*N/(N-1) -- subtract Steiner part





-- print some results:

elem_coors = sos.computeElementCoordinates(sos.database()) -- contains the element center coordinates

elem_id = 4000 -- element ID 4000

idx = sos.globalIndexFromElement(sos.database(), 0, elem_id) -- get the index of the element in the data vectors



print("Element #"..elem_id.. " has a mean of " .. mean[idx] .. " and variance of " .. variance[idx] .. " for the plastic strain:");

print("The center coordinate of the element is ", elem_coors:Col(idx):Transpose())



-- insert the results into SoS database:

mean_obj = sos.createElementDataObject(sos.database(), mean, false); -- no sample

sos.database():data():insert( sos.DataObjectKey("my_mean", "pstrain"), mean_obj)

var_obj = sos.createElementDataObject(sos.database(), variance, false); -- no sample

sos.database():data():insert( sos.DataObjectKey("my_var", "pstrain"), var_obj)



-- notice: The values will likely differ from the values computed with the SoS-internal algorithms. SoS treats the missing items in a specific way.



print("Terminate script with success.")







-- some advanced indexing:

ind1 = tmath.Matrix({{0,1,3,6}}):Transpose()

ind2 = tmath.Matrix({{0,0},{1,0},{2,0},{7,0}})

c1 = mean[ind1]

c2 = mean[ind2]

print(mean)

print("c1\n",c1)

print("c2\n",c2)



MEAN1 = mean*1

MEAN2 = mean*1

MEAN1[ind1] = c1*10

MEAN2[ind2] = c2*10

print("ind1:\n",ind1:Transpose());

print("ind2:\n",ind2:Transpose());

print("MEAN\n",mean:Transpose())

print("MEAN1\n",MEAN1:Transpose())

print("MEAN2\n",MEAN2:Transpose())