id int32 0 252k | repo stringlengths 7 55 | path stringlengths 4 127 | func_name stringlengths 1 88 | original_string stringlengths 75 19.8k | language stringclasses 1
value | code stringlengths 51 19.8k | code_tokens list | docstring stringlengths 3 17.3k | docstring_tokens list | sha stringlengths 40 40 | url stringlengths 87 242 |
|---|---|---|---|---|---|---|---|---|---|---|---|
17,500 | cuihantao/andes | andes/models/base.py | ModelBase.param_alter | def param_alter(self,
param,
default=None,
unit=None,
descr=None,
tomatrix=None,
nonzero=None,
mandatory=None,
power=None,
voltage=None,
current=None,
z=None,
y=None,
r=None,
g=None,
dccurrent=None,
dcvoltage=None,
time=None,
**kwargs):
"""
Set attribute of an existing parameter.
To be used to alter an attribute inherited from parent models.
See .. self.param_define for argument descriptions.
"""
assert param in self._data, \
'parameter <{}> does not exist in {}'.format(param, self._name)
def alter_attr(p, attr, value):
"""Set self.__dict__[attr] for param based on value
"""
if value is None:
return
elif (value is True) and (p not in self.__dict__[attr]):
self.__dict__[attr].append(p)
elif (value is False) and (p in self.__dict__[attr]):
self.__dict__[attr].remove(p)
else:
self.log('No need to alter {} for {}'.format(attr, p))
if default is not None:
self._data.update({param: default})
if unit is not None:
self._units.update({param: unit})
if descr is not None:
self._descr.update({param: descr})
alter_attr(param, '_params', tomatrix)
alter_attr(param, '_zeros', nonzero)
alter_attr(param, '_mandatory', mandatory)
alter_attr(param, '_powers', power)
alter_attr(param, '_voltages', voltage)
alter_attr(param, '_currents', current)
alter_attr(param, '_z', z)
alter_attr(param, '_y', y)
alter_attr(param, '_r', r)
alter_attr(param, '_g', g)
alter_attr(param, '_dcvoltages', dcvoltage)
alter_attr(param, '_dccurrents', dccurrent)
alter_attr(param, '_times', time) | python | def param_alter(self,
param,
default=None,
unit=None,
descr=None,
tomatrix=None,
nonzero=None,
mandatory=None,
power=None,
voltage=None,
current=None,
z=None,
y=None,
r=None,
g=None,
dccurrent=None,
dcvoltage=None,
time=None,
**kwargs):
assert param in self._data, \
'parameter <{}> does not exist in {}'.format(param, self._name)
def alter_attr(p, attr, value):
"""Set self.__dict__[attr] for param based on value
"""
if value is None:
return
elif (value is True) and (p not in self.__dict__[attr]):
self.__dict__[attr].append(p)
elif (value is False) and (p in self.__dict__[attr]):
self.__dict__[attr].remove(p)
else:
self.log('No need to alter {} for {}'.format(attr, p))
if default is not None:
self._data.update({param: default})
if unit is not None:
self._units.update({param: unit})
if descr is not None:
self._descr.update({param: descr})
alter_attr(param, '_params', tomatrix)
alter_attr(param, '_zeros', nonzero)
alter_attr(param, '_mandatory', mandatory)
alter_attr(param, '_powers', power)
alter_attr(param, '_voltages', voltage)
alter_attr(param, '_currents', current)
alter_attr(param, '_z', z)
alter_attr(param, '_y', y)
alter_attr(param, '_r', r)
alter_attr(param, '_g', g)
alter_attr(param, '_dcvoltages', dcvoltage)
alter_attr(param, '_dccurrents', dccurrent)
alter_attr(param, '_times', time) | [
"def",
"param_alter",
"(",
"self",
",",
"param",
",",
"default",
"=",
"None",
",",
"unit",
"=",
"None",
",",
"descr",
"=",
"None",
",",
"tomatrix",
"=",
"None",
",",
"nonzero",
"=",
"None",
",",
"mandatory",
"=",
"None",
",",
"power",
"=",
"None",
... | Set attribute of an existing parameter.
To be used to alter an attribute inherited from parent models.
See .. self.param_define for argument descriptions. | [
"Set",
"attribute",
"of",
"an",
"existing",
"parameter",
".",
"To",
"be",
"used",
"to",
"alter",
"an",
"attribute",
"inherited",
"from",
"parent",
"models",
"."
] | 7067898d4f26ce7534e968b8486c4aa8fe3a511a | https://github.com/cuihantao/andes/blob/7067898d4f26ce7534e968b8486c4aa8fe3a511a/andes/models/base.py#L654-L713 |
17,501 | cuihantao/andes | andes/models/base.py | ModelBase.eq_add | def eq_add(self, expr, var, intf=False):
"""
Add an equation to this model.
An equation is associated with the addresses of a variable. The
number of equations must equal that of variables.
Stored to ``self._equations`` is a tuple of ``(expr, var, intf,
ty)`` where ``ty`` is in ('f', 'g')
:param str expr: equation expression
:param str var: variable name to be associated with
:param bool intf: if this equation is added to an interface equation,
namely, an equation outside this model
:return: None
"""
# determine the type of the equation, ('f', 'g') based on var
# We assume that all differential equations are only modifiable by
# the model itself
# Only interface to algebraic varbailes of external models
ty = ''
if var in self._algebs:
ty = 'g'
elif var in self._states:
ty = 'f'
else:
for _, item in self._ac:
if var in item:
ty = 'g'
if intf is False:
intf = True
for _, item in self._dc:
if var == item:
ty = 'g'
if intf is False:
intf = True
if ty == '':
self.log(
'Equation associated with interface variable {var} '
'assumed as algeb'.
format(var=var),
DEBUG)
ty = 'g'
self._equations.append((expr, var, intf, ty)) | python | def eq_add(self, expr, var, intf=False):
# determine the type of the equation, ('f', 'g') based on var
# We assume that all differential equations are only modifiable by
# the model itself
# Only interface to algebraic varbailes of external models
ty = ''
if var in self._algebs:
ty = 'g'
elif var in self._states:
ty = 'f'
else:
for _, item in self._ac:
if var in item:
ty = 'g'
if intf is False:
intf = True
for _, item in self._dc:
if var == item:
ty = 'g'
if intf is False:
intf = True
if ty == '':
self.log(
'Equation associated with interface variable {var} '
'assumed as algeb'.
format(var=var),
DEBUG)
ty = 'g'
self._equations.append((expr, var, intf, ty)) | [
"def",
"eq_add",
"(",
"self",
",",
"expr",
",",
"var",
",",
"intf",
"=",
"False",
")",
":",
"# determine the type of the equation, ('f', 'g') based on var",
"# We assume that all differential equations are only modifiable by",
"# the model itself",
"# Only interface to algebraic ... | Add an equation to this model.
An equation is associated with the addresses of a variable. The
number of equations must equal that of variables.
Stored to ``self._equations`` is a tuple of ``(expr, var, intf,
ty)`` where ``ty`` is in ('f', 'g')
:param str expr: equation expression
:param str var: variable name to be associated with
:param bool intf: if this equation is added to an interface equation,
namely, an equation outside this model
:return: None | [
"Add",
"an",
"equation",
"to",
"this",
"model",
"."
] | 7067898d4f26ce7534e968b8486c4aa8fe3a511a | https://github.com/cuihantao/andes/blob/7067898d4f26ce7534e968b8486c4aa8fe3a511a/andes/models/base.py#L715-L764 |
17,502 | cuihantao/andes | andes/models/base.py | ModelBase.read_data_ext | def read_data_ext(self, model: str, field: str, idx=None, astype=None):
"""
Return a field of a model or group at the given indices
:param str model: name of the group or model to retrieve
:param str field: name of the field
:param list, int, float str idx: idx of elements to access
:param type astype: type cast
:return:
"""
ret = list()
if model in self.system.devman.devices:
ret = self.system.__dict__[model].get_field(field, idx)
elif model in self.system.devman.group.keys():
# ===============================================================
# Since ``self.system.devman.group`` is an unordered dictionary,
# ``idx`` must be given to retrieve ``field`` across models.
#
# Returns a matrix by default
# ===============================================================
assert idx is not None, \
'idx must be specified when accessing group fields'
astype = matrix
for item in idx:
dev_name = self.system.devman.group[model].get(item, None)
ret.append(self.read_data_ext(dev_name, field, idx=item))
else:
raise NameError(
'Model or Group <{0}> does not exist.'.format(model))
if (ret is None) or isinstance(ret, (int, float, str)):
return ret
elif astype is None:
return ret
else:
return astype(ret) | python | def read_data_ext(self, model: str, field: str, idx=None, astype=None):
ret = list()
if model in self.system.devman.devices:
ret = self.system.__dict__[model].get_field(field, idx)
elif model in self.system.devman.group.keys():
# ===============================================================
# Since ``self.system.devman.group`` is an unordered dictionary,
# ``idx`` must be given to retrieve ``field`` across models.
#
# Returns a matrix by default
# ===============================================================
assert idx is not None, \
'idx must be specified when accessing group fields'
astype = matrix
for item in idx:
dev_name = self.system.devman.group[model].get(item, None)
ret.append(self.read_data_ext(dev_name, field, idx=item))
else:
raise NameError(
'Model or Group <{0}> does not exist.'.format(model))
if (ret is None) or isinstance(ret, (int, float, str)):
return ret
elif astype is None:
return ret
else:
return astype(ret) | [
"def",
"read_data_ext",
"(",
"self",
",",
"model",
":",
"str",
",",
"field",
":",
"str",
",",
"idx",
"=",
"None",
",",
"astype",
"=",
"None",
")",
":",
"ret",
"=",
"list",
"(",
")",
"if",
"model",
"in",
"self",
".",
"system",
".",
"devman",
".",
... | Return a field of a model or group at the given indices
:param str model: name of the group or model to retrieve
:param str field: name of the field
:param list, int, float str idx: idx of elements to access
:param type astype: type cast
:return: | [
"Return",
"a",
"field",
"of",
"a",
"model",
"or",
"group",
"at",
"the",
"given",
"indices"
] | 7067898d4f26ce7534e968b8486c4aa8fe3a511a | https://github.com/cuihantao/andes/blob/7067898d4f26ce7534e968b8486c4aa8fe3a511a/andes/models/base.py#L766-L805 |
17,503 | cuihantao/andes | andes/models/base.py | ModelBase.copy_data_ext | def copy_data_ext(self, model, field, dest=None, idx=None, astype=None):
"""
Retrieve the field of another model and store it as a field.
:param model: name of the source model being a model name or a group name
:param field: name of the field to retrieve
:param dest: name of the destination field in ``self``
:param idx: idx of elements to access
:param astype: type cast
:type model: str
:type field: str
:type dest: str
:type idx: list, matrix
:type astype: None, list, matrix
:return: None
"""
# use default destination
if not dest:
dest = field
assert dest not in self._states + self._algebs
self.__dict__[dest] = self.read_data_ext(
model, field, idx, astype=astype)
if idx is not None:
if len(idx) == self.n:
self.link_to(model, idx, self.idx) | python | def copy_data_ext(self, model, field, dest=None, idx=None, astype=None):
# use default destination
if not dest:
dest = field
assert dest not in self._states + self._algebs
self.__dict__[dest] = self.read_data_ext(
model, field, idx, astype=astype)
if idx is not None:
if len(idx) == self.n:
self.link_to(model, idx, self.idx) | [
"def",
"copy_data_ext",
"(",
"self",
",",
"model",
",",
"field",
",",
"dest",
"=",
"None",
",",
"idx",
"=",
"None",
",",
"astype",
"=",
"None",
")",
":",
"# use default destination",
"if",
"not",
"dest",
":",
"dest",
"=",
"field",
"assert",
"dest",
"no... | Retrieve the field of another model and store it as a field.
:param model: name of the source model being a model name or a group name
:param field: name of the field to retrieve
:param dest: name of the destination field in ``self``
:param idx: idx of elements to access
:param astype: type cast
:type model: str
:type field: str
:type dest: str
:type idx: list, matrix
:type astype: None, list, matrix
:return: None | [
"Retrieve",
"the",
"field",
"of",
"another",
"model",
"and",
"store",
"it",
"as",
"a",
"field",
"."
] | 7067898d4f26ce7534e968b8486c4aa8fe3a511a | https://github.com/cuihantao/andes/blob/7067898d4f26ce7534e968b8486c4aa8fe3a511a/andes/models/base.py#L807-L837 |
17,504 | cuihantao/andes | andes/models/base.py | ModelBase.elem_add | def elem_add(self, idx=None, name=None, **kwargs):
"""
Add an element of this model
:param idx: element idx
:param name: element name
:param kwargs: keyword arguments of the parameters
:return: allocated idx
"""
idx = self.system.devman.register_element(dev_name=self._name, idx=idx)
self.system.__dict__[self._group].register_element(self._name, idx)
self.uid[idx] = self.n
self.idx.append(idx)
self.mdl_to.append(list())
self.mdl_from.append(list())
# self.n += 1
if name is None:
self.name.append(self._name + ' ' + str(self.n))
else:
self.name.append(name)
# check mandatory parameters
for key in self._mandatory:
if key not in kwargs.keys():
self.log(
'Mandatory parameter <{:s}.{:s}> missing'.format(
self.name[-1], key), ERROR)
sys.exit(1)
# set default values
for key, value in self._data.items():
self.__dict__[key].append(value)
# overwrite custom values
for key, value in kwargs.items():
if key not in self._data:
self.log(
'Parameter <{:s}.{:s}> is not used.'.format(
self.name[-1], key), WARNING)
continue
self.__dict__[key][-1] = value
# check data consistency
if not value and key in self._zeros:
if key == 'Sn':
default = self.system.mva
elif key == 'fn':
default = self.system.config.freq
else:
default = self._data[key]
self.__dict__[key][-1] = default
self.log(
'Using default value for <{:s}.{:s}>'.format(
self.name[-1], key), WARNING)
return idx | python | def elem_add(self, idx=None, name=None, **kwargs):
idx = self.system.devman.register_element(dev_name=self._name, idx=idx)
self.system.__dict__[self._group].register_element(self._name, idx)
self.uid[idx] = self.n
self.idx.append(idx)
self.mdl_to.append(list())
self.mdl_from.append(list())
# self.n += 1
if name is None:
self.name.append(self._name + ' ' + str(self.n))
else:
self.name.append(name)
# check mandatory parameters
for key in self._mandatory:
if key not in kwargs.keys():
self.log(
'Mandatory parameter <{:s}.{:s}> missing'.format(
self.name[-1], key), ERROR)
sys.exit(1)
# set default values
for key, value in self._data.items():
self.__dict__[key].append(value)
# overwrite custom values
for key, value in kwargs.items():
if key not in self._data:
self.log(
'Parameter <{:s}.{:s}> is not used.'.format(
self.name[-1], key), WARNING)
continue
self.__dict__[key][-1] = value
# check data consistency
if not value and key in self._zeros:
if key == 'Sn':
default = self.system.mva
elif key == 'fn':
default = self.system.config.freq
else:
default = self._data[key]
self.__dict__[key][-1] = default
self.log(
'Using default value for <{:s}.{:s}>'.format(
self.name[-1], key), WARNING)
return idx | [
"def",
"elem_add",
"(",
"self",
",",
"idx",
"=",
"None",
",",
"name",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"idx",
"=",
"self",
".",
"system",
".",
"devman",
".",
"register_element",
"(",
"dev_name",
"=",
"self",
".",
"_name",
",",
"idx",... | Add an element of this model
:param idx: element idx
:param name: element name
:param kwargs: keyword arguments of the parameters
:return: allocated idx | [
"Add",
"an",
"element",
"of",
"this",
"model"
] | 7067898d4f26ce7534e968b8486c4aa8fe3a511a | https://github.com/cuihantao/andes/blob/7067898d4f26ce7534e968b8486c4aa8fe3a511a/andes/models/base.py#L839-L899 |
17,505 | cuihantao/andes | andes/models/base.py | ModelBase.elem_remove | def elem_remove(self, idx=None):
"""
Remove elements labeled by idx from this model instance.
:param list,matrix idx: indices of elements to be removed
:return: None
"""
if idx is not None:
if idx in self.uid:
key = idx
item = self.uid[idx]
else:
self.log('The item <{:s}> does not exist.'.format(idx), ERROR)
return None
else:
return None
convert = False
if isinstance(self.__dict__[self._params[0]], matrix):
self._param_to_list()
convert = True
# self.n -= 1
self.uid.pop(key, '')
self.idx.pop(item)
self.mdl_from.pop(item)
self.mdl_to.pop(item)
for x, y in self.uid.items():
if y > item:
self.uid[x] = y - 1
for param in self._data:
self.__dict__[param].pop(item)
for param in self._service:
if len(self.__dict__[param]) == (self.n + 1):
if isinstance(self.__dict__[param], list):
self.__dict__[param].pop(item)
elif isinstance(self.__dict__[param], matrix):
service = list(self.__dict__[param])
service.pop(item)
self.__dict__[param] = matrix(service)
for x in self._states:
if len(self.__dict__[x]):
self.__dict__[x].pop(item)
for y in self._algebs:
if self.__dict__[y]:
self.__dict__[y].pop(item)
for key, param in self._ac.items():
if isinstance(param, list):
for subparam in param:
if len(self.__dict__[subparam]):
self.__dict__[subparam].pop(item)
else:
self.__dict__[param].pop(item)
for key, param in self._dc.items():
self.__dict__[param].pop(item)
self.name.pop(item)
if convert and self.n:
self._param_to_matrix() | python | def elem_remove(self, idx=None):
if idx is not None:
if idx in self.uid:
key = idx
item = self.uid[idx]
else:
self.log('The item <{:s}> does not exist.'.format(idx), ERROR)
return None
else:
return None
convert = False
if isinstance(self.__dict__[self._params[0]], matrix):
self._param_to_list()
convert = True
# self.n -= 1
self.uid.pop(key, '')
self.idx.pop(item)
self.mdl_from.pop(item)
self.mdl_to.pop(item)
for x, y in self.uid.items():
if y > item:
self.uid[x] = y - 1
for param in self._data:
self.__dict__[param].pop(item)
for param in self._service:
if len(self.__dict__[param]) == (self.n + 1):
if isinstance(self.__dict__[param], list):
self.__dict__[param].pop(item)
elif isinstance(self.__dict__[param], matrix):
service = list(self.__dict__[param])
service.pop(item)
self.__dict__[param] = matrix(service)
for x in self._states:
if len(self.__dict__[x]):
self.__dict__[x].pop(item)
for y in self._algebs:
if self.__dict__[y]:
self.__dict__[y].pop(item)
for key, param in self._ac.items():
if isinstance(param, list):
for subparam in param:
if len(self.__dict__[subparam]):
self.__dict__[subparam].pop(item)
else:
self.__dict__[param].pop(item)
for key, param in self._dc.items():
self.__dict__[param].pop(item)
self.name.pop(item)
if convert and self.n:
self._param_to_matrix() | [
"def",
"elem_remove",
"(",
"self",
",",
"idx",
"=",
"None",
")",
":",
"if",
"idx",
"is",
"not",
"None",
":",
"if",
"idx",
"in",
"self",
".",
"uid",
":",
"key",
"=",
"idx",
"item",
"=",
"self",
".",
"uid",
"[",
"idx",
"]",
"else",
":",
"self",
... | Remove elements labeled by idx from this model instance.
:param list,matrix idx: indices of elements to be removed
:return: None | [
"Remove",
"elements",
"labeled",
"by",
"idx",
"from",
"this",
"model",
"instance",
"."
] | 7067898d4f26ce7534e968b8486c4aa8fe3a511a | https://github.com/cuihantao/andes/blob/7067898d4f26ce7534e968b8486c4aa8fe3a511a/andes/models/base.py#L901-L966 |
17,506 | cuihantao/andes | andes/models/base.py | ModelBase.data_to_elem_base | def data_to_elem_base(self):
"""
Convert parameter data to element base
Returns
-------
None
"""
if self._flags['sysbase'] is False:
return
for key, val in self._store.items():
self.__dict__[key] = val
self._flags['sysbase'] = False | python | def data_to_elem_base(self):
if self._flags['sysbase'] is False:
return
for key, val in self._store.items():
self.__dict__[key] = val
self._flags['sysbase'] = False | [
"def",
"data_to_elem_base",
"(",
"self",
")",
":",
"if",
"self",
".",
"_flags",
"[",
"'sysbase'",
"]",
"is",
"False",
":",
"return",
"for",
"key",
",",
"val",
"in",
"self",
".",
"_store",
".",
"items",
"(",
")",
":",
"self",
".",
"__dict__",
"[",
"... | Convert parameter data to element base
Returns
-------
None | [
"Convert",
"parameter",
"data",
"to",
"element",
"base"
] | 7067898d4f26ce7534e968b8486c4aa8fe3a511a | https://github.com/cuihantao/andes/blob/7067898d4f26ce7534e968b8486c4aa8fe3a511a/andes/models/base.py#L1041-L1055 |
17,507 | cuihantao/andes | andes/models/base.py | ModelBase._intf_network | def _intf_network(self):
"""
Retrieve the ac and dc network interface variable indices.
:Example:
``self._ac = {'bus1': (a1, v1)}`` gives
- indices: self.bus1
- system.Bus.a -> self.a1
- system.Bus.v -> self.v1
``self._dc = {'node1': v1}`` gives
- indices: self.node1
- system.Node.v-> self.v1
:return: None
"""
for key, val in self._ac.items():
self.copy_data_ext(
model='Bus', field='a', dest=val[0], idx=self.__dict__[key])
self.copy_data_ext(
model='Bus', field='v', dest=val[1], idx=self.__dict__[key])
for key, val in self._dc.items():
self.copy_data_ext(
model='Node', field='v', dest=val, idx=self.__dict__[key])
# check for interface voltage differences
self._check_Vn() | python | def _intf_network(self):
for key, val in self._ac.items():
self.copy_data_ext(
model='Bus', field='a', dest=val[0], idx=self.__dict__[key])
self.copy_data_ext(
model='Bus', field='v', dest=val[1], idx=self.__dict__[key])
for key, val in self._dc.items():
self.copy_data_ext(
model='Node', field='v', dest=val, idx=self.__dict__[key])
# check for interface voltage differences
self._check_Vn() | [
"def",
"_intf_network",
"(",
"self",
")",
":",
"for",
"key",
",",
"val",
"in",
"self",
".",
"_ac",
".",
"items",
"(",
")",
":",
"self",
".",
"copy_data_ext",
"(",
"model",
"=",
"'Bus'",
",",
"field",
"=",
"'a'",
",",
"dest",
"=",
"val",
"[",
"0",... | Retrieve the ac and dc network interface variable indices.
:Example:
``self._ac = {'bus1': (a1, v1)}`` gives
- indices: self.bus1
- system.Bus.a -> self.a1
- system.Bus.v -> self.v1
``self._dc = {'node1': v1}`` gives
- indices: self.node1
- system.Node.v-> self.v1
:return: None | [
"Retrieve",
"the",
"ac",
"and",
"dc",
"network",
"interface",
"variable",
"indices",
"."
] | 7067898d4f26ce7534e968b8486c4aa8fe3a511a | https://github.com/cuihantao/andes/blob/7067898d4f26ce7534e968b8486c4aa8fe3a511a/andes/models/base.py#L1070-L1099 |
17,508 | cuihantao/andes | andes/models/base.py | ModelBase._intf_ctrl | def _intf_ctrl(self):
"""
Retrieve variable indices of controlled models.
Control interfaces are specified in ``self._ctrl``.
Each ``key:value`` pair has ``key`` being the variable names
for the reference idx and ``value`` being a tuple of
``(model name, field to read, destination field, return type)``.
:Example:
``self._ctrl = {'syn', ('Synchronous', 'omega', 'w', list)}``
- indices: self.syn
- self.w = list(system.Synchronous.omega)
:return: None
"""
for key, val in self._ctrl.items():
model, field, dest, astype = val
self.copy_data_ext(
model, field, dest=dest, idx=self.__dict__[key], astype=astype) | python | def _intf_ctrl(self):
for key, val in self._ctrl.items():
model, field, dest, astype = val
self.copy_data_ext(
model, field, dest=dest, idx=self.__dict__[key], astype=astype) | [
"def",
"_intf_ctrl",
"(",
"self",
")",
":",
"for",
"key",
",",
"val",
"in",
"self",
".",
"_ctrl",
".",
"items",
"(",
")",
":",
"model",
",",
"field",
",",
"dest",
",",
"astype",
"=",
"val",
"self",
".",
"copy_data_ext",
"(",
"model",
",",
"field",
... | Retrieve variable indices of controlled models.
Control interfaces are specified in ``self._ctrl``.
Each ``key:value`` pair has ``key`` being the variable names
for the reference idx and ``value`` being a tuple of
``(model name, field to read, destination field, return type)``.
:Example:
``self._ctrl = {'syn', ('Synchronous', 'omega', 'w', list)}``
- indices: self.syn
- self.w = list(system.Synchronous.omega)
:return: None | [
"Retrieve",
"variable",
"indices",
"of",
"controlled",
"models",
"."
] | 7067898d4f26ce7534e968b8486c4aa8fe3a511a | https://github.com/cuihantao/andes/blob/7067898d4f26ce7534e968b8486c4aa8fe3a511a/andes/models/base.py#L1101-L1122 |
17,509 | cuihantao/andes | andes/models/base.py | ModelBase._addr | def _addr(self):
"""
Assign dae addresses for algebraic and state variables.
Addresses are stored in ``self.__dict__[var]``.
``dae.m`` and ``dae.n`` are updated accordingly.
Returns
-------
None
"""
group_by = self._config['address_group_by']
assert not self._flags['address'], "{} address already assigned".format(self._name)
assert group_by in ('element', 'variable')
m0 = self.system.dae.m
n0 = self.system.dae.n
mend = m0 + len(self._algebs) * self.n
nend = n0 + len(self._states) * self.n
if group_by == 'variable':
for idx, item in enumerate(self._algebs):
self.__dict__[item] = list(
range(m0 + idx * self.n, m0 + (idx + 1) * self.n))
for idx, item in enumerate(self._states):
self.__dict__[item] = list(
range(n0 + idx * self.n, n0 + (idx + 1) * self.n))
elif group_by == 'element':
for idx, item in enumerate(self._algebs):
self.__dict__[item] = list(
range(m0 + idx, mend, len(self._algebs)))
for idx, item in enumerate(self._states):
self.__dict__[item] = list(
range(n0 + idx, nend, len(self._states)))
self.system.dae.m = mend
self.system.dae.n = nend
self._flags['address'] = True | python | def _addr(self):
group_by = self._config['address_group_by']
assert not self._flags['address'], "{} address already assigned".format(self._name)
assert group_by in ('element', 'variable')
m0 = self.system.dae.m
n0 = self.system.dae.n
mend = m0 + len(self._algebs) * self.n
nend = n0 + len(self._states) * self.n
if group_by == 'variable':
for idx, item in enumerate(self._algebs):
self.__dict__[item] = list(
range(m0 + idx * self.n, m0 + (idx + 1) * self.n))
for idx, item in enumerate(self._states):
self.__dict__[item] = list(
range(n0 + idx * self.n, n0 + (idx + 1) * self.n))
elif group_by == 'element':
for idx, item in enumerate(self._algebs):
self.__dict__[item] = list(
range(m0 + idx, mend, len(self._algebs)))
for idx, item in enumerate(self._states):
self.__dict__[item] = list(
range(n0 + idx, nend, len(self._states)))
self.system.dae.m = mend
self.system.dae.n = nend
self._flags['address'] = True | [
"def",
"_addr",
"(",
"self",
")",
":",
"group_by",
"=",
"self",
".",
"_config",
"[",
"'address_group_by'",
"]",
"assert",
"not",
"self",
".",
"_flags",
"[",
"'address'",
"]",
",",
"\"{} address already assigned\"",
".",
"format",
"(",
"self",
".",
"_name",
... | Assign dae addresses for algebraic and state variables.
Addresses are stored in ``self.__dict__[var]``.
``dae.m`` and ``dae.n`` are updated accordingly.
Returns
-------
None | [
"Assign",
"dae",
"addresses",
"for",
"algebraic",
"and",
"state",
"variables",
"."
] | 7067898d4f26ce7534e968b8486c4aa8fe3a511a | https://github.com/cuihantao/andes/blob/7067898d4f26ce7534e968b8486c4aa8fe3a511a/andes/models/base.py#L1124-L1164 |
17,510 | cuihantao/andes | andes/models/base.py | ModelBase._varname | def _varname(self):
"""
Set up variable names in ``self.system.varname``.
Variable names follows the convention ``VariableName,Model Name``.
A maximum of 24 characters are allowed for each variable.
:return: None
"""
if not self._flags['address']:
self.log('Unable to assign Varname before allocating address',
ERROR)
return
varname = self.system.varname
for i in range(self.n):
iname = str(self.name[i])
for e, var in enumerate(self._states):
unamex = self._unamex[e]
fnamex = self._fnamex[e]
idx = self.__dict__[var][i]
varname.unamex[idx] = '{} {}'.format(unamex, iname)[:33]
varname.fnamex[idx] = '$' + '{}\\ {}'.format(
fnamex, iname.replace(' ', '\\ '))[:33] + '$'
for e, var in enumerate(self._algebs):
unamey = self._unamey[e]
fnamey = self._fnamey[e]
idx = self.__dict__[var][i]
varname.unamey[idx] = '{} {}'.format(unamey, iname)[:33]
varname.fnamey[idx] = '$' + '{}\\ {}'.format(
fnamey, iname.replace(' ', '\\ '))[:33] + '$' | python | def _varname(self):
if not self._flags['address']:
self.log('Unable to assign Varname before allocating address',
ERROR)
return
varname = self.system.varname
for i in range(self.n):
iname = str(self.name[i])
for e, var in enumerate(self._states):
unamex = self._unamex[e]
fnamex = self._fnamex[e]
idx = self.__dict__[var][i]
varname.unamex[idx] = '{} {}'.format(unamex, iname)[:33]
varname.fnamex[idx] = '$' + '{}\\ {}'.format(
fnamex, iname.replace(' ', '\\ '))[:33] + '$'
for e, var in enumerate(self._algebs):
unamey = self._unamey[e]
fnamey = self._fnamey[e]
idx = self.__dict__[var][i]
varname.unamey[idx] = '{} {}'.format(unamey, iname)[:33]
varname.fnamey[idx] = '$' + '{}\\ {}'.format(
fnamey, iname.replace(' ', '\\ '))[:33] + '$' | [
"def",
"_varname",
"(",
"self",
")",
":",
"if",
"not",
"self",
".",
"_flags",
"[",
"'address'",
"]",
":",
"self",
".",
"log",
"(",
"'Unable to assign Varname before allocating address'",
",",
"ERROR",
")",
"return",
"varname",
"=",
"self",
".",
"system",
"."... | Set up variable names in ``self.system.varname``.
Variable names follows the convention ``VariableName,Model Name``.
A maximum of 24 characters are allowed for each variable.
:return: None | [
"Set",
"up",
"variable",
"names",
"in",
"self",
".",
"system",
".",
"varname",
"."
] | 7067898d4f26ce7534e968b8486c4aa8fe3a511a | https://github.com/cuihantao/andes/blob/7067898d4f26ce7534e968b8486c4aa8fe3a511a/andes/models/base.py#L1166-L1200 |
17,511 | cuihantao/andes | andes/models/base.py | ModelBase._param_to_matrix | def _param_to_matrix(self):
"""
Convert parameters defined in `self._params` to `cvxopt.matrix`
:return None
"""
for item in self._params:
self.__dict__[item] = matrix(self.__dict__[item], tc='d') | python | def _param_to_matrix(self):
for item in self._params:
self.__dict__[item] = matrix(self.__dict__[item], tc='d') | [
"def",
"_param_to_matrix",
"(",
"self",
")",
":",
"for",
"item",
"in",
"self",
".",
"_params",
":",
"self",
".",
"__dict__",
"[",
"item",
"]",
"=",
"matrix",
"(",
"self",
".",
"__dict__",
"[",
"item",
"]",
",",
"tc",
"=",
"'d'",
")"
] | Convert parameters defined in `self._params` to `cvxopt.matrix`
:return None | [
"Convert",
"parameters",
"defined",
"in",
"self",
".",
"_params",
"to",
"cvxopt",
".",
"matrix"
] | 7067898d4f26ce7534e968b8486c4aa8fe3a511a | https://github.com/cuihantao/andes/blob/7067898d4f26ce7534e968b8486c4aa8fe3a511a/andes/models/base.py#L1202-L1209 |
17,512 | cuihantao/andes | andes/models/base.py | ModelBase._param_to_list | def _param_to_list(self):
"""
Convert parameters defined in `self._param` to list
:return None
"""
for item in self._params:
self.__dict__[item] = list(self.__dict__[item]) | python | def _param_to_list(self):
for item in self._params:
self.__dict__[item] = list(self.__dict__[item]) | [
"def",
"_param_to_list",
"(",
"self",
")",
":",
"for",
"item",
"in",
"self",
".",
"_params",
":",
"self",
".",
"__dict__",
"[",
"item",
"]",
"=",
"list",
"(",
"self",
".",
"__dict__",
"[",
"item",
"]",
")"
] | Convert parameters defined in `self._param` to list
:return None | [
"Convert",
"parameters",
"defined",
"in",
"self",
".",
"_param",
"to",
"list"
] | 7067898d4f26ce7534e968b8486c4aa8fe3a511a | https://github.com/cuihantao/andes/blob/7067898d4f26ce7534e968b8486c4aa8fe3a511a/andes/models/base.py#L1211-L1218 |
17,513 | cuihantao/andes | andes/models/base.py | ModelBase.log | def log(self, msg, level=INFO):
"""Record a line of log in logger
:param str msg: content of the messag
:param level: logging level
:return: None
"""
logger.log(level, '<{}> - '.format(self._name) + msg) | python | def log(self, msg, level=INFO):
logger.log(level, '<{}> - '.format(self._name) + msg) | [
"def",
"log",
"(",
"self",
",",
"msg",
",",
"level",
"=",
"INFO",
")",
":",
"logger",
".",
"log",
"(",
"level",
",",
"'<{}> - '",
".",
"format",
"(",
"self",
".",
"_name",
")",
"+",
"msg",
")"
] | Record a line of log in logger
:param str msg: content of the messag
:param level: logging level
:return: None | [
"Record",
"a",
"line",
"of",
"log",
"in",
"logger"
] | 7067898d4f26ce7534e968b8486c4aa8fe3a511a | https://github.com/cuihantao/andes/blob/7067898d4f26ce7534e968b8486c4aa8fe3a511a/andes/models/base.py#L1220-L1229 |
17,514 | cuihantao/andes | andes/models/base.py | ModelBase.init_limit | def init_limit(self, key, lower=None, upper=None, limit=False):
""" check if data is within limits. reset if violates"""
above = agtb(self.__dict__[key], upper)
for idx, item in enumerate(above):
if item == 0.:
continue
maxval = upper[idx]
self.log(
'{0} <{1}.{2}> above its maximum of {3}.'.format(
self.name[idx], self._name, key, maxval), ERROR)
if limit:
self.__dict__[key][idx] = maxval
below = altb(self.__dict__[key], lower)
for idx, item in enumerate(below):
if item == 0.:
continue
minval = lower[idx]
self.log(
'{0} <{1}.{2}> below its minimum of {3}.'.format(
self.name[idx], self._name, key, minval), ERROR)
if limit:
self.__dict__[key][idx] = minval | python | def init_limit(self, key, lower=None, upper=None, limit=False):
above = agtb(self.__dict__[key], upper)
for idx, item in enumerate(above):
if item == 0.:
continue
maxval = upper[idx]
self.log(
'{0} <{1}.{2}> above its maximum of {3}.'.format(
self.name[idx], self._name, key, maxval), ERROR)
if limit:
self.__dict__[key][idx] = maxval
below = altb(self.__dict__[key], lower)
for idx, item in enumerate(below):
if item == 0.:
continue
minval = lower[idx]
self.log(
'{0} <{1}.{2}> below its minimum of {3}.'.format(
self.name[idx], self._name, key, minval), ERROR)
if limit:
self.__dict__[key][idx] = minval | [
"def",
"init_limit",
"(",
"self",
",",
"key",
",",
"lower",
"=",
"None",
",",
"upper",
"=",
"None",
",",
"limit",
"=",
"False",
")",
":",
"above",
"=",
"agtb",
"(",
"self",
".",
"__dict__",
"[",
"key",
"]",
",",
"upper",
")",
"for",
"idx",
",",
... | check if data is within limits. reset if violates | [
"check",
"if",
"data",
"is",
"within",
"limits",
".",
"reset",
"if",
"violates"
] | 7067898d4f26ce7534e968b8486c4aa8fe3a511a | https://github.com/cuihantao/andes/blob/7067898d4f26ce7534e968b8486c4aa8fe3a511a/andes/models/base.py#L1231-L1253 |
17,515 | cuihantao/andes | andes/models/base.py | ModelBase.doc | def doc(self, export='plain'):
"""
Build help document into a Texttable table
:param ('plain', 'latex') export: export format
:param save: save to file ``help_model.extension`` or not
:param writemode: file write mode
:return: None
"""
title = '<{}.{}>'.format(self._group, self._name)
table = Tab(export=export, title=title, descr=self.__doc__)
rows = []
keys = sorted(self._data.keys())
for key in keys:
val = self._data[key]
suf = ''
if key in self._mandatory:
suf = ' *'
elif key in self._powers + \
self._voltages + \
self._currents + \
self._z + \
self._y + \
self._dccurrents + \
self._dcvoltages + \
self._r + \
self._g + \
self._times:
suf = ' #'
c1 = key + suf
c2 = self._descr.get(key, '')
c3 = val
c4 = self._units.get(key, '-')
rows.append([c1, c2, c3, c4])
table.add_rows(rows, header=False)
table.header(['Parameter', 'Description', 'Default', 'Unit'])
if export == 'plain':
pass
elif export == 'latex':
raise NotImplementedError('LaTex output not implemented')
return table.draw() | python | def doc(self, export='plain'):
title = '<{}.{}>'.format(self._group, self._name)
table = Tab(export=export, title=title, descr=self.__doc__)
rows = []
keys = sorted(self._data.keys())
for key in keys:
val = self._data[key]
suf = ''
if key in self._mandatory:
suf = ' *'
elif key in self._powers + \
self._voltages + \
self._currents + \
self._z + \
self._y + \
self._dccurrents + \
self._dcvoltages + \
self._r + \
self._g + \
self._times:
suf = ' #'
c1 = key + suf
c2 = self._descr.get(key, '')
c3 = val
c4 = self._units.get(key, '-')
rows.append([c1, c2, c3, c4])
table.add_rows(rows, header=False)
table.header(['Parameter', 'Description', 'Default', 'Unit'])
if export == 'plain':
pass
elif export == 'latex':
raise NotImplementedError('LaTex output not implemented')
return table.draw() | [
"def",
"doc",
"(",
"self",
",",
"export",
"=",
"'plain'",
")",
":",
"title",
"=",
"'<{}.{}>'",
".",
"format",
"(",
"self",
".",
"_group",
",",
"self",
".",
"_name",
")",
"table",
"=",
"Tab",
"(",
"export",
"=",
"export",
",",
"title",
"=",
"title",... | Build help document into a Texttable table
:param ('plain', 'latex') export: export format
:param save: save to file ``help_model.extension`` or not
:param writemode: file write mode
:return: None | [
"Build",
"help",
"document",
"into",
"a",
"Texttable",
"table"
] | 7067898d4f26ce7534e968b8486c4aa8fe3a511a | https://github.com/cuihantao/andes/blob/7067898d4f26ce7534e968b8486c4aa8fe3a511a/andes/models/base.py#L1276-L1322 |
17,516 | cuihantao/andes | andes/models/base.py | ModelBase.check_limit | def check_limit(self, varname, vmin=None, vmax=None):
"""
Check if the variable values are within the limits.
Return False if fails.
"""
retval = True
assert varname in self.__dict__
if varname in self._algebs:
val = self.system.dae.y[self.__dict__[varname]]
elif varname in self._states:
val = self.system.dae.x[self.__dict__[varname]]
else: # service or temporary variable
val = matrix(self.__dict__[varname])
vmin = matrix(self.__dict__[vmin])
comp = altb(val, vmin)
comp = mul(self.u, comp)
for c, n, idx in zip(comp, self.name, range(self.n)):
if c == 1:
v = val[idx]
vm = vmin[idx]
self.log(
'Init of <{}.{}>={:.4g} is lower than min={:6.4g}'.format(
n, varname, v, vm), ERROR)
retval = False
vmax = matrix(self.__dict__[vmax])
comp = agtb(val, vmax)
comp = mul(self.u, comp)
for c, n, idx in zip(comp, self.name, range(self.n)):
if c == 1:
v = val[idx]
vm = vmax[idx]
self.log(
'Init of <{}.{}>={:.4g} is higher than max={:.4g}'.format(
n, varname, v, vm), ERROR)
retval = False
return retval | python | def check_limit(self, varname, vmin=None, vmax=None):
retval = True
assert varname in self.__dict__
if varname in self._algebs:
val = self.system.dae.y[self.__dict__[varname]]
elif varname in self._states:
val = self.system.dae.x[self.__dict__[varname]]
else: # service or temporary variable
val = matrix(self.__dict__[varname])
vmin = matrix(self.__dict__[vmin])
comp = altb(val, vmin)
comp = mul(self.u, comp)
for c, n, idx in zip(comp, self.name, range(self.n)):
if c == 1:
v = val[idx]
vm = vmin[idx]
self.log(
'Init of <{}.{}>={:.4g} is lower than min={:6.4g}'.format(
n, varname, v, vm), ERROR)
retval = False
vmax = matrix(self.__dict__[vmax])
comp = agtb(val, vmax)
comp = mul(self.u, comp)
for c, n, idx in zip(comp, self.name, range(self.n)):
if c == 1:
v = val[idx]
vm = vmax[idx]
self.log(
'Init of <{}.{}>={:.4g} is higher than max={:.4g}'.format(
n, varname, v, vm), ERROR)
retval = False
return retval | [
"def",
"check_limit",
"(",
"self",
",",
"varname",
",",
"vmin",
"=",
"None",
",",
"vmax",
"=",
"None",
")",
":",
"retval",
"=",
"True",
"assert",
"varname",
"in",
"self",
".",
"__dict__",
"if",
"varname",
"in",
"self",
".",
"_algebs",
":",
"val",
"="... | Check if the variable values are within the limits.
Return False if fails. | [
"Check",
"if",
"the",
"variable",
"values",
"are",
"within",
"the",
"limits",
"."
] | 7067898d4f26ce7534e968b8486c4aa8fe3a511a | https://github.com/cuihantao/andes/blob/7067898d4f26ce7534e968b8486c4aa8fe3a511a/andes/models/base.py#L1324-L1364 |
17,517 | cuihantao/andes | andes/models/base.py | ModelBase.on_bus | def on_bus(self, bus_idx):
"""
Return the indices of elements on the given buses for shunt-connected
elements
:param bus_idx: idx of the buses to which the elements are connected
:return: idx of elements connected to bus_idx
"""
assert hasattr(self, 'bus')
ret = []
if isinstance(bus_idx, (int, float, str)):
bus_idx = [bus_idx]
for item in bus_idx:
idx = []
for e, b in enumerate(self.bus):
if b == item:
idx.append(self.idx[e])
if len(idx) == 1:
idx = idx[0]
elif len(idx) == 0:
idx = None
ret.append(idx)
if len(ret) == 1:
ret = ret[0]
return ret | python | def on_bus(self, bus_idx):
assert hasattr(self, 'bus')
ret = []
if isinstance(bus_idx, (int, float, str)):
bus_idx = [bus_idx]
for item in bus_idx:
idx = []
for e, b in enumerate(self.bus):
if b == item:
idx.append(self.idx[e])
if len(idx) == 1:
idx = idx[0]
elif len(idx) == 0:
idx = None
ret.append(idx)
if len(ret) == 1:
ret = ret[0]
return ret | [
"def",
"on_bus",
"(",
"self",
",",
"bus_idx",
")",
":",
"assert",
"hasattr",
"(",
"self",
",",
"'bus'",
")",
"ret",
"=",
"[",
"]",
"if",
"isinstance",
"(",
"bus_idx",
",",
"(",
"int",
",",
"float",
",",
"str",
")",
")",
":",
"bus_idx",
"=",
"[",
... | Return the indices of elements on the given buses for shunt-connected
elements
:param bus_idx: idx of the buses to which the elements are connected
:return: idx of elements connected to bus_idx | [
"Return",
"the",
"indices",
"of",
"elements",
"on",
"the",
"given",
"buses",
"for",
"shunt",
"-",
"connected",
"elements"
] | 7067898d4f26ce7534e968b8486c4aa8fe3a511a | https://github.com/cuihantao/andes/blob/7067898d4f26ce7534e968b8486c4aa8fe3a511a/andes/models/base.py#L1366-L1396 |
17,518 | cuihantao/andes | andes/models/base.py | ModelBase.link_bus | def link_bus(self, bus_idx):
"""
Return the indices of elements linking the given buses
:param bus_idx:
:return:
"""
ret = []
if not self._config['is_series']:
self.log(
'link_bus function is not valid for non-series model <{}>'.
format(self.name))
return []
if isinstance(bus_idx, (int, float, str)):
bus_idx = [bus_idx]
fkey = list(self._ac.keys())
if 'bus' in fkey:
fkey.remove('bus')
nfkey = len(fkey)
fkey_val = [self.__dict__[i] for i in fkey]
for item in bus_idx:
idx = []
key = []
for i in range(self.n):
for j in range(nfkey):
if fkey_val[j][i] == item:
idx.append(self.idx[i])
key.append(fkey[j])
# <= 1 terminal should connect to the same bus
break
if len(idx) == 0:
idx = None
if len(key) == 0:
key = None
ret.append((idx, key))
return ret | python | def link_bus(self, bus_idx):
ret = []
if not self._config['is_series']:
self.log(
'link_bus function is not valid for non-series model <{}>'.
format(self.name))
return []
if isinstance(bus_idx, (int, float, str)):
bus_idx = [bus_idx]
fkey = list(self._ac.keys())
if 'bus' in fkey:
fkey.remove('bus')
nfkey = len(fkey)
fkey_val = [self.__dict__[i] for i in fkey]
for item in bus_idx:
idx = []
key = []
for i in range(self.n):
for j in range(nfkey):
if fkey_val[j][i] == item:
idx.append(self.idx[i])
key.append(fkey[j])
# <= 1 terminal should connect to the same bus
break
if len(idx) == 0:
idx = None
if len(key) == 0:
key = None
ret.append((idx, key))
return ret | [
"def",
"link_bus",
"(",
"self",
",",
"bus_idx",
")",
":",
"ret",
"=",
"[",
"]",
"if",
"not",
"self",
".",
"_config",
"[",
"'is_series'",
"]",
":",
"self",
".",
"log",
"(",
"'link_bus function is not valid for non-series model <{}>'",
".",
"format",
"(",
"sel... | Return the indices of elements linking the given buses
:param bus_idx:
:return: | [
"Return",
"the",
"indices",
"of",
"elements",
"linking",
"the",
"given",
"buses"
] | 7067898d4f26ce7534e968b8486c4aa8fe3a511a | https://github.com/cuihantao/andes/blob/7067898d4f26ce7534e968b8486c4aa8fe3a511a/andes/models/base.py#L1398-L1441 |
17,519 | cuihantao/andes | andes/models/base.py | ModelBase.elem_find | def elem_find(self, field, value):
"""
Return the indices of elements whose field first satisfies the given values
``value`` should be unique in self.field.
This function does not check the uniqueness.
:param field: name of the supplied field
:param value: value of field of the elemtn to find
:return: idx of the elements
:rtype: list, int, float, str
"""
if isinstance(value, (int, float, str)):
value = [value]
f = list(self.__dict__[field])
uid = np.vectorize(f.index)(value)
return self.get_idx(uid) | python | def elem_find(self, field, value):
if isinstance(value, (int, float, str)):
value = [value]
f = list(self.__dict__[field])
uid = np.vectorize(f.index)(value)
return self.get_idx(uid) | [
"def",
"elem_find",
"(",
"self",
",",
"field",
",",
"value",
")",
":",
"if",
"isinstance",
"(",
"value",
",",
"(",
"int",
",",
"float",
",",
"str",
")",
")",
":",
"value",
"=",
"[",
"value",
"]",
"f",
"=",
"list",
"(",
"self",
".",
"__dict__",
... | Return the indices of elements whose field first satisfies the given values
``value`` should be unique in self.field.
This function does not check the uniqueness.
:param field: name of the supplied field
:param value: value of field of the elemtn to find
:return: idx of the elements
:rtype: list, int, float, str | [
"Return",
"the",
"indices",
"of",
"elements",
"whose",
"field",
"first",
"satisfies",
"the",
"given",
"values"
] | 7067898d4f26ce7534e968b8486c4aa8fe3a511a | https://github.com/cuihantao/andes/blob/7067898d4f26ce7534e968b8486c4aa8fe3a511a/andes/models/base.py#L1443-L1460 |
17,520 | cuihantao/andes | andes/models/base.py | ModelBase._check_Vn | def _check_Vn(self):
"""Check data consistency of Vn and Vdcn if connected to Bus or Node
:return None
"""
if hasattr(self, 'bus') and hasattr(self, 'Vn'):
bus_Vn = self.read_data_ext('Bus', field='Vn', idx=self.bus)
for name, bus, Vn, Vn0 in zip(self.name, self.bus, self.Vn,
bus_Vn):
if Vn != Vn0:
self.log(
'<{}> has Vn={} different from bus <{}> Vn={}.'.format(
name, Vn, bus, Vn0), WARNING)
if hasattr(self, 'node') and hasattr(self, 'Vdcn'):
node_Vdcn = self.read_data_ext('Node', field='Vdcn', idx=self.node)
for name, node, Vdcn, Vdcn0 in zip(self.name, self.node, self.Vdcn,
node_Vdcn):
if Vdcn != Vdcn0:
self.log(
'<{}> has Vdcn={} different from node <{}> Vdcn={}.'
.format(name, Vdcn, node, Vdcn0), WARNING) | python | def _check_Vn(self):
if hasattr(self, 'bus') and hasattr(self, 'Vn'):
bus_Vn = self.read_data_ext('Bus', field='Vn', idx=self.bus)
for name, bus, Vn, Vn0 in zip(self.name, self.bus, self.Vn,
bus_Vn):
if Vn != Vn0:
self.log(
'<{}> has Vn={} different from bus <{}> Vn={}.'.format(
name, Vn, bus, Vn0), WARNING)
if hasattr(self, 'node') and hasattr(self, 'Vdcn'):
node_Vdcn = self.read_data_ext('Node', field='Vdcn', idx=self.node)
for name, node, Vdcn, Vdcn0 in zip(self.name, self.node, self.Vdcn,
node_Vdcn):
if Vdcn != Vdcn0:
self.log(
'<{}> has Vdcn={} different from node <{}> Vdcn={}.'
.format(name, Vdcn, node, Vdcn0), WARNING) | [
"def",
"_check_Vn",
"(",
"self",
")",
":",
"if",
"hasattr",
"(",
"self",
",",
"'bus'",
")",
"and",
"hasattr",
"(",
"self",
",",
"'Vn'",
")",
":",
"bus_Vn",
"=",
"self",
".",
"read_data_ext",
"(",
"'Bus'",
",",
"field",
"=",
"'Vn'",
",",
"idx",
"=",... | Check data consistency of Vn and Vdcn if connected to Bus or Node
:return None | [
"Check",
"data",
"consistency",
"of",
"Vn",
"and",
"Vdcn",
"if",
"connected",
"to",
"Bus",
"or",
"Node"
] | 7067898d4f26ce7534e968b8486c4aa8fe3a511a | https://github.com/cuihantao/andes/blob/7067898d4f26ce7534e968b8486c4aa8fe3a511a/andes/models/base.py#L1462-L1483 |
17,521 | cuihantao/andes | andes/routines/pflow.py | PFLOW.reset | def reset(self):
"""
Reset all internal storage to initial status
Returns
-------
None
"""
self.solved = False
self.niter = 0
self.iter_mis = []
self.F = None
self.system.dae.factorize = True | python | def reset(self):
self.solved = False
self.niter = 0
self.iter_mis = []
self.F = None
self.system.dae.factorize = True | [
"def",
"reset",
"(",
"self",
")",
":",
"self",
".",
"solved",
"=",
"False",
"self",
".",
"niter",
"=",
"0",
"self",
".",
"iter_mis",
"=",
"[",
"]",
"self",
".",
"F",
"=",
"None",
"self",
".",
"system",
".",
"dae",
".",
"factorize",
"=",
"True"
] | Reset all internal storage to initial status
Returns
-------
None | [
"Reset",
"all",
"internal",
"storage",
"to",
"initial",
"status"
] | 7067898d4f26ce7534e968b8486c4aa8fe3a511a | https://github.com/cuihantao/andes/blob/7067898d4f26ce7534e968b8486c4aa8fe3a511a/andes/routines/pflow.py#L27-L39 |
17,522 | cuihantao/andes | andes/routines/pflow.py | PFLOW.pre | def pre(self):
"""
Initialize system for power flow study
Returns
-------
None
"""
logger.info('-> Power flow study: {} method, {} start'.format(
self.config.method.upper(), 'flat' if self.config.flatstart else 'non-flat')
)
t, s = elapsed()
system = self.system
dae = self.system.dae
system.dae.init_xy()
for device, pflow, init0 in zip(system.devman.devices,
system.call.pflow, system.call.init0):
if pflow and init0:
system.__dict__[device].init0(dae)
# check for islands
system.check_islands(show_info=True)
t, s = elapsed(t)
logger.debug('Power flow initialized in {:s}.'.format(s)) | python | def pre(self):
logger.info('-> Power flow study: {} method, {} start'.format(
self.config.method.upper(), 'flat' if self.config.flatstart else 'non-flat')
)
t, s = elapsed()
system = self.system
dae = self.system.dae
system.dae.init_xy()
for device, pflow, init0 in zip(system.devman.devices,
system.call.pflow, system.call.init0):
if pflow and init0:
system.__dict__[device].init0(dae)
# check for islands
system.check_islands(show_info=True)
t, s = elapsed(t)
logger.debug('Power flow initialized in {:s}.'.format(s)) | [
"def",
"pre",
"(",
"self",
")",
":",
"logger",
".",
"info",
"(",
"'-> Power flow study: {} method, {} start'",
".",
"format",
"(",
"self",
".",
"config",
".",
"method",
".",
"upper",
"(",
")",
",",
"'flat'",
"if",
"self",
".",
"config",
".",
"flatstart",
... | Initialize system for power flow study
Returns
-------
None | [
"Initialize",
"system",
"for",
"power",
"flow",
"study"
] | 7067898d4f26ce7534e968b8486c4aa8fe3a511a | https://github.com/cuihantao/andes/blob/7067898d4f26ce7534e968b8486c4aa8fe3a511a/andes/routines/pflow.py#L41-L69 |
17,523 | cuihantao/andes | andes/routines/pflow.py | PFLOW.run | def run(self, **kwargs):
"""
call the power flow solution routine
Returns
-------
bool
True for success, False for fail
"""
ret = None
# initialization Y matrix and inital guess
self.pre()
t, _ = elapsed()
# call solution methods
if self.config.method == 'NR':
ret = self.newton()
elif self.config.method == 'DCPF':
ret = self.dcpf()
elif self.config.method in ('FDPF', 'FDBX', 'FDXB'):
ret = self.fdpf()
self.post()
_, s = elapsed(t)
if self.solved:
logger.info(' Solution converged in {} in {} iterations'.format(s, self.niter))
else:
logger.warning(' Solution failed in {} in {} iterations'.format(s,
self.niter))
return ret | python | def run(self, **kwargs):
ret = None
# initialization Y matrix and inital guess
self.pre()
t, _ = elapsed()
# call solution methods
if self.config.method == 'NR':
ret = self.newton()
elif self.config.method == 'DCPF':
ret = self.dcpf()
elif self.config.method in ('FDPF', 'FDBX', 'FDXB'):
ret = self.fdpf()
self.post()
_, s = elapsed(t)
if self.solved:
logger.info(' Solution converged in {} in {} iterations'.format(s, self.niter))
else:
logger.warning(' Solution failed in {} in {} iterations'.format(s,
self.niter))
return ret | [
"def",
"run",
"(",
"self",
",",
"*",
"*",
"kwargs",
")",
":",
"ret",
"=",
"None",
"# initialization Y matrix and inital guess",
"self",
".",
"pre",
"(",
")",
"t",
",",
"_",
"=",
"elapsed",
"(",
")",
"# call solution methods",
"if",
"self",
".",
"config",
... | call the power flow solution routine
Returns
-------
bool
True for success, False for fail | [
"call",
"the",
"power",
"flow",
"solution",
"routine"
] | 7067898d4f26ce7534e968b8486c4aa8fe3a511a | https://github.com/cuihantao/andes/blob/7067898d4f26ce7534e968b8486c4aa8fe3a511a/andes/routines/pflow.py#L71-L102 |
17,524 | cuihantao/andes | andes/routines/pflow.py | PFLOW.newton | def newton(self):
"""
Newton power flow routine
Returns
-------
(bool, int)
success flag, number of iterations
"""
dae = self.system.dae
while True:
inc = self.calc_inc()
dae.x += inc[:dae.n]
dae.y += inc[dae.n:dae.n + dae.m]
self.niter += 1
max_mis = max(abs(inc))
self.iter_mis.append(max_mis)
self._iter_info(self.niter)
if max_mis < self.config.tol:
self.solved = True
break
elif self.niter > 5 and max_mis > 1000 * self.iter_mis[0]:
logger.warning('Blown up in {0} iterations.'.format(self.niter))
break
if self.niter > self.config.maxit:
logger.warning('Reached maximum number of iterations.')
break
return self.solved, self.niter | python | def newton(self):
dae = self.system.dae
while True:
inc = self.calc_inc()
dae.x += inc[:dae.n]
dae.y += inc[dae.n:dae.n + dae.m]
self.niter += 1
max_mis = max(abs(inc))
self.iter_mis.append(max_mis)
self._iter_info(self.niter)
if max_mis < self.config.tol:
self.solved = True
break
elif self.niter > 5 and max_mis > 1000 * self.iter_mis[0]:
logger.warning('Blown up in {0} iterations.'.format(self.niter))
break
if self.niter > self.config.maxit:
logger.warning('Reached maximum number of iterations.')
break
return self.solved, self.niter | [
"def",
"newton",
"(",
"self",
")",
":",
"dae",
"=",
"self",
".",
"system",
".",
"dae",
"while",
"True",
":",
"inc",
"=",
"self",
".",
"calc_inc",
"(",
")",
"dae",
".",
"x",
"+=",
"inc",
"[",
":",
"dae",
".",
"n",
"]",
"dae",
".",
"y",
"+=",
... | Newton power flow routine
Returns
-------
(bool, int)
success flag, number of iterations | [
"Newton",
"power",
"flow",
"routine"
] | 7067898d4f26ce7534e968b8486c4aa8fe3a511a | https://github.com/cuihantao/andes/blob/7067898d4f26ce7534e968b8486c4aa8fe3a511a/andes/routines/pflow.py#L104-L137 |
17,525 | cuihantao/andes | andes/routines/pflow.py | PFLOW.dcpf | def dcpf(self):
"""
Calculate linearized power flow
Returns
-------
(bool, int)
success flag, number of iterations
"""
dae = self.system.dae
self.system.Bus.init0(dae)
self.system.dae.init_g()
Va0 = self.system.Bus.angle
for model, pflow, gcall in zip(self.system.devman.devices, self.system.call.pflow, self.system.call.gcall):
if pflow and gcall:
self.system.__dict__[model].gcall(dae)
sw = self.system.SW.a
sw.sort(reverse=True)
no_sw = self.system.Bus.a[:]
no_swv = self.system.Bus.v[:]
for item in sw:
no_sw.pop(item)
no_swv.pop(item)
Bp = self.system.Line.Bp[no_sw, no_sw]
p = matrix(self.system.dae.g[no_sw], (no_sw.__len__(), 1))
p = p-self.system.Line.Bp[no_sw, sw]*Va0[sw]
Sp = self.solver.symbolic(Bp)
N = self.solver.numeric(Bp, Sp)
self.solver.solve(Bp, Sp, N, p)
self.system.dae.y[no_sw] = p
self.solved = True
self.niter = 1
return self.solved, self.niter | python | def dcpf(self):
dae = self.system.dae
self.system.Bus.init0(dae)
self.system.dae.init_g()
Va0 = self.system.Bus.angle
for model, pflow, gcall in zip(self.system.devman.devices, self.system.call.pflow, self.system.call.gcall):
if pflow and gcall:
self.system.__dict__[model].gcall(dae)
sw = self.system.SW.a
sw.sort(reverse=True)
no_sw = self.system.Bus.a[:]
no_swv = self.system.Bus.v[:]
for item in sw:
no_sw.pop(item)
no_swv.pop(item)
Bp = self.system.Line.Bp[no_sw, no_sw]
p = matrix(self.system.dae.g[no_sw], (no_sw.__len__(), 1))
p = p-self.system.Line.Bp[no_sw, sw]*Va0[sw]
Sp = self.solver.symbolic(Bp)
N = self.solver.numeric(Bp, Sp)
self.solver.solve(Bp, Sp, N, p)
self.system.dae.y[no_sw] = p
self.solved = True
self.niter = 1
return self.solved, self.niter | [
"def",
"dcpf",
"(",
"self",
")",
":",
"dae",
"=",
"self",
".",
"system",
".",
"dae",
"self",
".",
"system",
".",
"Bus",
".",
"init0",
"(",
"dae",
")",
"self",
".",
"system",
".",
"dae",
".",
"init_g",
"(",
")",
"Va0",
"=",
"self",
".",
"system"... | Calculate linearized power flow
Returns
-------
(bool, int)
success flag, number of iterations | [
"Calculate",
"linearized",
"power",
"flow"
] | 7067898d4f26ce7534e968b8486c4aa8fe3a511a | https://github.com/cuihantao/andes/blob/7067898d4f26ce7534e968b8486c4aa8fe3a511a/andes/routines/pflow.py#L139-L179 |
17,526 | cuihantao/andes | andes/routines/pflow.py | PFLOW._iter_info | def _iter_info(self, niter, level=logging.INFO):
"""
Log iteration number and mismatch
Parameters
----------
level
logging level
Returns
-------
None
"""
max_mis = self.iter_mis[niter - 1]
msg = ' Iter {:<d}. max mismatch = {:8.7f}'.format(niter, max_mis)
logger.info(msg) | python | def _iter_info(self, niter, level=logging.INFO):
max_mis = self.iter_mis[niter - 1]
msg = ' Iter {:<d}. max mismatch = {:8.7f}'.format(niter, max_mis)
logger.info(msg) | [
"def",
"_iter_info",
"(",
"self",
",",
"niter",
",",
"level",
"=",
"logging",
".",
"INFO",
")",
":",
"max_mis",
"=",
"self",
".",
"iter_mis",
"[",
"niter",
"-",
"1",
"]",
"msg",
"=",
"' Iter {:<d}. max mismatch = {:8.7f}'",
".",
"format",
"(",
"niter",
... | Log iteration number and mismatch
Parameters
----------
level
logging level
Returns
-------
None | [
"Log",
"iteration",
"number",
"and",
"mismatch"
] | 7067898d4f26ce7534e968b8486c4aa8fe3a511a | https://github.com/cuihantao/andes/blob/7067898d4f26ce7534e968b8486c4aa8fe3a511a/andes/routines/pflow.py#L181-L195 |
17,527 | cuihantao/andes | andes/routines/pflow.py | PFLOW.calc_inc | def calc_inc(self):
"""
Calculate the Newton incrementals for each step
Returns
-------
matrix
The solution to ``x = -A\\b``
"""
system = self.system
self.newton_call()
A = sparse([[system.dae.Fx, system.dae.Gx],
[system.dae.Fy, system.dae.Gy]])
inc = matrix([system.dae.f, system.dae.g])
if system.dae.factorize:
self.F = self.solver.symbolic(A)
system.dae.factorize = False
try:
N = self.solver.numeric(A, self.F)
self.solver.solve(A, self.F, N, inc)
except ValueError:
logger.warning('Unexpected symbolic factorization.')
system.dae.factorize = True
except ArithmeticError:
logger.warning('Jacobian matrix is singular.')
system.dae.check_diag(system.dae.Gy, 'unamey')
return -inc | python | def calc_inc(self):
system = self.system
self.newton_call()
A = sparse([[system.dae.Fx, system.dae.Gx],
[system.dae.Fy, system.dae.Gy]])
inc = matrix([system.dae.f, system.dae.g])
if system.dae.factorize:
self.F = self.solver.symbolic(A)
system.dae.factorize = False
try:
N = self.solver.numeric(A, self.F)
self.solver.solve(A, self.F, N, inc)
except ValueError:
logger.warning('Unexpected symbolic factorization.')
system.dae.factorize = True
except ArithmeticError:
logger.warning('Jacobian matrix is singular.')
system.dae.check_diag(system.dae.Gy, 'unamey')
return -inc | [
"def",
"calc_inc",
"(",
"self",
")",
":",
"system",
"=",
"self",
".",
"system",
"self",
".",
"newton_call",
"(",
")",
"A",
"=",
"sparse",
"(",
"[",
"[",
"system",
".",
"dae",
".",
"Fx",
",",
"system",
".",
"dae",
".",
"Gx",
"]",
",",
"[",
"syst... | Calculate the Newton incrementals for each step
Returns
-------
matrix
The solution to ``x = -A\\b`` | [
"Calculate",
"the",
"Newton",
"incrementals",
"for",
"each",
"step"
] | 7067898d4f26ce7534e968b8486c4aa8fe3a511a | https://github.com/cuihantao/andes/blob/7067898d4f26ce7534e968b8486c4aa8fe3a511a/andes/routines/pflow.py#L197-L228 |
17,528 | cuihantao/andes | andes/routines/pflow.py | PFLOW.newton_call | def newton_call(self):
"""
Function calls for Newton power flow
Returns
-------
None
"""
# system = self.system
# exec(system.call.newton)
system = self.system
dae = self.system.dae
system.dae.init_fg()
system.dae.reset_small_g()
# evaluate algebraic equation mismatches
for model, pflow, gcall in zip(system.devman.devices,
system.call.pflow, system.call.gcall):
if pflow and gcall:
system.__dict__[model].gcall(dae)
# eval differential equations
for model, pflow, fcall in zip(system.devman.devices,
system.call.pflow, system.call.fcall):
if pflow and fcall:
system.__dict__[model].fcall(dae)
# reset islanded buses mismatches
system.Bus.gisland(dae)
if system.dae.factorize:
system.dae.init_jac0()
# evaluate constant Jacobian elements
for model, pflow, jac0 in zip(system.devman.devices,
system.call.pflow, system.call.jac0):
if pflow and jac0:
system.__dict__[model].jac0(dae)
dae.temp_to_spmatrix('jac0')
dae.setup_FxGy()
# evaluate Gy
for model, pflow, gycall in zip(system.devman.devices,
system.call.pflow, system.call.gycall):
if pflow and gycall:
system.__dict__[model].gycall(dae)
# evaluate Fx
for model, pflow, fxcall in zip(system.devman.devices,
system.call.pflow, system.call.fxcall):
if pflow and fxcall:
system.__dict__[model].fxcall(dae)
# reset islanded buses Jacobians
system.Bus.gyisland(dae)
dae.temp_to_spmatrix('jac') | python | def newton_call(self):
# system = self.system
# exec(system.call.newton)
system = self.system
dae = self.system.dae
system.dae.init_fg()
system.dae.reset_small_g()
# evaluate algebraic equation mismatches
for model, pflow, gcall in zip(system.devman.devices,
system.call.pflow, system.call.gcall):
if pflow and gcall:
system.__dict__[model].gcall(dae)
# eval differential equations
for model, pflow, fcall in zip(system.devman.devices,
system.call.pflow, system.call.fcall):
if pflow and fcall:
system.__dict__[model].fcall(dae)
# reset islanded buses mismatches
system.Bus.gisland(dae)
if system.dae.factorize:
system.dae.init_jac0()
# evaluate constant Jacobian elements
for model, pflow, jac0 in zip(system.devman.devices,
system.call.pflow, system.call.jac0):
if pflow and jac0:
system.__dict__[model].jac0(dae)
dae.temp_to_spmatrix('jac0')
dae.setup_FxGy()
# evaluate Gy
for model, pflow, gycall in zip(system.devman.devices,
system.call.pflow, system.call.gycall):
if pflow and gycall:
system.__dict__[model].gycall(dae)
# evaluate Fx
for model, pflow, fxcall in zip(system.devman.devices,
system.call.pflow, system.call.fxcall):
if pflow and fxcall:
system.__dict__[model].fxcall(dae)
# reset islanded buses Jacobians
system.Bus.gyisland(dae)
dae.temp_to_spmatrix('jac') | [
"def",
"newton_call",
"(",
"self",
")",
":",
"# system = self.system",
"# exec(system.call.newton)",
"system",
"=",
"self",
".",
"system",
"dae",
"=",
"self",
".",
"system",
".",
"dae",
"system",
".",
"dae",
".",
"init_fg",
"(",
")",
"system",
".",
"dae",
... | Function calls for Newton power flow
Returns
-------
None | [
"Function",
"calls",
"for",
"Newton",
"power",
"flow"
] | 7067898d4f26ce7534e968b8486c4aa8fe3a511a | https://github.com/cuihantao/andes/blob/7067898d4f26ce7534e968b8486c4aa8fe3a511a/andes/routines/pflow.py#L230-L288 |
17,529 | cuihantao/andes | andes/routines/pflow.py | PFLOW.post | def post(self):
"""
Post processing for solved systems.
Store load, generation data on buses.
Store reactive power generation on PVs and slack generators.
Calculate series flows and area flows.
Returns
-------
None
"""
if not self.solved:
return
system = self.system
exec(system.call.pfload)
system.Bus.Pl = system.dae.g[system.Bus.a]
system.Bus.Ql = system.dae.g[system.Bus.v]
exec(system.call.pfgen)
system.Bus.Pg = system.dae.g[system.Bus.a]
system.Bus.Qg = system.dae.g[system.Bus.v]
if system.PV.n:
system.PV.qg = system.dae.y[system.PV.q]
if system.SW.n:
system.SW.pg = system.dae.y[system.SW.p]
system.SW.qg = system.dae.y[system.SW.q]
exec(system.call.seriesflow)
system.Area.seriesflow(system.dae) | python | def post(self):
if not self.solved:
return
system = self.system
exec(system.call.pfload)
system.Bus.Pl = system.dae.g[system.Bus.a]
system.Bus.Ql = system.dae.g[system.Bus.v]
exec(system.call.pfgen)
system.Bus.Pg = system.dae.g[system.Bus.a]
system.Bus.Qg = system.dae.g[system.Bus.v]
if system.PV.n:
system.PV.qg = system.dae.y[system.PV.q]
if system.SW.n:
system.SW.pg = system.dae.y[system.SW.p]
system.SW.qg = system.dae.y[system.SW.q]
exec(system.call.seriesflow)
system.Area.seriesflow(system.dae) | [
"def",
"post",
"(",
"self",
")",
":",
"if",
"not",
"self",
".",
"solved",
":",
"return",
"system",
"=",
"self",
".",
"system",
"exec",
"(",
"system",
".",
"call",
".",
"pfload",
")",
"system",
".",
"Bus",
".",
"Pl",
"=",
"system",
".",
"dae",
"."... | Post processing for solved systems.
Store load, generation data on buses.
Store reactive power generation on PVs and slack generators.
Calculate series flows and area flows.
Returns
-------
None | [
"Post",
"processing",
"for",
"solved",
"systems",
"."
] | 7067898d4f26ce7534e968b8486c4aa8fe3a511a | https://github.com/cuihantao/andes/blob/7067898d4f26ce7534e968b8486c4aa8fe3a511a/andes/routines/pflow.py#L290-L323 |
17,530 | cuihantao/andes | andes/models/pv.py | PV.init0 | def init0(self, dae):
"""
Set initial voltage and reactive power for PQ.
Overwrites Bus.voltage values
"""
dae.y[self.v] = self.v0
dae.y[self.q] = mul(self.u, self.qg) | python | def init0(self, dae):
dae.y[self.v] = self.v0
dae.y[self.q] = mul(self.u, self.qg) | [
"def",
"init0",
"(",
"self",
",",
"dae",
")",
":",
"dae",
".",
"y",
"[",
"self",
".",
"v",
"]",
"=",
"self",
".",
"v0",
"dae",
".",
"y",
"[",
"self",
".",
"q",
"]",
"=",
"mul",
"(",
"self",
".",
"u",
",",
"self",
".",
"qg",
")"
] | Set initial voltage and reactive power for PQ.
Overwrites Bus.voltage values | [
"Set",
"initial",
"voltage",
"and",
"reactive",
"power",
"for",
"PQ",
".",
"Overwrites",
"Bus",
".",
"voltage",
"values"
] | 7067898d4f26ce7534e968b8486c4aa8fe3a511a | https://github.com/cuihantao/andes/blob/7067898d4f26ce7534e968b8486c4aa8fe3a511a/andes/models/pv.py#L99-L105 |
17,531 | cuihantao/andes | andes/models/pv.py | PV.disable_gen | def disable_gen(self, idx):
"""
Disable a PV element for TDS
Parameters
----------
idx
Returns
-------
"""
self.u[self.uid[idx]] = 0
self.system.dae.factorize = True | python | def disable_gen(self, idx):
self.u[self.uid[idx]] = 0
self.system.dae.factorize = True | [
"def",
"disable_gen",
"(",
"self",
",",
"idx",
")",
":",
"self",
".",
"u",
"[",
"self",
".",
"uid",
"[",
"idx",
"]",
"]",
"=",
"0",
"self",
".",
"system",
".",
"dae",
".",
"factorize",
"=",
"True"
] | Disable a PV element for TDS
Parameters
----------
idx
Returns
------- | [
"Disable",
"a",
"PV",
"element",
"for",
"TDS"
] | 7067898d4f26ce7534e968b8486c4aa8fe3a511a | https://github.com/cuihantao/andes/blob/7067898d4f26ce7534e968b8486c4aa8fe3a511a/andes/models/pv.py#L172-L185 |
17,532 | cuihantao/andes | andes/models/pq.py | PQ.init0 | def init0(self, dae):
"""Set initial p and q for power flow"""
self.p0 = matrix(self.p, (self.n, 1), 'd')
self.q0 = matrix(self.q, (self.n, 1), 'd') | python | def init0(self, dae):
self.p0 = matrix(self.p, (self.n, 1), 'd')
self.q0 = matrix(self.q, (self.n, 1), 'd') | [
"def",
"init0",
"(",
"self",
",",
"dae",
")",
":",
"self",
".",
"p0",
"=",
"matrix",
"(",
"self",
".",
"p",
",",
"(",
"self",
".",
"n",
",",
"1",
")",
",",
"'d'",
")",
"self",
".",
"q0",
"=",
"matrix",
"(",
"self",
".",
"q",
",",
"(",
"se... | Set initial p and q for power flow | [
"Set",
"initial",
"p",
"and",
"q",
"for",
"power",
"flow"
] | 7067898d4f26ce7534e968b8486c4aa8fe3a511a | https://github.com/cuihantao/andes/blob/7067898d4f26ce7534e968b8486c4aa8fe3a511a/andes/models/pq.py#L62-L65 |
17,533 | cuihantao/andes | andes/models/pq.py | PQ.init1 | def init1(self, dae):
"""Set initial voltage for time domain simulation"""
self.v0 = matrix(dae.y[self.v]) | python | def init1(self, dae):
self.v0 = matrix(dae.y[self.v]) | [
"def",
"init1",
"(",
"self",
",",
"dae",
")",
":",
"self",
".",
"v0",
"=",
"matrix",
"(",
"dae",
".",
"y",
"[",
"self",
".",
"v",
"]",
")"
] | Set initial voltage for time domain simulation | [
"Set",
"initial",
"voltage",
"for",
"time",
"domain",
"simulation"
] | 7067898d4f26ce7534e968b8486c4aa8fe3a511a | https://github.com/cuihantao/andes/blob/7067898d4f26ce7534e968b8486c4aa8fe3a511a/andes/models/pq.py#L67-L69 |
17,534 | DiamondLightSource/python-workflows | workflows/contrib/status_monitor.py | Monitor.update_status | def update_status(self, header, message):
"""Process incoming status message. Acquire lock for status dictionary before updating."""
with self._lock:
if self.message_box:
self.message_box.erase()
self.message_box.move(0, 0)
for n, field in enumerate(header):
if n == 0:
self.message_box.addstr(field + ":", curses.color_pair(1))
else:
self.message_box.addstr(
", " + field + ":", curses.color_pair(1)
)
self.message_box.addstr(header[field])
self.message_box.addstr(": ", curses.color_pair(1))
self.message_box.addstr(
str(message), curses.color_pair(2) + curses.A_BOLD
)
self.message_box.refresh()
if (
message["host"] not in self._node_status
or int(header["timestamp"])
>= self._node_status[message["host"]]["last_seen"]
):
self._node_status[message["host"]] = message
self._node_status[message["host"]]["last_seen"] = int(
header["timestamp"]
) | python | def update_status(self, header, message):
with self._lock:
if self.message_box:
self.message_box.erase()
self.message_box.move(0, 0)
for n, field in enumerate(header):
if n == 0:
self.message_box.addstr(field + ":", curses.color_pair(1))
else:
self.message_box.addstr(
", " + field + ":", curses.color_pair(1)
)
self.message_box.addstr(header[field])
self.message_box.addstr(": ", curses.color_pair(1))
self.message_box.addstr(
str(message), curses.color_pair(2) + curses.A_BOLD
)
self.message_box.refresh()
if (
message["host"] not in self._node_status
or int(header["timestamp"])
>= self._node_status[message["host"]]["last_seen"]
):
self._node_status[message["host"]] = message
self._node_status[message["host"]]["last_seen"] = int(
header["timestamp"]
) | [
"def",
"update_status",
"(",
"self",
",",
"header",
",",
"message",
")",
":",
"with",
"self",
".",
"_lock",
":",
"if",
"self",
".",
"message_box",
":",
"self",
".",
"message_box",
".",
"erase",
"(",
")",
"self",
".",
"message_box",
".",
"move",
"(",
... | Process incoming status message. Acquire lock for status dictionary before updating. | [
"Process",
"incoming",
"status",
"message",
".",
"Acquire",
"lock",
"for",
"status",
"dictionary",
"before",
"updating",
"."
] | 7ef47b457655b96f4d2ef7ee9863cf1b6d20e023 | https://github.com/DiamondLightSource/python-workflows/blob/7ef47b457655b96f4d2ef7ee9863cf1b6d20e023/workflows/contrib/status_monitor.py#L46-L73 |
17,535 | DiamondLightSource/python-workflows | workflows/contrib/status_monitor.py | Monitor._redraw_screen | def _redraw_screen(self, stdscr):
"""Redraw screen. This could be to initialize, or to redraw after resizing."""
with self._lock:
stdscr.clear()
stdscr.addstr(
0, 0, "workflows service monitor -- quit with Ctrl+C", curses.A_BOLD
)
stdscr.refresh()
self.message_box = self._boxwin(
5, curses.COLS, 2, 0, title="last seen message", color_pair=1
)
self.message_box.scrollok(True)
self.cards = [] | python | def _redraw_screen(self, stdscr):
with self._lock:
stdscr.clear()
stdscr.addstr(
0, 0, "workflows service monitor -- quit with Ctrl+C", curses.A_BOLD
)
stdscr.refresh()
self.message_box = self._boxwin(
5, curses.COLS, 2, 0, title="last seen message", color_pair=1
)
self.message_box.scrollok(True)
self.cards = [] | [
"def",
"_redraw_screen",
"(",
"self",
",",
"stdscr",
")",
":",
"with",
"self",
".",
"_lock",
":",
"stdscr",
".",
"clear",
"(",
")",
"stdscr",
".",
"addstr",
"(",
"0",
",",
"0",
",",
"\"workflows service monitor -- quit with Ctrl+C\"",
",",
"curses",
".",
"... | Redraw screen. This could be to initialize, or to redraw after resizing. | [
"Redraw",
"screen",
".",
"This",
"could",
"be",
"to",
"initialize",
"or",
"to",
"redraw",
"after",
"resizing",
"."
] | 7ef47b457655b96f4d2ef7ee9863cf1b6d20e023 | https://github.com/DiamondLightSource/python-workflows/blob/7ef47b457655b96f4d2ef7ee9863cf1b6d20e023/workflows/contrib/status_monitor.py#L96-L108 |
17,536 | DiamondLightSource/python-workflows | workflows/contrib/status_monitor.py | Monitor._erase_card | def _erase_card(self, number):
"""Destroy cards with this or higher number."""
with self._lock:
if number < (len(self.cards) - 1):
self._erase_card(number + 1)
if number > (len(self.cards) - 1):
return
max_cards_horiz = int(curses.COLS / 35)
obliterate = curses.newwin(
6,
35,
7 + 6 * (number // max_cards_horiz),
35 * (number % max_cards_horiz),
)
obliterate.erase()
obliterate.noutrefresh()
del self.cards[number] | python | def _erase_card(self, number):
with self._lock:
if number < (len(self.cards) - 1):
self._erase_card(number + 1)
if number > (len(self.cards) - 1):
return
max_cards_horiz = int(curses.COLS / 35)
obliterate = curses.newwin(
6,
35,
7 + 6 * (number // max_cards_horiz),
35 * (number % max_cards_horiz),
)
obliterate.erase()
obliterate.noutrefresh()
del self.cards[number] | [
"def",
"_erase_card",
"(",
"self",
",",
"number",
")",
":",
"with",
"self",
".",
"_lock",
":",
"if",
"number",
"<",
"(",
"len",
"(",
"self",
".",
"cards",
")",
"-",
"1",
")",
":",
"self",
".",
"_erase_card",
"(",
"number",
"+",
"1",
")",
"if",
... | Destroy cards with this or higher number. | [
"Destroy",
"cards",
"with",
"this",
"or",
"higher",
"number",
"."
] | 7ef47b457655b96f4d2ef7ee9863cf1b6d20e023 | https://github.com/DiamondLightSource/python-workflows/blob/7ef47b457655b96f4d2ef7ee9863cf1b6d20e023/workflows/contrib/status_monitor.py#L128-L144 |
17,537 | DiamondLightSource/python-workflows | workflows/contrib/status_monitor.py | Monitor._run | def _run(self, stdscr):
"""Start the actual service monitor"""
with self._lock:
curses.use_default_colors()
curses.curs_set(False)
curses.init_pair(1, curses.COLOR_RED, -1)
curses.init_pair(2, curses.COLOR_BLACK, -1)
curses.init_pair(3, curses.COLOR_GREEN, -1)
self._redraw_screen(stdscr)
try:
while not self.shutdown:
now = int(time.time())
with self._lock:
overview = self._node_status.copy()
cardnumber = 0
for host, status in overview.items():
age = now - int(status["last_seen"] / 1000)
with self._lock:
if age > 90:
del self._node_status[host]
else:
card = self._get_card(cardnumber)
card.erase()
card.move(0, 0)
card.addstr("Host: ", curses.color_pair(3))
card.addstr(host)
card.move(1, 0)
card.addstr("Service: ", curses.color_pair(3))
if "service" in status and status["service"]:
card.addstr(status["service"])
else:
card.addstr("---", curses.color_pair(2))
card.move(2, 0)
card.addstr("State: ", curses.color_pair(3))
if "status" in status:
status_code = status["status"]
state_string = CommonService.human_readable_state.get(
status_code, str(status_code)
)
state_color = None
if status_code in (
CommonService.SERVICE_STATUS_PROCESSING,
CommonService.SERVICE_STATUS_TIMER,
):
state_color = curses.color_pair(3) + curses.A_BOLD
if status_code == CommonService.SERVICE_STATUS_IDLE:
state_color = curses.color_pair(2) + curses.A_BOLD
if status_code == CommonService.SERVICE_STATUS_ERROR:
state_color = curses.color_pair(1)
if state_color:
card.addstr(state_string, state_color)
else:
card.addstr(state_string)
card.move(3, 0)
if age >= 10:
card.addstr(
"last seen %d seconds ago" % age,
curses.color_pair(1)
+ (0 if age < 60 else curses.A_BOLD),
)
card.noutrefresh()
cardnumber = cardnumber + 1
if cardnumber < len(self.cards):
with self._lock:
self._erase_card(cardnumber)
with self._lock:
curses.doupdate()
time.sleep(0.2)
except KeyboardInterrupt:
pass # User pressed CTRL+C
self._transport.disconnect() | python | def _run(self, stdscr):
with self._lock:
curses.use_default_colors()
curses.curs_set(False)
curses.init_pair(1, curses.COLOR_RED, -1)
curses.init_pair(2, curses.COLOR_BLACK, -1)
curses.init_pair(3, curses.COLOR_GREEN, -1)
self._redraw_screen(stdscr)
try:
while not self.shutdown:
now = int(time.time())
with self._lock:
overview = self._node_status.copy()
cardnumber = 0
for host, status in overview.items():
age = now - int(status["last_seen"] / 1000)
with self._lock:
if age > 90:
del self._node_status[host]
else:
card = self._get_card(cardnumber)
card.erase()
card.move(0, 0)
card.addstr("Host: ", curses.color_pair(3))
card.addstr(host)
card.move(1, 0)
card.addstr("Service: ", curses.color_pair(3))
if "service" in status and status["service"]:
card.addstr(status["service"])
else:
card.addstr("---", curses.color_pair(2))
card.move(2, 0)
card.addstr("State: ", curses.color_pair(3))
if "status" in status:
status_code = status["status"]
state_string = CommonService.human_readable_state.get(
status_code, str(status_code)
)
state_color = None
if status_code in (
CommonService.SERVICE_STATUS_PROCESSING,
CommonService.SERVICE_STATUS_TIMER,
):
state_color = curses.color_pair(3) + curses.A_BOLD
if status_code == CommonService.SERVICE_STATUS_IDLE:
state_color = curses.color_pair(2) + curses.A_BOLD
if status_code == CommonService.SERVICE_STATUS_ERROR:
state_color = curses.color_pair(1)
if state_color:
card.addstr(state_string, state_color)
else:
card.addstr(state_string)
card.move(3, 0)
if age >= 10:
card.addstr(
"last seen %d seconds ago" % age,
curses.color_pair(1)
+ (0 if age < 60 else curses.A_BOLD),
)
card.noutrefresh()
cardnumber = cardnumber + 1
if cardnumber < len(self.cards):
with self._lock:
self._erase_card(cardnumber)
with self._lock:
curses.doupdate()
time.sleep(0.2)
except KeyboardInterrupt:
pass # User pressed CTRL+C
self._transport.disconnect() | [
"def",
"_run",
"(",
"self",
",",
"stdscr",
")",
":",
"with",
"self",
".",
"_lock",
":",
"curses",
".",
"use_default_colors",
"(",
")",
"curses",
".",
"curs_set",
"(",
"False",
")",
"curses",
".",
"init_pair",
"(",
"1",
",",
"curses",
".",
"COLOR_RED",
... | Start the actual service monitor | [
"Start",
"the",
"actual",
"service",
"monitor"
] | 7ef47b457655b96f4d2ef7ee9863cf1b6d20e023 | https://github.com/DiamondLightSource/python-workflows/blob/7ef47b457655b96f4d2ef7ee9863cf1b6d20e023/workflows/contrib/status_monitor.py#L146-L217 |
17,538 | cuihantao/andes | andes/models/vsc.py | VSC.disable | def disable(self, idx):
"""Disable an element and reset the outputs"""
if idx not in self.uid.keys():
self.log('Element index {0} does not exist.'.format(idx))
return
self.u[self.uid[idx]] = 0 | python | def disable(self, idx):
if idx not in self.uid.keys():
self.log('Element index {0} does not exist.'.format(idx))
return
self.u[self.uid[idx]] = 0 | [
"def",
"disable",
"(",
"self",
",",
"idx",
")",
":",
"if",
"idx",
"not",
"in",
"self",
".",
"uid",
".",
"keys",
"(",
")",
":",
"self",
".",
"log",
"(",
"'Element index {0} does not exist.'",
".",
"format",
"(",
"idx",
")",
")",
"return",
"self",
".",... | Disable an element and reset the outputs | [
"Disable",
"an",
"element",
"and",
"reset",
"the",
"outputs"
] | 7067898d4f26ce7534e968b8486c4aa8fe3a511a | https://github.com/cuihantao/andes/blob/7067898d4f26ce7534e968b8486c4aa8fe3a511a/andes/models/vsc.py#L437-L442 |
17,539 | cuihantao/andes | andes/config/base.py | ConfigBase.get_alt | def get_alt(self, option):
"""
Return the alternative values of an option
Parameters
----------
option: str
option name
Returns
-------
str
a string of alternative options
"""
assert hasattr(self, option)
alt = option + '_alt'
if not hasattr(self, alt):
return ''
return ', '.join(self.__dict__[alt]) | python | def get_alt(self, option):
assert hasattr(self, option)
alt = option + '_alt'
if not hasattr(self, alt):
return ''
return ', '.join(self.__dict__[alt]) | [
"def",
"get_alt",
"(",
"self",
",",
"option",
")",
":",
"assert",
"hasattr",
"(",
"self",
",",
"option",
")",
"alt",
"=",
"option",
"+",
"'_alt'",
"if",
"not",
"hasattr",
"(",
"self",
",",
"alt",
")",
":",
"return",
"''",
"return",
"', '",
".",
"jo... | Return the alternative values of an option
Parameters
----------
option: str
option name
Returns
-------
str
a string of alternative options | [
"Return",
"the",
"alternative",
"values",
"of",
"an",
"option"
] | 7067898d4f26ce7534e968b8486c4aa8fe3a511a | https://github.com/cuihantao/andes/blob/7067898d4f26ce7534e968b8486c4aa8fe3a511a/andes/config/base.py#L36-L56 |
17,540 | cuihantao/andes | andes/config/base.py | ConfigBase.doc | def doc(self, export='plain'):
"""
Dump help document for setting classes
"""
rows = []
title = '<{:s}> config options'.format(self.__class__.__name__)
table = Tab(export=export, title=title)
for opt in sorted(self.config_descr):
if hasattr(self, opt):
c1 = opt
c2 = self.config_descr[opt]
c3 = self.__dict__.get(opt, '')
c4 = self.get_alt(opt)
rows.append([c1, c2, c3, c4])
else:
print('Setting {:s} has no {:s} option. Correct in config_descr.'.
format(self.__class__.__name__, opt))
table.add_rows(rows, header=False)
table.header(['Option', 'Description', 'Value', 'Alt.'])
return table.draw() | python | def doc(self, export='plain'):
rows = []
title = '<{:s}> config options'.format(self.__class__.__name__)
table = Tab(export=export, title=title)
for opt in sorted(self.config_descr):
if hasattr(self, opt):
c1 = opt
c2 = self.config_descr[opt]
c3 = self.__dict__.get(opt, '')
c4 = self.get_alt(opt)
rows.append([c1, c2, c3, c4])
else:
print('Setting {:s} has no {:s} option. Correct in config_descr.'.
format(self.__class__.__name__, opt))
table.add_rows(rows, header=False)
table.header(['Option', 'Description', 'Value', 'Alt.'])
return table.draw() | [
"def",
"doc",
"(",
"self",
",",
"export",
"=",
"'plain'",
")",
":",
"rows",
"=",
"[",
"]",
"title",
"=",
"'<{:s}> config options'",
".",
"format",
"(",
"self",
".",
"__class__",
".",
"__name__",
")",
"table",
"=",
"Tab",
"(",
"export",
"=",
"export",
... | Dump help document for setting classes | [
"Dump",
"help",
"document",
"for",
"setting",
"classes"
] | 7067898d4f26ce7534e968b8486c4aa8fe3a511a | https://github.com/cuihantao/andes/blob/7067898d4f26ce7534e968b8486c4aa8fe3a511a/andes/config/base.py#L58-L80 |
17,541 | cuihantao/andes | andes/config/base.py | ConfigBase.dump_conf | def dump_conf(self, conf=None):
"""
Dump settings to an rc config file
Parameters
----------
conf
configparser.ConfigParser() object
Returns
-------
None
"""
if conf is None:
conf = configparser.ConfigParser()
tab = self.__class__.__name__
conf[tab] = {}
for key, val in self.__dict__.items():
if key.endswith('_alt'):
continue
conf[tab][key] = str(val)
return conf | python | def dump_conf(self, conf=None):
if conf is None:
conf = configparser.ConfigParser()
tab = self.__class__.__name__
conf[tab] = {}
for key, val in self.__dict__.items():
if key.endswith('_alt'):
continue
conf[tab][key] = str(val)
return conf | [
"def",
"dump_conf",
"(",
"self",
",",
"conf",
"=",
"None",
")",
":",
"if",
"conf",
"is",
"None",
":",
"conf",
"=",
"configparser",
".",
"ConfigParser",
"(",
")",
"tab",
"=",
"self",
".",
"__class__",
".",
"__name__",
"conf",
"[",
"tab",
"]",
"=",
"... | Dump settings to an rc config file
Parameters
----------
conf
configparser.ConfigParser() object
Returns
-------
None | [
"Dump",
"settings",
"to",
"an",
"rc",
"config",
"file"
] | 7067898d4f26ce7534e968b8486c4aa8fe3a511a | https://github.com/cuihantao/andes/blob/7067898d4f26ce7534e968b8486c4aa8fe3a511a/andes/config/base.py#L82-L107 |
17,542 | cuihantao/andes | andes/config/base.py | ConfigBase.load_config | def load_config(self, conf):
"""
Load configurations from an rc file
Parameters
----------
rc: str
path to the rc file
Returns
-------
None
"""
section = self.__class__.__name__
if section not in conf.sections():
logger.debug('Config section {} not in rc file'.format(
self.__class__.__name__))
return
for key in conf[section].keys():
if not hasattr(self, key):
logger.debug('Config key {}.{} skipped'.format(section, key))
continue
val = conf[section].get(key)
try:
val = conf[section].getfloat(key)
except ValueError:
try:
val = conf[section].getboolean(key)
except ValueError:
pass
self.__dict__.update({key: val})
self.check() | python | def load_config(self, conf):
section = self.__class__.__name__
if section not in conf.sections():
logger.debug('Config section {} not in rc file'.format(
self.__class__.__name__))
return
for key in conf[section].keys():
if not hasattr(self, key):
logger.debug('Config key {}.{} skipped'.format(section, key))
continue
val = conf[section].get(key)
try:
val = conf[section].getfloat(key)
except ValueError:
try:
val = conf[section].getboolean(key)
except ValueError:
pass
self.__dict__.update({key: val})
self.check() | [
"def",
"load_config",
"(",
"self",
",",
"conf",
")",
":",
"section",
"=",
"self",
".",
"__class__",
".",
"__name__",
"if",
"section",
"not",
"in",
"conf",
".",
"sections",
"(",
")",
":",
"logger",
".",
"debug",
"(",
"'Config section {} not in rc file'",
".... | Load configurations from an rc file
Parameters
----------
rc: str
path to the rc file
Returns
-------
None | [
"Load",
"configurations",
"from",
"an",
"rc",
"file"
] | 7067898d4f26ce7534e968b8486c4aa8fe3a511a | https://github.com/cuihantao/andes/blob/7067898d4f26ce7534e968b8486c4aa8fe3a511a/andes/config/base.py#L109-L146 |
17,543 | DiamondLightSource/python-workflows | workflows/frontend/utilization.py | UtilizationStatistics.update_status | def update_status(self, new_status):
"""Record a status change with a current timestamp."""
timestamp = time.time()
self.status_history[-1]["end"] = timestamp
self.status_history.append(
{"start": timestamp, "end": None, "status": new_status}
) | python | def update_status(self, new_status):
timestamp = time.time()
self.status_history[-1]["end"] = timestamp
self.status_history.append(
{"start": timestamp, "end": None, "status": new_status}
) | [
"def",
"update_status",
"(",
"self",
",",
"new_status",
")",
":",
"timestamp",
"=",
"time",
".",
"time",
"(",
")",
"self",
".",
"status_history",
"[",
"-",
"1",
"]",
"[",
"\"end\"",
"]",
"=",
"timestamp",
"self",
".",
"status_history",
".",
"append",
"... | Record a status change with a current timestamp. | [
"Record",
"a",
"status",
"change",
"with",
"a",
"current",
"timestamp",
"."
] | 7ef47b457655b96f4d2ef7ee9863cf1b6d20e023 | https://github.com/DiamondLightSource/python-workflows/blob/7ef47b457655b96f4d2ef7ee9863cf1b6d20e023/workflows/frontend/utilization.py#L20-L26 |
17,544 | DiamondLightSource/python-workflows | workflows/frontend/utilization.py | UtilizationStatistics.report | def report(self):
"""Return a dictionary of different status codes and the percentage of time
spent in each throughout the last summation_period seconds.
Truncate the aggregated history appropriately."""
timestamp = time.time()
cutoff = timestamp - self.period
truncate = 0
summary = {}
for event in self.status_history[:-1]:
if event["end"] < cutoff:
truncate = truncate + 1
continue
summary[event["status"]] = (
summary.get(event["status"], 0)
+ event["end"]
- max(cutoff, event["start"])
)
summary[self.status_history[-1]["status"]] = (
summary.get(self.status_history[-1]["status"], 0)
+ timestamp
- max(cutoff, self.status_history[-1]["start"])
)
if truncate:
self.status_history = self.status_history[truncate:]
total_duration = sum(summary.values())
summary = {s: round(d / total_duration, 4) for s, d in summary.items()}
return summary | python | def report(self):
timestamp = time.time()
cutoff = timestamp - self.period
truncate = 0
summary = {}
for event in self.status_history[:-1]:
if event["end"] < cutoff:
truncate = truncate + 1
continue
summary[event["status"]] = (
summary.get(event["status"], 0)
+ event["end"]
- max(cutoff, event["start"])
)
summary[self.status_history[-1]["status"]] = (
summary.get(self.status_history[-1]["status"], 0)
+ timestamp
- max(cutoff, self.status_history[-1]["start"])
)
if truncate:
self.status_history = self.status_history[truncate:]
total_duration = sum(summary.values())
summary = {s: round(d / total_duration, 4) for s, d in summary.items()}
return summary | [
"def",
"report",
"(",
"self",
")",
":",
"timestamp",
"=",
"time",
".",
"time",
"(",
")",
"cutoff",
"=",
"timestamp",
"-",
"self",
".",
"period",
"truncate",
"=",
"0",
"summary",
"=",
"{",
"}",
"for",
"event",
"in",
"self",
".",
"status_history",
"[",... | Return a dictionary of different status codes and the percentage of time
spent in each throughout the last summation_period seconds.
Truncate the aggregated history appropriately. | [
"Return",
"a",
"dictionary",
"of",
"different",
"status",
"codes",
"and",
"the",
"percentage",
"of",
"time",
"spent",
"in",
"each",
"throughout",
"the",
"last",
"summation_period",
"seconds",
".",
"Truncate",
"the",
"aggregated",
"history",
"appropriately",
"."
] | 7ef47b457655b96f4d2ef7ee9863cf1b6d20e023 | https://github.com/DiamondLightSource/python-workflows/blob/7ef47b457655b96f4d2ef7ee9863cf1b6d20e023/workflows/frontend/utilization.py#L28-L54 |
17,545 | DiamondLightSource/python-workflows | workflows/util/__init__.py | generate_unique_host_id | def generate_unique_host_id():
"""Generate a unique ID, that is somewhat guaranteed to be unique among all
instances running at the same time."""
host = ".".join(reversed(socket.gethostname().split(".")))
pid = os.getpid()
return "%s.%d" % (host, pid) | python | def generate_unique_host_id():
host = ".".join(reversed(socket.gethostname().split(".")))
pid = os.getpid()
return "%s.%d" % (host, pid) | [
"def",
"generate_unique_host_id",
"(",
")",
":",
"host",
"=",
"\".\"",
".",
"join",
"(",
"reversed",
"(",
"socket",
".",
"gethostname",
"(",
")",
".",
"split",
"(",
"\".\"",
")",
")",
")",
"pid",
"=",
"os",
".",
"getpid",
"(",
")",
"return",
"\"%s.%d... | Generate a unique ID, that is somewhat guaranteed to be unique among all
instances running at the same time. | [
"Generate",
"a",
"unique",
"ID",
"that",
"is",
"somewhat",
"guaranteed",
"to",
"be",
"unique",
"among",
"all",
"instances",
"running",
"at",
"the",
"same",
"time",
"."
] | 7ef47b457655b96f4d2ef7ee9863cf1b6d20e023 | https://github.com/DiamondLightSource/python-workflows/blob/7ef47b457655b96f4d2ef7ee9863cf1b6d20e023/workflows/util/__init__.py#L7-L12 |
17,546 | cuihantao/andes | andes/models/governor.py | GovernorBase.data_to_sys_base | def data_to_sys_base(self):
"""Custom system base conversion function"""
if not self.n or self._flags['sysbase'] is True:
return
self.copy_data_ext(model='Synchronous', field='Sn', dest='Sn', idx=self.gen)
super(GovernorBase, self).data_to_sys_base()
self._store['R'] = self.R
self.R = self.system.mva * div(self.R, self.Sn) | python | def data_to_sys_base(self):
if not self.n or self._flags['sysbase'] is True:
return
self.copy_data_ext(model='Synchronous', field='Sn', dest='Sn', idx=self.gen)
super(GovernorBase, self).data_to_sys_base()
self._store['R'] = self.R
self.R = self.system.mva * div(self.R, self.Sn) | [
"def",
"data_to_sys_base",
"(",
"self",
")",
":",
"if",
"not",
"self",
".",
"n",
"or",
"self",
".",
"_flags",
"[",
"'sysbase'",
"]",
"is",
"True",
":",
"return",
"self",
".",
"copy_data_ext",
"(",
"model",
"=",
"'Synchronous'",
",",
"field",
"=",
"'Sn'... | Custom system base conversion function | [
"Custom",
"system",
"base",
"conversion",
"function"
] | 7067898d4f26ce7534e968b8486c4aa8fe3a511a | https://github.com/cuihantao/andes/blob/7067898d4f26ce7534e968b8486c4aa8fe3a511a/andes/models/governor.py#L52-L61 |
17,547 | cuihantao/andes | andes/models/governor.py | GovernorBase.data_to_elem_base | def data_to_elem_base(self):
"""Custom system base unconversion function"""
if not self.n or self._flags['sysbase'] is False:
return
self.R = mul(self.R, self.Sn) / self.system.mva
super(GovernorBase, self).data_to_elem_base() | python | def data_to_elem_base(self):
if not self.n or self._flags['sysbase'] is False:
return
self.R = mul(self.R, self.Sn) / self.system.mva
super(GovernorBase, self).data_to_elem_base() | [
"def",
"data_to_elem_base",
"(",
"self",
")",
":",
"if",
"not",
"self",
".",
"n",
"or",
"self",
".",
"_flags",
"[",
"'sysbase'",
"]",
"is",
"False",
":",
"return",
"self",
".",
"R",
"=",
"mul",
"(",
"self",
".",
"R",
",",
"self",
".",
"Sn",
")",
... | Custom system base unconversion function | [
"Custom",
"system",
"base",
"unconversion",
"function"
] | 7067898d4f26ce7534e968b8486c4aa8fe3a511a | https://github.com/cuihantao/andes/blob/7067898d4f26ce7534e968b8486c4aa8fe3a511a/andes/models/governor.py#L63-L68 |
17,548 | cuihantao/andes | andes/variables/fileman.py | add_suffix | def add_suffix(fullname, suffix):
""" Add suffix to a full file name"""
name, ext = os.path.splitext(fullname)
return name + '_' + suffix + ext | python | def add_suffix(fullname, suffix):
name, ext = os.path.splitext(fullname)
return name + '_' + suffix + ext | [
"def",
"add_suffix",
"(",
"fullname",
",",
"suffix",
")",
":",
"name",
",",
"ext",
"=",
"os",
".",
"path",
".",
"splitext",
"(",
"fullname",
")",
"return",
"name",
"+",
"'_'",
"+",
"suffix",
"+",
"ext"
] | Add suffix to a full file name | [
"Add",
"suffix",
"to",
"a",
"full",
"file",
"name"
] | 7067898d4f26ce7534e968b8486c4aa8fe3a511a | https://github.com/cuihantao/andes/blob/7067898d4f26ce7534e968b8486c4aa8fe3a511a/andes/variables/fileman.py#L121-L124 |
17,549 | cuihantao/andes | andes/variables/fileman.py | FileMan.get_fullpath | def get_fullpath(self, fullname=None, relative_to=None):
"""
Return the original full path if full path is specified, otherwise
search in the case file path
"""
# if is an empty path
if not fullname:
return fullname
isabs = os.path.isabs(fullname)
path, name = os.path.split(fullname)
if not name: # path to a folder
return None
else: # path to a file
if isabs:
return fullname
else:
return os.path.join(self.case_path, path, name) | python | def get_fullpath(self, fullname=None, relative_to=None):
# if is an empty path
if not fullname:
return fullname
isabs = os.path.isabs(fullname)
path, name = os.path.split(fullname)
if not name: # path to a folder
return None
else: # path to a file
if isabs:
return fullname
else:
return os.path.join(self.case_path, path, name) | [
"def",
"get_fullpath",
"(",
"self",
",",
"fullname",
"=",
"None",
",",
"relative_to",
"=",
"None",
")",
":",
"# if is an empty path",
"if",
"not",
"fullname",
":",
"return",
"fullname",
"isabs",
"=",
"os",
".",
"path",
".",
"isabs",
"(",
"fullname",
")",
... | Return the original full path if full path is specified, otherwise
search in the case file path | [
"Return",
"the",
"original",
"full",
"path",
"if",
"full",
"path",
"is",
"specified",
"otherwise",
"search",
"in",
"the",
"case",
"file",
"path"
] | 7067898d4f26ce7534e968b8486c4aa8fe3a511a | https://github.com/cuihantao/andes/blob/7067898d4f26ce7534e968b8486c4aa8fe3a511a/andes/variables/fileman.py#L99-L118 |
17,550 | cuihantao/andes | andes/models/agc.py | eAGC.switch | def switch(self):
"""Switch if time for eAgc has come"""
t = self.system.dae.t
for idx in range(0, self.n):
if t >= self.tl[idx]:
if self.en[idx] == 0:
self.en[idx] = 1
logger.info(
'Extended ACE <{}> activated at t = {}.'.format(
self.idx[idx], t)) | python | def switch(self):
t = self.system.dae.t
for idx in range(0, self.n):
if t >= self.tl[idx]:
if self.en[idx] == 0:
self.en[idx] = 1
logger.info(
'Extended ACE <{}> activated at t = {}.'.format(
self.idx[idx], t)) | [
"def",
"switch",
"(",
"self",
")",
":",
"t",
"=",
"self",
".",
"system",
".",
"dae",
".",
"t",
"for",
"idx",
"in",
"range",
"(",
"0",
",",
"self",
".",
"n",
")",
":",
"if",
"t",
">=",
"self",
".",
"tl",
"[",
"idx",
"]",
":",
"if",
"self",
... | Switch if time for eAgc has come | [
"Switch",
"if",
"time",
"for",
"eAgc",
"has",
"come"
] | 7067898d4f26ce7534e968b8486c4aa8fe3a511a | https://github.com/cuihantao/andes/blob/7067898d4f26ce7534e968b8486c4aa8fe3a511a/andes/models/agc.py#L169-L178 |
17,551 | cuihantao/andes | andes/routines/__init__.py | get_command | def get_command(all_pkg, hook):
"""
Collect the command-line interface names by querying ``hook`` in ``all_pkg``
Parameters
----------
all_pkg: list
list of package files
hook: str
A variable where the command is stored. ``__cli__`` by default.
Returns
-------
list
"""
ret = []
for r in all_pkg:
module = importlib.import_module(__name__ + '.' + r.lower())
ret.append(getattr(module, hook))
return ret | python | def get_command(all_pkg, hook):
ret = []
for r in all_pkg:
module = importlib.import_module(__name__ + '.' + r.lower())
ret.append(getattr(module, hook))
return ret | [
"def",
"get_command",
"(",
"all_pkg",
",",
"hook",
")",
":",
"ret",
"=",
"[",
"]",
"for",
"r",
"in",
"all_pkg",
":",
"module",
"=",
"importlib",
".",
"import_module",
"(",
"__name__",
"+",
"'.'",
"+",
"r",
".",
"lower",
"(",
")",
")",
"ret",
".",
... | Collect the command-line interface names by querying ``hook`` in ``all_pkg``
Parameters
----------
all_pkg: list
list of package files
hook: str
A variable where the command is stored. ``__cli__`` by default.
Returns
-------
list | [
"Collect",
"the",
"command",
"-",
"line",
"interface",
"names",
"by",
"querying",
"hook",
"in",
"all_pkg"
] | 7067898d4f26ce7534e968b8486c4aa8fe3a511a | https://github.com/cuihantao/andes/blob/7067898d4f26ce7534e968b8486c4aa8fe3a511a/andes/routines/__init__.py#L7-L25 |
17,552 | cuihantao/andes | andes/models/event.py | EventBase.get_times | def get_times(self):
"""
Return a list of occurrance times of the events
:return: list of times
"""
if not self.n:
return list()
ret = list()
for item in self._event_times:
ret += list(self.__dict__[item])
return ret + list(matrix(ret) - 1e-6) | python | def get_times(self):
if not self.n:
return list()
ret = list()
for item in self._event_times:
ret += list(self.__dict__[item])
return ret + list(matrix(ret) - 1e-6) | [
"def",
"get_times",
"(",
"self",
")",
":",
"if",
"not",
"self",
".",
"n",
":",
"return",
"list",
"(",
")",
"ret",
"=",
"list",
"(",
")",
"for",
"item",
"in",
"self",
".",
"_event_times",
":",
"ret",
"+=",
"list",
"(",
"self",
".",
"__dict__",
"["... | Return a list of occurrance times of the events
:return: list of times | [
"Return",
"a",
"list",
"of",
"occurrance",
"times",
"of",
"the",
"events"
] | 7067898d4f26ce7534e968b8486c4aa8fe3a511a | https://github.com/cuihantao/andes/blob/7067898d4f26ce7534e968b8486c4aa8fe3a511a/andes/models/event.py#L20-L34 |
17,553 | cuihantao/andes | andes/models/line.py | Line.build_y | def build_y(self):
"""Build transmission line admittance matrix into self.Y"""
if not self.n:
return
self.y1 = mul(self.u, self.g1 + self.b1 * 1j)
self.y2 = mul(self.u, self.g2 + self.b2 * 1j)
self.y12 = div(self.u, self.r + self.x * 1j)
self.m = polar(self.tap, self.phi * deg2rad)
self.m2 = abs(self.m)**2
self.mconj = conj(self.m)
# build self and mutual admittances into Y
self.Y = spmatrix(
div(self.y12 + self.y1, self.m2), self.a1, self.a1,
(self.nb, self.nb), 'z')
self.Y -= spmatrix(
div(self.y12, self.mconj), self.a1, self.a2, (self.nb, self.nb),
'z')
self.Y -= spmatrix(
div(self.y12, self.m), self.a2, self.a1, (self.nb, self.nb), 'z')
self.Y += spmatrix(self.y12 + self.y2, self.a2, self.a2,
(self.nb, self.nb), 'z') | python | def build_y(self):
if not self.n:
return
self.y1 = mul(self.u, self.g1 + self.b1 * 1j)
self.y2 = mul(self.u, self.g2 + self.b2 * 1j)
self.y12 = div(self.u, self.r + self.x * 1j)
self.m = polar(self.tap, self.phi * deg2rad)
self.m2 = abs(self.m)**2
self.mconj = conj(self.m)
# build self and mutual admittances into Y
self.Y = spmatrix(
div(self.y12 + self.y1, self.m2), self.a1, self.a1,
(self.nb, self.nb), 'z')
self.Y -= spmatrix(
div(self.y12, self.mconj), self.a1, self.a2, (self.nb, self.nb),
'z')
self.Y -= spmatrix(
div(self.y12, self.m), self.a2, self.a1, (self.nb, self.nb), 'z')
self.Y += spmatrix(self.y12 + self.y2, self.a2, self.a2,
(self.nb, self.nb), 'z') | [
"def",
"build_y",
"(",
"self",
")",
":",
"if",
"not",
"self",
".",
"n",
":",
"return",
"self",
".",
"y1",
"=",
"mul",
"(",
"self",
".",
"u",
",",
"self",
".",
"g1",
"+",
"self",
".",
"b1",
"*",
"1j",
")",
"self",
".",
"y2",
"=",
"mul",
"(",... | Build transmission line admittance matrix into self.Y | [
"Build",
"transmission",
"line",
"admittance",
"matrix",
"into",
"self",
".",
"Y"
] | 7067898d4f26ce7534e968b8486c4aa8fe3a511a | https://github.com/cuihantao/andes/blob/7067898d4f26ce7534e968b8486c4aa8fe3a511a/andes/models/line.py#L131-L152 |
17,554 | cuihantao/andes | andes/models/line.py | Line.incidence | def incidence(self):
"""Build incidence matrix into self.C"""
self.C = \
spmatrix(self.u, range(self.n), self.a1, (self.n, self.nb), 'd') -\
spmatrix(self.u, range(self.n), self.a2, (self.n, self.nb), 'd') | python | def incidence(self):
self.C = \
spmatrix(self.u, range(self.n), self.a1, (self.n, self.nb), 'd') -\
spmatrix(self.u, range(self.n), self.a2, (self.n, self.nb), 'd') | [
"def",
"incidence",
"(",
"self",
")",
":",
"self",
".",
"C",
"=",
"spmatrix",
"(",
"self",
".",
"u",
",",
"range",
"(",
"self",
".",
"n",
")",
",",
"self",
".",
"a1",
",",
"(",
"self",
".",
"n",
",",
"self",
".",
"nb",
")",
",",
"'d'",
")",... | Build incidence matrix into self.C | [
"Build",
"incidence",
"matrix",
"into",
"self",
".",
"C"
] | 7067898d4f26ce7534e968b8486c4aa8fe3a511a | https://github.com/cuihantao/andes/blob/7067898d4f26ce7534e968b8486c4aa8fe3a511a/andes/models/line.py#L221-L225 |
17,555 | cuihantao/andes | andes/models/line.py | Line.connectivity | def connectivity(self, bus):
"""check connectivity of network using Goderya's algorithm"""
if not self.n:
return
n = self.nb
fr = self.a1
to = self.a2
os = [0] * self.n
# find islanded buses
diag = list(
matrix(
spmatrix(self.u, to, os, (n, 1), 'd') +
spmatrix(self.u, fr, os, (n, 1), 'd')))
nib = bus.n_islanded_buses = diag.count(0)
bus.islanded_buses = []
for idx in range(n):
if diag[idx] == 0:
bus.islanded_buses.append(idx)
# find islanded areas
temp = spmatrix(
list(self.u) * 4, fr + to + fr + to, to + fr + fr + to, (n, n),
'd')
cons = temp[0, :]
nelm = len(cons.J)
conn = spmatrix([], [], [], (1, n), 'd')
bus.island_sets = []
idx = islands = 0
enum = 0
while 1:
while 1:
cons = cons * temp
cons = sparse(cons) # remove zero values
new_nelm = len(cons.J)
if new_nelm == nelm:
break
nelm = new_nelm
if len(cons.J) == n: # all buses are interconnected
return
bus.island_sets.append(list(cons.J))
conn += cons
islands += 1
nconn = len(conn.J)
if nconn >= (n - nib):
bus.island_sets = [i for i in bus.island_sets if i != []]
break
for element in conn.J[idx:]:
if not diag[idx]:
enum += 1 # skip islanded buses
if element <= enum:
idx += 1
enum += 1
else:
break
cons = temp[enum, :] | python | def connectivity(self, bus):
if not self.n:
return
n = self.nb
fr = self.a1
to = self.a2
os = [0] * self.n
# find islanded buses
diag = list(
matrix(
spmatrix(self.u, to, os, (n, 1), 'd') +
spmatrix(self.u, fr, os, (n, 1), 'd')))
nib = bus.n_islanded_buses = diag.count(0)
bus.islanded_buses = []
for idx in range(n):
if diag[idx] == 0:
bus.islanded_buses.append(idx)
# find islanded areas
temp = spmatrix(
list(self.u) * 4, fr + to + fr + to, to + fr + fr + to, (n, n),
'd')
cons = temp[0, :]
nelm = len(cons.J)
conn = spmatrix([], [], [], (1, n), 'd')
bus.island_sets = []
idx = islands = 0
enum = 0
while 1:
while 1:
cons = cons * temp
cons = sparse(cons) # remove zero values
new_nelm = len(cons.J)
if new_nelm == nelm:
break
nelm = new_nelm
if len(cons.J) == n: # all buses are interconnected
return
bus.island_sets.append(list(cons.J))
conn += cons
islands += 1
nconn = len(conn.J)
if nconn >= (n - nib):
bus.island_sets = [i for i in bus.island_sets if i != []]
break
for element in conn.J[idx:]:
if not diag[idx]:
enum += 1 # skip islanded buses
if element <= enum:
idx += 1
enum += 1
else:
break
cons = temp[enum, :] | [
"def",
"connectivity",
"(",
"self",
",",
"bus",
")",
":",
"if",
"not",
"self",
".",
"n",
":",
"return",
"n",
"=",
"self",
".",
"nb",
"fr",
"=",
"self",
".",
"a1",
"to",
"=",
"self",
".",
"a2",
"os",
"=",
"[",
"0",
"]",
"*",
"self",
".",
"n"... | check connectivity of network using Goderya's algorithm | [
"check",
"connectivity",
"of",
"network",
"using",
"Goderya",
"s",
"algorithm"
] | 7067898d4f26ce7534e968b8486c4aa8fe3a511a | https://github.com/cuihantao/andes/blob/7067898d4f26ce7534e968b8486c4aa8fe3a511a/andes/models/line.py#L227-L285 |
17,556 | cuihantao/andes | andes/models/line.py | Line.build_gy | def build_gy(self, dae):
"""Build line Jacobian matrix"""
if not self.n:
idx = range(dae.m)
dae.set_jac(Gy, 1e-6, idx, idx)
return
Vn = polar(1.0, dae.y[self.a])
Vc = mul(dae.y[self.v], Vn)
Ic = self.Y * Vc
diagVn = spdiag(Vn)
diagVc = spdiag(Vc)
diagIc = spdiag(Ic)
dS = self.Y * diagVn
dS = diagVc * conj(dS)
dS += conj(diagIc) * diagVn
dR = diagIc
dR -= self.Y * diagVc
dR = diagVc.H.T * dR
self.gy_store = sparse([[dR.imag(), dR.real()], [dS.real(),
dS.imag()]])
return self.gy_store | python | def build_gy(self, dae):
if not self.n:
idx = range(dae.m)
dae.set_jac(Gy, 1e-6, idx, idx)
return
Vn = polar(1.0, dae.y[self.a])
Vc = mul(dae.y[self.v], Vn)
Ic = self.Y * Vc
diagVn = spdiag(Vn)
diagVc = spdiag(Vc)
diagIc = spdiag(Ic)
dS = self.Y * diagVn
dS = diagVc * conj(dS)
dS += conj(diagIc) * diagVn
dR = diagIc
dR -= self.Y * diagVc
dR = diagVc.H.T * dR
self.gy_store = sparse([[dR.imag(), dR.real()], [dS.real(),
dS.imag()]])
return self.gy_store | [
"def",
"build_gy",
"(",
"self",
",",
"dae",
")",
":",
"if",
"not",
"self",
".",
"n",
":",
"idx",
"=",
"range",
"(",
"dae",
".",
"m",
")",
"dae",
".",
"set_jac",
"(",
"Gy",
",",
"1e-6",
",",
"idx",
",",
"idx",
")",
"return",
"Vn",
"=",
"polar"... | Build line Jacobian matrix | [
"Build",
"line",
"Jacobian",
"matrix"
] | 7067898d4f26ce7534e968b8486c4aa8fe3a511a | https://github.com/cuihantao/andes/blob/7067898d4f26ce7534e968b8486c4aa8fe3a511a/andes/models/line.py#L313-L339 |
17,557 | cuihantao/andes | andes/models/line.py | Line.seriesflow | def seriesflow(self, dae):
"""
Compute the flow through the line after solving PF.
Compute terminal injections, line losses
"""
# Vm = dae.y[self.v]
# Va = dae.y[self.a]
# V1 = polar(Vm[self.a1], Va[self.a1])
# V2 = polar(Vm[self.a2], Va[self.a2])
I1 = mul(self.v1, div(self.y12 + self.y1, self.m2)) - \
mul(self.v2, div(self.y12, self.mconj))
I2 = mul(self.v2, self.y12 + self.y2) - \
mul(self.v2, div(self.y12, self.m))
self.I1_real = I1.real()
self.I1_imag = I1.imag()
self.I2_real = I2.real()
self.I2_imag = I2.imag()
self.S1 = mul(self.v1, conj(I1))
self.S2 = mul(self.v2, conj(I2))
self.P1 = self.S1.real()
self.P2 = self.S2.real()
self.Q1 = self.S1.imag()
self.Q2 = self.S2.imag()
self.chg1 = mul(self.g1 + 1j * self.b1, div(self.v1**2, self.m2))
self.chg2 = mul(self.g2 + 1j * self.b2, self.v2**2)
self.Pchg1 = self.chg1.real()
self.Pchg2 = self.chg2.real()
self.Qchg1 = self.chg1.imag()
self.Qchg2 = self.chg2.imag()
self._line_flows = matrix([self.P1, self.P2, self.Q1, self.Q2,
self.I1_real, self.I1_imag,
self.I2_real, self.I2_imag]) | python | def seriesflow(self, dae):
# Vm = dae.y[self.v]
# Va = dae.y[self.a]
# V1 = polar(Vm[self.a1], Va[self.a1])
# V2 = polar(Vm[self.a2], Va[self.a2])
I1 = mul(self.v1, div(self.y12 + self.y1, self.m2)) - \
mul(self.v2, div(self.y12, self.mconj))
I2 = mul(self.v2, self.y12 + self.y2) - \
mul(self.v2, div(self.y12, self.m))
self.I1_real = I1.real()
self.I1_imag = I1.imag()
self.I2_real = I2.real()
self.I2_imag = I2.imag()
self.S1 = mul(self.v1, conj(I1))
self.S2 = mul(self.v2, conj(I2))
self.P1 = self.S1.real()
self.P2 = self.S2.real()
self.Q1 = self.S1.imag()
self.Q2 = self.S2.imag()
self.chg1 = mul(self.g1 + 1j * self.b1, div(self.v1**2, self.m2))
self.chg2 = mul(self.g2 + 1j * self.b2, self.v2**2)
self.Pchg1 = self.chg1.real()
self.Pchg2 = self.chg2.real()
self.Qchg1 = self.chg1.imag()
self.Qchg2 = self.chg2.imag()
self._line_flows = matrix([self.P1, self.P2, self.Q1, self.Q2,
self.I1_real, self.I1_imag,
self.I2_real, self.I2_imag]) | [
"def",
"seriesflow",
"(",
"self",
",",
"dae",
")",
":",
"# Vm = dae.y[self.v]",
"# Va = dae.y[self.a]",
"# V1 = polar(Vm[self.a1], Va[self.a1])",
"# V2 = polar(Vm[self.a2], Va[self.a2])",
"I1",
"=",
"mul",
"(",
"self",
".",
"v1",
",",
"div",
"(",
"self",
".",
"y12",
... | Compute the flow through the line after solving PF.
Compute terminal injections, line losses | [
"Compute",
"the",
"flow",
"through",
"the",
"line",
"after",
"solving",
"PF",
"."
] | 7067898d4f26ce7534e968b8486c4aa8fe3a511a | https://github.com/cuihantao/andes/blob/7067898d4f26ce7534e968b8486c4aa8fe3a511a/andes/models/line.py#L341-L382 |
17,558 | cuihantao/andes | andes/models/line.py | Line.switch | def switch(self, idx, u):
"""switch the status of Line idx"""
self.u[self.uid[idx]] = u
self.rebuild = True
self.system.dae.factorize = True
logger.debug('<Line> Status switch to {} on idx {}.'.format(u, idx)) | python | def switch(self, idx, u):
self.u[self.uid[idx]] = u
self.rebuild = True
self.system.dae.factorize = True
logger.debug('<Line> Status switch to {} on idx {}.'.format(u, idx)) | [
"def",
"switch",
"(",
"self",
",",
"idx",
",",
"u",
")",
":",
"self",
".",
"u",
"[",
"self",
".",
"uid",
"[",
"idx",
"]",
"]",
"=",
"u",
"self",
".",
"rebuild",
"=",
"True",
"self",
".",
"system",
".",
"dae",
".",
"factorize",
"=",
"True",
"l... | switch the status of Line idx | [
"switch",
"the",
"status",
"of",
"Line",
"idx"
] | 7067898d4f26ce7534e968b8486c4aa8fe3a511a | https://github.com/cuihantao/andes/blob/7067898d4f26ce7534e968b8486c4aa8fe3a511a/andes/models/line.py#L398-L403 |
17,559 | cuihantao/andes | andes/models/line.py | Line.get_flow_by_idx | def get_flow_by_idx(self, idx, bus):
"""Return seriesflow based on the external idx on the `bus` side"""
P, Q = [], []
if type(idx) is not list:
idx = [idx]
if type(bus) is not list:
bus = [bus]
for line_idx, bus_idx in zip(idx, bus):
line_int = self.uid[line_idx]
if bus_idx == self.bus1[line_int]:
P.append(self.P1[line_int])
Q.append(self.Q1[line_int])
elif bus_idx == self.bus2[line_int]:
P.append(self.P2[line_int])
Q.append(self.Q2[line_int])
return matrix(P), matrix(Q) | python | def get_flow_by_idx(self, idx, bus):
P, Q = [], []
if type(idx) is not list:
idx = [idx]
if type(bus) is not list:
bus = [bus]
for line_idx, bus_idx in zip(idx, bus):
line_int = self.uid[line_idx]
if bus_idx == self.bus1[line_int]:
P.append(self.P1[line_int])
Q.append(self.Q1[line_int])
elif bus_idx == self.bus2[line_int]:
P.append(self.P2[line_int])
Q.append(self.Q2[line_int])
return matrix(P), matrix(Q) | [
"def",
"get_flow_by_idx",
"(",
"self",
",",
"idx",
",",
"bus",
")",
":",
"P",
",",
"Q",
"=",
"[",
"]",
",",
"[",
"]",
"if",
"type",
"(",
"idx",
")",
"is",
"not",
"list",
":",
"idx",
"=",
"[",
"idx",
"]",
"if",
"type",
"(",
"bus",
")",
"is",... | Return seriesflow based on the external idx on the `bus` side | [
"Return",
"seriesflow",
"based",
"on",
"the",
"external",
"idx",
"on",
"the",
"bus",
"side"
] | 7067898d4f26ce7534e968b8486c4aa8fe3a511a | https://github.com/cuihantao/andes/blob/7067898d4f26ce7534e968b8486c4aa8fe3a511a/andes/models/line.py#L521-L537 |
17,560 | cuihantao/andes | andes/models/line.py | Line.leaf_bus | def leaf_bus(self, df=False):
"""
Return leaf bus idx, line idx, and the line foreign key
Returns
-------
(list, list, list) or DataFrame
"""
# leafs - leaf bus idx
# lines - line idx
# fkey - the foreign key of Line, in 'bus1' or 'bus2', linking the bus
leafs, lines, fkeys = list(), list(), list()
# convert to unique, ordered list
buses = sorted(list(set(self.bus1 + self.bus2)))
links = self.link_bus(buses)
for bus, link in zip(buses, links):
line = link[0]
fkey = link[1]
if line is None:
continue
if len(line) == 1:
leafs.append(bus)
lines.extend(line)
fkeys.extend(fkey)
# output formatting
if df is False:
return leafs, lines, fkeys
else:
_data = {'Bus idx': leafs, 'Line idx': lines, 'fkey': fkeys}
if globals()['pd'] is None:
globals()['pd'] = importlib.import_module('pandas')
return pd.DataFrame(data=_data) | python | def leaf_bus(self, df=False):
# leafs - leaf bus idx
# lines - line idx
# fkey - the foreign key of Line, in 'bus1' or 'bus2', linking the bus
leafs, lines, fkeys = list(), list(), list()
# convert to unique, ordered list
buses = sorted(list(set(self.bus1 + self.bus2)))
links = self.link_bus(buses)
for bus, link in zip(buses, links):
line = link[0]
fkey = link[1]
if line is None:
continue
if len(line) == 1:
leafs.append(bus)
lines.extend(line)
fkeys.extend(fkey)
# output formatting
if df is False:
return leafs, lines, fkeys
else:
_data = {'Bus idx': leafs, 'Line idx': lines, 'fkey': fkeys}
if globals()['pd'] is None:
globals()['pd'] = importlib.import_module('pandas')
return pd.DataFrame(data=_data) | [
"def",
"leaf_bus",
"(",
"self",
",",
"df",
"=",
"False",
")",
":",
"# leafs - leaf bus idx",
"# lines - line idx",
"# fkey - the foreign key of Line, in 'bus1' or 'bus2', linking the bus",
"leafs",
",",
"lines",
",",
"fkeys",
"=",
"list",
"(",
")",
",",
"list",
"(",
... | Return leaf bus idx, line idx, and the line foreign key
Returns
-------
(list, list, list) or DataFrame | [
"Return",
"leaf",
"bus",
"idx",
"line",
"idx",
"and",
"the",
"line",
"foreign",
"key"
] | 7067898d4f26ce7534e968b8486c4aa8fe3a511a | https://github.com/cuihantao/andes/blob/7067898d4f26ce7534e968b8486c4aa8fe3a511a/andes/models/line.py#L539-L576 |
17,561 | Legobot/Legobot | Legobot/Utilities.py | Utilities.truncate | def truncate(text, length=255):
"""
Splits the message into a list of strings of of length `length`
Args:
text (str): The text to be divided
length (int, optional): The length of the chunks of text. \
Defaults to 255.
Returns:
list: Text divided into chunks of length `length`
"""
lines = []
i = 0
while i < len(text) - 1:
try:
lines.append(text[i:i+length])
i += length
except IndexError as e:
lines.append(text[i:])
return lines | python | def truncate(text, length=255):
lines = []
i = 0
while i < len(text) - 1:
try:
lines.append(text[i:i+length])
i += length
except IndexError as e:
lines.append(text[i:])
return lines | [
"def",
"truncate",
"(",
"text",
",",
"length",
"=",
"255",
")",
":",
"lines",
"=",
"[",
"]",
"i",
"=",
"0",
"while",
"i",
"<",
"len",
"(",
"text",
")",
"-",
"1",
":",
"try",
":",
"lines",
".",
"append",
"(",
"text",
"[",
"i",
":",
"i",
"+",... | Splits the message into a list of strings of of length `length`
Args:
text (str): The text to be divided
length (int, optional): The length of the chunks of text. \
Defaults to 255.
Returns:
list: Text divided into chunks of length `length` | [
"Splits",
"the",
"message",
"into",
"a",
"list",
"of",
"strings",
"of",
"of",
"length",
"length"
] | d13da172960a149681cb5151ce34b2f3a58ad32b | https://github.com/Legobot/Legobot/blob/d13da172960a149681cb5151ce34b2f3a58ad32b/Legobot/Utilities.py#L24-L46 |
17,562 | cuihantao/andes | andes/variables/varname.py | VarName.resize_for_flows | def resize_for_flows(self):
"""Extend `unamey` and `fnamey` for bus injections and line flows"""
if self.system.config.dime_enable:
self.system.tds.config.compute_flows = True
if self.system.tds.config.compute_flows:
nflows = 2 * self.system.Bus.n + \
8 * self.system.Line.n + \
2 * self.system.Area.n_combination
self.unamey.extend([''] * nflows)
self.fnamey.extend([''] * nflows) | python | def resize_for_flows(self):
if self.system.config.dime_enable:
self.system.tds.config.compute_flows = True
if self.system.tds.config.compute_flows:
nflows = 2 * self.system.Bus.n + \
8 * self.system.Line.n + \
2 * self.system.Area.n_combination
self.unamey.extend([''] * nflows)
self.fnamey.extend([''] * nflows) | [
"def",
"resize_for_flows",
"(",
"self",
")",
":",
"if",
"self",
".",
"system",
".",
"config",
".",
"dime_enable",
":",
"self",
".",
"system",
".",
"tds",
".",
"config",
".",
"compute_flows",
"=",
"True",
"if",
"self",
".",
"system",
".",
"tds",
".",
... | Extend `unamey` and `fnamey` for bus injections and line flows | [
"Extend",
"unamey",
"and",
"fnamey",
"for",
"bus",
"injections",
"and",
"line",
"flows"
] | 7067898d4f26ce7534e968b8486c4aa8fe3a511a | https://github.com/cuihantao/andes/blob/7067898d4f26ce7534e968b8486c4aa8fe3a511a/andes/variables/varname.py#L27-L37 |
17,563 | cuihantao/andes | andes/variables/varname.py | VarName.append | def append(self, listname, xy_idx, var_name, element_name):
"""Append variable names to the name lists"""
self.resize()
string = '{0} {1}'
if listname not in ['unamex', 'unamey', 'fnamex', 'fnamey']:
logger.error('Wrong list name for varname.')
return
elif listname in ['fnamex', 'fnamey']:
string = '${0}\\ {1}$'
if isinstance(element_name, list):
for i, j in zip(xy_idx, element_name):
# manual elem_add LaTex space for auto-generated element name
if listname == 'fnamex' or listname == 'fnamey':
j = j.replace(' ', '\\ ')
self.__dict__[listname][i] = string.format(var_name, j)
elif isinstance(element_name, int):
self.__dict__[listname][xy_idx] = string.format(
var_name, element_name)
else:
logger.warning(
'Unknown element_name type while building varname') | python | def append(self, listname, xy_idx, var_name, element_name):
self.resize()
string = '{0} {1}'
if listname not in ['unamex', 'unamey', 'fnamex', 'fnamey']:
logger.error('Wrong list name for varname.')
return
elif listname in ['fnamex', 'fnamey']:
string = '${0}\\ {1}$'
if isinstance(element_name, list):
for i, j in zip(xy_idx, element_name):
# manual elem_add LaTex space for auto-generated element name
if listname == 'fnamex' or listname == 'fnamey':
j = j.replace(' ', '\\ ')
self.__dict__[listname][i] = string.format(var_name, j)
elif isinstance(element_name, int):
self.__dict__[listname][xy_idx] = string.format(
var_name, element_name)
else:
logger.warning(
'Unknown element_name type while building varname') | [
"def",
"append",
"(",
"self",
",",
"listname",
",",
"xy_idx",
",",
"var_name",
",",
"element_name",
")",
":",
"self",
".",
"resize",
"(",
")",
"string",
"=",
"'{0} {1}'",
"if",
"listname",
"not",
"in",
"[",
"'unamex'",
",",
"'unamey'",
",",
"'fnamex'",
... | Append variable names to the name lists | [
"Append",
"variable",
"names",
"to",
"the",
"name",
"lists"
] | 7067898d4f26ce7534e968b8486c4aa8fe3a511a | https://github.com/cuihantao/andes/blob/7067898d4f26ce7534e968b8486c4aa8fe3a511a/andes/variables/varname.py#L39-L60 |
17,564 | cuihantao/andes | andes/variables/varname.py | VarName.bus_line_names | def bus_line_names(self):
"""Append bus injection and line flow names to `varname`"""
if self.system.tds.config.compute_flows:
self.system.Bus._varname_inj()
self.system.Line._varname_flow()
self.system.Area._varname_inter() | python | def bus_line_names(self):
if self.system.tds.config.compute_flows:
self.system.Bus._varname_inj()
self.system.Line._varname_flow()
self.system.Area._varname_inter() | [
"def",
"bus_line_names",
"(",
"self",
")",
":",
"if",
"self",
".",
"system",
".",
"tds",
".",
"config",
".",
"compute_flows",
":",
"self",
".",
"system",
".",
"Bus",
".",
"_varname_inj",
"(",
")",
"self",
".",
"system",
".",
"Line",
".",
"_varname_flow... | Append bus injection and line flow names to `varname` | [
"Append",
"bus",
"injection",
"and",
"line",
"flow",
"names",
"to",
"varname"
] | 7067898d4f26ce7534e968b8486c4aa8fe3a511a | https://github.com/cuihantao/andes/blob/7067898d4f26ce7534e968b8486c4aa8fe3a511a/andes/variables/varname.py#L62-L67 |
17,565 | cuihantao/andes | andes/variables/varname.py | VarName.get_xy_name | def get_xy_name(self, yidx, xidx=0):
"""
Return variable names for the given indices
:param yidx:
:param xidx:
:return:
"""
assert isinstance(xidx, int)
if isinstance(yidx, int):
yidx = [yidx]
uname = ['Time [s]'] + self.uname
fname = ['$Time\\ [s]$'] + self.fname
xname = [list(), list()]
yname = [list(), list()]
xname[0] = uname[xidx]
xname[1] = fname[xidx]
yname[0] = [uname[i] for i in yidx]
yname[1] = [fname[i] for i in yidx]
return xname, yname | python | def get_xy_name(self, yidx, xidx=0):
assert isinstance(xidx, int)
if isinstance(yidx, int):
yidx = [yidx]
uname = ['Time [s]'] + self.uname
fname = ['$Time\\ [s]$'] + self.fname
xname = [list(), list()]
yname = [list(), list()]
xname[0] = uname[xidx]
xname[1] = fname[xidx]
yname[0] = [uname[i] for i in yidx]
yname[1] = [fname[i] for i in yidx]
return xname, yname | [
"def",
"get_xy_name",
"(",
"self",
",",
"yidx",
",",
"xidx",
"=",
"0",
")",
":",
"assert",
"isinstance",
"(",
"xidx",
",",
"int",
")",
"if",
"isinstance",
"(",
"yidx",
",",
"int",
")",
":",
"yidx",
"=",
"[",
"yidx",
"]",
"uname",
"=",
"[",
"'Time... | Return variable names for the given indices
:param yidx:
:param xidx:
:return: | [
"Return",
"variable",
"names",
"for",
"the",
"given",
"indices"
] | 7067898d4f26ce7534e968b8486c4aa8fe3a511a | https://github.com/cuihantao/andes/blob/7067898d4f26ce7534e968b8486c4aa8fe3a511a/andes/variables/varname.py#L89-L113 |
17,566 | cuihantao/andes | andes/plot.py | cli_parse | def cli_parse():
"""command line input parser"""
parser = ArgumentParser(prog='andesplot')
parser.add_argument('datfile', nargs=1, default=[], help='dat file name.')
parser.add_argument('x', nargs=1, type=int, help='x axis variable index')
parser.add_argument('y', nargs='*', help='y axis variable index')
parser.add_argument('--xmax', type=float, help='x axis maximum value')
parser.add_argument('--ymax', type=float, help='y axis maximum value')
parser.add_argument('--ymin', type=float, help='y axis minimum value')
parser.add_argument('--xmin', type=float, help='x axis minimum value')
parser.add_argument(
'--checkinit', action='store_true', help='check initialization value')
parser.add_argument(
'-x', '--xlabel', type=str, help='manual set x-axis text label')
parser.add_argument('-y', '--ylabel', type=str, help='y-axis text label')
parser.add_argument(
'-s', '--save', action='store_true', help='save to file')
parser.add_argument('-g', '--grid', action='store_true', help='grid on')
parser.add_argument(
'-d',
'--no_latex',
action='store_true',
help='disable LaTex formatting')
parser.add_argument(
'-u',
'--unattended',
action='store_true',
help='do not show the plot window')
parser.add_argument('--ytimes', type=str, help='y times')
parser.add_argument(
'--dpi', type=int, help='image resolution in dot per inch (DPI)')
args = parser.parse_args()
return vars(args) | python | def cli_parse():
parser = ArgumentParser(prog='andesplot')
parser.add_argument('datfile', nargs=1, default=[], help='dat file name.')
parser.add_argument('x', nargs=1, type=int, help='x axis variable index')
parser.add_argument('y', nargs='*', help='y axis variable index')
parser.add_argument('--xmax', type=float, help='x axis maximum value')
parser.add_argument('--ymax', type=float, help='y axis maximum value')
parser.add_argument('--ymin', type=float, help='y axis minimum value')
parser.add_argument('--xmin', type=float, help='x axis minimum value')
parser.add_argument(
'--checkinit', action='store_true', help='check initialization value')
parser.add_argument(
'-x', '--xlabel', type=str, help='manual set x-axis text label')
parser.add_argument('-y', '--ylabel', type=str, help='y-axis text label')
parser.add_argument(
'-s', '--save', action='store_true', help='save to file')
parser.add_argument('-g', '--grid', action='store_true', help='grid on')
parser.add_argument(
'-d',
'--no_latex',
action='store_true',
help='disable LaTex formatting')
parser.add_argument(
'-u',
'--unattended',
action='store_true',
help='do not show the plot window')
parser.add_argument('--ytimes', type=str, help='y times')
parser.add_argument(
'--dpi', type=int, help='image resolution in dot per inch (DPI)')
args = parser.parse_args()
return vars(args) | [
"def",
"cli_parse",
"(",
")",
":",
"parser",
"=",
"ArgumentParser",
"(",
"prog",
"=",
"'andesplot'",
")",
"parser",
".",
"add_argument",
"(",
"'datfile'",
",",
"nargs",
"=",
"1",
",",
"default",
"=",
"[",
"]",
",",
"help",
"=",
"'dat file name.'",
")",
... | command line input parser | [
"command",
"line",
"input",
"parser"
] | 7067898d4f26ce7534e968b8486c4aa8fe3a511a | https://github.com/cuihantao/andes/blob/7067898d4f26ce7534e968b8486c4aa8fe3a511a/andes/plot.py#L209-L241 |
17,567 | cuihantao/andes | andes/plot.py | add_plot | def add_plot(x, y, xl, yl, fig, ax, LATEX=False, linestyle=None, **kwargs):
"""Add plots to an existing plot"""
if LATEX:
xl_data = xl[1] # NOQA
yl_data = yl[1]
else:
xl_data = xl[0] # NOQA
yl_data = yl[0]
for idx in range(len(y)):
ax.plot(x, y[idx], label=yl_data[idx], linestyle=linestyle)
ax.legend(loc='upper right')
ax.set_ylim(auto=True) | python | def add_plot(x, y, xl, yl, fig, ax, LATEX=False, linestyle=None, **kwargs):
if LATEX:
xl_data = xl[1] # NOQA
yl_data = yl[1]
else:
xl_data = xl[0] # NOQA
yl_data = yl[0]
for idx in range(len(y)):
ax.plot(x, y[idx], label=yl_data[idx], linestyle=linestyle)
ax.legend(loc='upper right')
ax.set_ylim(auto=True) | [
"def",
"add_plot",
"(",
"x",
",",
"y",
",",
"xl",
",",
"yl",
",",
"fig",
",",
"ax",
",",
"LATEX",
"=",
"False",
",",
"linestyle",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"LATEX",
":",
"xl_data",
"=",
"xl",
"[",
"1",
"]",
"# NOQA... | Add plots to an existing plot | [
"Add",
"plots",
"to",
"an",
"existing",
"plot"
] | 7067898d4f26ce7534e968b8486c4aa8fe3a511a | https://github.com/cuihantao/andes/blob/7067898d4f26ce7534e968b8486c4aa8fe3a511a/andes/plot.py#L481-L494 |
17,568 | cuihantao/andes | andes/plot.py | check_init | def check_init(yval, yl):
""""Check initialization by comparing t=0 and t=end values"""
suspect = []
for var, label in zip(yval, yl):
if abs(var[0] - var[-1]) >= 1e-6:
suspect.append(label)
if suspect:
print('Initialization failure:')
print(', '.join(suspect))
else:
print('Initialization is correct.') | python | def check_init(yval, yl):
"suspect = []
for var, label in zip(yval, yl):
if abs(var[0] - var[-1]) >= 1e-6:
suspect.append(label)
if suspect:
print('Initialization failure:')
print(', '.join(suspect))
else:
print('Initialization is correct.') | [
"def",
"check_init",
"(",
"yval",
",",
"yl",
")",
":",
"suspect",
"=",
"[",
"]",
"for",
"var",
",",
"label",
"in",
"zip",
"(",
"yval",
",",
"yl",
")",
":",
"if",
"abs",
"(",
"var",
"[",
"0",
"]",
"-",
"var",
"[",
"-",
"1",
"]",
")",
">=",
... | Check initialization by comparing t=0 and t=end values | [
"Check",
"initialization",
"by",
"comparing",
"t",
"=",
"0",
"and",
"t",
"=",
"end",
"values"
] | 7067898d4f26ce7534e968b8486c4aa8fe3a511a | https://github.com/cuihantao/andes/blob/7067898d4f26ce7534e968b8486c4aa8fe3a511a/andes/plot.py#L577-L587 |
17,569 | cuihantao/andes | andes/plot.py | TDSData.load_lst | def load_lst(self):
"""
Load the lst file into internal data structures
"""
with open(self._lst_file, 'r') as fd:
lines = fd.readlines()
idx, uname, fname = list(), list(), list()
for line in lines:
values = line.split(',')
values = [x.strip() for x in values]
# preserve the idx ordering here in case variables are not
# ordered by idx
idx.append(int(values[0])) # convert to integer
uname.append(values[1])
fname.append(values[2])
self._idx = idx
self._fname = fname
self._uname = uname | python | def load_lst(self):
with open(self._lst_file, 'r') as fd:
lines = fd.readlines()
idx, uname, fname = list(), list(), list()
for line in lines:
values = line.split(',')
values = [x.strip() for x in values]
# preserve the idx ordering here in case variables are not
# ordered by idx
idx.append(int(values[0])) # convert to integer
uname.append(values[1])
fname.append(values[2])
self._idx = idx
self._fname = fname
self._uname = uname | [
"def",
"load_lst",
"(",
"self",
")",
":",
"with",
"open",
"(",
"self",
".",
"_lst_file",
",",
"'r'",
")",
"as",
"fd",
":",
"lines",
"=",
"fd",
".",
"readlines",
"(",
")",
"idx",
",",
"uname",
",",
"fname",
"=",
"list",
"(",
")",
",",
"list",
"(... | Load the lst file into internal data structures | [
"Load",
"the",
"lst",
"file",
"into",
"internal",
"data",
"structures"
] | 7067898d4f26ce7534e968b8486c4aa8fe3a511a | https://github.com/cuihantao/andes/blob/7067898d4f26ce7534e968b8486c4aa8fe3a511a/andes/plot.py#L73-L95 |
17,570 | cuihantao/andes | andes/plot.py | TDSData.find_var | def find_var(self, query, formatted=False):
"""
Return variable names and indices matching ``query``
"""
# load the variable list to search in
names = self._uname if formatted is False else self._fname
found_idx, found_names = list(), list()
for idx, name in zip(self._idx, names):
if re.search(query, name):
found_idx.append(idx)
found_names.append(name)
return found_idx, found_names | python | def find_var(self, query, formatted=False):
# load the variable list to search in
names = self._uname if formatted is False else self._fname
found_idx, found_names = list(), list()
for idx, name in zip(self._idx, names):
if re.search(query, name):
found_idx.append(idx)
found_names.append(name)
return found_idx, found_names | [
"def",
"find_var",
"(",
"self",
",",
"query",
",",
"formatted",
"=",
"False",
")",
":",
"# load the variable list to search in",
"names",
"=",
"self",
".",
"_uname",
"if",
"formatted",
"is",
"False",
"else",
"self",
".",
"_fname",
"found_idx",
",",
"found_name... | Return variable names and indices matching ``query`` | [
"Return",
"variable",
"names",
"and",
"indices",
"matching",
"query"
] | 7067898d4f26ce7534e968b8486c4aa8fe3a511a | https://github.com/cuihantao/andes/blob/7067898d4f26ce7534e968b8486c4aa8fe3a511a/andes/plot.py#L97-L112 |
17,571 | cuihantao/andes | andes/plot.py | TDSData.load_dat | def load_dat(self, delimiter=','):
"""
Load the dat file into internal data structures, ``self._data``
"""
try:
data = np.loadtxt(self._dat_file, delimiter=',')
except ValueError:
data = np.loadtxt(self._dat_file)
self._data = data | python | def load_dat(self, delimiter=','):
try:
data = np.loadtxt(self._dat_file, delimiter=',')
except ValueError:
data = np.loadtxt(self._dat_file)
self._data = data | [
"def",
"load_dat",
"(",
"self",
",",
"delimiter",
"=",
"','",
")",
":",
"try",
":",
"data",
"=",
"np",
".",
"loadtxt",
"(",
"self",
".",
"_dat_file",
",",
"delimiter",
"=",
"','",
")",
"except",
"ValueError",
":",
"data",
"=",
"np",
".",
"loadtxt",
... | Load the dat file into internal data structures, ``self._data`` | [
"Load",
"the",
"dat",
"file",
"into",
"internal",
"data",
"structures",
"self",
".",
"_data"
] | 7067898d4f26ce7534e968b8486c4aa8fe3a511a | https://github.com/cuihantao/andes/blob/7067898d4f26ce7534e968b8486c4aa8fe3a511a/andes/plot.py#L114-L123 |
17,572 | cuihantao/andes | andes/plot.py | TDSData.get_values | def get_values(self, idx):
"""
Return the variable values at the given indices
"""
if isinstance(idx, list):
idx = np.array(idx, dtype=int)
return self._data[:, idx] | python | def get_values(self, idx):
if isinstance(idx, list):
idx = np.array(idx, dtype=int)
return self._data[:, idx] | [
"def",
"get_values",
"(",
"self",
",",
"idx",
")",
":",
"if",
"isinstance",
"(",
"idx",
",",
"list",
")",
":",
"idx",
"=",
"np",
".",
"array",
"(",
"idx",
",",
"dtype",
"=",
"int",
")",
"return",
"self",
".",
"_data",
"[",
":",
",",
"idx",
"]"
... | Return the variable values at the given indices | [
"Return",
"the",
"variable",
"values",
"at",
"the",
"given",
"indices"
] | 7067898d4f26ce7534e968b8486c4aa8fe3a511a | https://github.com/cuihantao/andes/blob/7067898d4f26ce7534e968b8486c4aa8fe3a511a/andes/plot.py#L125-L132 |
17,573 | cuihantao/andes | andes/plot.py | TDSData.get_header | def get_header(self, idx, formatted=False):
"""
Return a list of the variable names at the given indices
"""
header = self._uname if not formatted else self._fname
return [header[x] for x in idx] | python | def get_header(self, idx, formatted=False):
header = self._uname if not formatted else self._fname
return [header[x] for x in idx] | [
"def",
"get_header",
"(",
"self",
",",
"idx",
",",
"formatted",
"=",
"False",
")",
":",
"header",
"=",
"self",
".",
"_uname",
"if",
"not",
"formatted",
"else",
"self",
".",
"_fname",
"return",
"[",
"header",
"[",
"x",
"]",
"for",
"x",
"in",
"idx",
... | Return a list of the variable names at the given indices | [
"Return",
"a",
"list",
"of",
"the",
"variable",
"names",
"at",
"the",
"given",
"indices"
] | 7067898d4f26ce7534e968b8486c4aa8fe3a511a | https://github.com/cuihantao/andes/blob/7067898d4f26ce7534e968b8486c4aa8fe3a511a/andes/plot.py#L134-L139 |
17,574 | cuihantao/andes | andes/plot.py | TDSData.export_csv | def export_csv(self, path, idx=None, header=None, formatted=False,
sort_idx=True, fmt='%.18e'):
"""
Export to a csv file
Parameters
----------
path : str
path of the csv file to save
idx : None or array-like, optional
the indices of the variables to export. Export all by default
header : None or array-like, optional
customized header if not `None`. Use the names from the lst file
by default
formatted : bool, optional
Use LaTeX-formatted header. Does not apply when using customized
header
sort_idx : bool, optional
Sort by idx or not, # TODO: implement sort
fmt : str
cell formatter
"""
if not idx:
idx = self._idx
if not header:
header = self.get_header(idx, formatted=formatted)
assert len(idx) == len(header), \
"Idx length does not match header length"
body = self.get_values(idx)
with open(path, 'w') as fd:
fd.write(','.join(header) + '\n')
np.savetxt(fd, body, fmt=fmt, delimiter=',') | python | def export_csv(self, path, idx=None, header=None, formatted=False,
sort_idx=True, fmt='%.18e'):
if not idx:
idx = self._idx
if not header:
header = self.get_header(idx, formatted=formatted)
assert len(idx) == len(header), \
"Idx length does not match header length"
body = self.get_values(idx)
with open(path, 'w') as fd:
fd.write(','.join(header) + '\n')
np.savetxt(fd, body, fmt=fmt, delimiter=',') | [
"def",
"export_csv",
"(",
"self",
",",
"path",
",",
"idx",
"=",
"None",
",",
"header",
"=",
"None",
",",
"formatted",
"=",
"False",
",",
"sort_idx",
"=",
"True",
",",
"fmt",
"=",
"'%.18e'",
")",
":",
"if",
"not",
"idx",
":",
"idx",
"=",
"self",
"... | Export to a csv file
Parameters
----------
path : str
path of the csv file to save
idx : None or array-like, optional
the indices of the variables to export. Export all by default
header : None or array-like, optional
customized header if not `None`. Use the names from the lst file
by default
formatted : bool, optional
Use LaTeX-formatted header. Does not apply when using customized
header
sort_idx : bool, optional
Sort by idx or not, # TODO: implement sort
fmt : str
cell formatter | [
"Export",
"to",
"a",
"csv",
"file"
] | 7067898d4f26ce7534e968b8486c4aa8fe3a511a | https://github.com/cuihantao/andes/blob/7067898d4f26ce7534e968b8486c4aa8fe3a511a/andes/plot.py#L141-L175 |
17,575 | cuihantao/andes | andes/utils/tab.py | Tab.auto_style | def auto_style(self):
"""
automatic styling according to _row_size
76 characters in a row
"""
if self._row_size is None:
return
elif self._row_size == 3:
self.set_cols_align(['l', 'l', 'l'])
self.set_cols_valign(['t', 't', 't'])
self.set_cols_width([12, 54, 12])
elif self._row_size == 4:
self.set_cols_align(['l', 'l', 'l', 'l'])
self.set_cols_valign(['t', 't', 't', 't'])
self.set_cols_width([10, 40, 10, 10]) | python | def auto_style(self):
if self._row_size is None:
return
elif self._row_size == 3:
self.set_cols_align(['l', 'l', 'l'])
self.set_cols_valign(['t', 't', 't'])
self.set_cols_width([12, 54, 12])
elif self._row_size == 4:
self.set_cols_align(['l', 'l', 'l', 'l'])
self.set_cols_valign(['t', 't', 't', 't'])
self.set_cols_width([10, 40, 10, 10]) | [
"def",
"auto_style",
"(",
"self",
")",
":",
"if",
"self",
".",
"_row_size",
"is",
"None",
":",
"return",
"elif",
"self",
".",
"_row_size",
"==",
"3",
":",
"self",
".",
"set_cols_align",
"(",
"[",
"'l'",
",",
"'l'",
",",
"'l'",
"]",
")",
"self",
"."... | automatic styling according to _row_size
76 characters in a row | [
"automatic",
"styling",
"according",
"to",
"_row_size",
"76",
"characters",
"in",
"a",
"row"
] | 7067898d4f26ce7534e968b8486c4aa8fe3a511a | https://github.com/cuihantao/andes/blob/7067898d4f26ce7534e968b8486c4aa8fe3a511a/andes/utils/tab.py#L45-L59 |
17,576 | cuihantao/andes | andes/utils/tab.py | Tab.draw | def draw(self):
"""generate texttable formatted string"""
self.guess_header()
self.add_left_space(
)
# for Texttable, elem_add a column of whitespace on the left for
# better visual effect
if self._title and self._descr:
pre = self._title + '\n' + self._descr + '\n\n'
elif self._title:
pre = self._title + '\n\n'
elif self._descr:
pre = 'Empty Title' + '\n' + self._descr + '\n'
else:
pre = ''
empty_line = '\n\n'
return pre + str(Texttable.draw(self)) + empty_line | python | def draw(self):
self.guess_header()
self.add_left_space(
)
# for Texttable, elem_add a column of whitespace on the left for
# better visual effect
if self._title and self._descr:
pre = self._title + '\n' + self._descr + '\n\n'
elif self._title:
pre = self._title + '\n\n'
elif self._descr:
pre = 'Empty Title' + '\n' + self._descr + '\n'
else:
pre = ''
empty_line = '\n\n'
return pre + str(Texttable.draw(self)) + empty_line | [
"def",
"draw",
"(",
"self",
")",
":",
"self",
".",
"guess_header",
"(",
")",
"self",
".",
"add_left_space",
"(",
")",
"# for Texttable, elem_add a column of whitespace on the left for",
"# better visual effect",
"if",
"self",
".",
"_title",
"and",
"self",
".",
"_des... | generate texttable formatted string | [
"generate",
"texttable",
"formatted",
"string"
] | 7067898d4f26ce7534e968b8486c4aa8fe3a511a | https://github.com/cuihantao/andes/blob/7067898d4f26ce7534e968b8486c4aa8fe3a511a/andes/utils/tab.py#L72-L88 |
17,577 | cuihantao/andes | andes/utils/tab.py | simpletab.guess_width | def guess_width(self):
"""auto fit column width"""
if len(self.header) <= 4:
nspace = 6
elif len(self.header) <= 6:
nspace = 5
else:
nspace = 4
ncol = len(self.header)
self._width = [nspace] * ncol
width = [0] * ncol
# set initial width from header
for idx, item in enumerate(self.header):
width[idx] = len(str(item))
# guess width of each column from first 10 lines of data
samples = min(len(self.data), 10)
for col in range(ncol):
for idx in range(samples):
data = self.data[idx][col]
if not isinstance(data, (float, int)):
temp = len(data)
else:
temp = 10
if temp > width[col]:
width[col] = temp
for col in range(ncol):
self._width[col] += width[col] | python | def guess_width(self):
if len(self.header) <= 4:
nspace = 6
elif len(self.header) <= 6:
nspace = 5
else:
nspace = 4
ncol = len(self.header)
self._width = [nspace] * ncol
width = [0] * ncol
# set initial width from header
for idx, item in enumerate(self.header):
width[idx] = len(str(item))
# guess width of each column from first 10 lines of data
samples = min(len(self.data), 10)
for col in range(ncol):
for idx in range(samples):
data = self.data[idx][col]
if not isinstance(data, (float, int)):
temp = len(data)
else:
temp = 10
if temp > width[col]:
width[col] = temp
for col in range(ncol):
self._width[col] += width[col] | [
"def",
"guess_width",
"(",
"self",
")",
":",
"if",
"len",
"(",
"self",
".",
"header",
")",
"<=",
"4",
":",
"nspace",
"=",
"6",
"elif",
"len",
"(",
"self",
".",
"header",
")",
"<=",
"6",
":",
"nspace",
"=",
"5",
"else",
":",
"nspace",
"=",
"4",
... | auto fit column width | [
"auto",
"fit",
"column",
"width"
] | 7067898d4f26ce7534e968b8486c4aa8fe3a511a | https://github.com/cuihantao/andes/blob/7067898d4f26ce7534e968b8486c4aa8fe3a511a/andes/utils/tab.py#L104-L133 |
17,578 | cuihantao/andes | andes/models/jit.py | JIT.jit_load | def jit_load(self):
"""
Import and instantiate this JIT object
Returns
-------
"""
try:
model = importlib.import_module('.' + self.model, 'andes.models')
device = getattr(model, self.device)
self.system.__dict__[self.name] = device(self.system, self.name)
g = self.system.__dict__[self.name]._group
self.system.group_add(g)
self.system.__dict__[g].register_model(self.name)
# register device after loading
self.system.devman.register_device(self.name)
self.loaded = 1
logger.debug('Imported model <{:s}.{:s}>.'.format(
self.model, self.device))
except ImportError:
logger.error(
'non-JIT model <{:s}.{:s}> import error'
.format(self.model, self.device))
except AttributeError:
logger.error(
'model <{:s}.{:s}> not exist. Check models/__init__.py'
.format(self.model, self.device)) | python | def jit_load(self):
try:
model = importlib.import_module('.' + self.model, 'andes.models')
device = getattr(model, self.device)
self.system.__dict__[self.name] = device(self.system, self.name)
g = self.system.__dict__[self.name]._group
self.system.group_add(g)
self.system.__dict__[g].register_model(self.name)
# register device after loading
self.system.devman.register_device(self.name)
self.loaded = 1
logger.debug('Imported model <{:s}.{:s}>.'.format(
self.model, self.device))
except ImportError:
logger.error(
'non-JIT model <{:s}.{:s}> import error'
.format(self.model, self.device))
except AttributeError:
logger.error(
'model <{:s}.{:s}> not exist. Check models/__init__.py'
.format(self.model, self.device)) | [
"def",
"jit_load",
"(",
"self",
")",
":",
"try",
":",
"model",
"=",
"importlib",
".",
"import_module",
"(",
"'.'",
"+",
"self",
".",
"model",
",",
"'andes.models'",
")",
"device",
"=",
"getattr",
"(",
"model",
",",
"self",
".",
"device",
")",
"self",
... | Import and instantiate this JIT object
Returns
------- | [
"Import",
"and",
"instantiate",
"this",
"JIT",
"object"
] | 7067898d4f26ce7534e968b8486c4aa8fe3a511a | https://github.com/cuihantao/andes/blob/7067898d4f26ce7534e968b8486c4aa8fe3a511a/andes/models/jit.py#L20-L49 |
17,579 | cuihantao/andes | andes/models/jit.py | JIT.elem_add | def elem_add(self, idx=None, name=None, **kwargs):
"""overloading elem_add function of a JIT class"""
self.jit_load()
if self.loaded:
return self.system.__dict__[self.name].elem_add(
idx, name, **kwargs) | python | def elem_add(self, idx=None, name=None, **kwargs):
self.jit_load()
if self.loaded:
return self.system.__dict__[self.name].elem_add(
idx, name, **kwargs) | [
"def",
"elem_add",
"(",
"self",
",",
"idx",
"=",
"None",
",",
"name",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"self",
".",
"jit_load",
"(",
")",
"if",
"self",
".",
"loaded",
":",
"return",
"self",
".",
"system",
".",
"__dict__",
"[",
"sel... | overloading elem_add function of a JIT class | [
"overloading",
"elem_add",
"function",
"of",
"a",
"JIT",
"class"
] | 7067898d4f26ce7534e968b8486c4aa8fe3a511a | https://github.com/cuihantao/andes/blob/7067898d4f26ce7534e968b8486c4aa8fe3a511a/andes/models/jit.py#L56-L61 |
17,580 | DiamondLightSource/python-workflows | workflows/services/sample_transaction.py | SampleTxn.initializing | def initializing(self):
"""Subscribe to a channel. Received messages must be acknowledged."""
self.subid = self._transport.subscribe(
"transient.transaction", self.receive_message, acknowledgement=True
) | python | def initializing(self):
self.subid = self._transport.subscribe(
"transient.transaction", self.receive_message, acknowledgement=True
) | [
"def",
"initializing",
"(",
"self",
")",
":",
"self",
".",
"subid",
"=",
"self",
".",
"_transport",
".",
"subscribe",
"(",
"\"transient.transaction\"",
",",
"self",
".",
"receive_message",
",",
"acknowledgement",
"=",
"True",
")"
] | Subscribe to a channel. Received messages must be acknowledged. | [
"Subscribe",
"to",
"a",
"channel",
".",
"Received",
"messages",
"must",
"be",
"acknowledged",
"."
] | 7ef47b457655b96f4d2ef7ee9863cf1b6d20e023 | https://github.com/DiamondLightSource/python-workflows/blob/7ef47b457655b96f4d2ef7ee9863cf1b6d20e023/workflows/services/sample_transaction.py#L19-L23 |
17,581 | DiamondLightSource/python-workflows | workflows/services/sample_transaction.py | SampleTxn.receive_message | def receive_message(self, header, message):
"""Receive a message"""
print("=== Receive ===")
print(header)
print(message)
print("MsgID: {0}".format(header["message-id"]))
assert header["message-id"]
txn = self._transport.transaction_begin()
print(" 1. Txn: {0}".format(str(txn)))
if self.crashpoint():
self._transport.transaction_abort(txn)
print("--- Abort ---")
return
self._transport.ack(header["message-id"], self.subid, transaction=txn)
print(" 2. Ack")
if self.crashpoint():
self._transport.transaction_abort(txn)
print("--- Abort ---")
return
self._transport.send("transient.destination", message, transaction=txn)
print(" 3. Send")
if self.crashpoint():
self._transport.transaction_abort(txn)
print("--- Abort ---")
return
self._transport.transaction_commit(txn)
print(" 4. Commit")
print("=== Done ===") | python | def receive_message(self, header, message):
print("=== Receive ===")
print(header)
print(message)
print("MsgID: {0}".format(header["message-id"]))
assert header["message-id"]
txn = self._transport.transaction_begin()
print(" 1. Txn: {0}".format(str(txn)))
if self.crashpoint():
self._transport.transaction_abort(txn)
print("--- Abort ---")
return
self._transport.ack(header["message-id"], self.subid, transaction=txn)
print(" 2. Ack")
if self.crashpoint():
self._transport.transaction_abort(txn)
print("--- Abort ---")
return
self._transport.send("transient.destination", message, transaction=txn)
print(" 3. Send")
if self.crashpoint():
self._transport.transaction_abort(txn)
print("--- Abort ---")
return
self._transport.transaction_commit(txn)
print(" 4. Commit")
print("=== Done ===") | [
"def",
"receive_message",
"(",
"self",
",",
"header",
",",
"message",
")",
":",
"print",
"(",
"\"=== Receive ===\"",
")",
"print",
"(",
"header",
")",
"print",
"(",
"message",
")",
"print",
"(",
"\"MsgID: {0}\"",
".",
"format",
"(",
"header",
"[",
"\"messa... | Receive a message | [
"Receive",
"a",
"message"
] | 7ef47b457655b96f4d2ef7ee9863cf1b6d20e023 | https://github.com/DiamondLightSource/python-workflows/blob/7ef47b457655b96f4d2ef7ee9863cf1b6d20e023/workflows/services/sample_transaction.py#L31-L65 |
17,582 | DiamondLightSource/python-workflows | workflows/services/sample_transaction.py | SampleTxnProducer.create_message | def create_message(self):
"""Create and send a unique message for this service."""
self.counter += 1
self._transport.send(
"transient.transaction",
"TXMessage #%d\n++++++++Produced@ %f"
% (self.counter, (time.time() % 1000) * 1000),
)
self.log.info("Created message %d", self.counter) | python | def create_message(self):
self.counter += 1
self._transport.send(
"transient.transaction",
"TXMessage #%d\n++++++++Produced@ %f"
% (self.counter, (time.time() % 1000) * 1000),
)
self.log.info("Created message %d", self.counter) | [
"def",
"create_message",
"(",
"self",
")",
":",
"self",
".",
"counter",
"+=",
"1",
"self",
".",
"_transport",
".",
"send",
"(",
"\"transient.transaction\"",
",",
"\"TXMessage #%d\\n++++++++Produced@ %f\"",
"%",
"(",
"self",
".",
"counter",
",",
"(",
"time",
".... | Create and send a unique message for this service. | [
"Create",
"and",
"send",
"a",
"unique",
"message",
"for",
"this",
"service",
"."
] | 7ef47b457655b96f4d2ef7ee9863cf1b6d20e023 | https://github.com/DiamondLightSource/python-workflows/blob/7ef47b457655b96f4d2ef7ee9863cf1b6d20e023/workflows/services/sample_transaction.py#L85-L93 |
17,583 | cuihantao/andes | andes/utils/time.py | elapsed | def elapsed(t0=0.0):
"""get elapsed time from the give time
Returns:
now: the absolute time now
dt_str: elapsed time in string
"""
now = time()
dt = now - t0
dt_sec = Decimal(str(dt)).quantize(Decimal('.0001'), rounding=ROUND_DOWN)
if dt_sec <= 1:
dt_str = str(dt_sec) + ' second'
else:
dt_str = str(dt_sec) + ' seconds'
return now, dt_str | python | def elapsed(t0=0.0):
now = time()
dt = now - t0
dt_sec = Decimal(str(dt)).quantize(Decimal('.0001'), rounding=ROUND_DOWN)
if dt_sec <= 1:
dt_str = str(dt_sec) + ' second'
else:
dt_str = str(dt_sec) + ' seconds'
return now, dt_str | [
"def",
"elapsed",
"(",
"t0",
"=",
"0.0",
")",
":",
"now",
"=",
"time",
"(",
")",
"dt",
"=",
"now",
"-",
"t0",
"dt_sec",
"=",
"Decimal",
"(",
"str",
"(",
"dt",
")",
")",
".",
"quantize",
"(",
"Decimal",
"(",
"'.0001'",
")",
",",
"rounding",
"=",... | get elapsed time from the give time
Returns:
now: the absolute time now
dt_str: elapsed time in string | [
"get",
"elapsed",
"time",
"from",
"the",
"give",
"time"
] | 7067898d4f26ce7534e968b8486c4aa8fe3a511a | https://github.com/cuihantao/andes/blob/7067898d4f26ce7534e968b8486c4aa8fe3a511a/andes/utils/time.py#L5-L19 |
17,584 | cuihantao/andes | andes/models/pss.py | PSS1.set_flag | def set_flag(self, value, flag, reset_val=False):
"""Set a flag to 0 if the corresponding value is 0"""
if not self.__dict__[flag]:
self.__dict__[flag] = matrix(1.0, (len(self.__dict__[value]), 1),
'd')
for idx, item in enumerate(self.__dict__[value]):
if item == 0:
self.__dict__[flag][idx] = 0
if reset_val:
self.__dict__[value][idx] = 1 | python | def set_flag(self, value, flag, reset_val=False):
if not self.__dict__[flag]:
self.__dict__[flag] = matrix(1.0, (len(self.__dict__[value]), 1),
'd')
for idx, item in enumerate(self.__dict__[value]):
if item == 0:
self.__dict__[flag][idx] = 0
if reset_val:
self.__dict__[value][idx] = 1 | [
"def",
"set_flag",
"(",
"self",
",",
"value",
",",
"flag",
",",
"reset_val",
"=",
"False",
")",
":",
"if",
"not",
"self",
".",
"__dict__",
"[",
"flag",
"]",
":",
"self",
".",
"__dict__",
"[",
"flag",
"]",
"=",
"matrix",
"(",
"1.0",
",",
"(",
"len... | Set a flag to 0 if the corresponding value is 0 | [
"Set",
"a",
"flag",
"to",
"0",
"if",
"the",
"corresponding",
"value",
"is",
"0"
] | 7067898d4f26ce7534e968b8486c4aa8fe3a511a | https://github.com/cuihantao/andes/blob/7067898d4f26ce7534e968b8486c4aa8fe3a511a/andes/models/pss.py#L139-L148 |
17,585 | cuihantao/andes | andes/variables/report.py | Report._update_summary | def _update_summary(self, system):
"""
Update the summary data
Parameters
----------
system
Returns
-------
None
"""
self.basic.update({
'nbus': system.Bus.n,
'ngen': system.PV.n + system.SW.n,
'ngen_on': sum(system.PV.u) + sum(system.SW.u),
'nload': system.PQ.n,
'nshunt': system.Shunt.n,
'nline': system.Line.n,
'ntransf': system.Line.trasf.count(True),
'narea': system.Area.n,
}) | python | def _update_summary(self, system):
self.basic.update({
'nbus': system.Bus.n,
'ngen': system.PV.n + system.SW.n,
'ngen_on': sum(system.PV.u) + sum(system.SW.u),
'nload': system.PQ.n,
'nshunt': system.Shunt.n,
'nline': system.Line.n,
'ntransf': system.Line.trasf.count(True),
'narea': system.Area.n,
}) | [
"def",
"_update_summary",
"(",
"self",
",",
"system",
")",
":",
"self",
".",
"basic",
".",
"update",
"(",
"{",
"'nbus'",
":",
"system",
".",
"Bus",
".",
"n",
",",
"'ngen'",
":",
"system",
".",
"PV",
".",
"n",
"+",
"system",
".",
"SW",
".",
"n",
... | Update the summary data
Parameters
----------
system
Returns
-------
None | [
"Update",
"the",
"summary",
"data"
] | 7067898d4f26ce7534e968b8486c4aa8fe3a511a | https://github.com/cuihantao/andes/blob/7067898d4f26ce7534e968b8486c4aa8fe3a511a/andes/variables/report.py#L64-L85 |
17,586 | cuihantao/andes | andes/variables/report.py | Report._update_extended | def _update_extended(self, system):
"""Update the extended data"""
if self.system.pflow.solved is False:
logger.warning(
'Cannot update extended summary. Power flow not solved.')
return
Sloss = sum(system.Line.S1 + system.Line.S2)
self.extended.update({
'Ptot':
sum(system.PV.pmax) + sum(system.SW.pmax), # + sum(system.SW.pmax)
'Pon':
sum(mul(system.PV.u, system.PV.pmax)),
'Pg':
sum(system.Bus.Pg),
'Qtot_min':
sum(system.PV.qmin) + sum(system.SW.qmin),
'Qtot_max':
sum(system.PV.qmax) + sum(system.SW.qmax),
'Qon_min':
sum(mul(system.PV.u, system.PV.qmin)),
'Qon_max':
sum(mul(system.PV.u, system.PV.qmax)),
'Qg':
round(sum(system.Bus.Qg), 5),
'Pl':
round(sum(system.PQ.p), 5),
'Ql':
round(sum(system.PQ.q), 5),
'Psh':
0.0,
'Qsh':
round(sum(system.PQ.q) - sum(system.Bus.Ql), 5),
'Ploss':
round(Sloss.real, 5),
'Qloss':
round(Sloss.imag, 5),
'Pch':
round(sum(system.Line.Pchg1 + system.Line.Pchg2), 5),
'Qch':
round(sum(system.Line.Qchg1 + system.Line.Qchg2), 5),
}) | python | def _update_extended(self, system):
if self.system.pflow.solved is False:
logger.warning(
'Cannot update extended summary. Power flow not solved.')
return
Sloss = sum(system.Line.S1 + system.Line.S2)
self.extended.update({
'Ptot':
sum(system.PV.pmax) + sum(system.SW.pmax), # + sum(system.SW.pmax)
'Pon':
sum(mul(system.PV.u, system.PV.pmax)),
'Pg':
sum(system.Bus.Pg),
'Qtot_min':
sum(system.PV.qmin) + sum(system.SW.qmin),
'Qtot_max':
sum(system.PV.qmax) + sum(system.SW.qmax),
'Qon_min':
sum(mul(system.PV.u, system.PV.qmin)),
'Qon_max':
sum(mul(system.PV.u, system.PV.qmax)),
'Qg':
round(sum(system.Bus.Qg), 5),
'Pl':
round(sum(system.PQ.p), 5),
'Ql':
round(sum(system.PQ.q), 5),
'Psh':
0.0,
'Qsh':
round(sum(system.PQ.q) - sum(system.Bus.Ql), 5),
'Ploss':
round(Sloss.real, 5),
'Qloss':
round(Sloss.imag, 5),
'Pch':
round(sum(system.Line.Pchg1 + system.Line.Pchg2), 5),
'Qch':
round(sum(system.Line.Qchg1 + system.Line.Qchg2), 5),
}) | [
"def",
"_update_extended",
"(",
"self",
",",
"system",
")",
":",
"if",
"self",
".",
"system",
".",
"pflow",
".",
"solved",
"is",
"False",
":",
"logger",
".",
"warning",
"(",
"'Cannot update extended summary. Power flow not solved.'",
")",
"return",
"Sloss",
"=",... | Update the extended data | [
"Update",
"the",
"extended",
"data"
] | 7067898d4f26ce7534e968b8486c4aa8fe3a511a | https://github.com/cuihantao/andes/blob/7067898d4f26ce7534e968b8486c4aa8fe3a511a/andes/variables/report.py#L87-L128 |
17,587 | cuihantao/andes | andes/variables/report.py | Report.update | def update(self, content=None):
"""
Update values based on the requested content
Parameters
----------
content
Returns
-------
"""
if not content:
return
if content == 'summary' or 'extended' or 'powerflow':
self._update_summary(self.system)
if content == 'extended' or 'powerflow':
self._update_extended(self.system) | python | def update(self, content=None):
if not content:
return
if content == 'summary' or 'extended' or 'powerflow':
self._update_summary(self.system)
if content == 'extended' or 'powerflow':
self._update_extended(self.system) | [
"def",
"update",
"(",
"self",
",",
"content",
"=",
"None",
")",
":",
"if",
"not",
"content",
":",
"return",
"if",
"content",
"==",
"'summary'",
"or",
"'extended'",
"or",
"'powerflow'",
":",
"self",
".",
"_update_summary",
"(",
"self",
".",
"system",
")",... | Update values based on the requested content
Parameters
----------
content
Returns
------- | [
"Update",
"values",
"based",
"on",
"the",
"requested",
"content"
] | 7067898d4f26ce7534e968b8486c4aa8fe3a511a | https://github.com/cuihantao/andes/blob/7067898d4f26ce7534e968b8486c4aa8fe3a511a/andes/variables/report.py#L130-L147 |
17,588 | DiamondLightSource/python-workflows | workflows/recipe/wrapper.py | RecipeWrapper.send | def send(self, *args, **kwargs):
"""Send messages to another service that is connected to the currently
running service via the recipe. The 'send' method will either use a
default channel name, set via the set_default_channel method, or an
unnamed output definition.
"""
if not self.transport:
raise ValueError(
"This RecipeWrapper object does not contain "
"a reference to a transport object."
)
if not self.recipe_step:
raise ValueError(
"This RecipeWrapper object does not contain "
"a recipe with a selected step."
)
if "output" not in self.recipe_step:
# The current recipe step does not have output channels.
return
if isinstance(self.recipe_step["output"], dict):
# The current recipe step does have named output channels.
if self.default_channel:
# Use named output channel
self.send_to(self.default_channel, *args, **kwargs)
else:
# The current recipe step does have unnamed output channels.
self._send_to_destinations(self.recipe_step["output"], *args, **kwargs) | python | def send(self, *args, **kwargs):
if not self.transport:
raise ValueError(
"This RecipeWrapper object does not contain "
"a reference to a transport object."
)
if not self.recipe_step:
raise ValueError(
"This RecipeWrapper object does not contain "
"a recipe with a selected step."
)
if "output" not in self.recipe_step:
# The current recipe step does not have output channels.
return
if isinstance(self.recipe_step["output"], dict):
# The current recipe step does have named output channels.
if self.default_channel:
# Use named output channel
self.send_to(self.default_channel, *args, **kwargs)
else:
# The current recipe step does have unnamed output channels.
self._send_to_destinations(self.recipe_step["output"], *args, **kwargs) | [
"def",
"send",
"(",
"self",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"not",
"self",
".",
"transport",
":",
"raise",
"ValueError",
"(",
"\"This RecipeWrapper object does not contain \"",
"\"a reference to a transport object.\"",
")",
"if",
"not",
... | Send messages to another service that is connected to the currently
running service via the recipe. The 'send' method will either use a
default channel name, set via the set_default_channel method, or an
unnamed output definition. | [
"Send",
"messages",
"to",
"another",
"service",
"that",
"is",
"connected",
"to",
"the",
"currently",
"running",
"service",
"via",
"the",
"recipe",
".",
"The",
"send",
"method",
"will",
"either",
"use",
"a",
"default",
"channel",
"name",
"set",
"via",
"the",
... | 7ef47b457655b96f4d2ef7ee9863cf1b6d20e023 | https://github.com/DiamondLightSource/python-workflows/blob/7ef47b457655b96f4d2ef7ee9863cf1b6d20e023/workflows/recipe/wrapper.py#L40-L70 |
17,589 | DiamondLightSource/python-workflows | workflows/recipe/wrapper.py | RecipeWrapper._generate_full_recipe_message | def _generate_full_recipe_message(self, destination, message, add_path_step):
"""Factory function to generate independent message objects for
downstream recipients with different destinations."""
if add_path_step and self.recipe_pointer:
recipe_path = self.recipe_path + [self.recipe_pointer]
else:
recipe_path = self.recipe_path
return {
"environment": self.environment,
"payload": message,
"recipe": self.recipe.recipe,
"recipe-path": recipe_path,
"recipe-pointer": destination,
} | python | def _generate_full_recipe_message(self, destination, message, add_path_step):
if add_path_step and self.recipe_pointer:
recipe_path = self.recipe_path + [self.recipe_pointer]
else:
recipe_path = self.recipe_path
return {
"environment": self.environment,
"payload": message,
"recipe": self.recipe.recipe,
"recipe-path": recipe_path,
"recipe-pointer": destination,
} | [
"def",
"_generate_full_recipe_message",
"(",
"self",
",",
"destination",
",",
"message",
",",
"add_path_step",
")",
":",
"if",
"add_path_step",
"and",
"self",
".",
"recipe_pointer",
":",
"recipe_path",
"=",
"self",
".",
"recipe_path",
"+",
"[",
"self",
".",
"r... | Factory function to generate independent message objects for
downstream recipients with different destinations. | [
"Factory",
"function",
"to",
"generate",
"independent",
"message",
"objects",
"for",
"downstream",
"recipients",
"with",
"different",
"destinations",
"."
] | 7ef47b457655b96f4d2ef7ee9863cf1b6d20e023 | https://github.com/DiamondLightSource/python-workflows/blob/7ef47b457655b96f4d2ef7ee9863cf1b6d20e023/workflows/recipe/wrapper.py#L163-L177 |
17,590 | DiamondLightSource/python-workflows | workflows/recipe/wrapper.py | RecipeWrapper._send_to_destinations | def _send_to_destinations(self, destinations, message, header=None, **kwargs):
"""Send messages to a list of numbered destinations. This is an internal
helper method used by the public 'send' methods.
"""
if not isinstance(destinations, list):
destinations = (destinations,)
for destination in destinations:
self._send_to_destination(destination, header, message, kwargs) | python | def _send_to_destinations(self, destinations, message, header=None, **kwargs):
if not isinstance(destinations, list):
destinations = (destinations,)
for destination in destinations:
self._send_to_destination(destination, header, message, kwargs) | [
"def",
"_send_to_destinations",
"(",
"self",
",",
"destinations",
",",
"message",
",",
"header",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"not",
"isinstance",
"(",
"destinations",
",",
"list",
")",
":",
"destinations",
"=",
"(",
"destinations"... | Send messages to a list of numbered destinations. This is an internal
helper method used by the public 'send' methods. | [
"Send",
"messages",
"to",
"a",
"list",
"of",
"numbered",
"destinations",
".",
"This",
"is",
"an",
"internal",
"helper",
"method",
"used",
"by",
"the",
"public",
"send",
"methods",
"."
] | 7ef47b457655b96f4d2ef7ee9863cf1b6d20e023 | https://github.com/DiamondLightSource/python-workflows/blob/7ef47b457655b96f4d2ef7ee9863cf1b6d20e023/workflows/recipe/wrapper.py#L179-L186 |
17,591 | DiamondLightSource/python-workflows | workflows/recipe/wrapper.py | RecipeWrapper._send_to_destination | def _send_to_destination(
self, destination, header, payload, transport_kwargs, add_path_step=True
):
"""Helper function to send a message to a specific recipe destination."""
if header:
header = header.copy()
header["workflows-recipe"] = True
else:
header = {"workflows-recipe": True}
dest_kwargs = transport_kwargs.copy()
if (
"transport-delay" in self.recipe[destination]
and "delay" not in transport_kwargs
):
dest_kwargs["delay"] = self.recipe[destination]["transport-delay"]
if self.recipe[destination].get("queue"):
self.transport.send(
self.recipe[destination]["queue"],
self._generate_full_recipe_message(destination, payload, add_path_step),
headers=header,
**dest_kwargs
)
if self.recipe[destination].get("topic"):
self.transport.broadcast(
self.recipe[destination]["topic"],
self._generate_full_recipe_message(destination, payload, add_path_step),
headers=header,
**dest_kwargs
) | python | def _send_to_destination(
self, destination, header, payload, transport_kwargs, add_path_step=True
):
if header:
header = header.copy()
header["workflows-recipe"] = True
else:
header = {"workflows-recipe": True}
dest_kwargs = transport_kwargs.copy()
if (
"transport-delay" in self.recipe[destination]
and "delay" not in transport_kwargs
):
dest_kwargs["delay"] = self.recipe[destination]["transport-delay"]
if self.recipe[destination].get("queue"):
self.transport.send(
self.recipe[destination]["queue"],
self._generate_full_recipe_message(destination, payload, add_path_step),
headers=header,
**dest_kwargs
)
if self.recipe[destination].get("topic"):
self.transport.broadcast(
self.recipe[destination]["topic"],
self._generate_full_recipe_message(destination, payload, add_path_step),
headers=header,
**dest_kwargs
) | [
"def",
"_send_to_destination",
"(",
"self",
",",
"destination",
",",
"header",
",",
"payload",
",",
"transport_kwargs",
",",
"add_path_step",
"=",
"True",
")",
":",
"if",
"header",
":",
"header",
"=",
"header",
".",
"copy",
"(",
")",
"header",
"[",
"\"work... | Helper function to send a message to a specific recipe destination. | [
"Helper",
"function",
"to",
"send",
"a",
"message",
"to",
"a",
"specific",
"recipe",
"destination",
"."
] | 7ef47b457655b96f4d2ef7ee9863cf1b6d20e023 | https://github.com/DiamondLightSource/python-workflows/blob/7ef47b457655b96f4d2ef7ee9863cf1b6d20e023/workflows/recipe/wrapper.py#L188-L217 |
17,592 | Legobot/Legobot | Legobot/Connectors/Slack.py | RtmBot.on_message | def on_message(self, event):
'''Runs when a message event is received
Args:
event: RTM API event.
Returns:
Legobot.messge
'''
metadata = self._parse_metadata(event)
message = Message(text=metadata['text'],
metadata=metadata).__dict__
if message.get('text'):
message['text'] = self.find_and_replace_userids(message['text'])
message['text'] = self.find_and_replace_channel_refs(
message['text']
)
return message | python | def on_message(self, event):
'''Runs when a message event is received
Args:
event: RTM API event.
Returns:
Legobot.messge
'''
metadata = self._parse_metadata(event)
message = Message(text=metadata['text'],
metadata=metadata).__dict__
if message.get('text'):
message['text'] = self.find_and_replace_userids(message['text'])
message['text'] = self.find_and_replace_channel_refs(
message['text']
)
return message | [
"def",
"on_message",
"(",
"self",
",",
"event",
")",
":",
"metadata",
"=",
"self",
".",
"_parse_metadata",
"(",
"event",
")",
"message",
"=",
"Message",
"(",
"text",
"=",
"metadata",
"[",
"'text'",
"]",
",",
"metadata",
"=",
"metadata",
")",
".",
"__di... | Runs when a message event is received
Args:
event: RTM API event.
Returns:
Legobot.messge | [
"Runs",
"when",
"a",
"message",
"event",
"is",
"received"
] | d13da172960a149681cb5151ce34b2f3a58ad32b | https://github.com/Legobot/Legobot/blob/d13da172960a149681cb5151ce34b2f3a58ad32b/Legobot/Connectors/Slack.py#L75-L93 |
17,593 | Legobot/Legobot | Legobot/Connectors/Slack.py | RtmBot.find_and_replace_userids | def find_and_replace_userids(self, text):
'''Finds occurrences of Slack userids and attempts to replace them with
display names.
Args:
text (string): The message text
Returns:
string: The message text with userids replaced.
'''
match = True
pattern = re.compile('<@([A-Z0-9]{9})>')
while match:
match = pattern.search(text)
if match:
name = self.get_user_display_name(match.group(1))
text = re.sub(re.compile(match.group(0)), '@' + name, text)
return text | python | def find_and_replace_userids(self, text):
'''Finds occurrences of Slack userids and attempts to replace them with
display names.
Args:
text (string): The message text
Returns:
string: The message text with userids replaced.
'''
match = True
pattern = re.compile('<@([A-Z0-9]{9})>')
while match:
match = pattern.search(text)
if match:
name = self.get_user_display_name(match.group(1))
text = re.sub(re.compile(match.group(0)), '@' + name, text)
return text | [
"def",
"find_and_replace_userids",
"(",
"self",
",",
"text",
")",
":",
"match",
"=",
"True",
"pattern",
"=",
"re",
".",
"compile",
"(",
"'<@([A-Z0-9]{9})>'",
")",
"while",
"match",
":",
"match",
"=",
"pattern",
".",
"search",
"(",
"text",
")",
"if",
"mat... | Finds occurrences of Slack userids and attempts to replace them with
display names.
Args:
text (string): The message text
Returns:
string: The message text with userids replaced. | [
"Finds",
"occurrences",
"of",
"Slack",
"userids",
"and",
"attempts",
"to",
"replace",
"them",
"with",
"display",
"names",
"."
] | d13da172960a149681cb5151ce34b2f3a58ad32b | https://github.com/Legobot/Legobot/blob/d13da172960a149681cb5151ce34b2f3a58ad32b/Legobot/Connectors/Slack.py#L113-L131 |
17,594 | Legobot/Legobot | Legobot/Connectors/Slack.py | RtmBot.find_and_replace_channel_refs | def find_and_replace_channel_refs(self, text):
'''Find occurrences of Slack channel referenfces and attempts to
replace them with just channel names.
Args:
text (string): The message text
Returns:
string: The message text with channel references replaced.
'''
match = True
pattern = re.compile('<#([A-Z0-9]{9})\|([A-Za-z0-9-]+)>')
while match:
match = pattern.search(text)
if match:
text = text.replace(match.group(0), '#' + match.group(2))
return text | python | def find_and_replace_channel_refs(self, text):
'''Find occurrences of Slack channel referenfces and attempts to
replace them with just channel names.
Args:
text (string): The message text
Returns:
string: The message text with channel references replaced.
'''
match = True
pattern = re.compile('<#([A-Z0-9]{9})\|([A-Za-z0-9-]+)>')
while match:
match = pattern.search(text)
if match:
text = text.replace(match.group(0), '#' + match.group(2))
return text | [
"def",
"find_and_replace_channel_refs",
"(",
"self",
",",
"text",
")",
":",
"match",
"=",
"True",
"pattern",
"=",
"re",
".",
"compile",
"(",
"'<#([A-Z0-9]{9})\\|([A-Za-z0-9-]+)>'",
")",
"while",
"match",
":",
"match",
"=",
"pattern",
".",
"search",
"(",
"text"... | Find occurrences of Slack channel referenfces and attempts to
replace them with just channel names.
Args:
text (string): The message text
Returns:
string: The message text with channel references replaced. | [
"Find",
"occurrences",
"of",
"Slack",
"channel",
"referenfces",
"and",
"attempts",
"to",
"replace",
"them",
"with",
"just",
"channel",
"names",
"."
] | d13da172960a149681cb5151ce34b2f3a58ad32b | https://github.com/Legobot/Legobot/blob/d13da172960a149681cb5151ce34b2f3a58ad32b/Legobot/Connectors/Slack.py#L133-L150 |
17,595 | Legobot/Legobot | Legobot/Connectors/Slack.py | RtmBot.get_channels | def get_channels(self, condensed=False):
'''Grabs all channels in the slack team
Args:
condensed (bool): if true triggers list condensing functionality
Returns:
dic: Dict of channels in Slack team.
See also: https://api.slack.com/methods/channels.list
'''
channel_list = self.slack_client.api_call('channels.list')
if not channel_list.get('ok'):
return None
if condensed:
channels = [{'id': item.get('id'), 'name': item.get('name')}
for item in channel_list.get('channels')]
return channels
else:
return channel_list | python | def get_channels(self, condensed=False):
'''Grabs all channels in the slack team
Args:
condensed (bool): if true triggers list condensing functionality
Returns:
dic: Dict of channels in Slack team.
See also: https://api.slack.com/methods/channels.list
'''
channel_list = self.slack_client.api_call('channels.list')
if not channel_list.get('ok'):
return None
if condensed:
channels = [{'id': item.get('id'), 'name': item.get('name')}
for item in channel_list.get('channels')]
return channels
else:
return channel_list | [
"def",
"get_channels",
"(",
"self",
",",
"condensed",
"=",
"False",
")",
":",
"channel_list",
"=",
"self",
".",
"slack_client",
".",
"api_call",
"(",
"'channels.list'",
")",
"if",
"not",
"channel_list",
".",
"get",
"(",
"'ok'",
")",
":",
"return",
"None",
... | Grabs all channels in the slack team
Args:
condensed (bool): if true triggers list condensing functionality
Returns:
dic: Dict of channels in Slack team.
See also: https://api.slack.com/methods/channels.list | [
"Grabs",
"all",
"channels",
"in",
"the",
"slack",
"team"
] | d13da172960a149681cb5151ce34b2f3a58ad32b | https://github.com/Legobot/Legobot/blob/d13da172960a149681cb5151ce34b2f3a58ad32b/Legobot/Connectors/Slack.py#L182-L202 |
17,596 | Legobot/Legobot | Legobot/Connectors/Slack.py | RtmBot.get_users | def get_users(self, condensed=False):
'''Grabs all users in the slack team
This should should only be used for getting list of all users. Do not
use it for searching users. Use get_user_info instead.
Args:
condensed (bool): if true triggers list condensing functionality
Returns:
dict: Dict of users in Slack team.
See also: https://api.slack.com/methods/users.list
'''
user_list = self.slack_client.api_call('users.list')
if not user_list.get('ok'):
return None
if condensed:
users = [{'id': item.get('id'), 'name': item.get('name'),
'display_name': item.get('profile').get('display_name')}
for item in user_list.get('members')]
return users
else:
return user_list | python | def get_users(self, condensed=False):
'''Grabs all users in the slack team
This should should only be used for getting list of all users. Do not
use it for searching users. Use get_user_info instead.
Args:
condensed (bool): if true triggers list condensing functionality
Returns:
dict: Dict of users in Slack team.
See also: https://api.slack.com/methods/users.list
'''
user_list = self.slack_client.api_call('users.list')
if not user_list.get('ok'):
return None
if condensed:
users = [{'id': item.get('id'), 'name': item.get('name'),
'display_name': item.get('profile').get('display_name')}
for item in user_list.get('members')]
return users
else:
return user_list | [
"def",
"get_users",
"(",
"self",
",",
"condensed",
"=",
"False",
")",
":",
"user_list",
"=",
"self",
".",
"slack_client",
".",
"api_call",
"(",
"'users.list'",
")",
"if",
"not",
"user_list",
".",
"get",
"(",
"'ok'",
")",
":",
"return",
"None",
"if",
"c... | Grabs all users in the slack team
This should should only be used for getting list of all users. Do not
use it for searching users. Use get_user_info instead.
Args:
condensed (bool): if true triggers list condensing functionality
Returns:
dict: Dict of users in Slack team.
See also: https://api.slack.com/methods/users.list | [
"Grabs",
"all",
"users",
"in",
"the",
"slack",
"team"
] | d13da172960a149681cb5151ce34b2f3a58ad32b | https://github.com/Legobot/Legobot/blob/d13da172960a149681cb5151ce34b2f3a58ad32b/Legobot/Connectors/Slack.py#L204-L227 |
17,597 | Legobot/Legobot | Legobot/Connectors/Slack.py | RtmBot.get_user_display_name | def get_user_display_name(self, userid):
'''Given a Slack userid, grabs user display_name from api.
Args:
userid (string): the user id of the user being queried
Returns:
dict: a dictionary of the api response
'''
user_info = self.slack_client.api_call('users.info', user=userid)
if user_info.get('ok'):
user = user_info.get('user')
if user.get('profile'):
return user.get('profile').get('display_name')
else:
return user.get('name')
else:
return userid | python | def get_user_display_name(self, userid):
'''Given a Slack userid, grabs user display_name from api.
Args:
userid (string): the user id of the user being queried
Returns:
dict: a dictionary of the api response
'''
user_info = self.slack_client.api_call('users.info', user=userid)
if user_info.get('ok'):
user = user_info.get('user')
if user.get('profile'):
return user.get('profile').get('display_name')
else:
return user.get('name')
else:
return userid | [
"def",
"get_user_display_name",
"(",
"self",
",",
"userid",
")",
":",
"user_info",
"=",
"self",
".",
"slack_client",
".",
"api_call",
"(",
"'users.info'",
",",
"user",
"=",
"userid",
")",
"if",
"user_info",
".",
"get",
"(",
"'ok'",
")",
":",
"user",
"=",... | Given a Slack userid, grabs user display_name from api.
Args:
userid (string): the user id of the user being queried
Returns:
dict: a dictionary of the api response | [
"Given",
"a",
"Slack",
"userid",
"grabs",
"user",
"display_name",
"from",
"api",
"."
] | d13da172960a149681cb5151ce34b2f3a58ad32b | https://github.com/Legobot/Legobot/blob/d13da172960a149681cb5151ce34b2f3a58ad32b/Legobot/Connectors/Slack.py#L229-L246 |
17,598 | Legobot/Legobot | Legobot/Connectors/Slack.py | RtmBot.get_dm_channel | def get_dm_channel(self, userid):
'''Perform a lookup of users to resolve a userid to a DM channel
Args:
userid (string): Slack userid to lookup.
Returns:
string: DM channel ID of user
'''
dm_open = self.slack_client.api_call('im.open', user=userid)
return dm_open['channel']['id'] | python | def get_dm_channel(self, userid):
'''Perform a lookup of users to resolve a userid to a DM channel
Args:
userid (string): Slack userid to lookup.
Returns:
string: DM channel ID of user
'''
dm_open = self.slack_client.api_call('im.open', user=userid)
return dm_open['channel']['id'] | [
"def",
"get_dm_channel",
"(",
"self",
",",
"userid",
")",
":",
"dm_open",
"=",
"self",
".",
"slack_client",
".",
"api_call",
"(",
"'im.open'",
",",
"user",
"=",
"userid",
")",
"return",
"dm_open",
"[",
"'channel'",
"]",
"[",
"'id'",
"]"
] | Perform a lookup of users to resolve a userid to a DM channel
Args:
userid (string): Slack userid to lookup.
Returns:
string: DM channel ID of user | [
"Perform",
"a",
"lookup",
"of",
"users",
"to",
"resolve",
"a",
"userid",
"to",
"a",
"DM",
"channel"
] | d13da172960a149681cb5151ce34b2f3a58ad32b | https://github.com/Legobot/Legobot/blob/d13da172960a149681cb5151ce34b2f3a58ad32b/Legobot/Connectors/Slack.py#L248-L259 |
17,599 | Legobot/Legobot | Legobot/Connectors/Slack.py | RtmBot.get_username | def get_username(self, userid):
'''Perform a lookup of users to resolve a userid to a username
Args:
userid (string): Slack userid to lookup.
Returns:
string: Human-friendly name of the user
'''
username = self.user_map.get(userid)
if not username:
users = self.get_users()
if users:
members = {
m['id']: m['name']
for m in users.get('members', [{}])
if m.get('id')
and m.get('name')
}
if members:
self.user_map.update(members)
username = self.user_map.get(userid, userid)
return username | python | def get_username(self, userid):
'''Perform a lookup of users to resolve a userid to a username
Args:
userid (string): Slack userid to lookup.
Returns:
string: Human-friendly name of the user
'''
username = self.user_map.get(userid)
if not username:
users = self.get_users()
if users:
members = {
m['id']: m['name']
for m in users.get('members', [{}])
if m.get('id')
and m.get('name')
}
if members:
self.user_map.update(members)
username = self.user_map.get(userid, userid)
return username | [
"def",
"get_username",
"(",
"self",
",",
"userid",
")",
":",
"username",
"=",
"self",
".",
"user_map",
".",
"get",
"(",
"userid",
")",
"if",
"not",
"username",
":",
"users",
"=",
"self",
".",
"get_users",
"(",
")",
"if",
"users",
":",
"members",
"=",... | Perform a lookup of users to resolve a userid to a username
Args:
userid (string): Slack userid to lookup.
Returns:
string: Human-friendly name of the user | [
"Perform",
"a",
"lookup",
"of",
"users",
"to",
"resolve",
"a",
"userid",
"to",
"a",
"username"
] | d13da172960a149681cb5151ce34b2f3a58ad32b | https://github.com/Legobot/Legobot/blob/d13da172960a149681cb5151ce34b2f3a58ad32b/Legobot/Connectors/Slack.py#L264-L289 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.