code stringlengths 1 18.2k |
|---|
def _get_attr_like_prefix(self, sig): """Return prefix text for attribute or data directive.""" sig_match = chpl_attr_sig_pattern.match(sig) if sig_match is None: return ChapelObject.get_signature_prefix(self, sig) prefixes, _, _, _ = sig_match.groups() if prefixes: return prefixes.strip() + ' ' elif self.objtype == 't... |
def _get_proc_like_prefix(self, sig): """Return prefix text for function or method directive (and similar). """ sig_match = chpl_sig_pattern.match(sig) if sig_match is None: return ChapelObject.get_signature_prefix(self, sig) prefixes, _, _, _, _ = sig_match.groups() if prefixes: return prefixes.strip() + ' ' elif self... |
def _get_sig_prefix(self, sig): """Return signature prefix text. For attribute, data, and proc/iter directives this might be part of the signature. E.g. `type myNewType` will return a prefix of 'type' and `inline proc foo()` will return 'inline proc'. """ if self._is_proc_like(): return self._get_proc_like_prefix(sig) ... |
def handle_signature(self, sig, signode): """Parse the signature *sig* into individual nodes and append them to the *signode*. If ValueError is raises, parsing is aborted and the whole *sig* string is put into a single desc_name node. The return value is the value that identifies the object. IOW, it is the identifier t... |
self.options.get( 'module', self.env.temp_data.get('chpl:module')) classname = self.env.temp_data.get('chpl:class') if classname: if name_prefix and name_prefix.startswith(classname): fullname = name_prefix + name # class name is given again in the signature name_prefix = name_prefix[len(classname):].lstrip('.') elif n... |
not arglist: # If this needs an arglist, and parens were provided in the # signature, add a parameterlist. Chapel supports paren-less # functions and methods, which can act as computed properties. If # arglist is the empty string, the signature included parens. If # arglist is None, it did not include parens. if self.n... |
def add_target_and_index(self, name_cls, sig, signode): """Add cross-reference IDs and entries to the index node, if applicable. *name_cls* is the return value of :py:meth:`handle_signature`. """ modname = self.options.get( 'module', self.env.temp_data.get('chpl:module')) fullname = (modname and modname + '.' or '') + ... |
def run(self): """Custom execution for chapel module directive. This class is instantiated by the directive implementation and then this method is called. It parses the options on the module directive, updates the environment according, and creates an index entry for the module. Based on the python domain module direct... |
modindex currently. ret.append(targetnode) indextext = _('%s (module)') % modname inode = addnodes.index(entries=[('single', indextext, 'module-' + modname, '')]) ret.append(inode) return ret |
def chpl_type_name(self): """Returns iterator or method or '' depending on object type.""" if not self.objtype.endswith('method'): return '' elif self.objtype.startswith('iter'): return 'iterator' elif self.objtype == 'method': return 'method' else: return '' |
def get_index_text(self, modname, name_cls): """Return text for index entry based on object type.""" name, cls = name_cls add_modules = self.env.config.add_module_names if self.objtype.endswith('method'): try: clsname, methname = name.rsplit('.', 1) except ValueError: if modname: return _('%s() (in module %s)') % (name... |
def get_index_text(self, modname, name_cls): """Return index entry text based on object type.""" if self.objtype in ('class', 'record'): if not modname: return _('%s (built-in %s)') % (name_cls[0], self.objtype) return _('%s (%s in %s)') % (name_cls[0], self.objtype, modname) else: return '' |
def before_content(self): """Called before parsing content. Push the class name onto the class name stack. Used to construct the full name for members. """ ChapelObject.before_content(self) if self.names: self.env.temp_data['chpl:class'] = self.names[0][0] self.clsname_set = True |
def get_index_text(self, modname, name_cls): """Return text for index entry based on object type.""" if self.objtype.endswith('function'): if not modname: return _('%s() (built-in %s)') % \ (name_cls[0], self.chpl_type_name) return _('%s() (in module %s)') % (name_cls[0], modname) elif self.objtype in ('data', 'type', ... |
def process_link(self, env, refnode, has_explicit_title, title, target): """Called after parsing title and target text, and creating the reference node. Alter the reference node and return it with chapel module and class information, if relevant. """ refnode['chpl:module'] = env.temp_data.get('chpl:module') refnode['ch... |
def generate(self, docnames=None): """Returns entries for index given by ``name``. If ``docnames`` is given, restrict to entries referring to these docnames. Retunrs tuple of ``(content, collapse)``. ``collapse`` is bool. When True, sub-entries should start collapsed for output formats that support collapsing. ``conten... |
* ``anchor`` - anchor for the entry within docname * ``extra`` - extra info for the entry * ``qualifier`` - qualifier for the description * ``description`` - description for the entry Qualifier and description are not rendered in some output formats. """ content = {} # list of prefixes to ignore ignores = self.domain.e... |
modname = modname[len(ignore):] stripped = ignore break else: stripped = '' # we stripped the whole module name? if not modname: modname, stripped = stripped, '' # Put the module in correct bucket (first letter). entries = content.setdefault(modname[0].lower(), []) package = modname.split('.')[0] if package != modname:... |
modindex at page load: only # collapse if number of toplevel modules is larger than number of # submodules collapse = len(modules) - num_toplevels < num_toplevels # sort by first leter content = sorted(iteritems(content)) return content, collapse |
def clear_doc(self, docname): """Remove the data associated with this instance of the domain.""" for fullname, (fn, x) in self.data['objects'].items(): if fn == docname: del self.data['objects'][fullname] for modname, (fn, x, x, x) in self.data['modules'].items(): if fn == docname: del self.data['modules'][modname] for... |
def find_obj(self, env, modname, classname, name, type_name, searchmode=0): """Find a Chapel object for "name", possibly with module or class/record name. Returns a list of (name, object entry) tuples. :arg int searchmode: If 1, search more specific names first. Otherwise, search built-ins first and then get more speci... |
and objects[modname + '.' + name][1] in objtypes): newname = modname + '.' + name elif name in objects and objects[name][1] in objtypes: newname = name else: # "Fuzzy" search mode. searchname = '.' + name matches = [(oname, objects[oname]) for oname in objects if oname.endswith(searchname) and objects[oname][1] in objt... |
+ name in objects): newname = modname + '.' + classname + '.' + name if newname is not None: matches.append((newname, objects[newname])) return matches |
def resolve_xref(self, env, fromdocname, builder, type_name, target, node, contnode): """Resolve the pending_xref *node* with give *type_name* and *target*. Returns None if xref node can not be resolved. If xref can be resolved, returns new node containing the *contnode*. """ # Special case the :chpl:chplref:`chplmodin... |
= self.find_obj(env, modname, clsname, target, type_name, searchmode) if not matches: return None elif len(matches) > 1: env.warn_node( 'more than one target found for cross-reference ' '%r: %s' % (target, ', '.join(match[0] for match in matches)), node) name, obj = matches[0] if obj[1] == 'module': return self._make_m... |
def resolve_any_xref(self, env, fromdocname, builder, target, node, contnode): """Similar to :py:meth:`ChapelDomain.resolve_xref`, but applies to *any* or similar role where type is not known. This returns a list of tuples with ("domain:role", newnode). """ modname = node.get('chpl:module') clsname = node.get('chpl:cla... |
def _make_refnode(self, fromdocname, builder, docname, labelid, sectname, contnode, **kwargs): """Return reference node for something like ``:chpl:chplref:``.""" nodeclass = kwargs.pop('nodeclass', nodes.reference) newnode = nodeclass('', '', internal=True, **kwargs) innernode = nodes.emphasis(sectname, sectname) if do... |
def _make_module_refnode(self, builder, fromdocname, name, contnode): """Helper function to generate new xref node based on current environment. """ # Get additional info for modules. docname, synopsis, platform, deprecated = self.data['modules'][name] title = name if synopsis: title += ': ' + synopsis if deprecated: t... |
def merge_domaindata(self, docnames, otherdata): """Merge in data regarding *docnames* from a different domaindata inventory (coming froma subprocess in a parallel build). """ for fullname, (fn, objtype) in otherdata['objects'].items(): if fn in docnames: self.data['objects'][fullname] = (fn, objtype) for modname, data... |
def get_objects(self): """Return iterable of "object descriptions", which are tuple with these items: * `name` * `dispname` * `type` * `docname` * `anchor` * `priority` For details on each item, see :py:meth:`~sphinx.domains.Domain.get_objects`. """ for modname, info in self.data['modules'].items(): yield (modname, mod... |
def main(argString=None): """The main function. :param argString: the options. :type argString: list of strings These are the steps of the modules: 1. Prints the options. 2. Reads the population file (:py:func:`read_population_file`). 3. Reads the ``mds`` file (:py:func:`read_mds_file`). 4. Computes the three reference... |
populations) # Finds the population centers logger.info("Finding reference population centers") centers, center_info = find_ref_centers(mds) # Computes three clusters using KMeans and the reference cluster centers logger.info("Finding outliers") outliers = find_outliers(mds, centers, center_info, args.outliers_of, args... |
a summary file in the working directory (for LaTeX), we want # to modify it, because it means that this script is run after the pipeline # (to modify the multiplier, for example). if args.overwrite_tex: summary_file = glob(os.path.join(os.getcwd(), "*.summary.tex")) if len(summary_file) == 0: logger.warning("No TeX sum... |
def overwrite_tex(tex_fn, nb_outliers, script_options): """Overwrites the TeX summary file with new values. :param tex_fn: the name of the TeX summary file to overwrite. :param nb_outliers: the number of outliers. :param script_options: the script options. :type tex_fn: str :type nb_outliers: int :type options: argpars... |
n = re.subn( r"(shows\s)the\sfirst\stwo\sprincipal\scomponents(\sof\sthe\sMDS" r"\sanalysis)", r"\g<1>components {} versus {}\g<2>".format( script_options.yaxis.replace("C", ""), script_options.xaxis.replace("C", ""), ), content, ) if n != 1: raise ProgramError("{}: invalid TeX summary file".format(tex_fn)) content, n ... |
) if n != 1: raise ProgramError("{}: invalid TeX summary file".format(tex_fn)) # Saving the new content with open(tex_fn, "w") as o_file: o_file.write(content) |
def find_outliers(mds, centers, center_info, ref_pop, options): """Finds the outliers for a given population. :param mds: the ``mds`` information about each samples. :param centers: the centers of the three reference population clusters. :param center_info: the label of the three reference population clusters. :param r... |
sample is an outlier of a given cluster :math:`C_j` if the distance between this sample and the center of the cluster :math:`C_j` (:math:`O_j`) is bigger than a constant times the cluster's standard deviation :math:`\\sigma_j`. .. math:: \\sigma_j = \\sqrt{\\frac{\\sum{d(s_i,O_j)^2}}{||C_j|| - 1}} where :math:`||C_j||`... |
import matplotlib as mpl if options.format != "X11" and mpl.get_backend() != "agg": mpl.use("Agg") import matplotlib.pyplot as plt if options.format != "X11": plt.ioff() import matplotlib.mlab as mlab from sklearn.cluster import KMeans from sklearn.metrics.pairwise import euclidean_distances # Formatting the data data ... |
# The population name ref_pop_name = ["CEU", "YRI", "JPT-CHB"] # The colors colors = ["#CC0000", "#669900", "#0099CC"] outlier_colors = ["#FFCACA", "#E2F0B6", "#C5EAF8"] # Plotting each of the clusters with the initial center plots_before = [] plots_after = [] plots_outliers = [] plot_outliers = None plot_not_outliers ... |
> options.multiplier * sigma).flatten(), subset_mds["pop"] != ref_pop_name[label], ) logger.info(" - {} outliers for the {} cluster".format( np.sum(outliers), ref_pop_name[label], )) # Saving the outliers if ref_pop_name[label] != options.outliers_of: # This is not the population we want, hence everybody is an outlier ... |
clip_on=False) # Plotting the not outliers plot_not_outliers, = axe_outliers.plot( subset_mds["c1"][np.logical_and( ~outliers, subset_mds["pop"] != ref_pop_name[label] )], subset_mds["c2"][np.logical_and( ~outliers, subset_mds["pop"] != ref_pop_name[label] )], "o", mec="#FFBB33", mfc="#FFBB33", ms=2, clip_on=False, ) o... |
fontsize=8).get_frame().set_alpha(0.5) # Saving the figure fig_before.savefig("{}.before.{}".format(options.out, options.format), dpi=300) fig_after.savefig("{}.after.{}".format(options.out, options.format), dpi=300) fig_outliers.savefig("{}.outliers.{}".format(options.out, options.format), dpi=300) return outliers_set |
def find_ref_centers(mds): """Finds the center of the three reference clusters. :param mds: the ``mds`` information about each samples. :type mds: numpy.recarray :returns: a tuple with a :py:class:`numpy.array` containing the centers of the three reference population cluster as first element, and a :py:class:`dict` con... |
return np.array(centers), {"CEU": 0, "YRI": 1, "JPT-CHB": 2} |
def read_mds_file(file_name, c1, c2, pops): """Reads a MDS file. :param file_name: the name of the ``mds`` file. :param c1: the first component to read (x axis). :param c2: the second component to read (y axis). :param pops: the population of each sample. :type file_name: str :type c1: str :type c2: str :type pops: dic... |
enumerate(create_row(input_file.readline())) ]) for col_name in {"FID", "IID", c1, c2}: if col_name not in header_index: msg = "{}: no column named {}".format(file_name, col_name) raise ProgramError(msg) for row in map(create_row, input_file): # Getting the sample ID sample_id = (row[header_index["FID"]], row[header_in... |
def read_population_file(file_name): """Reads the population file. :param file_name: the name of the population file. :type file_name: str :returns: a :py:class:`dict` containing the population for each of the samples. The population file should contain three columns: 1. The family ID. 2. The individual ID. 3. The popu... |
raise ProgramError(msg) # Saving the population file pops[tuple(row[:2])] = row[-1] return pops |
def checkArgs(args): """Checks the arguments and options. :param args: a :py:class:`argparse.Namespace` object containing the options of the program. :type args: argparse.Namespace :returns: ``True`` if everything was OK. If there is a problem with an option, an exception is raised using the :py:class:`ProgramError` cl... |
def add_custom_options(parser): """Adds custom options to a parser. :param parser: the parser to which to add options. :type parser: argparse.ArgumentParser """ parser.add_argument("--outliers-of", type=str, metavar="POP", default="CEU", choices=["CEU", "YRI", "JPT-CHB"], help=("Finds the outliers of this population. "... |
def from_data(cls, data): """Create a list of Messages from deserialized epubcheck json output. :param dict data: Decoded epubcheck json data :return list[Message]: List of messages """ messages = [] filename = data['checker']['filename'] for m in data['messages']: for l in m['locations']: location = l['path'] if not l... |
def show(self): """ if the dialog is showed again or is not started with exec_ naming the done button to 'update' make more sense because now the dialog doesn't block (anymore) """ self.btn_done.clicked.connect(lambda: self.btn_done.setText('update')) QtWidgets.QDialog.show(self) |
def check(self): """check whether all attributes are setted and have the right dtype""" for name, valItem, dtype in self.values: val = valItem.text() if dtype: try: val = dtype(val) except: msgBox = QtWidgets.QMessageBox() msgBox.setText( 'attribute %s has not the right dtype(%s)' % (name, str(dtype))) msgBox.exec_() s... |
def done(self, result): """save the geometry before dialog is close to restore it later""" self._geometry = self.geometry() QtWidgets.QDialog.done(self, result) |
def stayOpen(self): """optional dialog restore""" if not self._wantToClose: self.show() self.setGeometry(self._geometry) |
def get_start_date(module, x): """ 曜日による最初の授業の日を返す """ weekdays = ['月', '火', '水', '木', '金', '土', '日'] a, b = parse_module(module) module = a + b[0] d = datetime.datetime(*start_dates[module]) days = weekdays.index(x) - d.weekday() if days < 0: days += 7 delta = datetime.timedelta(days=days) return d + delta |
def get_end_date(module): """ モジュールの終わりの日を返す """ a, b = parse_module(module) module = a + b[-1] return datetime.datetime(*end_dates[module]) |
def parse_stupid_date(c): """ kdbが返してくる間抜けな授業時間をパースしてdatetimeを返す 例: 月1 木3,4 水3,4金5,6 月・火・水3-6 sqlite3 ~/.course_list.db 'select periods from courses'|sort|uniq """ start_time = { 1: { "hour": 8, "minute": 40 }, 2: { "hour": 10, "minute": 10 }, 3: { "hour": 12, "minute": 15 }, 4: { "hour": 13, "minute": 45 }, 5: { "hour... |
list(reversed(list(m.groups()))) weekdays = groups.pop().split('・') period_start = int(groups.pop()) if len(groups) == 0: sep = ',' period_end = period_start else: sep = groups.pop() period_end = int(groups.pop()) assert(sep in ['-', ',']) assert(1 <= period_start <= 6) assert(1 <= period_end <= 6) if sep == ',': asser... |
def generate_ics(courses): """.ics作るやつ""" events = "" for c in courses: created = strftime(datetime.datetime.utcnow()) + "Z" summary = c["title"] location = c["room"] description = "{id}・{modules}・{credit}単位".format(**c) try: dates = parse_stupid_date(c) except AssertionError as e: sys.stderr.write("無視: 日付またはモジュールのパースに... |
def configure(self, **kwds): """ Update Trovebox HTTP client configuration. :param api_version: Include a Trovebox API version in all requests. This can be used to ensure that your application will continue to work even if the Trovebox API is updated to a new revision. [default: None] :param ssl_verify: If true, HTTPS ... |
def get(self, endpoint, process_response=True, **params): """ Performs an HTTP GET from the specified endpoint (API path), passing parameters if given. The api_version is prepended to the endpoint, if it was specified when the Trovebox object was created. Returns the decoded JSON dictionary, and raises exceptions if an... |
return response.text else: raise TroveboxError("HTTP Error %d: %s" % (response.status_code, response.reason)) |
def _construct_url(self, endpoint): """Return the full URL to the specified endpoint""" parsed_url = urlparse(self.host) scheme = parsed_url[0] host = parsed_url[1] # Handle host without a scheme specified (eg. www.example.com) if scheme == "": scheme = "http" host = self.host if not endpoint.startswith("/"): endpoint ... |
def _process_params(self, params): """ Converts Unicode/lists/booleans inside HTTP parameters """ processed_params = {} for key, value in params.items(): processed_params[key] = self._process_param_value(value) return processed_params |
def _process_param_value(self, value): """ Returns a UTF-8 string representation of the parameter value, recursing into lists. """ # Extract IDs from objects if isinstance(value, TroveboxObject): return str(value.id).encode('utf-8') # Ensure strings are UTF-8 encoded elif isinstance(value, TEXT_TYPE): return value.enco... |
def _process_response(response): """ Decodes the JSON response, returning a dict. Raises an exception if an invalid response code is received. """ if response.status_code == 404: raise Trovebox404Error("HTTP Error %d: %s" % (response.status_code, response.reason)) try: json_response = response.json() code = json_respon... |
def _update_fields_with_objects(self): """ Convert dict fields into objects, where appropriate """ # Update the data with photo objects if self.type is not None: if self.type.startswith("photo"): self.data = Photo(self._client, self.data) else: raise NotImplementedError("Unrecognised activity type: %s" % self.type) |
def get_print_list(): """ get_print_list """ profiler = start_profile() meth1() meth2() meth3() meth4() return end_profile(profiler, returnvalue=True) |
def main(): """ main """ profiler = start_profile() meth1() meth2() meth3() meth4() aggregate() end_profile(profiler) runsnake_profile_method("aggregate", globals(), locals()) |
def crawl(self): """crawl function to return list of crawled urls.""" page = Linkfetcher(self.root) page.linkfetch() queue = Queue() for url in page.urls: queue.put(url) followed = [self.root] n = 0 while True: try: url = queue.get() except QueueEmpty: break n += 1 if url not in followed: try: host = urllib.parse.urlpa... |
def render(self, name, value, attrs=None): """Override the render() method to replace value with our current values This approach is based on the approach that Django's PasswordInput widget uses to ensure that passwords are not re-rendered in forms, except instead of prohibiting initial values we set them to those for ... |
def generate_captcha(self): """Generated a fresh captcha This method randomly generates a simple captcha question. It then generates a timestamp for the current time, and signs the answer cryptographically to protect against tampering and replay attacks. """ # Generate a fresh question self._question, answer = self._ge... |
def _generate_question(self): """Generate a random arithmetic question This method randomly generates a simple addition, subtraction, or multiplication question with two integers between 1 and 10, and then returns both question (formatted as a string) and answer. """ x = random.randint(1, 10) y = random.randint(1, 10) ... |
question = '{} {} {}'.format(x, operator, y) return mark_safe(question), answer |
def hash_answer(self, answer, timestamp): """Cryptographically hash the answer with the provided timestamp This method allows the widget to securely generate time-sensitive signatures that will both prevent tampering with the answer as well as provide some protection against replay attacks by limiting how long a given ... |
def main(argString=None): """The main function of this module. :param argString: the options. :type argString: list These are the steps: 1. Prints the options. 2. Reads the problematic samples (:py:func:`read_problematic_samples`). 3. Finds and checks the raw files for each of the problematic samples (:py:func:`check_f... |
def check_file_names(samples, raw_dir, options): """Check if all files are present. :param samples: a list of tuples with the family ID as first element (str) and sample ID as last element (str). :param raw_dir: the directory containing the raw files. :param options: the options. :type samples: list of tuples :type raw... |
os.path.isfile(file_name): file_name += ".gz" if not os.path.isfile(file_name): msg = "can't find file for sample {}".format(the_sample) raise ProgramError(msg) file_names[the_sample] = file_name return file_names |
def read_problematic_samples(file_name): """Reads a file with sample IDs. :param file_name: the name of the file containing problematic samples after sex check. :type file_name: str :returns: a set of problematic samples (tuple containing the family ID as first element and the sample ID as last element). Reads a file c... |
def plot_baf_lrr(file_names, options): """Plot BAF and LRR for a list of files. :param file_names: contains the name of the input file for each sample. :param options: the options. :type file_names: dict :type options: argparse.Namespace Plots the BAF (B Allele Frequency) and LRR (Log R Ratio) of each samples. Only the... |
"B Allele Freq", "Log R Ratio"}: if col_name not in header_index: msg = "{}: no column named {}".format(file_name, col_name) raise ProgramError(msg) # Reading the dat for line in input_file: row = line.rstrip("\r\n").split("\t") # We only need X and Y chromosomes chromosome = encode_chromosome(row[header_index["Chr"]])... |
numpy array data = np.array(data, dtype=[("chr", "a1"), ("pos", int), ("lrr", float), ("baf", float)]) # Creating the figure and axes fig, axes = plt.subplots(2, 2, figsize=(20, 8)) plt.subplots_adjust(left=0.05, right=0.97, wspace=0.15, hspace=0.3) fig.suptitle(sample, fontsize=16, weight="bold") # Setting subplot pro... |
lw=1.2) y_lrr_ax.set_ylabel("LRR", weight="bold") y_baf_ax.set_ylabel("BAF", weight="bold") y_baf_ax.set_xlabel("Position (Mb)", weight="bold") y_lrr_ax.set_title("Chromosome Y", weight="bold") # Saving the figure if options.format == "X11": plt.show() else: plt.savefig( "{}_{}_lrr_baf.{}".format(options.out, sample, o... |
def checkArgs(args): """Checks the arguments and options. :param args: an object containing the options of the program. :type args: argparse.Namespace :returns: ``True`` if everything was OK. If there is a problem with an option, an exception is raised using the :py:class:`ProgramError` class, a message is printed to t... |
def chirp_stimul(): """ Amplitude modulated chirp signal """ from scipy.signal import chirp, hilbert duration = 1.0 fs = 256 samples = int(fs * duration) t = np.arange(samples) / fs signal = chirp(t, 20.0, t[-1], 100.0) signal *= (1.0 + 0.5 * np.sin(2.0 * np.pi * 3.0 * t)) analytic_signal = hilbert(signal) * 0.5 ref_ab... |
def main(self, c): """ :type c: Complex :return: abs (gain corrected) angle (in 1 to -1 range) """ phase = Sfix(0.0, 0, -17) abs, _, angle = self.core.main(c.real, c.imag, phase) # get rid of CORDIC gain and extra bits self.y_abs = abs * (1.0 / 1.646760) self.y_angle = angle return self.y_abs, self.y_angle |
def authenticate(self, username="", password="", **kwargs): """Allow users to log in with their email address.""" try: user = get_user_model().objects.filter(email__iexact=username)[0] if check_password(password, user.password): return user else: return None except IndexError: # No user was found, return None - trigger... |
def authenticate(self, username=None, password=None, **kwargs): """Allow users to log in with their email address or username.""" try: # Try to fetch the user by searching the username or email field user = get_user_model().objects.filter(Q(username=username)|Q(email=username))[0] if check_password(password, user.passw... |
def _build_preconditions_table(self): '''Builds the local action precondition expressions.''' self.local_action_preconditions = dict() self.global_action_preconditions = [] action_fluents = self.action_fluents for precond in self.preconds: scope = precond.scope action_scope = [action for action in scope if action in ac... |
def _build_action_bound_constraints_table(self): '''Builds the lower and upper action bound constraint expressions.''' self.action_lower_bound_constraints = {} self.action_upper_bound_constraints = {} for name, preconds in self.local_action_preconditions.items(): for precond in preconds: expr_type = precond.etype expr_... |
def _extract_lower_bound(self, name: str, expr: Expression) -> Optional[Expression]: '''Returns the lower bound expression of the action with given `name`.''' etype = expr.etype args = expr.args if etype[1] in ['<=', '<']: if args[1].is_pvariable_expression() and args[1].name == name: return args[0] elif etype[1] in ['... |
def non_fluents(self) -> Dict[str, PVariable]: '''Returns non-fluent pvariables.''' return { str(pvar): pvar for pvar in self.pvariables if pvar.is_non_fluent() } |
def state_fluents(self) -> Dict[str, PVariable]: '''Returns state-fluent pvariables.''' return { str(pvar): pvar for pvar in self.pvariables if pvar.is_state_fluent() } |
def action_fluents(self) -> Dict[str, PVariable]: '''Returns action-fluent pvariables.''' return { str(pvar): pvar for pvar in self.pvariables if pvar.is_action_fluent() } |
def intermediate_fluents(self) -> Dict[str, PVariable]: '''Returns interm-fluent pvariables.''' return { str(pvar): pvar for pvar in self.pvariables if pvar.is_intermediate_fluent() } |
def intermediate_cpfs(self) -> List[CPF]: '''Returns list of intermediate-fluent CPFs in level order.''' _, cpfs = self.cpfs interm_cpfs = [cpf for cpf in cpfs if cpf.name in self.intermediate_fluents] interm_cpfs = sorted(interm_cpfs, key=lambda cpf: (self.intermediate_fluents[cpf.name].level, cpf.name)) return interm... |
def state_cpfs(self) -> List[CPF]: '''Returns list of state-fluent CPFs.''' _, cpfs = self.cpfs state_cpfs = [] for cpf in cpfs: name = utils.rename_next_state_fluent(cpf.name) if name in self.state_fluents: state_cpfs.append(cpf) state_cpfs = sorted(state_cpfs, key=lambda cpf: cpf.name) return state_cpfs |
def interm_fluent_ordering(self) -> List[str]: '''The list of intermediate-fluent names in canonical order. Returns: List[str]: A list of fluent names. ''' interm_fluents = self.intermediate_fluents.values() key = lambda pvar: (pvar.level, pvar.name) return [str(pvar) for pvar in sorted(interm_fluents, key=key)] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.