INSTRUCTION stringlengths 1 8.43k | RESPONSE stringlengths 75 104k |
|---|---|
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. | 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 ). | 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. | 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. | 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. | 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. | 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. | 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:: | 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:: | 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. | 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. | 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. | 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. | 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. | 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. | 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. | 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.
"... |
Based on MachineCurrents. m from MatDyn by Stijn Cole developed at Katholieke Universiteit Leuven. See U { http:// www. esat. kuleuven. be/ electa/ teaching/ matdyn/ } for more information. | def machineCurrents(self, Xg, U):
""" Based on MachineCurrents.m from MatDyn by Stijn Cole, developed at
Katholieke Universiteit Leuven. See U{http://www.esat.kuleuven.be/
electa/teaching/matdyn/} for more information.
@param Xg: Generator state variables.
@param U: Generator vo... |
Based on SolveNetwork. m from MatDyn by Stijn Cole developed at Katholieke Universiteit Leuven. See U { http:// www. esat. kuleuven. be/ electa/ teaching/ matdyn/ } for more information. | def solveNetwork(self, Xgen, augYbus_solver, gbus):
""" Based on SolveNetwork.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: array
@return: Bus voltages.
... |
Exciter model. | def exciter(self, Xexc, Pexc, Vexc):
""" Exciter model.
Based on Exciter.m from MatDyn by Stijn Cole, developed at Katholieke
Universiteit Leuven. See U{http://www.esat.kuleuven.be/electa/teaching/
matdyn/} for more information.
"""
exciters = self.exciters
F = ... |
Governor model. | def governor(self, Xgov, Pgov, Vgov):
""" Governor model.
Based on Governor.m from MatDyn by Stijn Cole, developed at Katholieke
Universiteit Leuven. See U{http://www.esat.kuleuven.be/electa/teaching/
matdyn/} for more information.
"""
governors = self.governors
... |
Generator model. | def generator(self, Xgen, Xexc, Xgov, Vgen):
""" Generator model.
Based on Generator.m from MatDyn by Stijn Cole, developed at Katholieke
Universiteit Leuven. See U{http://www.esat.kuleuven.be/electa/teaching/
matdyn/} for more information.
"""
generators = self.dyn_gene... |
Runs dynamic simulation. | def solve(self):
""" Runs dynamic simulation.
@rtype: dict
@return: Solution dictionary with the following keys:
- C{angles} - generator angles
- C{speeds} - generator speeds
- C{eq_tr} - q component of transient voltage behind
... |
NB: Insert \ newcolumntype {. } [ 1 ] { D {. } {. } { #1 }} in header. | def tex_table(a1, a2, mup):
""" NB: Insert \newcolumntype{.}[1]{D{.}{.}{#1}} in header.
"""
assert a1.shape == a2.shape
m, n = a1.shape
s = ""
s += "\\begin{table}\n"
s += "\\begin{center}\n"
cols = "c.{2.2}" + ("|.{2.1}.{3.1}" * (n)) + "|"
s += "\\begin{tabular}{%s}\n" % cols
s ... |
Writes case data to file in ReStructuredText format. | def _write_data(self, file):
""" Writes case data to file in ReStructuredText format.
"""
self.write_case_data(file)
file.write("Bus Data\n")
file.write("-" * 8 + "\n")
self.write_bus_data(file)
file.write("\n")
file.write("Branch Data\n")
file.w... |
Writes the header to file. | def write_case_data(self, file):
""" Writes the header to file.
"""
# title = "Power Flow Solution"
# file.write("=" * len(title))
# file.write("\n")
# file.write("\n%s\n" % title)
# file.write("=" * len(title))
# file.write("\n")
# Document subtitle.
... |
Writes bus data to a ReST table. | def write_bus_data(self, file):
""" Writes bus data to a ReST table.
"""
report = CaseReport(self.case)
buses = self.case.buses
col_width = 8
col_width_2 = col_width * 2 + 1
col1_width = 6
sep = "=" * 6 + " " + ("=" * col_width + " ") * 6 + "\n"
... |
Writes branch data to a ReST table. | def write_branch_data(self, file):
""" Writes branch data to a ReST table.
"""
report = CaseReport(self.case)
branches = self.case.branches
col_width = 8
col_width_2 = col_width*2+1
col1_width = 7
sep = ("=" * 7 + " ") * 3 + ("=" * col_width + " ") * ... |
Writes generator data to a ReST table. | def write_generator_data(self, file):
""" Writes generator data to a ReST table.
"""
report = CaseReport(self.case)
generators = self.case.generators
col_width = 8
col_width_2 = col_width*2+1
col1_width = 6
col_width_bool = 3
col_width_poly = 4
... |
Writes component numbers to a table. | def write_how_many(self, file):
""" Writes component numbers to a table.
"""
report = CaseReport(self.case)
# Map component labels to attribute names
components = [("Bus", "n_buses"), ("Generator", "n_generators"),
("Committed Generator", "n_online_generators"),
... |
Write component quantities to a table. | def write_how_much(self, file):
""" Write component quantities to a table.
"""
report = CaseReport(self.case)
col1_header = "Attribute"
col1_width = 24
col2_header = "P (MW)"
col3_header = "Q (MVAr)"
col_width = 8
sep = "="*col1_width +" "+ "=... |
Writes minimum and maximum values to a table. | def write_min_max(self, file):
""" Writes minimum and maximum values to a table.
"""
report = CaseReport(self.case)
col1_header = "Attribute"
col1_width = 19
col2_header = "Minimum"
col3_header = "Maximum"
col_width = 22
sep = "="*col1_width +... |
Return a name unique within a context based on the specified name. | def make_unique_name(base, existing=[], format="%s_%s"):
""" Return a name, unique within a context, based on the specified name.
@param base: the desired base name of the generated unique name.
@param existing: a sequence of the existing names to avoid returning.
@param format: a formatting specificat... |
calls antlr4 on grammar file | def call_antlr4(arg):
"calls antlr4 on grammar file"
# pylint: disable=unused-argument, unused-variable
antlr_path = os.path.join(ROOT_DIR, "java", "antlr-4.7-complete.jar")
classpath = os.pathsep.join([".", "{:s}".format(antlr_path), "$CLASSPATH"])
generated = os.path.join(ROOT_DIR, 'src', 'pymoca'... |
Setup the package. | def setup_package():
"""
Setup the package.
"""
with open('requirements.txt', 'r') as req_file:
install_reqs = req_file.read().split('\n')
cmdclass_ = {'antlr': AntlrBuildCommand}
cmdclass_.update(versioneer.get_cmdclass())
setup(
version=versioneer.get_version(),
n... |
Creates the dialog body. Returns the widget that should have initial focus. | def body(self, frame):
""" Creates the dialog body. Returns the widget that should have
initial focus.
"""
master = Frame(self)
master.pack(padx=5, pady=0, expand=1, fill=BOTH)
title = Label(master, text="Buses")
title.pack(side=TOP)
bus_lb = self.bu... |
Process the data. This method is called automatically to process the data * after * the dialog is destroyed. | def apply(self):
''' Process the data. This method is called automatically to process
the data, *after* the dialog is destroyed.
'''
bus = self.case.buses[int(self.bus_lb.curselection()[0])]
for attr in [a for a in BUS_ATTRS if a not in self.excluded+['mode']]:
v... |
Solves an optimal power flow and returns a results dictionary. | def solve(self, solver_klass=None):
""" Solves an optimal power flow and returns a results dictionary.
"""
# Start the clock.
t0 = time()
# Build an OPF model with variables and constraints.
om = self._construct_opf_model(self.case)
if om is None:
ret... |
Returns an OPF model. | def _construct_opf_model(self, case):
""" Returns an OPF model.
"""
# Zero the case result attributes.
self.case.reset()
base_mva = case.base_mva
# Check for one reference bus.
oneref, refs = self._ref_check(case)
if not oneref: #return {"status": "error... |
Checks that there is only one reference bus. | def _ref_check(self, case):
""" Checks that there is only one reference bus.
"""
refs = [bus._i for bus in case.buses if bus.type == REFERENCE]
if len(refs) == 1:
return True, refs
else:
logger.error("OPF requires a single reference bus.")
ret... |
Returns non - isolated case components. | def _remove_isolated(self, case):
""" Returns non-isolated case components.
"""
# case.deactivate_isolated()
buses = case.connected_buses
branches = case.online_branches
gens = case.online_generators
return buses, branches, gens |
Converts single - block piecewise - linear costs into linear polynomial. | def _pwl1_to_poly(self, generators):
""" Converts single-block piecewise-linear costs into linear
polynomial.
"""
for g in generators:
if (g.pcost_model == PW_LINEAR) and (len(g.p_cost) == 2):
g.pwl_to_poly()
return generators |
Returns the voltage angle variable set. | def _get_voltage_angle_var(self, refs, buses):
""" Returns the voltage angle variable set.
"""
Va = array([b.v_angle * (pi / 180.0) for b in buses])
Vau = Inf * ones(len(buses))
Val = -Vau
Vau[refs] = Va[refs]
Val[refs] = Va[refs]
return Variable("Va", l... |
Returns the voltage magnitude variable set. | def _get_voltage_magnitude_var(self, buses, generators):
""" Returns the voltage magnitude variable set.
"""
Vm = array([b.v_magnitude for b in buses])
# For buses with generators initialise Vm from gen data.
for g in generators:
Vm[g.bus._i] = g.v_magnitude
... |
Returns the generator active power set - point variable. | def _get_pgen_var(self, generators, base_mva):
""" Returns the generator active power set-point variable.
"""
Pg = array([g.p / base_mva for g in generators])
Pmin = array([g.p_min / base_mva for g in generators])
Pmax = array([g.p_max / base_mva for g in generators])
r... |
Returns the generator reactive power variable set. | def _get_qgen_var(self, generators, base_mva):
""" Returns the generator reactive power variable set.
"""
Qg = array([g.q / base_mva for g in generators])
Qmin = array([g.q_min / base_mva for g in generators])
Qmax = array([g.q_max / base_mva for g in generators])
retur... |
Returns non - linear constraints for OPF. | def _nln_constraints(self, nb, nl):
""" Returns non-linear constraints for OPF.
"""
Pmis = NonLinearConstraint("Pmis", nb)
Qmis = NonLinearConstraint("Qmis", nb)
Sf = NonLinearConstraint("Sf", nl)
St = NonLinearConstraint("St", nl)
return Pmis, Qmis, Sf, St |
Returns the power mismatch constraint ( B * Va + Pg = Pd ). | def _power_mismatch_dc(self, buses, generators, B, Pbusinj, base_mva):
""" Returns the power mismatch constraint (B*Va + Pg = Pd).
"""
nb, ng = len(buses), len(generators)
# Negative bus-generator incidence matrix.
gen_bus = array([g.bus._i for g in generators])
neg_Cg = ... |
Returns the branch flow limit constraint. The real power flows at the from end the lines are related to the bus voltage angles by Pf = Bf * Va + Pfinj. | def _branch_flow_dc(self, branches, Bf, Pfinj, base_mva):
""" Returns the branch flow limit constraint. The real power flows
at the from end the lines are related to the bus voltage angles by
Pf = Bf * Va + Pfinj.
"""
# Indexes of constrained lines.
il = array([i for i,l... |
Returns a linear constraint enforcing constant power factor for dispatchable loads. | def _const_pf_constraints(self, gn, base_mva):
""" Returns a linear constraint enforcing constant power factor for
dispatchable loads.
The power factor is derived from the original value of Pmin and either
Qmin (for inductive loads) or Qmax (for capacitive loads). If both Qmin
a... |
Returns the constraint on the branch voltage angle differences. | def _voltage_angle_diff_limit(self, buses, branches):
""" Returns the constraint on the branch voltage angle differences.
"""
nb = len(buses)
if not self.ignore_ang_lim:
iang = [i for i, b in enumerate(branches)
if (b.ang_min and (b.ang_min > -360.0))
... |
Returns the basin constraints for piece - wise linear gen cost variables. CCV cost formulation expressed as Ay * x < = by. | def _pwl_gen_costs(self, generators, base_mva):
""" Returns the basin constraints for piece-wise linear gen cost
variables. CCV cost formulation expressed as Ay * x <= by.
Based on makeAy.m from MATPOWER by C. E. Murillo-Sanchez, developed at
PSERC Cornell. See U{http://www.pserc.corne... |
Solves the combined unit decommitment/ optimal power flow problem. | def solve(self, solver_klass=None):
""" Solves the combined unit decommitment / optimal power flow problem.
"""
case = self.case
generators = case.online_generators
logger.info("Solving OPF with unit de-commitment [%s]." % case.name)
t0 = time()
# 1. Begin at s... |
Adds a variable to the model. | def add_var(self, var):
""" Adds a variable to the model.
"""
if var.name in [v.name for v in self.vars]:
logger.error("Variable set named '%s' already exists." % var.name)
return
var.i1 = self.var_N
var.iN = self.var_N + var.N - 1
self.vars.appen... |
Returns the variable set with the given name. | def get_var(self, name):
""" Returns the variable set with the given name.
"""
for var in self.vars:
if var.name == name:
return var
else:
raise ValueError |
Returns the linear constraints. | def linear_constraints(self):
""" Returns the linear constraints.
"""
if self.lin_N == 0:
return None, array([]), array([])
A = lil_matrix((self.lin_N, self.var_N), dtype=float64)
l = -Inf * ones(self.lin_N)
u = -l
for lin in self.lin_constraints:
... |
Adds a constraint to the model. | def add_constraint(self, con):
""" Adds a constraint to the model.
"""
if isinstance(con, LinearConstraint):
N, M = con.A.shape
if con.name in [c.name for c in self.lin_constraints]:
logger.error("Constraint set named '%s' already exists."
... |
Returns the constraint set with the given name. | def get_lin_constraint(self, name):
""" Returns the constraint set with the given name.
"""
for c in self.lin_constraints:
if c.name == name:
return c
else:
raise ValueError |
Returns the constraint set with the given name. | def get_nln_constraint(self, name):
""" Returns the constraint set with the given name.
"""
for c in self.nln_constraints:
if c.name == name:
return c
else:
raise ValueError |
Numerical linearization: param x0: initial state: param u0: initial input: return: list of Jacobians | def linearize(self, x0: np.array=None, u0: np.array=None) -> List[np.array]:
"""
Numerical linearization
:param x0: initial state
:param u0: initial input
:return: list of Jacobians
"""
ss = self.linearize_symbolic()
ss_eval = []
ss_subs = {}
... |
Gets all of the property mappings from the given property mapper considering the property mappings for self and the property mappings defined by the superclass.: param encoder: self when binded as class method: param property_mappings: mappings defined for the given encoder excluding mappings defined by superclasses: p... | def _get_all_property_mappings(encoder: MappingJSONEncoder, property_mappings: Iterable[JsonPropertyMapping],
superclasses: Tuple[PropertyMapper]) -> List[JsonPropertyMapping]:
"""
Gets all of the property mappings from the given property mapper, considering the property mappings ... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.