code stringlengths 1 18.2k |
|---|
def _weld_unary(array, weld_type, operation): """Apply operation on each element in the array. As mentioned by Weld, the operations follow the behavior of the equivalent C functions from math.h Parameters ---------- array : numpy.ndarray or WeldObject Data weld_type : WeldType Of the data operation : {'exp', 'log', 'sq... |
def _update_fields_with_objects(self): """ Convert dict fields into objects, where appropriate """ # Update the photo target with photo objects if self.target is not None: if self.target_type == "photo": self.target = Photo(self._client, self.target) else: raise NotImplementedError("Actions can only be assigned to " "P... |
def delete(self, **kwds): """ Endpoint: /action/<id>/delete.json Deletes this action. Returns True if successful. Raises a TroveboxError if not. """ result = self._client.action.delete(self, **kwds) self._delete_fields() return result |
def view(self, **kwds): """ Endpoint: /action/<id>/view.json Requests the full contents of the action. Updates the action object's fields with the response. """ result = self._client.action.view(self, **kwds) self._replace_fields(result.get_fields()) self._update_fields_with_objects() |
async def _stream_raw_result(self, res): ''' Stream result for TTY-enabled container above API 1.6 ''' async with res.context as response: response.raise_for_status() async for out in response.content.iter_chunked(1): yield out.decode() |
async def _stream_helper(self, response, decode=False): """Generator for data coming from a chunked-encoded HTTP response.""" if decode: async for chunk in json_stream( self._stream_helper(response, False)): yield chunk else: async with response.context as res: reader = res.content while True: # this read call will blo... |
def main(argString=None): """The main function of the module. :param argString: the options. :type argString: list These are the steps: 1. Prints the options. 2. Runs Plink with the ``geno`` option (:py:func:`runPlink`). 3. Compares the two ``bim`` files (before and after the Plink ``geno`` analysis) (:py:func:`compare... |
def compareBIM(args): """Compare two BIM file. :param args: the options. :type args: argparse.Namespace Creates a *Dummy* object to mimic an :py:class:`argparse.Namespace` class containing the options for the :py:mod:`pyGenClean.PlinkUtils.compare_bim` module. """ # Creating the CompareBIM options class Dummy(object): ... |
def runPlink(options): """Runs Plink with the geno option. :param options: the options. :type options: argparse.Namespace """ # The plink command plinkCommand = ["plink", "--noweb", "--bfile", options.bfile, "--geno", str(options.geno), "--make-bed", "--out", options.out] output = None try: output = subprocess.check_ou... |
def read(mfile, sfile): """ Returns an IadhoreData object, constructed from the passed i-ADHoRe multiplicon and segments output. - mfile (str), location of multiplicons.txt - sfile (str), location of segments.txt """ assert os.path.isfile(mfile), "%s multiplicon file does not exist" assert os.path.isfile(sfile), "%s se... |
def _dbsetup(self): """ Create/open local SQLite database """ self._dbconn = sqlite3.connect(self._db_file) # Create table for multiplicons sql = '''CREATE TABLE multiplicons (id, genome_x, list_x, parent, genome_y, list_y, level, number_of_anchorpoints, profile_length, begin_x, end_x, begin_y, end_y, is_redundant)''' ... |
def _parse_multiplicons(self): """ Read the multiplicon output file, and parse into a (i) tree using NetworkX, and (ii) an SQLite database. """ # Parse data with csv reader reader = csv.reader(open(self._multiplicon_file, 'rU'), delimiter='\t') for row in reader: if reader.line_num == 1: # skip header continue # Add da... |
def _parse_segments(self): """ Read the segment output file and parse into an SQLite database. """ reader = csv.reader(open(self._segment_file, 'rU'), delimiter='\t') for row in reader: if reader.line_num == 1: # skip header continue sql = '''INSERT INTO segments (id, multiplicon, genome, list, first, last, ord) VALUES... |
def get_multiplicon_leaves(self, redundant=False): """ Return a generator of the IDs of multiplicons found at leaves of the tree (i.e. from which no further multiplicons were derived). Arguments: o redundant - if true, report redundant multiplicons """ for node in self._multiplicon_graph.nodes(): if not len(self._multi... |
def get_multiplicon_seeds(self, redundant=False): """ Return a generator of the IDs of multiplicons that are initial seeding 'pairs' in level 2 multiplicons. Arguments: o redundant - if true, report redundant multiplicons """ for node in self._multiplicon_graph.nodes(): if not len(self._multiplicon_graph.in_edges(node)... |
def get_multiplicon_intermediates(self, redundant=False): """ Return a generator of the IDs of multiplicons that are neither seeding 'pairs' in level 2 multiplicons, nor leaves. Arguments: o redundant - if true, report redundant multiplicons """ for node in self._multiplicon_graph.nodes(): if len(self._multiplicon_grap... |
def get_multiplicon_properties(self, value): """ Return a dictionary describing multiplicon data: id, parent, level, number_of_anchorpoints, profile_length, is_redundant and the contributing genome segments """ sql = '''SELECT id, parent, level, number_of_anchorpoints, profile_length, is_redundant FROM multiplicons WHE... |
def get_multiplicon_segments(self, value): """ Return a dictionary describing the genome segments that contribute to the named multiplicon, keyed by genome, with (start feature, end feature) tuples. """ sql = '''SELECT genome, first, last FROM segments WHERE multiplicon=:mp''' cur = self._dbconn.cursor() cur.execute(sq... |
def get_multiplicons_at_level(self, level, redundant=False): """ Return a list of IDs of multiplicons at the requested level """ sql = '''SELECT id FROM multiplicons WHERE level=:level''' cur = self._dbconn.cursor() cur.execute(sql, {'level': str(level)}) result = [int(r[0]) for r in cur.fetchall()] cur.close() if redu... |
def is_redundant_multiplicon(self, value): """ Returns True if the passed multiplicon ID is redundant, False otherwise. - value, (int) multiplicon ID """ if not hasattr(self, '_redundant_multiplicon_cache'): sql = '''SELECT id FROM multiplicons WHERE is_redundant="-1"''' cur = self._dbconn.cursor() cur.execute(sql, {'i... |
def write(self, mfile="multiplicons.txt", sfile="segments.txt", clobber=False): """ Writes multiplicon and segment files to the named locations. - mfile, (str) location for multiplicons file - sfile, (str) location for segments file - clobber, (Boolean) True if we overwrite target files """ if not clobber: if os.path.i... |
def _write_multiplicons(self, filename): """ Write multiplicons to file. - filename, (str) location of output file """ # Column headers mhead = '\t'.join(['id', 'genome_x', 'list_x', 'parent', 'genome_y', 'list_y', 'level', 'number_of_anchorpoints', 'profile_length', 'begin_x', 'end_x', 'begin_y', 'end_y', 'is_redundan... |
def _write_segments(self, filename): """ Write segments to file. - filename, (str) location of output file """ # Column headers shead = '\t'.join(['id', 'multiplicon', 'genome', 'list', 'first', 'last', 'order']) with open(filename, 'w') as fhandle: fhandle.write(shead + '\n') for mrow in self.segments: fhandle.write('... |
def multiplicon_file(self, value): """ Setter for _multiplicon_file attribute """ assert os.path.isfile(value), "%s is not a valid file" % value self._multiplicon_file = value |
def segment_file(self, value): """ Setter for _segment_file attribute """ assert os.path.isfile(value), "%s is not a valid file" % value self._segment_file = value |
def db_file(self, value): """ Setter for _db_file attribute """ assert not os.path.isfile(value), "%s already exists" % value self._db_file = value |
def multiplicons(self): """ Multiplicon table from SQLite database. """ sql = '''SELECT * FROM multiplicons''' cur = self._dbconn.cursor() cur.execute(sql) data = [r for r in cur.fetchall()] cur.close() return data |
def main(): """ The main function of the module. The purpose of this module is to find markers that were removed by Plink. When Plinks exclude some markers from binary files, there are no easy way to find the list of removed markers, except by comparing the two BIM files (before and after modification). Here are the st... |
# Getting and checking the options args = parseArgs() checkArgs(args) # Reading the bim files beforeBIM = readBIM(args.before) afterBIM = readBIM(args.after) # Find differences... compareSNPs(beforeBIM, afterBIM, args.out) |
def compareSNPs(before, after, outFileName): """Compares two set of SNPs. :param before: the names of the markers in the ``before`` file. :param after: the names of the markers in the ``after`` file. :param outFileName: the name of the output file. :type before: set :type after: set :type outFileName: str Finds the dif... |
the SNPs "after" are in "before" if not (after <= before): msg = "some after SNPs are not in before" raise ProgramError(msg) # Printing the SNPs try: with open(outFileName, "w") as outputFile: differences = before - after if len(differences) > 0: print >>outputFile, "\n".join(differences) except IOError: msg = "%(outFi... |
def readBIM(fileName): """Reads a BIM file. :param fileName: the name of the BIM file to read. :type fileName: str :returns: the set of markers in the BIM file. Reads a Plink BIM file and extract the name of the markers. There is one marker per line, and the name of the marker is in the second column. There is no heade... |
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... |
ProgramError(msg) return True |
def add_attr(self, name, value): """Add an attribute to an ``Block`` object""" setattr(self, name, value) self.attrs.append(name) |
def ids(self): """Convenience method to get the ids for Materials present""" assert self.name == "Materials" ids = list() for attr in self.attrs: attr_obj = getattr(self, attr) if hasattr(attr_obj, 'Id'): ids.append(getattr(attr_obj, 'Id')) return ids |
def from_file(cls, fn, *args, **kwargs): """Constructor to build an AmiraHeader object from a file :param str fn: Amira file :return ah: object of class ``AmiraHeader`` containing header metadata :rtype: ah: :py:class:`ahds.header.AmiraHeader` """ return AmiraHeader(get_parsed_data(fn, *args, **kwargs)) |
def get_version(): """Returns the version of formic. This method retrieves the version from VERSION.txt, and it should be exactly the same as the version retrieved from the package manager""" try: # Try with the package manager, if present from pkg_resources import resource_string return resource_string(__name__, "VERS... |
def get_path_components(directory): """Breaks a path to a directory into a (drive, list-of-folders) tuple :param directory: :return: a tuple consisting of the drive (if any) and an ordered list of folder names """ drive, dirs = os.path.splitdrive(directory) folders = [] previous = "" while dirs != previous and dirs != ... |
def reconstitute_path(drive, folders): """Reverts a tuple from `get_path_components` into a path. :param drive: A drive (eg 'c:'). Only applicable for NT systems :param folders: A list of folder names :return: A path comprising the drive and list of folder names. The path terminate with a `os.path.sep` *only* if it is ... |
def create(pattern, casesensitive=True): """Factory for :class:`Matcher` instances; returns a :class:`Matcher` suitable for matching the supplied pattern""" casesensitive = determine_casesensitive(casesensitive) if "?" in pattern or "*" in pattern: return FNMatcher(pattern, casesensitive) else: return ConstantMatcher(p... |
def match(self, string): """Returns True if the pattern matches the string""" if self.casesensitive: return fnmatch.fnmatch(string, self.pattern) else: return fnmatch.fnmatch(string.lower(), self.pattern.lower()) |
def match(self, string): """Returns True if the argument matches the constant.""" if self.casesensitive: return self.pattern == os.path.normcase(string) else: return self.pattern.lower() == os.path.normcase(string).lower() |
def match_iter(self, path_elements, start_at): """A generator that searches over *path_elements* (starting from the index *start_at*), yielding for each match. Each value yielded is the index into *path_elements* to the first element *after* each match. In other words, the returned index has already consumed the matchi... |
def _match_iter_generic(self, path_elements, start_at): """Implementation of match_iter for >1 self.elements""" length = len(path_elements) # If bound to start, we stop searching at the first element if self.bound_start: end = 1 else: end = length - self.length + 1 # If bound to end, we start searching as late as possi... |
end is after the last possible end point in path_elements return for index in range(start, end): matched = True i = index for matcher in self.elements: element = path_elements[i] i += 1 if not matcher.match(element): matched = False break if matched: yield index + self.length |
def _match_iter_single(self, path_elements, start_at): """Implementation of match_iter optimized for self.elements of length 1""" length = len(path_elements) if length == 0: return # If bound to end, we start searching as late as possible if self.bound_end: start = length - 1 if start < start_at: return else: start = s... |
def _simplify(elements): """Simplifies and normalizes the list of elements removing redundant/repeated elements and normalising upper/lower case so case sensitivity is resolved here.""" simplified = [] previous = None for element in elements: if element == "..": raise FormicError("Invalid glob:" " Cannot have '..' in a... |
slash. del simplified[0] else: if simplified[0] != "**": simplified.insert(0, "**") return simplified |
def match_directory(self, path_elements): """Returns a :class:`MatchType` for the directory, expressed as a list of path elements, match for the :class:`Pattern`. If ``self.bound_start`` is True, the first :class:`Section` must match from the first directory element. If ``self.bound_end`` is True, the last :class:`Sect... |
sections: A list of the remaining sections (sections not yet matched) * path_elements: A list of directory names, each element being a single directory * location: index into path_elements for where the search should start """ if sections: section = sections[0] any_match = False for end in section.match_iter(path_eleme... |
start to the pattern, eg "/Users/myuser/**" # ii) We have a path not matching the first, anchored, section, eg "/usr" or "/Users/another" # Need to check whether the last path element matches the corresponding element in section # If it does, return NO_MATCH (it's incomplete) # If, however, the element's don't match, t... |
and allows subdirectories to also match return MatchType.MATCH else: # If the pattern is not bound to the end of the path (eg # NOT "**/term/**") the pattern matches all subdirectories return MatchType.MATCH_ALL_SUBDIRECTORIES # End of: def match_recurse(is_start, sections, path_elements, location): if self.sections: r... |
def match_files(self, matched, unmatched): """Moves all matching files from the set *unmatched* to the set *matched*. Both *matched* and *unmatched* are sets of string, the strings being unqualified file names""" this_match = set(self.file_filter(unmatched)) matched |= this_match unmatched -= this_match |
def _to_string(self): """Implemented a function for __str__ and __repr__ to use, but which prevents infinite recursion when migrating to Python 3""" if self.sections: start = "/" if self.bound_start else "**/" sections = "/**/".join(str(section) for section in self.sections) end = "" if self.bound_end else "/**" else: ... |
def _compute_all_files(self): """Handles lazy evaluation of self.all_files""" self._all_files = any(pat.all_files() for pat in self.patterns) |
def append(self, pattern): """Adds a :class:`Pattern` to the :class:`PatternSet`""" assert isinstance(pattern, Pattern) self.patterns.append(pattern) if self._all_files is not None: self._all_files = self._all_files or pattern.all_files() |
def extend(self, patterns): """Extend a :class:`PatternSet` with addition *patterns* *patterns* can either be: * A single :class:`Pattern` * Another :class:`PatternSet` or * A list of :class:`Pattern` instances""" assert patterns is not None if isinstance(patterns, Pattern): self.append(patterns) return if isinstance(p... |
def remove(self, pattern): """Remove a :class:`Pattern` from the :class:`PatternSet`""" assert isinstance(pattern, Pattern) self.patterns.remove(pattern) self._all_files = None |
def match_files(self, matched, unmatched): """Apply the include and exclude filters to those files in *unmatched*, moving those that are included, but not excluded, into the *matched* set. Both *matched* and *unmatched* are sets of unqualified file names.""" for pattern in self.iter(): pattern.match_files(matched, unma... |
def iter(self): """An iteration generator that allows the loop to modify the :class:`PatternSet` during the loop""" if self.patterns: patterns = list(self.patterns) for pattern in patterns: yield pattern |
def _find_parent(self, path_elements): """Recurse up the tree of FileSetStates until we find a parent, i.e. one whose path_elements member is the start of the path_element argument""" if not self.path_elements: # Automatically terminate on root return self elif self.path_elements == path_elements[0:len(self.path_elemen... |
def _matching_pattern_sets(self): """Returns an iterator containing all PatternSets that match this directory. This is build by chaining the this-directory specific PatternSet (self.matched_and_subdir), the local (non-inheriting) PatternSet (self.matched_no_subdir) with all the inherited PatternSets that match this dir... |
def match(self, files): """Given a set of files in this directory, returns all the files that match the :class:`Pattern` instances which match this directory.""" if not files: return set() if (self.matched_inherit.all_files() or self.matched_and_subdir.all_files() or self.matched_no_subdir.all_files()): # Optimization:... |
def no_possible_matches_in_subdirs(self): """Returns True if there are no possible matches for any subdirectories of this :class:`FileSetState`. When this :class:FileSetState is used for an 'include', a return of `True` means we can exclude all subdirectories.""" return (not self.parent_has_patterns and self.matched_in... |
def _preprocess(argument, casesensitive): """Receives the argument (from the constructor), and normalizes it into a list of Pattern objects.""" pattern_set = PatternSet() if argument is not None: if isinstance(argument, STRING_TYPES): argument = [argument, ] for glob in argument: if isinstance(glob, str): patterns = Pa... |
def get_directory(self): """Returns the directory in which the :class:`FileSet` will be run. If the directory was set with None in the constructor, get_directory() will return the current working directory. The returned result is normalized so it never contains a trailing path separator""" directory = self.directory if... |
def _receive(self, root, directory, dirs, files, include, exclude): """Internal function processing each yield from os.walk.""" self._received += 1 if not self.symlinks: where = root + os.path.sep + directory + os.path.sep files = [ file_name for file_name in files if not os.path.islink(where + file_name) ] include = F... |
def files(self): """A generator function for iterating over the individual files of the FileSet. The generator yields a tuple of ``(rel_dir_name, file_name)``: 1. *rel_dir_name*: The path relative to the starting directory 2. *file_name*: The unqualified file name """ directory = self.get_directory() prefix = len(direc... |
def qualified_files(self, absolute=True): """An alternative generator that yields files rather than directory/file tuples. If *absolute* is false, paths relative to the starting directory are returned, otherwise files are fully qualified.""" prefix = self.get_directory() if absolute else "." for rel_dir_name, file_name... |
def main(argString=None): """The main function of this module. :param argString: the options. :type argString: list of strings """ # Getting and checking the options args = parseArgs(argString) checkArgs(args) logger.info("Options used:") for key, value in vars(args).iteritems(): logger.info(" --{} {}".format(key.repla... |
def order_qc_dir(dirnames): """Order the QC directory names according to their date. :param dirnames: the list of directories to merge data from. :type dirnames: list :returns: the sorted list of directories :rtype: list """ return sorted( dirnames, key=lambda dn: time.strptime( os.path.basename(dn.rstrip("/"))[14:], "... |
def merge_required_files(dirnames, out_dir): """Merges the required files from each of the directories. :param dirnames: the list of directories to merge data from. :param out_dir: the name of the output directory. :type dirnames: list :type out_dir: str """ # The list of files to merge fn_to_merge = ("steps_summary.te... |
# Merging the graphic paths file graphic_paths = set() for dn in dirnames: fn = os.path.join(dn, "graphic_paths.txt") if os.path.isfile(fn): with open(fn, "r") as i_file: graphic_paths.update({ os.path.join(dn, path) for path in i_file.read().splitlines() }) if len(graphic_paths) > 0: with open(os.path.join(out_dir, "g... |
def get_final_numbers(filename, out_dir): """Copy the final_files file and get the number of markers and samples. :param filename: the name of the file. :param out_dir: the output directory. :type filename: str :type out_dir: str :returns: the final number of markers and samples :rtype: tuple """ # Copying the file shu... |
def get_summary_files(dirnames): """Gets the TeX summary files for each test. :param dirnames: the list of directories to merge data from. :type dirnames: list :returns: a list of summary file names. :rtype: list """ # A useful regular expression to get step number in the current directory step_nb_re = re.compile(r"^([... |
file for summary_file in step_summary_files: if len(summary_file) > 1: raise ProgramError("{}: multiple summary files".format( os.path.join(dn, sn), )) if not summary_file: raise ProgramError("{}: missing summary file".format( os.apth.join(dn, sn), )) final_summary_files.extend(i[0] for i in step_summary_files) return ... |
def generate_report(out_dir, latex_summaries, nb_markers, nb_samples, options): """Generates the report. :param out_dir: the output directory. :param latex_summaries: the list of LaTeX summaries. :param nb_markers: the final number of markers. :param nb_samples: the final number of samples. :param options: the list of ... |
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... |
required " "file".format(required_fn)) return True |
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("--report-title", type=str, metavar="TITLE", default="Genetic Data Clean Up", help="The report title. [default: %(default)s]") parser.add_a... |
def main(argString=None): """The main function of this module. :param argString: the options. :type argString: list Here are the steps for this function: 1. Prints the options. 2. Uses Plink to extract markers according to LD (:py:func:`selectSNPsAccordingToLD`). 3. Checks if there is enough markers after pruning (:py:... |
logger.info(" --{} {}".format(key.replace("_", "-"), value)) # Run plink logger.info("Running Plink to extract SNPs according to LD") snpsToExtract = selectSNPsAccordingToLD(args) # Check there is enough SNP in the output file logger.info("Checking if there are enough extracted SNP") if not checkNumberOfSNP(snpsToExtra... |
# Plot the related data logger.info("Plotting related individuals") plot_related_data(related_data["IBS2_RATIO"], related_data["Z1"], related_data["CODE"], r"$Z_1$", args.out + ".related_individuals_z1.png", args) plot_related_data(related_data["IBS2_RATIO"], related_data["Z2"], related_data["CODE"], r"$Z_2$", args.out... |
def plot_related_data(x, y, code, ylabel, fileName, options): """Plot Z1 and Z2 in function of IBS2* ratio. :param x: the x axis of the plot (``IBS2 ratio``). :param y: the y axis of the plot (either ``z1`` or ``z2``). :param code: the code of the relatedness of each sample pair. :param ylabel: the label of the y axis ... |
3 Parent-Child ``#FF8800`` 4 Twins or Duplicated samples ``#9933CC`` ==== =============================================== =========== Sample pairs with unknown relation are plotted using ``#669900`` as color. """ import matplotlib as mpl if mpl.get_backend() != "agg": mpl.use("Agg") import matplotlib.pyplot as plt plt.... |
== "4"], "o", ms=3, mec="#9933CC", mfc="#9933CC") # The legend prop = mpl.font_manager.FontProperties(size=8) leg = ax.legend([c1, c2, c3, c4, c5], ["Full sibs (n={})".format(np.sum(code == "1")), ("Half sibs, grand-parent-child or uncle-nephew " "(n={})".format(np.sum(code == "2"))), "Parent-child (n={})".format(np.su... |
def extractRelatedIndividuals(fileName, outPrefix, ibs2_ratio_threshold): """Extract related individuals according IBS2* ratio. :param fileName: the name of the input file. :param outPrefix: the prefix of the output files. :param ibs2_ratio_threshold: the ibs2 ratio threshold (tells if sample pair is related or not). :... |
of the second sample in the pair. * **IID2:** the individual ID of the second sample in the pair. * **Z0:** the probability that :math:`IBD = 0`. * **Z1:** the probability that :math:`IBD = 1`. * **Z2:** the probability that :math:`IBD = 2`. * **HOMHOM:** the number of :math:`IBS = 0` SNP pairs used in ``PPC`` test. * ... |
\\leq z_0 \\leq 0.33` and | Full-sibs | 1 | | :math:`0.40 \\leq z_1 \\leq 0.60` | | | +---------------------------------------+-----------------------+------+ | :math:`0.40 \\leq z_0 \\leq 0.60` and | Half-sibs or | 2 | | :math:`0.40 \\leq z_1 \\leq 0.60` | Grand-parent-Child or | | | | Uncle-Nephew | | +--------------... |
% locals() raise ProgramError(msg) # The input file inputFile = None try: if fileName.endswith(".gz"): inputFile = gzip.open(fileName, 'rb') else: inputFile = open(fileName, 'r') except IOError: msg = "{}: no such file".format(fileName) raise ProgramError(msg) headerIndex = None data = [] for i, line in enumerate(input... |
invalid HOMHOM or HETHET".format(fileName) raise ProgramError(float) # Computing IBS2* ratio ibs2_ratio = hethet / (homhom + hethet) if ibs2_ratio > ibs2_ratio_threshold: # Those pairs might be related # Finding the status status = "unknown" code = "5" z0 = row[headerIndex["Z0"]] z1 = row[headerIndex["Z1"]] z2 = row[he... |
<= 0.05) and (z1 >= 0.95) and (z2 <= 0.05): # parent child status = "parent-child" code = "3" elif (z0 <= 0.05) and (z1 <= 0.05) and (z2 >= 0.95): # twin status = "twins" code = "4" # Printing to file print >>outputFile, "\t".join(row + [str(ibs2_ratio), status, code]) data.append((ibs2_ratio, z1, z2, code)) # Closing ... |
def checkNumberOfSNP(fileName, minimumNumber): """Check there is enough SNPs in the file (with minimum). :param fileName: the name of the file. :param minimumNumber: the minimum number of markers that needs to be in the file. :type fileName: str :type minimumNumber: int :returns: ``True`` if there is enough markers in ... |
def splitFile(inputFileName, linePerFile, outPrefix): """Split a file. :param inputFileName: the name of the input file. :param linePerFile: the number of line per file (after splitting). :param outPrefix: the prefix of the output files. :type inputFileName: str :type linePerFile: int :type outPrefix: str :returns: the... |
1 tmpFile.close() try: tmpFile = open( outPrefix + "_tmp.list%d" % nbTmpFile, "w", ) except IOError: msg = "tmp.list%d: can't write file" % nbTmpFile raise ProgramError(msg) tmpFile.close() # Check if the number of line is zero (hence the last file is empty) if nbLine == 0: # We delete the last file file_name = outPref... |
def runGenome(bfile, options): """Runs the genome command from plink. :param bfile: the input file prefix. :param options: the options. :type bfile: str :type options: argparse.Namespace :returns: the name of the ``genome`` file. Runs Plink with the ``genome`` option. If the user asks for SGE (``options.sge`` is True),... |
to split the .fam file nbJob = splitFile(bfile + ".fam", options.line_per_file_for_sge, outPrefix) runGenomeSGE(bfile, options.out + ".frequency.frq", nbJob, outPrefix, options) # Merging genome files mergeGenomeLogFiles(outPrefix, nbJob) else: plinkCommand = ["plink", "--noweb", "--bfile", bfile, "--genome", "--genome... |
def mergeGenomeLogFiles(outPrefix, nbSet): """Merge genome and log files together. :param outPrefix: the prefix of the output files. :param nbSet: The number of set of files to merge together. :type outPrefix: str :type nbSet: int :returns: the name of the output file (the ``genome`` file). After merging, the files are... |
open printHeader = True # Read file here try: with open(fileName, 'r') as inputFile: for nbLine, line in enumerate(inputFile): if nbLine == 0: if printHeader: outputFile.write(line) else: outputFile.write(line) except IOError: msg = "%(fileName)s: no such file" % locals() raise ProgramError(msg) # Deleting the file try... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.