text
stringlengths
18
773k
def parse_entry(self, row): """Parse an individual VCF entry and return a VCFEntry which contains information about the call (such as alternative allele, zygosity, etc.) """ var_call = VCFEntry(self.individuals) var_call.parse_entry(row) return var_call
def add_entry(self, row): """This will parse the VCF entry and also store it within the VCFFile. It will also return the VCFEntry as well. """ var_call = VCFEntry(self.individuals) var_call.parse_entry( row ) self.entries[(var_call.chrom, var_call.pos)] = var_call ...
def get_header(self, individual=-1): """Returns the vcf header """ type_map = dict([(val,key) for key,val in self.meta.type_map.iteritems()]) extra = '\n'.join(['##{0}'.format(i) for i in self.meta.extra]) info = '\n'.join(['##INFO=<ID={0},Number={1},Type={2},Description={3}>'.f...
def add_info(self, entry): """Parse and store the info field""" entry = entry[8:-1] info = entry.split(',') if len(info) < 4: return False for v in info: key, value = v.split('=', 1) if key == 'ID': self.info[value] = {} ...
def add_filter(self, entry): """Parse and store the filter field""" entry = entry[10:-1] info = entry.split(',') if len(info) < 2: return False for v in info: key, value = v.split('=', 1) if key == 'ID': self.filter[value] = {} ...
def add_alt(self, entry): """Parse and store the alternative allele field""" entry = entry[7:-1] info = entry.split(',') if len(info) < 2: return False for v in info: key, value = v.split('=', 1) if key == 'ID': self.alt[value] ...
def sample_string(self, individual=-1): """Returns the VCF entry as it appears in the vcf file""" base = str(self) extra = self.get_sample_info(individual=individual) extra = [':'.join([str(j) for j in i]) for i in zip(*extra.values())] return '\t'.join([base, '\t'.join(extra)])
def get_sample_info(self, individual=-1): """Returns the sample info of a given sample or all by default """ if isinstance(individual, str): individual = self.individuals[individual] extra = OrderedDict() for format_ in self.format: index = getattr(self, ...
def is_homozygous(self, individual=None): """This will give a boolean list corresponding to whether each individual is homozygous for the alternative allele. """ if individual is not None: if isinstance(individual, str): individual = self.individuals[individu...
def get_alt(self, individual=0, nucleotides_only=True): """Returns the alternative alleles of the individual as a list""" #not i.startswith(',') is put in to handle cases like <DEL:ME:ALU> where we have no alternate allele #but some reference if isinstance(individual, str): i...
def get_alt_length(self, individual=0): """Returns the number of basepairs of each alternative allele""" if isinstance(individual, str): individual = self.individuals[individual] return [len(self.alt[i-1].replace('.','')) for i in self.genotype[individual] if i > 0 and not self.alt[i...
def get_alt_lengths(self): """Returns the longest length of the variant. For deletions, return is negative, SNPs return 0, and insertions are +. None return corresponds to no variant in interval for specified individual """ #this is a hack to store the # of individuals without h...
def has_snp(self, individual=0): """Returns a boolean list of SNP status, ordered by samples""" if isinstance(individual, str): individual = self.individuals[individual] alts = self.get_alt(individual=individual) if alts: return [i != self.ref and len(i) == len(se...
def parse_entry(self, entry): """This parses a VCF row and stores the relevant information""" entry = entry.split('\t') self.chrom, self.pos, self.id, self.ref, alt_, self.qual, filter_, info, self.format = entry[:9] self.samples = entry[9:] self.alt = alt_.split(',') if ...
def add_child(self, child): """Children are GFFFeatures and are defined when added. This is done to avoid memory overheads that may be incurred by GFF files that have millions of rows. """ child_id = getattr(child, 'id', None) if child_id: if not hasattr(self, 'child...
def _iso_handler(obj): """ Transforms an object into it's ISO format, if possible. If the object can't be transformed, then an error is raised for the JSON parser. This is meant to be used on datetime instances, but will work with any object having a method called isoformat. :param obj: o...
def try_encode(field_encoders, entity_dict): """ Inner encoding and try return string from entity dictionary :param field_encoders: :param entity_dict: :return: """ result = '' for field_encoder in field_encoders: try: result +=...
def encode(self, entity): """ Generate string of cwr format for all possible combinations of fields, accumulate and then elect the best. The best string it is who used most of all fields :param entity: :return: """ possible_results = [] entity_dict = self....
def argparser(self): """ For setting up the argparser for this instance. """ if self.__argparser is None: self.__argparser = self.argparser_factory() self.init_argparser(self.__argparser) return self.__argparser
def argparser_factory(self): """ Produces argparser for this type of Runtime. """ return ArgumentParser( prog=self.prog, description=self.__doc__, add_help=False, )
def init_argparser(self, argparser): """ This should not be called with an external argparser as it will corrupt tracking data if forced. """ def prepare_argparser(): if argparser in self.argparser_details: return False result = self.argpa...
def unrecognized_arguments_error(self, args, parsed, extras): """ This exists because argparser is dumb and naive and doesn't fail unrecognized arguments early. """ # loop variants kwargs = vars(parsed) failed = list(extras) # initial values runti...
def error(self, argparser, target, message): """ This was used as part of the original non-recursive lookup for the target parser. """ warnings.warn( 'Runtime.error is deprecated and will be removed by calmjs-4.0.0', DeprecationWarning) details = ...
def init_argparser_export_target( self, argparser, default=None, help='the export target', ): """ Subclass could override this by providing alternative keyword arguments and call this as its super. It should not reimplement this completely...
def init_argparser_working_dir( self, argparser, explanation='', help_template=( 'the working directory; %(explanation)s' 'default is current working directory (%(cwd)s)'), ): """ Subclass could an extra expanation on how th...
def init_argparser_build_dir( self, argparser, help=( 'the build directory, where all sources will be copied to ' 'as part of the build process; if left unspecified, the ' 'default behavior is to create a new temporary directory ' 'that will be...
def init_argparser_optional_advice( self, argparser, default=[], help=( 'a comma separated list of packages to retrieve optional ' 'advice from; the provided packages should have registered ' 'the appropriate entry points for setting up the advices for ' ...
def init_argparser(self, argparser): """ Other runtimes (or users of ArgumentParser) can pass their subparser into here to collect the arguments here for a subcommand. """ super(ToolchainRuntime, self).init_argparser(argparser) # it is possible for subclasses to...
def prepare_spec(self, spec, **kwargs): """ Prepare a spec for usage with the generic ToolchainRuntime. Subclasses should avoid overriding this; override create_spec instead. """ self.prepare_spec_debug_flag(spec, **kwargs) self.prepare_spec_export_target_checks...
def kwargs_to_spec(self, **kwargs): """ Turn the provided kwargs into arguments ready for toolchain. """ spec = self.create_spec(**kwargs) self.prepare_spec(spec, **kwargs) return spec
def init_argparser_package_names(self, argparser, help=( 'names of the python package to generate artifacts for; ' 'note that the metadata directory for the specified ' 'packages must be writable')): """ Default helper for setting up the package_names opti...
def init_argparser_source_registry( self, argparser, default=None, help=( 'comma separated list of registries to use for gathering ' 'JavaScript sources from the given Python packages' )): """ For setting up the source registry flag. """ ...
def init_argparser_loaderplugin_registry( self, argparser, default=None, help=( 'the name of the registry to use for the handling of loader ' 'plugins that may be loaded from the given Python packages' )): """ Default helper for setting up the load...
def init_argparser(self, argparser): """ Other runtimes (or users of ArgumentParser) can pass their subparser into here to collect the arguments here for a subcommand. """ super(SourcePackageToolchainRuntime, self).init_argparser(argparser) self.init_argparser_s...
def init_argparser(self, argparser): """ Other runtimes (or users of ArgumentParser) can pass their subparser into here to collect the arguments here for a subcommand. """ super(PackageManagerRuntime, self).init_argparser(argparser) # Ideally, we could use more ...
def alphanum(columns, name=None, extended=False, isLast=False): """ Creates the grammar for an Alphanumeric (A) field, accepting only the specified number of characters. By default Alphanumeric fields accept only ASCII characters, excluding lowercases. If the extended flag is set to True, then non-...
def _check_not_empty(string): """ Checks that the string is not empty. If it is empty an exception is raised, stopping the validation. This is used for compulsory alphanumeric fields. :param string: the field value """ string = string.strip() if len(string) == 0: message = 'T...
def numeric(columns, name=None): """ Creates the grammar for a Numeric (N) field, accepting only the specified number of characters. This version only allows integers. :param columns: number of columns for this field :param name: name for the field :return: grammar for the integer numeric ...
def numeric_float(columns, nums_int, name=None): """ Creates the grammar for a Numeric (N) field, accepting only the specified number of characters. This version only allows floats. As nothing in the string itself indicates how many of the characters are for the integer and the decimal section...
def _to_numeric_float(number, nums_int): """ Transforms a string into a float. The nums_int parameter indicates the number of characters, starting from the left, to be used for the integer value. All the remaining ones will be used for the decimal value. :param number: string with the number ...
def _check_above_value_float(string, minimum): """ Checks that the number parsed from the string is above a minimum. This is used on compulsory numeric fields. If the value is not above the minimum an exception is thrown. :param string: the field value :param minimum: minimum value """ ...
def boolean(name=None): """ Creates the grammar for a Boolean (B) field, accepting only 'Y' or 'N' :param name: name for the field :return: grammar for the flag field """ if name is None: name = 'Boolean Field' # Basic field field = pp.Regex('[YN]') # Parse action fie...
def _to_boolean(string): """ Transforms a string into a boolean value. If a value which is not 'Y' or 'N' is received, a ParseException is thrown. :param: string: the string to transform :return: True if the string is 'Y', False if it is 'N' """ if string == 'Y': result = True ...
def flag(name=None): """ Creates the grammar for a Flag (F) field, accepting only 'Y', 'N' or 'U'. :param name: name for the field :return: grammar for the flag field """ if name is None: name = 'Flag Field' # Basic field field = pp.Regex('[YNU]') # Name field.setName...
def date(name=None): """ Creates the grammar for a Date (D) field, accepting only numbers in a certain pattern. :param name: name for the field :return: grammar for the date field """ if name is None: name = 'Date Field' # Basic field # This regex allows values from 000001...
def time(name=None): """ Creates the grammar for a Time or Duration (T) field, accepting only numbers in a certain pattern. :param name: name for the field :return: grammar for the date field """ if name is None: name = 'Time Field' # Basic field # This regex allows values...
def lookup(values, name=None): """ Creates the grammar for a Lookup (L) field, accepting only values from a list. Like in the Alphanumeric field, the result will be stripped of all heading and trailing whitespaces. :param values: values allowed :param name: name for the field :return: ...
def blank(columns=1, name=None): """ Creates the grammar for a blank field. These are for constant empty strings which should be ignored, as they are used just as fillers. :param columns: number of columns, which is the required number of whitespaces :param name: name for the field :re...
def get_attribute(self, attribute, value=None, features=False): """This returns a list of GFF objects (or GFF Features) with the given attribute and if supplied, those attributes with the specified value :param attribute: The 'info' field attribute we are querying :param value: Optional...
def contains(self, seqid, start, end, overlap=True): """This returns a list of GFF objects which cover a specified location. :param seqid: The landmark identifier (usually a chromosome) :param start: The 1-based position of the start of the range we are querying :param end: The 1-based ...
def contains(self, chrom, start, end, overlap=True): """This returns a list of VCFEntry objects which cover a specified location. :param chrom: The landmark identifier (usually a chromosome) :param start: The 1-based position of the start of the range we are querying :param end: The 1-b...
def remove_variants(self, variants): """Remove a list of variants from the positions we are scanning""" chroms = set([i.chrom for i in variants]) for chrom in chroms: if self.append_chromosome: chrom = 'chr%s' % chrom to_delete = [pos for pos in self.posit...
def generate_handler_sourcepath( self, toolchain, spec, loaderplugin_sourcepath): """ The default implementation is a recursive lookup method, which subclasses may make use of. Subclasses must implement this to return a mapping of modnames the the absolute path of th...
def generate_handler_sourcepath( self, toolchain, spec, loaderplugin_sourcepath): """ Attempt to locate the plugin source; returns a mapping of modnames to the absolute path of the located sources. """ # TODO calmjs-4.0.0 consider formalizing to the method instead ...
def store_records_for_package(self, entry_point, records): """ Given that records are based on the parent, and the same entry point(s) will reference those same records multiple times, the actual stored records must be limited. """ pkg_records_entry = self._dist_to_packa...
def default_file_encoder(): """ Get default encoder cwr file :return: """ config = CWRConfiguration() field_configs = config.load_field_config('table') field_configs.update(config.load_field_config('common')) field_values = CWRTables() for entry in field_configs.values(): i...
def encode(self, tag): """ Parses a CWR file name from a FileTag object. The result will be a string following the format CWyynnnnsss_rrr.Vxx, where the numeric sequence will have the length set on the encoder's constructor. :param tag: FileTag to parse :return:...
def encode(self, transmission): """ Encodes the data, creating a CWR structure from an instance from the domain model. :param entity: the instance to encode :return: a cwr string structure created from the received data """ data = '' data += self._record_...
def getScans(self, modifications=True, fdr=True): """ get a random scan """ if not self.scans: for i in self: yield i else: for i in self.scans.values(): yield i yield None
def getScan(self, title, peptide=None): """ allows random lookup """ if self.ra.has_key(title): self.filename.seek(self.ra[title][0],0) toRead = self.ra[title][1]-self.ra[title][0] info = self.filename.read(toRead) scan = self.parseScan(inf...
def parseScan(self, scan): """ All input follows the BEGIN IONS row and ends before END IONS """ setupScan = True foundCharge = False foundMass = False foundTitle = False scanObj = ScanObject() scanObj.ms_level = 2 for row in scan.split('\n...
def getScan(self, specId, peptide=None): """ get a random scan """ sql = self.base_sql + " where sh.SpectrumID = %d and p.Sequence = '%s'"%(int(specId),peptide) self.cur.execute(sql) i = self.cur.fetchone() if not i: return None scan = self.par...
def getScans(self, modifications=False, fdr=True): """ get a random scan """ if fdr: sql = self.base_sql+"WHERE p.ConfidenceLevel >= {} and p.SearchEngineRank <= {} {}".format(self.clvl, self.srank, self.extra) try: self.cur.execute(sql) ...
def parseFullScan(self, i, modifications=False): """ parses scan info for giving a Spectrum Obj for plotting. takes significantly longer since it has to unzip/parse xml """ scanObj = PeptideObject() peptide = str(i[1]) pid=i[2] scanObj.acc = self.protein_map.get(i...
def getScans(self, modifications=True, fdr=True): """ get a random scan """ if fdr: sql = "select sp.Spectrum, p.Sequence, p.PeptideID, p.SpectrumID from spectrumheaders sh left join spectra sp on (sp.UniqueSpectrumID=sh.UniqueSpectrumID) left join peptides p on (sh.SpectrumI...
def parseFullScan(self, i, modifications=True): """ parses scan info for giving a Spectrum Obj for plotting. takes significantly longer since it has to unzip/parse xml """ scanObj = PeptideObject() peptide = str(i[1]) pid=i[2] if modifications: sql = '...
def _cls_lookup_dist(cls): """ Attempt to resolve the distribution from the provided class in the most naive way - this assumes the Python module path to the class contains the name of the package that provided the module and class. """ frags = cls.__module__.split('.') for name in ('.'.joi...
def verify_builder(builder): """ To ensure that the provided builder has a signature that is at least compatible. """ try: d = getcallargs(builder, package_names=[], export_target='some_path') except TypeError: return False return d == {'package_names': [], 'export_target': ...
def extract_builder_result(builder_result, toolchain_cls=Toolchain): """ Extract the builder result to produce a ``Toolchain`` and ``Spec`` instance. """ try: toolchain, spec = builder_result except Exception: return None, None if not isinstance(toolchain, toolchain_cls) or ...
def trace_toolchain(toolchain): """ Trace the versions of the involved packages for the provided toolchain instance. """ pkgs = [] for cls in getmro(type(toolchain)): if not issubclass(cls, Toolchain): continue dist = _cls_lookup_dist(cls) value = { ...
def get_artifact_filename(self, package_name, artifact_name): """ Similar to pkg_resources.resource_filename, however this works with the information cached in this registry instance, and arguments are not quite the same. Arguments: package_name The name of ...
def resolve_artifacts_by_builder_compat( self, package_names, builder_name, dependencies=False): """ Yield the list of paths to the artifacts in the order of the dependency resolution Arguments: package_names The names of the packages to probe the depend...
def get_artifact_metadata(self, package_name): """ Return metadata of the artifacts built through this registry. """ filename = self.metadata.get(package_name) if not filename or not exists(filename): return {} with open(filename, encoding='utf8') as fd: ...
def generate_metadata_entry(self, entry_point, toolchain, spec): """ After the toolchain and spec have been executed, this may be called to generate the artifact export entry for persistence into the metadata file. """ export_target = spec['export_target'] toolch...
def iter_records_for(self, package_name): """ Iterate records for a specific package. """ entry_points = self.packages.get(package_name, NotImplemented) if entry_points is NotImplemented: logger.debug( "package '%s' has not declared any entry points f...
def generate_builder(self, entry_point, export_target): """ Yields exactly one builder if both the provided entry point and export target satisfies the checks required. """ try: builder = entry_point.resolve() except ImportError: logger.error( ...
def execute_builder(self, entry_point, toolchain, spec): """ Accepts the arguments provided by the builder and executes them. """ toolchain(spec) if not exists(spec['export_target']): logger.error( "the entry point '%s' from package '%s' failed to " ...
def process_package(self, package_name): """ Build artifacts declared for the given package. """ metadata = super(ArtifactRegistry, self).process_package(package_name) if metadata: self.update_artifact_metadata(package_name, metadata)
def alphanum_variable(min_size, max_size, name=None): """ Creates the grammar for an alphanumeric code where the size ranges between two values. :param min_size: minimum size :param max_size: maximum size :param name: name for the field :return: grammar for an alphanumeric field of a variab...
def year(columns, name=None): """ Creates the grammar for a field containing a year. :param columns: the number of columns for the year :param name: the name of the field :return: """ if columns < 0: # Can't have negative size raise BaseException() field = numeric(colu...
def is_json_compat(value): """ Check that the value is either a JSON decodable string or a dict that can be encoded into a JSON. Raises ValueError when validation fails. """ try: value = json.loads(value) except ValueError as e: raise ValueError('JSON decoding error: ' + st...
def validate_json_field(dist, attr, value): """ Check for json validity. """ try: is_json_compat(value) except ValueError as e: raise DistutilsSetupError("%r %s" % (attr, e)) return True
def validate_line_list(dist, attr, value): """ Validate that the value is compatible """ # does not work as reliably in Python 2. if isinstance(value, str): value = value.split() value = list(value) try: check = (' '.join(value)).split() if check == value: ...
def write_json_file(argname, cmd, basename, filename): """ Write JSON captured from the defined argname into the package's egg-info directory using the specified filename. """ value = getattr(cmd.distribution, argname, None) if isinstance(value, dict): value = json.dumps( v...
def write_line_list(argname, cmd, basename, filename): """ Write out the retrieved value as list of lines. """ values = getattr(cmd.distribution, argname, None) if isinstance(values, list): values = '\n'.join(values) cmd.write_or_delete_file(argname, filename, values, force=True)
def find_pkg_dist(pkg_name, working_set=None): """ Locate a package's distribution by its name. """ working_set = working_set or default_working_set req = Requirement.parse(pkg_name) return working_set.find(req)
def convert_package_names(package_names): """ Convert package names, which can be a string of a number of package names or requirements separated by spaces. """ results = [] errors = [] for name in ( package_names.split() if hasattr(package_names, 'split') else pack...
def find_packages_requirements_dists(pkg_names, working_set=None): """ Return the entire list of dependency requirements, reversed from the bottom. """ working_set = working_set or default_working_set requirements = [ r for r in (Requirement.parse(req) for req in pkg_names) if w...
def find_packages_parents_requirements_dists(pkg_names, working_set=None): """ Leverages the `find_packages_requirements_dists` but strip out the distributions that matches pkg_names. """ dists = [] # opting for a naive implementation targets = set(pkg_names) for dist in find_packages_r...
def read_dist_egginfo_json(dist, filename=DEFAULT_JSON): """ Safely get a json within an egginfo from a distribution. """ # use the given package's distribution to acquire the json file. if not dist.has_metadata(filename): logger.debug("no '%s' for '%s'", filename, dist) return ...
def read_egginfo_json(pkg_name, filename=DEFAULT_JSON, working_set=None): """ Read json from egginfo of a package identified by `pkg_name` that's already installed within the current Python environment. """ working_set = working_set or default_working_set dist = find_pkg_dist(pkg_name, working_...
def flatten_dist_egginfo_json( source_dists, filename=DEFAULT_JSON, dep_keys=DEP_KEYS, working_set=None): """ Flatten a distribution's egginfo json, with the depended keys to be flattened. Originally this was done for this: Resolve a distribution's (dev)dependencies through the wor...
def flatten_egginfo_json( pkg_names, filename=DEFAULT_JSON, dep_keys=DEP_KEYS, working_set=None): """ A shorthand calling convention where the package name is supplied instead of a distribution. Originally written for this: Generate a flattened package.json with packages `pkg_names` that a...
def build_helpers_egginfo_json( json_field, json_key_registry, json_filename=None): """ Return a tuple of functions that will provide the usage of the JSON egginfo based around the provided field. """ json_filename = ( json_field + '.json' if json_filename is None else json_filename...
def build_helpers_module_registry_dependencies(registry_name='calmjs.module'): """ Return a tuple of funtions that will provide the functions that return the relevant sets of module registry records based on the dependencies defined for the provided packages. """ def get_module_registry_depende...
def has_calmjs_artifact_declarations(cmd, registry_name='calmjs.artifacts'): """ For a distutils command to verify that the artifact build step is possible. """ return any(get(registry_name).iter_records_for( cmd.distribution.get_name()))
def build_calmjs_artifacts(dist, key, value, cmdclass=BuildCommand): """ Trigger the artifact build process through the setuptools. """ if value is not True: return build_cmd = dist.get_command_obj('build') if not isinstance(build_cmd, cmdclass): logger.error( "'bui...
def get_rule(self, field_id): """ Returns the rule for the field identified by the id. If it is set as not being compulsory, the rule will be adapted to accept string composed only of white characters. :param field_id: unique id in the system for the field :return: the ...
def _create_field(self, field_id): """ Creates the field with the specified parameters. :param field_id: identifier for the field :return: the basic rule for the field """ # Field configuration info config = self._field_configs[field_id] adapter = self._...
def read_csv_file(self, file_name): """ Parses a CSV file into a list. :param file_name: name of the CSV file :return: a list with the file's contents """ result = [] with open(os.path.join(self.__path(), os.path.basename(file_name)), 'rt') as c...