In [7]:
import pysd
In [1]:
#%pylab inline
import pysd
print(pysd.__version__)
# #print pysd.__file__
# import pandas as pd
# #import os
# # import xarray as xr
# import numpy as np
# import networkx as nx
In [3]:
l = [1, 2, 3]
while l:
print(l[0])
l.pop()
In [25]:
l = set([1, 2, 'burnside'])
j = set(['hi', 'bob'])
In [28]:
l.update(j)
l.difference_update(j)
l
Out[28]:
In [15]:
l.remove('burnside')
In [18]:
if l:
print(l)
In [ ]:
x = pd.Series(np.arange(0,40,1))
# y = pd.Series(index=range(0,40))
# y[:10] = x[:10]**2
# y[10:30] = -1*(x[10:30]-20)**2 + 2*x[10]**2
# y[30:40] = (x[30:40]-40)**2
y = -1*np.cos(x*2*np.pi/40)
plt.plot(x, y)
d1 = y.diff()
d2 = d1.diff()
inc_growth = (d1 > 0) & (d2 > 0)
dec_growth = (d1 > 0) & (d2 < 0)
inc_decline = (d1 < 0) & (d2 < 0)
dec_decline = (d1 < 0) & (d2 > 0)
(inc_growth[inc_growth].index.max() <
dec_growth[dec_growth].index.min() <
dec_growth[dec_growth].index.max() <
inc_decline[inc_decline].index.min() <
inc_decline[inc_decline].index.max() <
dec_decline[dec_decline].index.min())
In [3]:
model = pysd.read_vensim('tests/test-models/samples/teacup/teacup.mdl')
doc = model.doc()
doc
Out[3]:
In [3]:
pysd.testing.sample_pspace(model, samples=10)
Out[3]:
In [3]:
doc
Out[3]:
In [5]:
set(doc[doc['Type'] == 'constant']['Real Name']) - {'FINAL TIME', 'INITIAL TIME', 'TIME STEP'}
Out[5]:
In [160]:
import pyDOE
from scipy.stats.distributions import uniform, expon, truncnorm, norm
unit_lhd = pyDOE.lhs(2, samples=10, criterion='c')
lhd[:,0] = expon(loc=0, scale=4).ppf(unit_lhd[:,0])
lhd
In [162]:
expon(loc=-1, scale=-1).ppf(unit_lhd[:,0])
Out[162]:
In [149]:
lhd = pyDOE.lhs(2, samples=50000, criterion='c')
lhd[:,0] = expon(loc=0, scale=4).ppf(lhd[:,0])
lhd
Out[149]:
In [151]:
np.isinf(-np.inf)
Out[151]:
In [140]:
a = pd.DataFrame(index=range(10))
a['hi'] = 5
a
Out[140]:
In [132]:
model = pysd.read_vensim('tests/test-models/tests/variable_ranges/test_variable_ranges.mdl')
model.doc()['Real Name'].values
Out[132]:
In [133]:
df = pd.DataFrame(columns=['Unbounded Variable Value Above 0',
'Unbounded Variable Value Below 0', 'Both Bounds Above 0',
'Both Bounds Below 0', 'Both Bounds Identical',
'Unbounded Variable Value 0', 'Lower Bound 0',
'Lower Bound Above 0', 'Lower Bound Below 0', 'Upper Bound 0',
'Upper Bound Above 0', 'Upper Bound Below 0'], index=range(10), data=0)
for i, row in df.iterrows():
a = row
break
print(row)
In [110]:
for row in df.itertuples():
a = row
break
print(row)
In [116]:
import scipy.stats
In [118]:
data = scipy.random.normal(loc=10, size=100)
scipy.stats.kstest(rvs=data, cdf='norm')
Out[118]:
In [131]:
data = scipy.random.normal(loc=10, size=50000)
a = scipy.stats.kstest(rvs=data, cdf='uniform', args=(10,100))
a.pvalue
Out[131]:
If there are two ends defined, use a uniform distribution between them If only one end is defined, use exponential distribution with current location set as mean, other end as location If neither end is defined, use normal distribution with current value as mean, magnitude of current value as scale.
In [76]:
def sample_pspace(model=None, bounds=None, param_list=None, samples=100):
"""
In iterator over various locations in the parameter space,
useful for
Parameters
----------
model
bounds
param_list
samples: int
How many samples to include in the iterator?
Returns
-------
params: dictionary
dictionary of 'variable':'value' pairs
"""
if isinstance(bounds, pd.DataFrame):
bounds = bounds.set_index('Real Name')
elif bounds is None:
elif isinstance(bounds, str):
if bounds.split('.')[-1] in ['xls', 'xlsx']:
bounds = pd.read_excel(bounds, sheetname='Bounds', index_col='Real Name')
elif bounds.split('.')[-1] == 'csv':
bounds = pd.read_csv(bounds, index_col='Real Name')
elif bounds.split('.')[-1] == 'tab':
bounds = pd.read_csv(bounds, sep='\t', index_col='Real Name')
else:
raise ValueError('Unknown file type: bounds')
else:
raise ValueError('Unknown type: bounds')
if param_list is None:
param_list = list(bounds.index)
pyDOE.lhs()
In [29]:
model = pysd.read_vensim('tests/test-models/samples/pendulum/Single_Pendulum.mdl')
In [32]:
res = model.run()
res.plot()
Out[32]:
In [34]:
t_series = res['Angular Position']
#def is_periodic(t_series):
fft = np.fft.fft(t_series)
plt.plot(fft)
Out[34]:
In [38]:
from scipy import signal
xs = np.arange(0, 4*np.pi, 0.05)
data = np.sin(xs)
plt.plot(xs, data)
peakind = signal.find_peaks_cwt(data, np.arange(1,10))
peakind, xs[peakind], data[peakind]
Out[38]:
In [42]:
peakind = signal.find_peaks_cwt(t_series, np.arange(1,10))
multiple_peaks = len(peakind) > 1
multiple_peaks
Out[42]:
In [64]:
segment = int(np.mean(np.diff(peakind))/8)
segment
Out[64]:
In [66]:
measure = np.mean([t_series.autocorr(i) for i in range(1,segment)])
measure > .75
Out[66]:
In [17]:
a = pd.DataFrame(np.ones((3,3)))
a['hi'] = 3
a
(a.index==2).argmax()
Out[17]:
In [22]:
model = pysd.read_vensim('tests/test-models/samples/teacup/teacup.mdl')
model.doc()
Out[22]:
In [26]:
model = pysd.read_vensim('tests/test-models/samples/teacup/teacup.mdl')
result0 = model.run()
result1 = model.run(params={'Room Temperature': 1000})
result2 = model.run()
model.reload()
result3 = model.run()
self.assertTrue((result0 == result3).all().all())
self.assertFalse((result0 == result1).all().all())
self.assertTrue((result1 == result2).all().all())
In [ ]:
model.
In [21]:
model.run()
Out[21]:
In [ ]:
In [6]:
d = {'a':1, 'b':2}
In [10]:
for key, val in d.items():
print(key, val)
In [11]:
import time
time.time()
Out[11]:
In [15]:
class MyObj(object):
def __init__(self):
self.inittime = time.time()
def reload_self(self):
self.__init__()
In [16]:
a = MyObj()
a.inittime
Out[16]:
In [17]:
a.reload_self()
a.inittime
Out[17]:
In [ ]: