INSTRUCTION
stringlengths
1
8.43k
RESPONSE
stringlengths
75
104k
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.
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.
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.
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.
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 Class containing the fla...
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...
Returns the voltage angle and generator set - point vectors.
def _update_solution_data(self, s): """ Returns the voltage angle and generator set-point vectors. """ x = s["x"] # Va_var = self.om.get_var("Va") # Vm_var = self.om.get_var("Vm") # Pg_var = self.om.get_var("Pg") # Qg_var = self.om.get_var("Qg") Va = x[self._...
Calculates the result attribute values.
def _update_case(self, bs, ln, gn, base_mva, Yf, Yt, Va, Vm, Pg, Qg,lmbda): """ Calculates the result attribute values. """ V = Vm * exp(1j * Va) # Va_var = self.om.get_var("Va") Vm_var = self._Vm Pmis = self.om.get_nln_constraint("Pmis") Qmis = self.om.get_nln_co...
Serializes the given serializable object or collection of serializable objects.: param serializable: the object or objects to serialize: return: a serialization of the given object
def serialize(self, serializable: Optional[Union[SerializableType, List[SerializableType]]]) \ -> PrimitiveJsonType: """ Serializes the given serializable object or collection of serializable objects. :param serializable: the object or objects to serialize :return: a serializ...
Serializes the given value using the given serializer.: param to_serialize: the value to deserialize: param serializer_cls: the type of serializer to use: return: serialized value
def _serialize_property_value(self, to_serialize: Any, serializer_cls: Type) -> Any: """ Serializes the given value using the given serializer. :param to_serialize: the value to deserialize :param serializer_cls: the type of serializer to use :return: serialized value """...
Creates a deserializer of the given type exploiting a cache.: param serializer_type: the type of deserializer to create: return: the created serializer
def _create_serializer_of_type_with_cache(self, serializer_type: Type) -> "Serializer": """ Creates a deserializer of the given type, exploiting a cache. :param serializer_type: the type of deserializer to create :return: the created serializer """ if serializer_type not ...
Deserializes the given representation of the serialized object.: param to_deserialize: the serialized object as a dictionary: return: the deserialized object or collection of deserialized objects
def deserialize(self, to_deserialize: PrimitiveJsonType) \ -> Optional[Union[SerializableType, List[SerializableType]]]: """ Deserializes the given representation of the serialized object. :param to_deserialize: the serialized object as a dictionary :return: the deserialized ...
Deserializes the given value using the given deserializer.: param to_deserialize: the value to deserialize: param deserializer_cls: the type of deserializer to use: return: deserialized value
def _deserialize_property_value(self, to_deserialize: PrimitiveJsonType, deserializer_cls: Type) -> Any: """ Deserializes the given value using the given deserializer. :param to_deserialize: the value to deserialize :param deserializer_cls: the type of deserializer to use :return...
Creates a deserializer of the given type exploiting a cache.: param deserializer_type: the type of deserializer to create: return: the deserializer
def _create_deserializer_of_type_with_cache(self, deserializer_type: Type) -> "Deserializer": """ Creates a deserializer of the given type, exploiting a cache. :param deserializer_type: the type of deserializer to create :return: the deserializer """ if deserializer_type ...
Simulates a Dae model.
def sim(model: HybridOde, options: Dict = None, # noqa: too-complex user_callback=None) -> Dict[str, np.array]: """ Simulates a Dae model. :model: The model to simulate :options: See opt dict below :user_callback: A routine to call after each integration step, f(t, x, y, m, p, c) -> ...
Loads a pickled case.
def read(self, file_or_filename): """ Loads a pickled case. """ if isinstance(file_or_filename, basestring): fname = os.path.basename(file_or_filename) logger.info("Unpickling case file [%s]." % fname) file = None try: file = open(...
Writes the case to file using pickle.
def write(self, file_or_filename): """ Writes the case to file using pickle. """ if isinstance(file_or_filename, basestring): fname = os.path.basename(file_or_filename) logger.info("Pickling case [%s]." % fname) file = None try: fi...
count comments and non - empty lines that contain code
def process_token(self, tok): """count comments and non-empty lines that contain code""" if(tok[0].__str__() in ('Token.Comment.Multiline', 'Token.Comment', 'Token.Literal.String.Doc')): self.comments += tok[1].count('\n')+1 elif(tok[0].__str__() in ('Token.Comment.Si...
Calculate ratio_comment_to_code and return with the other values
def get_metrics(self): """Calculate ratio_comment_to_code and return with the other values""" if(self.sloc == 0): if(self.comments == 0): ratio_comment_to_code = 0.00 else: ratio_comment_to_code = 1.00 else: ratio_comment_to_cod...
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. """ Pd = array([b.p_demand for b in self.case.buses if b.type == PQ]) logger.info("State: %s" % list(Pd)) return Pd
Perform an action on the world that changes it s internal state.
def performAction(self, action): """ Perform an action on the world that changes it's internal state. """ gs = [g for g in self.case.online_generators if g.bus.type !=REFERENCE] assert len(action) == len(gs) logger.info("Action: %s" % list(action)) # Set the output of ...
Re - initialises the environment.
def reset(self): """ Re-initialises the environment. """ logger.info("Reseting environment.") self._step = 0 # Reset the set-point of each generator to its original value. gs = [g for g in self.case.online_generators if g.bus.type !=REFERENCE] for i, g in enumer...
Returns the reward corresponding to the last action performed.
def getReward(self): """ Returns the reward corresponding to the last action performed. """ on = self.env.case.online_generators generators = [g for g in on if g.bus.type != REFERENCE] cost = sum([g.total_cost() for g in generators]) ref_penalty = 1000.0 refs =...
Is the current episode over?
def isFinished(self): """ Is the current episode over? """ finished = (self.env._step == len(self.env.profile)) if finished: logger.info("Finished episode.") return finished
Returns a list of 2 - tuples e. g. [ ( - 3. 14 3. 14 ) ( - 0. 001 0. 001 ) ] one tuple per parameter giving min and max for that parameter.
def getSensorLimits(self): """ Returns a list of 2-tuples, e.g. [(-3.14, 3.14), (-0.001, 0.001)], one tuple per parameter, giving min and max for that parameter. """ limits = [] for i in range(len([b for b in self.env.case.buses if b.type == PQ])): limits.append((0.0,...
Returns a list of 2 - tuples e. g. [ ( - 3. 14 3. 14 ) ( - 0. 001 0. 001 ) ] one tuple per parameter giving min and max for that parameter.
def getActorLimits(self): """ Returns a list of 2-tuples, e.g. [(-3.14, 3.14), (-0.001, 0.001)], one tuple per parameter, giving min and max for that parameter. """ generators = [g for g in self.env.case.online_generators if g.bus.type != REFERENCE] limits =...
Does one interaction between the task and the agent.
def _oneInteraction(self): """ Does one interaction between the task and the agent. """ if self.doOptimization: raise Exception('When using a black-box learning algorithm, only full episodes can be done.') else: self.stepid += 1 self.agent.integrateObs...
Does the the given number of episodes.
def doEpisodes(self, number=1): """ Does the the given number of episodes. """ env = self.task.env self.Pg = zeros((len(env.case.online_generators), len(env.profile))) rewards = super(OPFExperiment, self).doEpisodes(number) # Average the set-points for each period. ...
Gets the registered JSON encoder for the given type.: param type_to_encode: the type of object that is to be encoded: return: the encoder for the given object else None if unknown
def get_json_encoders_for_type(self, type_to_encode: type) -> Optional[Iterable[JSONEncoder]]: """ Gets the registered JSON encoder for the given type. :param type_to_encode: the type of object that is to be encoded :return: the encoder for the given object else `None` if unknown ...
Register the given JSON encoder for use with the given object type.: param encoder_type: the type of object to encode: param encoder: the JSON encoder: return: this builder
def register_json_encoder(self, encoder_type: type, encoder: JSONEncoder): """ Register the given JSON encoder for use with the given object type. :param encoder_type: the type of object to encode :param encoder: the JSON encoder :return: this builder """ self._js...
Builds JSON encoder that uses the encoders registered at the point in time when this method is called.: return: the JSON encoder
def build(self) -> RegisteredTypeJSONEncoderType: """ Builds JSON encoder that uses the encoders registered at the point in time when this method is called. :return: the JSON encoder """ class_name = "%s_%s" % (_RegisteredTypeJSONEncoder.__class__.__name__, id(self)) # Us...
searches for an object with the name given inside the object given. obj. child. meth will return the meth obj.
def getMethodByName(obj, name): """searches for an object with the name given inside the object given. "obj.child.meth" will return the meth obj. """ try:#to get a method by asking the service obj = obj._getMethodByName(name) except: #assumed a childObject is ment #split...
blocks until the response arrived or timeout is reached.
def waitForResponse(self, timeOut=None): """blocks until the response arrived or timeout is reached.""" self.__evt.wait(timeOut) if self.waiting(): raise Timeout() else: if self.response["error"]: raise Exception(self.response["error"]) ...
sends a request to the peer
def sendRequest(self, name, args): """sends a request to the peer""" (respEvt, id) = self.newResponseEvent() self.sendMessage({"id":id, "method":name, "params": args}) return respEvt
sends a response to the peer
def sendResponse(self, id, result, error): """sends a response to the peer""" self.sendMessage({"result":result, "error": error, "id":id})
creates a response event and adds it to a waiting list When the reponse arrives it will be removed from the list.
def newResponseEvent(self): """creates a response event and adds it to a waiting list When the reponse arrives it will be removed from the list. """ respEvt = ResponseEvent() self.respLock.acquire() eid = id(respEvt) self.respEvents[eid] = respEvt self...
handles a response by fireing the response event for the response coming in
def handleResponse(self, resp): """handles a response by fireing the response event for the response coming in""" id=resp["id"] evt = self.respEvents[id] del(self.respEvents[id]) evt.handleResponse(resp)
handles a request by calling the appropriete method the service exposes
def handleRequest(self, req): """handles a request by calling the appropriete method the service exposes""" name = req["method"] params = req["params"] id=req["id"] obj=None try: #to get a callable obj obj = getMethodByName(self.service, name) except ...
handles a notification request by calling the appropriete method the service exposes
def handleNotification(self, req): """handles a notification request by calling the appropriete method the service exposes""" name = req["method"] params = req["params"] try: #to get a callable obj obj = getMethodByName(self.service, name) rslt = obj(*params) ...
Parses a PSAT data file and returns a case object
def read(self, file_or_filename): """ Parses a PSAT data file and returns a case object file_or_filename: File object or path to PSAT data file return: Case object """ self.file_or_filename = file_or_filename logger.info("Parsing PSAT case file [%s]." % file_or_...
Returns a construct for an array of bus data.
def _get_bus_array_construct(self): """ Returns a construct for an array of bus data. """ bus_no = integer.setResultsName("bus_no") v_base = real.setResultsName("v_base") # kV v_magnitude = Optional(real).setResultsName("v_magnitude") v_angle = Optional(real).setResultsNa...
Returns a construct for an array of line data.
def _get_line_array_construct(self): """ Returns a construct for an array of line data. """ from_bus = integer.setResultsName("fbus") to_bus = integer.setResultsName("tbus") s_rating = real.setResultsName("s_rating") # MVA v_rating = real.setResultsName("v_rating") # kV ...
Returns a construct for an array of slack bus data.
def _get_slack_array_construct(self): """ Returns a construct for an array of slack bus data. """ bus_no = integer.setResultsName("bus_no") s_rating = real.setResultsName("s_rating") # MVA v_rating = real.setResultsName("v_rating") # kV v_magnitude = real.setResultsName("...
Returns a construct for an array of PV generator data.
def _get_pv_array_construct(self): """ Returns a construct for an array of PV generator data. """ bus_no = integer.setResultsName("bus_no") s_rating = real.setResultsName("s_rating") # MVA v_rating = real.setResultsName("v_rating") # kV p = real.setResultsName("p") # p.u....
Returns a construct for an array of PQ load data.
def _get_pq_array_construct(self): """ Returns a construct for an array of PQ load data. """ bus_no = integer.setResultsName("bus_no") s_rating = real.setResultsName("s_rating") # MVA v_rating = real.setResultsName("v_rating") # kV p = real.setResultsName("p") # p.u. ...
Returns a construct for an array of power demand data.
def _get_demand_array_construct(self): """ Returns a construct for an array of power demand data. """ bus_no = integer.setResultsName("bus_no") s_rating = real.setResultsName("s_rating") # MVA p_direction = real.setResultsName("p_direction") # p.u. q_direction = real.setR...
Returns a construct for an array of power supply data.
def _get_supply_array_construct(self): """ Returns a construct for an array of power supply data. """ bus_no = integer.setResultsName("bus_no") s_rating = real.setResultsName("s_rating") # MVA p_direction = real.setResultsName("p_direction") # CPF p_bid_max = real.setResu...
Returns a construct for an array of generator ramping data.
def _get_generator_ramping_construct(self): """ Returns a construct for an array of generator ramping data. """ supply_no = integer.setResultsName("supply_no") s_rating = real.setResultsName("s_rating") # MVA up_rate = real.setResultsName("up_rate") # p.u./h down_rate = r...
Returns a construct for an array of load ramping data.
def _get_load_ramping_construct(self): """ Returns a construct for an array of load ramping data. """ bus_no = integer.setResultsName("bus_no") s_rating = real.setResultsName("s_rating") # MVA up_rate = real.setResultsName("up_rate") # p.u./h down_rate = real.setResultsNa...
Adds a Bus object to the case.
def push_bus(self, tokens): """ Adds a Bus object to the case. """ logger.debug("Pushing bus data: %s" % tokens) bus = Bus() bus.name = tokens["bus_no"] bus.v_magnitude = tokens["v_magnitude"] bus.v_angle = tokens["v_angle"] bus.v_magnitude = tokens["v_ma...
Sorts bus list according to name ( bus_no ).
def sort_buses(self, tokens): """ Sorts bus list according to name (bus_no). """ self.case.buses.sort(key=lambda obj: obj.name)