# How can I convert coordinates from global to local CS in Mechanical? Member, Moderator, Employee Posts: 87    When I select an entity in Mechanical, I can choose a coordinate system to display coordinates in the selection information. Is there a way to do it by script?

Tagged:

• Member, Moderator, Employee Posts: 87    edited November 16

Here's an example for converting coordinates to a local coordinate system. Pay attention to proper unit conversions. The example works on cartesian coordinate systems and would require little work to apply to cylindrical CS as well.

```def convertToCS(coords,cs_name,convert=True):
# Converts coordinates to a given coordinate system
# If convert=True, 'coords' is assumed to be in users unit
# If convert=False, 'coords' must be in meters
import units

# Retrieve conversion factor from current length unit to meters
toUnit = "m" # Always generate the result to display in SI unit
fromUnit=ExtAPI.DataModel.AnalysisList.CurrentConsistentUnitFromQuantityName("Length")
convFact = units.ConvertUnit(1, fromUnit, toUnit, "Length")

# Retrieve axis from coordinate system
# Assume cs_name is unique (if not, the first one will be used)
csM = ExtAPI.DataModel.GetObjectsByName(cs_name)
csXAxis = csM.XAxis
csYAxis = csM.YAxis
csZAxis = csM.ZAxis

# Convert to 3D vectors
xAxis = Vector3D(csXAxis, csXAxis, csXAxis)
yAxis = Vector3D(csYAxis, csYAxis, csYAxis)
zAxis = Vector3D(csZAxis, csZAxis, csZAxis)

# create transformation matrix
# We use a 4x4 matrix with rotation and translations
idM  =  Matrix4D()
transM = idM.CreateSystem(xAxis,yAxis,zAxis)
# Transpose to ensure proper transformation from global to local
transM.Transpose()

# Translation part of the transformation matrix
origin=csM.Origin # Origin will be in user units, so convert to m
origin_transfd=transM.Transform(Vector3D(origin,origin,origin))

for i in range(0,3):
transM[12+i]=-origin_transfd[i]

# Now convert point to new CS
# First convert to meters if needed
if convert:
vec=Vector3D(coords*convFact, coords*convFact, coords*convFact)
else:
vec=Vector3D(coords, coords, coords)

# Rotate
vec_transfd=transM.Transform(vec)

# Return new coordinates in user units
if convert:
invFact=1/convFact
return [vec_transfd*invFact,vec_transfd*invFact,vec_transfd*invFact]
else:
return [vec_transfd,vec_transfd,vec_transfd]

# Test function on current selection's centroid
cursel=ExtAPI.SelectionManager.CurrentSelection
# using convert=False in function call as Centroid is always in meters
print(convertToCS(cursel.Entities.Centroid,'myCS',False))
```
• Member, Employee Posts: 123    Here are some similarly useful functions.