INSTRUCTION
stringlengths
1
8.43k
RESPONSE
stringlengths
75
104k
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...
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"]
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: ...
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.
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.
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):...
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 ...
Takes n elements ( not necessarily distinct ) from the sequence order matters.
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...
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.
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
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.
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 occurance.
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...
Returns the index of the reference bus.
def _get_reference_index(self, case): """ Returns the index of the reference bus. """ refs = [bus._i for bus in case.connected_buses if bus.type == REFERENCE] if len(refs) == 1: return refs [0] else: logger.error("Single swing bus required for DCPF.") ...
Make the vector of voltage phase guesses.
def _get_v_angle_guess(self, case): """ Make the vector of voltage phase guesses. """ v_angle = array([bus.v_angle * (pi / 180.0) for bus in case.connected_buses]) return v_angle
Calculates the voltage phase angles.
def _get_v_angle(self, case, B, v_angle_guess, p_businj, iref): """ Calculates the voltage phase angles. """ buses = case.connected_buses pv_idxs = [bus._i for bus in buses if bus.type == PV] pq_idxs = [bus._i for bus in buses if bus.type == PQ] pvpq_idxs = pv_idxs + pq_...
Updates the case with values computed from the voltage phase angle solution.
def _update_model(self, case, B, Bsrc, v_angle, p_srcinj, p_ref, ref_idx): """ Updates the case with values computed from the voltage phase angle solution. """ iref = ref_idx base_mva = case.base_mva buses = case.connected_buses branches = case.online_branches...
Resets the readonly variables.
def reset(self): """ Resets the readonly variables. """ self.p_lmbda = 0.0 self.q_lmbda = 0.0 self.mu_vmin = 0.0 self.mu_vmax = 0.0
Resets the readonly variables.
def reset(self): """ Resets the readonly variables. """ self.p_from = 0.0 self.p_to = 0.0 self.q_from = 0.0 self.q_to = 0.0 self.mu_s_from = 0.0 self.mu_s_to = 0.0 self.mu_angmin = 0.0 self.mu_angmax = 0.0
Returns the net complex bus power injection vector in p. u.
def getSbus(self, buses=None): """ Returns the net complex bus power injection vector in p.u. """ bs = self.buses if buses is None else buses s = array([self.s_surplus(v) / self.base_mva for v in bs]) return s
Reorders the list of generators according to bus index.
def sort_generators(self): """ Reorders the list of generators according to bus index. """ self.generators.sort(key=lambda gn: gn.bus._i)
Updates the indices of all buses.
def index_buses(self, buses=None, start=0): """ Updates the indices of all buses. @param start: Starting index, typically 0 or 1. @type start: int """ bs = self.connected_buses if buses is None else buses for i, b in enumerate(bs): b._i = start + i
Updates the indices of all branches.
def index_branches(self, branches=None, start=0): """ Updates the indices of all branches. @param start: Starting index, typically 0 or 1. @type start: int """ ln = self.online_branches if branches is None else branches for i, l in enumerate(ln): l._i = start...
Returns the total complex power generation capacity.
def s_supply(self, bus): """ Returns the total complex power generation capacity. """ Sg = array([complex(g.p, g.q) for g in self.generators if (g.bus == bus) and not g.is_load], dtype=complex64) if len(Sg): return sum(Sg) else: return ...
Returns the total complex power demand.
def s_demand(self, bus): """ Returns the total complex power demand. """ Svl = array([complex(g.p, g.q) for g in self.generators if (g.bus == bus) and g.is_load], dtype=complex64) Sd = complex(bus.p_demand, bus.q_demand) return -sum(Svl) + Sd
Based on makeYbus. m from MATPOWER by Ray Zimmerman developed at PSERC Cornell. See U { http:// www. pserc. cornell. edu/ matpower/ } for more information.
def getYbus(self, buses=None, branches=None): """ Based on makeYbus.m from MATPOWER by Ray Zimmerman, developed at PSERC Cornell. See U{http://www.pserc.cornell.edu/matpower/} for more information. @rtype: tuple @return: A triple consisting of the bus admittance matrix (i.e. for...
Based on makeB. m from MATPOWER by Ray Zimmerman developed at PSERC Cornell. See U { http:// www. pserc. cornell. edu/ matpower/ } for more information.
def makeB(self, buses=None, branches=None, method="XB"): """ Based on makeB.m from MATPOWER by Ray Zimmerman, developed at PSERC Cornell. See U{http://www.pserc.cornell.edu/matpower/} for more information. @param method: Specify "XB" or "BX" method. @type method: string ...
The bus real power injections are related to bus voltage angles by:: P = Bbus * Va + Pbusinj
def makeBdc(self, buses=None, branches=None): """ The bus real power injections are related to bus voltage angles by:: P = Bbus * Va + Pbusinj The real power flows at the from end the lines are related to the bus voltage angles by:: Pf = Bf * Va + Pfinj ...
Based on dSbus_dV. m from MATPOWER by Ray Zimmerman developed at PSERC Cornell. See U { http:// www. pserc. cornell. edu/ matpower/ } for more information.
def dSbus_dV(self, Y, V): """ Based on dSbus_dV.m from MATPOWER by Ray Zimmerman, developed at PSERC Cornell. See U{http://www.pserc.cornell.edu/matpower/} for more information. @return: The partial derivatives of power injection w.r.t. voltage magnitude and voltage ang...
Based on dIbr_dV. m from MATPOWER by Ray Zimmerman developed at PSERC Cornell. See U { http:// www. pserc. cornell. edu/ matpower/ } for more information.
def dIbr_dV(self, Yf, Yt, V): """ Based on dIbr_dV.m from MATPOWER by Ray Zimmerman, developed at PSERC Cornell. See U{http://www.pserc.cornell.edu/matpower/} for more information. @return: The partial derivatives of branch currents w.r.t. voltage magnitude and voltage ...
Based on dSbr_dV. m from MATPOWER by Ray Zimmerman developed at PSERC Cornell. See U { http:// www. pserc. cornell. edu/ matpower/ } for more information.
def dSbr_dV(self, Yf, Yt, V, buses=None, branches=None): """ Based on dSbr_dV.m from MATPOWER by Ray Zimmerman, developed at PSERC Cornell. See U{http://www.pserc.cornell.edu/matpower/} for more information. @return: The branch power flow vectors and the partial derivatives of ...
Based on dAbr_dV. m from MATPOWER by Ray Zimmerman developed at PSERC Cornell. See U { http:// www. pserc. cornell. edu/ matpower/ } for more information.
def dAbr_dV(self, dSf_dVa, dSf_dVm, dSt_dVa, dSt_dVm, Sf, St): """ Based on dAbr_dV.m from MATPOWER by Ray Zimmerman, developed at PSERC Cornell. See U{http://www.pserc.cornell.edu/matpower/} for more information. @rtype: tuple @return: The partial derivatives of the squared flo...
Based on d2Sbus_dV2. m from MATPOWER by Ray Zimmerman developed at PSERC Cornell. See U { http:// www. pserc. cornell. edu/ matpower/ } for more information.
def d2Sbus_dV2(self, Ybus, V, lam): """ Based on d2Sbus_dV2.m from MATPOWER by Ray Zimmerman, developed at PSERC Cornell. See U{http://www.pserc.cornell.edu/matpower/} for more information. @rtype: tuple @return: The 2nd derivatives of power injection w.r.t. voltage. """...
Based on d2Ibr_dV2. m from MATPOWER by Ray Zimmerman developed at PSERC Cornell. See U { http:// www. pserc. cornell. edu/ matpower/ } for more information.
def d2Ibr_dV2(self, Ybr, V, lam): """ Based on d2Ibr_dV2.m from MATPOWER by Ray Zimmerman, developed at PSERC Cornell. See U{http://www.pserc.cornell.edu/matpower/} for more information. @rtype: tuple @return: The 2nd derivatives of complex branch current w.r.t. voltage. ...
Based on d2Sbr_dV2. m from MATPOWER by Ray Zimmerman developed at PSERC Cornell. See U { http:// www. pserc. cornell. edu/ matpower/ } for more information.
def d2Sbr_dV2(self, Cbr, Ybr, V, lam): """ Based on d2Sbr_dV2.m from MATPOWER by Ray Zimmerman, developed at PSERC Cornell. See U{http://www.pserc.cornell.edu/matpower/} for more information. @rtype: tuple @return: The 2nd derivatives of complex power flow w.r.t. voltage. ...
Based on d2ASbr_dV2. m from MATPOWER by Ray Zimmerman developed at PSERC Cornell. See U { http:// www. pserc. cornell. edu/ matpower/ } for more information.
def d2ASbr_dV2(self, dSbr_dVa, dSbr_dVm, Sbr, Cbr, Ybr, V, lam): """ Based on d2ASbr_dV2.m from MATPOWER by Ray Zimmerman, developed at PSERC Cornell. See U{http://www.pserc.cornell.edu/matpower/} for more information. @rtype: tuple @return: The 2nd derivatives of |complex power...
Based on d2AIbr_dV2. m from MATPOWER by Ray Zimmerman developed at PSERC Cornell. See U { http:// www. pserc. cornell. edu/ matpower/ } for more information.
def d2AIbr_dV2(self, dIbr_dVa, dIbr_dVm, Ibr, Ybr, V, lam): """ Based on d2AIbr_dV2.m from MATPOWER by Ray Zimmerman, developed at PSERC Cornell. See U{http://www.pserc.cornell.edu/matpower/} for more information. @rtype: tuple @return: The 2nd derivatives of |complex current|**...
Based on pfsoln. m from MATPOWER by Ray Zimmerman developed at PSERC Cornell. See U { http:// www. pserc. cornell. edu/ matpower/ } for more information.
def pf_solution(self, Ybus, Yf, Yt, V): """ Based on pfsoln.m from MATPOWER by Ray Zimmerman, developed at PSERC Cornell. See U{http://www.pserc.cornell.edu/matpower/} for more information. Updates buses, generators and branches to match a power flow solution. """ buses ...
Resets the readonly variables for all of the case components.
def reset(self): """ Resets the readonly variables for all of the case components. """ for bus in self.buses: bus.reset() for branch in self.branches: branch.reset() for generator in self.generators: generator.reset()
Serialize the case as a MATPOWER data file.
def save_matpower(self, fd): """ Serialize the case as a MATPOWER data file. """ from pylon.io import MATPOWERWriter MATPOWERWriter(self).write(fd)
Serialize the case as a PSS/ E data file.
def save_psse(self, fd): """ Serialize the case as a PSS/E data file. """ from pylon.io import PSSEWriter return PSSEWriter(self).write(fd)
Returns a case object from the given PSAT data file.
def load_psat(cls, fd): """ Returns a case object from the given PSAT data file. """ from pylon.io.psat import PSATReader return PSATReader().read(fd)
Save a reStructuredText representation of the case.
def save_rst(self, fd): """ Save a reStructuredText representation of the case. """ from pylon.io import ReSTWriter ReSTWriter(self).write(fd)
Saves the case as a series of Comma - Separated Values.
def save_csv(self, fd): """ Saves the case as a series of Comma-Separated Values. """ from pylon.io.excel import CSVWriter CSVWriter(self).write(fd)
Saves the case as an Excel spreadsheet.
def save_excel(self, fd): """ Saves the case as an Excel spreadsheet. """ from pylon.io.excel import ExcelWriter ExcelWriter(self).write(fd)
Saves a representation of the case in the Graphviz DOT language.
def save_dot(self, fd): """ Saves a representation of the case in the Graphviz DOT language. """ from pylon.io import DotWriter DotWriter(self).write(fd)
Saves a CasADi model to disk.
def save_model(model_folder: str, model_name: str, model: Model, compiler_options: Dict[str, str]) -> None: """ Saves a CasADi model to disk. :param model_folder: Folder where the precompiled CasADi model will be stored. :param model_name: Name of the model. :param model: Model insta...
Loads a precompiled CasADi model into a CachedModel instance.
def load_model(model_folder: str, model_name: str, compiler_options: Dict[str, str]) -> CachedModel: """ Loads a precompiled CasADi model into a CachedModel instance. :param model_folder: Folder where the precompiled CasADi model is located. :param model_name: Name of the model. :param compiler_opt...
Solves AC optimal power flow.
def solve(self): """ Solves AC optimal power flow. """ case = self.om.case base_mva = case.base_mva # TODO: Explain this value. self.opt["cost_mult"] = 1e-4 # Unpack the OPF model. bs, ln, gn, _ = self._unpack_model(self.om) # Compute problem dime...
Runs a power flow
def solve(self): """ Runs a power flow @rtype: dict @return: Solution dictionary with the following keys: - C{V} - final complex voltages - C{converged} - boolean value indicating if the solver converged or not - C{it...
Returns the contents of the case to be used in the OPF.
def _unpack_case(self, case): """ Returns the contents of the case to be used in the OPF. """ base_mva = case.base_mva b = case.connected_buses l = case.online_branches g = case.online_generators nb = len(b) nl = len(l) ng = len(g) return ...
Set up indexing for updating v.
def _index_buses(self, buses): """ Set up indexing for updating v. """ refs = [bus._i for bus in buses if bus.type == REFERENCE] # if len(refs) != 1: # raise SlackBusError pv = [bus._i for bus in buses if bus.type == PV] pq = [bus._i for bus in buses if bus.type...
Returns the initial vector of complex bus voltages.
def _initial_voltage(self, buses, generators): """ Returns the initial vector of complex bus voltages. The bus voltage vector contains the set point for generator (including ref bus) buses, and the reference angle of the swing bus, as well as an initial guess for remaining magnitudes an...
Solves the power flow using a full Newton s method.
def _run_power_flow(self, Ybus, Sbus, V, pv, pq, pvpq, **kw_args): """ Solves the power flow using a full Newton's method. """ Va = angle(V) Vm = abs(V) # Initial evaluation of F(x0)... F = self._evaluate_function(Ybus, V, Sbus, pv, pq) # ...and convergency check...
Performs one Newton iteration.
def _one_iteration(self, F, Ybus, V, Vm, Va, pv, pq, pvpq): """ Performs one Newton iteration. """ J = self._build_jacobian(Ybus, V, pv, pq, pvpq) # Update step. dx = -1 * spsolve(J, F) # dx = -1 * linalg.lstsq(J.todense(), F)[0] # Update voltage vector. ...
Evaluates F ( x ).
def _evaluate_function(self, Ybus, V, Sbus, pv, pq): """ Evaluates F(x). """ mis = multiply(V, conj(Ybus * V)) - Sbus F = r_[mis[pv].real, mis[pq].real, mis[pq].imag] return F
Checks if the solution has converged to within the specified tolerance.
def _check_convergence(self, F): """ Checks if the solution has converged to within the specified tolerance. """ normF = linalg.norm(F, Inf) if normF < self.tolerance: converged = True else: converged = False if self.verbose: ...