Code stringlengths 103 85.9k | Summary listlengths 0 94 |
|---|---|
Please provide a description of the function:def _separable_approx2(h, N=1):
return np.cumsum([np.outer(fy, fx) for fy, fx in _separable_series2(h, N)], 0) | [
" returns the N first approximations to the 2d function h\n whose sum should be h\n "
] |
Please provide a description of the function:def _separable_series3(h, N=1, verbose=False):
hx, hy, hz = [], [], []
res = h.copy()
for i in range(N):
_hx, _hy, _hz, P = _splitrank3(res, verbose=verbose)
res -= P
hx.append(_hx)
hy.append(_hy)
hz.append(_hz)
r... | [
" finds separable approximations to the 3d kernel h\n returns res = (hx,hy,hz)[N]\n s.t. h \\approx sum_i einsum(\"i,j,k\",res[i,0],res[i,1],res[i,2])\n\n FIXME: This is just a naive and slow first try!\n "
] |
Please provide a description of the function:def _separable_approx3(h, N=1):
return np.cumsum([np.einsum("i,j,k", fz, fy, fx) for fz, fy, fx in _separable_series3(h, N)], 0) | [
" returns the N first approximations to the 3d function h\n "
] |
Please provide a description of the function:def separable_series(h, N=1):
if h.ndim == 2:
return _separable_series2(h, N)
elif h.ndim == 3:
return _separable_series3(h, N)
else:
raise ValueError("unsupported array dimension: %s (only 2d or 3d) " % h.ndim) | [
"\n finds the first N rank 1 tensors such that their sum approximates\n the tensor h (2d or 3d) best\n\n returns (e.g. for 3d case) res = (hx,hy,hz)[i]\n\n s.t.\n\n h \\approx sum_i einsum(\"i,j,k\",res[i,0],res[i,1],res[i,2])\n\n Parameters\n ----------\n h: ndarray\n input array (2 ... |
Please provide a description of the function:def separable_approx(h, N=1):
if h.ndim == 2:
return _separable_approx2(h, N)
elif h.ndim == 3:
return _separable_approx3(h, N)
else:
raise ValueError("unsupported array dimension: %s (only 2d or 3d) " % h.ndim) | [
"\n finds the k-th rank approximation to h, where k = 1..N\n\n similar to separable_series\n\n Parameters\n ----------\n h: ndarray\n input array (2 or 2 dimensional)\n N: int\n order of approximation\n\n Returns\n -------\n all N apprxoimations res[i], the i-th approxim... |
Please provide a description of the function:def offset_to_timezone(offset, now=None):
now = now or datetime.now()
# JS offsets are flipped, so unflip.
user_offset = -offset
# Helper: timezone offset in minutes
def get_tz_offset(tz):
try:
return tz.utcoffset(now).total_sec... | [
"Convert a minutes offset (JavaScript-style) into a pytz timezone\n\n The ``now`` parameter is generally used for testing only\n "
] |
Please provide a description of the function:def tables(self):
_tables = set()
for attr in six.itervalues(self.__dict__):
if isinstance(attr, list):
for item in attr:
if isinstance(item, Node):
_tables |= item.tables()
... | [
"\n Generic method that does a depth-first search on the node attributes.\n\n Child classes should override this method for better performance.\n "
] |
Please provide a description of the function:def transform(pattern):
result = []
groups = [[pattern]]
while groups:
children = groups.pop(0)
parents = [Required, Optional, OptionsShortcut, Either, OneOrMore]
if any(t in map(type, children) for t in parents):
child = ... | [
"Expand pattern into an (almost) equivalent one, but with single Either.\n\n Example: ((-a | -b) (-c | -d)) => (-a -c | -a -d | -b -c | -b -d)\n Quirks: [-a] => (-a), (-a...) => (-a -a)\n\n "
] |
Please provide a description of the function:def parse_long(tokens, options):
long, eq, value = tokens.move().partition('=')
assert long.startswith('--')
value = None if eq == value == '' else value
similar = [o for o in options if o.long == long]
if tokens.error is DocoptExit and similar == []... | [
"long ::= '--' chars [ ( ' ' | '=' ) chars ] ;"
] |
Please provide a description of the function:def parse_shorts(tokens, options):
token = tokens.move()
assert token.startswith('-') and not token.startswith('--')
left = token.lstrip('-')
parsed = []
while left != '':
short, left = '-' + left[0], left[1:]
similar = [o for o in op... | [
"shorts ::= '-' ( chars )* [ [ ' ' ] chars ] ;"
] |
Please provide a description of the function:def docopt(doc, argv=None, help=True, version=None, options_first=False):
argv = sys.argv[1:] if argv is None else argv
usage_sections = parse_section('usage:', doc)
if len(usage_sections) == 0:
raise DocoptLanguageError('"usage:" (case-insensitive)... | [
"Parse `argv` based on command-line interface described in `doc`.\n\n `docopt` creates your command-line interface based on its\n description that you pass as `doc`. Such description can contain\n --options, <positional-argument>, commands, which could be\n [optional], (required), (mutually | exclusive)... |
Please provide a description of the function:def fix_identities(self, uniq=None):
if not hasattr(self, 'children'):
return self
uniq = list(set(self.flat())) if uniq is None else uniq
for i, child in enumerate(self.children):
if not hasattr(child, 'children'):
... | [
"Make pattern-tree tips point to same object if they are equal."
] |
Please provide a description of the function:def fix_repeating_arguments(self):
either = [list(child.children) for child in transform(self).children]
for case in either:
for e in [child for child in case if case.count(child) > 1]:
if type(e) is Argument or type(e) is... | [
"Fix elements that should accumulate/increment values."
] |
Please provide a description of the function:def find_version(fname):
version = ""
with open(fname, "r") as fp:
reg = re.compile(r'__version__ = [\'"]([^\'"]*)[\'"]')
for line in fp:
m = reg.match(line)
if m:
version = m.group(1)
break... | [
"Attempts to find the version number in the file names fname.\n Raises RuntimeError if not found.\n "
] |
Please provide a description of the function:def format_context(
context: Context, formatter: typing.Union[str, Formatter] = "full"
) -> str:
if not context:
return ""
if callable(formatter):
formatter_func = formatter
else:
if formatter in CONTEXT_FORMATTERS:
f... | [
"Output the a context dictionary as a string."
] |
Please provide a description of the function:def make_banner(
text: typing.Optional[str] = None,
context: typing.Optional[Context] = None,
banner_template: typing.Optional[str] = None,
context_format: ContextFormat = "full",
) -> str:
banner_text = text or speak()
banner_template = banner_t... | [
"Generates a full banner with version info, the given text, and a\n formatted list of context variables.\n "
] |
Please provide a description of the function:def context_list2dict(context_list: typing.Sequence[typing.Any]) -> Context:
return {obj.__name__.split(".")[-1]: obj for obj in context_list} | [
"Converts a list of objects (functions, classes, or modules) to a\n dictionary mapping the object names to the objects.\n "
] |
Please provide a description of the function:def start(
context: typing.Optional[typing.Mapping] = None,
banner: typing.Optional[str] = None,
shell: typing.Type[Shell] = AutoShell,
prompt: typing.Optional[str] = None,
output: typing.Optional[str] = None,
context_format: str = "full",
**kwarg... | [
"Start up the konch shell. Takes the same parameters as Shell.__init__.\n "
] |
Please provide a description of the function:def config(config_dict: typing.Mapping) -> Config:
logger.debug(f"Updating with {config_dict}")
_cfg.update(config_dict)
return _cfg | [
"Configures the konch shell. This function should be called in a\n .konchrc file.\n\n :param dict config_dict: Dict that may contain 'context', 'banner', and/or\n 'shell' (default shell class to use).\n "
] |
Please provide a description of the function:def named_config(name: str, config_dict: typing.Mapping) -> None:
names = (
name
if isinstance(name, Iterable) and not isinstance(name, (str, bytes))
else [name]
)
for each in names:
_config_registry[each] = Config(**config_di... | [
"Adds a named config to the config registry. The first argument\n may either be a string or a collection of strings.\n\n This function should be called in a .konchrc file.\n "
] |
Please provide a description of the function:def __ensure_directory_in_path(filename: Path) -> None:
directory = Path(filename).parent.resolve()
if directory not in sys.path:
logger.debug(f"Adding {directory} to sys.path")
sys.path.insert(0, str(directory)) | [
"Ensures that a file's directory is in the Python path.\n "
] |
Please provide a description of the function:def confirm(text: str, default: bool = False) -> bool:
choices = "Y/n" if default else "y/N"
prompt = f"{style(text, bold=True)} [{choices}]: "
while 1:
try:
print(prompt, end="")
value = input("").lower().strip()
exce... | [
"Display a confirmation prompt."
] |
Please provide a description of the function:def use_file(
filename: typing.Union[Path, str, None], trust: bool = False
) -> typing.Union[types.ModuleType, None]:
config_file = filename or resolve_path(CONFIG_FILE)
def preview_unauthorized() -> None:
if not config_file:
return None... | [
"Load filename as a python file. Import ``filename`` and return it\n as a module.\n "
] |
Please provide a description of the function:def resolve_path(filename: Path) -> typing.Union[Path, None]:
current = Path.cwd()
# Stop search at home directory
sentinel_dir = Path.home().parent.resolve()
while current != sentinel_dir:
target = Path(current) / Path(filename)
if targe... | [
"Find a file by walking up parent directories until the file is found.\n Return the absolute path of the file.\n "
] |
Please provide a description of the function:def parse_args(argv: typing.Optional[typing.Sequence] = None) -> typing.Dict[str, str]:
return docopt(__doc__, argv=argv, version=__version__) | [
"Exposes the docopt command-line arguments parser.\n Return a dictionary of arguments.\n "
] |
Please provide a description of the function:def main(argv: typing.Optional[typing.Sequence] = None) -> typing.NoReturn:
args = parse_args(argv)
if args["--debug"]:
logging.basicConfig(
format="%(levelname)s %(filename)s: %(message)s", level=logging.DEBUG
)
logger.debug(arg... | [
"Main entry point for the konch CLI."
] |
Please provide a description of the function:def init_autoreload(mode: int) -> None:
from IPython.extensions import autoreload
ip = get_ipython() # type: ignore # noqa: F821
autoreload.load_ipython_extension(ip)
ip.magics_manager.magics["line"]["autoreload"](str(mode)) | [
"Load and initialize the IPython autoreload extension."
] |
Please provide a description of the function:def parse(self, text, element, context='eqn'):
# Remove the inline comments from `text` before parsing the grammar
# http://docs.oasis-open.org/xmile/xmile/v1.0/csprd01/xmile-v1.0-csprd01.html#_Toc398039973
text = re.sub(r"\{[^}]*\}"... | [
"\n context : <string> 'eqn', 'defn'\n If context is set to equation, lone identifiers will be parsed as calls to elements\n If context is set to definition, lone identifiers will be cleaned and returned.\n "
] |
Please provide a description of the function:def read_tabular(table_file, sheetname='Sheet1'):
if isinstance(table_file, str):
extension = table_file.split('.')[-1]
if extension in ['xls', 'xlsx']:
table = pd.read_excel(table_file, sheetname=sheetname)
elif extension == 'cs... | [
"\n Reads a vensim syntax model which has been formatted as a table.\n\n This is useful in contexts where model building is performed\n without the aid of Vensim.\n\n Parameters\n ----------\n table_file: .csv, .tab or .xls(x) file\n\n Table should have columns titled as in the table below\n\n\... |
Please provide a description of the function:def read_xmile(xmile_file):
from . import py_backend
from .py_backend.xmile.xmile2py import translate_xmile
py_model_file = translate_xmile(xmile_file)
model = load(py_model_file)
model.xmile_file = xmile_file
return model | [
" Construct a model object from `.xmile` file. "
] |
Please provide a description of the function:def read_vensim(mdl_file):
from .py_backend.vensim.vensim2py import translate_vensim
from .py_backend import functions
py_model_file = translate_vensim(mdl_file)
model = functions.Model(py_model_file)
model.mdl_file = mdl_file
return model | [
"\n Construct a model from Vensim `.mdl` file.\n\n Parameters\n ----------\n mdl_file : <string>\n The relative path filename for a raw Vensim `.mdl` file\n\n Returns\n -------\n model: a PySD class object\n Elements from the python model are loaded into the PySD class and ready t... |
Please provide a description of the function:def cache(horizon):
def cache_step(func):
@wraps(func)
def cached(*args):
try: # fails if cache is out of date or not instantiated
data = func.__globals__['__data']
assert cached.ca... | [
"\n Put a wrapper around a model function\n\n Decorators with parameters are tricky, you have to\n essentially create a decorator that returns a decorator,\n which itself then returns the function wrapper.\n\n Parameters\n ----------\n horizon: string\n - 'step' means cache just until th... |
Please provide a description of the function:def ramp(time, slope, start, finish=0):
t = time()
if t < start:
return 0
else:
if finish <= 0:
return slope * (t - start)
elif t > finish:
return slope * (finish - start)
else:
return slop... | [
"\n Implements vensim's and xmile's RAMP function\n\n Parameters\n ----------\n time: function\n The current time of modelling\n slope: float\n The slope of the ramp starting at zero at time start\n start: float\n Time at which the ramp begins\n finish: float\n Optio... |
Please provide a description of the function:def pulse(time, start, duration):
t = time()
return 1 if start <= t < start + duration else 0 | [
" Implements vensim's PULSE function\n\n In range [-inf, start) returns 0\n In range [start, start + duration) returns 1\n In range [start + duration, +inf] returns 0\n "
] |
Please provide a description of the function:def pulse_train(time, start, duration, repeat_time, end):
t = time()
if start <= t < end:
return 1 if (t - start) % repeat_time < duration else 0
else:
return 0 | [
" Implements vensim's PULSE TRAIN function\n\n In range [-inf, start) returns 0\n In range [start + n * repeat_time, start + n * repeat_time + duration) return 1\n In range [start + n * repeat_time + duration, start + (n+1) * repeat_time) return 0\n "
] |
Please provide a description of the function:def pulse_magnitude(time, magnitude, start, repeat_time=0):
t = time()
small = 1e-6 # What is considered zero according to Vensim Help
if repeat_time <= small:
if abs(t - start) < time.step():
return magnitude * time.step()
else:... | [
" Implements xmile's PULSE function\n \n PULSE: Generate a one-DT wide pulse at the given time\n Parameters: 2 or 3: (magnitude, first time[, interval])\n Without interval or when interval = 0, the PULSE is generated only once\n Example: PULSE(20, 12, ... |
Please provide a description of the function:def lookup_extrapolation(x, xs, ys):
length = len(xs)
if x < xs[0]:
dx = xs[1] - xs[0]
dy = ys[1] - ys[0]
k = dy / dx
return ys[0] + (x - xs[0]) * k
if x > xs[length - 1]:
dx = xs[length - 1] - xs[length - 2]
d... | [
"\n Intermediate values are calculated with linear interpolation between the intermediate points.\n Out-of-range values are calculated with linear extrapolation from the last two values at either end.\n "
] |
Please provide a description of the function:def lookup_discrete(x, xs, ys):
for index in range(0, len(xs)):
if x < xs[index]:
return ys[index - 1] if index > 0 else ys[index]
return ys[len(ys) - 1] | [
"\n Intermediate values take on the value associated with the next lower x-coordinate (also called a step-wise function). The last two points of a discrete graphical function must have the same y value.\n Out-of-range values are the same as the closest endpoint (i.e, no extrapolation is performed).\n "
] |
Please provide a description of the function:def xidz(numerator, denominator, value_if_denom_is_zero):
small = 1e-6 # What is considered zero according to Vensim Help
if abs(denominator) < small:
return value_if_denom_is_zero
else:
return numerator * 1.0 / denominator | [
"\n Implements Vensim's XIDZ function.\n This function executes a division, robust to denominator being zero.\n In the case of zero denominator, the final argument is returned.\n\n Parameters\n ----------\n numerator: float\n denominator: float\n Components of the division operation\n ... |
Please provide a description of the function:def initialize(self, initialization_order=None):
# Initialize time
if self.time is None:
if self.time_initialization is None:
self.time = Time()
else:
self.time = self.time_initialization()
... | [
"\n This function tries to initialize the stateful objects.\n\n In the case where an initialization function for `Stock A` depends on\n the value of `Stock B`, if we try to initialize `Stock A` before `Stock B`\n then we will get an error, as the value will not yet exist.\n\n In t... |
Please provide a description of the function:def set_components(self, params):
# It might make sense to allow the params argument to take a pandas series, where
# the indices of the series are variable names. This would make it easier to
# do a Pandas apply on a DataFrame of parameter v... | [
" Set the value of exogenous model elements.\n Element values can be passed as keyword=value pairs in the function call.\n Values can be numeric type or pandas Series.\n Series will be interpolated by integrator.\n\n Examples\n --------\n\n >>> model.set_components({'birth_... |
Please provide a description of the function:def _timeseries_component(self, series):
# this is only called if the set_component function recognizes a pandas series
# Todo: raise a warning if extrapolating from the end of the series.
return lambda: np.interp(self.time(), series.index, s... | [
" Internal function for creating a timeseries model element "
] |
Please provide a description of the function:def set_state(self, t, state):
self.time.update(t)
for key, value in state.items():
# TODO Implement map with reference between component and stateful element?
component_name = utils.get_value_by_insensitive_key_or_value(key,... | [
" Set the system state.\n\n Parameters\n ----------\n t : numeric\n The system time\n\n state : dict\n A (possibly partial) dictionary of the system state.\n The keys to this dictionary may be either pysafe names or original model file names\n "
] |
Please provide a description of the function:def clear_caches(self):
for element_name in dir(self.components):
element = getattr(self.components, element_name)
if hasattr(element, 'cache_val'):
delattr(element, 'cache_val') | [
" Clears the Caches for all model elements "
] |
Please provide a description of the function:def doc(self):
collector = []
for name, varname in self.components._namespace.items():
try:
docstring = getattr(self.components, varname).__doc__
lines = docstring.split('\n')
collector.appe... | [
"\n Formats a table of documentation strings to help users remember variable names, and\n understand how they are translated into python safe names.\n\n Returns\n -------\n docs_df: pandas dataframe\n Dataframe with columns for the model components:\n - R... |
Please provide a description of the function:def initialize(self):
self.time.update(self.components.initial_time())
self.time.stage = 'Initialization'
super(Model, self).initialize() | [
" Initializes the simulation model "
] |
Please provide a description of the function:def _build_euler_timeseries(self, return_timestamps=None):
t_0 = self.time()
t_f = return_timestamps[-1]
dt = self.components.time_step()
ts = np.arange(t_0, t_f, dt, dtype=np.float64)
# Add the returned time series into the ... | [
"\n - The integration steps need to include the return values.\n - There is no point running the model past the last return value.\n - The last timestep will be the last in that requested for return\n - Spacing should be at maximum what is specified by the integration time step.\n ... |
Please provide a description of the function:def _format_return_timestamps(self, return_timestamps=None):
if return_timestamps is None:
# Build based upon model file Start, Stop times and Saveper
# Vensim's standard is to expect that the data set includes the `final time`,
... | [
"\n Format the passed in return timestamps value as a numpy array.\n If no value is passed, build up array of timestamps based upon\n model start and end times, and the 'saveper' value.\n "
] |
Please provide a description of the function:def run(self, params=None, return_columns=None, return_timestamps=None,
initial_condition='original', reload=False):
if reload:
self.reload()
if params:
self.set_components(params)
self.set_initial_condit... | [
" Simulate the model's behavior over time.\n Return a pandas dataframe with timestamps as rows,\n model elements as columns.\n\n Parameters\n ----------\n params : dictionary\n Keys are strings of model component names.\n Values are numeric or pandas Series.\... |
Please provide a description of the function:def _default_return_columns(self):
return_columns = []
parsed_expr = []
for key, value in self.components._namespace.items():
if hasattr(self.components, value):
sig = signature(getattr(self.components, value))
... | [
"\n Return a list of the model elements that does not include lookup functions\n or other functions that take parameters.\n "
] |
Please provide a description of the function:def set_initial_condition(self, initial_condition):
if isinstance(initial_condition, tuple):
# Todo: check the values more than just seeing if they are a tuple.
self.set_state(*initial_condition)
elif isinstance(initial_condi... | [
" Set the initial conditions of the integration.\n\n Parameters\n ----------\n initial_condition : <string> or <tuple>\n Takes on one of the following sets of values:\n\n * 'original'/'o' : Reset to the model-file specified initial condition.\n * 'current'/'c' :... |
Please provide a description of the function:def _euler_step(self, dt):
self.state = self.state + self.ddt() * dt | [
" Performs a single step in the euler integration,\n updating stateful components\n\n Parameters\n ----------\n dt : float\n This is the amount to increase time by this step\n "
] |
Please provide a description of the function:def _integrate(self, time_steps, capture_elements, return_timestamps):
# Todo: consider adding the timestamp to the return elements, and using that as the index
outputs = []
for t2 in time_steps[1:]:
if self.time() in return_time... | [
"\n Performs euler integration\n\n Parameters\n ----------\n time_steps: iterable\n the time steps that the integrator progresses over\n capture_elements: list\n which model elements to capture - uses pysafe names\n return_timestamps:\n whic... |
Please provide a description of the function:def translate_xmile(xmile_file):
# process xml file
xml_parser = etree.XMLParser(encoding="utf-8", recover=True)
root = etree.parse(xmile_file, parser=xml_parser).getroot()
NS = root.nsmap[None] # namespace of the xmile document
def get_xpath_text... | [
" Translate an xmile model file into a python class.\n Functionality is currently limited.\n\n ",
" Safe access of occassionally missing elements ",
" Safe access of occassionally missing elements "
] |
Please provide a description of the function:def build(elements, subscript_dict, namespace, outfile_name):
# Todo: deal with model level documentation
# Todo: Make np, PySD.functions import conditional on usage in the file
# Todo: Make presence of subscript_dict instantiation conditional on usage
#... | [
"\n Actually constructs and writes the python representation of the model\n\n Parameters\n ----------\n elements: list\n Each element is a dictionary, with the various components needed to assemble\n a model component in python syntax. This will contain multiple entries for\n elemen... |
Please provide a description of the function:def build_element(element, subscript_dict):
if element['kind'] == 'constant':
cache_type = "@cache('run')"
elif element['kind'] in ['setup', 'stateful']: # setups only get called once, caching is wasted
cache_type = ''
elif element['kind'] =... | [
"\n Returns a string that has processed a single element dictionary\n Parameters\n ----------\n element: dictionary\n dictionary containing at least the elements:\n - kind: ['constant', 'setup', 'component', 'lookup']\n Different types of elements will be built differently\n ... |
Please provide a description of the function:def merge_partial_elements(element_list):
outs = dict() # output data structure
for element in element_list:
if element['py_expr'] != "None": # for
name = element['py_name']
if name not in outs:
# Use 'expr' for ... | [
"\n merges model elements which collectively all define the model component,\n mostly for multidimensional subscripts\n\n Parameters\n ----------\n element_list\n\n Returns\n -------\n "
] |
Please provide a description of the function:def add_stock(identifier, subs, expression, initial_condition, subscript_dict):
new_structure = []
if len(subs) == 0:
stateful_py_expr = 'functions.Integ(lambda: %s, lambda: %s)' % (expression,
... | [
"\n Creates new model element dictionaries for the model elements associated\n with a stock.\n\n Parameters\n ----------\n identifier: basestring\n the python-safe name of the stock\n\n subs: list\n a list of subscript elements\n\n expression: basestring\n The formula which... |
Please provide a description of the function:def add_n_delay(delay_input, delay_time, initial_value, order, subs, subscript_dict):
# the py name has to be unique to all the passed parameters, or if there are two things
# that delay the output by different amounts, they'll overwrite the original function...... | [
"\n Creates code to instantiate a stateful 'Delay' object,\n and provides reference to that object's output.\n\n The name of the stateful object is based upon the passed in parameters, so if\n there are multiple places where identical delay functions are referenced, the\n translated python file will ... |
Please provide a description of the function:def add_n_smooth(smooth_input, smooth_time, initial_value, order, subs, subscript_dict):
stateful = {
'py_name': utils.make_python_identifier('_smooth_%s_%s_%s_%s' % (smooth_input,
smoo... | [
"Constructs stock and flow chains that implement the calculation of\n a smoothing function.\n\n Parameters\n ----------\n smooth_input: <string>\n Reference to the model component that is the input to the smoothing function\n\n smooth_time: <string>\n Can be ... |
Please provide a description of the function:def add_n_trend(trend_input, average_time, initial_trend, subs, subscript_dict):
stateful = {
'py_name': utils.make_python_identifier('_trend_%s_%s_%s' % (trend_input,
average_time,
... | [
"Trend.\n\n Parameters\n ----------\n trend_input: <string>\n\n average_time: <string>\n\n\n trend_initial: <string>\n\n subs: list of strings\n List of strings of subscript indices that correspond to the\n list of expressions, and collectively define ... |
Please provide a description of the function:def add_initial(initial_input):
stateful = {
'py_name': utils.make_python_identifier('_initial_%s' % initial_input)[0],
'real_name': 'Smooth of %s' % initial_input,
'doc': 'Returns the value taken on during the initialization phase',
... | [
"\n Constructs a stateful object for handling vensim's 'Initial' functionality\n\n Parameters\n ----------\n initial_input: basestring\n The expression which will be evaluated, and the first value of which returned\n\n Returns\n -------\n reference: basestring\n reference to the I... |
Please provide a description of the function:def add_macro(macro_name, filename, arg_names, arg_vals):
func_args = '{ %s }' % ', '.join(["'%s': lambda: %s" % (key, val) for key, val in
zip(arg_names, arg_vals)])
stateful = {
'py_name': '_macro_' + macro_name +... | [
"\n Constructs a stateful object instantiating a 'Macro'\n\n Parameters\n ----------\n macro_name: basestring\n python safe name for macro\n filename: basestring\n filepath to macro definition\n func_args: dict\n dictionary of values to be passed to macro\n {key: functi... |
Please provide a description of the function:def add_incomplete(var_name, dependencies):
warnings.warn('%s has no equation specified' % var_name,
SyntaxWarning, stacklevel=2)
# first arg is `self` reference
return "functions.incomplete(%s)" % ', '.join(dependencies[1:]), [] | [
"\n Incomplete functions don't really need to be 'builders' as they\n add no new real structure, but it's helpful to have a function\n in which we can raise a warning about the incomplete equation\n at translate time.\n "
] |
Please provide a description of the function:def get_file_sections(file_str):
# the leading 'r' for 'raw' in this string is important for handling backslashes properly
file_structure_grammar = _include_common_grammar(r)
parser = parsimonious.Grammar(file_structure_grammar)
tree = parser.parse(fil... | [
"\n This is where we separate out the macros from the rest of the model file.\n Working based upon documentation at: https://www.vensim.com/documentation/index.html?macros.htm\n\n Macros will probably wind up in their own python modules eventually.\n\n Parameters\n ----------\n file_str\n\n Ret... |
Please provide a description of the function:def get_model_elements(model_str):
model_structure_grammar = _include_common_grammar(r)
parser = parsimonious.Grammar(model_structure_grammar)
tree = parser.parse(model_str)
class ModelParser(parsimonious.NodeVisitor):
def __init__(self, ast):... | [
"\n Takes in a string representing model text and splits it into elements\n\n I think we're making the assumption that all newline characters are removed...\n\n Parameters\n ----------\n model_str : string\n\n\n Returns\n -------\n entries : array of dictionaries\n Each dictionary con... |
Please provide a description of the function:def get_equation_components(equation_str):
component_structure_grammar = _include_common_grammar(r)
# replace any amount of whitespace with a single space
equation_str = equation_str.replace('\\t', ' ')
equation_str = re.sub(r"\s+", ' ', equation_str)... | [
"\n Breaks down a string representing only the equation part of a model element.\n Recognizes the various types of model elements that may exist, and identifies them.\n\n Parameters\n ----------\n equation_str : basestring\n the first section in each model element - the full equation.\n\n R... |
Please provide a description of the function:def parse_units(units_str):
if not len(units_str):
return units_str, (None, None)
if units_str[-1] == ']':
units, lims = units_str.rsplit('[') # type: str, str
else:
units = units_str
lims = '?, ?]'
lims = tuple([float(... | [
"\n Extract and parse the units\n Extract the bounds over which the expression is assumed to apply.\n\n Parameters\n ----------\n units_str\n\n Returns\n -------\n\n Examples\n --------\n >>> parse_units('Widgets/Month [-10,10,1]')\n ('Widgets/Month', (-10,10,1))\n\n >>> parse_un... |
Please provide a description of the function:def parse_general_expression(element, namespace=None, subscript_dict=None, macro_list=None):
if namespace is None:
namespace = {}
if subscript_dict is None:
subscript_dict = {}
in_ops = {
"+": "+", "-": "-", "*": "*", "/": "/", "^": ... | [
"\n Parses a normal expression\n # its annoying that we have to construct and compile the grammar every time...\n\n Parameters\n ----------\n element: dictionary\n\n namespace : dictionary\n\n subscript_dict : dictionary\n\n macro_list: list of dictionaries\n [{'name': 'M', 'py_name':... |
Please provide a description of the function:def parse_lookup_expression(element):
lookup_grammar = r
parser = parsimonious.Grammar(lookup_grammar)
tree = parser.parse(element['expr'])
class LookupParser(parsimonious.NodeVisitor):
def __init__(self, ast):
self.translation = ""... | [
" This syntax parses lookups that are defined with their own element ",
"\n lookup = _ \"(\" range? _ ( \"(\" _ number _ \",\" _ number _ \")\" _ \",\"? _ )+ \")\"\n number = (\"+\"/\"-\")? ~r\"\\d+\\.?\\d*(e[+-]\\d+)?\"\n _ = ~r\"[\\s\\\\]*\" # whitespace character\n\trange = _ \"[\" ~r\"[^\\]]*\" \"]\... |
Please provide a description of the function:def dict_find(in_dict, value):
# Todo: make this robust to repeated values
# Todo: make this robust to missing values
return list(in_dict.keys())[list(in_dict.values()).index(value)] | [
" Helper function for looking up directory keys by their values.\n This isn't robust to repeated values\n\n Parameters\n ----------\n in_dict : dictionary\n A dictionary containing `value`\n\n value : any type\n What we wish to find in the dictionary\n\n Returns\n -------\n ke... |
Please provide a description of the function:def xrmerge(das, accept_new=True):
da = das[0]
for new_da in das[1:]:
# Expand both to have same dimensions, padding with NaN
da, new_da = xr.align(da, new_da, join='outer')
# Fill NaNs one way or the other re. accept_new
da = new... | [
"\n Merges xarrays with different dimension sets\n Parameters\n ----------\n das : list of data_arrays\n\n accept_new\n\n Returns\n -------\n da : an xarray that is the merge of das\n\n References\n ----------\n Thanks to @jcmgray https://github.com/pydata/xarray/issues/742#issue-13... |
Please provide a description of the function:def find_subscript_name(subscript_dict, element):
if element in subscript_dict.keys():
return element
for name, elements in subscript_dict.items():
if element in elements:
return name | [
"\n Given a subscript dictionary, and a member of a subscript family,\n return the first key of which the member is within the value list.\n If element is already a subscript name, return that\n\n Parameters\n ----------\n subscript_dict: dictionary\n Follows the {'subscript name':['list','... |
Please provide a description of the function:def make_coord_dict(subs, subscript_dict, terse=True):
sub_elems_list = [y for x in subscript_dict.values() for y in x]
coordinates = {}
for sub in subs:
if sub in sub_elems_list:
name = find_subscript_name(subscript_dict, sub)
... | [
"\n This is for assisting with the lookup of a particular element, such that the output\n of this function would take the place of %s in this expression\n\n `variable.loc[%s]`\n\n Parameters\n ----------\n subs: list of strings\n coordinates, either as names of dimensions, or positions with... |
Please provide a description of the function:def make_python_identifier(string, namespace=None, reserved_words=None,
convert='drop', handle='force'):
if namespace is None:
namespace = dict()
if reserved_words is None:
reserved_words = list()
if string in na... | [
"\n Takes an arbitrary string and creates a valid Python identifier.\n\n If the input string is in the namespace, return its value.\n\n If the python identifier created is already in the namespace,\n but the input string is not (ie, two similar strings resolve to\n the same python identifier)\n\n ... |
Please provide a description of the function:def make_flat_df(frames, return_addresses):
# Todo: could also try a list comprehension here, or parallel apply
visited = list(map(lambda x: visit_addresses(x, return_addresses), frames))
return pd.DataFrame(visited) | [
"\n Takes a list of dictionaries, each representing what is returned from the\n model at a particular time, and creates a dataframe whose columns correspond\n to the keys of `return addresses`\n\n Parameters\n ----------\n frames: list of dictionaries\n each dictionary represents the result... |
Please provide a description of the function:def visit_addresses(frame, return_addresses):
outdict = dict()
for real_name, (pyname, address) in return_addresses.items():
if address:
xrval = frame[pyname].loc[address]
if xrval.size > 1:
outdict[real_name] = xr... | [
"\n Visits all of the addresses, returns a new dict\n which contains just the addressed elements\n\n\n Parameters\n ----------\n frame\n return_addresses: a dictionary,\n keys will be column names of the resulting dataframe, and are what the\n user passed in as 'return_columns'. Valu... |
Please provide a description of the function:def validate_request(request):
if getattr(settings, 'BASICAUTH_DISABLE', False):
# Not to use this env
return True
if 'HTTP_AUTHORIZATION' not in request.META:
return False
authorization_header = request.META['HTTP_AUTHORIZATION']
... | [
"Check an incoming request.\n\n Returns:\n - True if authentication passed\n - Adding request['REMOTE_USER'] as authenticated username.\n "
] |
Please provide a description of the function:def _find_address_range(addresses):
first = last = addresses[0]
last_index = 0
for ip in addresses[1:]:
if ip._ip == last._ip + 1:
last = ip
last_index += 1
else:
break
return (first, last, last_index) | [
"Find a sequence of addresses.\n\n Args:\n addresses: a list of IPv4 or IPv6 addresses.\n\n Returns:\n A tuple containing the first and last IP addresses in the sequence,\n and the index of the last IP address in the sequence.\n\n "
] |
Please provide a description of the function:def _prefix_from_prefix_int(self, prefixlen):
if not isinstance(prefixlen, (int, long)):
raise NetmaskValueError('%r is not an integer' % prefixlen)
prefixlen = int(prefixlen)
if not (0 <= prefixlen <= self._max_prefixlen):
... | [
"Validate and return a prefix length integer.\n\n Args:\n prefixlen: An integer containing the prefix length.\n\n Returns:\n The input, possibly converted from long to int.\n\n Raises:\n NetmaskValueError: If the input is not an integer, or out of range.\n ... |
Please provide a description of the function:def output_colored(code, text, is_bold=False):
if is_bold:
code = '1;%s' % code
return '\033[%sm%s\033[0m' % (code, text) | [
"\n Create function to output with color sequence\n "
] |
Please provide a description of the function:def init_app(self, app):
# Setup a few sane defaults.
app.config.setdefault('WEBPACK_MANIFEST_PATH',
'/tmp/themostridiculousimpossiblepathtonotexist')
app.config.setdefault('WEBPACK_ASSETS_URL', None)
s... | [
"\n Mutate the application passed in as explained here:\n http://flask.pocoo.org/docs/0.10/extensiondev/\n\n :param app: Flask application\n :return: None\n "
] |
Please provide a description of the function:def _set_asset_paths(self, app):
webpack_stats = app.config['WEBPACK_MANIFEST_PATH']
try:
with app.open_resource(webpack_stats, 'r') as stats_json:
stats = json.load(stats_json)
if app.config['WEBPACK_ASS... | [
"\n Read in the manifest json file which acts as a manifest for assets.\n This allows us to get the asset path as well as hashed names.\n\n :param app: Flask application\n :return: None\n "
] |
Please provide a description of the function:def javascript_tag(self, *args):
tags = []
for arg in args:
asset_path = self.asset_url_for('{0}.js'.format(arg))
if asset_path:
tags.append('<script src="{0}"></script>'.format(asset_path))
return '\... | [
"\n Convenience tag to output 1 or more javascript tags.\n\n :param args: 1 or more javascript file names\n :return: Script tag(s) containing the asset\n "
] |
Please provide a description of the function:def asset_url_for(self, asset):
if '//' in asset:
return asset
if asset not in self.assets:
return None
return '{0}{1}'.format(self.assets_url, self.assets[asset]) | [
"\n Lookup the hashed asset path of a file name unless it starts with\n something that resembles a web address, then take it as is.\n\n :param asset: A logical path to an asset\n :type asset: str\n :return: Asset path or None if not found\n "
] |
Please provide a description of the function:def pre_change_receiver(self, instance: Model, action: Action):
if action == Action.CREATE:
group_names = set()
else:
group_names = set(self.group_names(instance))
# use a thread local dict to be safe...
if no... | [
"\n Entry point for triggering the old_binding from save signals.\n "
] |
Please provide a description of the function:def post_change_receiver(self, instance: Model, action: Action, **kwargs):
try:
old_group_names = instance.__instance_groups.observers[self]
except (ValueError, KeyError):
old_group_names = set()
if action == Action.D... | [
"\n Triggers the old_binding to possibly send to its group.\n "
] |
Please provide a description of the function:def get_queryset(self, **kwargs) -> QuerySet:
assert self.queryset is not None, (
"'%s' should either include a `queryset` attribute, "
"or override the `get_queryset()` method."
% self.__class__.__name__
)
... | [
"\n Get the list of items for this view.\n This must be an iterable, and may be a queryset.\n Defaults to using `self.queryset`.\n\n This method should always be used rather than accessing `self.queryset`\n directly, as `self.queryset` gets evaluated only once, and those results\n... |
Please provide a description of the function:def get_object(self, **kwargs) ->Model:
queryset = self.filter_queryset(
queryset=self.get_queryset(**kwargs),
**kwargs
)
# Perform the lookup filtering.
lookup_url_kwarg = self.lookup_url_kwarg or self.lookup... | [
"\n Returns the object the view is displaying.\n\n You may want to override this if you need to provide non-standard\n queryset lookups. Eg if objects are referenced using multiple\n keyword arguments in the url conf.\n "
] |
Please provide a description of the function:def get_serializer(
self,
action_kwargs: Dict=None,
*args, **kwargs) -> Serializer:
serializer_class = self.get_serializer_class(
**action_kwargs
)
kwargs['context'] = self.get_serializer_conte... | [
"\n Return the serializer instance that should be used for validating and\n deserializing input, and for serializing output.\n "
] |
Please provide a description of the function:def get_serializer_class(self, **kwargs) -> Type[Serializer]:
assert self.serializer_class is not None, (
"'%s' should either include a `serializer_class` attribute, "
"or override the `get_serializer_class()` method."
% s... | [
"\n Return the class to use for the serializer.\n Defaults to using `self.serializer_class`.\n\n You may want to override this if you need to provide different\n serializations depending on the incoming request.\n\n (Eg. admins get full serialization, others get basic serializatio... |
Please provide a description of the function:async def handle_observed_action(self,
action: str, request_id: str, **kwargs):
try:
await self.check_permissions(action, **kwargs)
reply = partial(self.reply, action=action, request_id=request_id... | [
"\n run the action.\n "
] |
Please provide a description of the function:def view_as_consumer(
wrapped_view: typing.Callable[[HttpRequest], HttpResponse],
mapped_actions: typing.Optional[
typing.Dict[str, str]
]=None) -> Type[AsyncConsumer]:
if mapped_actions is None:
mapped_actions = {
... | [
"\n Wrap a django View so that it will be triggered by actions over this json\n websocket consumer.\n "
] |
Please provide a description of the function:async def check_permissions(self, action: str, **kwargs):
for permission in await self.get_permissions(action=action, **kwargs):
if not await ensure_async(permission.has_permission)(
scope=self.scope, consumer=self, action=ac... | [
"\n Check if the action should be permitted.\n Raises an appropriate exception if the request is not permitted.\n "
] |
Please provide a description of the function:async def handle_exception(self, exc: Exception, action: str, request_id):
if isinstance(exc, APIException):
await self.reply(
action=action,
errors=self._format_errors(exc.detail),
status=exc.statu... | [
"\n Handle any exception that occurs, by sending an appropriate message\n "
] |
Please provide a description of the function:async def handle_action(self, action: str, request_id: str, **kwargs):
try:
await self.check_permissions(action, **kwargs)
if action not in self.available_actions:
raise MethodNotAllowed(method=action)
me... | [
"\n run the action.\n "
] |
Please provide a description of the function:async def receive_json(self, content: typing.Dict, **kwargs):
# TODO assert format, if does not match return message.
request_id = content.pop('request_id')
action = content.pop('action')
await self.handle_action(action, request_id=re... | [
"\n Called with decoded JSON content.\n "
] |
Please provide a description of the function:async def handle_action(self, action: str, request_id: str, **kwargs):
try:
await self.check_permissions(action, **kwargs)
if action not in self.actions:
raise MethodNotAllowed(method=action)
content, sta... | [
"\n run the action.\n "
] |
Please provide a description of the function:def action(atomic=None, **kwargs):
def decorator(func):
if atomic is None:
_atomic = getattr(settings, 'ATOMIC_REQUESTS', False)
else:
_atomic = atomic
func.action = True
func.kwargs = kwargs
if asynci... | [
"\n Mark a method as an action.\n "
] |
Please provide a description of the function:def datetime_parser(s):
try:
ts = arrow.get(s)
# Convert UTC to local, result of get is UTC unless it specifies timezone, bonfire assumes
# all time to be machine local
if ts.tzinfo == arrow.get().tzinfo:
ts = ts.replace(t... | [
"\n Parse timestamp s in local time. First the arrow parser is used, if it fails, the parsedatetime parser is used.\n\n :param s:\n :return:\n "
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.