_id stringlengths 2 7 | title stringlengths 1 88 | partition stringclasses 3
values | text stringlengths 75 19.8k | language stringclasses 1
value | meta_information dict |
|---|---|---|---|---|---|
q55800 | SLOCMetric.process_token | train | def process_token(self, tok):
"""count comments and non-empty lines that contain code"""
if(tok[0].__str__() in ('Token.Comment.Multiline', 'Token.Comment',
'Token.Literal.String.Doc')):
self.comments += tok[1].count('\n')+1
elif(tok[0].__str__() in ('Token.Comment.Si... | python | {
"resource": ""
} |
q55801 | SLOCMetric.get_metrics | train | def get_metrics(self):
"""Calculate ratio_comment_to_code and return with the other values"""
if(self.sloc == 0):
if(self.comments == 0):
ratio_comment_to_code = 0.00
else:
ratio_comment_to_code = 1.00
else:
ratio_comment_to_cod... | python | {
"resource": ""
} |
q55802 | CaseEnvironment.performAction | train | def performAction(self, action):
""" Perform an action on the world that changes it's internal state.
"""
gs = [g for g in self.case.online_generators if g.bus.type !=REFERENCE]
assert len(action) == len(gs)
logger.info("Action: %s" % list(action))
# Set the output of ... | python | {
"resource": ""
} |
q55803 | CaseEnvironment.reset | train | def reset(self):
""" Re-initialises the environment.
"""
logger.info("Reseting environment.")
self._step = 0
# Reset the set-point of each generator to its original value.
gs = [g for g in self.case.online_generators if g.bus.type !=REFERENCE]
for i, g in enumer... | python | {
"resource": ""
} |
q55804 | MinimiseCostTask.isFinished | train | def isFinished(self):
""" Is the current episode over?
"""
finished = (self.env._step == len(self.env.profile))
if finished:
logger.info("Finished episode.")
return finished | python | {
"resource": ""
} |
q55805 | OPFExperiment._oneInteraction | train | def _oneInteraction(self):
""" Does one interaction between the task and the agent.
"""
if self.doOptimization:
raise Exception('When using a black-box learning algorithm, only full episodes can be done.')
else:
self.stepid += 1
self.agent.integrateObs... | python | {
"resource": ""
} |
q55806 | OPFExperiment.doEpisodes | train | def doEpisodes(self, number=1):
""" Does the the given number of episodes.
"""
env = self.task.env
self.Pg = zeros((len(env.case.online_generators), len(env.profile)))
rewards = super(OPFExperiment, self).doEpisodes(number)
# Average the set-points for each period.
... | python | {
"resource": ""
} |
q55807 | getMethodByName | train | def getMethodByName(obj, name):
"""searches for an object with the name given inside the object given.
"obj.child.meth" will return the meth obj.
"""
try:#to get a method by asking the service
obj = obj._getMethodByName(name)
except:
#assumed a childObject is ment
#split... | python | {
"resource": ""
} |
q55808 | ResponseEvent.waitForResponse | train | def waitForResponse(self, timeOut=None):
"""blocks until the response arrived or timeout is reached."""
self.__evt.wait(timeOut)
if self.waiting():
raise Timeout()
else:
if self.response["error"]:
raise Exception(self.response["error"])
... | python | {
"resource": ""
} |
q55809 | SimpleMessageHandler.sendRequest | train | def sendRequest(self, name, args):
"""sends a request to the peer"""
(respEvt, id) = self.newResponseEvent()
self.sendMessage({"id":id, "method":name, "params": args})
return respEvt | python | {
"resource": ""
} |
q55810 | SimpleMessageHandler.sendResponse | train | def sendResponse(self, id, result, error):
"""sends a response to the peer"""
self.sendMessage({"result":result, "error": error, "id":id}) | python | {
"resource": ""
} |
q55811 | SimpleMessageHandler.newResponseEvent | train | def newResponseEvent(self):
"""creates a response event and adds it to a waiting list
When the reponse arrives it will be removed from the list.
"""
respEvt = ResponseEvent()
self.respLock.acquire()
eid = id(respEvt)
self.respEvents[eid] = respEvt
self... | python | {
"resource": ""
} |
q55812 | SimpleMessageHandler.handleResponse | train | def handleResponse(self, resp):
"""handles a response by fireing the response event for the response coming in"""
id=resp["id"]
evt = self.respEvents[id]
del(self.respEvents[id])
evt.handleResponse(resp) | python | {
"resource": ""
} |
q55813 | SimpleServiceHandler.handleRequest | train | def handleRequest(self, req):
"""handles a request by calling the appropriete method the service exposes"""
name = req["method"]
params = req["params"]
id=req["id"]
obj=None
try: #to get a callable obj
obj = getMethodByName(self.service, name)
except ... | python | {
"resource": ""
} |
q55814 | SimpleServiceHandler.handleNotification | train | def handleNotification(self, req):
"""handles a notification request by calling the appropriete method the service exposes"""
name = req["method"]
params = req["params"]
try: #to get a callable obj
obj = getMethodByName(self.service, name)
rslt = obj(*params)
... | python | {
"resource": ""
} |
q55815 | PSATReader.read | train | def read(self, file_or_filename):
""" Parses a PSAT data file and returns a case object
file_or_filename: File object or path to PSAT data file
return: Case object
"""
self.file_or_filename = file_or_filename
logger.info("Parsing PSAT case file [%s]." % file_or_... | python | {
"resource": ""
} |
q55816 | PSATReader._get_bus_array_construct | train | def _get_bus_array_construct(self):
""" Returns a construct for an array of bus data.
"""
bus_no = integer.setResultsName("bus_no")
v_base = real.setResultsName("v_base") # kV
v_magnitude = Optional(real).setResultsName("v_magnitude")
v_angle = Optional(real).setResultsNa... | python | {
"resource": ""
} |
q55817 | PSATReader._get_line_array_construct | train | def _get_line_array_construct(self):
""" Returns a construct for an array of line data.
"""
from_bus = integer.setResultsName("fbus")
to_bus = integer.setResultsName("tbus")
s_rating = real.setResultsName("s_rating") # MVA
v_rating = real.setResultsName("v_rating") # kV
... | python | {
"resource": ""
} |
q55818 | PSATReader._get_slack_array_construct | train | def _get_slack_array_construct(self):
""" Returns a construct for an array of slack bus data.
"""
bus_no = integer.setResultsName("bus_no")
s_rating = real.setResultsName("s_rating") # MVA
v_rating = real.setResultsName("v_rating") # kV
v_magnitude = real.setResultsName("... | python | {
"resource": ""
} |
q55819 | PSATReader._get_pv_array_construct | train | def _get_pv_array_construct(self):
""" Returns a construct for an array of PV generator data.
"""
bus_no = integer.setResultsName("bus_no")
s_rating = real.setResultsName("s_rating") # MVA
v_rating = real.setResultsName("v_rating") # kV
p = real.setResultsName("p") # p.u.... | python | {
"resource": ""
} |
q55820 | PSATReader._get_pq_array_construct | train | def _get_pq_array_construct(self):
""" Returns a construct for an array of PQ load data.
"""
bus_no = integer.setResultsName("bus_no")
s_rating = real.setResultsName("s_rating") # MVA
v_rating = real.setResultsName("v_rating") # kV
p = real.setResultsName("p") # p.u.
... | python | {
"resource": ""
} |
q55821 | PSATReader._get_demand_array_construct | train | def _get_demand_array_construct(self):
""" Returns a construct for an array of power demand data.
"""
bus_no = integer.setResultsName("bus_no")
s_rating = real.setResultsName("s_rating") # MVA
p_direction = real.setResultsName("p_direction") # p.u.
q_direction = real.setR... | python | {
"resource": ""
} |
q55822 | PSATReader._get_supply_array_construct | train | def _get_supply_array_construct(self):
""" Returns a construct for an array of power supply data.
"""
bus_no = integer.setResultsName("bus_no")
s_rating = real.setResultsName("s_rating") # MVA
p_direction = real.setResultsName("p_direction") # CPF
p_bid_max = real.setResu... | python | {
"resource": ""
} |
q55823 | PSATReader._get_generator_ramping_construct | train | def _get_generator_ramping_construct(self):
""" Returns a construct for an array of generator ramping data.
"""
supply_no = integer.setResultsName("supply_no")
s_rating = real.setResultsName("s_rating") # MVA
up_rate = real.setResultsName("up_rate") # p.u./h
down_rate = r... | python | {
"resource": ""
} |
q55824 | PSATReader._get_load_ramping_construct | train | def _get_load_ramping_construct(self):
""" Returns a construct for an array of load ramping data.
"""
bus_no = integer.setResultsName("bus_no")
s_rating = real.setResultsName("s_rating") # MVA
up_rate = real.setResultsName("up_rate") # p.u./h
down_rate = real.setResultsNa... | python | {
"resource": ""
} |
q55825 | PSATReader.push_bus | train | def push_bus(self, tokens):
""" Adds a Bus object to the case.
"""
logger.debug("Pushing bus data: %s" % tokens)
bus = Bus()
bus.name = tokens["bus_no"]
bus.v_magnitude = tokens["v_magnitude"]
bus.v_angle = tokens["v_angle"]
bus.v_magnitude = tokens["v_ma... | python | {
"resource": ""
} |
q55826 | PSATReader.push_line | train | def push_line(self, tokens):
""" Adds a Branch object to the case.
"""
logger.debug("Pushing line data: %s" % tokens)
from_bus = self.case.buses[tokens["fbus"]-1]
to_bus = self.case.buses[tokens["tbus"]-1]
e = Branch(from_bus=from_bus, to_bus=to_bus)
e.r = token... | python | {
"resource": ""
} |
q55827 | PSATReader.push_slack | train | def push_slack(self, tokens):
""" Finds the slack bus, adds a Generator with the appropriate data
and sets the bus type to slack.
"""
logger.debug("Pushing slack data: %s" % tokens)
bus = self.case.buses[tokens["bus_no"] - 1]
g = Generator(bus)
g.q_max = tokens[... | python | {
"resource": ""
} |
q55828 | PSATReader.push_pv | train | def push_pv(self, tokens):
""" Creates and Generator object, populates it with data, finds its Bus
and adds it.
"""
logger.debug("Pushing PV data: %s" % tokens)
bus = self.case.buses[tokens["bus_no"]-1]
g = Generator(bus)
g.p = tokens["p"]
g.q_max = toke... | python | {
"resource": ""
} |
q55829 | PSATReader.push_pq | train | def push_pq(self, tokens):
""" Creates and Load object, populates it with data, finds its Bus and
adds it.
"""
logger.debug("Pushing PQ data: %s" % tokens)
bus = self.case.buses[tokens["bus_no"] - 1]
bus.p_demand = tokens["p"]
bus.q_demand = tokens["q"] | python | {
"resource": ""
} |
q55830 | PSATReader.push_supply | train | def push_supply(self, tokens):
""" Adds OPF and CPF data to a Generator.
"""
logger.debug("Pushing supply data: %s" % tokens)
bus = self.case.buses[tokens["bus_no"] - 1]
n_generators = len([g for g in self.case.generators if g.bus == bus])
if n_generators == 0:
... | python | {
"resource": ""
} |
q55831 | MATPOWERReader._parse_file | train | def _parse_file(self, file):
""" Parses the given file-like object.
"""
case = Case()
file.seek(0)
line = file.readline().split()
if line[0] != "function":
logger.error("Invalid data file header.")
return case
if line[1] != "mpc":
... | python | {
"resource": ""
} |
q55832 | MATPOWERWriter.write | train | def write(self, file_or_filename):
""" Writes case data to file in MATPOWER format.
"""
if isinstance(file_or_filename, basestring):
self._fcn_name, _ = splitext(basename(file_or_filename))
else:
self._fcn_name = self.case.name
self._fcn_name = self._fcn_... | python | {
"resource": ""
} |
q55833 | MATPOWERWriter.write_case_data | train | def write_case_data(self, file):
""" Writes the case data in MATPOWER format.
"""
file.write("function mpc = %s\n" % self._fcn_name)
file.write('\n%%%% MATPOWER Case Format : Version %d\n' % 2)
file.write("mpc.version = '%d';\n" % 2)
file.write("\n%%%%----- Power Flow D... | python | {
"resource": ""
} |
q55834 | MATPOWERWriter.write_generator_cost_data | train | def write_generator_cost_data(self, file):
""" Writes generator cost data to file.
"""
file.write("\n%%%% generator cost data\n")
file.write("%%\t1\tstartup\tshutdown\tn\tx1\ty1\t...\txn\tyn\n")
file.write("%%\t2\tstartup\tshutdown\tn\tc(n-1)\t...\tc0\n")
file.write("%sge... | python | {
"resource": ""
} |
q55835 | MATPOWERWriter.write_area_data | train | def write_area_data(self, file):
""" Writes area data to file.
"""
file.write("%% area data" + "\n")
file.write("%\tno.\tprice_ref_bus" + "\n")
file.write("areas = [" + "\n")
# TODO: Implement areas
file.write("\t1\t1;" + "\n")
file.write("];" + "\n") | python | {
"resource": ""
} |
q55836 | MetricBase.process_file | train | def process_file(self, language, key, token_list):
"""
Initiate processing for each token.
Override this if you want tt control the processing of the tokens yourself.
"""
self.language = language
for tok in token_list:
self.process_token(tok) | python | {
"resource": ""
} |
q55837 | ParticipantRenderer.draw_plot | train | def draw_plot(self):
""" Initialises plots of the environment.
"""
pylab.ion()
fig = pylab.figure(1)
# State plot.
# state_axis = fig.add_subplot(3, 1, 1) # numrows, numcols, fignum
# state_axis.title = 'State'
# state_axis.xlabel = 'Time (hours)'
# s... | python | {
"resource": ""
} |
q55838 | PSSEWriter.write_case_data | train | def write_case_data(self, file):
""" Writes case data to file.
"""
change_code = 0
s_base = self.case.base_mva
timestr = time.strftime("%Y%m%d%H%M", time.gmtime())
file.write("%d, %8.2f, 30 / PSS(tm)E-30 RAW created by Pylon (%s).\n" %
(change_co... | python | {
"resource": ""
} |
q55839 | plotGenCost | train | def plotGenCost(generators):
""" Plots the costs of the given generators.
"""
figure()
plots = []
for generator in generators:
if generator.pcost_model == PW_LINEAR:
x = [x for x, _ in generator.p_cost]
y = [y for _, y in generator.p_cost]
elif generator.pcost... | python | {
"resource": ""
} |
q55840 | ReSTExperimentWriter.write | train | def write(self, file):
""" Writes market experiment data to file in ReStructuredText format.
"""
# Write environment state data.
file.write("State\n")
file.write( ("-" * 5) + "\n")
self.writeDataTable(file, type="state")
# Write action data.
file.write("A... | python | {
"resource": ""
} |
q55841 | ReSTExperimentWriter.writeDataTable | train | def writeDataTable(self, file, type):
""" Writes agent data to an ReST table. The 'type' argument may
be 'state', 'action' or 'reward'.
"""
agents = self.experiment.agents
numAgents = len(self.experiment.agents)
colWidth = 8
idxColWidth = 3
sep = ("=" *... | python | {
"resource": ""
} |
q55842 | ProfitTask.performAction | train | def performAction(self, action):
""" Execute one action.
"""
# print "ACTION:", action
self.t += 1
Task.performAction(self, action)
# self.addReward()
self.samples += 1 | python | {
"resource": ""
} |
q55843 | split_dae_alg | train | def split_dae_alg(eqs: SYM, dx: SYM) -> Dict[str, SYM]:
"""Split equations into differential algebraic and algebraic only"""
dae = []
alg = []
for eq in ca.vertsplit(eqs):
if ca.depends_on(eq, dx):
dae.append(eq)
else:
alg.append(eq)
return {
'dae': ca... | python | {
"resource": ""
} |
q55844 | permute | train | def permute(x: SYM, perm: List[int]) -> SYM:
"""Perumute a vector"""
x_s = []
for i in perm:
x_s.append(x[i])
return ca.vertcat(*x_s) | python | {
"resource": ""
} |
q55845 | blt | train | def blt(f: List[SYM], x: List[SYM]) -> Dict[str, Any]:
"""
Sort equations by dependence
"""
J = ca.jacobian(f, x)
nblock, rowperm, colperm, rowblock, colblock, coarserow, coarsecol = J.sparsity().btf()
return {
'J': J,
'nblock': nblock,
'rowperm': rowperm,
'colper... | python | {
"resource": ""
} |
q55846 | HybridOde.create_function_f_m | train | def create_function_f_m(self):
"""Discrete state dynamics"""
return ca.Function(
'f_m',
[self.t, self.x, self.y, self.m, self.p, self.c, self.pre_c, self.ng, self.nu],
[self.f_m],
['t', 'x', 'y', 'm', 'p', 'c', 'pre_c', 'ng', 'nu'], ['m'], self.func_opt) | python | {
"resource": ""
} |
q55847 | HybridOde.create_function_f_J | train | def create_function_f_J(self):
"""Jacobian for state integration"""
return ca.Function(
'J',
[self.t, self.x, self.y, self.m, self.p, self.c, self.ng, self.nu],
[ca.jacobian(self.f_x_rhs, self.x)],
['t', 'x', 'y', 'm', 'p', 'c', 'ng', 'nu'], ['J'], self.fu... | python | {
"resource": ""
} |
q55848 | HybridDae.to_ode | train | def to_ode(self) -> HybridOde:
"""Convert to a HybridOde"""
res_split = split_dae_alg(self.f_x, self.dx)
alg = res_split['alg']
dae = res_split['dae']
x_rhs = tangent_approx(dae, self.dx, assert_linear=True)
y_rhs = tangent_approx(alg, self.y, assert_linear=True)
... | python | {
"resource": ""
} |
q55849 | format_from_extension | train | def format_from_extension(fname):
""" Tries to infer a protocol from the file extension."""
_base, ext = os.path.splitext(fname)
if not ext:
return None
try:
format = known_extensions[ext.replace('.', '')]
except KeyError:
format = None
return format | python | {
"resource": ""
} |
q55850 | pickle_matpower_cases | train | def pickle_matpower_cases(case_paths, case_format=2):
""" Parses the MATPOWER case files at the given paths and pickles the
resulting Case objects to the same directory.
"""
import pylon.io
if isinstance(case_paths, basestring):
case_paths = [case_paths]
for case_path in case_paths... | python | {
"resource": ""
} |
q55851 | fair_max | train | def fair_max(x):
""" Takes a single iterable as an argument and returns the same output as
the built-in function max with two output parameters, except that where
the maximum value occurs at more than one position in the vector, the
index is chosen randomly from these positions as opposed to just choos... | python | {
"resource": ""
} |
q55852 | factorial | train | def factorial(n):
""" Returns the factorial of n.
"""
f = 1
while (n > 0):
f = f * n
n = n - 1
return f | python | {
"resource": ""
} |
q55853 | _Named._get_name | train | def _get_name(self):
""" Returns the name, which is generated if it has not been already.
"""
if self._name is None:
self._name = self._generate_name()
return self._name | python | {
"resource": ""
} |
q55854 | _Serializable.save_to_file_object | train | def save_to_file_object(self, fd, format=None, **kwargs):
""" Save the object to a given file like object in the given format.
"""
format = 'pickle' if format is None else format
save = getattr(self, "save_%s" % format, None)
if save is None:
raise ValueError("Unknown... | python | {
"resource": ""
} |
q55855 | _Serializable.load_from_file_object | train | def load_from_file_object(cls, fd, format=None):
""" Load the object from a given file like object in the given format.
"""
format = 'pickle' if format is None else format
load = getattr(cls, "load_%s" % format, None)
if load is None:
raise ValueError("Unknown format ... | python | {
"resource": ""
} |
q55856 | _Serializable.save | train | def save(self, filename, format=None, **kwargs):
""" Save the object to file given by filename.
"""
if format is None:
# try to derive protocol from file extension
format = format_from_extension(filename)
with file(filename, 'wb') as fp:
self.save_to_f... | python | {
"resource": ""
} |
q55857 | _Serializable.load | train | def load(cls, filename, format=None):
""" Return an instance of the class that is saved in the file with the
given filename in the specified format.
"""
if format is None:
# try to derive protocol from file extension
format = format_from_extension(filename)
... | python | {
"resource": ""
} |
q55858 | DCPF.solve | train | def solve(self):
""" Solves a DC power flow.
"""
case = self.case
logger.info("Starting DC power flow [%s]." % case.name)
t0 = time.time()
# Update bus indexes.
self.case.index_buses()
# Find the index of the refence bus.
ref_idx = self._get_refer... | python | {
"resource": ""
} |
q55859 | DCPF._get_reference_index | train | 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.")
... | python | {
"resource": ""
} |
q55860 | DCPF._get_v_angle_guess | train | 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 | python | {
"resource": ""
} |
q55861 | DCPF._get_v_angle | train | 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_... | python | {
"resource": ""
} |
q55862 | DCPF._update_model | train | 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... | python | {
"resource": ""
} |
q55863 | Case.getSbus | train | 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 | python | {
"resource": ""
} |
q55864 | Case.sort_generators | train | def sort_generators(self):
""" Reorders the list of generators according to bus index.
"""
self.generators.sort(key=lambda gn: gn.bus._i) | python | {
"resource": ""
} |
q55865 | Case.index_buses | train | 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 | python | {
"resource": ""
} |
q55866 | Case.index_branches | train | 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... | python | {
"resource": ""
} |
q55867 | Case.s_supply | train | 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 ... | python | {
"resource": ""
} |
q55868 | Case.s_demand | train | 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 | python | {
"resource": ""
} |
q55869 | Case.reset | train | 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() | python | {
"resource": ""
} |
q55870 | Case.save_matpower | train | def save_matpower(self, fd):
""" Serialize the case as a MATPOWER data file.
"""
from pylon.io import MATPOWERWriter
MATPOWERWriter(self).write(fd) | python | {
"resource": ""
} |
q55871 | Case.load_psat | train | 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) | python | {
"resource": ""
} |
q55872 | Case.save_rst | train | def save_rst(self, fd):
""" Save a reStructuredText representation of the case.
"""
from pylon.io import ReSTWriter
ReSTWriter(self).write(fd) | python | {
"resource": ""
} |
q55873 | Case.save_csv | train | 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) | python | {
"resource": ""
} |
q55874 | Case.save_excel | train | def save_excel(self, fd):
""" Saves the case as an Excel spreadsheet.
"""
from pylon.io.excel import ExcelWriter
ExcelWriter(self).write(fd) | python | {
"resource": ""
} |
q55875 | Case.save_dot | train | 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) | python | {
"resource": ""
} |
q55876 | _ACPF.solve | train | 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... | python | {
"resource": ""
} |
q55877 | _ACPF._unpack_case | train | 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 ... | python | {
"resource": ""
} |
q55878 | _ACPF._index_buses | train | 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... | python | {
"resource": ""
} |
q55879 | _ACPF._initial_voltage | train | 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... | python | {
"resource": ""
} |
q55880 | NewtonPF._one_iteration | train | 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.
... | python | {
"resource": ""
} |
q55881 | NewtonPF._build_jacobian | train | 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
... | python | {
"resource": ""
} |
q55882 | FastDecoupledPF._evaluate_mismatch | train | 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 | python | {
"resource": ""
} |
q55883 | FastDecoupledPF._p_iteration | train | 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 | python | {
"resource": ""
} |
q55884 | FastDecoupledPF._q_iteration | train | 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 | python | {
"resource": ""
} |
q55885 | fmsin | train | 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... | python | {
"resource": ""
} |
q55886 | RDFReader._parse_rdf | train | def _parse_rdf(self, file):
""" Returns a case from the given file.
"""
store = Graph()
store.parse(file)
print len(store) | python | {
"resource": ""
} |
q55887 | load_plugins | train | 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):
... | python | {
"resource": ""
} |
q55888 | read_case | train | 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.
... | python | {
"resource": ""
} |
q55889 | detect_data_file | train | 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... | python | {
"resource": ""
} |
q55890 | DotWriter.write | train | 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'... | python | {
"resource": ""
} |
q55891 | DotWriter.write_bus_data | train | 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... | python | {
"resource": ""
} |
q55892 | DotWriter.write_branch_data | train | 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" % \
... | python | {
"resource": ""
} |
q55893 | DotWriter.write_generator_data | train | 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... | python | {
"resource": ""
} |
q55894 | DotWriter.create | train | 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... | python | {
"resource": ""
} |
q55895 | format | train | 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():
... | python | {
"resource": ""
} |
q55896 | ask | train | 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 | python | {
"resource": ""
} |
q55897 | main | train | 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... | python | {
"resource": ""
} |
q55898 | Watcher.check_configuration | train | 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)
... | python | {
"resource": ""
} |
q55899 | Watcher.check_dependencies | train | 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 ... | python | {
"resource": ""
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.