repository_name stringlengths 5 67 | func_path_in_repository stringlengths 4 234 | func_name stringlengths 0 314 | whole_func_string stringlengths 52 3.87M | language stringclasses 6
values | func_code_string stringlengths 52 3.87M | func_documentation_string stringlengths 1 47.2k | func_code_url stringlengths 85 339 |
|---|---|---|---|---|---|---|---|
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)
... | python | 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)
... | Return the original full path if full path is specified, otherwise
search in the case file path | https://github.com/cuihantao/andes/blob/7067898d4f26ce7534e968b8486c4aa8fe3a511a/andes/variables/fileman.py#L99-L118 |
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 <{}> act... | python | 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 <{}> act... | Switch if time for eAgc has come | https://github.com/cuihantao/andes/blob/7067898d4f26ce7534e968b8486c4aa8fe3a511a/andes/models/agc.py#L169-L178 |
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
... | python | 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
... | 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 | https://github.com/cuihantao/andes/blob/7067898d4f26ce7534e968b8486c4aa8fe3a511a/andes/routines/__init__.py#L7-L25 |
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(matr... | python | 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(matr... | Return a list of occurrance times of the events
:return: list of times | https://github.com/cuihantao/andes/blob/7067898d4f26ce7534e968b8486c4aa8fe3a511a/andes/models/event.py#L20-L34 |
cuihantao/andes | andes/models/event.py | EventBase.apply | def apply(self, sim_time):
"""
Apply the event and
:param sim_time:
:return:
"""
if not self.n:
return
# skip if already applied
if self._last_time != sim_time:
self._last_time = sim_time
else:
return | python | def apply(self, sim_time):
"""
Apply the event and
:param sim_time:
:return:
"""
if not self.n:
return
# skip if already applied
if self._last_time != sim_time:
self._last_time = sim_time
else:
return | Apply the event and
:param sim_time:
:return: | https://github.com/cuihantao/andes/blob/7067898d4f26ce7534e968b8486c4aa8fe3a511a/andes/models/event.py#L49-L62 |
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.ta... | python | 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.ta... | Build transmission line admittance matrix into self.Y | https://github.com/cuihantao/andes/blob/7067898d4f26ce7534e968b8486c4aa8fe3a511a/andes/models/line.py#L131-L152 |
cuihantao/andes | andes/models/line.py | Line.build_b | def build_b(self):
"""build Bp and Bpp for fast decoupled method"""
if not self.n:
return
method = self.system.pflow.config.method.lower()
# Build B prime matrix
y1 = mul(
self.u, self.g1
) # y1 neglects line charging shunt, and g1 is usually 0 i... | python | def build_b(self):
"""build Bp and Bpp for fast decoupled method"""
if not self.n:
return
method = self.system.pflow.config.method.lower()
# Build B prime matrix
y1 = mul(
self.u, self.g1
) # y1 neglects line charging shunt, and g1 is usually 0 i... | build Bp and Bpp for fast decoupled method | https://github.com/cuihantao/andes/blob/7067898d4f26ce7534e968b8486c4aa8fe3a511a/andes/models/line.py#L159-L219 |
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):
"""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') | Build incidence matrix into self.C | https://github.com/cuihantao/andes/blob/7067898d4f26ce7534e968b8486c4aa8fe3a511a/andes/models/line.py#L221-L225 |
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(
spm... | python | 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(
spm... | check connectivity of network using Goderya's algorithm | https://github.com/cuihantao/andes/blob/7067898d4f26ce7534e968b8486c4aa8fe3a511a/andes/models/line.py#L227-L285 |
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)
... | python | 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)
... | Build line Jacobian matrix | https://github.com/cuihantao/andes/blob/7067898d4f26ce7534e968b8486c4aa8fe3a511a/andes/models/line.py#L313-L339 |
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])
... | python | 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])
... | Compute the flow through the line after solving PF.
Compute terminal injections, line losses | https://github.com/cuihantao/andes/blob/7067898d4f26ce7534e968b8486c4aa8fe3a511a/andes/models/line.py#L341-L382 |
cuihantao/andes | andes/models/line.py | Line.v1 | def v1(self):
"""Return voltage phasors at the "from buses" (bus1)"""
Vm = self.system.dae.y[self.v]
Va = self.system.dae.y[self.a]
return polar(Vm[self.a1], Va[self.a1]) | python | def v1(self):
"""Return voltage phasors at the "from buses" (bus1)"""
Vm = self.system.dae.y[self.v]
Va = self.system.dae.y[self.a]
return polar(Vm[self.a1], Va[self.a1]) | Return voltage phasors at the "from buses" (bus1) | https://github.com/cuihantao/andes/blob/7067898d4f26ce7534e968b8486c4aa8fe3a511a/andes/models/line.py#L385-L389 |
cuihantao/andes | andes/models/line.py | Line.v2 | def v2(self):
"""Return voltage phasors at the "to buses" (bus2)"""
Vm = self.system.dae.y[self.v]
Va = self.system.dae.y[self.a]
return polar(Vm[self.a2], Va[self.a2]) | python | def v2(self):
"""Return voltage phasors at the "to buses" (bus2)"""
Vm = self.system.dae.y[self.v]
Va = self.system.dae.y[self.a]
return polar(Vm[self.a2], Va[self.a2]) | Return voltage phasors at the "to buses" (bus2) | https://github.com/cuihantao/andes/blob/7067898d4f26ce7534e968b8486c4aa8fe3a511a/andes/models/line.py#L392-L396 |
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):
"""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)) | switch the status of Line idx | https://github.com/cuihantao/andes/blob/7067898d4f26ce7534e968b8486c4aa8fe3a511a/andes/models/line.py#L398-L403 |
cuihantao/andes | andes/models/line.py | Line._varname_flow | def _varname_flow(self):
"""Build variable names for Pij, Pji, Qij, Qji, Sij, Sji"""
if not self.n:
return
mpq = self.system.dae.m + 2 * self.system.Bus.n
nl = self.n
# Pij
xy_idx = range(mpq, mpq + nl)
self.system.varname.append(
listnam... | python | def _varname_flow(self):
"""Build variable names for Pij, Pji, Qij, Qji, Sij, Sji"""
if not self.n:
return
mpq = self.system.dae.m + 2 * self.system.Bus.n
nl = self.n
# Pij
xy_idx = range(mpq, mpq + nl)
self.system.varname.append(
listnam... | Build variable names for Pij, Pji, Qij, Qji, Sij, Sji | https://github.com/cuihantao/andes/blob/7067898d4f26ce7534e968b8486c4aa8fe3a511a/andes/models/line.py#L409-L519 |
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... | python | 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... | Return seriesflow based on the external idx on the `bus` side | https://github.com/cuihantao/andes/blob/7067898d4f26ce7534e968b8486c4aa8fe3a511a/andes/models/line.py#L521-L537 |
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... | python | 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... | Return leaf bus idx, line idx, and the line foreign key
Returns
-------
(list, list, list) or DataFrame | https://github.com/cuihantao/andes/blob/7067898d4f26ce7534e968b8486c4aa8fe3a511a/andes/models/line.py#L539-L576 |
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:
lis... | python | 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:
lis... | 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` | https://github.com/Legobot/Legobot/blob/d13da172960a149681cb5151ce34b2f3a58ad32b/Legobot/Utilities.py#L24-L46 |
cuihantao/andes | andes/variables/varname.py | VarName.resize | def resize(self):
"""Resize (extend) the list for variable names"""
yext = self.system.dae.m - len(self.unamey)
xext = self.system.dae.n - len(self.unamex)
if yext > 0:
self.unamey.extend([''] * yext)
self.fnamey.extend([''] * yext)
if xext > 0:
... | python | def resize(self):
"""Resize (extend) the list for variable names"""
yext = self.system.dae.m - len(self.unamey)
xext = self.system.dae.n - len(self.unamex)
if yext > 0:
self.unamey.extend([''] * yext)
self.fnamey.extend([''] * yext)
if xext > 0:
... | Resize (extend) the list for variable names | https://github.com/cuihantao/andes/blob/7067898d4f26ce7534e968b8486c4aa8fe3a511a/andes/variables/varname.py#L16-L25 |
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 + \
... | python | 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 + \
... | Extend `unamey` and `fnamey` for bus injections and line flows | https://github.com/cuihantao/andes/blob/7067898d4f26ce7534e968b8486c4aa8fe3a511a/andes/variables/varname.py#L27-L37 |
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... | python | 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... | Append variable names to the name lists | https://github.com/cuihantao/andes/blob/7067898d4f26ce7534e968b8486c4aa8fe3a511a/andes/variables/varname.py#L39-L60 |
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):
"""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() | Append bus injection and line flow names to `varname` | https://github.com/cuihantao/andes/blob/7067898d4f26ce7534e968b8486c4aa8fe3a511a/andes/variables/varname.py#L62-L67 |
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
... | python | 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
... | Return variable names for the given indices
:param yidx:
:param xidx:
:return: | https://github.com/cuihantao/andes/blob/7067898d4f26ce7534e968b8486c4aa8fe3a511a/andes/variables/varname.py#L89-L113 |
DiamondLightSource/python-workflows | workflows/services/__init__.py | get_known_services | def get_known_services():
"""Return a dictionary of all known services.
:return: A dictionary containing entries { service name : service class }
Future: This will change to a dictionary containing references to
factories: { service name : service class factory }
A fac... | python | def get_known_services():
"""Return a dictionary of all known services.
:return: A dictionary containing entries { service name : service class }
Future: This will change to a dictionary containing references to
factories: { service name : service class factory }
A fac... | Return a dictionary of all known services.
:return: A dictionary containing entries { service name : service class }
Future: This will change to a dictionary containing references to
factories: { service name : service class factory }
A factory is a function that takes no ... | https://github.com/DiamondLightSource/python-workflows/blob/7ef47b457655b96f4d2ef7ee9863cf1b6d20e023/workflows/services/__init__.py#L14-L34 |
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 in... | python | 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 in... | command line input parser | https://github.com/cuihantao/andes/blob/7067898d4f26ce7534e968b8486c4aa8fe3a511a/andes/plot.py#L209-L241 |
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_d... | python | 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_d... | Add plots to an existing plot | https://github.com/cuihantao/andes/blob/7067898d4f26ce7534e968b8486c4aa8fe3a511a/andes/plot.py#L481-L494 |
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))
els... | python | 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))
els... | Check initialization by comparing t=0 and t=end values | https://github.com/cuihantao/andes/blob/7067898d4f26ce7534e968b8486c4aa8fe3a511a/andes/plot.py#L577-L587 |
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 = ... | python | 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 = ... | Load the lst file into internal data structures | https://github.com/cuihantao/andes/blob/7067898d4f26ce7534e968b8486c4aa8fe3a511a/andes/plot.py#L73-L95 |
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 zi... | python | 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 zi... | Return variable names and indices matching ``query`` | https://github.com/cuihantao/andes/blob/7067898d4f26ce7534e968b8486c4aa8fe3a511a/andes/plot.py#L97-L112 |
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=','):
"""
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 | Load the dat file into internal data structures, ``self._data`` | https://github.com/cuihantao/andes/blob/7067898d4f26ce7534e968b8486c4aa8fe3a511a/andes/plot.py#L114-L123 |
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):
"""
Return the variable values at the given indices
"""
if isinstance(idx, list):
idx = np.array(idx, dtype=int)
return self._data[:, idx] | Return the variable values at the given indices | https://github.com/cuihantao/andes/blob/7067898d4f26ce7534e968b8486c4aa8fe3a511a/andes/plot.py#L125-L132 |
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):
"""
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] | Return a list of the variable names at the given indices | https://github.com/cuihantao/andes/blob/7067898d4f26ce7534e968b8486c4aa8fe3a511a/andes/plot.py#L134-L139 |
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 indice... | python | 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 indice... | 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 ... | https://github.com/cuihantao/andes/blob/7067898d4f26ce7534e968b8486c4aa8fe3a511a/andes/plot.py#L141-L175 |
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'])
... | python | 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'])
... | automatic styling according to _row_size
76 characters in a row | https://github.com/cuihantao/andes/blob/7067898d4f26ce7534e968b8486c4aa8fe3a511a/andes/utils/tab.py#L45-L59 |
cuihantao/andes | andes/utils/tab.py | Tab.add_left_space | def add_left_space(self, nspace=1):
"""elem_add n cols of spaces before the first col.
(for texttable 0.8.3)"""
sp = ' ' * nspace
for item in self._rows:
item[0] = sp + item[0] | python | def add_left_space(self, nspace=1):
"""elem_add n cols of spaces before the first col.
(for texttable 0.8.3)"""
sp = ' ' * nspace
for item in self._rows:
item[0] = sp + item[0] | elem_add n cols of spaces before the first col.
(for texttable 0.8.3) | https://github.com/cuihantao/andes/blob/7067898d4f26ce7534e968b8486c4aa8fe3a511a/andes/utils/tab.py#L65-L70 |
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... | python | 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... | generate texttable formatted string | https://github.com/cuihantao/andes/blob/7067898d4f26ce7534e968b8486c4aa8fe3a511a/andes/utils/tab.py#L72-L88 |
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
# ... | python | 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
# ... | auto fit column width | https://github.com/cuihantao/andes/blob/7067898d4f26ce7534e968b8486c4aa8fe3a511a/andes/utils/tab.py#L104-L133 |
DiamondLightSource/python-workflows | workflows/transport/common_transport.py | CommonTransport.subscribe | def subscribe(self, channel, callback, **kwargs):
"""Listen to a queue, notify via callback function.
:param channel: Queue name to subscribe to
:param callback: Function to be called when messages are received.
The callback will pass two arguments, the header as a
... | python | def subscribe(self, channel, callback, **kwargs):
"""Listen to a queue, notify via callback function.
:param channel: Queue name to subscribe to
:param callback: Function to be called when messages are received.
The callback will pass two arguments, the header as a
... | Listen to a queue, notify via callback function.
:param channel: Queue name to subscribe to
:param callback: Function to be called when messages are received.
The callback will pass two arguments, the header as a
dictionary structure, and the message.
... | https://github.com/DiamondLightSource/python-workflows/blob/7ef47b457655b96f4d2ef7ee9863cf1b6d20e023/workflows/transport/common_transport.py#L43-L73 |
DiamondLightSource/python-workflows | workflows/transport/common_transport.py | CommonTransport.unsubscribe | def unsubscribe(self, subscription, drop_callback_reference=False, **kwargs):
"""Stop listening to a queue or a broadcast
:param subscription: Subscription ID to cancel
:param drop_callback_reference: Drop the reference to the registered
callback function ... | python | def unsubscribe(self, subscription, drop_callback_reference=False, **kwargs):
"""Stop listening to a queue or a broadcast
:param subscription: Subscription ID to cancel
:param drop_callback_reference: Drop the reference to the registered
callback function ... | Stop listening to a queue or a broadcast
:param subscription: Subscription ID to cancel
:param drop_callback_reference: Drop the reference to the registered
callback function immediately. This
means any buffered messages sti... | https://github.com/DiamondLightSource/python-workflows/blob/7ef47b457655b96f4d2ef7ee9863cf1b6d20e023/workflows/transport/common_transport.py#L75-L95 |
DiamondLightSource/python-workflows | workflows/transport/common_transport.py | CommonTransport.drop_callback_reference | def drop_callback_reference(self, subscription):
"""Drop reference to the callback function after unsubscribing.
Any future messages arriving for that subscription will result in
exceptions being raised.
:param subscription: Subscription ID to delete callback reference for.
"""
... | python | def drop_callback_reference(self, subscription):
"""Drop reference to the callback function after unsubscribing.
Any future messages arriving for that subscription will result in
exceptions being raised.
:param subscription: Subscription ID to delete callback reference for.
"""
... | Drop reference to the callback function after unsubscribing.
Any future messages arriving for that subscription will result in
exceptions being raised.
:param subscription: Subscription ID to delete callback reference for. | https://github.com/DiamondLightSource/python-workflows/blob/7ef47b457655b96f4d2ef7ee9863cf1b6d20e023/workflows/transport/common_transport.py#L97-L111 |
DiamondLightSource/python-workflows | workflows/transport/common_transport.py | CommonTransport.subscribe_broadcast | def subscribe_broadcast(self, channel, callback, **kwargs):
"""Listen to a broadcast topic, notify via callback function.
:param channel: Topic name to subscribe to
:param callback: Function to be called when messages are received.
The callback will pass two arguments, t... | python | def subscribe_broadcast(self, channel, callback, **kwargs):
"""Listen to a broadcast topic, notify via callback function.
:param channel: Topic name to subscribe to
:param callback: Function to be called when messages are received.
The callback will pass two arguments, t... | Listen to a broadcast topic, notify via callback function.
:param channel: Topic name to subscribe to
:param callback: Function to be called when messages are received.
The callback will pass two arguments, the header as a
dictionary structure, and the m... | https://github.com/DiamondLightSource/python-workflows/blob/7ef47b457655b96f4d2ef7ee9863cf1b6d20e023/workflows/transport/common_transport.py#L113-L147 |
DiamondLightSource/python-workflows | workflows/transport/common_transport.py | CommonTransport.subscription_callback | def subscription_callback(self, subscription):
"""Retrieve the callback function for a subscription. Raise a
workflows.Error if the subscription does not exist.
All transport callbacks can be intercepted by setting an
interceptor function with subscription_callback_intercept().
:... | python | def subscription_callback(self, subscription):
"""Retrieve the callback function for a subscription. Raise a
workflows.Error if the subscription does not exist.
All transport callbacks can be intercepted by setting an
interceptor function with subscription_callback_intercept().
:... | Retrieve the callback function for a subscription. Raise a
workflows.Error if the subscription does not exist.
All transport callbacks can be intercepted by setting an
interceptor function with subscription_callback_intercept().
:param subscription: Subscription ID to look up
:re... | https://github.com/DiamondLightSource/python-workflows/blob/7ef47b457655b96f4d2ef7ee9863cf1b6d20e023/workflows/transport/common_transport.py#L149-L163 |
DiamondLightSource/python-workflows | workflows/transport/common_transport.py | CommonTransport.send | def send(self, destination, message, **kwargs):
"""Send a message to a queue.
:param destination: Queue name to send to
:param message: Either a string or a serializable object to be sent
:param **kwargs: Further parameters for the transport layer. For example
delay: Delay... | python | def send(self, destination, message, **kwargs):
"""Send a message to a queue.
:param destination: Queue name to send to
:param message: Either a string or a serializable object to be sent
:param **kwargs: Further parameters for the transport layer. For example
delay: Delay... | Send a message to a queue.
:param destination: Queue name to send to
:param message: Either a string or a serializable object to be sent
:param **kwargs: Further parameters for the transport layer. For example
delay: Delay transport of message by this many seconds
h... | https://github.com/DiamondLightSource/python-workflows/blob/7ef47b457655b96f4d2ef7ee9863cf1b6d20e023/workflows/transport/common_transport.py#L175-L187 |
DiamondLightSource/python-workflows | workflows/transport/common_transport.py | CommonTransport.raw_send | def raw_send(self, destination, message, **kwargs):
"""Send a raw (unmangled) message to a queue.
This may cause errors if the receiver expects a mangled message.
:param destination: Queue name to send to
:param message: Either a string or a serializable object to be sent
:param ... | python | def raw_send(self, destination, message, **kwargs):
"""Send a raw (unmangled) message to a queue.
This may cause errors if the receiver expects a mangled message.
:param destination: Queue name to send to
:param message: Either a string or a serializable object to be sent
:param ... | Send a raw (unmangled) message to a queue.
This may cause errors if the receiver expects a mangled message.
:param destination: Queue name to send to
:param message: Either a string or a serializable object to be sent
:param **kwargs: Further parameters for the transport layer. For examp... | https://github.com/DiamondLightSource/python-workflows/blob/7ef47b457655b96f4d2ef7ee9863cf1b6d20e023/workflows/transport/common_transport.py#L189-L201 |
DiamondLightSource/python-workflows | workflows/transport/common_transport.py | CommonTransport.broadcast | def broadcast(self, destination, message, **kwargs):
"""Broadcast a message.
:param destination: Topic name to send to
:param message: Either a string or a serializable object to be sent
:param **kwargs: Further parameters for the transport layer. For example
delay: Delay ... | python | def broadcast(self, destination, message, **kwargs):
"""Broadcast a message.
:param destination: Topic name to send to
:param message: Either a string or a serializable object to be sent
:param **kwargs: Further parameters for the transport layer. For example
delay: Delay ... | Broadcast a message.
:param destination: Topic name to send to
:param message: Either a string or a serializable object to be sent
:param **kwargs: Further parameters for the transport layer. For example
delay: Delay transport of message by this many seconds
headers... | https://github.com/DiamondLightSource/python-workflows/blob/7ef47b457655b96f4d2ef7ee9863cf1b6d20e023/workflows/transport/common_transport.py#L203-L215 |
DiamondLightSource/python-workflows | workflows/transport/common_transport.py | CommonTransport.raw_broadcast | def raw_broadcast(self, destination, message, **kwargs):
"""Broadcast a raw (unmangled) message.
This may cause errors if the receiver expects a mangled message.
:param destination: Topic name to send to
:param message: Either a string or a serializable object to be sent
:param *... | python | def raw_broadcast(self, destination, message, **kwargs):
"""Broadcast a raw (unmangled) message.
This may cause errors if the receiver expects a mangled message.
:param destination: Topic name to send to
:param message: Either a string or a serializable object to be sent
:param *... | Broadcast a raw (unmangled) message.
This may cause errors if the receiver expects a mangled message.
:param destination: Topic name to send to
:param message: Either a string or a serializable object to be sent
:param **kwargs: Further parameters for the transport layer. For example
... | https://github.com/DiamondLightSource/python-workflows/blob/7ef47b457655b96f4d2ef7ee9863cf1b6d20e023/workflows/transport/common_transport.py#L217-L229 |
DiamondLightSource/python-workflows | workflows/transport/common_transport.py | CommonTransport.ack | def ack(self, message, subscription_id=None, **kwargs):
"""Acknowledge receipt of a message. This only makes sense when the
'acknowledgement' flag was set for the relevant subscription.
:param message: ID of the message to be acknowledged, OR a dictionary
containing a fie... | python | def ack(self, message, subscription_id=None, **kwargs):
"""Acknowledge receipt of a message. This only makes sense when the
'acknowledgement' flag was set for the relevant subscription.
:param message: ID of the message to be acknowledged, OR a dictionary
containing a fie... | Acknowledge receipt of a message. This only makes sense when the
'acknowledgement' flag was set for the relevant subscription.
:param message: ID of the message to be acknowledged, OR a dictionary
containing a field 'message-id'.
:param subscription_id: ID of the associat... | https://github.com/DiamondLightSource/python-workflows/blob/7ef47b457655b96f4d2ef7ee9863cf1b6d20e023/workflows/transport/common_transport.py#L231-L258 |
DiamondLightSource/python-workflows | workflows/transport/common_transport.py | CommonTransport.nack | def nack(self, message, subscription_id=None, **kwargs):
"""Reject receipt of a message. This only makes sense when the
'acknowledgement' flag was set for the relevant subscription.
:param message: ID of the message to be rejected, OR a dictionary
containing a field 'mess... | python | def nack(self, message, subscription_id=None, **kwargs):
"""Reject receipt of a message. This only makes sense when the
'acknowledgement' flag was set for the relevant subscription.
:param message: ID of the message to be rejected, OR a dictionary
containing a field 'mess... | Reject receipt of a message. This only makes sense when the
'acknowledgement' flag was set for the relevant subscription.
:param message: ID of the message to be rejected, OR a dictionary
containing a field 'message-id'.
:param subscription_id: ID of the associated subscr... | https://github.com/DiamondLightSource/python-workflows/blob/7ef47b457655b96f4d2ef7ee9863cf1b6d20e023/workflows/transport/common_transport.py#L260-L285 |
DiamondLightSource/python-workflows | workflows/transport/common_transport.py | CommonTransport.transaction_begin | def transaction_begin(self, **kwargs):
"""Start a new transaction.
:param **kwargs: Further parameters for the transport layer. For example
:return: A transaction ID that can be passed to other functions.
"""
self.__transaction_id += 1
self.__transactions.add(self.__trans... | python | def transaction_begin(self, **kwargs):
"""Start a new transaction.
:param **kwargs: Further parameters for the transport layer. For example
:return: A transaction ID that can be passed to other functions.
"""
self.__transaction_id += 1
self.__transactions.add(self.__trans... | Start a new transaction.
:param **kwargs: Further parameters for the transport layer. For example
:return: A transaction ID that can be passed to other functions. | https://github.com/DiamondLightSource/python-workflows/blob/7ef47b457655b96f4d2ef7ee9863cf1b6d20e023/workflows/transport/common_transport.py#L287-L296 |
DiamondLightSource/python-workflows | workflows/transport/common_transport.py | CommonTransport.transaction_abort | def transaction_abort(self, transaction_id, **kwargs):
"""Abort a transaction and roll back all operations.
:param transaction_id: ID of transaction to be aborted.
:param **kwargs: Further parameters for the transport layer.
"""
if transaction_id not in self.__transactions:
... | python | def transaction_abort(self, transaction_id, **kwargs):
"""Abort a transaction and roll back all operations.
:param transaction_id: ID of transaction to be aborted.
:param **kwargs: Further parameters for the transport layer.
"""
if transaction_id not in self.__transactions:
... | Abort a transaction and roll back all operations.
:param transaction_id: ID of transaction to be aborted.
:param **kwargs: Further parameters for the transport layer. | https://github.com/DiamondLightSource/python-workflows/blob/7ef47b457655b96f4d2ef7ee9863cf1b6d20e023/workflows/transport/common_transport.py#L298-L307 |
DiamondLightSource/python-workflows | workflows/transport/common_transport.py | CommonTransport.transaction_commit | def transaction_commit(self, transaction_id, **kwargs):
"""Commit a transaction.
:param transaction_id: ID of transaction to be committed.
:param **kwargs: Further parameters for the transport layer.
"""
if transaction_id not in self.__transactions:
raise workflows.Er... | python | def transaction_commit(self, transaction_id, **kwargs):
"""Commit a transaction.
:param transaction_id: ID of transaction to be committed.
:param **kwargs: Further parameters for the transport layer.
"""
if transaction_id not in self.__transactions:
raise workflows.Er... | Commit a transaction.
:param transaction_id: ID of transaction to be committed.
:param **kwargs: Further parameters for the transport layer. | https://github.com/DiamondLightSource/python-workflows/blob/7ef47b457655b96f4d2ef7ee9863cf1b6d20e023/workflows/transport/common_transport.py#L309-L318 |
cuihantao/andes | andes/filters/matpower.py | read | def read(file, system):
"""Read a MATPOWER data file into mpc and build andes device elements"""
func = re.compile('function\\s')
mva = re.compile('\\s*mpc.baseMVA\\s*=\\s*')
bus = re.compile('\\s*mpc.bus\\s*=\\s*\\[')
gen = re.compile('\\s*mpc.gen\\s*=\\s*\\[')
branch = re.compile('\\s*mpc.bran... | python | def read(file, system):
"""Read a MATPOWER data file into mpc and build andes device elements"""
func = re.compile('function\\s')
mva = re.compile('\\s*mpc.baseMVA\\s*=\\s*')
bus = re.compile('\\s*mpc.bus\\s*=\\s*\\[')
gen = re.compile('\\s*mpc.gen\\s*=\\s*\\[')
branch = re.compile('\\s*mpc.bran... | Read a MATPOWER data file into mpc and build andes device elements | https://github.com/cuihantao/andes/blob/7067898d4f26ce7534e968b8486c4aa8fe3a511a/andes/filters/matpower.py#L14-L250 |
cuihantao/andes | andes/models/shunt.py | Shunt.full_y | def full_y(self, Y):
"""Add self(shunt) into full Jacobian Y"""
if not self.n:
return
Ysh = matrix(self.g,
(self.n, 1), 'd') + 1j * matrix(self.b, (self.n, 1), 'd')
uYsh = mul(self.u, Ysh)
Y += spmatrix(uYsh, self.a, self.a, Y.size, 'z') | python | def full_y(self, Y):
"""Add self(shunt) into full Jacobian Y"""
if not self.n:
return
Ysh = matrix(self.g,
(self.n, 1), 'd') + 1j * matrix(self.b, (self.n, 1), 'd')
uYsh = mul(self.u, Ysh)
Y += spmatrix(uYsh, self.a, self.a, Y.size, 'z') | Add self(shunt) into full Jacobian Y | https://github.com/cuihantao/andes/blob/7067898d4f26ce7534e968b8486c4aa8fe3a511a/andes/models/shunt.py#L51-L58 |
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(se... | python | 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(se... | Import and instantiate this JIT object
Returns
------- | https://github.com/cuihantao/andes/blob/7067898d4f26ce7534e968b8486c4aa8fe3a511a/andes/models/jit.py#L20-L49 |
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):
"""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) | overloading elem_add function of a JIT class | https://github.com/cuihantao/andes/blob/7067898d4f26ce7534e968b8486c4aa8fe3a511a/andes/models/jit.py#L56-L61 |
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):
"""Subscribe to a channel. Received messages must be acknowledged."""
self.subid = self._transport.subscribe(
"transient.transaction", self.receive_message, acknowledgement=True
) | Subscribe to a channel. Received messages must be acknowledged. | https://github.com/DiamondLightSource/python-workflows/blob/7ef47b457655b96f4d2ef7ee9863cf1b6d20e023/workflows/services/sample_transaction.py#L19-L23 |
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. T... | python | 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. T... | Receive a message | https://github.com/DiamondLightSource/python-workflows/blob/7ef47b457655b96f4d2ef7ee9863cf1b6d20e023/workflows/services/sample_transaction.py#L31-L65 |
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.... | python | 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.... | Create and send a unique message for this service. | https://github.com/DiamondLightSource/python-workflows/blob/7ef47b457655b96f4d2ef7ee9863cf1b6d20e023/workflows/services/sample_transaction.py#L85-L93 |
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... | python | 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... | get elapsed time from the give time
Returns:
now: the absolute time now
dt_str: elapsed time in string | https://github.com/cuihantao/andes/blob/7067898d4f26ce7534e968b8486c4aa8fe3a511a/andes/utils/time.py#L5-L19 |
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__... | python | 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__... | Set a flag to 0 if the corresponding value is 0 | https://github.com/cuihantao/andes/blob/7067898d4f26ce7534e968b8486c4aa8fe3a511a/andes/models/pss.py#L139-L148 |
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... | python | 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... | Update the summary data
Parameters
----------
system
Returns
-------
None | https://github.com/cuihantao/andes/blob/7067898d4f26ce7534e968b8486c4aa8fe3a511a/andes/variables/report.py#L64-L85 |
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.up... | python | 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.up... | Update the extended data | https://github.com/cuihantao/andes/blob/7067898d4f26ce7534e968b8486c4aa8fe3a511a/andes/variables/report.py#L87-L128 |
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.... | python | 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 values based on the requested content
Parameters
----------
content
Returns
------- | https://github.com/cuihantao/andes/blob/7067898d4f26ce7534e968b8486c4aa8fe3a511a/andes/variables/report.py#L130-L147 |
cuihantao/andes | andes/variables/report.py | Report.write | def write(self, content=None):
"""
Write report to file.
Parameters
----------
content: str
'summary', 'extended', 'powerflow'
"""
if self.system.files.no_output is True:
return
t, _ = elapsed()
if not content:
... | python | def write(self, content=None):
"""
Write report to file.
Parameters
----------
content: str
'summary', 'extended', 'powerflow'
"""
if self.system.files.no_output is True:
return
t, _ = elapsed()
if not content:
... | Write report to file.
Parameters
----------
content: str
'summary', 'extended', 'powerflow' | https://github.com/cuihantao/andes/blob/7067898d4f26ce7534e968b8486c4aa8fe3a511a/andes/variables/report.py#L149-L264 |
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.
"""
i... | python | 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.
"""
i... | 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. | https://github.com/DiamondLightSource/python-workflows/blob/7ef47b457655b96f4d2ef7ee9863cf1b6d20e023/workflows/recipe/wrapper.py#L40-L70 |
DiamondLightSource/python-workflows | workflows/recipe/wrapper.py | RecipeWrapper.start | def start(self, header=None, **kwargs):
"""Trigger the start of a recipe, sending the defined payloads to the
recipients set in the recipe. Any parameters to this function are
passed to the transport send/broadcast methods.
If the wrapped recipe has already been started then a ValueError... | python | def start(self, header=None, **kwargs):
"""Trigger the start of a recipe, sending the defined payloads to the
recipients set in the recipe. Any parameters to this function are
passed to the transport send/broadcast methods.
If the wrapped recipe has already been started then a ValueError... | Trigger the start of a recipe, sending the defined payloads to the
recipients set in the recipe. Any parameters to this function are
passed to the transport send/broadcast methods.
If the wrapped recipe has already been started then a ValueError will
be raised. | https://github.com/DiamondLightSource/python-workflows/blob/7ef47b457655b96f4d2ef7ee9863cf1b6d20e023/workflows/recipe/wrapper.py#L111-L128 |
DiamondLightSource/python-workflows | workflows/recipe/wrapper.py | RecipeWrapper.checkpoint | def checkpoint(self, message, header=None, delay=0, **kwargs):
"""Send a message to the current recipe destination. This can be used to
keep a state for longer processing tasks.
:param delay: Delay transport of message by this many seconds
"""
if not self.transport:
r... | python | def checkpoint(self, message, header=None, delay=0, **kwargs):
"""Send a message to the current recipe destination. This can be used to
keep a state for longer processing tasks.
:param delay: Delay transport of message by this many seconds
"""
if not self.transport:
r... | Send a message to the current recipe destination. This can be used to
keep a state for longer processing tasks.
:param delay: Delay transport of message by this many seconds | https://github.com/DiamondLightSource/python-workflows/blob/7ef47b457655b96f4d2ef7ee9863cf1b6d20e023/workflows/recipe/wrapper.py#L130-L151 |
DiamondLightSource/python-workflows | workflows/recipe/wrapper.py | RecipeWrapper.apply_parameters | def apply_parameters(self, parameters):
"""Recursively apply parameter replacement (see recipe.py) to the wrapped
recipe, updating internal references afterwards.
While this operation is useful for testing it should not be used in
production. Replacing parameters means that the recipe ch... | python | def apply_parameters(self, parameters):
"""Recursively apply parameter replacement (see recipe.py) to the wrapped
recipe, updating internal references afterwards.
While this operation is useful for testing it should not be used in
production. Replacing parameters means that the recipe ch... | Recursively apply parameter replacement (see recipe.py) to the wrapped
recipe, updating internal references afterwards.
While this operation is useful for testing it should not be used in
production. Replacing parameters means that the recipe changes as it is
passed down the chain of ser... | https://github.com/DiamondLightSource/python-workflows/blob/7ef47b457655b96f4d2ef7ee9863cf1b6d20e023/workflows/recipe/wrapper.py#L153-L161 |
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_... | python | 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_... | Factory function to generate independent message objects for
downstream recipients with different destinations. | https://github.com/DiamondLightSource/python-workflows/blob/7ef47b457655b96f4d2ef7ee9863cf1b6d20e023/workflows/recipe/wrapper.py#L163-L177 |
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,)
... | python | 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,)
... | Send messages to a list of numbered destinations. This is an internal
helper method used by the public 'send' methods. | https://github.com/DiamondLightSource/python-workflows/blob/7ef47b457655b96f4d2ef7ee9863cf1b6d20e023/workflows/recipe/wrapper.py#L179-L186 |
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:
... | python | 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:
... | Helper function to send a message to a specific recipe destination. | https://github.com/DiamondLightSource/python-workflows/blob/7ef47b457655b96f4d2ef7ee9863cf1b6d20e023/workflows/recipe/wrapper.py#L188-L217 |
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=meta... | 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=meta... | Runs when a message event is received
Args:
event: RTM API event.
Returns:
Legobot.messge | https://github.com/Legobot/Legobot/blob/d13da172960a149681cb5151ce34b2f3a58ad32b/Legobot/Connectors/Slack.py#L75-L93 |
Legobot/Legobot | Legobot/Connectors/Slack.py | RtmBot.run | def run(self):
'''Extends the run() method of threading.Thread
'''
self.connect()
while True:
for event in self.slack_client.rtm_read():
logger.debug(event)
if 'type' in event and event['type'] in self.supported_events:
eve... | python | def run(self):
'''Extends the run() method of threading.Thread
'''
self.connect()
while True:
for event in self.slack_client.rtm_read():
logger.debug(event)
if 'type' in event and event['type'] in self.supported_events:
eve... | Extends the run() method of threading.Thread | https://github.com/Legobot/Legobot/blob/d13da172960a149681cb5151ce34b2f3a58ad32b/Legobot/Connectors/Slack.py#L95-L111 |
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
... | 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
... | 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. | https://github.com/Legobot/Legobot/blob/d13da172960a149681cb5151ce34b2f3a58ad32b/Legobot/Connectors/Slack.py#L113-L131 |
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.
... | 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.
... | 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. | https://github.com/Legobot/Legobot/blob/d13da172960a149681cb5151ce34b2f3a58ad32b/Legobot/Connectors/Slack.py#L133-L150 |
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
... | 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
... | 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 | https://github.com/Legobot/Legobot/blob/d13da172960a149681cb5151ce34b2f3a58ad32b/Legobot/Connectors/Slack.py#L182-L202 |
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
... | 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
... | 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... | https://github.com/Legobot/Legobot/blob/d13da172960a149681cb5151ce34b2f3a58ad32b/Legobot/Connectors/Slack.py#L204-L227 |
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('u... | 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('u... | 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 | https://github.com/Legobot/Legobot/blob/d13da172960a149681cb5151ce34b2f3a58ad32b/Legobot/Connectors/Slack.py#L229-L246 |
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)
... | 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)
... | 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 | https://github.com/Legobot/Legobot/blob/d13da172960a149681cb5151ce34b2f3a58ad32b/Legobot/Connectors/Slack.py#L248-L259 |
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 userna... | 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 userna... | 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 | https://github.com/Legobot/Legobot/blob/d13da172960a149681cb5151ce34b2f3a58ad32b/Legobot/Connectors/Slack.py#L264-L289 |
Legobot/Legobot | Legobot/Connectors/Slack.py | RtmBot.get_userid_from_botid | def get_userid_from_botid(self, botid):
'''Perform a lookup of bots.info to resolve a botid to a userid
Args:
botid (string): Slack botid to lookup.
Returns:
string: userid value
'''
botinfo = self.slack_client.api_call('bots.info', bot=botid)
if ... | python | def get_userid_from_botid(self, botid):
'''Perform a lookup of bots.info to resolve a botid to a userid
Args:
botid (string): Slack botid to lookup.
Returns:
string: userid value
'''
botinfo = self.slack_client.api_call('bots.info', bot=botid)
if ... | Perform a lookup of bots.info to resolve a botid to a userid
Args:
botid (string): Slack botid to lookup.
Returns:
string: userid value | https://github.com/Legobot/Legobot/blob/d13da172960a149681cb5151ce34b2f3a58ad32b/Legobot/Connectors/Slack.py#L291-L303 |
Legobot/Legobot | Legobot/Connectors/Slack.py | RtmBot._parse_metadata | def _parse_metadata(self, message):
'''Parse incoming messages to build metadata dict
Lots of 'if' statements. It sucks, I know.
Args:
message (dict): JSON dump of message sent from Slack
Returns:
Legobot.Metadata
'''
# Try to handle all the fie... | python | def _parse_metadata(self, message):
'''Parse incoming messages to build metadata dict
Lots of 'if' statements. It sucks, I know.
Args:
message (dict): JSON dump of message sent from Slack
Returns:
Legobot.Metadata
'''
# Try to handle all the fie... | Parse incoming messages to build metadata dict
Lots of 'if' statements. It sucks, I know.
Args:
message (dict): JSON dump of message sent from Slack
Returns:
Legobot.Metadata | https://github.com/Legobot/Legobot/blob/d13da172960a149681cb5151ce34b2f3a58ad32b/Legobot/Connectors/Slack.py#L305-L356 |
Legobot/Legobot | Legobot/Connectors/Slack.py | Slack.build_attachment | def build_attachment(self, text, target, attachment, thread):
'''Builds a slack attachment.
Args:
message (Legobot.Message): message w/ metadata to send.
Returns:
attachment (dict): attachment data.
'''
attachment = {
'as_user': True,
... | python | def build_attachment(self, text, target, attachment, thread):
'''Builds a slack attachment.
Args:
message (Legobot.Message): message w/ metadata to send.
Returns:
attachment (dict): attachment data.
'''
attachment = {
'as_user': True,
... | Builds a slack attachment.
Args:
message (Legobot.Message): message w/ metadata to send.
Returns:
attachment (dict): attachment data. | https://github.com/Legobot/Legobot/blob/d13da172960a149681cb5151ce34b2f3a58ad32b/Legobot/Connectors/Slack.py#L403-L426 |
Legobot/Legobot | Legobot/Connectors/Slack.py | Slack.handle | def handle(self, message):
'''Attempts to send a message to the specified destination in Slack.
Extends Legobot.Lego.handle()
Args:
message (Legobot.Message): message w/ metadata to send.
'''
logger.debug(message)
if Utilities.isNotEmpty(message['metadata'][... | python | def handle(self, message):
'''Attempts to send a message to the specified destination in Slack.
Extends Legobot.Lego.handle()
Args:
message (Legobot.Message): message w/ metadata to send.
'''
logger.debug(message)
if Utilities.isNotEmpty(message['metadata'][... | Attempts to send a message to the specified destination in Slack.
Extends Legobot.Lego.handle()
Args:
message (Legobot.Message): message w/ metadata to send. | https://github.com/Legobot/Legobot/blob/d13da172960a149681cb5151ce34b2f3a58ad32b/Legobot/Connectors/Slack.py#L428-L487 |
cuihantao/andes | andes/filters/__init__.py | guess | def guess(system):
"""
input format guess function. First guess by extension, then test by lines
"""
files = system.files
maybe = []
if files.input_format:
maybe.append(files.input_format)
# first, guess by extension
for key, val in input_formats.items():
if type(val) == ... | python | def guess(system):
"""
input format guess function. First guess by extension, then test by lines
"""
files = system.files
maybe = []
if files.input_format:
maybe.append(files.input_format)
# first, guess by extension
for key, val in input_formats.items():
if type(val) == ... | input format guess function. First guess by extension, then test by lines | https://github.com/cuihantao/andes/blob/7067898d4f26ce7534e968b8486c4aa8fe3a511a/andes/filters/__init__.py#L32-L85 |
cuihantao/andes | andes/filters/__init__.py | parse | def parse(system):
"""
Parse input file with the given format in system.files.input_format
"""
t, _ = elapsed()
input_format = system.files.input_format
add_format = system.files.add_format
# exit when no input format is given
if not input_format:
logger.error(
'No ... | python | def parse(system):
"""
Parse input file with the given format in system.files.input_format
"""
t, _ = elapsed()
input_format = system.files.input_format
add_format = system.files.add_format
# exit when no input format is given
if not input_format:
logger.error(
'No ... | Parse input file with the given format in system.files.input_format | https://github.com/cuihantao/andes/blob/7067898d4f26ce7534e968b8486c4aa8fe3a511a/andes/filters/__init__.py#L88-L151 |
cuihantao/andes | andes/routines/eig.py | EIG.calc_state_matrix | def calc_state_matrix(self):
"""
Return state matrix and store to ``self.As``
Returns
-------
matrix
state matrix
"""
system = self.system
Gyx = matrix(system.dae.Gx)
self.solver.linsolve(system.dae.Gy, Gyx)
self.As = matrix(... | python | def calc_state_matrix(self):
"""
Return state matrix and store to ``self.As``
Returns
-------
matrix
state matrix
"""
system = self.system
Gyx = matrix(system.dae.Gx)
self.solver.linsolve(system.dae.Gy, Gyx)
self.As = matrix(... | Return state matrix and store to ``self.As``
Returns
-------
matrix
state matrix | https://github.com/cuihantao/andes/blob/7067898d4f26ce7534e968b8486c4aa8fe3a511a/andes/routines/eig.py#L39-L63 |
cuihantao/andes | andes/routines/eig.py | EIG.calc_eigvals | def calc_eigvals(self):
"""
Solve eigenvalues of the state matrix ``self.As``
Returns
-------
None
"""
self.eigs = numpy.linalg.eigvals(self.As)
# TODO: use scipy.sparse.linalg.eigs(self.As)
return self.eigs | python | def calc_eigvals(self):
"""
Solve eigenvalues of the state matrix ``self.As``
Returns
-------
None
"""
self.eigs = numpy.linalg.eigvals(self.As)
# TODO: use scipy.sparse.linalg.eigs(self.As)
return self.eigs | Solve eigenvalues of the state matrix ``self.As``
Returns
-------
None | https://github.com/cuihantao/andes/blob/7067898d4f26ce7534e968b8486c4aa8fe3a511a/andes/routines/eig.py#L65-L76 |
cuihantao/andes | andes/routines/eig.py | EIG.calc_part_factor | def calc_part_factor(self):
"""
Compute participation factor of states in eigenvalues
Returns
-------
"""
mu, N = numpy.linalg.eig(self.As)
# TODO: use scipy.sparse.linalg.eigs(self.As)
N = matrix(N)
n = len(mu)
idx = range(n)
W... | python | def calc_part_factor(self):
"""
Compute participation factor of states in eigenvalues
Returns
-------
"""
mu, N = numpy.linalg.eig(self.As)
# TODO: use scipy.sparse.linalg.eigs(self.As)
N = matrix(N)
n = len(mu)
idx = range(n)
W... | Compute participation factor of states in eigenvalues
Returns
------- | https://github.com/cuihantao/andes/blob/7067898d4f26ce7534e968b8486c4aa8fe3a511a/andes/routines/eig.py#L78-L112 |
cuihantao/andes | andes/routines/eig.py | EIG.dump_results | def dump_results(self):
"""
Save eigenvalue analysis reports
Returns
-------
None
"""
system = self.system
mu = self.mu
partfact = self.part_fact
if system.files.no_output:
return
text = []
header = []
... | python | def dump_results(self):
"""
Save eigenvalue analysis reports
Returns
-------
None
"""
system = self.system
mu = self.mu
partfact = self.part_fact
if system.files.no_output:
return
text = []
header = []
... | Save eigenvalue analysis reports
Returns
-------
None | https://github.com/cuihantao/andes/blob/7067898d4f26ce7534e968b8486c4aa8fe3a511a/andes/routines/eig.py#L186-L286 |
cuihantao/andes | andes/models/breaker.py | Breaker.get_times | def get_times(self):
"""Return all the action times and times-1e-6 in a list"""
if not self.n:
return []
self.times = list(mul(self.u1, self.t1)) + \
list(mul(self.u2, self.t2)) + \
list(mul(self.u3, self.t3)) + \
list(mul(self.u4, self.t4))
... | python | def get_times(self):
"""Return all the action times and times-1e-6 in a list"""
if not self.n:
return []
self.times = list(mul(self.u1, self.t1)) + \
list(mul(self.u2, self.t2)) + \
list(mul(self.u3, self.t3)) + \
list(mul(self.u4, self.t4))
... | Return all the action times and times-1e-6 in a list | https://github.com/cuihantao/andes/blob/7067898d4f26ce7534e968b8486c4aa8fe3a511a/andes/models/breaker.py#L75-L86 |
Legobot/Legobot | Legobot/Connectors/Discord.py | Heartbeat.send | def send(self, ws, seq):
"""
Sends heartbeat message to Discord
Attributes:
ws: Websocket connection to discord
seq: Sequence number of heartbeat
"""
payload = {'op': 1, 'd': seq}
payload = json.dumps(payload)
logger.debug("Sending heartb... | python | def send(self, ws, seq):
"""
Sends heartbeat message to Discord
Attributes:
ws: Websocket connection to discord
seq: Sequence number of heartbeat
"""
payload = {'op': 1, 'd': seq}
payload = json.dumps(payload)
logger.debug("Sending heartb... | Sends heartbeat message to Discord
Attributes:
ws: Websocket connection to discord
seq: Sequence number of heartbeat | https://github.com/Legobot/Legobot/blob/d13da172960a149681cb5151ce34b2f3a58ad32b/Legobot/Connectors/Discord.py#L37-L50 |
Legobot/Legobot | Legobot/Connectors/Discord.py | DiscoBot.create_message | def create_message(self, channel_id, text):
"""
Sends a message to a Discord channel or user via REST API
Args:
channel_id (string): ID of destingation Discord channel
text (string): Content of message
"""
baseurl = self.rest_baseurl + \
'/ch... | python | def create_message(self, channel_id, text):
"""
Sends a message to a Discord channel or user via REST API
Args:
channel_id (string): ID of destingation Discord channel
text (string): Content of message
"""
baseurl = self.rest_baseurl + \
'/ch... | Sends a message to a Discord channel or user via REST API
Args:
channel_id (string): ID of destingation Discord channel
text (string): Content of message | https://github.com/Legobot/Legobot/blob/d13da172960a149681cb5151ce34b2f3a58ad32b/Legobot/Connectors/Discord.py#L109-L122 |
Legobot/Legobot | Legobot/Connectors/Discord.py | DiscoBot.identify | def identify(self, token):
"""
Identifies to the websocket endpoint
Args:
token (string): Discord bot token
"""
payload = {
'op': 2,
'd': {
'token': self.token,
'properties': {
'$os': sys.pl... | python | def identify(self, token):
"""
Identifies to the websocket endpoint
Args:
token (string): Discord bot token
"""
payload = {
'op': 2,
'd': {
'token': self.token,
'properties': {
'$os': sys.pl... | Identifies to the websocket endpoint
Args:
token (string): Discord bot token | https://github.com/Legobot/Legobot/blob/d13da172960a149681cb5151ce34b2f3a58ad32b/Legobot/Connectors/Discord.py#L124-L149 |
Legobot/Legobot | Legobot/Connectors/Discord.py | DiscoBot.on_hello | def on_hello(self, message):
"""
Runs on a hello event from websocket connection
Args:
message (dict): Full message from Discord websocket connection"
"""
logger.info("Got a hello")
self.identify(self.token)
self.heartbeat_thread = Heartbeat(self.ws,... | python | def on_hello(self, message):
"""
Runs on a hello event from websocket connection
Args:
message (dict): Full message from Discord websocket connection"
"""
logger.info("Got a hello")
self.identify(self.token)
self.heartbeat_thread = Heartbeat(self.ws,... | Runs on a hello event from websocket connection
Args:
message (dict): Full message from Discord websocket connection" | https://github.com/Legobot/Legobot/blob/d13da172960a149681cb5151ce34b2f3a58ad32b/Legobot/Connectors/Discord.py#L151-L164 |
Legobot/Legobot | Legobot/Connectors/Discord.py | DiscoBot.on_heartbeat | def on_heartbeat(self, message):
"""
Runs on a heartbeat event from websocket connection
Args:
message (dict): Full message from Discord websocket connection"
"""
logger.info("Got a heartbeat")
logger.info("Heartbeat message: {}".format(message))
sel... | python | def on_heartbeat(self, message):
"""
Runs on a heartbeat event from websocket connection
Args:
message (dict): Full message from Discord websocket connection"
"""
logger.info("Got a heartbeat")
logger.info("Heartbeat message: {}".format(message))
sel... | Runs on a heartbeat event from websocket connection
Args:
message (dict): Full message from Discord websocket connection" | https://github.com/Legobot/Legobot/blob/d13da172960a149681cb5151ce34b2f3a58ad32b/Legobot/Connectors/Discord.py#L166-L177 |
Legobot/Legobot | Legobot/Connectors/Discord.py | DiscoBot.on_message | def on_message(self, message):
"""
Runs on a create_message event from websocket connection
Args:
message (dict): Full message from Discord websocket connection"
"""
if 'content' in message['d']:
metadata = self._parse_metadata(message)
messa... | python | def on_message(self, message):
"""
Runs on a create_message event from websocket connection
Args:
message (dict): Full message from Discord websocket connection"
"""
if 'content' in message['d']:
metadata = self._parse_metadata(message)
messa... | Runs on a create_message event from websocket connection
Args:
message (dict): Full message from Discord websocket connection" | https://github.com/Legobot/Legobot/blob/d13da172960a149681cb5151ce34b2f3a58ad32b/Legobot/Connectors/Discord.py#L179-L192 |
Legobot/Legobot | Legobot/Connectors/Discord.py | DiscoBot._parse_metadata | def _parse_metadata(self, message):
"""
Sets metadata in Legobot message
Args:
message (dict): Full message from Discord websocket connection"
Returns:
Legobot.Metadata
"""
metadata = Metadata(source=self.actor_urn).__dict__
if 'author' ... | python | def _parse_metadata(self, message):
"""
Sets metadata in Legobot message
Args:
message (dict): Full message from Discord websocket connection"
Returns:
Legobot.Metadata
"""
metadata = Metadata(source=self.actor_urn).__dict__
if 'author' ... | Sets metadata in Legobot message
Args:
message (dict): Full message from Discord websocket connection"
Returns:
Legobot.Metadata | https://github.com/Legobot/Legobot/blob/d13da172960a149681cb5151ce34b2f3a58ad32b/Legobot/Connectors/Discord.py#L194-L219 |
Legobot/Legobot | Legobot/Connectors/Discord.py | DiscoBot.handle | def handle(self, message):
"""
Dispatches messages to appropriate handler based on opcode
Args:
message (dict): Full message from Discord websocket connection
"""
opcode = message['op']
if opcode == 10:
self.on_hello(message)
elif opcode ... | python | def handle(self, message):
"""
Dispatches messages to appropriate handler based on opcode
Args:
message (dict): Full message from Discord websocket connection
"""
opcode = message['op']
if opcode == 10:
self.on_hello(message)
elif opcode ... | Dispatches messages to appropriate handler based on opcode
Args:
message (dict): Full message from Discord websocket connection | https://github.com/Legobot/Legobot/blob/d13da172960a149681cb5151ce34b2f3a58ad32b/Legobot/Connectors/Discord.py#L227-L244 |
Legobot/Legobot | Legobot/Connectors/Discord.py | DiscoBot.run | def run(self):
"""
Overrides run method of threading.Thread.
Called by DiscoBot.start(), inherited from threading.Thread
"""
self.ws = self.connect()
while True:
try:
data = json.loads(self.ws.recv())
self.handle(data)
... | python | def run(self):
"""
Overrides run method of threading.Thread.
Called by DiscoBot.start(), inherited from threading.Thread
"""
self.ws = self.connect()
while True:
try:
data = json.loads(self.ws.recv())
self.handle(data)
... | Overrides run method of threading.Thread.
Called by DiscoBot.start(), inherited from threading.Thread | https://github.com/Legobot/Legobot/blob/d13da172960a149681cb5151ce34b2f3a58ad32b/Legobot/Connectors/Discord.py#L246-L258 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.