Python生成器
Python构建器允许构建可以使用PySD Model类运行的模型。
在转换中使用一对一词典意味着功能的广度本质上是有限的。如果没有直接的Python等效物可用,PySD会提供一个函数库,例如 pulse , step 等,这些特定于动态模型行为。
除了在Vensim/XMILE和Python之间转换单个命令外,PySD还通过用强调线替换空白来重新处理组件标识符,使其具有Python安全性。转换器允许源标识符使用字母数字字符、空白或特殊字符。为了实现这一目标,创建了一个命名空间,该命名空间将变量的原始名称与Python安全名称链接起来。PySD模型类中也提供了命名空间,允许用户使用原始名称和Python安全名称。
构建模型产生的Python代码的格式为 black 库并将其写入原始模型所在的同一文件夹中。
主要建设者
模型构建器类允许将AbstractModel转换为PySD模型,将Python代码写入文件中,稍后可以使用PySD模型类加载这些文件。每个抽象级别都有自己的构建器。然而,用户只需使用AbstractModel创建模型构建器对象并调用 build_model 法
- class pysd.builders.python.python_model_builder.ModelBuilder(abstract_model: AbstractModel)[源代码]
模型构建器允许从抽象模型构建PySD Python模型。
- 参数:
abstract_model (AbstractModel) -- 要构建的抽象模型。
- class pysd.builders.python.python_model_builder.SectionBuilder(abstract_section: AbstractSection)[源代码]
SectionBuilder允许构建PySD模型的一部分。每个部分都将是一个文件,除非模型已设置为拆分为模块。
- 参数:
abstract_section (AbstractSection) -- 要构建的抽象部分。
- class pysd.builders.python.python_model_builder.ElementBuilder(abstract_element: AbstractElement, section: SectionBuilder)[源代码]
ElementBuilder允许构建PySD模型的元素。
- 参数:
abstract_element (AbstractElement) -- 要构建的抽象元素。
section (SectionBuilder) -- 定义元素的部分。需要给下标和命名空间的访问权限。
- class pysd.builders.python.python_model_builder.ComponentBuilder(abstract_component: AbstractComponent, element: ElementBuilder, section: SectionBuilder)[源代码]
CLARentBuilder允许构建PySD模型的组件。
- 参数:
abstract_component (AbstracComponent) -- 要构建的抽象组件。
element (ElementBuilder) -- 定义组件的元素。需要为合并脚注和其他组件提供访问权限。
section (SectionBuilder) -- 定义元素的部分。需要给下标和命名空间的访问权限。
表达构建者
从抽象语法树到Python的转换以两种方式发生。外部表达与其构建者一起访问,后者将分裂其论点并与各自的构建者一起访问它们。到达最低级别后,它将被转换成Python,返回一个Building AST对象,该对象将包括pPython表达、其脚注、对其他元素的调用及其算术顺序(更多信息请参阅Build AST)。将为每个访问的参数从较低级别到顶层返回Building AST,给出最终的表达。
- class pysd.builders.python.python_expressions_builder.BuildAST(expression: str, calls: dict, subscripts: dict, order: int)[源代码]
Python表情持有者。
- 参数:
- reshape(subscripts: SubscriptManager, final_subscripts: dict, final_element: bool = False) None[源代码]
将对象重塑为所需的脚注。如果它不为0,它会修改该公式并降低阶数。
- 参数:
subscripts (SubscriptManager) -- 该部分的脚注。
final_subscripts (dict) -- 所需的最终脚注。
final_element (bool (optional)) -- 如果为True,则将使用最终的脚注重新塑造数组,以具有耻辱形状。否则,长度为1的维度将包含在位置中,以允许与其他数组进行算术运算。默认为假。
- class pysd.builders.python.python_expressions_builder.StructureBuilder(value: object, component: object)[源代码]
抽象树结构的主要构建器。所有的构建器都是该类的子类,这允许它们继承方法。
- class pysd.builders.python.python_expressions_builder.OperationBuilder(operation: ArithmeticStructure | LogicStructure, component: object)[源代码]
算术和逻辑运算的生成器。
- class pysd.builders.python.python_expressions_builder.GameBuilder(game_str: GameStructure, component: object)[源代码]
GAME表情的生成器。
- class pysd.builders.python.python_expressions_builder.CallBuilder(call_str: CallStructure, component: object)[源代码]
用于调用函数、宏和查找的生成器。
- class pysd.builders.python.python_expressions_builder.AllocateAvailableBuilder(allocate_str: AllocateAvailableStructure, component: object)[源代码]
allocate_active函数的生成器。
- class pysd.builders.python.python_expressions_builder.AllocateByPriorityBuilder(allocate_str: AllocateByPriorityStructure, component: object)[源代码]
allocate_by_priority函数的生成器。
- class pysd.builders.python.python_expressions_builder.ExtLookupBuilder(getlookup_str: GetLookupsStructure, component: object)[源代码]
Builder for External Lookups.
- class pysd.builders.python.python_expressions_builder.ExtDataBuilder(getdata_str: GetDataStructure, component: object)[源代码]
外部数据的生成器。
- class pysd.builders.python.python_expressions_builder.ExtConstantBuilder(getconstant_str: GetConstantsStructure, component: object)[源代码]
外部常数的生成器。
- class pysd.builders.python.python_expressions_builder.TabDataBuilder(data_str: DataStructure, component: object)[源代码]
空数据运算式的生成器。
- class pysd.builders.python.python_expressions_builder.InitialBuilder(initial_str: InitialStructure, component: object)[源代码]
缩写的生成器。
- class pysd.builders.python.python_expressions_builder.IntegBuilder(integ_str: IntegStructure, component: object)[源代码]
整合/股票的构建者。
- class pysd.builders.python.python_expressions_builder.DelayBuilder(dtype: str, delay_str: DelayStructure | DelayNStructure, component: object)[源代码]
定期延误的构建者。
- class pysd.builders.python.python_expressions_builder.DelayFixedBuilder(delay_str: DelayFixedStructure, component: object)[源代码]
延迟已修复的构建者。
- class pysd.builders.python.python_expressions_builder.SmoothBuilder(smooth_str: SmoothStructure | SmoothNStructure, component: object)[源代码]
光滑的建造者。
- class pysd.builders.python.python_expressions_builder.TrendBuilder(trend_str: TrendStructure, component: object)[源代码]
趋势的构建者。
- class pysd.builders.python.python_expressions_builder.ForecastBuilder(forecast_str: ForecastStructure, component: object)[源代码]
预测的构建者。
- class pysd.builders.python.python_expressions_builder.SampleIfTrueBuilder(sampleiftrue_str: SampleIfTrueStructure, component: object)[源代码]
如果为True,则示例的生成器。
- class pysd.builders.python.python_expressions_builder.LookupsBuilder(lookups_str: LookupsStructure, component: object)[源代码]
定期查找的生成器。
- class pysd.builders.python.python_expressions_builder.InlineLookupsBuilder(inlinelookups_str: InlineLookupsStructure, component: object)[源代码]
用于内联查找的生成器。
- class pysd.builders.python.python_expressions_builder.ReferenceBuilder(reference_str: ReferenceStructure, component: object)[源代码]
用于引用其他变量的生成器。
- class pysd.builders.python.python_expressions_builder.NumericBuilder(value: object, component: object)[源代码]
数字和nan值的生成器。
- class pysd.builders.python.python_expressions_builder.ArrayBuilder(value: object, component: object)[源代码]
数组的生成器。
- pysd.builders.python.python_expressions_builder.merge_dependencies(*dependencies: dict, inplace: bool = False) dict[源代码]
合并元素的两个依赖项。
- pysd.builders.python.python_expressions_builder.visit_loc(current_subs: dict, original_subs: dict, keep_shape: bool = False) tuple[源代码]
比较原始下标和当前下标,并根据需要返回子索引信息。
- 参数:
- 返回:
loc ( list of str or None )--各维度的订阅列表。如果所有内容都已满(“:”),则没有被删除,这意味着不需要数组索引。
rename ( dict )--要重命名的维度的字典。
final_subs ( dict )--变量最后一个后缀的字典。
reset_coords ( bool )--布尔值,指示是否需要重新设置坐标。
to_float ( bool )--布尔值,指示变量是否应转换为浮点数。
- class pysd.builders.python.python_expressions_builder.ASTVisitor(component: object)[源代码]
ASTVisitor允许访问组件的抽象Synatx树,返回Python对象并生成必要的对象。
- 参数:
component (ComponentBuilder) -- 要构建的组件构建器。
支持的表达示例
运营商
抽象语法 |
Python转换 |
|---|---|
逻辑结构( ['negative'] ,(A,)) |
-A |
A |
A |
逻辑结构( [':NOT:'] ,(A,)) |
numpy.not(A) |
抽象语法 |
Python转换 |
|---|---|
算术结构( ['^'] ,(A,B)) |
A**B |
算术结构( ['*'] ,(A,B)) |
A*B |
算术结构( ['/'] ,(A,B)) |
A/B |
呼叫结构(“模”,(A,B)) |
pysd.functions.模(A,B) |
算术结构( ['+'] ,(A,B)) |
A+B |
算术结构( ['-'] ,(A,B)) |
A-B |
逻辑结构( ['='] ,(A,B)) |
A == B |
逻辑结构( ['<>'] ,(A,B)) |
A!= B |
逻辑结构( ['<'] ,(A,B)) |
A < B |
逻辑结构( ['>'] ,(A,B)) |
A > B |
逻辑结构( ['>='] ,(A,B)) |
A >= B |
逻辑结构( ['<='] ,(A,B)) |
A <= B |
逻辑结构( [':AND:'] ,(A,B)) |
numpy。和(A,B) |
逻辑结构( [':OR:'] ,(A,B)) |
numpy。或(A,B) |
功能
抽象语法 |
Python转换 |
Python评论 |
|---|---|---|
CallStructure('abs', (A,)) |
numpy.abs(A) |
|
呼叫结构(' min ',(A,B)) |
numpy.minimum(A,B) |
|
呼叫结构(' max ',(A,B)) |
numpy. max(A,B) |
|
呼叫结构(' vmin_xmile ',(A,)) |
pysd.functions.vmin(A) |
|
呼叫结构(' vmax_xmile ',(A,)) |
pysd.functions.vmax(A) |
|
呼叫结构(' SQRT ',(A,)) |
numpy.sqrt |
|
CallStructure('exp',(A,)) |
numpy. BEP(A) |
|
呼叫结构(' In ',(A,)) |
numpy.log(A) |
|
呼叫结构(' pi ',(,)) |
numpy.py |
|
呼叫结构(' sin ',(A,)) |
numpy.sin(A) |
|
呼叫结构(' cos ',(A,)) |
numpy.cos(A) |
|
CallStructure('tan',(A,)) |
numpy.tan(A) |
|
呼叫结构(' arcsin ',(A,)) |
numpy.arcsin(A) |
|
CallStructure('arccos',(A,)) |
numpy.arccos(A) |
|
呼叫结构(“arctan”,(A,)) |
numpy.arctan(A) |
|
呼叫结构(' invert_matrix ',(A,)) |
pysd.functions.invert_matrix(A) |
|
CallStructure('elmcount',(A,)) |
len(A) |
|
CallArchitecture(' int ',(A,)) |
pysd.functions.integer(A) |
|
呼叫结构(“量子”,(A,B)) |
pysd.函数.量子(A,B) |
|
呼叫结构(“模”,(A,B)) |
pysd.functions.模(A,B) |
|
呼叫结构(' if_then_else ',(A,B)) |
pysd.functions.if_then_else(A,lambda:B,lambda:C) |
|
呼叫结构(' if_then_else ',(A,B)) |
pysd.functions.if_then_else(A,lambda:B,lambda:C) |
|
呼叫结构(' xidz ',(A,B,X)) |
pysd.functions.xidz(A,B,X) |
|
呼叫结构(' zidz ',(A,B)) |
pysd.functions.zidz(A,B) |
|
呼叫结构(' vmin ',(A,)) |
pysd.functions.vmin(A, ['dim!'] ) |
|
CallStructure('vmax',(A,)) |
pysd.functions.vmax(A, ['dim!'] ) |
|
呼叫结构(' sum ',(A,)) |
pysd.functions.sum(A, ['dim!'] ) |
|
呼叫结构(' prod ',(A,)) |
pysd.functions.prod(A, ['dim!'] ) |
|
呼叫结构('脉冲',(开始,宽度)) |
pysd.functions.pulse(start,width=width) |
|
呼叫结构(' Xpulse ',(开始,幅度)) |
pysd.functions.pulse(开始,幅度=幅度) |
|
CallStructure('Xpulse_train',(start,interval,magnitude)) |
pysd.functions.pulse(开始,重复_时间=间隔,幅度=幅度) |
|
CallStructure('pulse_train',(start,tbetween,width,end)) |
pysd.functions.pulse(start,repeat_time=tbetween,root = root,end=end) |
|
呼叫结构(' ramp ',(slope,start_time,end_time)) |
pysd.functions.ramp(时间、slope、start_time、end_time) |
|
呼叫结构(' ramp ',(slope,start_time)) |
pysd.functions.ramp(时间、slope、start_time) |
|
CallStructure('step',(height,step_time)) |
pysd.functions.Step(时间、高度、Step_time) |
|
CallStructure('get_time_value',(relativeto,offset,measure)) |
pysd.functions.get_time_value(时间、相对于、补偿、测量) |
|
CallArchitecture(' vector_select ',(sel_数组,BEP_数组,miss_val,n_action,e_action)) |
pysd.functions.vector_select(sel_数组,BEP_数组, ['dim!'] 、miss_val、n_action、e_action) |
|
呼叫结构(' vector_rank ',(vec,Direction)) |
vector_rank(vec,direction) |
|
呼叫结构(' vector_reorder ',(vec,svec)) |
vector_reorder(vec,svec) |
|
呼叫结构(' vector_sort_order ',(vec,Direction)) |
vector_sort_order(vec,direction) |
|
游戏结构(A) |
A |
|
AllocateDeliverable Architecture(请求、pp、avenue) |
分配_可用(请求、PP、可用) |
并非包括所有优先级配置文件。 |
AllocateByPriorityArchitecture(请求、优先级、大小、宽度、供应) |
分配_by_优先级(请求、优先级、宽度、供应) |
|
初始结构(值) |
pysd.statefuls.Initial |
|
SampleIfTrueArchitecture(条件、输入、初始值) |
pysd.有权势.SampleIfTrue(.) |
|
呼叫结构(' random_0_1 ',()) |
NP.random. unique(0,1,size=final_shape) |
|
CallArchitecture(' random_uniform ',(m,x,s)) |
np.random.uniform(m,x,size=final_shape) |
|
呼叫结构(' random_normal ',(m,x,h,r,s)) |
stats.truncnorm.rvs((m-h)/r,(x-h)/r,loc=h,scale=r,size=final_shape) |
|
呼叫结构(' random_exponential ',(m,x,h,r,s)) |
stats.truncexpon.rvs((x-NP. max(m,h)/r,loc=NP. max(m,h),scale=r,size=final_shape) |
抽象语法 |
Python转换 |
|---|---|
延迟结构(输入,延迟_时间,初始值,1) |
pysd。有权势的人。延迟(.) |
延迟结构(输入,delay_time,输入,1) |
pysd。有权势的人。延迟(.) |
延迟结构(输入,延迟_时间,初始值,3) |
pysd。有权势的人。延迟(.) |
延迟结构(输入,delay_time,输入,3) |
pysd。有权势的人。延迟(.) |
DelayNStructure(输入,delay_time,initial_Value,n) |
pysd.statefuls.DelayN(.) |
DelayNArchitecture(输入,delay_time,输入,n) |
pysd.statefuls.DelayN(.) |
DelayFixed(输入、delay_time、initial_Value) |
pysd。有状态。延迟修复(.) |
DelayFixed(输入,delay_time,输入) |
pysd。有状态。延迟修复(.) |
SmoothFrame(输入,smth_time,initial_value,1) |
pysd。有权势。顺利(.) |
SmothArchitecture(输入,smth_time,输入,1) |
pysd。有权势。顺利(.) |
SmoothFrame(输入,smth_time,initial_value,3) |
pysd。有权势。顺利(.) |
SmoothStructure(input,smth_time,input,3) |
pysd。有权势。顺利(.) |
SmothNStructure(输入,smth_time,initional_Value,n) |
pysd.有状态.SmoothN(.) |
SmothNStructure(输入,smth_time,输入,n) |
pysd.有状态.SmoothN(.) |
预测结构(输入、平均时间、地平线、初始趋势) |
pysd。有权势的人。预测(.) |
预测结构(输入,平均_时间,地平线,0) |
pysd。有权势的人。预测(.) |
TrendStructure(input, average_time, initial_trend) |
pysd。有权势的人。趋势(.) |
趋势结构(输入,平均_时间,0) |
pysd。有权势的人。趋势(.) |
抽象语法 |
Python转换 |
|---|---|
GetDataStructure('file','tab','time_row_or_col','cell') |
pysd. externative.ExtData(.) |
GetDataStructure('file','tab','time_row_or_col','cell') |
pysd. externative.ExtData(.) |
GetLookupsArchitecture('文件',' x_row_or_col ',',cell ') |
pysd.external.ExtLookup(...) |
GetLookupsArchitecture('文件',' x_row_or_col ',',cell ') |
pysd.external.ExtLookup(...) |
GetConstantsStructure('file','tab','cell') |
pysd. externative.ExtConstant(.) |
GetConstantsStructure('file','tab','cell') |
pysd. externative.ExtConstant(.) |
名字空间管理器
- class pysd.builders.python.namespace.NamespaceManager(parameters: List[str] = [])[源代码]
命名空间管理器对象允许在命名空间中包含新元素并在命名空间中搜索元素。当包含新元素时,使用Python安全名称来编写等式。
- 参数:
parameters (list (optional)) -- 在宏中用作参数的参数列表。通过德福克特,这是一个空列表。
- make_python_identifier(string: str, prefix: str = None, add_to_namespace: bool = False) str[源代码]
获取任意字符串并创建有效的Python标识符。
如果创建的Python标识符已经在命名空间中,但输入字符串不在(即,两个相似的字符串解析为相同的Python标识符),或者如果标识符是reserved_words列表中的保留字,或者是Python默认保留字,则添加_1,或者如果_1在命名空间中,则添加_2等。
- 参数:
- 返回:
identifier --基于输入字符串的有效Python标识符。
- 返回类型:
示例
>>> make_python_identifier('Capital') 'capital'
>>> make_python_identifier('multiple words') 'multiple_words'
>>> make_python_identifier('multiple spaces') 'multiple_spaces'
当名称是Python关键字时,添加“_1”以区分它> make_python_identifier(' for ')' for_1 '
删除开头和结尾的空白> make_pony_identifier(“whiteSpace”)“whiteSpace”
直接删除大多数特殊字符:> make_python_identifier(' H @t tra!ck ')' ht_trck '
添加有效字符串到前导数字> make_python_identifier('123abc')'nvs_123abc'
已在命名空间中> make_python_identifier(' Var $')#namency = ð ' Var ':'
命名空间冲突> make_pony_identifier(' Var @')#namency =' Var $':' var '}' var_1 '
>>> make_python_identifier('Var$') # namespace={'Var@': 'var', ... 'Var%':'var_1'} 'var_2'
引用
字幕经理
- class pysd.builders.python.subscripts.SubscriptManager(abstract_subscripts: List[AbstractSubscriptRange], _root: Path)[源代码]
SubwrittManager对象允许保存小节中包含的脚注、搜索元素或键并简化它们。
- 参数:
abstrac_subscripts (list) -- 来自AbstractModel的AbstractSubwrittRanges列表。
_root (pathlib.Path) -- 模型文件的路径。需要从Excel文件中读取脚注范围。
- make_coord_dict(subs: List[str]) dict[源代码]
这用于协助查找特定元素。
- 参数:
subs (list of strings) -- 坐标,可以是维度的名称,也可以是维度内的位置。
- 返回:
coordinates --访问我们感兴趣的xArray数量所需的坐标。
- 返回类型:
示例
>>> sm = SubscriptManager([], Path('')) >>> sm._subscripts = { ... 'Dim1': ['A', 'B', 'C'], ... 'Dim2': ['A', 'B', 'C', 'D']} >>> sm.make_coord_dict(['Dim1', 'D']) {'Dim1': ['A', 'B', 'C'], 'Dim2': ['D']} >>> sm.make_coord_dict(['A']) {'Dim1': ['A']} >>> sm.make_coord_dict(['A', 'B']) {'Dim1': ['A'], 'Dim2': ['B']} >>> sm.make_coord_dict(['A', 'Dim1']) {'Dim2': ['A'], 'Dim1': ['A', 'B', 'C']}
- make_merge_list(subs_list: List[List[str]], element: str = '') List[str][源代码]
这用于在构建xrmerge时提供帮助。合并后,从一系列订阅列表中返回最终的订阅列表。合并具有来自不同定义的脚注的变量时是必要的。
- 参数:
- 返回:
dims --合并后的最终脚注。
- 返回类型:
示例
>>> sm = SubscriptManager([], Path('')) >>> sm._subscripts = {"upper": ["A", "B"], "all": ["A", "B", "C"]} >>> sm.make_merge_list([['A'], ['B']]) ['upper'] >>> sm.make_merge_list([['A'], ['B'], ['C']]) ['all'] >>> sm.make_merge_list([['upper'], ['C']]) ['all'] >>> sm.make_merge_list([['A'], ['C']]) ['all']
- simplify_subscript_input(coords: dict, merge_subs: List[str] = None) tuple[源代码]
简化了后缀输入,以避免在可以使用_subscpt_dict时打印坐标列表。使模型代码更加简单。
- 参数:
- 返回:
final_subs, coords --在模型文件中生成coord指令的最终脚注和方程。
- 返回类型:
示例
>>> sm = SubscriptManager([], Path('')) >>> sm._subscripts = { ... "dim": ["A", "B", "C"], ... "dim2": ["A", "B", "C", "D"]} >>> sm.simplify_subscript_input({"dim": ["A", "B", "C"]}) ({"dim": ["A", "B", "C"]}, "{'dim': _subscript_dict['dim']}" >>> sm.simplify_subscript_input({"dim": ["A", "B", "C"]}, ["dim2"]) ({"dim2": ["A", "B", "C"]}, "{'dim2': _subscript_dict['dim']}" >>> sm.simplify_subscript_input({"dim": ["A", "B"]}) ({"dim": ["A", "B"]}, "{'dim': ['A', 'B']}"