Search code examples
pythonmatrixansys

Create a matrix based on 3 lists


I'm trying to create a matrix based on 3 different lists read from an input file. I need a matrix of 3 columns: Col_2 representing the x coordinates first, then Col_3 for the y and Col_4 for the z in third position.

The goal is to enter this matrix into the ConvexHulll function and get a number that I will then append in another array.

right now I'm using this code but the output file is not created and I supposed it was because of the faulty Matrix. (this code is called in the script of an ACT extension)

Thanks in advance for your help! I didn't manage to import my input file but it looks like this (33563 lines)

import sys
import os

def ScipyRW(UserFiles,inputfile,outputfile,SF):
#Sample code for testing Scipy library from IronPython(ACT)
import scipy as sp 
import numpy as np

scaleFactor=float(SF) 

print(UserFiles)
print(inputfile)
print(outputfile)
print(scaleFactor)

fn=open(inputfile,'r')
line=fn.readline()


Col_1=[]
Col_2=[]
Col_3=[]
Col_4=[]

while line:
    v=line.split(",")
    Col_1.append(float((v[0]))) #reading column 1
    Col_2.append(float((v[1]))) #reading column 2
    Col_3.append(float((v[2]))) #reading column 3
    Col_4.append(float((v[3]))) #reading column 4
    line=fn.readline()
fn.close()

print("csv file read")

from scipy.spatial import ConvexHull

NodeNo=np.append(Col_1)
Matrix=np.array([Col_2],[Col_3],[Col_4])

myhull = ConvexHull(Matrix)
vol= hull.volume
ar = hull.area

myICV = vol-(ar*scaleFactor)/1000
print(myICV)

NodeNo=np.array(Col_1)
ICV=np.full_like(NodeNo,myICV)

np.savetxt(outputfile,(NodeNo,ICV),delimiter=',',fmt='%f') #save output into txt file

print ("Input csv file processed by numpy and written out")

ScipyRW(sys.argv[1],sys.argv[2],sys.argv[3],sys.argv[4])

Solution

  • I modified your script a little:

    import scipy as sp 
    import numpy as np
    inputfile = "path/to/coordinate/file"
    
    Col_1=[]
    Col_2=[]
    Col_3=[]
    Col_4=[]
    # replaced while with for-loop
    for line in open(inputfile):
        v = line.split(',')
        Col_1.append(float((v[0]))) #reading column 1
        Col_2.append(float((v[1]))) #reading column 2
        Col_3.append(float((v[2]))) #reading column 3
        Col_4.append(float((v[3]))) #reading column 4
        
    from scipy.spatial import ConvexHull
    
    # Replaced append with direct assignment
    NodeNo=Col_1
    # Added a matrix transpose and fixed brackets
    Matrix=np.array([Col_2,Col_3,Col_4]).T
    
    myhull = ConvexHull(Matrix)
    vol= myhull.volume
    ar = myhull.area
    scaleFactor = 1
    
    myICV = vol-(ar*scaleFactor)/1000
    print(myICV)
    
    NodeNo=np.array(Col_1)
    ICV=np.full_like(NodeNo,myICV)