INSTRUCTION stringlengths 1 8.43k | RESPONSE stringlengths 75 104k |
|---|---|
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. | 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. | 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 ( usually the last action take... | 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 action taken ) then simply adj... | 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. | 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. | 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... |
Clears prices according to auction type. | def _clearPrices(self):
""" Clears prices according to auction type.
"""
for offbid in self.offers + self.bids:
if self.auctionType == DISCRIMINATIVE:
offbid.clearedPrice = offbid.price
elif self.auctionType == FIRST_PRICE:
offbid.clearedPr... |
Clip cleared prices according to guarantees and limits. | def _clipPrices(self):
""" Clip cleared prices according to guarantees and limits.
"""
# Guarantee that cleared offer prices are >= offers.
if self.guaranteeOfferPrice:
for offer in self.offers:
if offer.accepted and offer.clearedPrice < offer.price:
... |
Logs offer/ bid cleared values. | def _logClearances(self):
""" Logs offer/bid cleared values.
"""
for offer in self.offers:
logger.info("%.2fMW offer cleared at %.2f$/MWh for %s (%.2f)." %
(offer.clearedQuantity, offer.clearedPrice,
offer.generator.name, offer.revenue... |
Try make a GET request with an HTTP client against a certain path and return once any response has been received ignoring any errors. | def wait_for_response(client, timeout, path='/', expected_status_code=None):
"""
Try make a GET request with an HTTP client against a certain path and
return once any response has been received, ignoring any errors.
:param ContainerHttpClient client:
The HTTP client to use to connect to the con... |
: param container: The container to make requests against.: param container_port: The container port to make requests against. If None the first container port is used.: returns: A ContainerClient object configured to make requests to the container. | def for_container(cls, container, container_port=None):
"""
:param container:
The container to make requests against.
:param container_port:
The container port to make requests against. If ``None``, the first
container port is used.
:returns:
... |
Make a request against a container. | def request(self, method, path=None, url_kwargs=None, **kwargs):
"""
Make a request against a container.
:param method:
The HTTP method to use.
:param list path:
The HTTP path (either absolute or relative).
:param dict url_kwargs:
Parameters t... |
Sends a GET request. | def get(self, path=None, url_kwargs=None, **kwargs):
"""
Sends a GET request.
:param path:
The HTTP path (either absolute or relative).
:param url_kwargs:
Parameters to override in the generated URL. See `~hyperlink.URL`.
:param **kwargs:
Opti... |
Sends an OPTIONS request. | def options(self, path=None, url_kwargs=None, **kwargs):
"""
Sends an OPTIONS request.
:param path:
The HTTP path (either absolute or relative).
:param url_kwargs:
Parameters to override in the generated URL. See `~hyperlink.URL`.
:param **kwargs:
... |
Sends a HEAD request. | def head(self, path=None, url_kwargs=None, **kwargs):
"""
Sends a HEAD request.
:param path:
The HTTP path (either absolute or relative).
:param url_kwargs:
Parameters to override in the generated URL. See `~hyperlink.URL`.
:param **kwargs:
Op... |
Sends a POST request. | def post(self, path=None, url_kwargs=None, **kwargs):
"""
Sends a POST request.
:param path:
The HTTP path (either absolute or relative).
:param url_kwargs:
Parameters to override in the generated URL. See `~hyperlink.URL`.
:param **kwargs:
Op... |
Sends a PUT request. | def put(self, path=None, url_kwargs=None, **kwargs):
"""
Sends a PUT request.
:param path:
The HTTP path (either absolute or relative).
:param url_kwargs:
Parameters to override in the generated URL. See `~hyperlink.URL`.
:param **kwargs:
Opti... |
Sends a PUT request. | def patch(self, path=None, url_kwargs=None, **kwargs):
"""
Sends a PUT request.
:param path:
The HTTP path (either absolute or relative).
:param url_kwargs:
Parameters to override in the generated URL. See `~hyperlink.URL`.
:param **kwargs:
Op... |
Sends a PUT request. | def delete(self, path=None, url_kwargs=None, **kwargs):
"""
Sends a PUT request.
:param path:
The HTTP path (either absolute or relative).
:param url_kwargs:
Parameters to override in the generated URL. See `~hyperlink.URL`.
:param **kwargs:
O... |
This function serves as a handler for the different implementations of the IUWT decomposition. It allows the different methods to be used almost interchangeably. | def iuwt_decomposition(in1, scale_count, scale_adjust=0, mode='ser', core_count=2, store_smoothed=False,
store_on_gpu=False):
"""
This function serves as a handler for the different implementations of the IUWT decomposition. It allows the
different methods to be used almost interchang... |
This function serves as a handler for the different implementations of the IUWT recomposition. It allows the different methods to be used almost interchangeably. | def iuwt_recomposition(in1, scale_adjust=0, mode='ser', core_count=1, store_on_gpu=False, smoothed_array=None):
"""
This function serves as a handler for the different implementations of the IUWT recomposition. It allows the
different methods to be used almost interchangeably.
INPUTS:
in1 ... |
This function calls the a trous algorithm code to decompose the input into its wavelet coefficients. This is the isotropic undecimated wavelet transform implemented for a single CPU core. | def ser_iuwt_decomposition(in1, scale_count, scale_adjust, store_smoothed):
"""
This function calls the a trous algorithm code to decompose the input into its wavelet coefficients. This is
the isotropic undecimated wavelet transform implemented for a single CPU core.
INPUTS:
in1 (no... |
This function calls the a trous algorithm code to recompose the input into a single array. This is the implementation of the isotropic undecimated wavelet transform recomposition for a single CPU core. | def ser_iuwt_recomposition(in1, scale_adjust, smoothed_array):
"""
This function calls the a trous algorithm code to recompose the input into a single array. This is the
implementation of the isotropic undecimated wavelet transform recomposition for a single CPU core.
INPUTS:
in1 (no de... |
The following is a serial implementation of the a trous algorithm. Accepts the following parameters: | def ser_a_trous(C0, filter, scale):
"""
The following is a serial implementation of the a trous algorithm. Accepts the following parameters:
INPUTS:
filter (no default): The filter-bank which is applied to the components of the transform.
C0 (no default): The current array on whic... |
This function calls the a trous algorithm code to decompose the input into its wavelet coefficients. This is the isotropic undecimated wavelet transform implemented for multiple CPU cores. NOTE: Python is not well suited to multiprocessing - this may not improve execution speed. | def mp_iuwt_decomposition(in1, scale_count, scale_adjust, store_smoothed, core_count):
"""
This function calls the a trous algorithm code to decompose the input into its wavelet coefficients. This is
the isotropic undecimated wavelet transform implemented for multiple CPU cores. NOTE: Python is not well sui... |
This function calls the a trous algorithm code to recompose the input into a single array. This is the implementation of the isotropic undecimated wavelet transform recomposition for multiple CPU cores. | def mp_iuwt_recomposition(in1, scale_adjust, core_count, smoothed_array):
"""
This function calls the a trous algorithm code to recompose the input into a single array. This is the
implementation of the isotropic undecimated wavelet transform recomposition for multiple CPU cores.
INPUTS:
in1 ... |
This is a reimplementation of the a trous filter which makes use of multiprocessing. In particular it divides the input array of dimensions NxN into M smaller arrays of dimensions ( N/ M ) xN where M is the number of cores which are to be used. | def mp_a_trous(C0, wavelet_filter, scale, core_count):
"""
This is a reimplementation of the a trous filter which makes use of multiprocessing. In particular,
it divides the input array of dimensions NxN into M smaller arrays of dimensions (N/M)xN, where M is the
number of cores which are to be used.
... |
This is the convolution step of the a trous algorithm. | def mp_a_trous_kernel(C0, wavelet_filter, scale, slice_ind, slice_width, r_or_c="row"):
"""
This is the convolution step of the a trous algorithm.
INPUTS:
C0 (no default): The current array which is to be decomposed.
wavelet_filter (no default): The filter-bank which is ap... |
This function calls the a trous algorithm code to decompose the input into its wavelet coefficients. This is the isotropic undecimated wavelet transform implemented for a GPU. | def gpu_iuwt_decomposition(in1, scale_count, scale_adjust, store_smoothed, store_on_gpu):
"""
This function calls the a trous algorithm code to decompose the input into its wavelet coefficients. This is
the isotropic undecimated wavelet transform implemented for a GPU.
INPUTS:
in1 (... |
This function calls the a trous algorithm code to recompose the input into a single array. This is the implementation of the isotropic undecimated wavelet transform recomposition for a GPU. | def gpu_iuwt_recomposition(in1, scale_adjust, store_on_gpu, smoothed_array):
"""
This function calls the a trous algorithm code to recompose the input into a single array. This is the
implementation of the isotropic undecimated wavelet transform recomposition for a GPU.
INPUTS:
in1 (no ... |
Simple convenience function so that the a trous kernels can be easily accessed by any function. | def gpu_a_trous():
"""
Simple convenience function so that the a trous kernels can be easily accessed by any function.
"""
ker1 = SourceModule("""
__global__ void gpu_a_trous_row_kernel(float *in1, float *in2, float *wfil, int *scale)
{
... |
logout and remove all session data | def unauth(request):
"""
logout and remove all session data
"""
if check_key(request):
api = get_api(request)
request.session.clear()
logout(request)
return HttpResponseRedirect(reverse('main')) |
display some user info to show we have authenticated successfully | def info(request):
"""
display some user info to show we have authenticated successfully
"""
if check_key(request):
api = get_api(request)
user = api.users(id='self')
print dir(user)
return render_to_response('djfoursquare/info.html', {'user': user})
else:
ret... |
Check to see if we already have an access_key stored if we do then we have already gone through OAuth. If not then we haven t and we probably need to. | def check_key(request):
"""
Check to see if we already have an access_key stored,
if we do then we have already gone through
OAuth. If not then we haven't and we probably need to.
"""
try:
access_key = request.session.get('oauth_token', None)
if not access_key:
return... |
Iterate over items in a streaming response from the Docker client within a timeout. | def stream_timeout(stream, timeout, timeout_msg=None):
"""
Iterate over items in a streaming response from the Docker client within
a timeout.
:param ~docker.types.daemon.CancellableStream stream:
Stream from the Docker client to consume items from.
:param timeout:
Timeout value in ... |
Get per - program state. | def get_state(self, caller):
"""
Get per-program state.
"""
if caller in self.state:
return self.state[caller]
else:
rv = self.state[caller] = DictObject()
return rv |
Value might be either name registered in System namespace or object either StatusObject or Callable. If Callable evaluate: meth:. call method. If StatusObject return status. | def call_eval(self, value, caller, return_value=True, **kwargs):
"""
Value might be either name registered in System namespace, or object, either
StatusObject or Callable. If Callable, evaluate :meth:`.call` method. If StatusObject,
return status.
"""
value = ... |
This function basically sets up: attr:. system if it is not yet set up. After that other Callable initialization actions are performed. | def setup_callable_system(self, system, init=False):
"""
This function basically sets up :attr:`.system`, if it is not yet set up. After that,
other Callable initialization actions are performed.
:param init: value ``True`` is given when running this at the initialization ph... |
Return object for given name registered in System namespace. | def name_to_system_object(self, value):
"""
Return object for given name registered in System namespace.
"""
if not self.system:
raise SystemNotReady
if isinstance(value, (str, Object)):
rv = self.system.name_to_system_object(value)
return rv ... |
Recursively collect all potential triggers/ targets in this node and its children. Define targets and triggers of this particular callable in: meth: _give_triggers and: meth: _give_targets. | def collect(self, target):
"""Recursively collect all potential triggers/targets in this node and its children.
Define targets and triggers of this particular callable in :meth:`_give_triggers`
and :meth:`_give_targets`.
:param str target: valid values: ``'targets'`` and ``'triggers'``
... |
Recursively cancel all threaded background processes of this Callable. This is called automatically for actions if program deactivates. | def cancel(self, caller):
"""
Recursively cancel all threaded background processes of this Callable.
This is called automatically for actions if program deactivates.
"""
for o in {i for i in self.children if isinstance(i, AbstractCallable)}:
o.cancel(caller) |
Give string representation of the callable. | def give_str(self):
"""
Give string representation of the callable.
"""
args = self._args[:]
kwargs = self._kwargs
return self._give_str(args, kwargs) |
Give indented string representation of the callable. This is used in: ref: automate - webui. | def give_str_indented(self, tags=False):
"""
Give indented string representation of the callable.
This is used in :ref:`automate-webui`.
"""
args = self._args[:]
kwargs = self._kwargs
rv = self._give_str_indented(args, kwargs, tags)
if not tags:
... |
Prepares the request and catches common errors and returns tuple of data and the request response. | def _make_request(self, endpoint, params):
"""
Prepares the request and catches common errors and returns tuple of data and the request response.
Read more about error codes: https://docs.polrproject.org/en/latest/developer-guide/api/#http-error-codes
:param endpoint: full endpoint url... |
Creates a short url if valid | def shorten(self, long_url, custom_ending=None, is_secret=False):
"""
Creates a short url if valid
:param str long_url: The url to shorten.
:param custom_ending: The custom url to create if available.
:type custom_ending: str or None
:param bool is_secret: if not public,... |
Returns the short url ending from a short url or an short url ending. | def _get_ending(self, lookup_url):
"""
Returns the short url ending from a short url or an short url ending.
Example:
- Given `<your Polr server>/5N3f8`, return `5N3f8`.
- Given `5N3f8`, return `5N3f8`.
:param lookup_url: A short url or short url ending
:type ... |
Looks up the url_ending to obtain information about the short url. | def lookup(self, lookup_url, url_key=None):
"""
Looks up the url_ending to obtain information about the short url.
If it exists, the API will return a dictionary with information, including
the long_url that is the destination of the given short url URL.
The lookup object look... |
The following contructs a restoring beam from the psf. This is accoplished by fitting an elliptical Gaussian to the central lobe of the PSF. | def beam_fit(psf, cdelt1, cdelt2):
"""
The following contructs a restoring beam from the psf. This is accoplished by fitting an elliptical Gaussian to the
central lobe of the PSF.
INPUTS:
psf (no default): Array containing the psf for the image in question.
cdelt1, cdelt2 (no default... |
Setup argparse arguments. | def make_argparser():
"""
Setup argparse arguments.
:return: The parser which :class:`MypolrCli` expects parsed arguments from.
:rtype: argparse.ArgumentParser
"""
parser = argparse.ArgumentParser(prog='mypolr',
description="Interacts with the Polr Project's... |
This function estimates the noise using the MAD estimator. | def estimate_threshold(in1, edge_excl=0, int_excl=0):
"""
This function estimates the noise using the MAD estimator.
INPUTS:
in1 (no default): The array from which the noise is estimated
OUTPUTS:
out1 An array of per-scale noise estimates.
"""
... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.