コード例 #1
0
def findOutputSet(ModelName, StepName, InstanceName, SetName, Output='COORD'):
    output = []
    time = []
    odbName = ModelName + '.odb'

    odb = visualization.openOdb(odbName)
    for i in range(len(odb.steps[StepName].frames)):
        output_frame = []
        lastFrame = odb.steps[StepName].frames[i]
        print(i, lastFrame.frameValue)
        time.append(lastFrame.frameValue)
        coordset = odb.rootAssembly.instances[InstanceName.upper()].nodeSets[
            SetName.upper()]

        # Retrieve Y-displacements at the splines/connectors
        dispField = lastFrame.fieldOutputs[Output]

        dFieldpTip = dispField.getSubset(region=coordset)

        for i in range(len(dFieldpTip.values)):
            output_frame.append(dFieldpTip.values[i].data)
        output.append(output_frame)
    odb.close()

    return np.array(output), np.array(time)
コード例 #2
0
def get_displacement(odbName, StepName, components=[2]):
    """
    This ODB reading script does the following:
    -Retrieves the displacement at TIPNODE
    """

    # Open the output database.
    print 'Made it in'
    #    odbName = ModelName+'.odb'
    #    print odbName
    odb = visualization.openOdb(odbName)
    lastFrame = odb.steps[StepName].frames[-1]
    print 'odb open'

    # Selecting the node(s) to be queried
    pTip = odb.rootAssembly.nodeSets['TIPNODE']

    # Retrieve Y-displacements at the splines/connectors
    print 'Retrieving ALL final displacements at ALL points'
    dispField = lastFrame.fieldOutputs['U']

    print 'Retrieving ALL displacements at TIPNODE'
    dFieldpTip = dispField.getSubset(region=pTip)

    print 'Retrieving only U2 at TIPNODE'
    #Note, U1=data[0], U2=data[1], U3=data[2]
    disppTip = []
    for component in components:
        disppTip.append(dFieldpTip.values[0].data[component - 1])
    odb.close()
    if len(disppTip) == 1:
        return disppTip[0]
    else:
        return disppTip
コード例 #3
0
def find_stress(ModelName,elsetName):
	# Open the output database.
	print 'Made it in'
	odbName = ModelName+'.odb'
	print odbName
	odb = visualization.openOdb(odbName)
	lastFrame = odb.steps['RBM'].frames[-1]
	#elsetName='ALL_PART'
	elset = elemset = None
	region = "over the entire model"
	assembly = odb.rootAssembly

	#Check to see if the element set exists
	#in the assembly

	if elsetName:
	   try:
		   elemset = assembly.elementSets[elsetName]
		   region = " in the element set : " + elsetName;
	   except KeyError:
		   print 'An assembly level elset named %s does' \
				  'not exist in the output database %s' \
				  % (elsetName, odbName)
		   odb.close()
		   exit(0)
		   
	""" Initialize maximum values """
	maxMises = -0.1
	maxVMElem = 0
	maxStep = "_None_"
	maxFrame = -1
	Stress = 'S'
	isStressPresent = 0
	for step in odb.steps.values():
	   print 'Processing Step:', step.name
	   for frame in step.frames:
		   allFields = frame.fieldOutputs
		   if (allFields.has_key(Stress)):
			   isStressPresent = 1
			   stressSet = allFields[Stress]
			   if elemset:
				   stressSet = stressSet.getSubset(
					   region=elemset)      
			   for stressValue in stressSet.values:                
				   if (stressValue.mises > maxMises):
					   maxMises = stressValue.mises
					   maxVMElem = stressValue.elementLabel
					   maxStep = step.name
					   maxFrame = frame.incrementNumber
	if(isStressPresent):
	   print 'Maximum von Mises stress %s is %f in element %d'%(
		   region, maxMises, maxVMElem)
	   print 'Location: frame # %d  step:  %s '%(maxFrame,maxStep)
	else:
	   print 'Stress output is not available in' \
			 'the output database : %s\n' %(odb.name)  		
        odb.close()
        return maxMises		
コード例 #4
0
def dealResult(jobName, messageType, data, userData):
    import winsound
    import visualization
    if ((messageType==JOB_ABORTED) or (messageType==JOB_SUBMITTED)):
        winsound.PlaySound("SystemQuestion", winsound.SND_ALIAS)
    elif (messageType==JOB_COMPLETED):
        winsound.PlaySound("SystemExclamation", winsound.SND_ALIAS)
        odb = visualization.openOdb(path=jobName + '.odb')
        userData.setValues(displayedObject=odb)
        userData.odbDisplay.display.setValues(plotState=CONTOURS_ON_DEF)
コード例 #5
0
def getResults2(ModelName):
    disppTip = [[0 for y in range(3)] for x in range(10000)]
    disppTip2 = [[0 for y in range(3)] for x in range(10000)]
    """
	This ODB reading script does the following:
	-Retrieves the displacement at TIPNODE
	-Scans for max. Mises stress in a part (if set exists)
	"""

    # Open the output database.
    print 'Made it in'
    odbName = ModelName + '.odb'
    print odbName
    odb = visualization.openOdb(odbName)
    lastFrame = odb.steps['RBM'].frames[-1]
    firstFrame = odb.steps['RBM'].frames[0]
    print 'odb open'

    # Selecting the node(s) to be queried
    pTip = odb.rootAssembly.nodeSets['TIPNODE']
    dtm = odb.rootAssembly.datumCsyses['Datum_Aero_Data']
    session.viewports['Viewport: 1'].odbDisplay.basicOptions.setValues(
        transformationType=USER_SPECIFIED, datumCsys=dtm)
    # Retrieve Y-displacements at the splines/connectors
    print 'Retrieving ALL final displacements at ALL points'
    dispField = firstFrame.fieldOutputs['COORD']
    dispField2 = lastFrame.fieldOutputs['COORD']
    print 'Retrieving ALL displacements at TIPNODE'
    dFieldpTip = dispField.getSubset(region=pTip)
    dFieldpTip2 = dispField2.getSubset(region=pTip)
    print 'Retrieving only U2 at TIPNODE'
    #Note, U1=data[0], U2=data[1], U3=data[2]
    nnodes = len(dFieldpTip.values)
    for i in range(nnodes):
        disppTip[i][0] = dFieldpTip.values[i].data[0]
        disppTip[i][1] = dFieldpTip.values[i].data[1]
        disppTip[i][2] = dFieldpTip.values[i].data[2]
        disppTip2[i][0] = dFieldpTip2.values[i].data[0]
        disppTip2[i][1] = dFieldpTip2.values[i].data[1]
        disppTip2[i][2] = dFieldpTip2.values[i].data[2]
        #The following is left for use in later probems/projects
    odb.close()
    disppTip = np.array(disppTip)
    disppTip2 = np.array(disppTip2)
    disppTip = disppTip[~np.all(disppTip == 0, axis=1)]
    disppTip2 = disppTip2[~np.all(disppTip2 == 0, axis=1)]
    np.savetxt("initial.txt", disppTip, delimiter=",")
    np.savetxt("final.txt", disppTip2, delimiter=",")
    return disppTip, disppTip2
コード例 #6
0
def get_coordinates_linear(ModelName, StepName, InstanceName, SetName):
    """
    This ODB reading script does the following:
    -Retrieves the coordinates at SetName for a LINEAR ANALYSIS
	
	DO NOT USE THIS WHEN NLGEOM IS ON! IT WILL DOUBLE DIP!
    """
    Coordinates = {'x': [], 'y': []}
    # Open the output database.
    print 'Made it in'
    odbName = ModelName + '.odb'
    #    print odbName
    odb = visualization.openOdb(odbName)
    lastFrame = odb.steps[StepName].frames[-1]
    print 'odb open'

    # Selecting the node(s) to be queried
    coordset = odb.rootAssembly.instances[InstanceName.upper()].nodeSets[
        SetName.upper()]

    # Retrieve Y-displacements at the splines/connectors
    print 'Retrieving ALL final displacements at ALL points'
    dispField = lastFrame.fieldOutputs['U']

    print 'Retrieving ALL displacements at TIPNODE'
    dFieldpTip = dispField.getSubset(region=coordset)

    print 'Retrieving ALL final displacements at ALL points'
    coordField = lastFrame.fieldOutputs['COORD']

    print 'Retrieving ALL displacements at Set'
    cFieldpTip = coordField.getSubset(region=coordset)

    print 'Retrieving coordinates at sets at Set'
    #Note, U1=data[0], U2=data[1], U3=data[2]
    for i in range(len(dFieldpTip.values)):
        Coordinates['x'].append(cFieldpTip.values[i].data[0] +
                                dFieldpTip.values[i].data[0])
        Coordinates['y'].append(cFieldpTip.values[i].data[1] +
                                dFieldpTip.values[i].data[1])
    odb.close()
    return Coordinates
コード例 #7
0
def vizuMyJob(odbName):
    from abaqus import session
    from abaqusConstants import FILLED,DEFORMED,CONTOURS_ON_DEF,SYMBOLS_ON_DEF,INTEGRATION_POINT,INVARIANT,RESULTANT,UNIFORM,ON
    # Create a new viewport in which to display the model and the results of the analysis.
    myViewport = session.Viewport(name='session viewport', origin=(0, 0), width=300, height=190)  
    # Open the output database and display a contour plot.
    import visualization
    myOdb = visualization.openOdb(path=odbName + '.odb')
    myViewport.setValues(displayedObject=myOdb)
    myViewport.graphicsOptions.setValues(backgroundStyle=GRADIENT)
    myViewport.graphicsOptions.setValues(backgroundBottomColor='#B9C9E1', backgroundOverride=OFF)
    myViewport.graphicsOptions.setValues(backgroundBottomColor='#ECECEC')
    myOdbDisplay = myViewport.odbDisplay
    myOdbDisplay.commonOptions.setValues(renderStyle=FILLED)
    myOdbDisplay.display.setValues(plotState=(DEFORMED, CONTOURS_ON_DEF, SYMBOLS_ON_DEF, ))
    myOdbDisplay.setPrimaryVariable(variableLabel='S',  outputPosition=INTEGRATION_POINT, refinement=(INVARIANT, 'Mises'), )
    if 'FibresIn'  in odbName or 'WithFiberDirection' in odbName:
        myOdbDisplay.setSymbolVariable(variableLabel='LOCALDIR1', outputPosition=INTEGRATION_POINT,  vectorQuantity=RESULTANT, )
        myOdbDisplay.symbolOptions.setValues(vectorColor='White', vectorColorMethod=UNIFORM, symbolDensity=0.9)
        myOdbDisplay.commonOptions.setValues(translucency=ON,translucencyFactor=0.45)
コード例 #8
0
from abaqus import *
from abaqusConstants import *
import visualization as vis

# 创建窗口视图, 通过Viewport函数, 名称(name)
myViewport = session.Viewport(name='Superposition example',origin=(10,10),width=100,height=100)
# 打开已经存在的odb结果文件, 通过path指定odb文件
myOdb = vis.openOdb(path='C:\\Users\\ZhangC\\test.odb')
# 在当前视图窗口显示结果对象, 设置默认的plot对象
myViewport.setValues(displayedObject=myOdb)
# 创建一个载荷步对象
firstStep = myOdb.steps['Step-1']
# 创建两个帧对象, -1表示最后一帧
frame1 = firstStep.frames[-1]
frame2 = firstStep.frames[-5]
# 选取两个载荷步最后一帧的位移场
dis1 = frame1.fieldOutputs['U']
dis2 = frame2.fieldOutputs['U']
# 选取两个载荷步最后一帧的应力场
stress1 = frame1.fieldOutputs['S']
stress2 = frame2.fieldOutputs['S']
# 创建新的输出场
deltaDis = dis1 - dis2
deltaStress = stress1 - stress2
# 设置形状变形, 依据新的位移场, Abaqus通过这个变量来显示变形形状
myViewport.odbDisplay.setDeformedVariable(deltaDis)
# 创建新的应力场云图, 场数据是新的应力场, 输出位置是积分点, 显示其中的Mises应力
myViewport.odbDisplay.setPrimaryVariable(field = deltaStress, outputPosition=INTEGRATION_POINT, refinement = (INVARIANT,'Mises'))
# 显示新的Mises云图, 并且在变形后的图形上显示
myViewport.odbDisplay.display.setValues(plotState=(CONTOURS_ON_DEF,))
コード例 #9
0
def CalculateMetrics(fileName, componentList, reqMetricSet):
    gLogger.info('\n\n~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~')
    gLogger.info('FUNCTION: CalculateMetrics\n')
    global gStructuralMetricTypes
    global gThermalMetricTypes

    odbFileName = fileName + '.odb'
    myOdb = visualization.openOdb(path=odbFileName)

    maxShear = 0
    maxBearing = 0
    maxMises = 0
    maxTemp = -10**9
    minTemp = 10**9

    mainDir = os.path.join(os.getcwd(), odbName)
    if not os.path.exists(mainDir):
        os.makedirs(mainDir)
    os.chdir(mainDir)

    assembly = myOdb.rootAssembly

    distortedElementIDList = list()

    # get the distorted Element set
    if 'WarnElemDistorted' in assembly.elementSets.keys():
        warnElemDistorted = assembly.elementSets['WarnElemDistorted']
        distortedElementSet = warnElemDistorted.elements
        if len(distortedElementSet) > 0:
            distortedElements = distortedElementSet[0]
            for item in distortedElements:
                distortedElementIDList.append(item.label)

    for component in componentList.values():
        if len(component.Children) > 0:
            continue
        try:  # deck-based
            elemset = assembly.instances['PART-1-1'].elementSets[
                component.ElementID]
        except:  # model-based
            elemset = assembly.instances[component.ElementID]

        distortedStressDict = {}
        noneDistortedStressDict = {}
        for step in myOdb.steps.values():
            lastFrame = step.frames[-1]
            if 'S' in reqMetricSet:
                distortedStressDict, noneDistortedStressDict, maxMises, maxBearing, maxShear = \
                    ProcessStress(lastFrame, elemset, maxMises, maxBearing, maxShear,
                                  distortedStressDict, distortedElementIDList, noneDistortedStressDict)
            if 'TEMP' in reqMetricSet:
                maxTemp, minTemp = ProcessThermal(lastFrame, elemset, maxTemp,
                                                  minTemp)

        if 'S' in reqMetricSet:
            # calculate FactorOfSafety
            try:
                factorOfSafety = float(component.Allowables.
                                       mechanical__strength_tensile) / maxMises
            except ZeroDivisionError:
                factorOfSafety = 0.0

            shearQuality = bearQuality = miseQuality = 1
            if len(distortedStressDict) > 0:
                shearQuality, bearQuality, miseQuality = ProcessDistorted(
                    distortedStressDict, (maxMises, maxBearing, maxShear))

            shearRange, bearRange, miseRange, outRangeIDs = EvaluateStressGradient(
                noneDistortedStressDict)
            component.OutOfRangeDistorted = outRangeIDs
            UpdateComponentStressMetrics(componentList, component, maxMises,
                                         maxShear, maxBearing, factorOfSafety,
                                         shearQuality, bearQuality,
                                         miseQuality, shearRange, bearRange,
                                         miseRange)
        if 'TEMP' in reqMetricSet:
            UpdateComponentThermalMetrics(componentList, component, maxTemp,
                                          minTemp)

        #end for

    gLogger.info('\n~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\n')
    SetupViewportPNG(myOdb, fileName, reqMetricSet)
    myOdb.close()  # close odb
    os.chdir('..')  # bring you back to /Analysis/Abaqus
コード例 #10
0
def CalculateMetrics(fileName, componentList):
    gLogger.info('\n\n~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~')
    gLogger.info('FUNCTION: CalculateMetrics\n')
    #global gComponentList
    #global gQualityLookup
    
    odbFileName=fileName + '.odb'
    myOdb = visualization.openOdb(path=odbFileName)

    maxShear = 0
    maxBearing = 0
    maxMises = 0
    minFOS = 0    
    lowYieldRange = 0
    upperYieldRange = 0

    stress = 'S'
    displacement = 'U'

    assembly = myOdb.rootAssembly

    distortedElementIDList = list()

    # get the distorted Element set
    distortedElements = None
    if 'WarnElemDistorted' in assembly.elementSets.keys():
        warnElemDistorted = assembly.elementSets['WarnElemDistorted']
        distortedElementSet = warnElemDistorted.elements
        if (len(distortedElementSet) > 0):
            distortedElements = distortedElementSet[0]
            for item in distortedElements:
                distortedElementIDList.append(item.label)
        

    # Shows how to print key()
    #elemset = assembly.elementSets.keys()
    #for item in elemset:
    #    Write2Log(str(item) +'\n')  

    for component in componentList.values():
        elemset = assembly.instances['PART-1-1'].elementSets[component.ElementID]
        distortedStressDict = {}        # empty dict

        noneDistortedStressDict = {}    # empty dict

        for step in myOdb.steps.values():
            lastFrame = step.frames[-1]
            stressFields = lastFrame.fieldOutputs[stress]
            elementStressSet = stressFields.getSubset(region=elemset)
            for stressValue in elementStressSet.values:
                elementLabel = stressValue.elementLabel
                if elementLabel not in distortedElementIDList:
                    if (stressValue.mises > maxMises):
                        maxMises = stressValue.mises
                    if (stressValue.press > maxBearing):
                        maxBearing = stressValue.press
                    if (stressValue.tresca > maxShear):
                        maxShear = stressValue.tresca

                    if elementLabel not in noneDistortedStressDict:
                        noneDistortedStressDict[elementLabel] = dict()
                        noneDistortedStressDict[elementLabel]['Shear'] = list()
                        noneDistortedStressDict[elementLabel]['Mises'] = list()
                        noneDistortedStressDict[elementLabel]['Bearing'] = list()

                    noneDistortedStressDict[elementLabel]['Shear'].append(stressValue.tresca)
                    noneDistortedStressDict[elementLabel]['Mises'].append(stressValue.mises)
                    noneDistortedStressDict[elementLabel]['Bearing'].append(stressValue.press)
                    
                else:
                    #Write2Log('Distorted[' + str(elementLabel) + ']:		' + str(stressValue.tresca) + '		' + str(stressValue.mises) + '		' + str(stressValue.press))
                    if elementLabel not in distortedStressDict:
                        distortedStressDict[elementLabel] = dict()
                        distortedStressDict[elementLabel]['Shear'] = list()
                        distortedStressDict[elementLabel]['Mises'] = list()
                        distortedStressDict[elementLabel]['Bearing'] = list()

                    distortedStressDict[elementLabel]['Shear'].append(stressValue.tresca)
                    distortedStressDict[elementLabel]['Mises'].append(stressValue.mises)
                    distortedStressDict[elementLabel]['Bearing'].append(stressValue.press)

                    
        # calculate FactorOfSafety
        factorOfSafety = 0
        mShear = float(component.MaterialProperty['Shear'])
        mBear = float(component.MaterialProperty['Bearing'])
        mMises = float(component.MaterialProperty['Mises'])
        #factorOfSafety = min(mShear/maxShear,
        #                     mBear/maxBearing,
        #                     mMises/maxMises)
        factorOfSafety = mMises/maxMises

        if component.MetricsInfo.has_key('Shear'):
            component.MetricsOutput[component.MetricsInfo['Shear']] = maxShear
            #Write2Log('\nMaxMises: ' + str(maxMises))
        if component.MetricsInfo.has_key('Bearing'):
            component.MetricsOutput[component.MetricsInfo['Bearing']] = maxBearing
            #Write2Log('\nMaxBearing: ' + str(maxBearing))
        if component.MetricsInfo.has_key('Mises'):
            component.MetricsOutput[component.MetricsInfo['Mises']] = maxMises
            #Write2Log('\nMaxShear: ' + str(maxShear))
        if component.MetricsInfo.has_key('FactorOfSafety'):
            component.MetricsOutput[component.MetricsInfo['FactorOfSafety']] = factorOfSafety
            #Write2Log('\nFactorOfSafety: ' + str(factorOfSafety))       
        
        shearQuality = bearQuality = miseQuality = 1
        shearRange = bearRange = miseRange = 1
        if (len(distortedStressDict) > 0):
            shearQuality, bearQuality, miseQuality = ProcessDistorted(distortedStressDict, (maxMises, maxBearing, maxShear))

        shearRange, bearRange, miseRange, outRangeIDs = EvaluateStressGradient(noneDistortedStressDict)
        component.OutOfRangeDistorted = outRangeIDs
        
        component.QualityOutput['Shear'] = ComputedMetricsSummary.gQualityLookup[shearQuality]
        component.QualityOutput['Bearing'] = ComputedMetricsSummary.gQualityLookup[bearQuality]
        component.QualityOutput['Mises'] = ComputedMetricsSummary.gQualityLookup[miseQuality]
        component.RangeInfo['Shear'] = ComputedMetricsSummary.gQualityLookup[shearRange]
        component.RangeInfo['Bearing'] = ComputedMetricsSummary.gQualityLookup[bearRange]
        component.RangeInfo['Mises'] = ComputedMetricsSummary.gQualityLookup[miseRange]

        

        #end for

    gLogger.info('\n~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\n')
    CreateViewportPNG(myOdb, fileName)
    
    myOdb.close()           # close odb
コード例 #11
0
ファイル: Post_P.py プロジェクト: walgren/Substructures
def odbPostProcess(jobName, loadFlag):
    ### Obtain Rotation Array
    odbName = jobName + '.odb'
    odb = visualization.openOdb(odbName)
    step = odb.steps['Step-1']

    ## Call for RP-2 Node Set
    nodeSet = odb.rootAssembly.nodeSets['TOP_RP']
    elsetName = 'ALL_PART'
    elset = elemset = None
    region = 'over the entire model'
    assembly = odb.rootAssembly

    i = 0
    frame = step.frames[
        -1]  # we only care about the last frame (snapshot) of data
    forceField = frame.fieldOutputs['RF']  # RF = reaction force
    forceField_nodeSet = forceField.getSubset(region=nodeSet)
    dispField = frame.fieldOutputs['U']  # U = displacement
    dispField_nodeSet = dispField.getSubset(region=nodeSet)
    if loadFlag == 1:  #x-displacement
        performanceMetric = forceField_nodeSet.values[0].data[
            0] / dispField_nodeSet.values[0].data[0]
    elif loadFlag == 2:  #y-displacement
        performanceMetric = forceField_nodeSet.values[0].data[
            1] / dispField_nodeSet.values[0].data[1]
    elif loadFlag == 3:  #z-rotation
        momentField = frame.fieldOutputs['RM']
        momentField_nodeSet = momentField.getSubset(region=nodeSet)
        rotationField = frame.fieldOutputs['UR']
        rotationField_nodeSet = rotationField.getSubset(region=nodeSet)
        performanceMetric = momentField_nodeSet.values[0].data[
            2] / rotationField_nodeSet.values[0].data[2]
        print(rotationField_nodeSet.values[0].data[2],
              momentField_nodeSet.values[0].data[2])

    ## Scan the entire part for max Strain and Stress
    if elsetName:
        try:
            elemset = assembly.elementSets[elsetName]
            region = " in the element set : " + elsetName
        except KeyError:
            print 'An assembly level elset named %s does' \
                   'not exist in the output database %s' \
                   % (elsetName, odbName)
            odb.close()
            exit(0)
    """ Initialize maximum values """
    maxMises = -0.1
    maxVMElem = 0

    Stress = 'S'
    allFields = frame.fieldOutputs
    if (allFields.has_key(Stress)):
        isStressPresent = 1
        stressSet = allFields[Stress]
        if elemset:
            stressSet = stressSet.getSubset(region=elemset)
        bulkData = stressSet.bulkDataBlocks
        maxMises = max(bulkData[0].mises)

    odb.close()

    return performanceMetric, maxMises
コード例 #12
0
observation_points = list(range(0, 231))
del_indices = [0, 21, 42, 63, 84, 105, 126, 147, 168, 188, 210]
observation_points = [
    i for j, i in enumerate(observation_points) if j not in del_indices
]
observation_points = observation_points[0:-1:40]
observation_size = np.size(observation_points)
number_variables = 4
index_variables = [11, 12, 22, 44]

#define the container for the fields outputs
d_U_D = []

#open odb file
odb = ['']
odb[0] = visualization.openOdb('Job-1.odb')
a = odb[0].steps['Step-1'].frames[-1]

#define the gradient name in the odb file
gradient_name_total = []
for int_point in range(number_integration_points):
    for index in range(number_variables):
        tmp = index_variables[index]
        gradient_name = 'd_U_D' + '_' + str(int_point) + '_' + str(tmp)
        gradient_name_total.append(gradient_name)

#access gradient
start = timeit.default_timer()

d_U_D_tmp = [
    a.fieldOutputs[gradient_name].getSubset(position=NODAL).values
コード例 #13
0
myViewport = session.Viewport(name='State Plot',
                              origin=(0, 0),
                              width=250,
                              height=200)
SetContourRange(0, 800, vp='State Plot')

# upgrade odb if required (original simulation executed in older abaq. version)
if isUpgradeRequiredForOdb(odb_path):
    upgradeOdb(odb_path, odb_path + '_')
    shutil.move(odb_path + '_.odb', odb_path)

# Open the output database and associate it with the viewport.
# Then set the plot state to CONTOURS_ON_DEF
try:
    odb = visualization.openOdb(path=odb_path)

except (AbaqusException), e:
    print 'Abaqus Exception:', e

myViewport.setValues(displayedObject=odb)

myViewport.odbDisplay.display.setValues(plotState=(CONTOURS_ON_DEF, ))

# Establish print preferences
session.printOptions.setValues(vpBackground=OFF)
session.psOptions.setValues(orientation=LANDSCAPE)
myViewport.viewportAnnotationOptions.setValues(triad=OFF, title=OFF, state=OFF)
myViewport.odbDisplay.basicOptions.setValues(coordSystemDisplay=OFF, )

# Find the last available Step / Frame
コード例 #14
0
def finite_element_analysis(points,
                            is_planar=CONS["PLANAR_MODE"],
                            print_photo=CONS["PHOTO_MODE"]):
    model_name = "Model" + "_" + str(random.random())[2:]

    # Create a models
    my_model = ABQ.mdb.Model(name=model_name)

    # Create a part
    my_sketch = my_model.ConstrainedSketch(name="Profile", sheetSize=300.0)
    # Create lines by 2 points
    for index in RULES["Lines"]:
        my_sketch.Line(point1=points[index[0] - 1],
                       point2=points[index[1] - 1])
    # Create arcs by 3 points
    for index in RULES["Arcs"]:
        my_sketch.Arc3Points(
            point1=points[index[0] - 1],
            point2=points[index[2] - 1],
            point3=points[index[1] - 1],
        )
    # Create part
    if is_planar:
        my_part = my_model.Part(
            name="FootPart",
            dimensionality=ABC.TWO_D_PLANAR,
            type=ABC.DEFORMABLE_BODY,
        )
        my_part.BaseShell(sketch=my_sketch)
    else:
        my_part = my_model.Part(
            name="FootPart",
            dimensionality=ABC.THREE_D,
            type=ABC.DEFORMABLE_BODY,
        )
        my_part.BaseSolidExtrude(sketch=my_sketch, depth=CONS["DEPTH"])

    # Create a material
    my_material = my_model.Material(name="POM")
    my_material.Elastic(table=((CONS["YOUNGS_MODULUS"],
                                CONS["POISSONS_RATIO"]), ))

    # Create section
    my_model.HomogeneousSolidSection(name="FootSection",
                                     material="POM",
                                     thickness=None)
    if is_planar:
        my_part.SectionAssignment(region=(my_part.faces, ),
                                  sectionName="FootSection")
    else:
        my_part.SectionAssignment(region=(my_part.cells, ),
                                  sectionName="FootSection")

    # Create an instance
    my_assembly = my_model.rootAssembly
    my_instance = my_assembly.Instance(name="FootInstance",
                                       part=my_part,
                                       dependent=ABC.OFF)

    # Create a step
    my_model.StaticStep(
        name="LoadStep",
        previous="Initial",
        timePeriod=1.0,
        initialInc=0.1,
        description="Weight of patient",
    )

    # Create track point
    vertices = my_instance.vertices
    track_point = vertices.findAt((tuple(points[1] + [0]), ))
    my_assembly.Set(vertices=track_point, name="TrackPoint")

    # Create field output request and set one frame only
    my_field_request = my_model.fieldOutputRequests["F-Output-1"]
    my_field_request.setValues(variables=OUTPUT_VARIABLE_TUPLE)

    my_history_request = my_model.historyOutputRequests["H-Output-1"]
    my_history_request.setValues(
        variables=("U1", "U2", "U3", "UR1", "UR2", "UR3"),
        region=my_assembly.sets["TrackPoint"],
    )

    if is_planar:
        # Fix face and apply load
        fixed_edge_center = (
            (points[6][0] + points[7][0]) / 2,
            (points[6][1] + points[7][1]) / 2,
            0,
        )
        loaded_edge_center = (
            (points[0][0] + points[1][0]) / 2,
            (points[0][1] + points[1][1]) / 2,
            0,
        )
        # Fix face
        fixed_edge = my_instance.edges.findAt((fixed_edge_center, ))
        my_model.EncastreBC(name="Fixed",
                            createStepName="LoadStep",
                            region=(fixed_edge, ))
        # Apply load
        loaded_edge = my_instance.edges.findAt((loaded_edge_center, ))
        length = my_part.getLength(edges=loaded_edge)
        my_model.Pressure(
            name="Loaded",
            createStepName="LoadStep",
            region=((loaded_edge, ABC.SIDE1), ),
            magnitude=CONS["LOAD_MAGNITUDE"] / (length * CONS["DEPTH"]),
        )
    else:
        # Fix face and apply load
        fixed_face_center = (
            (points[6][0] + points[7][0]) / 2,
            (points[6][1] + points[7][1]) / 2,
            CONS["DEPTH"] / 2,
        )
        loaded_face_center = (
            (points[0][0] + points[1][0]) / 2,
            (points[0][1] + points[1][1]) / 2,
            CONS["DEPTH"] / 2,
        )
        # Fix face
        fixed_face = my_instance.faces.findAt((fixed_face_center, ))
        my_model.EncastreBC(name="Fixed",
                            createStepName="LoadStep",
                            region=(fixed_face, ))
        # Apply load
        loaded_face = my_instance.faces.findAt((loaded_face_center, ))
        area = my_part.getArea(faces=loaded_face)
        my_model.Pressure(
            name="Loaded",
            createStepName="LoadStep",
            region=((loaded_face, ABC.SIDE1), ),
            magnitude=CONS["LOAD_MAGNITUDE"] / area,
        )

    # Mesh the instance
    my_assembly.seedPartInstance(regions=(my_instance, ),
                                 size=CONS["ELEMENT_SEED_SIZE"])
    my_assembly.generateMesh(regions=(my_instance, ))

    # Create and submit job
    job_name = model_name
    my_job = ABQ.mdb.Job(name=job_name,
                         model=model_name,
                         description="Foot design")
    my_job.submit()
    my_job.waitForCompletion()

    # Read the field output
    my_odb = odbAccess.openOdb(path=job_name + ".odb")
    last_step = my_odb.steps["LoadStep"]
    last_frame = last_step.frames[-1]
    field_outputs = last_frame.fieldOutputs["S"]
    field_output = max(
        [getattr(value, "mises") for value in field_outputs.values])

    # Read the history output
    history_region_name = last_step.historyRegions.keys()[0]
    history_region = last_step.historyRegions[history_region_name]
    history_output = [
        value.data[-1][-1]
        for value in history_region.historyOutputs.values()[:2]
    ]

    objective = (history_output[0]**2 + history_output[1]**2)**(0.5)

    # Print result photo, just for Mises
    if print_photo:
        # View the result (not working with noGUI)
        my_odb = visualization.openOdb(path=job_name + ".odb")
        my_viewport = ABQ.session.viewports["Viewport: 1"]
        my_viewport.setValues(displayedObject=my_odb)
        my_viewport.view.fitView()
        my_viewport.odbDisplay.display.setValues(plotState=ABC.CONTOURS_ON_DEF)
        my_viewport.odbDisplay.setPrimaryVariable(
            variableLabel="S",
            outputPosition=ABC.INTEGRATION_POINT,
            refinement=(ABC.INVARIANT, "Mises"),
        )
        my_viewport.odbDisplay.commonOptions.setValues(renderStyle=ABC.FILLED)

        # Export image
        my_viewport.view.pan(xFraction=0.1)
        ABQ.session.defaultViewportAnnotationOptions.setValues(title=ABC.OFF,
                                                               state=ABC.OFF,
                                                               triad=ABC.OFF)
        ABQ.session.printOptions.setValues(rendition=ABC.COLOR,
                                           vpDecorations=ABC.OFF,
                                           vpBackground=ABC.OFF)
        ABQ.session.printToFile(
            fileName=str(CONS["OUTPUT_PHOTO_DIRECTORY"]) + job_name,
            # format=ABC.PNG,
            format=ABC.SVG,
            canvasObjects=(my_viewport, ),
        )

    # Close output database and delete the model
    my_odb.close()
    del my_model

    # Delete unnecessary files
    remove_unnecessary_files(job_name)

    return {
        "objective": objective,
        "field_output": field_output,
    }
コード例 #15
0
"""

# 2. 导入相应模块
from abaqus import *
from abaqusConstants import *
import visualization

# 3. 创建新视口函数
myViewport = session.Viewport(name='Superposition example',
                              origin=(10, 10),
                              width=150,
                              height=100)

# 4. 打开输出数据库
myOdb = visualization.openOdb(
    path=
    'D:\\Coding\\Github\\Python-in-Abaqus\\Learning\\2 Abaqus script interface\\2.4-example\\viewer_tutorial.odb'
)  # path 应该给出文件的绝对路径
myViewport.setValues(displayedObject=myOdb)

# 5. 获取Step1和Step2结束时刻的位移增量和应力增量
firstStep = myOdb.steps['Step-1']
secondStep = myOdb.steps['Step-2']

frame1 = firstStep.frames[-1]
frame2 = secondStep.frames[-1]

displacement1 = frame1.fieldOutputs['U']
displacement2 = frame2.fieldOutputs['U']
stress1 = frame1.fieldOutputs['S']
stress2 = frame2.fieldOutputs['S']
コード例 #16
0
ファイル: dataHandling.py プロジェクト: zzalscv2/TexGen
def ComputeEquivalentMaterialProperties(modelName, thermoMechSwitch):

    # Open the relevent .ODB file.
    fileName = modelName + '.odb'
    resultODB = visualization.openOdb(path=fileName, readOnly=True)

    # Collect the various steps.
    isothermalStep = resultODB.steps.values()[0]
    if (thermoMechSwitch == 1):
        thermoMechanicalStep = resultODB.steps.values()[1]

    # The load-cases are held in frames.
    # Index 0 holds the reference frame.
    # 1 holds the Fx load-case.
    frameFx = resultODB.steps[isothermalStep.name].frames[1]
    # 2 holds the Fy load-case.
    frameFy = resultODB.steps[isothermalStep.name].frames[2]
    # 3 holds the Fx load-case.
    frameFz = resultODB.steps[isothermalStep.name].frames[3]
    # 4 holds the Shear_xy load-case.
    frameShear_xy = resultODB.steps[isothermalStep.name].frames[4]
    # 5 holds the Shear_zx load-case.
    frameShear_zx = resultODB.steps[isothermalStep.name].frames[5]
    # 6 holds the Shear_yz load-case.
    frameShear_yz = resultODB.steps[isothermalStep.name].frames[6]

    if (thermoMechSwitch == 1):
        # Index 0 holds the reference frame.
        frameThermomechanical = resultODB.steps[
            thermoMechanicalStep.name].frames[1]

    # Load case Fx.
    Fx_eps0_x = frameFx.fieldOutputs['U'].values[0].data[0]
    Fx_eps0_y = frameFx.fieldOutputs['U'].values[1].data[0]
    Fx_eps0_z = frameFx.fieldOutputs['U'].values[2].data[0]

    # Load case FY.
    Fy_eps0_x = frameFy.fieldOutputs['U'].values[0].data[0]
    Fy_eps0_y = frameFy.fieldOutputs['U'].values[1].data[0]
    Fy_eps0_z = frameFy.fieldOutputs['U'].values[2].data[0]

    # Load case Fz.
    Fz_eps0_x = frameFz.fieldOutputs['U'].values[0].data[0]
    Fz_eps0_y = frameFz.fieldOutputs['U'].values[1].data[0]
    Fz_eps0_z = frameFz.fieldOutputs['U'].values[2].data[0]

    # Load case Shear_xy.
    Shear_xy_gamma0_xy = frameShear_xy.fieldOutputs['U'].values[3].data[0]

    # Load case Shear_zx.
    Shear_zx_gamma0_zx = frameShear_zx.fieldOutputs['U'].values[4].data[0]

    # Load case Shear_yz.
    Shear_yz_gamma0_yz = frameShear_yz.fieldOutputs['U'].values[5].data[0]

    if (thermoMechSwitch == 1):
        # Thermomechanical expansion.
        Th_eps0_x = frameThermomechanical.fieldOutputs['U'].values[0].data[0]
        Th_eps0_y = frameThermomechanical.fieldOutputs['U'].values[1].data[0]
        Th_eps0_z = frameThermomechanical.fieldOutputs['U'].values[2].data[0]

    # It is assumed that the needed data has been extracted properly.

    # Material properties.
    # The loads are now nominal.
    # E0_x = lVect[0]/volUC/Fx_eps0_x
    E0_x = 1.0 / Fx_eps0_x
    v0_xy = -Fx_eps0_y / Fx_eps0_x
    v0_xz = -Fx_eps0_z / Fx_eps0_x

    E0_y = 1.0 / Fy_eps0_y
    v0_yx = -Fy_eps0_x / Fy_eps0_y
    v0_yz = -Fy_eps0_z / Fy_eps0_y

    E0_z = 1.0 / Fz_eps0_z
    v0_zx = -Fz_eps0_x / Fz_eps0_z
    v0_zy = -Fz_eps0_y / Fz_eps0_z

    G0_xy = 1.0 / Shear_xy_gamma0_xy

    G0_yz = 1.0 / Shear_yz_gamma0_yz

    G0_zx = 1.0 / Shear_zx_gamma0_zx

    if (thermoMechSwitch == 1):
        alpha0_x = Th_eps0_x
        alpha0_y = Th_eps0_y
        alpha0_z = Th_eps0_z
    else:
        alpha0_x = 0.0
        alpha0_y = 0.0
        alpha0_z = 0.0

    # Now adding the displacements.
    return (E0_x, v0_xy, v0_xz, E0_y, v0_yx, v0_yz, E0_z, v0_zx, v0_zy, G0_yz,
            G0_zx, G0_xy, Fx_eps0_x, Fx_eps0_y, Fx_eps0_z, Fy_eps0_x,
            Fy_eps0_y, Fy_eps0_z, Fz_eps0_x, Fz_eps0_y, Fz_eps0_z,
            Shear_yz_gamma0_yz, Shear_zx_gamma0_zx, Shear_xy_gamma0_xy,
            alpha0_x, alpha0_y, alpha0_z)
コード例 #17
0
from the last frame of different steps, and display a contour
plot of the result.
"""

from abaqus import *
from abaqusConstants import *
import visualization

myViewport = session.Viewport(name='Superposition example',
                              origin=(10, 10),
                              width=150,
                              height=100)

# Open the tutorial output database.

myOdb = visualization.openOdb(path='viewer_tutorial.odb')

# Associate the output database with the viewport.

myViewport.setValues(displayedObject=myOdb)

# Create variables that refer to the first two steps.

firstStep = myOdb.steps['Step-1']
secondStep = myOdb.steps['Step-2']

# Read displacement and stress data from the last frame
# of the first two steps.

frame1 = firstStep.frames[-1]
frame2 = secondStep.frames[-1]
コード例 #18
0
def find_strain(JobName, StepName, FOTYPE, SetName = None, object = 'assembly', 

                object_name = None, strain_metric = 'mises'):

    """Finds Strain for a Set if SetName defined.Currently only works for mises.

        Otherwise finds maxMises for the whole model
        - object = 'assembly' or 'instance' (in that case specify name of instance.

        - strain_metric = 'mises' to get maximum equivalent stress and 'principal'"""

    odbName = JobName + '.odb'

    odb = visualization.openOdb(odbName)

    lastFrame = odb.steps[StepName].frames[-1]

    deformation = lastFrame.fieldOutputs[FOTYPE]

    # If not Set defined, get the value for the whole thing

    if SetName == None:

        raise NotImplementedError

    else:

        elsetName = SetName

        elset = elemset = None

        assembly = odb.rootAssembly

        #Check to see if the element set exists

        #in the assembly

        if elsetName:

           try:

               if object == 'assembly':

                   elemset = assembly.elementSets[elsetName]

                   region = " in the element set : " + elsetName;

               elif object == 'instance':

                   elemset = assembly.instances[object_name.upper()].elementSets[elsetName.upper()]                    

           except KeyError:

               print assembly.elementSets

               print 'An assembly level elset named %s does' \
                      'not exist in the output database %s' \
                      % (elsetName, odbName)

               exit(0)

        """ Initialize maximum values """

        maxStrain = -0.1

        maxStrainElem = 0

        maxStep = "_None_"

        maxFrame = -1

        Stress = 'S'

        isStressPresent = 0

        for step in odb.steps.values():

           if StepName == None or step.name == StepName:

               if elemset:

                   strainSet = deformation.getSubset(region=elemset)

               for strainValue in strainSet.values:

                   if strain_metric == 'mises':

                      strain_i = strainValue.mises

                   elif strain_metric == 'principal':

                      strain_i = abs(strainValue.maxPrincipal)
                      strain_act=strainValue.maxPrincipal					  

                   elif strain_metric == 'Shear':

                      strain_i = abs(strainValue.data[5])
                      strain_act=strainValue.data[5]					
                   if (strain_i > maxStrain):
                       
					   maxStrain = strain_i
					   retStrain = strain_act

					   maxStrainElem = strainValue.elementLabel

					   maxStep = step.name

					   maxFrame = lastFrame.incrementNumber

        odb.close()

        return retStrain	



	"""
コード例 #19
0
def getResults2(ModelName):
    disppTip = [0 for x in range(17)]
    disppTip2 = [0 for x in range(17)]
    """
	This ODB reading script does the following:
	-Retrieves the displacement at TIPNODE
	-Scans for max. Mises stress in a part (if set exists)
	"""

    # Open the output database.
    print 'Made it in'
    odbName = ModelName + '.odb'
    print odbName
    odb = visualization.openOdb(odbName)
    lastFrame = odb.steps['RBM'].frames[-1]
    firstFrame = odb.steps['RBM'].frames[0]
    print 'odb open'

    # Selecting the node(s) to be queried
    pTip = odb.rootAssembly.nodeSets['TIPNODE']

    # Retrieve Y-displacements at the splines/connectors
    print 'Retrieving ALL final displacements at ALL points'
    dispField = firstFrame.fieldOutputs['COORD']
    dispField2 = lastFrame.fieldOutputs['COORD']
    print 'Retrieving ALL displacements at TIPNODE'
    dFieldpTip = dispField.getSubset(region=pTip)
    dFieldpTip2 = dispField2.getSubset(region=pTip)
    print 'Retrieving only U2 at TIPNODE'
    #Note, U1=data[0], U2=data[1], U3=data[2]

    for i in range(8):
        disppTip[i] = dFieldpTip.values[i].data[0]
        disppTip[i + 8] = dFieldpTip.values[i].data[2]
        disppTip2[i] = dFieldpTip2.values[i].data[0]
        disppTip2[i + 8] = dFieldpTip2.values[i].data[2]
        #The following is left for use in later probems/projects
    print 'Scanning the PART for maximum VM STRESS'
    elsetName = 'ALL_PART'
    elset = elemset = None
    region = "over the entire model"
    assembly = odb.rootAssembly

    #Check to see if the element set exists
    #in the assembly

    if elsetName:
        try:
            elemset = assembly.elementSets[elsetName]
            region = " in the element set : " + elsetName
        except KeyError:
            print 'An assembly level elset named %s does' \
             'not exist in the output database %s' \
             % (elsetName, odbName)
            odb.close()
            exit(0)
    """ Initialize maximum values """
    maxMises = -0.1
    maxVMElem = 0
    maxStep = "_None_"
    maxFrame = -1
    Stress = 'S'
    isStressPresent = 0
    for step in odb.steps.values():
        print 'Processing Step:', step.name
        for frame in step.frames:
            allFields = frame.fieldOutputs
            if (allFields.has_key(Stress)):
                isStressPresent = 1
                stressSet = allFields[Stress]
                if elemset:
                    stressSet = stressSet.getSubset(region=elemset)
                for stressValue in stressSet.values:
                    if (stressValue.mises > maxMises):
                        maxMises = stressValue.mises
                        maxVMElem = stressValue.elementLabel
                        maxStep = step.name
                        maxFrame = frame.incrementNumber
    if (isStressPresent):
        print 'Maximum von Mises stress %s is %f in element %d' % (
            region, maxMises, maxVMElem)
        print 'Location: frame # %d  step:  %s ' % (maxFrame, maxStep)
    else:
        print 'Stress output is not available in' \
        'the output database : %s\n' %(odb.name)
    disppTip[16] = maxMises
    odb.close()
    return disppTip, disppTip2
コード例 #20
0
ファイル: odbExample.py プロジェクト: Anzumana/Abaqus
Script to open an output database, superimpose variables
from the last frame of different steps, and display a contour
plot of the result.
"""

from abaqus import *
from abaqusConstants import *
import visualization

myViewport = session.Viewport(name='Superposition example',
    origin=(10, 10), width=150, height=100)

# Open the tutorial output database.

myOdb = visualization.openOdb(path='viewer_tutorial.odb')

# Associate the output database with the viewport.

myViewport.setValues(displayedObject=myOdb)

# Create variables that refer to the first two steps.

firstStep = myOdb.steps['Step-1']
secondStep = myOdb.steps['Step-2']

# Read displacement and stress data from the last frame
# of the first two steps.

frame1 = firstStep.frames[-1]
frame2 = secondStep.frames[-1]
コード例 #21
0
# -*- coding: mbcs -*-

from abaqus import *
from abaqusConstants import *
import visualization




myViewport = session.Viewport(name='Whatever Viewport',
    origin=(0, 0), width=150, height=100)
	
myOdb = visualization.openOdb(path='Job-1.odb')

myViewport.setValues(displayedObject=myOdb)


#窗口最大化
session.viewports['Whatever Viewport'].makeCurrent()
session.viewports['Whatever Viewport'].maximize()
session.viewports['Viewport: 1'].restore()
session.viewports['Whatever Viewport'].maximize()
#-----------------------------------------------


session.viewports['Whatever Viewport'].odbDisplay.display.setValues(plotState=(
    CONTOURS_ON_UNDEF, ))
session.viewports['Whatever Viewport'].view.setValues(session.views['Iso'])
session.viewports['Whatever Viewport'].view.rotate(xAngle=5, yAngle=-20, 
    zAngle=190, mode=MODEL)
session.printToFile(
コード例 #22
0
ファイル: one_element.py プロジェクト: erolsson/fem_py
                  model=model,
                  numCpus=1,
                  numDomains=1,
                  multiprocessingMode=THREADS,
                  userSubroutine=umat_file)

if os.path.exists(simulation_name + '.lck'):
    os.remove(simulation_name + '.lck')

job.submit()
job.waitForCompletion()
# ==========================================================================
#                           Output to file
# ==========================================================================

odb = visualization.openOdb(simulation_name + '.odb')
frames_load = odb.steps['step'].frames

data = np.zeros((len(frames_load), 13))
for i in range(0, len(frames_load)):
    frame = frames_load[i]
    S = frame.fieldOutputs['S'].values[0]
    E = frame.fieldOutputs['E'].values[0]
    data[i, 0:6] = S.data
    data[i, 6:12] = E.data
    data[i, 12] = frame.frameValue

with open('stressStrain' + simulation_name + '.pkl', 'wb') as pickle_handle:
    pickle.dump(data, pickle_handle)
odb.close()
コード例 #23
0
def CalculateMetrics(fileName, componentList, reqMetricSet):
    gLogger.info('\n\n~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~')
    gLogger.info('FUNCTION: CalculateMetrics\n')
    global gStructuralMetricTypes
    global gThermalMetricTypes
    
    odbFileName = fileName + '.odb'
    myOdb = visualization.openOdb(path=odbFileName)

    maxShear = 0
    maxBearing = 0
    maxMises = 0
    maxTemp = -10**9
    minTemp = 10**9

    mainDir = os.path.join(os.getcwd(), odbName)
    if not os.path.exists(mainDir):
        os.makedirs(mainDir)
    os.chdir(mainDir)

    assembly = myOdb.rootAssembly

    distortedElementIDList = list()

    # get the distorted Element set
    if 'WarnElemDistorted' in assembly.elementSets.keys():
        warnElemDistorted = assembly.elementSets['WarnElemDistorted']
        distortedElementSet = warnElemDistorted.elements
        if len(distortedElementSet) > 0:
            distortedElements = distortedElementSet[0]
            for item in distortedElements:
                distortedElementIDList.append(item.label)

    for component in componentList.values():
        if len(component.Children) > 0:
            continue
        try:     # deck-based
            elemset = assembly.instances['PART-1-1'].elementSets[component.ElementID]
        except:  # model-based
            elemset = assembly.instances[component.ElementID]
        
        distortedStressDict = {}
        noneDistortedStressDict = {}
        for step in myOdb.steps.values():
            lastFrame = step.frames[-1]
            if 'S' in reqMetricSet:
                distortedStressDict, noneDistortedStressDict, maxMises, maxBearing, maxShear = \
                    ProcessStress(lastFrame, elemset, maxMises, maxBearing, maxShear,
                                  distortedStressDict, distortedElementIDList, noneDistortedStressDict)
            if 'TEMP' in reqMetricSet:
                maxTemp, minTemp = ProcessThermal(lastFrame, elemset, maxTemp, minTemp)
        
        if 'S' in reqMetricSet:
            # calculate FactorOfSafety
            try:
                factorOfSafety = float(component.Allowables.mechanical__strength_tensile)/maxMises
            except ZeroDivisionError:
                factorOfSafety = 0.0
            
            shearQuality = bearQuality = miseQuality = 1
            if len(distortedStressDict) > 0:
                shearQuality, bearQuality, miseQuality = ProcessDistorted(distortedStressDict,
                                                                          (maxMises, maxBearing, maxShear))

            shearRange, bearRange, miseRange, outRangeIDs = EvaluateStressGradient(noneDistortedStressDict)
            component.OutOfRangeDistorted = outRangeIDs
            UpdateComponentStressMetrics(componentList, component, maxMises, maxShear, maxBearing, factorOfSafety,
                                         shearQuality, bearQuality, miseQuality, shearRange,
                                         bearRange, miseRange)
        if 'TEMP' in reqMetricSet:
            UpdateComponentThermalMetrics(componentList, component, maxTemp, minTemp)

        #end for

    gLogger.info('\n~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\n')
    SetupViewportPNG(myOdb, fileName, reqMetricSet)
    myOdb.close()           # close odb
    os.chdir('..')  # bring you back to /Analysis/Abaqus
コード例 #24
0
# 显示划分网格后的梁模型。
myViewport.assemblyDisplay.setValues(mesh=ON)
myViewport.assemblyDisplay.meshOptions.setValues(meshTechnique=ON)
myViewport.setValues(displayedObject=myAssembly)

# 导入job模块。
import job

# 为模型创建并提交分析作业。
jobName = 'beam_tutorial'
myJob = mdb.Job(name=jobName,
                model='Beam',
                description='Cantilever beam tutorial')

# 等待分析作业完成。
myJob.submit()
myJob.waitForCompletion()
print '分析已顺利完成,下面进行后处理。'

# 导入visualization模块。
import visualization

# 打开输出数据库,显示默认的等值线图。
myOdb = visualization.openOdb(path=jobName + '.odb')
myViewport.setValues(displayedObject=myOdb)
myViewport.odbDisplay.display.setValues(plotState=CONTOURS_ON_DEF)
myViewport.odbDisplay.commonOptions.setValues(renderStyle=FILLED)

# 将Mises等值线图输出为PNG格式的文件。
session.printToFile(fileName='Mises', format=PNG, canvasObjects=(myViewport, ))
print '文件Mises.png保存于工作目录下,请查看!'
コード例 #25
0
def evalOneMax(individual, iter, nmodel):
    # Declare variables as global
    global lengthMesh, nx, ny, nX, nY, xlength, ylength
    ### Create a new model named 'Model-Iter0-Num0'
    modelName = 'Model-Iter'+str(iter)+'-Num'+str(nmodel)
    myModel = mdb.Model(name= modelName)
    ### Create constrained sketch for all deformable elements
    for i in range(nX):
        for j in range(nY):
            s = mdb.models[modelName].ConstrainedSketch(name='__profile__', sheetSize=xlength*nX*1.2)
            s.setPrimaryObject(option=STANDALONE)
            s.rectangle(point1=(i*xlength, j*ylength), point2=((i+1)*xlength, (j+1)*ylength))
            # Create part named 'Part-Plate-i-j'
            partName = 'Part-Plate-'+str(i)+'-'+str(j)
            p = mdb.models[modelName].Part(name=partName, dimensionality=TWO_D_PLANAR, type=DEFORMABLE_BODY)
            p = mdb.models[modelName].parts[partName]
            p.BaseShell(sketch=s)
            s.unsetPrimaryObject()
            # Define vertices sets
            v = p.vertices
            location1 = (i*xlength, j*ylength, 0)  # bottom-left
            location2 = (i*xlength, (j+1)*ylength, 0)   # top-left
            location3 = ((i+1)*xlength, (j+1)*ylength, 0)   # top-right
            location4 = ((i+1)*xlength, j*ylength, 0)   # bottom-right
            verts1 = v.findAt((location1, ))
            verts2 = v.findAt((location2, ))
            verts3 = v.findAt((location3, ))
            verts4 = v.findAt((location4, ))
            p.Set(vertices=verts1, name='Set-1')
            p.Set(vertices=verts2, name='Set-2')
            p.Set(vertices=verts3, name='Set-3')
            p.Set(vertices=verts4, name='Set-4')
            del mdb.models[modelName].sketches['__profile__']

    ### Create materials named 'Material-Active' and 'Material-Inactive'
    activeName = 'Material-Active'
    inactiveName = 'Material-Inactive'
    mdb.models[modelName].Material(name=activeName)
    mdb.models[modelName].materials[activeName].Elastic(table=((210000.0, 0.3), ))
    mdb.models[modelName].materials[activeName].Expansion(table=((0.00025, ), ))
    mdb.models[modelName].Material(name=inactiveName)
    mdb.models[modelName].materials[inactiveName].Elastic(table=((210000.0, 0.3), ))
    mdb.models[modelName].materials[inactiveName].Expansion(table=((0.00005, ), ))
    ### Create HomogeneousSolidSection objects and assign material property to them 
    activeSection = 'Section-Active'
    inactiveSection = 'Section-Inactive'
    mdb.models[modelName].HomogeneousSolidSection(name=activeSection, material=activeName, thickness=None)
    mdb.models[modelName].HomogeneousSolidSection(name=inactiveSection, material=inactiveName, thickness=None)
    
    ### Adding sections to parts accordingly
    ### Resulting section pattern is like a checkerboard
    for i in range(nX):
        for j in range(nY):
            # Create partName named 'Part-Plate-i-j'
            partName = 'Part-Plate-'+str(i)+'-'+str(j)
            p = mdb.models[modelName].parts[partName]
            f = p.faces
            faces = f.getSequenceFromMask(mask=('[#1 ]', ), )
            # Create a region
            region = regionToolset.Region(faces=faces)
            if individual[j*nX+i] == 0:
                p.SectionAssignment(region=region, sectionName=inactiveSection, 
                    offset=0.0, offsetType=MIDDLE_SURFACE, offsetField='', thicknessAssignment=FROM_SECTION)
            elif individual[j*nX+i] == 1:
                p.SectionAssignment(region=region, sectionName=activeSection, 
                    offset=0.0, offsetType=MIDDLE_SURFACE, offsetField='', thicknessAssignment=FROM_SECTION)

    ### Create assembly consisting of all plate instances
    a = mdb.models[modelName].rootAssembly
    a.DatumCsysByDefault(CARTESIAN)
    for i in range(nX):
        for j in range(nY):
            # Create partName named 'Part-Plate-i-j'
            partName = 'Part-Plate-'+str(i)+'-'+str(j)
            instanceName = partName+'-1'
            p = mdb.models[modelName].parts[partName]
            # Create indenpendent instances by setting 'dependent' to OFF
            a.Instance(name=instanceName, part=p, dependent=OFF)

    ### Generate mesh for the assembly
    # Create tuple of part instances
    partInstances = []
    for i in range(nX):
        for j in range(nY):
            instanceName = 'Part-Plate-'+str(i)+'-'+str(j)+'-1'
            partInstances.append(a.instances[instanceName])
    partInstances=tuple(partInstances)
    # Seed part instances
    a.seedPartInstance(regions=partInstances, size=lengthMesh, deviationFactor=0.1, minSizeFactor=0.1)
    # Generate mesh for partInstances based on previous seeding
    a.generateMesh(regions=partInstances)

    ### Create a new step named 'Step-ThermalExpansion' after initial step
    mdb.models[modelName].StaticStep(name='Step-ThermalExpansion', previous='Initial')

    ### Create interaction edges and define interaction relations 
    for i in range(nX):
        for j in range(nY):
            # Create instanceName named 'Part-Plate-i-j-1'
            instanceName = 'Part-Plate-'+str(i)+'-'+str(j)+'-1'
            s1 = a.instances[instanceName].edges
            edgeCenter1 = ((i+0.5)*xlength, (j+1.0)*ylength, 0)
            edgeCenter2 = ((i+0.0)*xlength, (j+0.5)*ylength, 0)
            edgeCenter3 = ((i+1.0)*xlength, (j+0.5)*ylength, 0)
            edgeCenter4 = ((i+0.5)*xlength, (j+0.0)*ylength, 0)
            edges1 = s1.findAt((edgeCenter1, ))
            edges2 = s1.findAt((edgeCenter2, ))
            edges3 = s1.findAt((edgeCenter3, ))
            edges4 = s1.findAt((edgeCenter4, ))
            edges1 = (edges1, ); edges2 = (edges2, ); edges3 = (edges3, ); edges4 = (edges4, )
            # Create surfaces for all 4 edges of current element
            # a is rootAssembly
            a.Surface(side1Edges=edges1, name='Surf-Plate-'+str(i)+'-'+str(j)+'-1')
            a.Surface(side1Edges=edges2, name='Surf-Plate-'+str(i)+'-'+str(j)+'-2')
            a.Surface(side1Edges=edges3, name='Surf-Plate-'+str(i)+'-'+str(j)+'-3')
            a.Surface(side1Edges=edges4, name='Surf-Plate-'+str(i)+'-'+str(j)+'-4')
    # Define interaction relations between lower and upper surfaces
    for i in range(nX):
        for j in range(nY-1):
            surfName1 = 'Surf-Plate-'+str(i)+'-'+str(j)+'-1'
            surfName2 = 'Surf-Plate-'+str(i)+'-'+str(j+1)+'-4'
            region1=a.surfaces[surfName1]
            region2=a.surfaces[surfName2]
            contactName = 'Constraint-'+str(i)+str(j)+str(i)+str(j+1)+'-14'
            mdb.models[modelName].Tie(name=contactName, master=region1, slave=region2, 
                positionToleranceMethod=COMPUTED, adjust=ON, tieRotations=ON, thickness=ON)
    # Define interaction relations between left and right surfaces
    for i in range(nX-1):
        for j in range(nY):
            surfName1 = 'Surf-Plate-'+str(i)+'-'+str(j)+'-3'
            surfName2 = 'Surf-Plate-'+str(i+1)+'-'+str(j)+'-2'
            region1=a.surfaces[surfName1]
            region2=a.surfaces[surfName2]
            contactName = 'Constraint-'+str(i)+str(j)+str(i+1)+str(j)+'-32'
            mdb.models[modelName].Tie(name=contactName, master=region1, slave=region2, 
                positionToleranceMethod=COMPUTED, adjust=ON, tieRotations=ON, thickness=ON)

    ### Create boundary conditions for the assembly
    a = mdb.models[modelName].rootAssembly
    for j in range(nY):
        instanceName = 'Part-Plate-0-'+str(j)+'-1'
        e1 = a.instances[instanceName].edges
        edgeCenter = (0.0, (j+0.5)*ylength, 0.0)
        edges1 = e1.findAt((edgeCenter, ))
        edges1 = (edges1, )
        setName = 'Set-Plate-0-'+str(j)+'-Fix'
        a.Set(edges=edges1, name=setName)
        # Set boundary conditions
        region = a.sets[setName]
        bcName = 'BC-Plate-0-'+str(j)+'-Fix'
        mdb.models[modelName].DisplacementBC(name=bcName, 
            createStepName='Initial', region=region, u1=SET, u2=UNSET, ur3=SET, 
            amplitude=UNSET, distributionType=UNIFORM, fieldName='', localCsys=None)
    instanceName = 'Part-Plate-0-0-1'
    v1 = a.instances[instanceName].vertices
    vertexCenter = (0.0, 0.0, 0.0)
    v = v1.findAt((vertexCenter, ))
    v = (v, )
    setName = 'Set-Plate-Origin-Fix'
    a.Set(vertices=v, name=setName)
    region = a.sets[setName]
    bcName = 'BC-Origin-Fix'
    # Origin fix in x-direction, y-direction, xy-rotation
    mdb.models[modelName].DisplacementBC(name=bcName, 
            createStepName='Initial', region=region, u1=SET, u2=SET, ur3=SET, 
            amplitude=UNSET, distributionType=UNIFORM, fieldName='', localCsys=None)

    ### Define nodeSets that records the displacement information of the entire assembly
    # 1st: bottom left vertices of all deformable elements
    a = mdb.models[modelName].rootAssembly
    for i in range(nX):
        for j in range(nY):
            nodeName = 'Node-Plate-'+str(i)+'-'+str(j)
            instanceName = 'Part-Plate-'+str(i)+'-'+str(j)+'-1'
            v1 = a.instances[instanceName].vertices
            vertexCenter = (i*xlength, j*ylength, 0.0)
            v = v1.findAt((vertexCenter, ))
            v = (v, )
            a.Set(vertices=v, name=nodeName)
    # 2nd: top left vertices of elements in the top row
    for i in range(nX):
        nodeName = 'Node-Plate-'+str(i)+'-'+str(nY)
        instanceName = 'Part-Plate-'+str(i)+'-'+str(nY-1)+'-1'
        v1 = a.instances[instanceName].vertices
        vertexCenter = (i*xlength, nY*ylength, 0.0)
        v = v1.findAt((vertexCenter, ))
        v = (v, )
        a.Set(vertices=v, name=nodeName)
    # 3rd: bottom right vertices of elements in the rightmost column
    for j in range(nY):
        nodeName = 'Node-Plate-'+str(nX)+'-'+str(j)
        instanceName = 'Part-Plate-'+str(nX-1)+'-'+str(j)+'-1'
        v1 = a.instances[instanceName].vertices
        vertexCenter = (nX*xlength, j*ylength, 0.0)
        v = v1.findAt((vertexCenter, ))
        v = (v, )
        a.Set(vertices=v, name=nodeName)
    # 4th: top right vertex of the entire assembly
    nodeName = 'Node-Plate-'+str(nX)+'-'+str(nY)
    instanceName = 'Part-Plate-'+str(nX-1)+'-'+str(nY-1)+'-1'
    v1 = a.instances[instanceName].vertices
    vertexCenter = (nX*xlength, nY*ylength, 0.0)
    v = v1.findAt((vertexCenter, ))
    v = (v, )
    a.Set(vertices=v, name=nodeName)

    ### Define ambient temperature field
    a = mdb.models[modelName].rootAssembly
    allFaceSet = []
    for i in range(nX):
        for j in range(nY):
            instanceName = 'Part-Plate-'+str(i)+'-'+str(j)+'-1'
            f1 = a.instances[instanceName].faces
            faces = f1.getSequenceFromMask(mask=('[#1 ]', ), )
            allFaceSet.append(faces)
    allFaceSet =tuple(allFaceSet)
    setName = 'Set-allFace'
    a.Set(faces=allFaceSet, name=setName)
    region = a.sets[setName]
    # Set temperature for initial and final state
    initialT = 20.0
    finalT = 120.0
    mdb.models[modelName].Temperature(name='Predefined Field-Temperature', 
        createStepName='Initial', region=region, distributionType=UNIFORM, 
        crossSectionDistribution=CONSTANT_THROUGH_THICKNESS, magnitudes=(initialT, ))
    mdb.models[modelName].predefinedFields['Predefined Field-Temperature'].setValuesInStep(
        stepName='Step-ThermalExpansion', magnitudes=(finalT, ))

    ### Create job and submit
    jobName = 'Job-Iter'+str(iter)+'-Num'+str(nmodel)
    mdb.Job(name=jobName, model=modelName, description='', 
        type=ANALYSIS, atTime=None, waitMinutes=0, waitHours=0, queue=None, 
        memory=90, memoryUnits=PERCENTAGE, getMemoryFromAnalysis=True, 
        explicitPrecision=SINGLE, nodalOutputPrecision=SINGLE, echoPrint=OFF, 
        modelPrint=OFF, contactPrint=OFF, historyPrint=OFF, userSubroutine='', scratch='', resultsFormat=ODB)
    mdb.jobs[jobName].submit(consistencyChecking=OFF)
    mdb.jobs[jobName].waitForCompletion()
    print 'The analysis has been completed. On going postprocessing'

    ### Visualization
    myOdb = visualization.openOdb(path = jobName + '.odb')
    myViewport = session.Viewport(name='Viewport-'+modelName, origin =(0.0, 0.0), width=240, height=90)
    myViewport.setValues(displayedObject = myOdb)
    myViewport.view.setValues(viewOffsetY=2.0*nY*ylength)  # Move center of the viewport upward
    myViewport.odbDisplay.display.setValues(plotState=(CONTOURS_ON_UNDEF, CONTOURS_ON_DEF, ))
    myViewport.odbDisplay.commonOptions.setValues(visibleEdges=NONE)
    myViewport.odbDisplay.superimposeOptions.setValues(visibleEdges=NONE)
    myViewport.odbDisplay.commonOptions.setValues(renderStyle = FILLED)
    myViewport.odbDisplay.setPrimaryVariable(variableLabel='U', outputPosition=NODAL, refinement=(COMPONENT, 'U2'))
    myViewport.viewportAnnotationOptions.setValues(triad=OFF, title=OFF, state=OFF, compass=OFF)
    myViewport.viewportAnnotationOptions.setValues(legendFont='-*-verdana-medium-r-normal-*-*-80-*-*-p-*-*-*')
    myViewport.viewportAnnotationOptions.setValues(legendBox=OFF)
    fileName = 'U2-Iter'+str(iter)+'-Num'+str(nmodel)
    session.printToFile(fileName = fileName, format = PNG, canvasObjects = (myViewport, ))
    print 'File ' + fileName + ' has been saved in the working directory. Please check!'


    ### Output nodal displacements
    odb = openOdb(path = jobName + '.odb')
    assembly = odb.rootAssembly
    # First step + Last frame of the simulation
    step1 = odb.steps['Step-ThermalExpansion']
    lastFrame = step1.frames[-1]

    ##########################################
    # Define functions to calculate RMSE
    def SquaredError(xy):
        return (Shape(xy[0])-xy[1])**2

    # Defines the target shape
    def Shape(x):
        return (5*nY*ylength/((nX*xlength)**2))*x**2

    coordinates = []
    for i in range(nX+1):
        nodeName = 'NODE-PLATE-'+str(i)+'-'+str(0)
        nodes = assembly.nodeSets[nodeName]
        displacement = lastFrame.fieldOutputs['U']
        nodesDisplacement = displacement.getSubset(region = nodes)
        # coordinates stores the target coordinates of bottom nodes
        coordinates.append([i*xlength+nodesDisplacement.values[0].data[0], nodesDisplacement.values[0].data[1]])
    # Root Mean Square Error
    # Square root of sum of squares over number of individuals
    RMSE = (sum(map(SquaredError, coordinates))**0.5)/len(coordinates)

    ### Must close current odb object in order to begin the next iteration
    odb.close()
    del mdb.models[modelName]
    del mdb.jobs[jobName]

    return RMSE,
コード例 #26
0
myViewport.assemblyDisplay.meshOptions.setValues(meshTechnique=ON)
myViewport.setValues(displayedObject=myAssembly)

#-------------------------------------------------------

import job

# Create an analysis job for the model and submit it.

jobName = 'beam_tutorial'
myJob = mdb.Job(name=jobName, model='Beam',
    description='Cantilever beam tutorial')

# Wait for the job to complete.

myJob.submit()
myJob.waitForCompletion()

#-------------------------------------------------------

import visualization

# Open the output database and display a
# default contour plot.

myOdb = visualization.openOdb(path=jobName + '.odb')
myViewport.setValues(displayedObject=myOdb)
myViewport.odbDisplay.display.setValues(plotState=CONTOURS_ON_DEF)

myViewport.odbDisplay.commonOptions.setValues(renderStyle=FILLED)
コード例 #27
0
def evalOneMax(individual, iter, nmodel):
    ## Create a new model named 'Model'
    modelName = 'Model-Iter'+str(iter)+'-Num'+str(nmodel)
    myModel = mdb.Model(name= modelName)
    ## Create Upper constraint sketches, starting from the top-left corner
    for i in range(nX):
        for j in range(nY):
            s = mdb.models[modelName].ConstrainedSketch(name='__profile__', sheetSize=scaling)
            g, v, d, c = s.geometry, s.vertices, s.dimensions, s.constraints
            s.setPrimaryObject(option=STANDALONE)
            # Points in the data array is sorted according to decreasing Y-coordinates
            s.Line(point1=(UpperXY[i][2*j+0], UpperXY[i][2*j+1]),     point2=(UpperXY[i+1][2*j+0], UpperXY[i+1][2*j+1]))
            s.Line(point1=(UpperXY[i+1][2*j+0], UpperXY[i+1][2*j+1]), point2=(UpperXY[i+1][2*j+2], UpperXY[i+1][2*j+3]))
            s.Line(point1=(UpperXY[i+1][2*j+2], UpperXY[i+1][2*j+3]), point2=(UpperXY[i][2*j+2], UpperXY[i][2*j+3]))
            s.Line(point1=(UpperXY[i][2*j+2], UpperXY[i][2*j+3]),     point2=(UpperXY[i][2*j+0], UpperXY[i][2*j+1]))
            # Create part named 'Part-Upper-i-j'
            partName = 'Part-Upper-'+str(i)+'-'+str(j)
            p = mdb.models[modelName].Part(name=partName, dimensionality=TWO_D_PLANAR, type=DEFORMABLE_BODY)
            p = mdb.models[modelName].parts[partName]
            p.BaseShell(sketch=s)
            s.unsetPrimaryObject()
            del mdb.models[modelName].sketches['__profile__']
    ## Create Lower constraint sketches, starting from the bottom-left corner
    for i in range(nXL):
        for j in range(nYL):
            s = mdb.models[modelName].ConstrainedSketch(name='__profile__', sheetSize=scaling)
            g, v, d, c = s.geometry, s.vertices, s.dimensions, s.constraints
            s.setPrimaryObject(option=STANDALONE)
            # Points in the data array is sorted according to increasing Y-coordinates
            s.Line(point1=(LowerXY[i][2*j+0], LowerXY[i][2*j+1]),     point2=(LowerXY[i+1][2*j+0], LowerXY[i+1][2*j+1]))
            s.Line(point1=(LowerXY[i+1][2*j+0], LowerXY[i+1][2*j+1]), point2=(LowerXY[i+1][2*j+2], LowerXY[i+1][2*j+3]))
            s.Line(point1=(LowerXY[i+1][2*j+2], LowerXY[i+1][2*j+3]), point2=(LowerXY[i][2*j+2], LowerXY[i][2*j+3]))
            s.Line(point1=(LowerXY[i][2*j+2], LowerXY[i][2*j+3]),     point2=(LowerXY[i][2*j+0], LowerXY[i][2*j+1]))
            # Create part named 'Part-Lower-i-j'
            partName = 'Part-Lower-'+str(i)+'-'+str(j)
            p = mdb.models[modelName].Part(name=partName, dimensionality=TWO_D_PLANAR, type=DEFORMABLE_BODY)
            p = mdb.models[modelName].parts[partName]
            p.BaseShell(sketch=s)
            s.unsetPrimaryObject()
            del mdb.models[modelName].sketches['__profile__']
    ## Create tip of the wing
    s = mdb.models[modelName].ConstrainedSketch(name='__profile__', sheetSize=scaling)
    g, v, d, c = s.geometry, s.vertices, s.dimensions, s.constraints
    s.setPrimaryObject(option=STANDALONE)
    for j in range(nY):
        s.Line(point1=(UpperXY[nX][2*j+0], UpperXY[nX][2*j+1]),   point2=(UpperXY[nX][2*(j+1)+0], UpperXY[nX][2*(j+1)+1]))
        s.Line(point1=(LowerXY[nXL][2*j+0], LowerXY[nXL][2*j+1]), point2=(LowerXY[nXL][2*(j+1)+0], LowerXY[nXL][2*(j+1)+1]))
    s.Line(point1=(UpperXY[nX][0], UpperXY[nX][1]),   point2=(scaling*1.0, 0.0))
    s.Line(point1=(LowerXY[nXL][0], LowerXY[nXL][1]), point2=(scaling*1.0, 0.0))
    partName = 'Part-Tip'
    p = mdb.models[modelName].Part(name=partName, dimensionality=TWO_D_PLANAR, type=DEFORMABLE_BODY)
    p = mdb.models[modelName].parts[partName]
    p.BaseShell(sketch=s)
    s.unsetPrimaryObject()
    del mdb.models[modelName].sketches['__profile__']

    ## Create materials named 'Material-Active' and 'Material-Inactive'
    activeName = 'Material-Active'
    inactiveName = 'Material-Inactive' 
    mdb.models[modelName].Material(name=activeName)
    mdb.models[modelName].materials[activeName].Elastic(table=((210000.0, 0.3), ))
    mdb.models[modelName].materials[activeName].Expansion(table=((expandActive, ), ))
    mdb.models[modelName].Material(name=inactiveName)
    mdb.models[modelName].materials[inactiveName].Elastic(table=((210000.0, 0.3), ))
    mdb.models[modelName].materials[inactiveName].Expansion(table=((expandInactive, ), ))
    ## Create HomogeneousSolidSection objects and assign material property to them 
    activeSection = 'Section-Active'
    inactiveSection = 'Section-Inactive'
    mdb.models[modelName].HomogeneousSolidSection(name=activeSection, material=activeName, thickness=None)
    mdb.models[modelName].HomogeneousSolidSection(name=inactiveSection, material=inactiveName, thickness=None)
    ## Assign material sections to Upper part elements
    for i in range(nX):
        for j in range(nY):
            # Create partName named 'Part-Upper-i-j'
            partName = 'Part-Upper-'+str(i)+'-'+str(j)
            p = mdb.models[modelName].parts[partName]
            f = p.faces
            faces = f.getSequenceFromMask(mask=('[#1 ]', ), )
            region = regionToolset.Region(faces=faces)
            if individual[j*nX+i] == 0:
                p.SectionAssignment(region=region, sectionName=inactiveSection, 
                    offset=0.0, offsetType=MIDDLE_SURFACE, offsetField='', thicknessAssignment=FROM_SECTION)
            elif individual[j*nX+i] == 1:
                p.SectionAssignment(region=region, sectionName=activeSection, 
                    offset=0.0, offsetType=MIDDLE_SURFACE, offsetField='', thicknessAssignment=FROM_SECTION)
    ## Assign material sections to Lower part elements
    for i in range(nXL):
        for j in range(nYL):
            # Create partName named 'Part-Lower-i-j'
            partName = 'Part-Lower-'+str(i)+'-'+str(j)
            p = mdb.models[modelName].parts[partName]
            f = p.faces
            faces = f.getSequenceFromMask(mask=('[#1 ]', ), )
            region = regionToolset.Region(faces=faces)
            if individual[j*nXL+i+nX*nY] == 0:
                p.SectionAssignment(region=region, sectionName=inactiveSection, 
                    offset=0.0, offsetType=MIDDLE_SURFACE, offsetField='', thicknessAssignment=FROM_SECTION)
            elif individual[j*nXL+i+nX*nY] == 1:
                p.SectionAssignment(region=region, sectionName=activeSection, 
                    offset=0.0, offsetType=MIDDLE_SURFACE, offsetField='', thicknessAssignment=FROM_SECTION)

    partName='Part-Tip'
    p = mdb.models[modelName].parts[partName]
    f = p.faces
    faces = f.getSequenceFromMask(mask=('[#1 ]', ), )
    region = regionToolset.Region(faces=faces)
    p.SectionAssignment(region=region, sectionName=inactiveSection, offset=0.0, offsetType=MIDDLE_SURFACE, 
        offsetField='', thicknessAssignment=FROM_SECTION)

    ## Create assembly consisting of all plate instances
    a = mdb.models[modelName].rootAssembly
    a.DatumCsysByDefault(CARTESIAN)
    for i in range(nX):
        for j in range(nY):
            partName = 'Part-Upper-'+str(i)+'-'+str(j)
            instanceName = partName+'-1'
            p = mdb.models[modelName].parts[partName]
            # Create indenpendent instances by setting 'dependent' to OFF
            a.Instance(name=instanceName, part=p, dependent=OFF)
    for i in range(nXL):
        for j in range(nYL):
            partName = 'Part-Lower-'+str(i)+'-'+str(j)
            instanceName = partName+'-1'
            p = mdb.models[modelName].parts[partName]
            a.Instance(name=instanceName, part=p, dependent=OFF)
    partName='Part-Tip'
    instanceName = partName+'-1'
    p = mdb.models[modelName].parts[partName]
    a.Instance(name=instanceName, part=p, dependent=OFF)

    ## Generate mesh for the assembly
    partInstances = []
    for i in range(nX):
        for j in range(nY):
            instanceName = 'Part-Upper-'+str(i)+'-'+str(j)+'-1'
            partInstances.append(a.instances[instanceName])
    for i in range(nXL):
        for j in range(nYL):
            instanceName = 'Part-Lower-'+str(i)+'-'+str(j)+'-1'
            partInstances.append(a.instances[instanceName])
    instanceName = 'Part-Tip-1'
    partInstances.append(a.instances[instanceName])
    partInstances=tuple(partInstances)
    a.seedPartInstance(regions=partInstances, size=lengthMesh, deviationFactor=0.1, minSizeFactor=0.1)
    a.generateMesh(regions=partInstances)
    ## Create a new step named 'Step-ThermalExpansion' after initial step
    mdb.models[modelName].StaticStep(name='Step-ThermalExpansion', previous='Initial')

    ################## Define interaction relations ##################
    ## Create Upper interaction edges and define interaction relations 
    for i in range(nX):
        for j in range(nY):
            # Create instanceName named 'Part-Upper-i-j-1'
            instanceName = 'Part-Upper-'+str(i)+'-'+str(j)+'-1'
            # Lower:3, Right:2, Upper:1, Left:4
            s1 = a.instances[instanceName].edges
            # Edges are located in clockwise direction
            edgeCenter1 = (0.5*(UpperXY[i][2*j+0]+UpperXY[i+1][2*j+0]),   0.5*(UpperXY[i][2*j+1]+UpperXY[i+1][2*j+1]), 0)
            edgeCenter2 = (0.5*(UpperXY[i+1][2*j+0]+UpperXY[i+1][2*j+2]), 0.5*(UpperXY[i+1][2*j+1]+UpperXY[i+1][2*j+3]), 0)
            edgeCenter3 = (0.5*(UpperXY[i+1][2*j+2]+UpperXY[i][2*j+2]),   0.5*(UpperXY[i+1][2*j+3]+UpperXY[i][2*j+3]), 0)
            edgeCenter4 = (0.5*(UpperXY[i][2*j+2]+UpperXY[i][2*j+0]),     0.5*(UpperXY[i][2*j+3]+UpperXY[i][2*j+1]), 0)
            edges1 = s1.findAt((edgeCenter1, ))
            edges2 = s1.findAt((edgeCenter2, ))
            edges3 = s1.findAt((edgeCenter3, ))
            edges4 = s1.findAt((edgeCenter4, ))
            edges1 = (edges1, ); edges2 = (edges2, ); edges3 = (edges3, ); edges4 = (edges4, )
            # Create surfaces for all 4 edges of current element
            a.Surface(side1Edges=edges1, name='Surf-Upper-'+str(i)+'-'+str(j)+'-1') 
            a.Surface(side1Edges=edges2, name='Surf-Upper-'+str(i)+'-'+str(j)+'-2') 
            a.Surface(side1Edges=edges3, name='Surf-Upper-'+str(i)+'-'+str(j)+'-3')  
            a.Surface(side1Edges=edges4, name='Surf-Upper-'+str(i)+'-'+str(j)+'-4')  
    # Define interaction relations between lower and upper surfaces
    for i in range(nX):
        for j in range(nY-1):
            surfName1 = 'Surf-Upper-'+str(i)+'-'+str(j)+'-3'
            surfName2 = 'Surf-Upper-'+str(i)+'-'+str(j+1)+'-1'
            region1=a.surfaces[surfName1]; region2=a.surfaces[surfName2]
            contactName = 'Constraint-Upper-'+str(i)+str(j)+str(i)+str(j+1)+'-31'
            mdb.models[modelName].Tie(name=contactName, master=region1, slave=region2, 
                positionToleranceMethod=COMPUTED, adjust=ON, tieRotations=ON, thickness=ON)
    # Define interaction relations between left and right surfaces
    for i in range(nX-1):
        for j in range(nY):
            surfName1 = 'Surf-Upper-'+str(i)+'-'+str(j)+'-2'
            surfName2 = 'Surf-Upper-'+str(i+1)+'-'+str(j)+'-4'
            region1=a.surfaces[surfName1]; region2=a.surfaces[surfName2]
            contactName = 'Constraint-Upper-'+str(i)+str(j)+str(i+1)+str(j)+'-24'
            mdb.models[modelName].Tie(name=contactName, master=region1, slave=region2, 
                positionToleranceMethod=COMPUTED, adjust=ON, tieRotations=ON, thickness=ON)

    ## Create Lower interaction edges and define interaction relations 
    for i in range(nXL):
        for j in range(nYL):
            # Create instanceName named 'Part-Plate-i-j-1'
            instanceName = 'Part-Lower-'+str(i)+'-'+str(j)+'-1'
            # Lower:1, Right:2, Upper:3, Left:4
            s1 = a.instances[instanceName].edges
            # Edges are located in clockwise direction
            edgeCenter1 = (0.5*(LowerXY[i][2*j+0]+LowerXY[i+1][2*j+0]),   0.5*(LowerXY[i][2*j+1]+LowerXY[i+1][2*j+1]), 0)
            edgeCenter2 = (0.5*(LowerXY[i+1][2*j+0]+LowerXY[i+1][2*j+2]), 0.5*(LowerXY[i+1][2*j+1]+LowerXY[i+1][2*j+3]), 0)
            edgeCenter3 = (0.5*(LowerXY[i+1][2*j+2]+LowerXY[i][2*j+2]),   0.5*(LowerXY[i+1][2*j+3]+LowerXY[i][2*j+3]), 0)
            edgeCenter4 = (0.5*(LowerXY[i][2*j+2]+LowerXY[i][2*j+0]),     0.5*(LowerXY[i][2*j+3]+LowerXY[i][2*j+1]), 0)
            edges1 = s1.findAt((edgeCenter1, ))
            edges2 = s1.findAt((edgeCenter2, ))
            edges3 = s1.findAt((edgeCenter3, ))
            edges4 = s1.findAt((edgeCenter4, ))
            edges1 = (edges1, ); edges2 = (edges2, ); edges3 = (edges3, ); edges4 = (edges4, )
            # Create surfaces for all 4 edges of current element
            a.Surface(side1Edges=edges1, name='Surf-Lower-'+str(i)+'-'+str(j)+'-1')  # Lower
            a.Surface(side1Edges=edges2, name='Surf-Lower-'+str(i)+'-'+str(j)+'-2')  # Left
            a.Surface(side1Edges=edges3, name='Surf-Lower-'+str(i)+'-'+str(j)+'-3')  # Upper
            a.Surface(side1Edges=edges4, name='Surf-Lower-'+str(i)+'-'+str(j)+'-4')  # Right
    # Define interaction relations between lower and upper surfaces
    for i in range(nXL):
        for j in range(nYL-1):
            surfName1 = 'Surf-Lower-'+str(i)+'-'+str(j)+'-3'
            surfName2 = 'Surf-Lower-'+str(i)+'-'+str(j+1)+'-1'
            region1=a.surfaces[surfName1]; region2=a.surfaces[surfName2]
            contactName = 'Constraint-Lower-'+str(i)+str(j)+str(i)+str(j+1)+'-31'
            mdb.models[modelName].Tie(name=contactName, master=region1, slave=region2, 
                positionToleranceMethod=COMPUTED, adjust=ON, tieRotations=ON, thickness=ON)
    # Define interaction relations between left and right surfaces
    for i in range(nXL-1):
        for j in range(nYL):
            surfName1 = 'Surf-Lower-'+str(i)+'-'+str(j)+'-2'
            surfName2 = 'Surf-Lower-'+str(i+1)+'-'+str(j)+'-4'
            region1=a.surfaces[surfName1]; region2=a.surfaces[surfName2]
            contactName = 'Constraint-Lower-'+str(i)+str(j)+str(i+1)+str(j)+'-24'
            mdb.models[modelName].Tie(name=contactName, master=region1, slave=region2, 
                positionToleranceMethod=COMPUTED, adjust=ON, tieRotations=ON, thickness=ON)
 
    ## Create interaction edges of the wing tip
    instanceName = 'Part-Tip-1'
    s1 = a.instances[instanceName].edges
    for j in range(nY):
        edgeCenter1 = (0.5*(UpperXY[nX][2*j+0]+UpperXY[nX][2*(j+1)+0]), 0.5*(UpperXY[nX][2*j+1]+UpperXY[nX][2*(j+1)+1]), 0)
        edgeCenter2 = (0.5*(LowerXY[nXL][2*j+0]+LowerXY[nXL][2*(j+1)+0]), 0.5*(LowerXY[nXL][2*j+1]+LowerXY[nXL][2*(j+1)+1]), 0)
        edges1 = s1.findAt((edgeCenter1, ))
        edges2 = s1.findAt((edgeCenter2, ))
        edges1 = (edges1, ); edges2 = (edges2, )
        a.Surface(side1Edges=edges1, name='Surf-Upper-Tip-'+str(j))
        a.Surface(side1Edges=edges2, name='Surf-Lower-Tip-'+str(j)) 
    # Define interaction relations
    for j in range(nY):
        surfName1 = 'Surf-Upper-'+str(nX-1)+'-'+str(j)+'-2'
        surfName2 = 'Surf-Upper-Tip-'+str(j)
        surfName3 = 'Surf-Lower-'+str(nXL-1)+'-'+str(j)+'-2'
        surfName4 = 'Surf-Lower-Tip-'+str(j)
        region1=a.surfaces[surfName1]
        region2=a.surfaces[surfName2]
        region3=a.surfaces[surfName3]
        region4=a.surfaces[surfName4]
        contactName1 = 'Constraint-Upper-Tip-'+str(j)
        contactName2 = 'Constraint-Lower-Tip-'+str(j)
        mdb.models[modelName].Tie(name=contactName1, master=region1, slave=region2, 
            positionToleranceMethod=COMPUTED, adjust=ON, tieRotations=ON, thickness=ON)
        mdb.models[modelName].Tie(name=contactName2, master=region4, slave=region3, 
            positionToleranceMethod=COMPUTED, adjust=ON, tieRotations=ON, thickness=ON)

    ## Create boundary conditions for the assembly
    a = mdb.models[modelName].rootAssembly
    for j in range(nY):
        instanceName = 'Part-Upper-0-'+str(j)+'-1'
        e1 = a.instances[instanceName].edges
        edgeCenter = (0.5*(UpperXY[0][2*j+0]+UpperXY[0][2*(j+1)+0]), 0.5*(UpperXY[0][2*j+1]+UpperXY[0][2*(j+1)+1]), 0.0)
        edges1 = e1.findAt((edgeCenter, )); edges1 = (edges1, )
        setName = 'Set-Upper-0-'+str(j)+'-Fix'
        a.Set(edges=edges1, name=setName)
        # Set boundary conditions
        region = a.sets[setName]
        bcName = 'BC-Upper-0-'+str(j)+'-Fix'
        mdb.models[modelName].DisplacementBC(name=bcName, createStepName='Initial', region=region, u1=SET, u2=UNSET, ur3=SET, 
            amplitude=UNSET, distributionType=UNIFORM, fieldName='', localCsys=None)
    instanceName = 'Part-Upper-0-0-1'
    v1 = a.instances[instanceName].vertices
    vertexCenter = (UpperXY[0][0], UpperXY[0][1], 0.0)
    v = v1.findAt((vertexCenter, )); v = (v, )
    setName = 'Set-Upper-Origin-Fix'
    a.Set(vertices=v, name=setName)
    region = a.sets[setName]
    bcName = 'BC-Upper-Origin-Fix'
    # Origin fix in x-direction, y-direction, xy-rotation
    mdb.models[modelName].DisplacementBC(name=bcName, createStepName='Initial', region=region, u1=SET, u2=SET, ur3=SET, 
        amplitude=UNSET, distributionType=UNIFORM, fieldName='', localCsys=None)

    ## Create boundary conditions for the assembly
    a = mdb.models[modelName].rootAssembly
    for j in range(nYL):
        instanceName = 'Part-Lower-0-'+str(j)+'-1'
        e1 = a.instances[instanceName].edges
        edgeCenter = (0.5*(LowerXY[0][2*j+0]+LowerXY[0][2*(j+1)+0]), 0.5*(LowerXY[0][2*j+1]+LowerXY[0][2*(j+1)+1]), 0.0)
        edges1 = e1.findAt((edgeCenter, )); edges1 = (edges1, )
        setName = 'Set-Lower-0-'+str(j)+'-Fix'
        a.Set(edges=edges1, name=setName)
        # Set boundary conditions
        region = a.sets[setName]
        bcName = 'BC-Lower-0-'+str(j)+'-Fix'
        mdb.models[modelName].DisplacementBC(name=bcName, createStepName='Initial', region=region, u1=SET, u2=UNSET, ur3=SET, 
            amplitude=UNSET, distributionType=UNIFORM, fieldName='', localCsys=None)
    instanceName = 'Part-Lower-0-0-1'
    v1 = a.instances[instanceName].vertices
    vertexCenter = (LowerXY[0][0], LowerXY[0][1], 0.0)
    v = v1.findAt((vertexCenter, )); v = (v, )
    setName = 'Set-Lower-Origin-Fix'
    a.Set(vertices=v, name=setName)
    region = a.sets[setName]
    bcName = 'BC-Lower-Origin-Fix'
    # Origin fix in x-direction, y-direction, xy-rotation
    mdb.models[modelName].DisplacementBC(name=bcName, createStepName='Initial', region=region, u1=SET, u2=SET, ur3=SET, 
        amplitude=UNSET, distributionType=UNIFORM, fieldName='', localCsys=None)

    ## Define nodeSets that records the displacement information of the entire assembly
    ############# Upper #############
    # 1st: top-right vertices of all elements in the upper elements of the entire assembly
    a = mdb.models[modelName].rootAssembly
    for i in range(nX):
        nodeName = 'Node-Upper-'+str(i)+'-0'
        instanceName = 'Part-Upper-'+str(i)+'-0-1'
        v1 = a.instances[instanceName].vertices
        vertexCenter = (UpperXY[i+1][0], UpperXY[i+1][1], 0.0)
        v = v1.findAt((vertexCenter, )); v = (v, )
        a.Set(vertices=v, name=nodeName)
    # 2nd: leftmost vertex of all upper elements
    nodeName = 'Node-Upper-Origin'
    instanceName = 'Part-Upper-0-0-1'
    v1 = a.instances[instanceName].vertices
    vertexCenter = (UpperXY[0][0], UpperXY[0][1], 0.0)
    v = v1.findAt((vertexCenter, )); v = (v, )
    a.Set(vertices=v, name=nodeName)
    ############# Lower #############
    # 1st: bottom-right vertices of all elements in the lower elements of the entire assembly
    for i in range(nXL):
        nodeName = 'Node-Lower-'+str(i)+'-0'
        instanceName = 'Part-Lower-'+str(i)+'-0-1'
        v1 = a.instances[instanceName].vertices
        vertexCenter = (LowerXY[i+1][0], LowerXY[i+1][1], 0.0)
        v = v1.findAt((vertexCenter, )); v = (v, )
        a.Set(vertices=v, name=nodeName)
    # 2nd: leftmost vertex of all lower elements
    nodeName = 'Node-Lower-Origin'
    instanceName = 'Part-Lower-0-0-1'
    v1 = a.instances[instanceName].vertices
    vertexCenter = (LowerXY[0][0], LowerXY[0][1], 0.0)
    v = v1.findAt((vertexCenter, )); v = (v, )
    a.Set(vertices=v, name=nodeName)

    ## Define ambient temperature field
    a = mdb.models[modelName].rootAssembly
    allFaceSet = []
    for i in range(nX):
        for j in range(nY):
            instanceName = 'Part-Upper-'+str(i)+'-'+str(j)+'-1'
            f1 = a.instances[instanceName].faces
            faces = f1.getSequenceFromMask(mask=('[#1 ]', ), )
            allFaceSet.append(faces)
    for i in range(nXL):
        for j in range(nYL):
            instanceName = 'Part-Lower-'+str(i)+'-'+str(j)+'-1'
            f1 = a.instances[instanceName].faces
            faces = f1.getSequenceFromMask(mask=('[#1 ]', ), )
            allFaceSet.append(faces)
    instanceName = 'Part-Tip-1'
    f1 = a.instances[instanceName].faces
    faces = f1.getSequenceFromMask(mask=('[#1 ]', ), )
    allFaceSet.append(faces)
    allFaceSet =tuple(allFaceSet)
    setName = 'Set-UpperLower-AllFace'
    a.Set(faces=allFaceSet, name=setName)
    region = a.sets[setName]
    mdb.models[modelName].Temperature(name='Predefined Field-Temperature', createStepName='Initial', region=region, 
        distributionType=UNIFORM, crossSectionDistribution=CONSTANT_THROUGH_THICKNESS, magnitudes=(initialT, ))
    mdb.models[modelName].predefinedFields['Predefined Field-Temperature'].setValuesInStep(
        stepName='Step-ThermalExpansion', magnitudes=(finalT, ))

    ## Create job and submit. Set parallel computing
    jobName = 'Job-Iter'+str(iter)+'-Num'+str(nmodel)
    mdb.Job(name=jobName, model=modelName, description='', type=ANALYSIS, atTime=None, waitMinutes=0, waitHours=0, 
        queue=None, memory=90, memoryUnits=PERCENTAGE, getMemoryFromAnalysis=True, explicitPrecision=SINGLE, 
        nodalOutputPrecision=SINGLE, echoPrint=OFF, modelPrint=OFF, contactPrint=OFF, historyPrint=OFF, 
        userSubroutine='', scratch='', resultsFormat=ODB, parallelizationMethodExplicit=DOMAIN, 
        numDomains=numDomainsCPUs, activateLoadBalancing=False, multiprocessingMode=THREADS, numCpus=numDomainsCPUs)     
    mdb.jobs[jobName].submit(consistencyChecking=OFF)
    mdb.jobs[jobName].waitForCompletion()
    print 'The analysis has been completed. On going postprocessing'

    ## Visualization
    myOdb = visualization.openOdb(path = jobName + '.odb')
    myViewport = session.Viewport(name='Viewport-'+modelName, origin =(0.0, 0.0), width=240, height=90)
    myViewport.setValues(displayedObject = myOdb)
    # myViewport.view.setValues(viewOffsetY=offset*nY*ylength)  # Move center of the viewport upward
    myViewport.odbDisplay.display.setValues(plotState=(CONTOURS_ON_UNDEF, CONTOURS_ON_DEF, ))
    myViewport.odbDisplay.commonOptions.setValues(visibleEdges=NONE)
    myViewport.odbDisplay.superimposeOptions.setValues(visibleEdges=NONE)
    myViewport.odbDisplay.commonOptions.setValues(renderStyle = FILLED)
    myViewport.odbDisplay.setPrimaryVariable(variableLabel='U', outputPosition=NODAL, refinement=(COMPONENT, 'U2'))
    myViewport.viewportAnnotationOptions.setValues(triad=OFF, title=OFF, state=OFF, compass=OFF)
    myViewport.viewportAnnotationOptions.setValues(legendFont='-*-verdana-medium-r-normal-*-*-80-*-*-p-*-*-*')
    myViewport.viewportAnnotationOptions.setValues(legendBox=OFF)
    fileName = 'U2-Iter'+str(iter)+'-Num'+str(nmodel)
    session.printToFile(fileName = fileName, format = PNG, canvasObjects = (myViewport, ))
    print 'File ' + fileName + ' has been saved in the working directory. Please check!'

    ## Obtain the last frame of the analysis
    odb = openOdb(path = jobName + '.odb')
    assembly = odb.rootAssembly
    # First step + Last frame of the simulation
    step1 = odb.steps['Step-ThermalExpansion']
    lastFrame = step1.frames[-1]

    UpperCoordinates, LowerCoordinates = [], []
    for i in range(nX):
        nodeName = 'NODE-UPPER-'+str(i)+'-'+str(0)
        nodes = assembly.nodeSets[nodeName]
        displacement = lastFrame.fieldOutputs['U']
        nodesDisplacement = displacement.getSubset(region = nodes)
        # coordinates stores the target coordinates of bottom nodes
        UpperCoordinates.append([UpperXY[i+1][0]+nodesDisplacement.values[0].data[0], 
            UpperXY[i+1][1]+nodesDisplacement.values[0].data[1]])
    for i in range(nXL):
        nodeName = 'NODE-LOWER-'+str(i)+'-'+str(0)
        nodes = assembly.nodeSets[nodeName]
        displacement = lastFrame.fieldOutputs['U']
        nodesDisplacement = displacement.getSubset(region = nodes)
        # coordinates stores the target coordinates of bottom nodes
        LowerCoordinates.append([LowerXY[i+1][0]+nodesDisplacement.values[0].data[0], 
            LowerXY[i+1][1]+nodesDisplacement.values[0].data[1]])

    # Calculate squared error
    def SquaredErrorUpper(xy):
        return (ShapeUpper(xy[0])-xy[1])**2
    def SquaredErrorLower(xy):
        return (ShapeLower(xy[0])-xy[1])**2

    # Defines the target shape
    def ShapeUpper(x):
        a=(1.0*UpperOrigin[1])/(1.0*scaling-UpperOrigin[0])**2
        return a*((x-UpperOrigin[0])**2)+UpperOrigin[1]
    def ShapeLower(x):
        b=(2.0*UpperOrigin[1]-LowerOrigin[1])/(1.0*scaling-LowerOrigin[0])**2
        return b*((x-LowerOrigin[0])**2)+LowerOrigin[1]
    
    RMSE = ((sum(map(SquaredErrorUpper, UpperCoordinates))+sum(map(SquaredErrorLower, LowerCoordinates)))**0.5)/(len(UpperCoordinates)+len(LowerCoordinates))
    del mdb.models[modelName]
    del mdb.jobs[jobName]
    odb.close()
    return RMSE,