INSTRUCTION stringlengths 1 46.3k | RESPONSE stringlengths 75 80.2k |
|---|---|
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 voltages.
@rtype: tuple
@return... | 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.
@rtype: array
@return: Bus voltages. | 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.
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. | 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.
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. | 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.
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. | 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.
@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
reactance
... | 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.
@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 specification for how the name is made unique. | 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... |
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 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 |
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.
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
and Qmax are zero, this implies a unity power factor without... | 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.
Based on makeAy.m from MATPOWER by C. E. Murillo-Sanchez, developed at
PSERC Cornell. See U{http://www.pserc.cornell.edu/matpower/} for more
information. | 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... | 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 ... |
Build a subclass of `MappingJSONEncoder`.
:return: the built subclass | def build(self) -> type:
"""
Build a subclass of `MappingJSONEncoder`.
:return: the built subclass
"""
def _get_property_mappings(encoder: MappingJSONEncoder) -> List[JsonPropertyMapping]:
return _get_all_property_mappings(encoder, self.mappings, self.superclasses)
... |
Build a subclass of `MappingJSONDecoder`.
:return: the built subclass | def build(self) -> type:
"""
Build a subclass of `MappingJSONDecoder`.
:return: the built subclass
"""
def _get_property_mappings(encoder: MappingJSONEncoder) -> List[JsonPropertyMapping]:
return _get_all_property_mappings(encoder, self.mappings, self.superclasses)
... |
Solves using the Interior Point OPTimizer. | def _solve(self, x0, A, l, u, xmin, xmax):
""" Solves using the Interior Point OPTimizer.
"""
# Indexes of constrained lines.
il = [i for i,ln in enumerate(self._ln) if 0.0 < ln.rate_a < 1e10]
nl2 = len(il)
neqnln = 2 * self._nb # no. of non-linear equality constraints
... |
Applies branch outtages. | def doOutages(self):
""" Applies branch outtages.
"""
assert len(self.branchOutages) == len(self.market.case.branches)
weights = [[(False, r), (True, 1 - (r))] for r in self.branchOutages]
for i, ln in enumerate(self.market.case.branches):
ln.online = weighted_choic... |
Returns the case to its original state. | def reset_case(self):
""" Returns the case to its original state.
"""
for bus in self.market.case.buses:
bus.p_demand = self.pdemand[bus]
for task in self.tasks:
for g in task.env.generators:
g.p = task.env._g0[g]["p"]
g.p_max = tas... |
Do the given numer of episodes, and return the rewards of each
step as a list. | def doEpisodes(self, number=1):
""" Do the given numer of episodes, and return the rewards of each
step as a list.
"""
for episode in range(number):
print "Starting episode %d." % episode
# Initialise the profile cycle.
if len(self.profile.shape) ... |
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("Entering simulation period %d." % self.stepid)
# Apply branches outages.
if self.branchOutages is not None:
self.doOutages()
... |
Sets initial conditions for the experiment. | def reset(self):
""" Sets initial conditions for the experiment.
"""
self.stepid = 0
for task, agent in zip(self.tasks, self.agents):
task.reset()
agent.module.reset()
agent.history.reset() |
Learn on the current dataset, either for many timesteps and even
episodes (batchMode = True) or for a single timestep
(batchMode = False). Batch mode is possible, because Q-Learning is an
off-policy method.
In batchMode, the algorithm goes through all the samples in the history
... | def learn(self):
""" Learn on the current dataset, either for many timesteps and even
episodes (batchMode = True) or for a single timestep
(batchMode = False). Batch mode is possible, because Q-Learning is an
off-policy method.
In batchMode, the algorithm goes through all the sa... |
Update the propensities for all actions. The propensity for last
action chosen will be updated using the feedback value that resulted
from performing the action.
If j is the index of the last action chosen, r_j is the reward received
for performing j, i is the current action being updat... | def _updatePropensities(self, lastState, lastAction, reward):
""" Update the propensities for all actions. The propensity for last
action chosen will be updated using the feedback value that resulted
from performing the action.
If j is the index of the last action chosen, r_j is the rew... |
This is the standard experience function for the Roth-Erev
algorithm. Here propensities for all actions are updated and similarity
does not come into play. That is, all action choices are assumed to be
equally similar. If the actionIndex points to the action the reward is
associated with... | def _experience(self, lastState, action, previousAction, reward):
""" This is the standard experience function for the Roth-Erev
algorithm. Here propensities for all actions are updated and similarity
does not come into play. That is, all action choices are assumed to be
equally similar.... |
This is an altered version of the experience function for used in
the standard Roth-Erev algorithm. Like in RELearner, propensities for
all actions are updated and similarity does not come into play. If the
actionIndex points to the action the reward is associated with (usually
the last... | def _experience(self, previousState, action, previousAction, reward):
""" This is an altered version of the experience function for used in
the standard Roth-Erev algorithm. Like in RELearner, propensities for
all actions are updated and similarity does not come into play. If the
action... |
Proportional probability method. | def _forwardImplementation(self, inbuf, outbuf):
""" Proportional probability method.
"""
assert self.module
propensities = self.module.getActionValues(0)
summedProps = sum(propensities)
probabilities = propensities / summedProps
action = eventGenerator(probabi... |
Writes case data to file in Excel format. | def write(self, file_or_filename):
""" Writes case data to file in Excel format.
"""
self.book = Workbook()
self._write_data(None)
self.book.save(file_or_filename) |
Writes the header to file. | def write_case_data(self, file):
""" Writes the header to file.
"""
case_sheet = self.book.add_sheet("Case")
case_sheet.write(0, 0, "Name")
case_sheet.write(0, 1, self.case.name)
case_sheet.write(1, 0, "base_mva")
case_sheet.write(1, 1, self.case.base_mva) |
Writes bus data to an Excel spreadsheet. | def write_bus_data(self, file):
""" Writes bus data to an Excel spreadsheet.
"""
bus_sheet = self.book.add_sheet("Buses")
for i, bus in enumerate(self.case.buses):
for j, attr in enumerate(BUS_ATTRS):
bus_sheet.write(i, j, getattr(bus, attr)) |
Writes branch data to an Excel spreadsheet. | def write_branch_data(self, file):
""" Writes branch data to an Excel spreadsheet.
"""
branch_sheet = self.book.add_sheet("Branches")
for i, branch in enumerate(self.case.branches):
for j, attr in enumerate(BRANCH_ATTRS):
branch_sheet.write(i, j, getattr(bran... |
Write generator data to file. | def write_generator_data(self, file):
""" Write generator data to file.
"""
generator_sheet = self.book.add_sheet("Generators")
for j, generator in enumerate(self.case.generators):
i = generator.bus._i
for k, attr in enumerate(GENERATOR_ATTRS):
ge... |
Writes case data as CSV. | def write(self, file_or_filename):
""" Writes case data as CSV.
"""
if isinstance(file_or_filename, basestring):
file = open(file_or_filename, "wb")
else:
file = file_or_filename
self.writer = csv.writer(file)
super(CSVWriter, self).write(file) |
Writes the case data as CSV. | def write_case_data(self, file):
""" Writes the case data as CSV.
"""
writer = self._get_writer(file)
writer.writerow(["Name", "base_mva"])
writer.writerow([self.case.name, self.case.base_mva]) |
Writes bus data as CSV. | def write_bus_data(self, file):
""" Writes bus data as CSV.
"""
writer = self._get_writer(file)
writer.writerow(BUS_ATTRS)
for bus in self.case.buses:
writer.writerow([getattr(bus, attr) for attr in BUS_ATTRS]) |
Writes branch data as CSV. | def write_branch_data(self, file):
""" Writes branch data as CSV.
"""
writer = self._get_writer(file)
writer.writerow(BRANCH_ATTRS)
for branch in self.case.branches:
writer.writerow([getattr(branch, a) for a in BRANCH_ATTRS]) |
Write generator data as CSV. | def write_generator_data(self, file):
""" Write generator data as CSV.
"""
writer = self._get_writer(file)
writer.writerow(["bus"] + GENERATOR_ATTRS)
for g in self.case.generators:
i = g.bus._i
writer.writerow([i] + [getattr(g,a) for a in GENERATOR_ATTRS]... |
Returns the offers/bids for the given generator. | def getOffbids(self, g):
""" Returns the offers/bids for the given generator.
"""
if not g.is_load:
offbids = [x for x in self.offers if x.generator == g]
else:
offbids = [x for x in self.bids if x.vLoad == g]
return offbids |
Computes cleared offers and bids. | def run(self):
""" Computes cleared offers and bids.
"""
# Start the clock.
t0 = time.time()
# Manage reactive power offers/bids.
haveQ = self._isReactiveMarket()
# Withhold offers/bids outwith optional price limits.
self._withholdOffbids()
# Co... |
Returns a flag indicating the existance of offers/bids for reactive
power. | def _isReactiveMarket(self):
""" Returns a flag indicating the existance of offers/bids for reactive
power.
"""
vLoads = [g for g in self.case.generators if g.is_load]
if [offbid for offbid in self.offers + self.bids if offbid.reactive]:
haveQ = True
... |
Withholds offers/bids with invalid (<= 0.0) quantities or prices
outwith the set limits. | def _withholdOffbids(self):
""" Withholds offers/bids with invalid (<= 0.0) quantities or prices
outwith the set limits.
"""
limits = self.limits
# Eliminate offers (but not bids) above 'price_cap'.
if not limits.has_key('max_offer'):
limits['max_offer'] ... |
Converts offers/bids to pwl functions and updates limits. | def _offbidToCase(self):
""" Converts offers/bids to pwl functions and updates limits.
"""
generators = [g for g in self.case.generators if not g.is_load]
vLoads = [g for g in self.case.generators if g.is_load]
# Convert offers into piecewise linear segments and update limits.
... |
Computes dispatch points and LMPs using OPF. | def _runOPF(self):
""" Computes dispatch points and LMPs using OPF.
"""
if self.decommit:
solver = UDOPF(self.case, dc=(self.locationalAdjustment == "dc"))
elif self.locationalAdjustment == "dc":
solver = OPF(self.case, dc=True)
else:
solver = ... |
Sets the nodal prices associated with each offer/bid. | def _nodalPrices(self, haveQ):
""" Sets the nodal prices associated with each offer/bid.
"""
# Guarantee that cleared offer prices are >= offered prices.
gteeOfferPrice = True
gteeBidPrice = True
for offer in self.offers:
if not offer.reactive:
... |
Clears an auction to determine the quantity and price for each
offer/bid. | def _runAuction(self, gteeOfferPrice, gteeBidPrice, haveQ):
""" Clears an auction to determine the quantity and price for each
offer/bid.
"""
pOffers = [offer for offer in self.offers if not offer.reactive]
pBids = [bid for bid in self.bids if not bid.reactive]
# Cle... |
Return a JSON string representation of a Python data structure.
>>> JSONEncoder().encode({"foo": ["bar", "baz"]})
'{"foo":["bar", "baz"]}' | def encode(self, o):
"""
Return a JSON string representation of a Python data structure.
>>> JSONEncoder().encode({"foo": ["bar", "baz"]})
'{"foo":["bar", "baz"]}'
"""
# This doesn't pass the iterator directly to ''.join() because it
# sucks at reporting exceptio... |
:param ast_tree: AST to generate from
:param model_name: class to generate
:param options: dictionary of generator options
:return: casadi model | def generate(ast_tree: ast.Tree, model_name: str, options: Dict[str, bool]=None) -> Model:
"""
:param ast_tree: AST to generate from
:param model_name: class to generate
:param options: dictionary of generator options
:return: casadi model
"""
if options is None:
options = {}
com... |
We pull components and symbols from the AST on demand.
This is to ensure that parametrized vector dimensions can be resolved. Vector
dimensions need to be known at CasADi MX creation time.
:param tree:
:return: | def get_mx(self, tree: Union[ast.Symbol, ast.ComponentRef, ast.Expression]) -> ca.MX:
"""
We pull components and symbols from the AST on demand.
This is to ensure that parametrized vector dimensions can be resolved. Vector
dimensions need to be known at CasADi MX creation time.
... |
use processors to compute file metrics. | def compute_file_metrics(processors, language, key, token_list):
"""use processors to compute file metrics."""
# multiply iterator
tli = itertools.tee(token_list, len(processors))
metrics = OrderedDict()
# reset all processors
for p in processors:
p.reset()
# process all tokens
... |
This methods load the IWNLP.Lemmatizer json file and creates a dictionary
of lowercased forms which maps each form to its possible lemmas. | def load(self, lemmatizer_path):
"""
This methods load the IWNLP.Lemmatizer json file and creates a dictionary
of lowercased forms which maps each form to its possible lemmas.
"""
self.lemmatizer = {}
with io.open(lemmatizer_path, encoding='utf-8') as data_file:
... |
Return all lemmas for a given word. This method assumes that the specified word is present in the dictionary
:param word: Word that is present in the IWNLP lemmatizer | def get_lemmas(self, word, pos=None, ignore_case=False):
"""
Return all lemmas for a given word. This method assumes that the specified word is present in the dictionary
:param word: Word that is present in the IWNLP lemmatizer
"""
entries = self.get_entries(word, pos, ignore_cas... |
Python port of the lemmatize method, see https://github.com/Liebeck/IWNLP.Lemmatizer/blob/master/IWNLP.Lemmatizer.Predictor/IWNLPSentenceProcessor.cs | def lemmatize(self, word, pos_universal_google):
"""
Python port of the lemmatize method, see https://github.com/Liebeck/IWNLP.Lemmatizer/blob/master/IWNLP.Lemmatizer.Predictor/IWNLPSentenceProcessor.cs
"""
if pos_universal_google == "NOUN":
if self.contains_entry(word, "Nou... |
Writes the case data to file. | def write(self, file_or_filename):
""" Writes the case data to file.
"""
if isinstance(file_or_filename, basestring):
file = None
try:
file = open(file_or_filename, "wb")
except Exception, detail:
logger.error("Error opening %s.... |
Create serializer that is to be used by this encoder
:return: the serializer | def _create_serializer(self) -> JsonObjectSerializer:
"""
Create serializer that is to be used by this encoder
:return: the serializer
"""
if self._serializer_cache is None:
serializer_cls = type(
"%sInternalSerializer" % type(self),
(J... |
Creates a deserializer that is to be used by this decoder.
:return: the deserializer | def _create_deserializer(self) -> JsonObjectDeserializer:
"""
Creates a deserializer that is to be used by this decoder.
:return: the deserializer
"""
if self._deserializer_cache is None:
deserializer_cls = type(
"%sInternalDeserializer" % type(self),
... |
Convert the nested component reference to flat tuple of names, which is
hashable and can therefore be used as dictionary key. Note that this
function ignores any array indices in the component reference.
:return: flattened tuple of c's names | def to_tuple(self) -> tuple:
"""
Convert the nested component reference to flat tuple of names, which is
hashable and can therefore be used as dictionary key. Note that this
function ignores any array indices in the component reference.
:return: flattened tuple of c's names
... |
Convert the tuple pointing to a component to
a component reference.
:param components: tuple of components name
:return: ComponentRef | def from_tuple(cls, components: tuple) -> 'ComponentRef':
"""
Convert the tuple pointing to a component to
a component reference.
:param components: tuple of components name
:return: ComponentRef
"""
component_ref = ComponentRef(name=components[0], child=[])
... |
Convert the string pointing to a component using dot notation to
a component reference.
:param s: string pointing to component using dot notation
:return: ComponentRef | def from_string(cls, s: str) -> 'ComponentRef':
"""
Convert the string pointing to a component using dot notation to
a component reference.
:param s: string pointing to component using dot notation
:return: ComponentRef
"""
components = s.split('.')
retur... |
Helper function to append two component references to eachother, e.g.
a "within" component ref and an "object type" component ref.
:return: New component reference, with other appended to self. | def concatenate(cls, *args: List['ComponentRef']) -> 'ComponentRef':
"""
Helper function to append two component references to eachother, e.g.
a "within" component ref and an "object type" component ref.
:return: New component reference, with other appended to self.
"""
... |
Add a (sub)class to this class.
:param c: (Sub)class to add. | def add_class(self, c: 'Class') -> None:
"""
Add a (sub)class to this class.
:param c: (Sub)class to add.
"""
self.classes[c.name] = c
c.parent = self |
: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... |
Returns the reward corresponding to the last action performed. | def getReward(self):
""" Returns the reward corresponding to the last action performed.
"""
t = self.env.market.period
# Compute revenue minus costs.
totalEarnings = 0.0
for g in self.env.generators:
# Compute costs in $ (not $/hr).
costs = g.tota... |
The action vector is stripped and the only element is cast to
integer and given to the super class. | def performAction(self, action):
""" The action vector is stripped and the only element is cast to
integer and given to the super class.
"""
self.t += 1
super(ProfitTask, self).performAction(int(action[0]))
self.samples += 1 |
A filtered mapping towards performAction of the underlying
environment. | def addReward(self, r=None):
""" A filtered mapping towards performAction of the underlying
environment.
"""
r = self.getReward() if r is None else r
# by default, the cumulative reward is just the sum over the episode
if self.discount:
self.cumulativeRew... |
Solves a state estimation problem. | def run(self):
""" Solves a state estimation problem.
"""
case = self.case
baseMVA = case.base_mva
buses = self.case.connected_buses
branches = case.online_branches
generators = case.online_generators
meas = self.measurements
# Update indices.
... |
Returns the initial voltage profile. | def getV0(self, v_mag_guess, buses, generators, type=CASE_GUESS):
""" Returns the initial voltage profile.
"""
if type == CASE_GUESS:
Va = array([b.v_angle * (pi / 180.0) for b in buses])
Vm = array([b.v_magnitude for b in buses])
V0 = Vm * exp(1j * Va)
... |
Prints comparison of measurements and their estimations. | def output_solution(self, fd, z, z_est, error_sqrsum):
""" Prints comparison of measurements and their estimations.
"""
col_width = 11
sep = ("=" * col_width + " ") * 4 + "\n"
fd.write("State Estimation\n")
fd.write("-" * 16 + "\n")
fd.write(sep)
fd.write... |
Clears a set of bids and offers. | def run(self):
""" Clears a set of bids and offers.
"""
# Compute cleared offer/bid quantities from total dispatched quantity.
self._clearQuantities()
# Compute shift values to add to lam to get desired pricing.
# lao, fro, lab, frb = self._first_rejected_last_accepted()
... |
Computes the cleared quantities for each offer/bid according
to the dispatched output from the OPF solution. | def _clearQuantities(self):
""" Computes the cleared quantities for each offer/bid according
to the dispatched output from the OPF solution.
"""
generators = [g for g in self.case.generators if not g.is_load]
vLoads = [g for g in self.case.generators if g.is_load]
for g ... |
Computes the cleared bid quantity from total dispatched quantity. | def _clearQuantity(self, offbids, gen):
""" Computes the cleared bid quantity from total dispatched quantity.
"""
# Filter out offers/bids not applicable to the generator in question.
gOffbids = [offer for offer in offbids if offer.generator == gen]
# Offers/bids within valid pr... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.