INSTRUCTION stringlengths 1 46.3k | RESPONSE stringlengths 75 80.2k |
|---|---|
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.
@param start: Starting index, typically 0 or 1.
@type start: int | 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.
@param start: Starting index, typically 0 or 1.
@type start: int | 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.
@rtype: tuple
@return: A triple consisting of the bus admittance matrix (i.e. for all
buses) and the matrices Yf and Yt which, when... | 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.
@param method: Specify "XB" or "BX" method.
@type method: string
@rtype: tuple
@return: Two matrices, B prime and B double pr... | 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
The real power flows at the from end the lines are related to the bus
voltage angles by::
Pf = Bf * Va + Pfinj
| Pf | | Bff Bft | | Vaf | | Pfinj... | 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.
@return: The partial derivatives of power injection w.r.t. voltage
magnitude and voltage angle.
@rtype: tuple | 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.
@return: The partial derivatives of branch currents w.r.t. voltage
magnitude and voltage angle.
@rtype: tuple | 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.
@return: The branch power flow vectors and the partial derivatives of
branch power flow w.r.t voltage magnitude and voltage angle.
... | 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.
@rtype: tuple
@return: The partial derivatives of the squared flow magnitudes w.r.t
voltage magnitude and voltage angle giv... | 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.
@rtype: tuple
@return: The 2nd derivatives of power injection w.r.t. voltage. | 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.
@rtype: tuple
@return: The 2nd derivatives of complex branch current w.r.t. voltage. | 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.
@rtype: tuple
@return: The 2nd derivatives of complex power flow w.r.t. voltage. | 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.
@rtype: tuple
@return: The 2nd derivatives of |complex power flow|**2 w.r.t. V. | 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.
@rtype: tuple
@return: The 2nd derivatives of |complex current|**2 w.r.t. V. | 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.
Updates buses, generators and branches to match a power flow solution. | 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.
:param model_folder: Folder where the precompiled CasADi model will be stored.
:param model_name: Name of the model.
:param model: Model instance.
:param compiler_options: Dictionary of compiler options. | 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.
:param model_folder: Folder where the precompiled CasADi model is located.
:param model_name: Name of the model.
:param compiler_options: Dictionary of compiler options.
:returns: 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
@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{iterations} - the number of ite... | 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.
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 and
angles. | 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:
... |
Returns the Jacobian matrix. | def _build_jacobian(self, Ybus, V, pv, pq, pvpq):
""" Returns the Jacobian matrix.
"""
pq_col = [[i] for i in pq]
pvpq_col = [[i] for i in pvpq]
dS_dVm, dS_dVa = self.case.dSbus_dV(Ybus, V)
J11 = dS_dVa[pvpq_col, pvpq].real
J12 = dS_dVm[pvpq_col, pq].real
... |
Solves the power flow using a full Newton's method. | def _run_power_flow(self, Ybus, Sbus, V, pv, pq, pvpq):
""" Solves the power flow using a full Newton's method.
"""
i = 0
Va = angle(V)
Vm = abs(V)
# FIXME: Do not repeat build for each Q limit loop.
Bp, Bpp = self.case.makeB(method=self.method)
# Evalua... |
Evaluates the mismatch. | def _evaluate_mismatch(self, Ybus, V, Sbus, pq, pvpq):
""" Evaluates the mismatch.
"""
mis = (multiply(V, conj(Ybus * V)) - Sbus) / abs(V)
P = mis[pvpq].real
Q = mis[pq].imag
return P, Q |
Checks if the solution has converged to within the specified
tolerance. | def _check_convergence(self, P, Q, i, type):
""" Checks if the solution has converged to within the specified
tolerance.
"""
normP = linalg.norm(P, Inf)
normQ = linalg.norm(Q, Inf)
if self.verbose:
logger.info(" %s %3d %10.3e %10.3e" % (type,i, normP, n... |
Performs a P iteration, updates Va. | def _p_iteration(self, P, Bp_solver, Vm, Va, pvpq):
""" Performs a P iteration, updates Va.
"""
dVa = -Bp_solver.solve(P)
# Update voltage.
Va[pvpq] = Va[pvpq] + dVa
V = Vm * exp(1j * Va)
return V, Vm, Va |
Performs a Q iteration, updates Vm. | def _q_iteration(self, Q, Bpp_solver, Vm, Va, pq):
""" Performs a Q iteration, updates Vm.
"""
dVm = -Bpp_solver.solve(Q)
# Update voltage.
Vm[pq] = Vm[pq] + dVm
V = Vm * exp(1j * Va)
return V, Vm, Va |
Signal with sinusoidal frequency modulation.
generates a frequency modulation with a sinusoidal frequency.
This sinusoidal modulation is designed such that the instantaneous
frequency at time T0 is equal to FNORM0, and the ambiguity between
increasing or decreasing frequency is solved by PM1.
N ... | def fmsin(N, fnormin=0.05, fnormax=0.45, period=None, t0=None, fnorm0=0.25, pm1=1):
"""
Signal with sinusoidal frequency modulation.
generates a frequency modulation with a sinusoidal frequency.
This sinusoidal modulation is designed such that the instantaneous
frequency at time T0 is equal to FNOR... |
Converts XY point from Spherical Mercator EPSG:900913 to lat/lon in
WGS84 Datum | def metres2latlon(mx, my, origin_shift= 2 * pi * 6378137 / 2.0):
"""Converts XY point from Spherical Mercator EPSG:900913 to lat/lon in
WGS84 Datum"""
lon = (mx / origin_shift) * 180.0
lat = (my / origin_shift) * 180.0
lat = 180 / pi * (2 * atan( exp( lat * pi / 180.0)) - pi / 2.0)
return lat, ... |
Returns a case from the given file. | def _parse_rdf(self, file):
""" Returns a case from the given file.
"""
store = Graph()
store.parse(file)
print len(store) |
Load and installed metrics plugins. | def load_plugins(group='metrics.plugin.10'):
"""Load and installed metrics plugins.
"""
# on using entrypoints:
# http://stackoverflow.com/questions/774824/explain-python-entry-points
file_processors = []
build_processors = []
for ep in pkg_resources.iter_entry_points(group, name=None):
... |
Serialize ``obj`` as a JSON formatted stream to ``fp`` (a
``.write()``-supporting file-like object).
If ``skipkeys`` is ``True`` then ``dict`` keys that are not basic types
(``str``, ``unicode``, ``int``, ``long``, ``float``, ``bool``, ``None``)
will be skipped instead of raising a ``TypeError``.
... | def dump(obj, fp, skipkeys=False, ensure_ascii=True, check_circular=True,
allow_nan=True, cls=None, indent=None, **kw):
"""
Serialize ``obj`` as a JSON formatted stream to ``fp`` (a
``.write()``-supporting file-like object).
If ``skipkeys`` is ``True`` then ``dict`` keys that are not basic type... |
Serialize ``obj`` to a JSON formatted ``str``.
If ``skipkeys`` is ``True`` then ``dict`` keys that are not basic types
(``str``, ``unicode``, ``int``, ``long``, ``float``, ``bool``, ``None``)
will be skipped instead of raising a ``TypeError``.
If ``ensure_ascii`` is ``False``, then the return value w... | def dumps(obj, skipkeys=False, ensure_ascii=True, check_circular=True,
allow_nan=True, cls=None, indent=None, **kw):
"""
Serialize ``obj`` to a JSON formatted ``str``.
If ``skipkeys`` is ``True`` then ``dict`` keys that are not basic types
(``str``, ``unicode``, ``int``, ``long``, ``float``, ``... |
Deserialize ``fp`` (a ``.read()``-supporting file-like object containing
a JSON document) to a Python object.
If the contents of ``fp`` is encoded with an ASCII based encoding other
than utf-8 (e.g. latin-1), then an appropriate ``encoding`` name must
be specified. Encodings that are not ASCII based (... | def load(fp, encoding=None, cls=None, object_hook=None, **kw):
"""
Deserialize ``fp`` (a ``.read()``-supporting file-like object containing
a JSON document) to a Python object.
If the contents of ``fp`` is encoded with an ASCII based encoding other
than utf-8 (e.g. latin-1), then an appropriate ``e... |
Deserialize ``s`` (a ``str`` or ``unicode`` instance containing a JSON
document) to a Python object.
If ``s`` is a ``str`` instance and is encoded with an ASCII based encoding
other than utf-8 (e.g. latin-1) then an appropriate ``encoding`` name
must be specified. Encodings that are not ASCII based (s... | def loads(s, encoding=None, cls=None, object_hook=None, **kw):
"""
Deserialize ``s`` (a ``str`` or ``unicode`` instance containing a JSON
document) to a Python object.
If ``s`` is a ``str`` instance and is encoded with an ASCII based encoding
other than utf-8 (e.g. latin-1) then an appropriate ``en... |
Returns a case object from the given input file object. The data
format may be optionally specified. | def read_case(input, format=None):
""" Returns a case object from the given input file object. The data
format may be optionally specified.
"""
# Map of data file types to readers.
format_map = {"matpower": MATPOWERReader,
"psse": PSSEReader, "pickle": PickleReader}
# Read case data.
... |
Detects the format of a network data file according to the
file extension and the header. | def detect_data_file(input, file_name=""):
""" Detects the format of a network data file according to the
file extension and the header.
"""
_, ext = os.path.splitext(file_name)
if ext == ".m":
line = input.readline() # first line
if line.startswith("function"):
type... |
Parses the command line and call Pylon with the correct data. | def main():
""" Parses the command line and call Pylon with the correct data.
"""
parser = optparse.OptionParser(usage="usage: pylon [options] input_file",
version="%prog 0.4.4")
parser.add_option("-o", "--output", dest="output", metavar="FILE",
help="Write th... |
Writes the case data in Graphviz DOT language.
The format 'raw' is used to dump the Dot representation of the Case
object, without further processing. The output can be processed by any
of graphviz tools, defined in 'prog'. | def write(self, file_or_filename, prog=None, format='xdot'):
""" Writes the case data in Graphviz DOT language.
The format 'raw' is used to dump the Dot representation of the Case
object, without further processing. The output can be processed by any
of graphviz tools, defined in 'prog'... |
Writes bus data to file. | def write_bus_data(self, file, padding=" "):
""" Writes bus data to file.
"""
for bus in self.case.buses:
attrs = ['%s="%s"' % (k, v) for k, v in self.bus_attr.iteritems()]
# attrs.insert(0, 'label="%s"' % bus.name)
attr_str = ", ".join(attrs)
f... |
Writes branch data in Graphviz DOT language. | def write_branch_data(self, file, padding=" "):
""" Writes branch data in Graphviz DOT language.
"""
attrs = ['%s="%s"' % (k,v) for k,v in self.branch_attr.iteritems()]
attr_str = ", ".join(attrs)
for br in self.case.branches:
file.write("%s%s -> %s [%s];\n" % \
... |
Write generator data in Graphviz DOT language. | def write_generator_data(self, file, padding=" "):
""" Write generator data in Graphviz DOT language.
"""
attrs = ['%s="%s"' % (k, v) for k, v in self.gen_attr.iteritems()]
attr_str = ", ".join(attrs)
edge_attrs = ['%s="%s"' % (k,v) for k,v in {}.iteritems()]
edge_att... |
Creates and returns a representation of the graph using the
Graphviz layout program given by 'prog', according to the given format.
Writes the graph to a temporary dot file and processes it with the
program given by 'prog' (which defaults to 'dot'), reading the output
and returning it a... | def create(self, dotdata, prog="dot", format="xdot"):
""" Creates and returns a representation of the graph using the
Graphviz layout program given by 'prog', according to the given format.
Writes the graph to a temporary dot file and processes it with the
program given by 'prog' (which... |
compute output in XML format. | def format(file_metrics, build_metrics):
"""compute output in XML format."""
def indent(elem, level=0):
i = "\n" + level*" "
if len(elem):
if not elem.text or not elem.text.strip():
elem.text = i + " "
if not elem.tail or not elem.tail.strip():
... |
Primal-dual interior point method for NLP (non-linear programming).
Minimize a function F(X) beginning from a starting point M{x0}, subject to
optional linear and non-linear constraints and variable bounds::
min f(x)
x
subject to::
g(x) = 0 (non-linear equa... | def pips(f_fcn, x0, A=None, l=None, u=None, xmin=None, xmax=None,
gh_fcn=None, hess_fcn=None, opt=None):
"""Primal-dual interior point method for NLP (non-linear programming).
Minimize a function F(X) beginning from a starting point M{x0}, subject to
optional linear and non-linear constraints and v... |
Uses the Python Interior Point Solver (PIPS) to solve the following
QP (quadratic programming) problem::
min 1/2 x'*H*x + C'*x
x
subject to::
l <= A*x <= u (linear constraints)
xmin <= x <= xmax (variable bounds)
Note the calling syntax is almost ... | def qps_pips(H, c, A, l, u, xmin=None, xmax=None, x0=None, opt=None):
"""Uses the Python Interior Point Solver (PIPS) to solve the following
QP (quadratic programming) problem::
min 1/2 x'*H*x + C'*x
x
subject to::
l <= A*x <= u (linear constraints)
... |
Asks the user his opinion. | def ask(message='Are you sure? [y/N]'):
"""Asks the user his opinion."""
agree = False
answer = raw_input(message).lower()
if answer.startswith('y'):
agree = True
return agree |
What do you expect? | def main(prog_args=None):
"""
What do you expect?
"""
if prog_args is None:
prog_args = sys.argv
parser = optparse.OptionParser()
parser.usage = """Usage: %[prog] [options] [<path>]"""
parser.add_option("-t", "--test-program", dest="test_program",
default="nose", help="speci... |
Checks if configuration is ok. | def check_configuration(self, file_path, test_program, custom_args):
"""Checks if configuration is ok."""
# checking filepath
if not os.path.isdir(file_path):
raise InvalidFilePath("INVALID CONFIGURATION: file path %s is not a directory" %
os.path.abspath(file_path)
... |
Checks if the test program is available in the python environnement | def check_dependencies(self):
"Checks if the test program is available in the python environnement"
if self.test_program == 'nose':
try:
import nose
except ImportError:
sys.exit('Nosetests is not available on your system. Please install it and try ... |
Returns the full command to be executed at runtime | def get_cmd(self):
"""Returns the full command to be executed at runtime"""
cmd = None
if self.test_program in ('nose', 'nosetests'):
cmd = "nosetests %s" % self.file_path
elif self.test_program == 'django':
executable = "%s/manage.py" % self.file_path
... |
Returns `True` if the file is not ignored | def include(self, path):
"""Returns `True` if the file is not ignored"""
for extension in IGNORE_EXTENSIONS:
if path.endswith(extension):
return False
parts = path.split(os.path.sep)
for part in parts:
if part in self.ignore_dirs:
r... |
Walks the walk. nah, seriously: reads the file and stores a hashkey
corresponding to its content. | def walk(self, top, file_list={}):
"""Walks the walk. nah, seriously: reads the file and stores a hashkey
corresponding to its content."""
for root, dirs, files in os.walk(top, topdown=False):
if os.path.basename(root) in self.ignore_dirs:
# Do not dig in ignored dirs... |
Returns total filesize (in MB) | def file_sizes(self):
"""Returns total filesize (in MB)"""
size = sum(map(os.path.getsize, self.file_list))
return size / 1024 / 1024 |
Extracts differences between lists. For debug purposes | def diff_list(self, list1, list2):
"""Extracts differences between lists. For debug purposes"""
for key in list1:
if key in list2 and list2[key] != list1[key]:
print key
elif key not in list2:
print key |
Runs the appropriate command | def run(self, cmd):
"""Runs the appropriate command"""
print datetime.datetime.now()
output = subprocess.Popen(cmd, shell=True)
output = output.communicate()[0]
print output |
Main loop daemon. | def loop(self):
"""Main loop daemon."""
while True:
sleep(1)
new_file_list = self.walk(self.file_path, {})
if new_file_list != self.file_list:
if self.debug:
self.diff_list(new_file_list, self.file_list)
self.run_tes... |
compute output in JSON format. | def format(file_metrics, build_metrics):
"""compute output in JSON format."""
metrics = {'files': file_metrics}
if build_metrics:
metrics['build'] = build_metrics
body = json.dumps(metrics, sort_keys=True, indent=4) + '\n'
return body |
Returns the linear equality and inequality constraints. | def split_linear_constraints(A, l, u):
""" Returns the linear equality and inequality constraints.
"""
ieq = []
igt = []
ilt = []
ibx = []
for i in range(len(l)):
if abs(u[i] - l[i]) <= EPS:
ieq.append(i)
elif (u[i] > 1e10) and (l[i] > -1e10):
igt.appe... |
Computes the partial derivative of power injection w.r.t. voltage.
References:
Ray Zimmerman, "dSbus_dV.m", MATPOWER, version 3.2,
PSERC (Cornell), http://www.pserc.cornell.edu/matpower/ | def dSbus_dV(Y, V):
""" Computes the partial derivative of power injection w.r.t. voltage.
References:
Ray Zimmerman, "dSbus_dV.m", MATPOWER, version 3.2,
PSERC (Cornell), http://www.pserc.cornell.edu/matpower/
"""
I = Y * V
diagV = spdiag(V)
diagIbus = spdiag(I)
... |
Computes partial derivatives of branch currents w.r.t. voltage.
Ray Zimmerman, "dIbr_dV.m", MATPOWER, version 4.0b1,
PSERC (Cornell), http://www.pserc.cornell.edu/matpower/ | def dIbr_dV(Yf, Yt, V):
""" Computes partial derivatives of branch currents w.r.t. voltage.
Ray Zimmerman, "dIbr_dV.m", MATPOWER, version 4.0b1,
PSERC (Cornell), http://www.pserc.cornell.edu/matpower/
"""
# nb = len(V)
Vnorm = div(V, abs(V))
diagV = spdiag(V)
diagVnorm = spd... |
Computes the branch power flow vector and the partial derivative of
branch power flow w.r.t voltage. | def dSbr_dV(Yf, Yt, V, buses, branches):
""" Computes the branch power flow vector and the partial derivative of
branch power flow w.r.t voltage.
"""
nl = len(branches)
nb = len(V)
f = matrix([l.from_bus._i for l in branches])
t = matrix([l.to_bus._i for l in branches])
# Compute c... |
Partial derivatives of squared flow magnitudes w.r.t voltage.
Computes partial derivatives of apparent power w.r.t active and
reactive power flows. Partial derivative must equal 1 for lines
with zero flow to avoid division by zero errors (1 comes from
L'Hopital). | def dAbr_dV(dSf_dVa, dSf_dVm, dSt_dVa, dSt_dVm, Sf, St):
""" Partial derivatives of squared flow magnitudes w.r.t voltage.
Computes partial derivatives of apparent power w.r.t active and
reactive power flows. Partial derivative must equal 1 for lines
with zero flow to avoid division by zer... |
Computes 2nd derivatives of power injection w.r.t. voltage. | def d2Sbus_dV2(Ybus, V, lam):
""" Computes 2nd derivatives of power injection w.r.t. voltage.
"""
n = len(V)
Ibus = Ybus * V
diaglam = spdiag(lam)
diagV = spdiag(V)
A = spmatrix(mul(lam, V), range(n), range(n))
B = Ybus * diagV
C = A * conj(B)
D = Ybus.H * diagV
E = conj(dia... |
Computes 2nd derivatives of complex branch current w.r.t. voltage. | def d2Ibr_dV2(Ybr, V, lam):
""" Computes 2nd derivatives of complex branch current w.r.t. voltage.
"""
nb = len(V)
diaginvVm = spdiag(div(matrix(1.0, (nb, 1)), abs(V)))
Haa = spdiag(mul(-(Ybr.T * lam), V))
Hva = -1j * Haa * diaginvVm
Hav = Hva
Hvv = spmatrix([], [], [], (nb, nb))
r... |
Computes 2nd derivatives of complex power flow w.r.t. voltage. | def d2Sbr_dV2(Cbr, Ybr, V, lam):
""" Computes 2nd derivatives of complex power flow w.r.t. voltage.
"""
nb = len(V)
diaglam = spdiag(lam)
diagV = spdiag(V)
A = Ybr.H * diaglam * Cbr
B = conj(diagV) * A * diagV
D = spdiag(mul((A*V), conj(V)))
E = spdiag(mul((A.T * conj(V)), V))
... |
Computes 2nd derivatives of |complex power flow|**2 w.r.t. V. | def d2ASbr_dV2(dSbr_dVa, dSbr_dVm, Sbr, Cbr, Ybr, V, lam):
""" Computes 2nd derivatives of |complex power flow|**2 w.r.t. V.
"""
diaglam = spdiag(lam)
diagSbr_conj = spdiag(conj(Sbr))
Saa, Sav, Sva, Svv = d2Sbr_dV2(Cbr, Ybr, V, diagSbr_conj * lam)
Haa = 2 * ( Saa + dSbr_dVa.T * diaglam * conj(... |
Computes 2nd derivatives of |complex current|**2 w.r.t. V. | def d2AIbr_dV2(dIbr_dVa, dIbr_dVm, Ibr, Ybr, V, lam):
""" Computes 2nd derivatives of |complex current|**2 w.r.t. V.
"""
diaglam = spdiag(lam)
diagIbr_conj = spdiag(conj(Ibr))
Iaa, Iav, Iva, Ivv = d2Ibr_dV2(Ybr, V, diagIbr_conj * lam)
Haa = 2 * ( Iaa + dIbr_dVa.T * diaglam * conj(dIbr_dVa) ).r... |
Converts a sparse SciPy matrix into a sparse CVXOPT matrix. | def tocvx(B):
""" Converts a sparse SciPy matrix into a sparse CVXOPT matrix.
"""
Bcoo = B.tocoo()
return spmatrix(Bcoo.data, Bcoo.row.tolist(), Bcoo.col.tolist()) |
Solves the either quadratic or linear program. | def _run_opf(self, P, q, AA, ll, uu, xmin, xmax, x0, opt):
""" Solves the either quadratic or linear program.
"""
AAcvx = tocvx(AA)
nx = x0.shape[0] # number of variables
# add var limits to linear constraints
eyex = spmatrix(1.0, range(nx), range(nx))
A = sparse(... |
Calculates the result attribute values. | def _update_case(self, bs, ln, gn, base_mva, Bf, Pfinj, Va, Pg, lmbda):
""" Calculates the result attribute values.
"""
for i, bus in enumerate(bs):
bus.v_angle = Va[i] * 180.0 / pi |
Directly maps the agents and the tasks. | def doInteractions(self, number=1):
""" Directly maps the agents and the tasks.
"""
t0 = time.time()
for _ in range(number):
self._oneInteraction()
elapsed = time.time() - t0
logger.info("%d interactions executed in %.3fs." % (number, elapsed))
retu... |
Coordinates one interaction between each agent and its environment. | def _oneInteraction(self):
""" Coordinates one interaction between each agent and its environment.
"""
self.stepid += 1
logger.info("\nEntering simulation period %d." % self.stepid)
# Initialise the market.
self.market.reset()
# Get an action from each agent an... |
Based on AugYbus.m from MatDyn by Stijn Cole, developed at
Katholieke Universiteit Leuven. See U{http://www.esat.kuleuven.be/
electa/teaching/matdyn/} for more information.
@rtype: csr_matrix
@return: The augmented bus admittance matrix. | def getAugYbus(self, U0, gbus):
""" Based on AugYbus.m from MatDyn by Stijn Cole, developed at
Katholieke Universiteit Leuven. See U{http://www.esat.kuleuven.be/
electa/teaching/matdyn/} for more information.
@rtype: csr_matrix
@return: The augmented bus admittance matrix.
... |
Based on GeneratorInit.m from MatDyn by Stijn Cole, developed at
Katholieke Universiteit Leuven. See U{http://www.esat.kuleuven.be/
electa/teaching/matdyn/} for more information.
@rtype: tuple
@return: Initial generator conditions. | def generatorInit(self, U0):
""" Based on GeneratorInit.m from MatDyn by Stijn Cole, developed at
Katholieke Universiteit Leuven. See U{http://www.esat.kuleuven.be/
electa/teaching/matdyn/} for more information.
@rtype: tuple
@return: Initial generator conditions.
"""
... |
Based on ExciterInit.m from MatDyn by Stijn Cole, developed at
Katholieke Universiteit Leuven. See U{http://www.esat.kuleuven.be/
electa/teaching/matdyn/} for more information.
@rtype: tuple
@return: Exciter initial conditions. | def exciterInit(self, Xexc, Vexc):
""" Based on ExciterInit.m from MatDyn by Stijn Cole, developed at
Katholieke Universiteit Leuven. See U{http://www.esat.kuleuven.be/
electa/teaching/matdyn/} for more information.
@rtype: tuple
@return: Exciter initial conditions.
"""
... |
Based on GovernorInit.m from MatDyn by Stijn Cole, developed at
Katholieke Universiteit Leuven. See U{http://www.esat.kuleuven.be/
electa/teaching/matdyn/} for more information.
@rtype: tuple
@return: Initial governor conditions. | def governorInit(self, Xgov, Vgov):
""" Based on GovernorInit.m from MatDyn by Stijn Cole, developed at
Katholieke Universiteit Leuven. See U{http://www.esat.kuleuven.be/
electa/teaching/matdyn/} for more information.
@rtype: tuple
@return: Initial governor conditions.
"... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.