Example 13 for “Python Scripts for ABAQUS: Learn by Example”

someone cold help me?
I’m trying to do the example 13 of “Python Scripts for ABAQUS: Learn by Example”, but it isn’t working.

Whem the script arrives at “while float(max_stress) < max_acceptable_stress:” it’s runing in loop for the same increment of concentrated force (5) and consequently not incrementing it.
I left the complete script below so we can check for any errors.

from abaqus import * 
from abaqusConstants import * 
import regionToolset
import displayGroupOdbToolset as dgo
import job
import odbAccess
import os

session.viewports['Viewport: 1'].setValues(displayedObject=None)

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

#Criando o modelo
mdb.models.changeKey(fromName='Model-1', toName='Plate Bending Model')
plateModel = mdb.models['Plate Bending Model']

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

#Criando a part
import sketch
import part

#a) Esboce a placa usando a ferramenta retângulo
plateProfileSketch = plateModel.ConstrainedSketch(name='Plate Sketch',
                                                        sheetSize=20)
plateProfileSketch.rectangle(point1=(0.0,0.0), point2=(5.0,3.0))

#b) Crie um shell chamado "Plate" usando o esboço
platePart=plateModel.Part(name='Plate', dimensionality=THREE_D,
                                        type=DEFORMABLE_BODY)
platePart.BaseShell(sketch=plateProfileSketch)

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

#Criando material
import material

#Criando material AISI 1005 Steel atribuindo densidade de massa, módulo de elasticidade e coeficiente de poisson
plateMaterial = plateModel.Material(name='AISI 1005 Steel')
plateMaterial.Density(table=((7872, ),       ))
plateMaterial.Elastic(table=((200E9, 0.29), ))

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

#criar uma seção de casca homogênea com espessura de 0,1m e atribuir a placa a ela
import section

#Criando uma sessão para atribuir ao plate
plateSection = plateModel.HomogeneousShellSection(name='Plate Section',
                                                  material='AISI 1005 Steel',
                                                  thicknessType=UNIFORM,
                                                  thickness=0.1, preIntegrate=OFF,
                                                  idealization=NO_IDEALIZATION,
                                                  thicknessField='',
                                                  poissonDefinition=DEFAULT,
                                                  thicknessModulus=None,
                                                  temperature=GRADIENT,
                                                  useDensity=OFF,
                                                  nodalThicknessField='',
                                                  integrationRule=SIMPSON,
                                                  numIntPts=5)
    
#Atribuindo o plate na sessão 
plate_face_point = (2.5, 1.5, 0.0)
plate_face = platePart.faces.findAt((plate_face_point,))
plate_region = (plate_face,)
    
platePart.SectionAssignment(region=plate_region, sectionName='Plate Section',
                            offset=0.0, offsetType=MIDDLE_SURFACE, offsetField='')
                                
#-------------------------------------
    
#Criando o assembly
import assembly
    
#Criando a part instance
plateAssembly = plateModel.rootAssembly
plateInstance = plateAssembly.Instance(name='Plate Instance', part=platePart,
                                                                  dependent=ON)
                                                                  
#------------------------------------

#Criando o step 

import step

#criando um step geral estatico
plateModel.StaticStep(name='Load Step', previous='Initial', 
                        description='Aplicando carga concentrada nesse step')
#------------------------------------
   
#Criando o field output request
    
#mudando o nome de 'F-Output-1' para 'Output Stresses and Displacements'
plateModel.fieldOutputRequests.changeKey(fromName='F-Output-1',
                                          toName='Output Stresses and Displacements')
                                             
#Como "F-Output-1" é aplicado na etapa "Aply Load" por padrão, "Selected Field Outputs" também será.
#Precisamos apenas definir as variáveis ​​​​necessárias.
plateModel.fieldOutputRequests['Output Stresses and Displacements']
                                                .setValues(variables=('S','U'))
#----------------------------

#Criando o history output request

#Não queremos nenhum history outputs, então vamos deletar o existente "H-Output-1"
del plateModel.historyOutputRequests['H-Output-1']

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

#Aplicando condições de contorno - fixando uma aresta
fixed_edge = plateInstance.edges.findAt(((0.0,1.5,0.0), ))
fixed_edge_region=regionToolset.Region(edges=fixed_edge)

plateModel.DisplacementBC(name='FixEdge', createStepName='Initial',
                          region=fixed_edge_region,
                          u1=SET, u2=SET, u3=SET, ur1=SET, ur2=SET, ur3=SET,
                          amplitude=UNSET, distributionType=UNIFORM, fieldName='',
                          localCsys=None)

# Em vez de usar as condições de contorno de deslocamentos/rotações e configurar 
# os seis graus de liberdade (DoF) para zero
# Poderíamos simplesmente ter usado a condição de Encastre com a seguinte instrução
plateModel.EncastreBC(name='Encastre edge', createStepName='Initial',
                                            region=fixed_edge_region)                          

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

#Criando vertices para aplicar cargas concentradas atraves de partitioning part

#Criando datum points
platePart.DatumPointByCoordinate(coords=(0.0,1.0,0.0))
platePart.DatumPointByCoordinate(coords=(0.0,2.0,0.0)) 
platePart.DatumPointByCoordinate(coords=(5.0,1.0,0.0)) 
platePart.DatumPointByCoordinate(coords=(5.0,2.0,0.0)) 

#Atribuindo os datum points nas variaveis
#Abaqus salva os 4 datum points em platePart.datums
#Desde que suas chaves estejam ou não iniciando em 0, coloque as chaves em um array salvo
#em ordem crescente
platePart_datums_keys = platePart.datums.keys()
platePart_datums_keys.sort()

plate_datum_point_1 = platePart.datums[platePart_datums_keys[0]]
plate_datum_point_2 = platePart.datums[platePart_datums_keys[1]]
plate_datum_point_3 = platePart.datums[platePart_datums_keys[2]]
plate_datum_point_4 = platePart.datums[platePart_datums_keys[3]]

#Selecionando toda a face e particionando usando dois pontos

partition_face_pt = (2.5,1.5,0.0)
partition_face = platePart.faces.findAt((partition_face_pt, ))
platePart.PartitionFaceByShortestPath(point1=plate_datum_point_1,
                                      point2=plate_datum_point_3,
                                      faces=partition_face)

#Agora que existem duas faces, selecionamos aquela que precisas ser particionada
partition_face_pt = (2.5, 2.0, 0.0)
partition_face = platePart.faces.findAt((partition_face_pt, ))
platePart.PartitionFaceByShortestPath(point1=plate_datum_point_2,
                                      point2=plate_datum_point_4,
                                      faces=partition_face)
                                     
#Com as partições criadas, podemos extrair os vertices
vertices_for_concentrated_force = plateInstance.vertices 
                                                .findAt(((5.0,1.0,0.0),),
                                                ((5.0,2.0,0.0),),)
                                                
#----------------------------------------

#Criando a malha
import mesh

#setando o tipo de elemento
plate_mesh_region = plate_region

elemType1 = mesh.ElemType(elemCode=S8R, elemLibrary=STANDARD)
elemType2 = mesh.ElemType(elemCode=STRI65, elemLibrary=STANDARD)

platePart.setElementType(regions=plate_mesh_region, elemTypes=(elemType1, elemType2))

#Gerando arestas pelo numero
mesh_edges_vertical = platePart.edges.findAt(((0.0,0.5,0.0), ),
                                             ((0.0,1.5,0.0), ),
                                             ((0.0,2.5,0.0), ),
                                             ((5.0,0.5,0.0), ),
                                             ((5.0,1.5,0.0), ),
                                             ((5.0,2.5,0.0), ))
                                             

mesh_edges_horizontal = platePart.edges.findAt(((2.5,0.0,0.0), ),
                                               ((2.5,1.0,0.0), ),
                                               ((2.5,2.0,0.0), ),
                                               ((2.5,3.0,0.0), ))
                                               
platePart.seedEdgeByNumber(edges=mesh_edges_vertical, number = 3)
platePart.seedEdgeByNumber(edges=mesh_edges_horizontal, number = 10)

platePart.generateMesh()

#ATE AQUI FUNCIONANDO!

#IIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIII
#**********************************************************************************


#               ANALISE ITERATIVA COMEÇA AQUI!!!

# Faça alterações aqui:
concentrated_force_initial_guess = 5
concentrated_force_guess_increment_size = 5
max_acceptable_stress = 35E+3

max_stress = 0
concentrated_force = concentrated_force_initial_guess
force_list = []
stress_list = []

while float(max_stress) < max_acceptable_stress:
    # Remover a força existente, se houver
    if 'Concentrated Forces' in plateModel.loads.keys():
        del plateModel.loads['Concentrated Forces']
    
    
    # Aplicar a nova carga concentrada
    plateModel.ConcentratedForce(
        name='Concentrated Forces',
        createStepName='Load Step',
        region=(vertices_for_concentrated_force,),
        cf3=-concentrated_force,
        distributionType=UNIFORM
    )
    
    # Criar e rodar o Job
    
    
    job_name = 'PlateJob'+repr(concentrated_force)+'N'
    
    
    mdb.Job(name=job_name, model='Plate Bending Model', type=ANALYSIS,
                            description='Job simulates the bending of a plate')
    
    #roda o job
    mdb.jobs[job_name].submit(consistencyChecking=OFF)
    
    #não retorna até o job acabar de rodar
    mdb.jobs[job_name].waitForCompletion()
    
    # Abrir o .odb e processar os resultados
    plate_viewport = session.Viewport(name='Plate Results Viewport for force of ' + repr(concentrated_force) + 'N')
    plate_Odb_Path = job_name + '.odb'    
    an_odb_object = session.openOdb(name=plate_Odb_Path)
    plate_viewport.setValues(displayedObject=an_odb_object)
    plate_viewport.odbDisplay.display.setValues(plotState=(CONTOURS_ON_DEF, ))
    
    # Relatar tensões em ordem decrescente
    
    session.viewports['Viewport: 1'].setValues(displayedObject=an_odb_object)
    session.fieldReportOptions.setValues(sort=DESCENDING)

    report_name_and_path = 'PlateReport' + repr(concentrated_force) + 'N.rpt'
    
    session.writeFieldReport(
        fileName=report_name_and_path,
        append=OFF,
        sortItem='S.Mises',
        odb=an_odb_object,
        step=0,
        frame=1,
        outputPosition=INTEGRATION_POINT,
        variable=(('S', INTEGRATION_POINT, ((INVARIANT, 'Mises'),)),)
    )
    
    extracted_line = ''
    
    f=open(report_name_and_path)
    for line in f:
        str=line
        if 'Maximum' in str:
            extracted_line = str
            break
    
    extracted_list = extracted_line.split()
    max_stress = float(extracted_list[2])  # Converter tensão máxima para float
    
    print("depois dos comando extracted line")
    print(max_stress)
    # Adicionar força e tensão às listas
    force_list.append(concentrated_force)
    stress_list.append(max_stress)

    # Incrementar a carga para a próxima iteração
    concentrated_force += concentrated_force_guess_increment_size
    print("apos incremetar a carga")
    
    
# Produzindo uma tabela de força e tensão
try:
    os.makedirs('C:/SimulationResults/')
except FileExistsError:
    print("! Diretório já existe. Continuando...")

with open('C:/SimulationResults/iterative_analysis.txt', 'w') as g:
    g.write('Force t Max Stress n')

    for i in range(len(force_list)):
        g.write(f"{force_list[i]}t{stress_list[i]}n")

    g.write('nn')
    g.write(
        f"A força que está causando a tensão máxima admissível de {max_acceptable_stress} N está entre "
        f"{force_list[-2]} N e {force_list[-1]} N."
    )
    
#g.close()


#                   ANALISE ITERATIVA ACABA AQUI!!!
#*************************************************************************************
#IIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIII


# Determinando quais elementos excedem a tensão máxima admissível
highlight_element_list = []

with open(report_name_and_path) as h:
    # No arquivo de relatório, a tabela começa após uma linha cheia de caracteres '-'.
    # Extraia as linhas uma por uma até que essa linha seja encontrada.
    for line in h:
        if '------------------------------------' in line:
            break
        
    # Lendo as linhas da tabela uma de cada vez
    for line in h:
        if not line.strip():  # Verifica se a linha está vazia
            break
        str_list = line.split()
        # Verifica se a tensão excede o limite permitido
        if float(str_list[3]) > max_acceptable_stress:
            highlight_element_list.append(str_list[0])

# Convertendo a lista para tupla
highlight_element_tuple = tuple(highlight_element_list)

# Alterando a cor dos elementos na viewport onde a tensão excedeu o máximo admissível
plate_viewport.setColor(initialColor='FFFF00', translucency=0.4)

leaf = dgo.LeafFromModelElemLabels(
    elementLabels=(('PLATE INSTANCE', highlight_element_tuple),)
)

plate_viewport.odbDisplay.display.setValues(plotState=(DESFORMED,))
plate_viewport.setColor(leaf=leaf, fillColor='Red')

# Imprimindo uma mensagem para o usuário na área de mensagem
print('*********************************')
print('Otimização completada!')
print('Múltiplos viewports foram criados, um para cada simulação.n')
print('Eles podem aparecer um acima do outro, e você precisará movê-los ' +
      'pela tela para revelar os que estão atrás.n')
print('A última viewport a ser criada (a que está no topo) destaca em vermelho os elementos que excedem a tensão máxima admissível.n')

I dont know what Im suposed to do or try to fix it.

New contributor

EWERSON DOS SANTOS RODRIGUES is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.

Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa Dịch vụ tổ chức sự kiện 5 sao Thông tin về chúng tôi Dịch vụ sinh nhật bé trai Dịch vụ sinh nhật bé gái Sự kiện trọn gói Các tiết mục giải trí Dịch vụ bổ trợ Tiệc cưới sang trọng Dịch vụ khai trương Tư vấn tổ chức sự kiện Hình ảnh sự kiện Cập nhật tin tức Liên hệ ngay Thuê chú hề chuyên nghiệp Tiệc tất niên cho công ty Trang trí tiệc cuối năm Tiệc tất niên độc đáo Sinh nhật bé Hải Đăng Sinh nhật đáng yêu bé Khánh Vân Sinh nhật sang trọng Bích Ngân Tiệc sinh nhật bé Thanh Trang Dịch vụ ông già Noel Xiếc thú vui nhộn Biểu diễn xiếc quay đĩa Dịch vụ tổ chức tiệc uy tín Khám phá dịch vụ của chúng tôi Tiệc sinh nhật cho bé trai Trang trí tiệc cho bé gái Gói sự kiện chuyên nghiệp Chương trình giải trí hấp dẫn Dịch vụ hỗ trợ sự kiện Trang trí tiệc cưới đẹp Khởi đầu thành công với khai trương Chuyên gia tư vấn sự kiện Xem ảnh các sự kiện đẹp Tin mới về sự kiện Kết nối với đội ngũ chuyên gia Chú hề vui nhộn cho tiệc sinh nhật Ý tưởng tiệc cuối năm Tất niên độc đáo Trang trí tiệc hiện đại Tổ chức sinh nhật cho Hải Đăng Sinh nhật độc quyền Khánh Vân Phong cách tiệc Bích Ngân Trang trí tiệc bé Thanh Trang Thuê dịch vụ ông già Noel chuyên nghiệp Xem xiếc khỉ đặc sắc Xiếc quay đĩa thú vị
Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa
Thiết kế website Thiết kế website Thiết kế website Cách kháng tài khoản quảng cáo Mua bán Fanpage Facebook Dịch vụ SEO Tổ chức sinh nhật