INSTRUCTION
stringlengths
1
46.3k
RESPONSE
stringlengths
75
80.2k
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. :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) -> ret (ret < 0 means abort)
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 file_or_filename: File object or path to PSAT data file return: 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 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)
Adds a Branch object to the case.
def push_line(self, tokens): """ Adds a Branch object to the case. """ logger.debug("Pushing line data: %s" % tokens) from_bus = self.case.buses[tokens["fbus"]-1] to_bus = self.case.buses[tokens["tbus"]-1] e = Branch(from_bus=from_bus, to_bus=to_bus) e.r = token...
Finds the slack bus, adds a Generator with the appropriate data and sets the bus type to slack.
def push_slack(self, tokens): """ Finds the slack bus, adds a Generator with the appropriate data and sets the bus type to slack. """ logger.debug("Pushing slack data: %s" % tokens) bus = self.case.buses[tokens["bus_no"] - 1] g = Generator(bus) g.q_max = tokens[...
Creates and Generator object, populates it with data, finds its Bus and adds it.
def push_pv(self, tokens): """ Creates and Generator object, populates it with data, finds its Bus and adds it. """ logger.debug("Pushing PV data: %s" % tokens) bus = self.case.buses[tokens["bus_no"]-1] g = Generator(bus) g.p = tokens["p"] g.q_max = toke...
Adds OPF and CPF data to a Generator.
def push_supply(self, tokens): """ Adds OPF and CPF data to a Generator. """ logger.debug("Pushing supply data: %s" % tokens) bus = self.case.buses[tokens["bus_no"] - 1] n_generators = len([g for g in self.case.generators if g.bus == bus]) if n_generators == 0: ...
Creates and Load object, populates it with data, finds its Bus and adds it.
def push_pq(self, tokens): """ Creates and Load object, populates it with data, finds its Bus and adds it. """ logger.debug("Pushing PQ data: %s" % tokens) bus = self.case.buses[tokens["bus_no"] - 1] bus.p_demand = tokens["p"] bus.q_demand = tokens["q"]
Parses the given file-like object.
def _parse_file(self, file): """ Parses the given file-like object. """ case = Case() file.seek(0) line = file.readline().split() if line[0] != "function": logger.error("Invalid data file header.") return case if line[1] != "mpc": ...
Writes case data to file in MATPOWER format.
def write(self, file_or_filename): """ Writes case data to file in MATPOWER format. """ if isinstance(file_or_filename, basestring): self._fcn_name, _ = splitext(basename(file_or_filename)) else: self._fcn_name = self.case.name self._fcn_name = self._fcn_...
Writes the case data in MATPOWER format.
def write_case_data(self, file): """ Writes the case data in MATPOWER format. """ file.write("function mpc = %s\n" % self._fcn_name) file.write('\n%%%% MATPOWER Case Format : Version %d\n' % 2) file.write("mpc.version = '%d';\n" % 2) file.write("\n%%%%----- Power Flow D...
Writes bus data in MATPOWER format.
def write_bus_data(self, file): """ Writes bus data in MATPOWER format. """ # labels = ["bus_id", "type", "Pd", "Qd", "Gs", "Bs", "area", "Vm", "Va", # "baseKV", "Vmax", "Vmin"] bus_attrs = ["_i", "type", "p_demand", "q_demand", "g_shunt","b_shunt", "area", "v_magn...
Writes generator data in MATPOWER format.
def write_generator_data(self, file): """ Writes generator data in MATPOWER format. """ gen_attr = ["p", "q", "q_max", "q_min", "v_magnitude", "base_mva", "online", "p_max", "p_min", "mu_pmax", "mu_pmin", "mu_qmax", "mu_qmin"] file.write("\n%%%% generator data\n"...
Writes branch data to file.
def write_branch_data(self, file): """ Writes branch data to file. """ branch_attr = ["r", "x", "b", "rate_a", "rate_b", "rate_c", "ratio", "phase_shift", "online", "ang_min", "ang_max", "p_from", "q_from", "p_to", "q_to", "mu_s_from", "mu_s_to", "mu_angmin", ...
Writes generator cost data to file.
def write_generator_cost_data(self, file): """ Writes generator cost data to file. """ file.write("\n%%%% generator cost data\n") file.write("%%\t1\tstartup\tshutdown\tn\tx1\ty1\t...\txn\tyn\n") file.write("%%\t2\tstartup\tshutdown\tn\tc(n-1)\t...\tc0\n") file.write("%sge...
Writes area data to file.
def write_area_data(self, file): """ Writes area data to file. """ file.write("%% area data" + "\n") file.write("%\tno.\tprice_ref_bus" + "\n") file.write("areas = [" + "\n") # TODO: Implement areas file.write("\t1\t1;" + "\n") file.write("];" + "\n")
Initiate processing for each token. Override this if you want tt control the processing of the tokens yourself.
def process_file(self, language, key, token_list): """ Initiate processing for each token. Override this if you want tt control the processing of the tokens yourself. """ self.language = language for tok in token_list: self.process_token(tok)
Updates the data used by the renderer.
def updateData(self, data): """ Updates the data used by the renderer. """ # pylab.ion() fig = pylab.figure(1) n_agent = len(data) idx = 1 for i, adata in enumerate(data): saxis = fig.add_subplot(3, n_agent, i + 1) saxis.plot(adata[0]) ...
Updates the data used by the renderer.
def updateData(self, state_data, action_data, reward_data): """ Updates the data used by the renderer. """ # self.dataLock.acquire() self.state_data[:, self.updates] = state_data self.action_data[:, self.updates] = action_data self.reward_data[0, self.updates] = reward_da...
Initialises plots of the environment.
def draw_plot(self): """ Initialises plots of the environment. """ pylab.ion() fig = pylab.figure(1) # State plot. # state_axis = fig.add_subplot(3, 1, 1) # numrows, numcols, fignum # state_axis.title = 'State' # state_axis.xlabel = 'Time (hours)' # s...
:param ast_tree: AST to generate from :param model_name: class to generate :return: sympy source code for model
def generate(ast_tree: ast.Tree, model_name: str): """ :param ast_tree: AST to generate from :param model_name: class to generate :return: sympy source code for model """ component_ref = ast.ComponentRef.from_string(model_name) ast_tree_new = copy.deepcopy(ast_tree) ast_walker = TreeWalk...
Plot simulation data. :data: A dictionary of arrays. :fields: A list of variables you want to plot (e.g. ['x', y', 'c'])
def plot(data: Dict[str, np.array], fields: List[str] = None, *args, **kwargs): """ Plot simulation data. :data: A dictionary of arrays. :fields: A list of variables you want to plot (e.g. ['x', y', 'c']) """ if plt is None: return if fields is None: fields = ['x', 'y', 'm',...
Returns a case from a version 30 PSS/E raw file. @param file_or_filename: File name or file like object with PSS/E data @return: Case object
def read(self, file_or_filename): """ Returns a case from a version 30 PSS/E raw file. @param file_or_filename: File name or file like object with PSS/E data @return: Case object """ t0 = time.time() self.init() if isinstance(file_or_filename, basestring)...
Parses the given file.
def _parse_file(self, file): """ Parses the given file. """ case = Case() file.seek(0) case.base_mva = float(file.next().split(",")[1].split("/")[0]) case.name = "%s %s" % (file.next().strip(), file.next().strip()) bustype_map = {1: "PQ", 2: "PV", 3: "ref...
Writes case data to file.
def write_case_data(self, file): """ Writes case data to file. """ change_code = 0 s_base = self.case.base_mva timestr = time.strftime("%Y%m%d%H%M", time.gmtime()) file.write("%d, %8.2f, 30 / PSS(tm)E-30 RAW created by Pylon (%s).\n" % (change_co...
Writes bus data in MATPOWER format.
def write_bus_data(self, file): """ Writes bus data in MATPOWER format. """ # I, 'NAME', BASKV, IDE, GL, BL, AREA, ZONE, VM, VA, OWNER bus_attrs = ["_i", "name", "v_base", "type", "g_shunt", "b_shunt", "area", "zone", "v_magnitude", "v_angl...
Writes generator data in MATPOWER format.
def write_generator_data(self, file): """ Writes generator data in MATPOWER format. """ for generator in self.case.generators: vals = [] vals.append(generator.bus._i) # I vals.append("1 ") # ID vals.append(generator.p) vals.appe...
Writes branch data to file.
def write_branch_data(self, file): """ Writes branch data to file. """ # I,J,CKT,R,X,B,RATEA,RATEB,RATEC,GI,BI,GJ,BJ,ST,LEN,O1,F1,...,O4,F4 branch_attr = ["r", "x", "b", "rate_a", "rate_b", "rate_c"] for branch in self.case.branches: if feq(branch.ratio, 0.0):...
Takes n elements (not necessarily distinct) from the sequence, order matters. @see: http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/190465
def xselections(items, n): """ Takes n elements (not necessarily distinct) from the sequence, order matters. @see: http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/190465 """ if n==0: yield [] else: for i in xrange(len(items)): for ss in xselections(items, n-1...
Makes weighted choices. Accepts a list of tuples with the item and probability as a pair like: >>> x = [('one', 0.25), ('two', 0.25), ('three', 0.5)] >>> y=windex(x)
def weighted_choice(lst): """ Makes weighted choices. Accepts a list of tuples with the item and probability as a pair like: >>> x = [('one', 0.25), ('two', 0.25), ('three', 0.5)] >>> y=windex(x) """ n = random.uniform(0, 1) for item, weight in lst: if n < weight: break ...
Plots the costs of the given generators.
def plotGenCost(generators): """ Plots the costs of the given generators. """ figure() plots = [] for generator in generators: if generator.pcost_model == PW_LINEAR: x = [x for x, _ in generator.p_cost] y = [y for _, y in generator.p_cost] elif generator.pcost...
Writes reward and action data for plotting sparklines with PGF/TikZ. @see: http://www.texample.net/tikz/examples/weather-stations-data/
def sparklineData(data, filename): """ Writes reward and action data for plotting sparklines with PGF/TikZ. @see: http://www.texample.net/tikz/examples/weather-stations-data/ """ fd = file(filename, "w+b") for name in data.keys(): action, reward = data[name] altName = name.lower()....
Writes market experiment data to file in ReStructuredText format.
def write(self, file): """ Writes market experiment data to file in ReStructuredText format. """ # Write environment state data. file.write("State\n") file.write( ("-" * 5) + "\n") self.writeDataTable(file, type="state") # Write action data. file.write("A...
Writes agent data to an ReST table. The 'type' argument may be 'state', 'action' or 'reward'.
def writeDataTable(self, file, type): """ Writes agent data to an ReST table. The 'type' argument may be 'state', 'action' or 'reward'. """ agents = self.experiment.agents numAgents = len(self.experiment.agents) colWidth = 8 idxColWidth = 3 sep = ("=" *...
Execute one action.
def performAction(self, action): """ Execute one action. """ # print "ACTION:", action self.t += 1 Task.performAction(self, action) # self.addReward() self.samples += 1
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. """ actorLimits = [] for _ in range(self.env.numOffbids): for _ in self.env.generators: ...
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 = [] limits.extend(self._getTotalDemandLimits()) # limits.extend(self._getDemandLimits()) # ...
Split equations into differential algebraic and algebraic only
def split_dae_alg(eqs: SYM, dx: SYM) -> Dict[str, SYM]: """Split equations into differential algebraic and algebraic only""" dae = [] alg = [] for eq in ca.vertsplit(eqs): if ca.depends_on(eq, dx): dae.append(eq) else: alg.append(eq) return { 'dae': ca...
Perumute a vector
def permute(x: SYM, perm: List[int]) -> SYM: """Perumute a vector""" x_s = [] for i in perm: x_s.append(x[i]) return ca.vertcat(*x_s)
Sort equations by dependence
def blt(f: List[SYM], x: List[SYM]) -> Dict[str, Any]: """ Sort equations by dependence """ J = ca.jacobian(f, x) nblock, rowperm, colperm, rowblock, colblock, coarserow, coarsecol = J.sparsity().btf() return { 'J': J, 'nblock': nblock, 'rowperm': rowperm, 'colper...
Create a tangent approximation of a non-linear function f(x) about point a using a block lower triangular solver 0 = f(x) = f(a) + J*x # taylor series about a (if f(x) linear in x, then globally valid) J*x = -f(a) # solve for x x = -J^{-1}f(a) # but inverse is slow, so we use solv...
def tangent_approx(f: SYM, x: SYM, a: SYM = None, assert_linear: bool = False) -> Dict[str, SYM]: """ Create a tangent approximation of a non-linear function f(x) about point a using a block lower triangular solver 0 = f(x) = f(a) + J*x # taylor series about a (if f(x) linear in x, then globally vali...
condition function
def create_function_f_c(self): """condition function""" return ca.Function( 'f_c', [self.t, self.x, self.y, self.m, self.p, self.ng, self.nu], [self.f_c], ['t', 'x', 'y', 'm', 'p', 'ng', 'nu'], ['c'], self.func_opt)
state reinitialization (reset) function
def create_function_f_i(self): """state reinitialization (reset) function""" return ca.Function( 'f_i', [self.t, self.x, self.y, self.m, self.p, self.c, self.pre_c, self.ng, self.nu], [self.f_i], ['t', 'x', 'y', 'm', 'p', 'c', 'pre_c', 'ng', 'nu'], ['x_n']...
Discrete state dynamics
def create_function_f_m(self): """Discrete state dynamics""" return ca.Function( 'f_m', [self.t, self.x, self.y, self.m, self.p, self.c, self.pre_c, self.ng, self.nu], [self.f_m], ['t', 'x', 'y', 'm', 'p', 'c', 'pre_c', 'ng', 'nu'], ['m'], self.func_opt)
Jacobian for state integration
def create_function_f_J(self): """Jacobian for state integration""" return ca.Function( 'J', [self.t, self.x, self.y, self.m, self.p, self.c, self.ng, self.nu], [ca.jacobian(self.f_x_rhs, self.x)], ['t', 'x', 'y', 'm', 'p', 'c', 'ng', 'nu'], ['J'], self.fu...
output function
def create_function_f_y(self): """output function""" return ca.Function( 'y', [self.t, self.x, self.m, self.p, self.c, self.ng, self.nu], [self.y_rhs], ['t', 'x', 'm', 'p', 'c', 'ng', 'nu'], ['y'], self.func_opt)
Convert to a HybridOde
def to_ode(self) -> HybridOde: """Convert to a HybridOde""" res_split = split_dae_alg(self.f_x, self.dx) alg = res_split['alg'] dae = res_split['dae'] x_rhs = tangent_approx(dae, self.dx, assert_linear=True) y_rhs = tangent_approx(alg, self.y, assert_linear=True) ...
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: [int]
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: [int] """ self._lastAction = [] # Markups chosen for each generator. ...
Converts arrays of percentage price markups and capacity withholds into offers/bids and submits them to the marketplace.
def _offbid(self, markups, withholds): """ Converts arrays of percentage price markups and capacity withholds into offers/bids and submits them to the marketplace. """ for i, g in enumerate(self.generators): ratedPMin = self._g0[g]["p_min"] ratedPMax = self._g0[g]...
Tries to infer a protocol from the file extension.
def format_from_extension(fname): """ Tries to infer a protocol from the file extension.""" _base, ext = os.path.splitext(fname) if not ext: return None try: format = known_extensions[ext.replace('.', '')] except KeyError: format = None return format
Parses the MATPOWER case files at the given paths and pickles the resulting Case objects to the same directory.
def pickle_matpower_cases(case_paths, case_format=2): """ Parses the MATPOWER case files at the given paths and pickles the resulting Case objects to the same directory. """ import pylon.io if isinstance(case_paths, basestring): case_paths = [case_paths] for case_path in case_paths...
Takes a single iterable as an argument and returns the same output as the built-in function max with two output parameters, except that where the maximum value occurs at more than one position in the vector, the index is chosen randomly from these positions as opposed to just choosing the first occuran...
def fair_max(x): """ Takes a single iterable as an argument and returns the same output as the built-in function max with two output parameters, except that where the maximum value occurs at more than one position in the vector, the index is chosen randomly from these positions as opposed to just choos...
Returns the factorial of n.
def factorial(n): """ Returns the factorial of n. """ f = 1 while (n > 0): f = f * n n = n - 1 return f
Returns the name, which is generated if it has not been already.
def _get_name(self): """ Returns the name, which is generated if it has not been already. """ if self._name is None: self._name = self._generate_name() return self._name
Save the object to a given file like object in the given format.
def save_to_file_object(self, fd, format=None, **kwargs): """ Save the object to a given file like object in the given format. """ format = 'pickle' if format is None else format save = getattr(self, "save_%s" % format, None) if save is None: raise ValueError("Unknown...
Load the object from a given file like object in the given format.
def load_from_file_object(cls, fd, format=None): """ Load the object from a given file like object in the given format. """ format = 'pickle' if format is None else format load = getattr(cls, "load_%s" % format, None) if load is None: raise ValueError("Unknown format ...
Save the object to file given by filename.
def save(self, filename, format=None, **kwargs): """ Save the object to file given by filename. """ if format is None: # try to derive protocol from file extension format = format_from_extension(filename) with file(filename, 'wb') as fp: self.save_to_f...
Return an instance of the class that is saved in the file with the given filename in the specified format.
def load(cls, filename, format=None): """ Return an instance of the class that is saved in the file with the given filename in the specified format. """ if format is None: # try to derive protocol from file extension format = format_from_extension(filename) ...
Solves a DC power flow.
def solve(self): """ Solves a DC power flow. """ case = self.case logger.info("Starting DC power flow [%s]." % case.name) t0 = time.time() # Update bus indexes. self.case.index_buses() # Find the index of the refence bus. ref_idx = self._get_refer...