我正在使用一个名为 PySD 的包进行系统动力学建模。PySD 将模型从 Vensim(系统动力学建模包)转换为 python,并允许用户用比 Vensim 更复杂的例程替换各种方程。我正在运行一个带有各种下标的模型,这会产生一种不寻常的输出格式。输出被读入一个数据帧,其下标元素的各个值最终是 xarray.DataArrays。我想知道如何获取一列 xarray.DataArrays (最终成为一个系列)并将其转换为二维数组,第二维是下标的数量。
import pysd
import numpy as np
model=pysd.load("Example.py")
stocks=model.run
pop=np.array(Population) #Creates an object array
Population=stocks.Populaton #Creates a series
#How to get an array of population values for each country?
example.py 代码如下(请记住,这是说明问题的任意示例)
from __future__ import division
import numpy as np
from pysd import utils
import xarray as xr
from pysd.functions import cache
from pysd import functions
_subscript_dict = {
'Country': ['Canada', 'USA', 'China', 'Norway', 'India', 'England',
'Mexico', 'Yemen']
}
_namespace = {
'TIME': 'time',
'Time': 'time',
'Deaths': 'deaths',
'Births': 'births',
'Population': 'population',
'Birth rate': 'birth_rate',
'Murder rate': 'murder_rate',
'Natural death rate': 'natural_death_rate',
'FINAL TIME': 'final_time',
'INITIAL TIME': 'initial_time',
'SAVEPER': 'saveper',
'TIME STEP': 'time_step'
}
@cache('step')
def deaths():
return murder_rate() * population() + natural_death_rate() * population()
@cache('step')
def births():
return birth_rate() * population()
@cache('step')
def population():
return integ_population()
@cache('run')
def birth_rate():
return utils.xrmerge([
xr.DataArray(
data=[5., 5., 5., 5., 5., 5., 5., 5.],
coords={
'Country':
['Canada', 'USA', 'China', 'Norway', 'India', 'England', 'Mexico', 'Yemen']
},
dims=['Country']),
xr.DataArray(data=[10.], coords={'Country': ['Mexico']}, dims=
['Country']),
xr.DataArray(data=[8.], coords={'Country': ['Yemen']}, dims=
['Country']),
])
@cache('step')
def murder_rate():
return time()
@cache('run')
def natural_death_rate():
return utils.xrmerge([
xr.DataArray(
data=[3., 3., 3., 3., 3., 3., 3., 3.],
coords={
'Country':
['Canada', 'USA', 'China', 'Norway', 'India', 'England', 'Mexico', 'Yemen']
},
dims=['Country']),
xr.DataArray(data=[5.], coords={'Country': ['Yemen']}, dims=['Country']),
xr.DataArray(data=[5.], coords={'Country': ['Mexico']}, dims=['Country']),
])
@cache('run')
def final_time():
return 100
@cache('run')
def initial_time():
return 0
@cache('step')
def saveper():
return time_step()
@cache('run')
def time_step():
return 1
def _init_population():
return xr.DataArray(
data=np.ones([8]) * 10,
coords={
'Country': ['Canada', 'USA', 'China', 'Norway', 'India', 'England', 'Mexico', 'Yemen']
},
dims=['Country'])
@cache('step')
def _dpopulation_dt():
return births() - deaths()
integ_population = functions.Integ(lambda: _dpopulation_dt(), lambda: _init_population())
如果 example.py 文件选项卡不符合要求,我深表歉意。任何帮助,将不胜感激!