【sap2000】【python】python相关的3个案例-1/3

python相关的3个案例

Python COM,Python NET,IronPython的区别

这三个术语都与 Python 语言和其他编程平台(尤其是 Microsoft .NET 及其组件)之间的互操作性有关。我们来看看它们之间的主要区别:

  1. Python COM(Python for COM,Python 和 Component Object Model 的互操作性):Python COM 是一种让 Python 脚本和基于 Component Object Model(COM)的应用程序进行互操作的方法。COM 是一个用于创建和使用可重用组件的二进制接口标准,广泛应用于 Windows 系统中。通过 Python COM,Python 脚本可以创建和控制 COM 对象,例如 Microsoft Word 或 Excel。Python COM 的一种实现是 pywin32 库,它提供了 Python 访问 COM 对象和 Windows API 的能力。

  2. Python NET(Python for .NET,Python 和 .NET Framework 的互操作性):Python NET 是一种让 Python 脚本和基于 .NET Framework 的应用程序进行互操作的方法。.NET Framework 是一个由 Microsoft 开发的软件开发框架,用于构建和运行 Windows 应用程序。通过 Python NET,Python 脚本可以直接调用 .NET 组件和库。

    一个常见的 Python NET 实现是 pythonnet 库,它允许 Python 与 .NET 程序的互操作,例如,可以在 Python 脚本中调用 .NET 库和类,或在 .NET 应用程序中执行 Python 脚本。

  3. IronPython:IronPython 是一个 Python 语言的实现,它是基于 .NET Framework 的。与 CPython(Python 的默认实现)不同,IronPython 使用了 .NET 运行时和类库,这使得 IronPython 脚本可以更容易地与其他 .NET 语言(如 C#、VB.NET 等)编写的应用程序进行互操作。IronPython 允许开发人员在 .NET 环境中使用 Python 语法和特性,同时保持与 .NET 生态系统的紧密集成。

总之,Python COM 和 Python NET 都是在标准 Python(即 CPython)中实现与其他技术(COM 和 .NET)的互操作性的库。而 IronPython 是一个基于 .NET Framework 的 Python 语言实现,本身具有与 .NET 组件的紧密集成。

Python COM,Python NET,IronPython适合应用的场景

这三种 Python 技术的应用场景各自不同,它们在特定情况下都有实际应用。下面是这三种技术的典型应用场景:

  1. Python COM(Python for COM):Python COM 主要用于与基于 COM 的应用程序进行互操作。这些程序通常是 Windows 平台上的传统软件,如 Microsoft Office 套件(Word、Excel、Outlook 等)。通过 Python COM,您可以编写自动化脚本来操作这些应用程序,例如创建 Word 文档、处理 Excel 工作簿、发送 Outlook 电子邮件等。Python COM 还可以用于与其他使用 COM 技术的软件系统进行交互,如一些工程模拟软件、图形处理程序等。

  2. Python NET(Python for .NET):Python NET 的主要应用场景是与基于 .NET Framework 的应用程序进行互操作。这些应用程序可能是用 C#、VB.NET 等 .NET 语言编写的。通过 Python NET,您可以在 Python 脚本中调用 .NET 类库和组件,这使得 Python 能够访问在 .NET 生态系统中编写的功能。这在需要在 Python 应用程序中集成现有 .NET 代码或使用 .NET 提供的特定功能时非常有用。

  3. IronPython:IronPython 的应用场景通常是在 .NET 环境中使用 Python 语言进行软件开发。由于 IronPython 是基于 .NET Framework 的 Python 实现,它与其他 .NET 语言(如 C#、VB.NET 等)具有良好的互操作性。使用 IronPython,您可以在 .NET 应用程序中运行 Python 脚本、使用 .NET 类库,甚至将 Python 代码与其他 .NET 代码混合在一起。IronPython 在需要使用 Python 语法和特性进行 .NET 开发时特别有用。

这些技术在实际应用中的使用频率取决于特定领域和项目需求。例如,在自动化 Microsoft Office 应用程序的任务中,Python COM 可能会更常用;而在需要与现有 .NET 代码集成的 Python 项目中,Python NET 或 IronPython 可能会更受欢迎。在选择这些技术时,请务必考虑您的具体需求和目标。

常用的.NET 类库和组件

.NET 类库和组件包括了一系列用于构建和运行 .NET 应用程序的类、接口、值类型、属性和事件。这些类库和组件提供了丰富的功能,以帮助开发者更轻松地开发应用程序。以下是 .NET 类库和组件的一些主要类别:

  1. 基础类库(Base Class Library,BCL):BCL 提供了一组核心功能,如文件 I/O(输入/输出)、字符串处理、数据结构、算法等。这些基础功能为 .NET 开发者提供了一个共享的基础平台。

  2. 运行时(Runtime):.NET 运行时(例如,.NET Framework、.NET Core 和 .NET 5+)负责在目标平台上执行 .NET 代码。它们包括垃圾回收、异常处理、安全性和其他与执行 .NET 代码相关的功能。

  3. ASP.NET:ASP.NET 是一个用于构建 Web 应用程序和服务的框架。它提供了一组基于 .NET 的工具和库,用于创建并托管动态网站、Web API 和实时 Web 应用程序。

  4. Entity Framework(EF):Entity Framework 是一个流行的对象关系映射(ORM)框架,用于简化 .NET 应用程序中的数据访问。EF 允许开发者使用 .NET 对象和 LINQ 查询直接操作数据库,而无需编写复杂的 SQL 代码。

  5. Windows Presentation Foundation(WPF):WPF 是一个用于构建丰富的桌面应用程序界面的 UI 框架。它提供了基于 XAML 的声明式编程模型,以及为 2D 和 3D 图形、动画和媒体提供支持的强大渲染引擎。

  6. Windows Forms(WinForms):Windows Forms 是一个用于构建 Windows 桌面应用程序的图形界面框架。尽管较旧,但它仍然广泛用于构建传统的 Windows 客户端应用程序。

  7. Windows Communication Foundation(WCF):WCF 是一个用于构建服务导向架构(SOA)应用程序的框架。它允许开发者创建基于消息传递的分布式应用程序和服务。

  8. Xamarin:Xamarin 是一个基于 .NET 的跨平台移动应用开发框架。它允许开发者使用 C# 编写代码并在 iOS、Android 和 Windows 上共享大部分代码。

此外,还有许多其他 .NET 类库和组件,例如 ML.NET(用于机器学习应用程序)、SignalR(用于实时 Web 通信)等。这些类库和组件可以帮助开发者在各种领域构建丰富、高性能的应用程序。

Example 7 (Python COM)

Remarks

This example was created using Python 3.9.7. It is based on the Sap2000 verification problem Example 1-001.

This example creates the example verification problem from scratch, runs the analysis, extracts results, and compares the results with hand calculated values.

该案例从头开始(from scratch)创建一个实例验证问题(the example verification problem)、运行分析、提取结果、比较结果与手算值。

Example

  1. Download and install Python 3.9.7 or higher for Windows. Python is freely available at python.org.

  2. Install the Python package “comtypes”. This example was created using comtypes version 1.1.14 . If you are using Python 3.4 or higher, the easiest way to install this package is by opening a command prompt with administrative privileges and entering the command:

    comtypes 是一个纯 Python 包,用于处理 Microsoft COM (Component Object Model) 组件对象模型技术。COM 是一种跨编程语言的二进制接口标准,允许不同编程语言编写的组件相互通信和互操作。comtypes 库提供了一种简便的方式,让 Python 可以轻松地与 COM 组件进行交互。

    comtypes 的主要功能和优势包括:

    1. 动态类型:comtypes 可以动态创建和访问 COM 接口和对象,无需预先编写类型库(.tlb)或生成的 Python 包装器。
    2. 自动类型库处理:comtypes 可以直接从类型库中获取接口信息,并在运行时生成所需的 Python 类。
    3. 简化的错误处理:comtypes 会将 COM 错误自动转换为 Python 异常,简化了错误处理过程。
    4. 支持回调函数:comtypes 可以处理事件回调,允许 Python 函数作为事件处理器。
    5. 跨平台兼容:comtypes 支持 Windows 和其他平台上的 Python 运行时。

    comtypes 常用于与如 Microsoft Office、ArcGIS 等应用程序的 COM 组件进行交互。通过使用 comtypes,Python 开发者可以访问和操作这些应用程序中的数据和功能。

  3. Create a Python .py file using IDLE or any text editor and paste in the following code. Please pay attention to the comments(注释) in this code block; they contain important information about running the script.

Please note that the Remote API is not available for Python client applications using COM.

import os

import sys

import comtypes.client

 

#set the following flag to True to attach to an existing instance of the program

#otherwise a new instance of the program will be started
#将下列标志AttachToInstance设置为True,以附加到程序的现有实例
#否则将启动程序的新实例

AttachToInstance = False

AttachToInstance = False

 

#set the following flag to True to manually specify the path to SAP2000.exe

#this allows for a connection to a version of SAP2000 other than the latest installation

#otherwise the latest installed version of SAP2000 will be launched

SpecifyPath = False

 

#if the above flag is set to True, specify the path to SAP2000 below

#ProgramPath = 'C:\Program Files\Computers and Structures\SAP2000 24\SAP2000.exe'
#full path to the model

#set it to the desired path of your model



APIPath = 'C:\CSiAPIexample' #APIPath的完整路径

if not os.path.exists(APIPath): #将其设置为模型ModelPath所需的路径

        try:

            os.makedirs(APIPath)

        except OSError:

            pass

ModelPath = APIPath + os.sep + 'API_1-001.sdb' 

"""
os.sep是Python内置模块os中的一个字符串常量,表示操作系统路径中的分隔符。
在Windows操作系统中,分隔符为反斜杠(\),而在Unix和类Unix系统(如Linux和macOS)中,分隔符为正斜杠(/)。
为了编写跨平台的Python代码,可以使用os.sep来代替硬编码分隔符,从而使代码在不同的操作系统上都能正确地工作
"""

'\nos.sep是Python内置模块os中的一个字符串常量,表示操作系统路径中的分隔符。\n在Windows操作系统中,分隔符为反斜杠(\\),而在Unix和类Unix系统(如Linux和macOS)中,分隔符为正斜杠(/)。\n为了编写跨平台的Python代码,可以使用os.sep来代替硬编码分隔符,从而使代码在不同的操作系统上都能正确地工作\n'
#create API helper object

helper = comtypes.client.CreateObject('SAP2000v1.Helper')

# SAP2000v1.Helper 是一个封装了 SAP2000 应用程序的一些功能的 COM 类。通过与这个 COM 组件进行交互,你可以使用 Python 或其他编程语言来控制 SAP2000。
# 这可以用于自动化一些任务,例如模型创建、分析和结果提取等。这样的自动化可以提高工作效率,减少人为错误,并允许更复杂的分析。

helper = helper.QueryInterface(comtypes.gen.SAP2000v1.cHelper)

# 调用了 helper.QueryInterface 方法来获取一个与 'SAP2000v1.cHelper' 接口兼容的对象。
# comtypes.gen.SAP2000v1.cHelper 是由 comtypes 自动生成的一个接口描述。
# 现在,可以使用 helper 对象来调用 SAP2000 软件的 API 方法。


"""
这段代码的目的是连接到一个正在运行的 SAP2000 实例,或者创建一个新的 SAP2000 实例。代码中使用了几个条件分支来处理不同的情况:

1. 如果 `AttachToInstance` 为 `True`,代码将尝试连接到一个已经运行的 SAP2000 实例。
通过调用 `helper.GetObject("CSI.SAP2000.API.SapObject")` 方法,它试图获取活动的 `SapObject`。
如果连接失败,将会捕获 `OSError` 或 `comtypes.COMError` 异常,并打印一条错误消息,然后退出程序。

2. 如果 `AttachToInstance` 为 `False`,代码将尝试创建一个新的 SAP2000 实例。这里有两种情况:

   a. 如果 `SpecifyPath` 为 `True`,代码将尝试从给定的 `ProgramPath` 创建一个新的 SAP2000 实例。
   如果创建失败,将会捕获 `OSError` 或 `comtypes.COMError` 异常,并打印一条错误消息,然后退出程序。

   b. 如果 `SpecifyPath` 为 `False`,代码将尝试从最新安装的 SAP2000 版本创建一个新的实例。
   这是通过调用 `helper.CreateObjectProgID("CSI.SAP2000.API.SapObject")` 方法实现的。
   如果创建失败,将会捕获 `OSError` 或 `comtypes.COMError` 异常,并打印一条错误消息,然后退出程序。

3. 如果成功创建了一个新的 SAP2000 实例,代码将调用 `mySapObject.ApplicationStart()` 方法启动 SAP2000 应用程序。

总之,这段代码的作用是连接到现有的 SAP2000 实例或创建新的实例,以便你可以使用 Python 脚本控制 SAP2000。
在成功连接或创建实例之后,你可以使用 `mySapObject` 对象来调用 SAP2000 API 的方法,以实现与 SAP2000 模型的交互。

"""

if AttachToInstance:

    #attach to a running instance of SAP2000

    try:

        #get the active SapObject

            mySapObject = helper.GetObject("CSI.SAP2000.API.SapObject") 

    except (OSError, comtypes.COMError):

        print("No running instance of the program found or failed to attach.")

        sys.exit(-1)

else:

 

    if SpecifyPath:

        try:

            #'create an instance of the SAPObject from the specified path

            mySapObject = helper.CreateObject(ProgramPath)

        except (OSError, comtypes.COMError):

            print("Cannot start a new instance of the program from " + ProgramPath)

            sys.exit(-1)

    else:

        try:

            #create an instance of the SAPObject from the latest installed SAP2000

            mySapObject = helper.CreateObjectProgID("CSI.SAP2000.API.SapObject")

        except (OSError, comtypes.COMError):

            print("Cannot start a new instance of the program.")

            sys.exit(-1)

 

    #start SAP2000 application

    mySapObject.ApplicationStart()
    

运行结果,start SAP2000 application
image-20230704162747905

"""
创建新的模型SapModel对象,初始化InitializeNewModel并创建一个new blank model
"""
#create SapModel object

SapModel = mySapObject.SapModel

 

#initialize model

SapModel.InitializeNewModel()

 

#create new blank model

ret = SapModel.File.NewBlank()

image-20230704152615198

# 定义材料CONC
#define material property

MATERIAL_CONCRETE = 2

ret = SapModel.PropMaterial.SetMaterial('CONC', MATERIAL_CONCRETE)

image-20230704162854636

SetMaterial解析

Syntax

SapObject.SapModel.PropMaterial.SetMaterial

VB6 Procedure

Function SetMaterial(ByVal Name As String, ByVal MatType As eMatType, Optional ByVal Color As Long = -1, Optional ByVal Notes As String = “”, Optional ByVal GUID As String = “”) As Long
这是一个名为 SetMaterial 的函数,它有五个参数:

这是一个名为 SetMaterial` 的函数,它有五个参数:

  1. Name (ByVal, 类型:String):材料的名称。
  2. MatType (ByVal, 类型:eMatType):材料的类型,使用 eMatType 枚举类型表示。
  3. Color (Optional, ByVal, 类型:Long,默认值:-1):材料的颜色,用长整数表示。如果不提供,默认值为 -1。
  4. Notes (Optional, ByVal, 类型:String,默认值:空字符串):关于材料的注释或说明。如果不提供,默认值为空字符串。
  5. GUID (Optional, ByVal, 类型:String,默认值:空字符串):材料的全局唯一标识符(GUID)。如果不提供,默认值为空字符串。

函数的返回值类型为 Long

在这个函数中,ByVal 关键字表示参数是通过值传递的,这意味着函数内部对参数的更改不会影响到函数外部的原始变量。Optional 关键字表示参数是可选的,即在调用函数时可以不传递这些参数,它们将使用默认值。

Parameters参数

Name

The name of an existing or new material property. If this is an existing property, that property is modified; otherwise, a new property is added.

现有的或新的物质属性的名称。
如果这是一个现有属性,则修改该属性;
否则,将添加一个新属性。

MatType材料

This is one of the following items in the eMatType enumeration.
这是eMatType枚举中的下列项之一。

eMatType_Steel = 1

eMatType_Concrete = 2

eMatType_NoDesign = 3

eMatType_Aluminum = 4

eMatType_ColdFormed = 5

eMatType_Rebar = 6

eMatType_Tendon = 7
image-20230704163043611

Color

The display color assigned to the material. If Color is specified as -1, the program will automatically assign a color.
分配给材料的显示颜色。如果Color指定为-1,程序将自动分配一种颜色。

Notes

The notes, if any, assigned to the material.
如果有的话,给材料分配的注释。

GUID全局唯一标识符

The GUID (global unique identifier), if any, assigned to the material. If this item is input as Default, the program assigns a GUID to the material.
GUID(全局唯一标识符),如果有的话,分配给材质。如果这个项目作为默认输入,程序将为材质分配一个GUID。

Remarks

This function initializes a material property. If this function is called for an existing material property, all items for the material are reset to their default value.
这个函数初始化一个材质属性。如果对现有材质属性调用此函数,则该材质的所有项将重置为其默认值。
The function returns zero if the material is successfully initialized; otherwise it returns a nonzero value.
如果材料初始化成功,函数返回0;否则它返回一个非零值

#assign isotropic mechanical properties to material
#赋予CONC材料各向同性力学性能
ret = SapModel.PropMaterial.SetMPIsotropic('CONC', 3600, 0.2, 0.0000055)

image-20230704163942743

SetMPIsotropic设置MP各向同性材料解析

Syntax

SapObject.SapModel.PropMaterial.SetMPIsotropic

VB6 Procedure

Function SetMPIsotropic(ByVal Name As String, ByVal e As Double, ByVal u As Double, ByVal a As Double, Optional ByVal Temp As Double = 0) As Long
这是一个名为 SetMPIsotropic 的函数,它有五个参数:

  1. Name (ByVal, 类型:String):材料的名称。
  2. e (ByVal, 类型:Double):材料的弹性模量(或称杨氏模量)。
  3. u (ByVal, 类型:Double):材料的泊松比。
  4. a (ByVal, 类型:Double):材料的线膨胀系数。
  5. Temp (Optional, ByVal, 类型:Double,默认值:0):材料的温度。如果不提供,默认值为 0。

函数的返回值类型为 Long

在这个函数中,
ByVal 关键字表示参数是通过值传递的,这意味着函数内部对参数的更改不会影响到函数外部的原始变量。
Optional 关键字表示参数是可选的,即在调用函数时可以不传递这些参数,它们将使用默认值。

Parameters

Name

The name of an existing material property.

  • e

The modulus of elasticity. [F/L2]

  • u

Poisson’s ratio.

  • a

The thermal coefficient. [1/T]

  • Temp

This item applies only if the specified material has properties that are temperature dependent. That is, it applies only if properties are specified for the material at more than one temperature.

This item is the temperature at which the specified data applies. The temperature must have been defined previously for the material.

Remarks

This function sets the material directional symmetry type to isotropic, and assigns the isotropic mechanical properties.

The function returns zero if the data is successfully assigned; otherwise it returns a nonzero value.
此函数将材料的方向对称类型设置为各向同性,并分配各向同性的力学性能。
如果数据被成功赋值,函数返回0;否则它返回一个非零值。

#定义矩形框架截面属性
#define rectangular frame section property

ret = SapModel.PropFrame.SetRectangle('R1', 'CONC', 12, 12)

image-20230704165225780
image-20230704170908322

PropFrame.SetRectangle框架矩形截面

Syntax

SapObject.SapModel.PropFrame.SetRectangle

VB6 Procedure

Function SetRectangle(ByVal Name As String, ByVal MatProp As String, ByVal t3 As Double, ByVal t2 As Double, Optional ByVal Color As Long = -1, Optional ByVal Notes As String = “”, Optional ByVal GUID As String = “”) As Long

这是一个名为 SetRectangle 的函数,它有七个参数:

  1. Name (ByVal, 类型:String):现有的或新的框架截面属性的名称。如果这是一个现有属性,则修改该属性;否则,将添加一个新属性。
  2. MatProp (ByVal, 类型:String):截面的材料属性名称。
  3. t3 (ByVal, 类型:Double):截面深度。[L]
  4. t2 (ByVal, 类型:Double):截面宽度。[L]
  5. Color (Optional, ByVal, 类型:Long,默认值:-1):分配给截面的显示颜色。如果 Color 指定为 -1,程序将自动分配一种颜色。
  6. Notes (Optional, ByVal, 类型:String,默认值:空字符串):如果有的话,给截面分配的注释。如果不提供,默认值为空字符串。
  7. GUID (Optional, ByVal, 类型:String,默认值:空字符串):GUID(全局唯一标识符),如果有的话,分配给截面。如果不提供,默认值为空字符串。

函数的返回值类型为 Long

在这个函数中,ByVal 关键字表示参数是通过值传递的,这意味着函数内部对参数的更改不会影响到函数外部的原始变量。Optional 关键字表示参数是可选的,即在调用函数时可以不传递这些参数,它们将使用默认值。

这个函数用于初始化一个实心矩形框架截面属性。如果截面属性初始化成功,函数返回0;否则它返回一个非零值。

Parameters

Name

The name of an existing or new frame section property. If this is an existing property, that property is modified; otherwise, a new property is added.

MatProp

The name of the material property for the section.

t3

The section depth. [L]

t2

The section width. [L]

Color

The display color assigned to the section. If Color is specified as -1, the program will automatically assign a color.

Notes

The notes, if any, assigned to the section.

GUID

The GUID (global unique identifier), if any, assigned to the section. If this item is input as Default, the program assigns a GUID to the section.

Remarks

This function initializes a solid rectangular frame section property. If this function is called for an existing frame section property, all items for the section are reset to their default value.

The function returns zero if the section property is successfully initialized; otherwise it returns a nonzero value.

#define frame section property modifiers
#定义框架部分属性修正系数

ModValue = [1000, 0, 0, 1, 1, 1, 1, 1]

ret = SapModel.PropFrame.SetModifiers('R1', ModValue)

image-20230704172227417

#switch to k-ft units
#切换到k-ft单位

kip_ft_F = 4

ret = SapModel.SetPresentUnits(kip_ft_F)

image-20230704172314194

#add frame object by coordinates
#添加框架对象的坐标


FrameName1 = ' '

FrameName2 = ' '

FrameName3 = ' '

[FrameName1, ret] = SapModel.FrameObj.AddByCoord(0, 0, 0, 0, 0, 10, FrameName1, 'R1', '1', 'Global')

[FrameName2, ret] = SapModel.FrameObj.AddByCoord(0, 0, 10, 8, 0, 16, FrameName2, 'R1', '2', 'Global')

[FrameName3, ret] = SapModel.FrameObj.AddByCoord(-4, 0, 10, 0, 0, 10, FrameName3, 'R1', '3', 'Global')

image-20230704172522878

#assign point object restraint at base
# 在支座点对对象约束
PointName1 = ' '

PointName2 = ' '

Restraint = [True, True, True, True, False, False]

[PointName1, PointName2, ret] = SapModel.FrameObj.GetPoints(FrameName1, PointName1, PointName2)

ret = SapModel.PointObj.SetRestraint(PointName1, Restraint)
#assign point object restraint at top
#在顶部指定点对象约束
Restraint = [True, True, False, False, False, False]

[PointName1, PointName2, ret] = SapModel.FrameObj.GetPoints(FrameName2, PointName1, PointName2)

ret = SapModel.PointObj.SetRestraint(PointName2, Restraint)
#refresh view, update (initialize) zoom
#刷新视图,更新(初始化)缩放
# 刷新视图,才刷新视图

ret = SapModel.View.RefreshView(0, False)

image-20230704173102847

SapModel.View.RefreshView更新视图

Syntax

SapObject.SapModel.View.RefreshView

VB6 Procedure

Function RefreshView(Optional ByVal Window As Long = 0, Optional ByVal Zoom As Boolean = True) As Long
这是一个名为 RefreshView 的函数,它有两个可选参数:

  1. Window (Optional, ByVal, 类型:Long,默认值:0):表示要刷新视图的窗口编号。如果不提供,默认值为 0,表示刷新所有窗口。
  2. Zoom (Optional, ByVal, 类型:Boolean,默认值:True):表示是否在刷新视图时进行缩放以适应窗口大小。如果不提供,默认值为 True,表示在刷新视图时进行缩放。

函数的返回值类型为 Long

在这个函数中,ByVal 关键字表示参数是通过值传递的,这意味着函数内部对参数的更改不会影响到函数外部的原始变量。Optional 关键字表示参数是可选的,即在调用函数时可以不传递这些参数,它们将使用默认值。

这个函数用于刷新指定窗口的视图,可以选择是否进行缩放以适应窗口大小。如果视图刷新成功,函数返回0;否则它返回一个非零值。

Parameters

  • Window

This is 0 meaning all windows or an existing window number. It indicates the window(s) to have its view refreshed.

  • Zoom

If this item is True, the window zoom is maintained when the view is refreshed. If it is False, the zoom returns to a default zoom.

Remarks

This function refreshes the view for the specified window(s). It returns zero if the window views are successfully refreshed, otherwise it returns a nonzero value.

See RefreshWindow and RefreshView for more information.

#add load patterns
#添加荷载模式

LTYPE_OTHER = 8

ret = SapModel.LoadPatterns.Add('1', LTYPE_OTHER, 1, True)

ret = SapModel.LoadPatterns.Add('2', LTYPE_OTHER, 0, True)

ret = SapModel.LoadPatterns.Add('3', LTYPE_OTHER, 0, True)

ret = SapModel.LoadPatterns.Add('4', LTYPE_OTHER, 0, True)

ret = SapModel.LoadPatterns.Add('5', LTYPE_OTHER, 0, True)

ret = SapModel.LoadPatterns.Add('6', LTYPE_OTHER, 0, True)

ret = SapModel.LoadPatterns.Add('7', LTYPE_OTHER, 0, True)

image-20230704173538685

#assign loading for load pattern 2
# 给指定的结构模型分配荷载(模式2)

# SapModel.FrameObj.GetPoints来获取指定框架对象的端点名称。
# 返回结果包括端点名称 PointName1 和 PointName2,以及函数调用结果 ret。
[PointName1, PointName2, ret] = SapModel.FrameObj.GetPoints(FrameName3, PointName1, PointName2)

# 定义一个列表 PointLoadValue,表示在点荷载上施加的六个分量值(Fx, Fy, Fz, Mx, My, Mz)
PointLoadValue = [0,0,-10,0,0,0]

"""
调用 SapModel.PointObj.SetLoadForce(PointName1, '2', PointLoadValue) 函数来给指定的点对象 PointName1 分配点荷载。
荷载模式为 '2',荷载值由 PointLoadValue 列表给出。
函数返回结果 ret(result),表示函数调用成功与否。
"""
ret = SapModel.PointObj.SetLoadForce(PointName1, '2', PointLoadValue)

"""
调用 SapModel.FrameObj.SetLoadDistributed(FrameName3, '2', 1, 10, 0, 1, 1.8, 1.8) 函数来给指定的框架对象 FrameName3 分配LoadDistributed分布式荷载。
荷载模式为 '2',荷载类型为1(线性变化),
荷载方向为10(局部坐标系下的Y轴),
荷载起始和终止值分别为1.8。
函数返回结果 ret,表示函数调用成功与否。
"""
ret = SapModel.FrameObj.SetLoadDistributed(FrameName3, '2', 1, 10, 0, 1, 1.8, 1.8)

#assign loading for load pattern 3
# 给指定的结构/位置分配其他点/均布荷载(模式3~7)

[PointName1, PointName2, ret] = SapModel.FrameObj.GetPoints(FrameName3, PointName1, PointName2)

PointLoadValue = [0,0,-17.2,0,-54.4,0]

ret = SapModel.PointObj.SetLoadForce(PointName2, '3', PointLoadValue)

 

#assign loading for load pattern 4

ret = SapModel.FrameObj.SetLoadDistributed(FrameName2, '4', 1, 11, 0, 1, 2, 2)

 

#assign loading for load pattern 5

ret = SapModel.FrameObj.SetLoadDistributed(FrameName1, '5', 1, 2, 0, 1, 2, 2, 'Local')

ret = SapModel.FrameObj.SetLoadDistributed(FrameName2, '5', 1, 2, 0, 1, -2, -2, 'Local')

 

#assign loading for load pattern 6

ret = SapModel.FrameObj.SetLoadDistributed(FrameName1, '6', 1, 2, 0, 1, 0.9984, 0.3744, 'Local')

ret = SapModel.FrameObj.SetLoadDistributed(FrameName2, '6', 1, 2, 0, 1, -0.3744, 0, 'Local')

 

#assign loading for load pattern 7

ret = SapModel.FrameObj.SetLoadPoint(FrameName2, '7', 1, 2, 0.5, -15, 'Local')

"""
捕捉sap2000的界面并放大到全屏
"""
import time
import pygetwindow as gw
import ctypes
from ctypes import wintypes
import keyboard


# Define necessary Windows API functions and constants
user32 = ctypes.WinDLL('user32', use_last_error=True)

SW_MAXIMIZE = 3

HWND = wintypes.HWND
user32.ShowWindow.argtypes = (HWND, ctypes.c_int)
user32.ShowWindow.restype = wintypes.BOOL

# Find the SAP2000 window and get its handle (HWND)
sap2000_window = gw.getWindowsWithTitle('SAP2000 v24.2.0 Ultimate C 64-bit - (Untitled)')[0]
sap2000_hwnd = sap2000_window._hWnd

# Maximize the SAP2000 window using its handle
user32.ShowWindow(HWND(sap2000_hwnd), SW_MAXIMIZE)

# Give some time for the view to update
time.sleep(3)

#保持sap程序在前端被激活
sap2000_window = gw.getWindowsWithTitle('SAP2000 v24.2.0 Ultimate C 64-bit - (Untitled)')[0]
sap2000_window.restore()
sap2000_window.activate()
#切换到3D
keyboard.press_and_release('alt')
keyboard.press_and_release('p')
keyboard.press_and_release('o')
keyboard.press_and_release('o')
keyboard.press_and_release('enter')
time.sleep(1)
keyboard.press_and_release('tab')
time.sleep(1)
keyboard.press_and_release('down')
keyboard.press_and_release('tab')
time.sleep(1)
keyboard.press_and_release('enter')
#切换到XY
#refresh view, update (initialize) zoom
#刷新视图,更新(初始化)缩放
SapModel.View.RefreshView(0, True)
#SAP没有视图的API接口,模版中将相应视图保存为"3D""XY"。
#恢复显示只不改变视角,恢复视图会回复居中的视角

# 截图EMFUse the Alt+F+M shortcut to save the view as an image
keyboard.press_and_release('alt')
keyboard.press_and_release('f')
keyboard.press_and_release('m')
keyboard.write('pic1')
time.sleep(1)
keyboard.press_and_release('enter')
print("Image capture command sent")

Image capture command sent
#switch to k-in units
#设置单位SetPresentUnits

kip_in_F = 3

ret = SapModel.SetPresentUnits(kip_in_F)
#save model
#保存模型.File.Save
#return
ret = SapModel.File.Save(ModelPath)

image-20230704210113629

image-20230704210345035

#run model (this will create the analysis model)

ret = SapModel.Analyze.RunAnalysis()

#initialize for Sap2000 results
"""
SapResult 列表被初始化为包含 7 个零的列表。
接下来,我们使用 GetPoints 函数从 SAP2000 模型中获取与 FrameName2 相关联的两个端点的名称。
PointName1 和 PointName2 变量将分别存储这两个端点的名称。
"""
SapResult= [0,0,0,0,0,0,0]

[PointName1, PointName2, ret] = SapModel.FrameObj.GetPoints(FrameName2, PointName1, PointName2)
#get Sap2000 results for load cases 1 through 7
"""
获取关于 1 到 7 工况的结果
"""
for i in range(0,7):

      NumberResults = 0

      Obj = []

      Elm = []

      ACase = []

      StepType = []

      StepNum = []

      U1 = []

      U2 = []

      U3 = []

      R1 = []

      R2 = []

      R3 = []

      ObjectElm = 0
"""
然后,我们取消选择所有用于输出的案例和组合DeselectAllCasesAndCombosForOutput,
选择要下一个负荷情况SetCaseSelectedForOutput(str(i+1))。
"""
      ret = SapModel.Results.Setup.DeselectAllCasesAndCombosForOutput()

      ret = SapModel.Results.Setup.SetCaseSelectedForOutput(str(i+1))

        
"""工况1~4
PointName2(框架结构的第二个端点)获取关节位移JointDispl结果。
将 U3(Z 方向的位移)的结果存储在 SapResult[i]。

"""
      if i <= 3:

          [NumberResults, Obj, Elm, ACase, StepType, StepNum, U1, U2, U3, R1, R2, R3, ret] = SapModel.Results.JointDispl(PointName2, ObjectElm, NumberResults, Obj, Elm, ACase, StepType, StepNum, U1, U2, U3, R1, R2, R3)

          SapResult[i] = U3[0]

"""工况5~7
使用 PointName1(框架结构的第一个端点)获取关节位移结果。
将 U1(X 方向的位移)的结果存储在 SapResult[i]
"""
      else:

          [NumberResults, Obj, Elm, ACase, StepType, StepNum, U1, U2, U3, R1, R2, R3, ret] = SapModel.Results.JointDispl(PointName1, ObjectElm, NumberResults, Obj, Elm, ACase, StepType, StepNum, U1, U2, U3, R1, R2, R3)

          SapResult[i] = U1[0]

#close Sap2000
#SAP算完关闭,但是仍然保留在程序变量里SapResult= [0,0,0,0,0,0,0]
"""
ret = mySapObject.ApplicationExit(False):此行代码将关闭 SAP2000 应用程序。
参数 False 表示在退出应用程序之前不提示用户保存更改。

SapModel = None:将 SapModel 变量设置为 None,以释放与 SAP2000 模型相关的资源。
mySapObject = None:将 mySapObject 变量设置为 None,以释放与 SAP2000 应用程序相关的资源。
"""
ret = mySapObject.ApplicationExit(False)

SapModel = None

mySapObject = None
---------------------------------------------------------------------------

AttributeError                            Traceback (most recent call last)

Cell In[49], line 10
      1 #close Sap2000
      2 #SAP算完关闭,但是仍然保留在程序变量里
      3 """
      4 ret = mySapObject.ApplicationExit(False):此行代码将关闭 SAP2000 应用程序。
      5 参数 False 表示在退出应用程序之前不提示用户保存更改。
   (...)
      8 mySapObject = None:将 mySapObject 变量设置为 None,以释放与 SAP2000 应用程序相关的资源。
      9 """
---> 10 ret = mySapObject.ApplicationExit(False)
     12 SapModel = None
     14 mySapObject = None


AttributeError: 'NoneType' object has no attribute 'ApplicationExit'

#fill independent results
#独立手算结果

IndResult= [0,0,0,0,0,0,0]

IndResult[0] = -0.02639

IndResult[1] = 0.06296

IndResult[2] = 0.06296

IndResult[3] = -0.2963

IndResult[4] = 0.3125

IndResult[5] = 0.11556

IndResult[6] = 0.00651
#fill percent difference

PercentDiff = [0,0,0,0,0,0,0]

for i in range(0,7):

      PercentDiff[i] = (SapResult[i] / IndResult[i]) - 1

#display results

for i in range(0,7):

      print()

      print(SapResult[i])

      print(IndResult[i])

      print(PercentDiff[i])
-0.026389708333499594
-0.02639
-1.1052159924473948e-05

0.0629596111115078
0.06296
-6.1767549587310455e-06

0.0629596111115078
0.06296
-6.1767549587310455e-06

-0.2963018518537188
-0.2963
6.249928176993436e-06

0.3125018518538204
0.3125
5.92593222537019e-06

0.11555582518591315
0.11556
-3.612680933584578e-05

0.006511371527818799
0.00651
0.0002106801564976113
  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

hmywillstronger

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值