I m trying to extract energy at each integration point in Abaqus. I can do it for stresses or strains but i cant do for the energetical quantities. The obtained error is : “KeyError: 'ELEN'”, but in Abaqus it is the good keyword… Below it is my code to extract it :
from odbAccess import *
import numpy as np
odb = openOdb(path='C:/Desktop/Fish1.odb')
# lastFrame = odb.steps['Step-2'].frames[-1]
lastFrame = odb.steps['Step-1'].frames[-1]
topCenter = \
odb.rootAssembly.instances['PART-1-1']
stressField = lastFrame.fieldOutputs['ELEN']
field = stressField.getSubset(region=topCenter,
position=INTEGRATION_POINT, elementType = 'CPS3')
fieldValues = field.values
sortie = open('C:/Users/tests.txt', 'w')
sortie.write('Eleme \t Integ \t\t PE11 \t\t\t PE22 \t\t\t PE12 \n')
for v in fieldValues:
sortie.write('%-10.2f'% ( v.elementLabel))
if v.integrationPoint:
sortie.write('%-10.2f'% (v.integrationPoint))
sortie.write('%-10.3f\t\t %-10.3f\t\t %-10.3f\t\t %-10.3f\t\t \n'% (v.data[0], v.data[1], v.data[2], v.data[3]))
sortie.close()
I guess you have already checked in Abaqus Viewer whether the FieldOutput ELEN is available there.
ELEN is a whole element variable, so you can't extract it at integration points, because it is not available there.
from odbAccess import *
import numpy as np
odb = openOdb(path='C:/Desktop/Fish1.odb')
lastFrame = odb.steps['Step-1'].frames[-1]
topCenter = odb.rootAssembly.instances['PART-1-1']
stressField = lastFrame.fieldOutputs['ELEN']
field = stressField.getSubset(region=topCenter, elementType = 'CPS3')
fieldValues = field.values
Even though it is not really the solution you asked for, i hope this will help.
Related
I am trying to implement a "user-friendly" portfolio optimization program in Python.
Since I am still a beginner I did not quite manage to realize it.
The only thing the program should use as input are the stock codes.
I tried to create a mwe below:
import numpy as np
import yfinance as yf
import pandas as pd
def daily_returns(price):
price = price.to_numpy()
shift_1 = price[1:]
shift_2 = price[:-1]
return (shift_1 - shift_2)/shift_1
def annual_returns(price):
price = price.to_numpy()
start = price[0]
end = price[len(price)-1]
return (end-start)/start
def adjusting(price):
adj = len(price)
diff = adj - adjvalue
if diff != 0:
price_new = price[:-diff]
else: price_new = price
return price_new
#Minimal Reproducible Example
#getting user input
names = input('Stock codes:')
names = names.split()
a = len(names)
msft = yf.Ticker(names[0])
aapl = yf.Ticker(names[1])
#import data
hist_msft = msft.history(interval='1d',start='2020-01-01',end='2020-12-31')
hist_msft = pd.DataFrame(hist_msft,columns=['Close'])
#hist_msft = hist_msft.to_numpy()
hist_aapl = aapl.history(interval='1d',start='2020-01-01',end='2020-12-31')
hist_aapl = pd.DataFrame(hist_aapl,columns=['Close'])
#hist_aapl = hist_aapl.to_numpy()
#daily returns
aapl_daily_returns = daily_returns(hist_aapl)
aapl_daily_returns = np.ravel(aapl_daily_returns)
msft_daily_returns = daily_returns(hist_msft)
msft_daily_returns = np.ravel(msft_daily_returns)
#adjusting for different trading periods
adjvalue = min(len(aapl_daily_returns),len(msft_daily_returns))
aapl_adj = adjusting(aapl_daily_returns)
msft_adj = adjusting(msft_daily_returns)
#annual returns
aapl_ann_returns = annual_returns(hist_aapl)
msft_ann_returns = annual_returns(hist_msft)
#inputs for optimization
cov_mat = np.cov([aapl_adj,msft_adj])*252
ann_returns = np.concatenate((aapl_ann_returns,msft_ann_returns))
Now I just want the code to work with a various, unknown number of inputs. I tried reading a lot about global variables or tried to figure it out with dictionaries but couldn't really achieve any progress.
I think using the for loop can solve your problem!
...
names = input('Stock codes:')
names = names.split()
for name in names:
#analyze here
#I don't know anything about stocks so I wont write anything here
...
I am running this code and oddly, nothing happens. There is no error nor does it freeze. It simply just runs the code without storing variables, nothing is printed out and it doesn't open the window that is supposed to show the plot. So it simply does nothing. It is very odd. This worked only a few minutes ago and I did not change anything about it previously. I did make sure that the variable explorer is displaying all the definitions in the script. I intentionally removed the plotting section at the end since it just made the code set longer and the same issue persists here without it.
Code:
#Import libraries
import numpy as np
from scipy.integrate import odeint
#from scipy.integrate import solve_ivp
from time import time
import matplotlib.pyplot as plt
from matplotlib.pyplot import grid
from mpl_toolkits.mplot3d import Axes3D
import numpy, scipy.io
from matplotlib.patches import Circle
'''
import sympy as sy
import random as rand
from scipy import interpolate
'''
'''
Initiate Timer
'''
TimeStart = time()
'''
#User defined inputs
'''
TStep = (17.8E-13)
TFinal = (17.8E-10)
R0 = 0.02
V0X = 1E7
ParticleCount = 1 #No. of particles to generate energies for energy generation
BInput = 0.64 #Magnitude of B field near pole of magnet in experiment
ScaleV0Z = 1
'''
#Defining constants based on user input and nature (Cleared of all errors!)
'''
#Defining Space and Particle Density based on Pressure PV = NkT
k = 1.38E-23 #Boltzman Constant
#Natural Constants
Q_e = -1.602E-19 #Charge of electron
M_e = 9.11E-31 #Mass of electron
JToEv = 6.24E+18 #Joules to eV conversion
EpNaut = 8.854187E-12
u0 = 1.256E-6
k = 1/(4*np.pi*EpNaut)
QeMe = Q_e/M_e
'''
Create zeros matrices to populate later (Cannot create TimeIndex array!)
'''
TimeSpan = np.linspace(0,TFinal,num=round((TFinal/TStep)))
TimeIndex = np.linspace(0,TimeSpan.size,num=TimeSpan.size)
ParticleTrajectoryMat = np.zeros([91,TimeSpan.size,6])
BFieldTracking = np.zeros([TimeSpan.size,3])
InputAngle = np.array([np.linspace(0,90,91)])
OutputAngle = np.zeros([InputAngle.size,1])
OutputRadial = np.zeros([InputAngle.size,1])
'''
Define B-Field
'''
def BField(x,y,z):
InputCoord = np.array([x,y,z])
VolMag = 3.218E-6 #Volume of magnet in experiment in m^3
BR = np.sqrt(InputCoord[0]**2 + InputCoord[1]**2 + InputCoord[2]**2)
MagMoment = np.array([0,0,(BInput*VolMag)/u0])
BDipole = (u0/(4*np.pi))*(((3*InputCoord*np.dot(MagMoment,InputCoord))/BR**5)-(MagMoment/BR**3))
#BVec = np.array([BDipole[0],BDipole[1],BDipole[2]])
#print(BDipole[0],BDipole[1],BDipole[2])
return (BDipole[0],BDipole[1],BDipole[2])
'''
Lorentz Force Differential Equations Definition
'''
def LorentzForce(PosVel,t,Constants):
X,Y,Z,VX,VY,VZ = PosVel
Bx,By,Bz,QeMe = Constants
BFInput = np.array([Bx,By,Bz])
VelInput = np.array([VX,VY,VZ])
Accel = QeMe * (np.cross(VelInput, BFInput))
LFEqs = np.concatenate((VelInput, Accel), axis = 0)
return LFEqs
'''
Cartesean to Spherical coordinates converter function. Returns: [Radius (m), Theta (rad), Phi (rad)]
'''
def Cart2Sphere(xIn,yIn,zIn):
P = np.sqrt(xIn**2 + yIn**2 + zIn**2)
if xIn == 0:
Theta = np.pi/2
else:
Theta = np.arctan(yIn/xIn)
Phi = np.arccos(zIn/np.sqrt(xIn**2 + yIn**2 + zIn**2))
SphereVector = np.array([P,Theta,Phi])
return SphereVector
'''
Main Loop
'''
for angletrack in range(0,InputAngle.size):
MirrorAngle = InputAngle[0,angletrack]
MirrorAngleRad = MirrorAngle*(np.pi/180)
V0Z = np.abs(V0X/np.sin(MirrorAngleRad))*np.sqrt(1-(np.sin(MirrorAngleRad))**2)
V0Z = V0Z*ScaleV0Z
#Define initial conditions
V0 = np.array([[V0X,0,V0Z]])
S0 = np.array([[0,R0,0]])
ParticleTrajectoryMat[0,:] = np.concatenate((S0,V0),axis=None)
for timeplace in range(0,TimeIndex.size-1):
ICs = np.concatenate((S0,V0),axis=None)
Bx,By,Bz = BField(S0[0,0],S0[0,1],S0[0,2])
BFieldTracking[timeplace,:] = np.array([Bx,By,Bz])
AllConstantInputs = [Bx,By,Bz,QeMe]
t = np.array([TimeSpan[timeplace],TimeSpan[timeplace+1]])
ODESolution = odeint(LorentzForce,ICs,t,args=(AllConstantInputs,))
ParticleTrajectoryMat[angletrack,timeplace+1,:] = ODESolution[1,:]
S0[0,0:3] = ODESolution[1,0:3]
V0[0,0:3] = ODESolution[1,3:6]
MatSize = np.array([ParticleTrajectoryMat.shape])
RowNum = MatSize[0,1]
SphereMat = np.zeros([RowNum,3])
SphereMatDeg = np.zeros([RowNum,3])
for cart2sphereplace in range(0,RowNum):
SphereMat[cart2sphereplace,:] = Cart2Sphere(ParticleTrajectoryMat[angletrack,cart2sphereplace,0],ParticleTrajectoryMat[angletrack,cart2sphereplace,1],ParticleTrajectoryMat[angletrack,cart2sphereplace,2])
for rad2deg in range(0,RowNum):
SphereMatDeg[rad2deg,:] = np.array([SphereMat[rad2deg,0],(180/np.pi)*SphereMat[rad2deg,1],(180/np.pi)*SphereMat[rad2deg,2]])
PhiDegVec = np.array([SphereMatDeg[:,2]])
RVec = np.array([SphereMatDeg[:,0]])
MinPhi = np.amin(PhiDegVec)
MinPhiLocationTuple = np.where(PhiDegVec == np.amin(PhiDegVec))
MinPhiLocation = int(MinPhiLocationTuple[1])
RAtMinPhi = RVec[0,MinPhiLocation]
OutputAngle[angletrack,0] = MinPhi
OutputRadial[angletrack,0] = RAtMinPhi
print('Mirror Angle Input (In deg): ',InputAngle[0,angletrack])
print('Mirror Angle Output (In deg): ',MinPhi)
print('R Value at minimum Phi (m): ',RAtMinPhi)
InputAngleTrans = np.matrix.transpose(InputAngle)
CompareMat = np.concatenate((InputAngleTrans,OutputAngle),axis=1)
I started to work in the field of computational chemistry and I was ask to do Principal Component Analysis on some trajectory from molecular dynamics. I was told to use MDAnalysis package, thus I find one tutorial on their page a tried to follow it (but I included my own inputs of course) to see if it will be working. I have never done analysis like this ad I am also new to python coding.
I attached my code inspired by tutorial. But it doesnt work for me, it raises many errors, one of the errors is that it cant take my inputs (topology is PDB file, coordinate is XTC file), but those are formats which are listed in supported formats or other error is that "class PCA" is not defined.
I didnt find much about dealing with PCA using MDAanalysis from other people, thus I hoped that here I could find someone, who have ever done something like this and could, please, help me. I have alreadz tried related subreddits, but without result.
from __future__ import division, absolute_import
import MDAnalysis as mda
import MDAnalysis.analysis.pca as pca
from six.moves import range
import warnings
import numpy as np
import scipy.integrate
from MDAnalysis import Universe
from MDAnalysis.analysis.align import _fit_to
from MDAnalysis.lib.log import ProgressMeter
u = mda.Universe("L22trial.pdb", "L22trial.xtc")
PCA = mda.analysis.pca.PCA
class PCA():
pca = PCA(u, select='backbone').run()
pca_space = pca.transform(u.select_atoms('backbone'))
def __init__(self, universe, select='all', align=False, mean=None,
n_components=None, **kwargs):
super(PCA, self).__init__(universe.trajectory, **kwargs)
self._u = universe
self.align = align
self._calculated = False
self.n_components = n_components
self._select = select
self._mean = mean
def _prepare(self):
self._u.trajectory[self.start]
self._reference = self._u.select_atoms(self._select)
self._atoms = self._u.select_atoms(self._select)
self._n_atoms = self._atoms.n_atoms
if self._mean is None:
self.mean = np.zeros(self._n_atoms*3)
self._calc_mean = True
else:
self.mean = self._mean.positions
self._calc_mean = False
if self.n_frames == 1:
raise ValueError('No covariance information can be gathered from a single trajectory frame.\n')
n_dim = self._n_atoms * 3
self.cov = np.zeros((n_dim, n_dim))
self._ref_atom_positions = self._reference.positions
self._ref_cog = self._reference.center_of_geometry()
self._ref_atom_positions -= self._ref_cog
if self._calc_mean:
interval = int(self.n_frames // 100)
interval = interval if interval > 0 else 1
format = ("Mean Calculation Step %(step)5d/%(numsteps)d [%(percentage)5.1f%%]")
mean_pm = ProgressMeter(self.n_frames if self.n_frames else 1, interval=interval, verbose=self._verbose, format=format)
for i, ts in enumerate(self._u.trajectory[self.start:self.stop:self.step]):
if self.align:
mobile_cog = self._atoms.center_of_geometry()
mobile_atoms, old_rmsd = _fit_to(self._atoms.positions, self._ref_atom_positions, self._atoms, mobile_com=mobile_cog, ref_com=self._ref_cog)
else:
self.mean += self._atoms.positions.ravel()
mean_pm.echo(i)
self.mean /= self.n_frames
self.mean_atoms = self._atoms
self.mean_atoms.positions = self._atoms.positions
def _single_frame(self):
if self.align:
mobile_cog = self._atoms.center_of_geometry()
mobile_atoms, old_rmsd = _fit_to(self._atoms.positions, self._ref_atom_positions, self._atoms, mobile_com=mobile_cog, ref_com=self._ref_cog)
x = mobile_atoms.positions.ravel()
else:
x = self._atoms.positions.ravel()
x -= self.mean
self.cov += np.dot(x[:, np.newaxis], x[:, np.newaxis].T)
def _conclude(self):
self.cov /= self.n_frames - 1
e_vals, e_vects = np.linalg.eig(self.cov)
sort_idx = np.argsort(e_vals)[::-1]
self.variance = e_vals[sort_idx]
self.variance = self.variance[:self.n_components]
self.p_components = e_vects[:self.n_components, sort_idx]
self.cumulated_variance = (np.cumsum(self.variance) / np.sum(self.variance))
self._calculated = True
def transform(self, atomgroup, n_components=None, start=None, stop=None, step=None):
if not self._calculated:
raise ValueError('Call run() on the PCA before using transform')
if isinstance(atomgroup, Universe):
atomgroup = atomgroup.atoms
if(self._n_atoms != atomgroup.n_atoms):
raise ValueError('PCA has been fit for {} atoms. Your atomgroup has {} atoms'.format(self._n_atoms, atomgroup.n_atoms))
if not (self._atoms.types == atomgroup.types).all():
warnings.warn('Atom types do not match with types used to fit PCA')
traj = atomgroup.universe.trajectory
start, stop, step = traj.check_slice_indices(start, stop, step)
n_frames = len(range(start, stop, step))
dim = (n_components if n_components is not None else self.p_components.shape[1])
dot = np.zeros((n_frames, dim))
for i, ts in enumerate(traj[start:stop:step]):
xyz = atomgroup.positions.ravel() - self.mean
dot[i] = np.dot(xyz, self.p_components[:, :n_components])
return dot
def cosine_content(pca_space, i):
t = np.arange(len(pca_space))
T = len(pca_space)
cos = np.cos(np.pi * t * (i + 1) / T)
return ((2.0 / T) * (scipy.integrate.simps(cos*pca_space[:, i])) ** 2 /
scipy.integrate.simps(pca_space[:, i] ** 2))
it seems you copied and pasted the PCA class itsefl. My guess is that you don't need to do this (I have never used that module so it s just a guess).
The documentation ( https://www.mdanalysis.org/docs/documentation_pages/analysis/pca.html ) seems to indicate the only thing you need to do is the following
import MDAnalysis as mda
import MDAnalysis.analysis.pca as pca
u = mda.Universe("L22trial.pdb", "L22trial.xtc")
mypca = pca.PCA(u, select='backbone').run()
pca_space = mypca.transform(u.select_atoms('backbone'))
If you have an error message "No module named 'MDAnalysis.analysis.pca.PCA'; 'MDAnalysis.analysis.pca' is not a package" it means what it says :-).
That means there is no package on your computer named MDAnalysis. to fix this you need to install using pip install command or conda if you use conda package manager. See this link https://www.mdanalysis.org/pages/installation_quick_start/
Looking at the link https://www.mdanalysis.org/docs/_modules/MDAnalysis/analysis/pca.html from which you got inspired it confirmed my first guess and I think my answer should allow you using that package.
I try to read the World Coordinate System (WCS) from a FITS file using satrapy and this code:
from astropy.wcs import WCS
from astropy.io import fits
data = 'file.fits'
hdu = fits.open(data)
w = WCS(hdu[0].header)
I get the error:
WARNING: FITSFixedWarning: RADECSYS= 'ICRS '
RADECSYS is non-standard, use RADESYSa. [astropy.wcs.wcs]
The header file is:
SIMPLE = T
BITPIX = -32
NAXIS = 2
NAXIS1 = 2048
NAXIS2 = 1489
RADECSYS= 'ICRS '
CTYPE1 = 'DEC--TAN'
CTYPE2 = 'RA---TAN'
CUNIT1 = 'deg '
CUNIT2 = 'deg '
CRPIX1 = 1.02500000000000E+03
CRPIX2 = 7.45000000000000E+02
CRVAL1 = 7.34210000000000E-01
CRVAL2 = 2.49604300000000E+01
CD1_1 = 1.09999999400000E-04
CD2_2 = 1.09999999400000E-04
CD1_2 = 0.00000000000000E+00
CD2_1 = 0.00000000000000E+00
COADD_0 = 'fpCs-002570-i5-0112.resamp.fits'
COADD_1 = 'fpCs-002570-i5-0113.resamp.fits'
COADD_2 = 'fpCs-002650-i5-0142.resamp.fits'
COADD_3 = 'fpCs-002650-i5-0143.resamp.fits'
COADD_4 = 'fpCs-002677-i5-0142.resamp.fits'
COADD_5 = 'fpCs-002677-i5-0143.resamp.fits'
COADD_6 = 'fpCs-002700-i5-0032.resamp.fits'
COADD_7 = 'fpCs-002700-i5-0033.resamp.fits'
COADD_8 = 'fpCs-002728-i5-0579.resamp.fits'
COADD_9 = 'fpCs-002728-i5-0580.resamp.fits'
COADD_10= 'fpCs-002738-i5-0084.resamp.fits'
COADD_11= 'fpCs-002738-i5-0085.resamp.fits'
COADD_12= 'fpCs-002820-i5-0032.resamp.fits'
COADD_13= 'fpCs-002820-i5-0033.resamp.fits'
COADD_14= 'fpCs-002855-i5-0038.resamp.fits'
COADD_15= 'fpCs-002855-i5-0039.resamp.fits'
COADD_16= 'fpCs-002873-i5-0075.resamp.fits'
COADD_17= 'fpCs-002873-i5-0076.resamp.fits'
COADD_18= 'fpCs-003362-i5-0033.resamp.fits'
COADD_19= 'fpCs-003362-i5-0034.resamp.fits'
COADD_20= 'fpCs-003362-i5-0035.resamp.fits'
COADD_21= 'fpCs-003384-i5-0535.resamp.fits'
COADD_22= 'fpCs-003384-i5-0536.resamp.fits'
COADD_23= 'fpCs-004128-i5-0289.resamp.fits'
COADD_24= 'fpCs-004128-i5-0290.resamp.fits'
COADD_25= 'fpCs-004157-i5-0042.resamp.fits'
COADD_26= 'fpCs-004157-i5-0043.resamp.fits'
COADD_27= 'fpCs-004198-i5-0528.resamp.fits'
COADD_28= 'fpCs-004198-i5-0529.resamp.fits'
COADD_29= 'fpCs-004207-i5-0538.resamp.fits'
COADD_30= 'fpCs-004207-i5-0539.resamp.fits'
COADD_31= 'fpCs-004868-i5-0374.resamp.fits'
COADD_32= 'fpCs-004868-i5-0375.resamp.fits'
COADD_33= 'fpCs-004874-i5-0587.resamp.fits'
COADD_34= 'fpCs-004874-i5-0588.resamp.fits'
COADD_35= 'fpCs-004895-i5-0202.resamp.fits'
COADD_36= 'fpCs-004895-i5-0203.resamp.fits'
COADD_37= 'fpCs-004905-i5-0168.resamp.fits'
COADD_38= 'fpCs-004905-i5-0169.resamp.fits'
COADD_39= 'fpCs-004933-i5-0529.resamp.fits'
COADD_40= 'fpCs-004933-i5-0530.resamp.fits'
COADD_41= 'fpCs-004948-i5-0109.resamp.fits'
COADD_42= 'fpCs-004948-i5-0110.resamp.fits'
COADD_43= 'fpCs-005566-i5-0395.resamp.fits'
COADD_44= 'fpCs-005566-i5-0396.resamp.fits'
COADD_45= 'fpCs-005603-i5-0614.resamp.fits'
COADD_46= 'fpCs-005603-i5-0615.resamp.fits'
COADD_47= 'fpCs-005633-i5-0582.resamp.fits'
COADD_48= 'fpCs-005633-i5-0583.resamp.fits'
COADD_49= 'fpCs-005642-i5-0242.resamp.fits'
COADD_50= 'fpCs-005642-i5-0243.resamp.fits'
COADD_51= 'fpCs-005658-i5-0069.resamp.fits'
COADD_52= 'fpCs-005658-i5-0070.resamp.fits'
COADD_53= 'fpCs-005765-i5-0161.resamp.fits'
COADD_54= 'fpCs-005765-i5-0162.resamp.fits'
COADD_55= 'fpCs-005770-i5-0548.resamp.fits'
COADD_56= 'fpCs-005770-i5-0549.resamp.fits'
COADD_57= 'fpCs-005777-i5-0013.resamp.fits'
COADD_58= 'fpCs-005777-i5-0014.resamp.fits'
COADD_59= 'fpCs-005781-i5-0546.resamp.fits'
COADD_60= 'fpCs-005781-i5-0547.resamp.fits'
COADD_61= 'fpCs-005792-i5-0587.resamp.fits'
COADD_62= 'fpCs-005792-i5-0588.resamp.fits'
COADD_63= 'fpCs-005792-i5-0589.resamp.fits'
COADD_64= 'fpCs-005800-i5-0568.resamp.fits'
COADD_65= 'fpCs-005800-i5-0569.resamp.fits'
COADD_66= 'fpCs-005813-i5-0605.resamp.fits'
COADD_67= 'fpCs-005813-i5-0606.resamp.fits'
COADD_68= 'fpCs-005823-i5-0572.resamp.fits'
COADD_69= 'fpCs-005823-i5-0573.resamp.fits'
COADD_70= 'fpCs-005898-i5-0610.resamp.fits'
COADD_71= 'fpCs-005898-i5-0611.resamp.fits'
COADD_72= 'fpCs-005918-i5-0587.resamp.fits'
COADD_73= 'fpCs-005918-i5-0588.resamp.fits'
I have compared this to other WCS in header files and it does look different, but I am sure how to fix things. Also I am unsure how to use RADESYSa rather then RADECSYS. There does not seem to be any documentation that I can find. Any help would be appreciated.
The issue is that the keyword header should be RADESYS not RADECSYS according to the FITS standard (please report this to the people who made this FITS file). To avoid the warning, you can do:
from astropy.wcs import WCS
from astropy.io import fits
data = 'file.fits'
hdu = fits.open(data)
hdu[0].header.rename_keyword('RADECSYS', 'RADESYS')
w = WCS(hdu[0].header)
I am creating my own .obj exporter for maya.
When i'm exporting just one mesh my code works just fine but when exporting several meshes / objects it fails to create the complete meshes.
I'm pretty sure that the problem is when i'm getting the
face.getVertices(), face.getUVIndex() and face.normalIndex() and printing them to the file. As i said the first mesh works fine but when it gets to the second mesh the codinates gets all wrong, they connect to the wrong triangles.
If anyone has any ideas on how to possibly loop them differently or change the values to the correct ones i would be forever greatful. Help would be very very appreciated!
Here is an example on how a multi object mesh ends out.
http://postimg.org/image/rr0fvs0v7/
import pymel.core as pm
import pymel.core.nodetypes as nt
planes = pm.ls(sl=True)
def meshFile():
def myRound(n):
return round(n, 6)
file = open("C:/Users/Blondiegirls/Desktop/test2.obj", "wb")
file.write("mtllib test2.mtl\r\n")
for p in planes[:]:
#pm.polyTriangulate(planes[0])
file.write("\r\ng default")
# Printa world kordinater
for index, point in enumerate(p.vtx):
temp = index,map(myRound, point.getPosition(space='world'))
file.write("\r\nv ")
file.write(str(' '.join(map(str, temp[1]))))
# Printa texture kordinater
mesh = pm.ls(g=True)[0]
U,V = mesh.getUVs()
UVs = zip(U,V)
for uv in UVs:
file.write("\r\nvt ")
file.write(str(uv[0])+" "+str(uv[1]))
#printa normals
for n in p.getNormals():
file.write("\r\nvn ")
file.write(str(n[0])+" "+str(n[1])+" "+str(n[2]))
file.write("\r\ns 1")
file.write("\r\ng ")
file.write(str(p))
file.write("\r\nusemtl test")
for faceIndex, face in enumerate(p.faces):
faceVertices = face.getVertices()
faceUV0 = face.getUVIndex(0)+1
faceUV1 = face.getUVIndex(1)+1
faceUV2 = face.getUVIndex(2)+1
faceNor0 = face.normalIndex(0)+1
faceNor1 = face.normalIndex(1)+1
faceNor2 = face.normalIndex(2)+1
file.write("\r\nf ")
faceVertices0 = int(faceVertices[0])+1
faceVertices1 = int(faceVertices[1])+1
faceVertices2 = int(faceVertices[2])+1
temp3 = (str(faceVertices0)) + "/" + (str(faceUV0)) +"/" + (str(faceNor0)) + " " + (str(faceVertices1)) + "/" + (str(faceUV1)) +"/" + (str(faceNor1)) + " " + (str(faceVertices2)) + "/" + (str(faceUV2)) +"/" + (str(faceNor2))
file.write(str(temp3))
file.close()
meshFile()
def MTLFile():
file2 = open("C:/Users/Blondiegirls/Desktop/test2.mtl", "wb")
object = cmds.ls(sl=1)[0].split(':')[0]
#print('object: '+object)
shipTX = pm.PyNode(object)
shadingGroups = shipTX.shadingGroups()
sg1 = shadingGroups[0]
material = sg1.listConnections(source=True, destination=False, type=nt.Lambert)[0]
file = material.color.listConnections(type=nt.File)[0]
filename = file.fileTextureName.get()
materialColor = material.getColor() #for Kd
materialAmbient = material.getAmbientColor() #for Ka
materialSpecular = material.getSpecularColor() #for Ks
refractiveIndex = material.getRefractiveIndex() #for Ni
file2.write("newmtl "+"test"+"\r\n")
file2.write("Ka "+str(materialAmbient[0])+" "+str(materialAmbient[1])+" "+str(materialAmbient[2])+"\r\n")
file2.write("Kd "+str(materialColor[0])+" "+str(materialColor[1])+" "+str(materialColor[2])+"\r\n")
file2.write("Ks "+str(materialSpecular[0])+" "+str(materialSpecular[1])+" "+str(materialSpecular[2])+"\r\n")
file2.write("d 1.0\r\n")
file2.write("Illum 2\r\n")
file2.write("map_Kd "+filename+"\r\n") #for map_Kd
file2.close()
MTLFile()
The problem is this line:
mesh = pm.ls(g=True)[0]
U,V = mesh.getUVs()
This is querying all of the geometry in the scene and returning the first object, but you should be operating on the current mesh in the iteration. I think what you want is:
U,V = p.getUVs()
Also, you should probably consider adding an argument to meshFile() rather than relying on a variable in the global scope.