INSTRUCTION
stringlengths
1
46.3k
RESPONSE
stringlengths
75
80.2k
Create credential request as HolderProver and store in wallet; return credential json and metadata json. Raise AbsentLinkSecret if link secret not set. :param cred_offer_json: credential offer json :param cd_id: credential definition identifier :return: cred request json and correspond...
async def create_cred_req(self, cred_offer_json: str, cd_id: str) -> (str, str): """ Create credential request as HolderProver and store in wallet; return credential json and metadata json. Raise AbsentLinkSecret if link secret not set. :param cred_offer_json: credential offer json ...
Store cred in wallet as HolderProver, return its credential identifier as created in wallet. Raise AbsentTails if tails file not available for revocation registry for input credential. :param cred_json: credential json as HolderProver created :param cred_req_metadata_json: credential request m...
async def store_cred(self, cred_json: str, cred_req_metadata_json) -> str: """ Store cred in wallet as HolderProver, return its credential identifier as created in wallet. Raise AbsentTails if tails file not available for revocation registry for input credential. :param cred_json: cred...
Load caches and archive enough to go offline and be able to generate proof on all credentials in wallet. Return timestamp (epoch seconds) of cache load event, also used as subdirectory for cache archives. :return: cache load event timestamp (epoch seconds)
async def load_cache(self, archive: bool = False) -> int: """ Load caches and archive enough to go offline and be able to generate proof on all credentials in wallet. Return timestamp (epoch seconds) of cache load event, also used as subdirectory for cache archives. :re...
Return json object on lists of all unique box identifiers for credentials in wallet: schema identifiers, credential definition identifiers, and revocation registry identifiers; e.g., :: { "schema_id": [ "R17v42T4pk...:2:tombstone:1.2", "9cHbp54C8n......
async def get_box_ids_json(self) -> str: """ Return json object on lists of all unique box identifiers for credentials in wallet: schema identifiers, credential definition identifiers, and revocation registry identifiers; e.g., :: { "schema_id": [ "R...
Return human-readable credentials from wallet by input filter for schema identifier and/or credential definition identifier components; return all credentials for no filter. :param filt: indy-sdk filter for credentials; i.e., :: { "schema_id": string, # op...
async def get_creds_display_coarse(self, filt: dict = None) -> str: """ Return human-readable credentials from wallet by input filter for schema identifier and/or credential definition identifier components; return all credentials for no filter. :param filt: indy-sdk filter for ...
Get credentials from HolderProver wallet corresponding to proof request and filter criteria; return credential identifiers from wallet and credentials json. Return empty set and empty production for no such credentials. :param proof_req_json: proof request json as Verifier creates; has entries ...
async def get_creds(self, proof_req_json: str, filt: dict = None, filt_dflt_incl: bool = False) -> (Set[str], str): """ Get credentials from HolderProver wallet corresponding to proof request and filter criteria; return credential identifiers from wallet and credentials json. Return empt...
Get creds structure from HolderProver wallet by credential identifiers. :param proof_req_json: proof request as per get_creds() above :param cred_ids: set of credential identifiers of interest :return: json with cred(s) for input credential identifier(s)
async def get_creds_by_id(self, proof_req_json: str, cred_ids: set) -> str: """ Get creds structure from HolderProver wallet by credential identifiers. :param proof_req_json: proof request as per get_creds() above :param cred_ids: set of credential identifiers of interest :retur...
Create proof as HolderProver. Raise: * AbsentLinkSecret if link secret not set * CredentialFocus on attempt to create proof on no creds or multiple creds for a credential definition * AbsentTails if missing required tails file * BadRevStateTime if a timestamp for...
async def create_proof(self, proof_req: dict, creds: dict, requested_creds: dict) -> str: """ Create proof as HolderProver. Raise: * AbsentLinkSecret if link secret not set * CredentialFocus on attempt to create proof on no creds or multiple creds for a credential defini...
Close and delete HolderProver wallet, then create and open a replacement on prior link secret. Note that this operation effectively destroys private keys for credential definitions. Its intended use is primarily for testing and demonstration. Raise AbsentLinkSecret if link secret not set. ...
async def reset_wallet(self) -> str: """ Close and delete HolderProver wallet, then create and open a replacement on prior link secret. Note that this operation effectively destroys private keys for credential definitions. Its intended use is primarily for testing and demonstration. ...
Creates and xml element for the `doc` with the given `parent` and `tag` as the tagName. `attrib` should be a dictionary of string keys to primitives or dicts if the value is a dict, then the keys of the dict are joined with the `attrib` key using a colon. This deals with the badgerfish c...
def _create_sub_el(doc, parent, tag, attrib, data=None): """Creates and xml element for the `doc` with the given `parent` and `tag` as the tagName. `attrib` should be a dictionary of string keys to primitives or dicts if the value is a dict, then the keys of the dict are joined with the `att...
Breaks o into four content type by key syntax: attrib keys (start with '@'), text (value associated with the '$' or None), child element keys (all others) meta element
def _partition_keys_for_xml(self, o): """Breaks o into four content type by key syntax: attrib keys (start with '@'), text (value associated with the '$' or None), child element keys (all others) meta element """ ak = {} tk = None c...
Values in the meta element dict are converted to a BadgerFish-style encoding (see _convert_hbf_meta_val_for_xml), so regardless of input_format, we treat them as if they were BadgerFish.
def _add_meta_dict_to_xml(self, doc, parent, meta_dict): """ Values in the meta element dict are converted to a BadgerFish-style encoding (see _convert_hbf_meta_val_for_xml), so regardless of input_format, we treat them as if they were BadgerFish. """ if not meta_...
Values in the meta element dict are converted to a BadgerFish-style encoding (see _convert_hbf_meta_val_for_xml), so regardless of input_format, we treat them as if they were BadgerFish.
def _add_meta_value_to_xml_doc(self, doc, parent, obj): """Values in the meta element dict are converted to a BadgerFish-style encoding (see _convert_hbf_meta_val_for_xml), so regardless of input_format, we treat them as if they were BadgerFish. """ return self._add_subtr...
Returns a histogram of your data. :param data: The data to histogram :type data: list[object] :return: The histogram :rtype: dict[object, int]
def histogram(data): """Returns a histogram of your data. :param data: The data to histogram :type data: list[object] :return: The histogram :rtype: dict[object, int] """ ret = {} for datum in data: if datum in ret: ret[datum] += 1 else: ret[datum...
Prints object key-value pairs in a custom format :param data: The dict to print :type data: dict :rtype: None
def print_data(data): """Prints object key-value pairs in a custom format :param data: The dict to print :type data: dict :rtype: None """ print(", ".join(["{}=>{}".format(key, value) for key, value in data]))
Get the subdirectories within a package This will include resources (non-submodules) and submodules
def find_subdirectories(package): """ Get the subdirectories within a package This will include resources (non-submodules) and submodules """ try: subdirectories = os.walk(package_to_path(package)).next()[1] except StopIteration: subdirectories = [] return subdirectories
Find all files in a subdirectory and return paths relative to dir This is similar to (and uses) setuptools.findall However, the paths returned are in the form needed for package_data
def subdir_findall(dir, subdir): """ Find all files in a subdirectory and return paths relative to dir This is similar to (and uses) setuptools.findall However, the paths returned are in the form needed for package_data """ strip_n = len(dir.split('/')) path = '/'.join((dir, subdir)) re...
For a list of packages, find the package_data This function scans the subdirectories of a package and considers all non-submodule subdirectories as resources, including them in the package_data Returns a dictionary suitable for setup(package_data=<result>)
def find_package_data(packages): """ For a list of packages, find the package_data This function scans the subdirectories of a package and considers all non-submodule subdirectories as resources, including them in the package_data Returns a dictionary suitable for setup(package_data=<result>) ...
from: http://cburgmer.posterous.com/pip-requirementstxt-and-setuppy
def parse_requirements(file_name): """ from: http://cburgmer.posterous.com/pip-requirementstxt-and-setuppy """ requirements = [] with open(file_name, 'r') as f: for line in f: if re.match(r'(\s*#)|(\s*$)', line): continue if re.match(r'\s*-e\s+', line): ...
from: http://cburgmer.posterous.com/pip-requirementstxt-and-setuppy
def parse_dependency_links(file_name): """ from: http://cburgmer.posterous.com/pip-requirementstxt-and-setuppy """ dependency_links = [] with open(file_name) as f: for line in f: if re.match(r'\s*-[ef]\s+', line): dependency_links.append(re.sub(r'\s*-[ef]\...
Return the full path of the jupyter notebook.
def get_notebook_name(): """ Return the full path of the jupyter notebook. """ kernel_id = re.search('kernel-(.*).json', ipykernel.connect.get_connection_file()).group(1) servers = list_running_servers() for ss in servers: response = requests.get(urljoin(ss['url...
Converts a `JSONEncoder` class into an equivalent `Serializer` class. :param encoder_cls: the encoder class type or a function that returns the type :return: the equivalent `Serializer` class
def json_encoder_to_serializer(encoder_cls: Union[Type[JSONEncoder], Callable[[], Type[JSONEncoder]]]) \ -> Type[Serializer]: """ Converts a `JSONEncoder` class into an equivalent `Serializer` class. :param encoder_cls: the encoder class type or a function that returns the type :return: the equi...
Converts a `JSONDecoder` class into an equivalent `Deserializer` class. :param decoder_cls: the decoder class type or a function that returns the type :return: the equivalent `Deserializer` class
def json_decoder_to_deserializer(decoder_cls: Union[Type[JSONDecoder], Callable[[], Type[JSONDecoder]]]) \ -> Type[Deserializer]: """ Converts a `JSONDecoder` class into an equivalent `Deserializer` class. :param decoder_cls: the decoder class type or a function that returns the type :return: th...
Compute output in CSV format (only file_metrics).
def format(file_metrics, build_metrics): """Compute output in CSV format (only file_metrics).""" # TODO maybe we need different output for build_metrics in csv format, too? # filter out positions metric def report_header(file_metrics): values = list(file_metrics.values())[0] print(values...
Powerful and flexible utility to search and tag files using patterns. :param root_dir: directory where we start the search :param includes: list or iterator of include pattern tuples (pattern, tag) :param excludes: list or iterator of exclude patterns :param gitignore: list of ignore patterns (gitwildca...
def glob_files(root_dir, includes=None, excludes=None, gitignore=None): """Powerful and flexible utility to search and tag files using patterns. :param root_dir: directory where we start the search :param includes: list or iterator of include pattern tuples (pattern, tag) :param excludes: list or iterat...
Main routine for metrics.
def process_file_metrics(context, file_processors): """Main routine for metrics.""" file_metrics = OrderedDict() # TODO make available the includes and excludes feature gitignore = [] if os.path.isfile('.gitignore'): with open('.gitignore', 'r') as ifile: gitignore = ifile.read(...
use processors to collect build metrics.
def process_build_metrics(context, build_processors): """use processors to collect build metrics.""" build_metrics = OrderedDict() # reset all processors for p in build_processors: p.reset() # collect metrics from all processors for p in build_processors: build_metrics.update(p...
Print the summary
def summary(processors, metrics, context): """Print the summary""" # display aggregated metric values on language level def display_header(processors, before='', after=''): """Display the header for the summary results.""" print(before, end=' ') for processor in processors: ...
perform an action on the world that changes it's internal state (maybe stochastically). All you have to do is pull one of the arm and receive a payout. Each arm has a distribution of different payouts that are delivered with different probabilities.
def performAction(self, action): """ perform an action on the world that changes it's internal state (maybe stochastically). All you have to do is pull one of the arm and receive a payout. Each arm has a distribution of different payouts that are delivered with different probabi...
Returns portfolios with U12 and U20 generators removed and generators of the same type at the same bus aggregated.
def get_portfolios3(): """ Returns portfolios with U12 and U20 generators removed and generators of the same type at the same bus aggregated. """ g1 = [0] g2 = [1] g7 = [2] g13 = [3] g14 = [4] # sync cond g15 = [5] g16 = [6] g18 = [7] g21 = [8] g22 = [9] g23 = [10...
Returns an experiment that uses the Roth-Erev learning method.
def get_re_experiment(case, minor=1): """ Returns an experiment that uses the Roth-Erev learning method. """ locAdj = "ac" experimentation = 0.55 recency = 0.3 tau = 100.0 decay = 0.999 nStates = 3 # stateless RE? Pd0 = get_pd_max(case, profile) Pd_min = get_pd_min(case, profile...
Convenience method for calling methods with walker.
def call(self, tag_name: str, *args, **kwargs): """Convenience method for calling methods with walker.""" if hasattr(self, tag_name): getattr(self, tag_name)(*args, **kwargs)
Get the derivative of the variable, create it if it doesn't exist.
def der(self, x: Sym): """Get the derivative of the variable, create it if it doesn't exist.""" name = 'der({:s})'.format(x.name()) if name not in self.scope['dvar'].keys(): self.scope['dvar'][name] = self.sym.sym(name, *x.shape) self.scope['states'].append(x.name()) ...
rising edge
def edge(self, c): """rising edge""" return ca.logic_and(c, ca.logic_not(self.pre_cond(c)))
Create a gaussian noise variable
def noise_gaussian(self, mean, std): """Create a gaussian noise variable""" assert std > 0 ng = self.sym.sym('ng_{:d}'.format(len(self.scope['ng']))) self.scope['ng'].append(ng) return mean + std*ng
Create a uniform noise variable
def noise_uniform(self, lower_bound, upper_bound): """Create a uniform noise variable""" assert upper_bound > lower_bound nu = self.sym.sym('nu_{:d}'.format(len(self.scope['nu']))) self.scope['nu'].append(nu) return lower_bound + nu*(upper_bound - lower_bound)
Convenience function for printing indenting debug output.
def log(self, *args, **kwargs): """Convenience function for printing indenting debug output.""" if self.verbose: print(' ' * self.depth, *args, **kwargs)
Returns the 6 bus case from Wood & Wollenberg PG&C.
def get_case6ww(): """ Returns the 6 bus case from Wood & Wollenberg PG&C. """ path = os.path.dirname(pylon.__file__) path = os.path.join(path, "test", "data") path = os.path.join(path, "case6ww", "case6ww.pkl") case = pylon.Case.load(path) case.generators[0].p_cost = (0.0, 4.0, 200.0) ...
Returns the 24 bus IEEE Reliability Test System.
def get_case24_ieee_rts(): """ Returns the 24 bus IEEE Reliability Test System. """ path = os.path.dirname(pylon.__file__) path = os.path.join(path, "test", "data") path = os.path.join(path, "case24_ieee_rts", "case24_ieee_rts.pkl") case = pylon.Case.load(path) # FIXME: Correct generator n...
Returns a tuple of task and agent for the given learner.
def get_discrete_task_agent(generators, market, nStates, nOffer, markups, withholds, maxSteps, learner, Pd0=None, Pd_min=0.0): """ Returns a tuple of task and agent for the given learner. """ env = pyreto.discrete.MarketEnvironment(generators, market, numS...
Returns a task-agent tuple whose action is always zero.
def get_zero_task_agent(generators, market, nOffer, maxSteps): """ Returns a task-agent tuple whose action is always zero. """ env = pyreto.discrete.MarketEnvironment(generators, market, nOffer) task = pyreto.discrete.ProfitTask(env, maxSteps=maxSteps) agent = pyreto.util.ZeroAgent(env.outdim, env.i...
Returns a task-agent tuple whose action is always minus one.
def get_neg_one_task_agent(generators, market, nOffer, maxSteps): """ Returns a task-agent tuple whose action is always minus one. """ env = pyreto.discrete.MarketEnvironment(generators, market, nOffer) task = pyreto.discrete.ProfitTask(env, maxSteps=maxSteps) agent = pyreto.util.NegOneAgent(env.out...
Runs the given experiment and returns the results.
def run_experiment(experiment, roleouts, episodes, in_cloud=False, dynProfile=None): """ Runs the given experiment and returns the results. """ def run(): if dynProfile is None: maxsteps = len(experiment.profile) # episode length else: maxsteps = dy...
Returns percentages of peak load for all hours of the year. @return: Numpy array of doubles with length 8736.
def get_full_year(): """ Returns percentages of peak load for all hours of the year. @return: Numpy array of doubles with length 8736. """ weekly = get_weekly() daily = get_daily() hourly_winter_wkdy, hourly_winter_wknd = get_winter_hourly() hourly_summer_wkdy, hourly_summer_wknd = ...
Returns percentages of peak load for all days of the year. Data from the IEEE RTS.
def get_all_days(): """ Returns percentages of peak load for all days of the year. Data from the IEEE RTS. """ weekly = get_weekly() daily = get_daily() return [w * (d / 100.0) for w in weekly for d in daily]
Returns an experiment that uses the Roth-Erev learning method.
def get_re_experiment(case, minor=1): """ Returns an experiment that uses the Roth-Erev learning method. """ gen = case.generators profile = array([1.0]) maxSteps = len(profile) experimentation = 0.55 recency = 0.3 tau = 100.0 decay = 0.99#9995 market = pyreto.SmartMarket(case,...
Returns an experiment that uses Q-learning.
def get_q_experiment(case, minor=1): """ Returns an experiment that uses Q-learning. """ gen = case.generators profile = array([1.0]) maxSteps = len(profile) if minor == 1: alpha = 0.3 # Learning rate. gamma = 0.99 # Discount factor # The closer epsilon gets to 0, the m...
Is the machine at it's limit of reactive power?
def q_limited(self): """ Is the machine at it's limit of reactive power? """ if (self.q >= self.q_max) or (self.q <= self.q_min): return True else: return False
Computes total cost for the generator at the given output level.
def total_cost(self, p=None, p_cost=None, pcost_model=None): """ Computes total cost for the generator at the given output level. """ p = self.p if p is None else p p_cost = self.p_cost if p_cost is None else p_cost pcost_model = self.pcost_model if pcost_model is None else pcost...
Converts the first segment of the pwl cost to linear quadratic. FIXME: Curve-fit for all segments.
def pwl_to_poly(self): """ Converts the first segment of the pwl cost to linear quadratic. FIXME: Curve-fit for all segments. """ if self.pcost_model == PW_LINEAR: x0 = self.p_cost[0][0] y0 = self.p_cost[0][1] x1 = self.p_cost[1][0] y1 = se...
Sets the piece-wise linear cost attribute, converting the polynomial cost variable by evaluating at zero and then at n_points evenly spaced points between p_min and p_max.
def poly_to_pwl(self, n_points=4): """ Sets the piece-wise linear cost attribute, converting the polynomial cost variable by evaluating at zero and then at n_points evenly spaced points between p_min and p_max. """ assert self.pcost_model == POLYNOMIAL p_min = self.p_min ...
Returns quantity and price offers created from the cost function.
def get_offers(self, n_points=6): """ Returns quantity and price offers created from the cost function. """ from pyreto.smart_market import Offer qtyprc = self._get_qtyprc(n_points) return [Offer(self, qty, prc) for qty, prc in qtyprc]
Returns quantity and price bids created from the cost function.
def get_bids(self, n_points=6): """ Returns quantity and price bids created from the cost function. """ from pyreto.smart_market import Bid qtyprc = self._get_qtyprc(n_points) return [Bid(self, qty, prc) for qty, prc in qtyprc]
Returns a list of tuples of the form (qty, prc) created from the cost function. If the cost function is polynomial it will be converted to piece-wise linear using poly_to_pwl(n_points).
def _get_qtyprc(self, n_points=6): """ Returns a list of tuples of the form (qty, prc) created from the cost function. If the cost function is polynomial it will be converted to piece-wise linear using poly_to_pwl(n_points). """ if self.pcost_model == POLYNOMIAL: # C...
Updates the piece-wise linear total cost function using the given offer blocks. Based on off2case.m from MATPOWER by Ray Zimmerman, developed at PSERC Cornell. See U{http://www.pserc.cornell.edu/matpower/} for more info.
def offers_to_pwl(self, offers): """ Updates the piece-wise linear total cost function using the given offer blocks. Based on off2case.m from MATPOWER by Ray Zimmerman, developed at PSERC Cornell. See U{http://www.pserc.cornell.edu/matpower/} for more info. """ assert no...
Updates the piece-wise linear total cost function using the given bid blocks. Based on off2case.m from MATPOWER by Ray Zimmerman, developed at PSERC Cornell. See U{http://www.pserc.cornell.edu/matpower/} for more info.
def bids_to_pwl(self, bids): """ Updates the piece-wise linear total cost function using the given bid blocks. Based on off2case.m from MATPOWER by Ray Zimmerman, developed at PSERC Cornell. See U{http://www.pserc.cornell.edu/matpower/} for more info. """ assert self.is_...
Returns a list of points for a piece-wise linear function from the given offer/bid blocks.
def _offbids_to_points(self, offbids, arebids=False): """ Returns a list of points for a piece-wise linear function from the given offer/bid blocks. """ # Sort offers/bids by price in ascending order. offbids.sort(key=lambda x: x.price, reverse=arebids) points = [(0.0, o...
Sets the active power limits, 'p_max' and 'p_min', according to the pwl cost function points.
def _adjust_limits(self): """ Sets the active power limits, 'p_max' and 'p_min', according to the pwl cost function points. """ if not self.is_load: # self.p_min = min([point[0] for point in self.p_cost]) self.p_max = max([point[0] for point in self.p_cost]) ...
Returns the currently visible state of the world as a numpy array of doubles.
def getSensors(self): """ Returns the currently visible state of the world as a numpy array of doubles. """ sensors = array([]) sensors = r_[sensors, self._getTotalDemandSensor()] # sensors = r_[sensors, self._getDemandSensor()] # sensors = r_[sensors, self._get...
Performs an action on the world that changes it's internal state. @param action: an action that should be executed in the Environment @type action: array: [ g1_prc, g2_prc, g1_qty, g2_qty, ... ]
def performAction(self, action): """ Performs an action on the world that changes it's internal state. @param action: an action that should be executed in the Environment @type action: array: [ g1_prc, g2_prc, g1_qty, g2_qty, ... ] """ self._lastAction = [] n = s...
The number of action values that the environment accepts.
def indim(self): """ The number of action values that the environment accepts. """ indim = self.numOffbids * len(self.generators) if self.maxWithhold is not None: return indim * 2 else: return indim
Returns an array of length nb where each value is the sum of the Lagrangian multipliers on the upper and the negative of the Lagrangian multipliers on the lower voltage limits.
def _getBusVoltageLambdaSensor(self): """ Returns an array of length nb where each value is the sum of the Lagrangian multipliers on the upper and the negative of the Lagrangian multipliers on the lower voltage limits. """ muVmin = array([b.mu_vmin for b in self.market.case.connected_bus...
Flattens component refs in a tree :param container: class :param expression: original expression :param instance_prefix: prefix for instance :return: flattened expression
def flatten_component_refs( container: ast.Class, expression: ast.Union[ast.ConnectClause, ast.AssignmentStatement, ast.ForStatement, ast.Symbol], instance_prefix: str) -> ast.Union[ast.ConnectClause, ast.AssignmentStatement, ast.ForStatement, ast.Symbol]: """ Flattens component refs in ...
Turns the function references in this expression into fully scoped references (e.g. relative to absolute). The component references of all referenced functions are put into the functions set. :param node: collection for performing symbol lookup etc. :param expression: original expression :param fun...
def fully_scope_function_calls(node: ast.Tree, expression: ast.Expression, function_set: OrderedDict) -> ast.Expression: """ Turns the function references in this expression into fully scoped references (e.g. relative to absolute). The component references of all referenced functions are put into the fu...
Apply a modification to a symbol if the scope matches (or is None) :param sym: symbol to apply modifications for :param scope: scope of modification
def modify_symbol(sym: ast.Symbol, scope: ast.InstanceClass) -> None: """ Apply a modification to a symbol if the scope matches (or is None) :param sym: symbol to apply modifications for :param scope: scope of modification """ # We assume that we do not screw up the order of applying modificati...
Finds all derivative expressions and annotates all differentiated symbols as states by adding state the prefix list :param node: node of tree to walk :return:
def annotate_states(node: ast.Node) -> None: """ Finds all derivative expressions and annotates all differentiated symbols as states by adding state the prefix list :param node: node of tree to walk :return: """ w = TreeWalker() w.walk(StateAnnotator(node), node)
This function takes a Tree and flattens it so that all subclasses instances are replaced by the their equations and symbols with name mangling of the instance name passed. :param root: The Tree to flatten :param class_name: The class that we want to create a flat model for :return: flat_class, a Cla...
def flatten(root: ast.Tree, class_name: ast.ComponentRef) -> ast.Class: """ This function takes a Tree and flattens it so that all subclasses instances are replaced by the their equations and symbols with name mangling of the instance name passed. :param root: The Tree to flatten :param class_na...
Skip certain childs in the tree walking. By default it prevents endless recursion by skipping references to e.g. parent nodes. :return: True if child needs to be skipped, False otherwise.
def skip_child(self, tree: ast.Node, child_name: str) -> bool: """ Skip certain childs in the tree walking. By default it prevents endless recursion by skipping references to e.g. parent nodes. :return: True if child needs to be skipped, False otherwise. """ if isinstance...
Walks an AST tree recursively :param listener: :param tree: :return: None
def walk(self, listener: TreeListener, tree: ast.Node) -> None: """ Walks an AST tree recursively :param listener: :param tree: :return: None """ name = tree.__class__.__name__ if hasattr(listener, 'enterEvery'): getattr(listener, 'enterEvery')...
Handles tree walking, has to account for dictionaries and lists :param listener: listener that reacts to walked events :param tree: the tree to walk :return: None
def handle_walk(self, listener: TreeListener, tree: Union[ast.Node, dict, list]) -> None: """ Handles tree walking, has to account for dictionaries and lists :param listener: listener that reacts to walked events :param tree: the tree to walk :return: None """ if ...
Parse a Doxygen source file and return a dictionary of all the values. Values will be strings and lists of strings.
def DoxyfileParse(file_contents): """ Parse a Doxygen source file and return a dictionary of all the values. Values will be strings and lists of strings. """ data = {} import shlex lex = shlex.shlex(instream = file_contents, posix = True) lex.wordchars += "*+./-:" lex.whitespace = lex.whites...
Doxygen Doxyfile source scanner. This should scan the Doxygen file and add any files used to generate docs to the list of source files.
def DoxySourceScan(node, env, path): """ Doxygen Doxyfile source scanner. This should scan the Doxygen file and add any files used to generate docs to the list of source files. """ default_file_patterns = [ '*.c', '*.cc', '*.cxx', '*.cpp', '*.c++', '*.java', '*.ii', '*.ixx', '*.ipp', '*.i++'...
Doxygen Doxyfile emitter
def DoxyEmitter(source, target, env): """Doxygen Doxyfile emitter""" # possible output formats and their default values and output locations output_formats = { "HTML": ("YES", "html"), "LATEX": ("YES", "latex"), "RTF": ("NO", "rtf"), "MAN": ("YES", "man"), "XML": ("NO", "xml"), ...
Add builders and construction variables for the Doxygen tool. This is currently for Doxygen 1.4.6.
def generate(env): """ Add builders and construction variables for the Doxygen tool. This is currently for Doxygen 1.4.6. """ doxyfile_scanner = env.Scanner( DoxySourceScan, "DoxySourceScan", scan_check = DoxySourceScanCheck, ) import SCons.Builder doxyfile_builder = SCons.Bu...
Reset metric counter.
def reset(self): """Reset metric counter.""" self._positions = [] self._line = 1 self._curr = None # current scope we are analyzing self._scope = 0 self.language = None
we identified a scope and add it to positions.
def add_scope(self, scope_type, scope_name, scope_start, is_method=False): """we identified a scope and add it to positions.""" if self._curr is not None: self._curr['end'] = scope_start - 1 # close last scope self._curr = { 'type': scope_type, 'name': scope_name, ...
count lines and track position of classes and functions
def process_token(self, tok): """count lines and track position of classes and functions""" if tok[0] == Token.Text: count = tok[1].count('\n') if count: self._line += count # adjust linecount if self._detector.process(tok): pass # works bee...
Returns data from the OPF model.
def _unpack_model(self, om): """ Returns data from the OPF model. """ buses = om.case.connected_buses branches = om.case.online_branches gens = om.case.online_generators cp = om.get_cost_params() # Bf = om._Bf # Pfinj = om._Pfinj return buses, bra...
Returns the problem dimensions.
def _dimension_data(self, buses, branches, generators): """ Returns the problem dimensions. """ ipol = [i for i, g in enumerate(generators) if g.pcost_model == POLYNOMIAL] ipwl = [i for i, g in enumerate(generators) if g.pcost_model == PW_LINEAR] n...
Returns the linear problem constraints.
def _linear_constraints(self, om): """ Returns the linear problem constraints. """ A, l, u = om.linear_constraints() # l <= A*x <= u # Indexes for equality, greater than (unbounded above), less than # (unbounded below) and doubly-bounded box constraints. # ieq = flatnonze...
Returns bounds on the optimisation variables.
def _var_bounds(self): """ Returns bounds on the optimisation variables. """ x0 = array([]) xmin = array([]) xmax = array([]) for var in self.om.vars: x0 = r_[x0, var.v0] xmin = r_[xmin, var.vl] xmax = r_[xmax, var.vu] return ...
Selects an interior initial point for interior point solver.
def _initial_interior_point(self, buses, generators, xmin, xmax, ny): """ Selects an interior initial point for interior point solver. """ Va = self.om.get_var("Va") va_refs = [b.v_angle * pi / 180.0 for b in buses if b.type == REFERENCE] x0 = (xmin + xmax) / 2...
Solves DC optimal power flow and returns a results dict.
def solve(self): """ Solves DC optimal power flow and returns a results dict. """ base_mva = self.om.case.base_mva Bf = self.om._Bf Pfinj = self.om._Pfinj # Unpack the OPF model. bs, ln, gn, cp = self._unpack_model(self.om) # Compute problem dimensions. ...
Returns the piece-wise linear components of the objective function.
def _pwl_costs(self, ny, nxyz, ipwl): """ Returns the piece-wise linear components of the objective function. """ any_pwl = int(ny > 0) if any_pwl: y = self.om.get_var("y") # Sum of y vars. Npwl = csr_matrix((ones(ny), (zeros(ny), array(ipwl) + y.i1)))...
Returns the quadratic cost components of the objective function.
def _quadratic_costs(self, generators, ipol, nxyz, base_mva): """ Returns the quadratic cost components of the objective function. """ npol = len(ipol) rnpol = range(npol) gpol = [g for g in generators if g.pcost_model == POLYNOMIAL] if [g for g in gpol if len(g.p_cost) ...
Combines pwl, polynomial and user-defined costs.
def _combine_costs(self, Npwl, Hpwl, Cpwl, fparm_pwl, any_pwl, Npol, Hpol, Cpol, fparm_pol, npol, nw): """ Combines pwl, polynomial and user-defined costs. """ NN = vstack([n for n in [Npwl, Npol] if n is not None], "csr") if (Hpwl is not None) and (Hpol is not No...
Transforms quadratic coefficients for w into coefficients for x.
def _transform_coefficients(self, NN, HHw, CCw, ffparm, polycf, any_pwl, npol, nw): """ Transforms quadratic coefficients for w into coefficients for x. """ nnw = any_pwl + npol + nw M = csr_matrix((ffparm[:, 3], (range(nnw), range(nnw)))) MR = M * ...
Solves the either quadratic or linear program.
def _run_opf(self, HH, CC, AA, ll, uu, xmin, xmax, x0, opt): """ Solves the either quadratic or linear program. """ N = self._nieq if HH.nnz > 0: solution = qps_pips(HH, CC, AA, ll, uu, xmin, xmax, x0, opt) else: solution = qps_pips(None, CC, AA, ll, uu, ...
Returns the voltage angle and generator set-point vectors.
def _update_solution_data(self, s, HH, CC, C0): """ Returns the voltage angle and generator set-point vectors. """ x = s["x"] Va_v = self.om.get_var("Va") Pg_v = self.om.get_var("Pg") Va = x[Va_v.i1:Va_v.iN + 1] Pg = x[Pg_v.i1:Pg_v.iN + 1] # f = 0.5 * dot(...
Calculates the result attribute values.
def _update_case(self, bs, ln, gn, base_mva, Bf, Pfinj, Va, Pg, lmbda): """ Calculates the result attribute values. """ Pmis = self.om.get_lin_constraint("Pmis") Pf = self.om.get_lin_constraint("Pf") Pt = self.om.get_lin_constraint("Pt") Pg_v = self.om.get_var("Pg") ...
Adds a constraint on the reference bus angles.
def _ref_bus_angle_constraint(self, buses, Va, xmin, xmax): """ Adds a constraint on the reference bus angles. """ refs = [bus._i for bus in buses if bus.type == REFERENCE] Varefs = array([b.v_angle for b in buses if b.type == REFERENCE]) xmin[Va.i1 - 1 + refs] = Varefs ...
Solves AC optimal power flow.
def solve(self): """ Solves AC optimal power flow. """ case = self.om.case self._base_mva = case.base_mva # TODO: Find an explanation for this value. self.opt["cost_mult"] = 1e-4 # Unpack the OPF model. self._bs, self._ln, self._gn, _ = self._unpack_model...
Solves using Python Interior Point Solver (PIPS).
def _solve(self, x0, A, l, u, xmin, xmax): """ Solves using Python Interior Point Solver (PIPS). """ s = pips(self._costfcn, x0, A, l, u, xmin, xmax, self._consfcn, self._hessfcn, self.opt) return s
Evaluates the objective function.
def _f(self, x, user_data=None): """ Evaluates the objective function. """ p_gen = x[self._Pg.i1:self._Pg.iN + 1] # Active generation in p.u. q_gen = x[self._Qg.i1:self._Qg.iN + 1] # Reactive generation in p.u. # Polynomial cost of P and Q. xx = r_[p_gen, q_gen] * self._...
Evaluates the cost gradient.
def _df(self, x, user_data=None): """ Evaluates the cost gradient. """ p_gen = x[self._Pg.i1:self._Pg.iN + 1] # Active generation in p.u. q_gen = x[self._Qg.i1:self._Qg.iN + 1] # Reactive generation in p.u. # Polynomial cost of P and Q. xx = r_[p_gen, q_gen] * self._base...
Evaluates the cost Hessian.
def _d2f(self, x): """ Evaluates the cost Hessian. """ d2f_dPg2 = lil_matrix((self._ng, 1)) # w.r.t p.u. Pg d2f_dQg2 = lil_matrix((self._ng, 1)) # w.r.t p.u. Qg] for i in self._ipol: p_cost = list(self._gn[i].p_cost) d2f_dPg2[i, 0] = polyval(polyder(p_cos...
Evaluates the constraint function values.
def _gh(self, x): """ Evaluates the constraint function values. """ Pgen = x[self._Pg.i1:self._Pg.iN + 1] # Active generation in p.u. Qgen = x[self._Qg.i1:self._Qg.iN + 1] # Reactive generation in p.u. for i, gen in enumerate(self._gn): gen.p = Pgen[i] * self._base_m...
Evaluates the objective function, gradient and Hessian for OPF.
def _costfcn(self, x): """ Evaluates the objective function, gradient and Hessian for OPF. """ f = self._f(x) df = self._df(x) d2f = self._d2f(x) return f, df, d2f
Evaluates nonlinear constraints and their Jacobian for OPF.
def _consfcn(self, x): """ Evaluates nonlinear constraints and their Jacobian for OPF. """ h, g = self._gh(x) dh, dg = self._dgh(x) return h, g, dh, dg
Evaluates Hessian of Lagrangian for AC OPF.
def _hessfcn(self, x, lmbda): """ Evaluates Hessian of Lagrangian for AC OPF. """ Pgen = x[self._Pg.i1:self._Pg.iN + 1] # Active generation in p.u. Qgen = x[self._Qg.i1:self._Qg.iN + 1] # Reactive generation in p.u. for i, g in enumerate(self._gn): g.p = Pgen[i] * se...