code
string
signature
string
docstring
string
loss_without_docstring
float64
loss_with_docstring
float64
factor
float64
Vm = self.system.dae.y[self.v] Va = self.system.dae.y[self.a] return polar(Vm[self.a2], Va[self.a2])
def v2(self)
Return voltage phasors at the "to buses" (bus2)
7.318374
5.910769
1.238143
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)
switch the status of Line idx
15.872754
13.134926
1.208439
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( listname='unamey', xy_idx=xy_idx, var_name='Pij', element_name=self.name) self.system.varname.append( listname='fnamey', xy_idx=xy_idx, var_name='P_{ij}', element_name=self.name) # Pji xy_idx = range(mpq + nl, mpq + 2 * nl) self.system.varname.append( listname='unamey', xy_idx=xy_idx, var_name='Pji', element_name=self.name) self.system.varname.append( listname='fnamey', xy_idx=xy_idx, var_name='P_{ji}', element_name=self.name) # Qij xy_idx = range(mpq + 2 * nl, mpq + 3 * nl) self.system.varname.append( listname='unamey', xy_idx=xy_idx, var_name='Qij', element_name=self.name) self.system.varname.append( listname='fnamey', xy_idx=xy_idx, var_name='Q_{ij}', element_name=self.name) # Qji xy_idx = range(mpq + 3 * nl, mpq + 4 * nl) self.system.varname.append( listname='unamey', xy_idx=xy_idx, var_name='Qji', element_name=self.name) self.system.varname.append( listname='fnamey', xy_idx=xy_idx, var_name='Q_{ji}', element_name=self.name) # Iij Real xy_idx = range(mpq + 4 * nl, mpq + 5 * nl) self.system.varname.append( listname='unamey', xy_idx=xy_idx, var_name='Iij_Re', element_name=self.name) self.system.varname.append( listname='fnamey', xy_idx=xy_idx, var_name='\\Re(I_{ij})', element_name=self.name) # Iij Imag xy_idx = range(mpq + 5 * nl, mpq + 6 * nl) self.system.varname.append( listname='unamey', xy_idx=xy_idx, var_name='Iij_Im', element_name=self.name) self.system.varname.append( listname='fnamey', xy_idx=xy_idx, var_name='\\Im(I_{ij})', element_name=self.name) # Iji Real xy_idx = range(mpq + 6 * nl, mpq + 7 * nl) self.system.varname.append( listname='unamey', xy_idx=xy_idx, var_name='Iji_Re', element_name=self.name) self.system.varname.append( listname='fnamey', xy_idx=xy_idx, var_name='\\Re(I_{ji})', element_name=self.name) # Iji Imag xy_idx = range(mpq + 7 * nl, mpq + 8 * nl) self.system.varname.append( listname='unamey', xy_idx=xy_idx, var_name='Iji_Im', element_name=self.name) self.system.varname.append( listname='fnamey', xy_idx=xy_idx, var_name='\\Im(I_{ji})', element_name=self.name)
def _varname_flow(self)
Build variable names for Pij, Pji, Qij, Qji, Sij, Sji
1.415877
1.378361
1.027219
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)
Return seriesflow based on the external idx on the `bus` side
2.175023
2.146079
1.013487
# 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)
Return leaf bus idx, line idx, and the line foreign key Returns ------- (list, list, list) or DataFrame
4.330393
3.798107
1.140145
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)
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`
3.116817
2.903828
1.073348
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: self.unamex.extend([''] * xext) self.fnamex.extend([''] * xext)
def resize(self)
Resize (extend) the list for variable names
2.983856
2.801812
1.064974
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)
Extend `unamey` and `fnamey` for bus injections and line flows
7.105388
5.396403
1.31669
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)
Append variable names to the name lists
4.354812
4.294639
1.014011
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)
Append bus injection and line flow names to `varname`
17.921675
10.007618
1.790803
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)
Return variable names for the given indices :param yidx: :param xidx: :return:
2.870815
2.921149
0.982769
if not hasattr(get_known_services, "cache"): setattr( get_known_services, "cache", { e.name: e.load() for e in pkg_resources.iter_entry_points("workflows.services") }, ) register = get_known_services.cache.copy() return register
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 factory is a function that takes no arguments and returns an uninstantiated service class. This will avoid importing all service classes.
3.683178
3.539325
1.040644
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()
command line input parser
2.431638
2.412513
1.007927
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)
Add plots to an existing plot
2.595372
2.567317
1.010928
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)
Check initialization by comparing t=0 and t=end values
3.800006
3.423071
1.110116
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)
Load the lst file into internal data structures
3.747838
3.506667
1.068775
# 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)
Return variable names and indices matching ``query``
3.916055
3.875189
1.010546
try: data = np.loadtxt(self._dat_file, delimiter=',') except ValueError: data = np.loadtxt(self._dat_file) self._data = data
def load_dat(self, delimiter=',')
Load the dat file into internal data structures, ``self._data``
3.02887
3.023318
1.001836
if isinstance(idx, list): idx = np.array(idx, dtype=int) return self._data[:, idx]
def get_values(self, idx)
Return the variable values at the given indices
4.520028
3.85023
1.173963
header = self._uname if not formatted else self._fname return [header[x] for x in idx]
def get_header(self, idx, formatted=False)
Return a list of the variable names at the given indices
9.93535
7.368437
1.348366
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')
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
2.652094
2.956842
0.896935
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)
automatic styling according to _row_size 76 characters in a row
2.065826
1.782128
1.159191
sp = ' ' * nspace for item in self._rows: item[0] = sp + item[0]
def add_left_space(self, nspace=1)
elem_add n cols of spaces before the first col. (for texttable 0.8.3)
5.995852
4.921463
1.218307
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)
generate texttable formatted string
6.641047
5.960825
1.114115
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)
auto fit column width
2.706399
2.59695
1.042145
self.__subscription_id += 1 def mangled_callback(header, message): return callback(header, self._mangle_for_receiving(message)) if "disable_mangling" in kwargs: if kwargs["disable_mangling"]: mangled_callback = callback del kwargs["disable_mangling"] self.__subscriptions[self.__subscription_id] = { "channel": channel, "callback": mangled_callback, "ack": kwargs.get("acknowledgement"), "unsubscribed": False, } self.log.debug("Subscribing to %s with ID %d", channel, self.__subscription_id) self._subscribe(self.__subscription_id, channel, mangled_callback, **kwargs) return self.__subscription_id
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 dictionary structure, and the message. :param **kwargs: Further parameters for the transport layer. For example disable_mangling: Receive messages as unprocessed strings. exclusive: Attempt to become exclusive subscriber to the queue. acknowledgement: If true receipt of each message needs to be acknowledged. :return: A unique subscription ID
2.917994
2.559369
1.140123
if subscription not in self.__subscriptions: raise workflows.Error("Attempting to unsubscribe unknown subscription") if self.__subscriptions[subscription]["unsubscribed"]: raise workflows.Error( "Attempting to unsubscribe already unsubscribed subscription" ) self._unsubscribe(subscription, **kwargs) self.__subscriptions[subscription]["unsubscribed"] = True if drop_callback_reference: self.drop_callback_reference(subscription)
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 immediately. This means any buffered messages still in flight will not arrive at the intended destination and cause exceptions to be raised instead. :param **kwargs: Further parameters for the transport layer.
2.845482
3.23198
0.880414
if subscription not in self.__subscriptions: raise workflows.Error( "Attempting to drop callback reference for unknown subscription" ) if not self.__subscriptions[subscription]["unsubscribed"]: raise workflows.Error( "Attempting to drop callback reference for live subscription" ) del self.__subscriptions[subscription]
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.
4.072871
3.88716
1.047775
self.__subscription_id += 1 def mangled_callback(header, message): return callback(header, self._mangle_for_receiving(message)) if "disable_mangling" in kwargs: if kwargs["disable_mangling"]: mangled_callback = callback del kwargs["disable_mangling"] self.__subscriptions[self.__subscription_id] = { "channel": channel, "callback": mangled_callback, "ack": False, "unsubscribed": False, } self.log.debug( "Subscribing to broadcasts on %s with ID %d", channel, self.__subscription_id, ) self._subscribe_broadcast( self.__subscription_id, channel, mangled_callback, **kwargs ) return self.__subscription_id
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, the header as a dictionary structure, and the message. :param **kwargs: Further parameters for the transport layer. For example disable_mangling: Receive messages as unprocessed strings. retroactive: Ask broker to send old messages if possible :return: A unique subscription ID
2.824335
2.630685
1.073612
subscription_record = self.__subscriptions.get(subscription) if not subscription_record: raise workflows.Error("Attempting to callback on unknown subscription") callback = subscription_record["callback"] if self.__callback_interceptor: return self.__callback_interceptor(callback) return 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(). :param subscription: Subscription ID to look up :return: Callback function
6.038634
3.932572
1.535543
message = self._mangle_for_sending(message) self._send(destination, message, **kwargs)
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 transport of message by this many seconds headers: Optional dictionary of header entries expiration: Optional expiration time, relative to sending time transaction: Transaction ID if message should be part of a transaction
5.396978
8.140754
0.662958
self._send(destination, message, **kwargs)
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 **kwargs: Further parameters for the transport layer. For example delay: Delay transport of message by this many seconds headers: Optional dictionary of header entries expiration: Optional expiration time, relative to sending time transaction: Transaction ID if message should be part of a transaction
5.959243
7.637609
0.78025
message = self._mangle_for_sending(message) self._broadcast(destination, message, **kwargs)
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 transport of message by this many seconds headers: Optional dictionary of header entries expiration: Optional expiration time, relative to sending time transaction: Transaction ID if message should be part of a transaction
5.979517
8.920269
0.670329
self._broadcast(destination, message, **kwargs)
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 **kwargs: Further parameters for the transport layer. For example delay: Delay transport of message by this many seconds headers: Optional dictionary of header entries expiration: Optional expiration time, relative to sending time transaction: Transaction ID if message should be part of a transaction
6.660147
9.089373
0.73274
if isinstance(message, dict): message_id = message.get("message-id") if not subscription_id: subscription_id = message.get("subscription") else: message_id = message if not message_id: raise workflows.Error("Cannot acknowledge message without " + "message ID") if not subscription_id: raise workflows.Error( "Cannot acknowledge message without " + "subscription ID" ) self.log.debug( "Acknowledging message %s on subscription %s", message_id, subscription_id ) self._ack(message_id, subscription_id, **kwargs)
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 field 'message-id'. :param subscription_id: ID of the associated subscription. Optional when a dictionary is passed as first parameter and that dictionary contains field 'subscription'. :param **kwargs: Further parameters for the transport layer. For example transaction: Transaction ID if acknowledgement should be part of a transaction
2.447862
2.329658
1.050739
if isinstance(message, dict): message_id = message.get("message-id") if not subscription_id: subscription_id = message.get("subscription") else: message_id = message if not message_id: raise workflows.Error("Cannot reject message without " + "message ID") if not subscription_id: raise workflows.Error("Cannot reject message without " + "subscription ID") self.log.debug( "Rejecting message %s on subscription %s", message_id, subscription_id ) self._nack(message_id, subscription_id, **kwargs)
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 'message-id'. :param subscription_id: ID of the associated subscription. Optional when a dictionary is passed as first parameter and that dictionary contains field 'subscription'. :param **kwargs: Further parameters for the transport layer. For example transaction: Transaction ID if rejection should be part of a transaction
2.561317
2.34154
1.09386
self.__transaction_id += 1 self.__transactions.add(self.__transaction_id) self.log.debug("Starting transaction with ID %d", self.__subscription_id) self._transaction_begin(self.__transaction_id, **kwargs) return self.__transaction_id
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.
3.63536
3.640781
0.998511
if transaction_id not in self.__transactions: raise workflows.Error("Attempting to abort unknown transaction") self.log.debug("Aborting transaction %s", transaction_id) self.__transactions.remove(transaction_id) self._transaction_abort(transaction_id, **kwargs)
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.
3.607054
4.05151
0.890299
if transaction_id not in self.__transactions: raise workflows.Error("Attempting to commit unknown transaction") self.log.debug("Committing transaction %s", transaction_id) self.__transactions.remove(transaction_id) self._transaction_commit(transaction_id, **kwargs)
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.
3.57551
4.141679
0.8633
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')
def full_y(self, Y)
Add self(shunt) into full Jacobian Y
6.241746
5.489526
1.137028
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)
Import and instantiate this JIT object Returns -------
3.93428
3.81959
1.030027
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)
overloading elem_add function of a JIT class
7.779336
6.364852
1.222234
self.subid = self._transport.subscribe( "transient.transaction", self.receive_message, acknowledgement=True )
def initializing(self)
Subscribe to a channel. Received messages must be acknowledged.
28.839771
17.501413
1.647854
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)
Receive a message
3.458576
3.5046
0.986868
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)
Create and send a unique message for this service.
10.278676
8.990042
1.14334
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)
get elapsed time from the give time Returns: now: the absolute time now dt_str: elapsed time in string
2.518105
2.588575
0.972777
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)
Set a flag to 0 if the corresponding value is 0
2.801239
2.656142
1.054627
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)
Update the summary data Parameters ---------- system Returns ------- None
4.331319
4.250705
1.018965
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)
Update the extended data
2.717103
2.673504
1.016308
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)
Update values based on the requested content Parameters ---------- content Returns -------
6.46333
5.902077
1.095094
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)
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.
3.746649
3.141623
1.192584
if not self.transport: raise ValueError( "This RecipeWrapper object does not contain " "a reference to a transport object." ) if self.recipe_step: raise ValueError("This recipe has already been started.") for destination, payload in self.recipe["start"]: self._send_to_destination(destination, header, payload, kwargs)
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 will be raised.
7.091691
4.974186
1.425699
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." ) kwargs["delay"] = delay self._send_to_destination( self.recipe_pointer, header, message, kwargs, add_path_step=False )
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
6.393996
5.996743
1.066245
self.recipe.apply_parameters(parameters) self.recipe_step = self.recipe[self.recipe_pointer]
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 changes as it is passed down the chain of services. This makes debugging very difficult.
8.334971
6.14631
1.356093
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)
Factory function to generate independent message objects for downstream recipients with different destinations.
3.333814
3.409115
0.977912
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)
Send messages to a list of numbered destinations. This is an internal helper method used by the public 'send' methods.
2.834399
2.794474
1.014287
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 )
Helper function to send a message to a specific recipe destination.
2.67955
2.479641
1.08062
'''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)
Runs when a message event is received Args: event: RTM API event. Returns: Legobot.messge
6.543231
4.094957
1.597876
'''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: event_type = event['type'] dispatcher = self.supported_events[event_type] message = dispatcher(event) logger.debug(message) self.baseplate.tell(message) self.keepalive() time.sleep(0.1) return
def run(self)
Extends the run() method of threading.Thread
5.061318
4.444094
1.138886
'''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)
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.
3.439909
2.178088
1.579325
'''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)
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.
4.051169
2.132125
1.900062
'''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)
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
3.692305
1.91205
1.931072
'''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)
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
3.58801
1.729891
2.074125
'''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)
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
2.972882
1.796592
1.654734
'''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)
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
5.598773
2.557775
2.188923
'''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)
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
3.494892
2.470287
1.414771
'''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 botinfo['ok'] is True: return botinfo['bot'].get('user_id') else: return 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
4.230135
2.097873
2.016392
'''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 fields of events we care about. metadata = Metadata(source=self.actor_urn).__dict__ metadata['thread_ts'] = message.get('thread_ts') if 'presence' in message: metadata['presence'] = message['presence'] if 'text' in message: metadata['text'] = message['text'] elif 'previous_message' in message: # Try to handle slack links if 'text' in message['previous_message']: metadata['text'] = message['previous_message']['text'] else: metadata['text'] = None else: metadata['text'] = None if 'user' in message: metadata['source_user'] = message['user'] elif 'bot_id' in message: metadata['source_user'] = self.get_userid_from_botid( message['bot_id']) elif 'message' in message and 'user' in message['message']: metadata['source_user'] = message['message']['user'] else: metadata['source_user'] = None metadata['user_id'] = metadata['source_user'] metadata['display_name'] = self.get_username(metadata['source_user']) if 'channel' in message: metadata['source_channel'] = message['channel'] # Slack starts DM channel IDs with "D" if message['channel'].startswith('D'): metadata['is_private_message'] = True else: metadata['is_private_message'] = False metadata['source_connector'] = 'slack' return 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
3.258196
2.5161
1.294939
'''Builds a slack attachment. Args: message (Legobot.Message): message w/ metadata to send. Returns: attachment (dict): attachment data. ''' attachment = { 'as_user': True, 'text': text, 'channel': target, 'attachments': [ { 'fallback': text, 'image_url': attachment } ] } if thread: attachment['thread_ts'] = thread return 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.
4.253322
2.104922
2.020656
'''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']['opts']): target = message['metadata']['opts']['target'] thread = message['metadata']['opts'].get('thread') # pattern = re.compile('@([a-zA-Z0-9._-]+)') pattern = re.compile('^@([a-zA-Z0-9._-]+)|\s@([a-zA-Z0-9._-]+)') matches = re.findall(pattern, message['text']) matches = set(matches) logger.debug('MATCHES!!!! {}'.format(matches)) for match in matches: if isinstance(match, tuple): if match[0] != '': match = match[0] else: match = match[1] if not match.startswith('@'): match = '@' + match message['text'] = message['text'].replace( match, '<{}>'.format(match) ) pattern = re.compile('#([A-Za-z0-9-]+)') matches = re.findall(pattern, message['text']) matches = set(matches) for match in matches: channel_id = self.botThread.get_channel_id_by_name(match) if channel_id: message['text'] = message['text'].replace( '#' + match, '<#{}|{}>'.format( channel_id, match ) ) if (message['text'].find('<<@') != -1 or message['text'].find('<<#') != -1): message['text'] = message['text'].replace('<<', '<') message['text'] = message['text'].replace('>>', '>') if target.startswith('U'): target = self.botThread.get_dm_channel(target) attachment = message['metadata']['opts'].get('attachment') if attachment: text = message['metadata']['opts'].get('fallback') attachment = self.build_attachment( text, target, attachment, thread) self.botThread.post_attachment(attachment) else: self.botThread.slack_client.rtm_send_message( target, message['text'], thread=thread)
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.
2.939016
2.455001
1.197155
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) == list: for item in val: if files.ext.strip('.').lower() == item: maybe.append(key) else: if files.ext.strip('.').lower() == val: maybe.append(key) # second, guess by lines true_format = '' fid = open(files.case, 'r') for item in maybe: try: parser = importlib.import_module('.' + item, __name__) testlines = getattr(parser, 'testlines') if testlines(fid): true_format = item break except ImportError: logger.debug( 'Parser for {:s} format is not found. ' 'Format guess will continue.'. format(item)) fid.close() if true_format: logger.debug('Input format guessed as {:s}.'.format(true_format)) else: logger.error('Unable to determine case format.') files.input_format = true_format # guess addfile format if files.addfile: _, add_ext = os.path.splitext(files.addfile) for key, val in input_formats.items(): if type(val) == list: if add_ext[1:] in val: files.add_format = key else: if add_ext[1:] == val: files.add_format = key return true_format
def guess(system)
input format guess function. First guess by extension, then test by lines
3.088683
2.951452
1.046496
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 input format found. Specify or guess a format before parsing.') return False # exit if the format parser could not be imported try: parser = importlib.import_module('.' + input_format, __name__) dmparser = importlib.import_module('.' + 'dome', __name__) if add_format: addparser = importlib.import_module('.' + add_format, __name__) except ImportError: logger.error( 'Parser for {:s} format not found. Program will exit.'.format( input_format)) return False # try parsing the base case file logger.info('Parsing input file <{:s}>'.format(system.files.fullname)) if not parser.read(system.files.case, system): logger.error( 'Error parsing case file {:s} with {:s} format parser.'.format( system.files.fullname, input_format)) return False # Try parsing the addfile if system.files.addfile: if not system.files.add_format: logger.error('Unknown addfile format.') return logger.info('Parsing additional file {:s}.'.format( system.files.addfile)) if not addparser.readadd(system.files.addfile, system): logger.error( 'Error parsing addfile {:s} with {:s} format parser.'.format( system.files.addfile, input_format)) return False # Try parsing the dynfile with dm filter if system.files.dynfile: logger.info('Parsing input file {:s}.'.format( system.files.dynfile)) if not dmparser.read(system.files.dynfile, system): logger.error( 'Error parsing dynfile {:s} with dm format parser.'.format( system.files.dynfile)) return False _, s = elapsed(t) logger.debug('Case file {:s} parsed in {:s}.'.format( system.files.fullname, s)) return True
def parse(system)
Parse input file with the given format in system.files.input_format
2.941806
2.826175
1.040914
system = self.system Gyx = matrix(system.dae.Gx) self.solver.linsolve(system.dae.Gy, Gyx) self.As = matrix(system.dae.Fx - system.dae.Fy * Gyx) # ------------------------------------------------------ # TODO: use scipy eigs # self.As = sparse(self.As) # I = np.array(self.As.I).reshape((-1,)) # J = np.array(self.As.J).reshape((-1,)) # V = np.array(self.As.V).reshape((-1,)) # self.As = csr_matrix((V, (I, J)), shape=self.As.size) # ------------------------------------------------------ return self.As
def calc_state_matrix(self)
Return state matrix and store to ``self.As`` Returns ------- matrix state matrix
4.498807
4.348986
1.03445
self.eigs = numpy.linalg.eigvals(self.As) # TODO: use scipy.sparse.linalg.eigs(self.As) return self.eigs
def calc_eigvals(self)
Solve eigenvalues of the state matrix ``self.As`` Returns ------- None
5.780078
5.184093
1.114964
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 = matrix(spmatrix(1.0, idx, idx, (n, n), N.typecode)) gesv(N, W) partfact = mul(abs(W.T), abs(N)) b = matrix(1.0, (1, n)) WN = b * partfact partfact = partfact.T for item in idx: mu_real = mu[item].real mu_imag = mu[item].imag mu[item] = complex(round(mu_real, 4), round(mu_imag, 4)) partfact[item, :] /= WN[item] # participation factor self.mu = matrix(mu) self.part_fact = matrix(partfact) return self.mu, self.part_fact
def calc_part_factor(self)
Compute participation factor of states in eigenvalues Returns -------
4.725015
4.447582
1.062378
system = self.system mu = self.mu partfact = self.part_fact if system.files.no_output: return text = [] header = [] rowname = [] data = [] neig = len(mu) mu_real = mu.real() mu_imag = mu.imag() npositive = sum(1 for x in mu_real if x > 0) nzero = sum(1 for x in mu_real if x == 0) nnegative = sum(1 for x in mu_real if x < 0) numeral = [] for idx, item in enumerate(range(neig)): if mu_real[idx] == 0: marker = '*' elif mu_real[idx] > 0: marker = '**' else: marker = '' numeral.append('#' + str(idx + 1) + marker) # compute frequency, undamped frequency and damping freq = [0] * neig ufreq = [0] * neig damping = [0] * neig for idx, item in enumerate(mu): if item.imag == 0: freq[idx] = 0 ufreq[idx] = 0 damping[idx] = 0 else: freq[idx] = abs(item) / 2 / pi ufreq[idx] = abs(item.imag / 2 / pi) damping[idx] = -div(item.real, abs(item)) * 100 # obtain most associated variables var_assoc = [] for prow in range(neig): temp_row = partfact[prow, :] name_idx = list(temp_row).index(max(temp_row)) var_assoc.append(system.varname.unamex[name_idx]) pf = [] for prow in range(neig): temp_row = [] for pcol in range(neig): temp_row.append(round(partfact[prow, pcol], 5)) pf.append(temp_row) text.append(system.report.info) header.append(['']) rowname.append(['EIGENVALUE ANALYSIS REPORT']) data.append('') text.append('STATISTICS\n') header.append(['']) rowname.append(['Positives', 'Zeros', 'Negatives']) data.append([npositive, nzero, nnegative]) text.append('EIGENVALUE DATA\n') header.append([ 'Most Associated', 'Real', 'Imag', 'Damped Freq.', 'Frequency', 'Damping [%]' ]) rowname.append(numeral) data.append( [var_assoc, list(mu_real), list(mu_imag), ufreq, freq, damping]) cpb = 7 # columns per block nblock = int(ceil(neig / cpb)) if nblock <= 100: for idx in range(nblock): start = cpb * idx end = cpb * (idx + 1) text.append('PARTICIPATION FACTORS [{}/{}]\n'.format( idx + 1, nblock)) header.append(numeral[start:end]) rowname.append(system.varname.unamex) data.append(pf[start:end]) dump_data(text, header, rowname, data, system.files.eig) logger.info('report saved.')
def dump_results(self)
Save eigenvalue analysis reports Returns ------- None
3.142249
3.052855
1.029282
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)) self.times = matrix(list(set(self.times))) self.times = list(self.times) + list(self.times - 1e-6) return self.times
def get_times(self)
Return all the action times and times-1e-6 in a list
3.054767
2.623855
1.164229
payload = {'op': 1, 'd': seq} payload = json.dumps(payload) logger.debug("Sending heartbeat with payload {}".format(payload)) ws.send(payload) return
def send(self, ws, seq)
Sends heartbeat message to Discord Attributes: ws: Websocket connection to discord seq: Sequence number of heartbeat
4.293795
3.643048
1.178627
baseurl = self.rest_baseurl + \ '/channels/{}/messages'.format(channel_id) requests.post(baseurl, headers=self.headers, data=json.dumps({'content': text}))
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
4.494324
4.202945
1.069327
payload = { 'op': 2, 'd': { 'token': self.token, 'properties': { '$os': sys.platform, '$browser': 'legobot', '$device': 'legobot' }, 'compress': False, 'large_threshold': 250 } } payload['d']['synced_guilds'] = [] logger.info("Identifying with the following message: \ {}".format(payload)) self.ws.send(json.dumps(payload)) return
def identify(self, token)
Identifies to the websocket endpoint Args: token (string): Discord bot token
3.213862
2.843008
1.130444
logger.info("Got a hello") self.identify(self.token) self.heartbeat_thread = Heartbeat(self.ws, message['d']['heartbeat_interval']) self.heartbeat_thread.start() return
def on_hello(self, message)
Runs on a hello event from websocket connection Args: message (dict): Full message from Discord websocket connection"
7.272665
5.209585
1.396016
logger.info("Got a heartbeat") logger.info("Heartbeat message: {}".format(message)) self.heartbeat_thread.update_sequence(message['d']) return
def on_heartbeat(self, message)
Runs on a heartbeat event from websocket connection Args: message (dict): Full message from Discord websocket connection"
8.798882
6.987982
1.259145
if 'content' in message['d']: metadata = self._parse_metadata(message) message = Message(text=message['d']['content'], metadata=metadata).__dict__ logger.debug(message) self.baseplate.tell(message)
def on_message(self, message)
Runs on a create_message event from websocket connection Args: message (dict): Full message from Discord websocket connection"
9.515918
9.002151
1.057072
metadata = Metadata(source=self.actor_urn).__dict__ if 'author' in message['d']: metadata['source_user'] = message['d']['author']['username'] else: metadata['source_user'] = None if 'channel_id' in message['d']: metadata['source_channel'] = message['d']['channel_id'] else: metadata['source_channel'] = None metadata['user_id'] = metadata['source_user'] metadata['display_name'] = metadata['source_user'] metadata['source_connector'] = 'discord' return metadata
def _parse_metadata(self, message)
Sets metadata in Legobot message Args: message (dict): Full message from Discord websocket connection" Returns: Legobot.Metadata
3.32986
3.454375
0.963954
opcode = message['op'] if opcode == 10: self.on_hello(message) elif opcode == 11: self.on_heartbeat(message) elif opcode == 0: self.on_message(message) else: logger.debug("Not a message we handle: OPCODE {}".format(opcode)) return
def handle(self, message)
Dispatches messages to appropriate handler based on opcode Args: message (dict): Full message from Discord websocket connection
3.622779
3.277856
1.105228
self.ws = self.connect() while True: try: data = json.loads(self.ws.recv()) self.handle(data) except json.decoder.JSONDecodeError as e: logger.fatal("No data on socket...")
def run(self)
Overrides run method of threading.Thread. Called by DiscoBot.start(), inherited from threading.Thread
4.948243
4.222627
1.17184
''' Attempts to send a message to the specified destination in Discord. Extends Legobot.Lego.handle() Args: message (Legobot.Message): message w/ metadata to send. ''' logger.debug(message) if Utilities.isNotEmpty(message['metadata']['opts']): target = message['metadata']['opts']['target'] self.botThread.create_message(target, message['text'])
def handle(self, message)
Attempts to send a message to the specified destination in Discord. Extends Legobot.Lego.handle() Args: message (Legobot.Message): message w/ metadata to send.
11.866632
3.995701
2.96985
yext = self.m - len(self.y) xext = self.n - len(self.x) if yext > 0: yzeros = zeros(yext, 1) yones = ones(yext, 1) self.y = matrix([self.y, yzeros], (self.m, 1), 'd') self.g = matrix([self.g, yzeros], (self.m, 1), 'd') self.uy = matrix([self.uy, yones], (self.m, 1), 'd') self.zymin = matrix([self.zymin, yones], (self.m, 1), 'd') self.zymax = matrix([self.zymax, yones], (self.m, 1), 'd') if xext > 0: xzeros = zeros(xext, 1) xones = ones(xext, 1) self.x = matrix([self.x, xzeros], (self.n, 1), 'd') self.f = matrix([self.f, xzeros], (self.n, 1), 'd') self.ux = matrix([self.ux, xones], (self.n, 1), 'd') self.zxmin = matrix([self.zxmin, xones], (self.n, 1), 'd') self.zxmax = matrix([self.zxmax, xones], (self.n, 1), 'd')
def resize(self)
Resize dae and and extend for init1 variables
1.643412
1.595608
1.02996
yidx = matrix(yidx) yval = self.y[yidx] ny = len(yidx) if isinstance(ymin, (int, float, list)): ymin = matrix(ymin, (ny, 1), 'd') if isinstance(ymax, (int, float, list)): ymax = matrix(ymax, (ny, 1), 'd') if not min_set: min_set = ymin elif isinstance(min_set, (int, float, list)): min_set = matrix(min_set, (ny, 1), 'd') if not max_set: max_set = ymax elif isinstance(max_set, (int, float, list)): max_set = matrix(max_set, (ny, 1), 'd') above = ageb(yval, ymax) below = aleb(yval, ymin) above_idx = index(above, 1.0) below_idx = index(below, 1.0) above_yidx = yidx[above_idx] below_yidx = yidx[below_idx] idx = list(above_idx) + list(below_idx) if len(above_yidx) > 0: self.y[above_yidx] = max_set[above_idx] self.zymax[above_yidx] = 0 if len(below_yidx) > 0: self.y[below_yidx] = min_set[below_idx] self.zymin[below_yidx] = 0 if len(idx): self.g[yidx[idx]] = 0 self.ac_reset = True
def hard_limit(self, yidx, ymin, ymax, min_set=None, max_set=None)
Set hard limits for algebraic variables and reset the equation mismatches :param yidx: algebraic variable indices :param ymin: lower limit to check for :param ymax: upper limit to check for :param min_set: optional lower limit to set (``ymin`` as default) :param max_set: optional upper limit to set (``ymax`` as default) :type yidx: list, matrix :type ymin: matrix, int, float, list :type ymax: matrix, int, float, list :type min_set: matrix :type max_set: matrix :return: None
2.087649
2.054239
1.016264
ny = len(yidx) assert ny == len( ridx), "Length of output vars and remote vars does not match" assert rtype in ('x', 'y'), "ridx must be either y (algeb) or x (state)" if isinstance(min_yset, (int, float)): min_yset = matrix(min_yset, (ny, 1), 'd') if isinstance(max_yset, (int, float)): max_yset = matrix(max_yset, (ny, 1), 'd') above_idx, below_idx = list(), list() yidx = matrix(yidx) if rmax: # find the over-limit remote idx above = ageb(self.__dict__[rtype][ridx], rmax) above_idx = index(above, 1.0) # reset the y values based on the remote limit violations self.y[yidx[above_idx]] = max_yset[above_idx] self.zymax[yidx[above_idx]] = 0 if rmin: below = aleb(self.__dict__[rtype][ridx], rmin) below_idx = index(below, 1.0) self.y[yidx[below_idx]] = min_yset[below_idx] self.zymin[yidx[below_idx]] = 0 idx = above_idx + below_idx self.g[yidx[idx]] = 0 if len(idx) > 0: self.factorize = True
def hard_limit_remote(self, yidx, ridx, rtype='y', rmin=None, rmax=None, min_yset=0, max_yset=0)
Limit the output of yidx if the remote y is not within the limits This function needs to be modernized.
3.53763
3.485177
1.01505
xidx = matrix(xidx) xval = self.x[xidx] fval = self.f[xidx] if isinstance(xmin, (float, int, list)): xmin = matrix(xmin, xidx.size, 'd') if isinstance(xmax, (float, int, list)): xmax = matrix(xmax, xidx.size, 'd') x_above = ageb(xval, xmax) f_above = ageb(fval, 0.0) x_below = aleb(xval, xmin) f_below = aleb(fval, 0.0) above = aandb(x_above, f_above) above_idx = index(above, 1.0) if len(above_idx) > 0: above_xidx = xidx[above_idx] self.x[above_xidx] = xmax[above_idx] self.zxmax[above_xidx] = 0 below = aandb(x_below, f_below) below_idx = index(below, 1.0) if len(below_idx) > 0: below_xidx = xidx[below_idx] self.x[below_xidx] = xmin[below_idx] self.zxmin[below_xidx] = 0 idx = list(above_idx) + list(below_idx) if len(idx) > 0: self.f[xidx[idx]] = 0 self.ac_reset = True
def anti_windup(self, xidx, xmin, xmax)
Anti-windup limiter for state variables. Resets the limited variables and differential equations. :param xidx: state variable indices :param xmin: lower limit :param xmax: upper limit :type xidx: matrix, list :type xmin: matrix, float, int, list :type xmax: matrix, float, int, list
2.386915
2.435137
0.980197
if self.ac_reset is False: return mn = self.m + self.n x = index(aandb(self.zxmin, self.zxmax), 0.) y = [i + self.n for i in index(aandb(self.zymin, self.zymax), 0.)] xy = list(x) + y eye = spdiag([1.0] * mn) H = spmatrix(1.0, xy, xy, (mn, mn), 'd') # Modifying ``eye`` is more efficient than ``eye = eye - H``. # CVXOPT modifies eye in place because all the accessed elements exist. for idx in xy: eye[idx, idx] = 0 if len(xy) > 0: self.Ac = eye * (self.Ac * eye) - H self.q[x] = 0 self.ac_reset = False self.factorize = True
def reset_Ac(self)
Reset ``dae.Ac`` sparse matrix for disabled equations due to hard_limit and anti_windup limiters. :return: None
6.987867
6.630096
1.053962
nrow, ncol = 0, 0 if m[0] == 'F': nrow = self.n elif m[0] == 'G': nrow = self.m if m[1] == 'x': ncol = self.n elif m[1] == 'y': ncol = self.m return nrow, ncol
def get_size(self, m)
Return the 2-D size of a Jacobian matrix in tuple
2.503706
2.37374
1.054751
assert m in ('Fx', 'Fy', 'Gx', 'Gy', 'Fx0', 'Fy0', 'Gx0', 'Gy0'), \ 'Wrong Jacobian matrix name <{0}>'.format(m) if isinstance(val, (int, float)): val = val * ones(len(row), 1) self._temp[m]['I'] = matrix([self._temp[m]['I'], matrix(row)]) self._temp[m]['J'] = matrix([self._temp[m]['J'], matrix(col)]) self._temp[m]['V'] = matrix([self._temp[m]['V'], matrix(val)])
def add_jac(self, m, val, row, col)
Add tuples (val, row, col) to the Jacobian matrix ``m`` Implemented in numpy.arrays for temporary storage.
2.919921
2.923321
0.998837
assert ty in ('jac0', 'jac') jac0s = ['Fx0', 'Fy0', 'Gx0', 'Gy0'] jacs = ['Fx', 'Fy', 'Gx', 'Gy'] if ty == 'jac0': todo = jac0s elif ty == 'jac': todo = jacs for m in todo: self.__dict__[m] = spmatrix(self._temp[m]['V'], self._temp[m]['I'], self._temp[m]['J'], self.get_size(m), 'd') if ty == 'jac': self.__dict__[m] += self.__dict__[m + '0'] self.apply_set(ty)
def temp_to_spmatrix(self, ty)
Convert Jacobian tuples to matrices :param ty: name of the matrices to convert in ``('jac0','jac')`` :return: None
3.645483
3.299998
1.104693
assert m in ('Fx', 'Fy', 'Gx', 'Gy', 'Fx0', 'Fy0', 'Gx0', 'Gy0'), \ 'Wrong Jacobian matrix name <{0}>'.format(m) if isinstance(val, (int, float)) and isinstance(row, (np.ndarray, matrix, list)): val = val * ones(len(row), 1) self._set[m]['I'] = matrix([self._set[m]['I'], matrix(row)]) self._set[m]['J'] = matrix([self._set[m]['J'], matrix(col)]) self._set[m]['V'] = matrix([self._set[m]['V'], matrix(val)])
def set_jac(self, m, val, row, col)
Set the values at (row, col) to val in Jacobian m :param m: Jacobian name :param val: values to set :param row: row indices :param col: col indices :return: None
3.399104
3.375294
1.007054
assert ty in ('jac0', 'jac') if ty == 'jac0': todo = ['Fx0', 'Fy0', 'Gx0', 'Gy0'] else: todo = ['Fx', 'Fy', 'Gx', 'Gy'] for m in todo: for idx in range(len(self._set[m]['I'])): i = self._set[m]['I'][idx] j = self._set[m]['J'][idx] v = self._set[m]['V'][idx] self.__dict__[m][i, j] = v
def apply_set(self, ty)
Apply Jacobian set values to matrices :param ty: Jacobian type in ``('jac0', 'jac')`` :return:
3.11083
2.646528
1.175438
if eq in ['f', 'x']: key = 'unamex' elif eq in ['g', 'y']: key = 'unamey' if value: value = list(value) else: value = list(self.__dict__[eq]) out = '' for name, val, idx in zip(self.system.varname.__dict__[key], value, range(len(value))): out += '{:20s} [{:>12.4f}] {:g}\n'.format(name, val, idx) return out
def show(self, eq, value=None)
Show equation or variable array along with the names
4.530451
4.267943
1.061507
if eq not in ('f', 'g', 'q'): return elif eq in ('f', 'q'): key = 'unamex' elif eq == 'g': key = 'unamey' idx = 0 for m, n in zip(self.system.varname.__dict__[key], self.__dict__[eq]): if n == val: return m, idx idx += 1 return
def find_val(self, eq, val)
Return the name of the equation having the given value
5.873533
5.309058
1.106323
assert eq in ('f', 'g') for idx, var in enumerate(self.__dict__[eq]): if abs(var) <= 1e-12: self.__dict__[eq][idx] = 0
def reset_small(self, eq)
Reset numbers smaller than 1e-12 in f and g equations
4.435478
3.067378
1.446016