code
stringlengths
1
18.2k
def get_content(identifier, default=None): ''' Returns the DynamicContent instance for the given identifier. If no object is found, a new one will be created. :param identifier: String representing the unique identifier of a ``DynamicContent`` object. :param default: String that should be used in case that no matching ...
def rescale_taps(taps): """ Rescale taps in that way that their sum equals 1 """ taps = np.array(taps) cs = sum(taps) # fixme: not sure here, abs seems right as it avoids overflows in core, # then again it reduces the fir gain # cs = sum(abs(taps)) for (i, x) in enumerate(taps): taps[i] = x / cs return taps.tolist()
def to_json(value): """ Converts a value to a jsonable type. """ if type(value) in JSON_TYPES: return value elif hasattr(value, "to_json"): return value.to_json() elif isinstance(value, list) or isinstance(value, set) or \ isinstance(value, deque) or isinstance(value, tuple): return [to_json(v) for v in value] elif isi...
def lock_pid(self): """ Get the pid of the lock. """ if os.path.exists(self.lock_filename): return int(open(self.lock_filename).read()) else: return None
def is_locked_by_me(self): """ See if the lock exists and is belongs to this process. """ ## get pid of lock lock_pid = self.lock_pid() ## not locked if lock_pid is None: logger.debug('Lock {} is not aquired.'.format(self.lock_filename)) return False ## locked by me if self.pid == lock_pid: logger.debug('Lock {} is aqu...
lock_pid: os.remove(self.lock_filename) fcntl.lockf(lock_fd, fcntl.LOCK_UN) logger.debug('The lock is removed by me.') else: logger.debug('The lock is substituted by another lock.') os.close(lock_fd) return False
def acquire_try_once(self): """ Try to aquire the lock once. """ if self.is_locked_by_me(): return True else: try: self.fd = os.open(self.lock_filename, os.O_CREAT | os.O_RDWR | os.O_EXCL) except FileExistsError: logger.debug('I tried to get the lock {}, but another process was faster.'.format(self.lock_filename)) retu...
def acquire(self): """ Try to aquire the lock. """ if self.timeout is not None: sleep_intervals = int(self.timeout / self.sleep_time) else: sleep_intervals = float('inf') while not self.acquire_try_once() and sleep_intervals > 0: time.sleep(self.sleep_time) sleep_intervals -= 1 if not self.is_locked_by_me(): raise util...
def release(self): """ Release the lock. """ if self.is_locked_by_me(): os.remove(self.lock_filename) logger.debug('The lock {} is released by me (pid: {}).'.format(self.lock_filename, self.pid)) if self.fd: os.close(self.fd) self.fd = None
def main(argString=None): """The main function. :param argString: the options. :type argString: list These are the steps of this module: 1. Prints the options. 2. Finds the overlapping markers between the three reference panels and the source panel (:py:func:`findOverlappingSNPsWithReference`). 3. Extract the required ...
that need flipping in their reference panel (:py:func:`flipSNPs`). 10. Combines the reference and the source panels (:py:func:`combinePlinkBinaryFiles`). 11. Runs part of :py:mod:`pyGenClean.RelatedSamples.find_related_samples` on the combined data set (:py:func:`runRelatedness`). 12. Creates the ``mds`` file from the ...
overlap with the reference file logger.info("Finding overlapping SNPs between reference and " "source panels") findOverlappingSNPsWithReference( prefix=args.bfile, referencePrefixes=referencePrefixes, referencePopulations=popNames, outPrefix=args.out, ) # Extract the required SNPs using Plink (reference panels) logger....
panels") combinePlinkBinaryFiles( prefixes=[ args.out + ".reference_panel.{}.rename".format(pop) for pop in popNames ], outPrefix=args.out + ".reference_panel.ALL.rename", ) # Computing the frequency (reference panel) logger.info("Computing reference panel frequencies") computeFrequency( prefix=args.out + ".reference_p...
need to be flip in the reference logger.info("Flipping SNPs in reference panel") flipSNPs( inPrefix=args.out + ".reference_panel.ALL.rename.cleaned", outPrefix=args.out + ".reference_panel.ALL.rename.cleaned.flipped", flipFileName=args.out + ".snp_to_flip_in_reference", ) # Combining the reference panel logger.info("Co...
+ ".source_panel.ALL.fam") labels = popNames + ["SOURCE"] createPopulationFile( inputFiles=famFiles, labels=labels, outputFileName=args.out + ".population_file", ) # Plot the MDS value logger.info("Creating the MDS plot") plotMDS( inputFileName=args.out + ".mds.mds", outPrefix=args.out + ".mds", populationFileName=args...
def create_scree_plot(in_filename, out_filename, plot_title): """Creates a scree plot using smartpca results. :param in_filename: the name of the input file. :param out_filename: the name of the output file. :param plot_title: the title of the scree plot. :type in_filename: str :type out_filename: str :type plot_title:...
def compute_eigenvalues(in_prefix, out_prefix): """Computes the Eigenvalues using smartpca from Eigensoft. :param in_prefix: the prefix of the input files. :param out_prefix: the prefix of the output files. :type in_prefix: str :type out_prefix: str Creates a "parameter file" used by smartpca and runs it. """ # First, ...
def find_the_outliers(mds_file_name, population_file_name, ref_pop_name, multiplier, out_prefix): """Finds the outliers of a given population. :param mds_file_name: the name of the ``mds`` file. :param population_file_name: the name of the population file. :param ref_pop_name: the name of the reference population for w...
{}".format(e) raise ProgramError(msg)
def createPopulationFile(inputFiles, labels, outputFileName): """Creates a population file. :param inputFiles: the list of input files. :param labels: the list of labels (corresponding to the input files). :param outputFileName: the name of the output file. :type inputFiles: list :type labels: list :type outputFileName...
fileName = inputFiles[i] label = labels[i] try: with open(fileName, 'r') as inputFile: for line in inputFile: row = line.rstrip("\r\n").split(" ") # Getting the informations famID = row[0] indID = row[1] # Printing to file print >>outputFile, "\t".join([famID, indID, label]) except IOError: msg = "%(fileName)s: no such...
def plotMDS(inputFileName, outPrefix, populationFileName, options): """Plots the MDS value. :param inputFileName: the name of the ``mds`` file. :param outPrefix: the prefix of the output files. :param populationFileName: the name of the population file. :param options: the options :type inputFileName: str :type outPref...
= [(0.215686275, 0.000494118, 0.721568627), (0.301960784, 0.68627451, 0.290196078), (0.596078431, 0.305882353, 0.639215686), (0.894117647, 0.101960784, 0.109803922), (0.596078431, 0.305882353, 0.639215686)] sizes = [12, 12, 12, 8, 12] markers = [".", ".", ".", "+", "D"] # Plotting the data PlotMDS.plotMDS(data, order, ...
def createMDSFile(nb_components, inPrefix, outPrefix, genomeFileName): """Creates a MDS file using Plink. :param nb_components: the number of component. :param inPrefix: the prefix of the input file. :param outPrefix: the prefix of the output file. :param genomeFileName: the name of the ``genome`` file. :type nb_compon...
def runRelatedness(inputPrefix, outPrefix, options): """Run the relatedness step of the data clean up. :param inputPrefix: the prefix of the input file. :param outPrefix: the prefix of the output file. :param options: the options :type inputPrefix: str :type outPrefix: str :type options: argparse.Namespace :returns: th...
".fam"]]): msg = "{}: not a valid binary prefix".format(inputPrefix) raise ProgramError(msg) newBfile = None try: newBfile = Relatedness.main(new_options) except Relatedness.ProgramError as e: msg = "compute genome: {}".format(e) raise ProgramError(msg) return newBfile
def allFileExists(fileList): """Check that all file exists. :param fileList: the list of file to check. :type fileList: list Check if all the files in ``fileList`` exists. """ allExists = True for fileName in fileList: allExists = allExists and os.path.isfile(fileName) return allExists
def excludeSNPs(inPrefix, outPrefix, exclusionFileName): """Exclude some SNPs using Plink. :param inPrefix: the prefix of the input file. :param outPrefix: the prefix of the output file. :param exclusionFileName: the name of the file containing the markers to be excluded. :type inPrefix: str :type outPrefix: str :type ...
def findFlippedSNPs(frqFile1, frqFile2, outPrefix): """Find flipped SNPs and flip them in the data. :param frqFile1: the name of the first frequency file. :param frqFile2: the name of the second frequency file. :param outPrefix: the prefix of the output files. :type frqFile1: str :type frqFile2: str :type outPrefix: st...
in at least one data set. It will also be removed if it's impossible to determine the phase of the marker (*e.g.* if the two alleles are ``A`` and ``T`` or ``C`` and ``G``). """ allelesFiles = [{}, {}] files = [frqFile1, frqFile2] for k, fileName in enumerate(files): try: with open(fileName, "r") as inputFile: headerIn...
in alleles: alleles.remove("0") allelesFiles[k][snpName] = alleles except IOError: msg = "%(fileName)s: no such file" % locals() raise ProgramError(msg) allelesFile1, allelesFile2 = allelesFiles # Finding the SNPs to flip toFlipOutputFile = None try: toFlipOutputFile = open(outPrefix + ".snp_to_flip_in_reference", "w")...
snpName else: if alleles1 != alleles2: # Let's try the flip one if flipGenotype(alleles1) == alleles2: # We need to flip it print >>toFlipOutputFile, snpName else: # Those SNP are discordant... print >>toRemoveOutputFile, snpName else: # We want to remove this SNP, because there is at least one # homozygous individual ...
def combinePlinkBinaryFiles(prefixes, outPrefix): """Combine Plink binary files. :param prefixes: a list of the prefix of the files that need to be combined. :param outPrefix: the prefix of the output file (the combined file). :type prefixes: list :type outPrefix: str It uses Plink to merge a list of binary files (whic...
outputFile.close() # Runing plink plinkCommand = ["plink", "--noweb", "--bfile", prefixes[0], "--merge-list", outPrefix + ".files_to_merge", "--make-bed", "--out", outPrefix] runCommand(plinkCommand)
def findOverlappingSNPsWithReference(prefix, referencePrefixes, referencePopulations, outPrefix): """Find the overlapping SNPs in 4 different data sets. :param prefix: the prefix of all the files. :param referencePrefixes: the prefix of the reference population files. :param referencePopulations: the name of the refere...
three reference panels. * ``outPrefix.source_snp_to_extract``: the name of the markers that needs to be extracted from the source panel. * ``outPrefix.update_names``: a file (readable by Plink) that will help in changing the names of the selected markers in the reference panels, so that they become comparable with the ...
Reading each of the reference markers refSnpToExtract = defaultdict(dict) refSnp = defaultdict(set) for refPop, refPrefix in izip(referencePopulations, referencePrefixes): try: with open(refPrefix + ".bim", "r") as inputFile: for line in inputFile: row = line.rstrip("\r\n").split("\t") chromosome = row[0] position = ro...
= open( outPrefix + ".{}_snp_to_extract".format(refPop), mode="w", ) except IOError: msg = "{}.POP_snp_to_extract: can't write file".format(outPrefix) raise ProgramError(msg) sourceOutputFile = None try: sourceOutputFile = open(outPrefix + ".source_snp_to_extract", "w") except IOError: msg = "{}.source_snp_to_extract: ...
def extractSNPs(snpToExtractFileNames, referencePrefixes, popNames, outPrefix, runSGE, options): """Extract a list of SNPs using Plink. :param snpToExtractFileNames: the name of the files which contains the markers to extract from the original data set. :param referencePrefixes: a list containing the three reference po...
in os.environ: msg = "could not load drmaa: set DRMAA_LIBRARY_PATH" raise ProgramError(msg) # Import the python drmaa library try: import drmaa except ImportError: raise ProgramError("drmaa is not install, install drmaa") # Initializing a session s = drmaa.Session() s.initialize() zipped = izip(popNames, referencePrefi...
job template and the job ID jobTemplates.append(jt) jobIDs.append(jobID) else: # We run normal runCommand(plinkCommand) if runSGE: # We wait for all the jobs to be over hadProblems = [] for jobID in jobIDs: retVal = s.wait(jobID, drmaa.Session.TIMEOUT_WAIT_FOREVER) hadProblems.append(retVal.exitStatus == 0) # The jobs ...
def runCommand(command): """Run a command. :param command: the command to run. :type command: list Tries to run a command. If it fails, raise a :py:class:`ProgramError`. This function uses the :py:mod:`subprocess` module. .. warning:: The variable ``command`` should be a list of strings (no other type). """ output = No...
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...
msg = "%(fileName)s: no such file" % locals() raise ProgramError(msg) # Check the indep-pairwise option # The two first must be int, the last one float try: for i in xrange(2): tmp = int(args.indep_pairwise[i]) tmp = float(args.indep_pairwise[2]) except ValueError: msg = "indep-pairwise: need INT INT FLOAT" raise Progr...
number of component to compute if args.nb_components < 2 or args.nb_components > 10: msg = ("nb-components: must be between 2 and 10 (inclusive), " "not {}".format(args.nb_components)) raise ProgramError(msg) # Check the minimum number of SNPs if args.min_nb_snp < 1: msg = "min-nb-snp: must be above 1" raise ProgramErr...
def extract_favicon(bs4): """Extracting favicon url from BeautifulSoup object :param bs4: `BeautifulSoup` :return: `list` List of favicon urls """ favicon = [] selectors = [ 'link[rel="icon"]', 'link[rel="Icon"]', 'link[rel="ICON"]', 'link[rel^="shortcut"]', 'link[rel^="Shortcut"]', 'link[rel^="SHORTCUT"]' ] for select...
def extract_metas(bs4): """Extracting meta tags from BeautifulSoup object :param bs4: `BeautifulSoup` :return: `list` List of meta tags """ meta_tags = [] metas = bs4.select('meta') for meta in metas: meta_content = {} meta_attrs = [ 'charset', 'name', 'content', 'property', 'http-equiv', 'itemprop' ] for attr in meta_...
def convert_invalid_url(url): """Convert invalid url with adding extra 'http://' schema into it :param url: :return: """ regex_valid_url = re.compile( r'^(?:http|ftp)s?://' # http:// or https:// r'(?:(?:[A-Z0-9](?:[A-Z0-9-]{0,61}[A-Z0-9])?\.)+(?:[A-Z]{2,6}\.?|[A-Z0-9-]{2,}\.?)|' #domain... r'localhost|' #localhost... r...
def extract_links(bs4): """Extracting links from BeautifulSoup object :param bs4: `BeautifulSoup` :return: `list` List of links """ unique_links = list(set([anchor['href'] for anchor in bs4.select('a[href]') if anchor.has_attr('href')])) # remove irrelevant link unique_links = [link for link in unique_links if link != ...
def extract_original_links(base_url, bs4): """Extracting links that contains specific url from BeautifulSoup object :param base_url: `str` specific url that matched with the links :param bs4: `BeautifulSoup` :return: `list` List of links """ valid_url = convert_invalid_url(base_url) url = urlparse(valid_url) base_url =...
def extract_css_links(bs4): """Extracting css links from BeautifulSoup object :param bs4: `BeautifulSoup` :return: `list` List of links """ links = extract_links(bs4) real_css = [anchor for anchor in links if anchor.endswith(('.css', '.CSS'))] css_link_tags = [anchor['href'] for anchor in bs4.select('link[type="text/cs...
def extract_js_links(bs4): """Extracting js links from BeautifulSoup object :param bs4: `BeautifulSoup` :return: `list` List of links """ links = extract_links(bs4) real_js = [anchor for anchor in links if anchor.endswith(('.js', '.JS'))] js_tags = [anchor['src'] for anchor in bs4.select('script[type="text/javascript"]...
def extract_images(bs4, lazy_image_attribute=None): """If lazy attribute is supplied, find image url on that attribute :param bs4: :param lazy_image_attribute: :return: """ # get images form 'img' tags if lazy_image_attribute: images = [image[lazy_image_attribute] for image in bs4.select('img') if image.has_attr(lazy_i...
def extract_canonical(bs4): """Extracting canonical url :param bs4: :return: """ link_rel = bs4.select('link[rel="canonical"]') if link_rel.__len__() > 0: if link_rel[0].has_attr('href'): return link_rel[0]['href'] return None
def html(self, selector): """Return html result that executed by given css selector :param selector: `str` css selector :return: `list` or `None` """ result = self.__bs4.select(selector) return [str(r) for r in result] \ if result.__len__() > 1 else \ str(result[0]) if result.__len__() > 0 else None
def text(self, selector): """Return text result that executed by given css selector :param selector: `str` css selector :return: `list` or `None` """ result = self.__bs4.select(selector) return [r.get_text() for r in result] \ if result.__len__() > 1 else \ result[0].get_text() if result.__len__() > 0 else None
def conversion_rate(self): """ The percentage of participants that have converted for this variant. Returns a > 0 float representing a percentage rate. """ participants = self.participant_count if participants == 0: return 0.0 return self.experiment.conversions_for(self.name) / float(participants)
def z_score(self): """ Calculate the Z-Score between this alternative and the project control. Statistical formulas based on: http://20bits.com/article/statistical-analysis-and-ab-testing """ control = VariantStat(self.experiment.control, self.experiment) alternative = self if control.name == alternative.name: return '...
def confidence_level(self): """ Based on the variant's Z-Score, returns a human-readable string that describes the confidence with which we can say the results are statistically significant. """ z = self.z_score if isinstance(z, string_types): return z z = abs(round(z, 3)) if z == 0.0: return "No Change" elif z < 1.65:...
def evaluate(self, verbose=False, decode=True, passes=None, num_threads=1, apply_experimental=True): """Evaluates by creating an Index containing evaluated data. See `LazyResult` Returns ------- Index Index with evaluated data. """ evaluated_data = super(Index, self).evaluate(verbose, decode, passes, num_threads, apply...
def tail(self, n=5): """Return Index with the last n values. Parameters ---------- n : int Number of values. Returns ------- Series Index containing the last n values. Examples -------- >>> ind = bl.Index(np.arange(3, dtype=np.float64)) >>> print(ind.tail(2).evaluate()) [1. 2.] """ if self.empty: return self else: if s...
def fillna(self, value): """Returns Index with missing values replaced with value. Parameters ---------- value : {int, float, bytes, bool} Scalar value to replace missing values with. Returns ------- Index With missing values replaced. """ if not is_scalar(value): raise TypeError('Value to replace with is not a valid s...
def from_pandas(cls, index): """Create baloo Index from pandas Index. Parameters ---------- index : pandas.base.Index Returns ------- Index """ from pandas import Index as PandasIndex check_type(index, PandasIndex) return Index(index.values, index.dtype, index.name)
def to_pandas(self): """Convert to pandas Index. Returns ------- pandas.base.Index """ if not self.is_raw(): raise ValueError('Cannot convert to pandas Index if not evaluated.') from pandas import Index as PandasIndex return PandasIndex(self.values, self.dtype, name=self.name)
def get_plink_version(): """Gets the Plink version from the binary. :returns: the version of the Plink software :rtype: str This function uses :py:class:`subprocess.Popen` to gather the version of the Plink binary. Since executing the software to gather the version creates an output file, it is deleted. .. warning:: Th...
raise ProgramError("plink: command not found") # Deleting the output file automatically created by Plink if os.path.isfile(tmp_fn + ".log"): os.remove(tmp_fn + ".log") # Finding the version version = re.search(r"\|\s+PLINK!\s+\|\s+(\S+)\s+\|", output) if version is None: version = "unknown" else: version = version.grou...
def _check_args(logZ, f, x, samples, weights): """ Sanity-check the arguments for :func:`fgivenx.drivers.compute_samples`. Parameters ---------- f, x, samples, weights: see arguments for :func:`fgivenx.drivers.compute_samples` """ # convert to arrays if logZ is None: logZ = [0] f = [f] samples = [samples] weights = [we...
%i" % (len(logZ), len(samples))) samples = [numpy.array(s, dtype='double') for s in samples] for s in samples: if len(s.shape) is not 2: raise ValueError("each set of samples should be a 2D array") # weights if len(logZ) != len(weights): raise ValueError("len(logZ) = %i != len(weights)= %i" % (len(logZ), len(weights)))...
def _normalise_weights(logZ, weights, ntrim=None): """ Correctly normalise the weights for trimming This takes a list of log-evidences, and re-normalises the weights so that the largest weight across all samples is 1, and the total weight in each set of samples is proportional to the evidence. Parameters ---------- log...
not None and ntrim < ntot: weights = [w*ntrim/ntot for w in weights] return logZ, weights
def _equally_weight_samples(samples, weights): """ Convert samples to be equally weighted. Samples are trimmed by discarding samples in accordance with a probability determined by the corresponding weight. This function has assumed you have normalised the weights properly. If in doubt, convert weights via: `weights /= ...
def notification_push(dev_type, to, message=None, **kwargs): """ Send data from your server to your users' devices. """ key = { 'ANDROID': settings.GCM_ANDROID_APIKEY, 'IOS': settings.GCM_IOS_APIKEY } if not key[dev_type]: raise ImproperlyConfigured( "You haven't set the 'GCM_{}_APIKEY' setting yet.".format(dev_type)) ...
def get_device_model(): """ Returns the Device model that is active in this project. """ try: return apps.get_model(settings.GCM_DEVICE_MODEL) except ValueError: raise ImproperlyConfigured("GCM_DEVICE_MODEL must be of the form 'app_label.model_name'") except LookupError: raise ImproperlyConfigured( "GCM_DEVICE_MODEL re...
def from_json(self, json: Map) -> Maybe[Project]: ''' Try to instantiate a Project from the given json object. Convert the **type** key to **tpe** and its value to Maybe. Make sure **root** is a directory, fall back to resolution by **tpe/name**. Reinsert the root dir into the json dict, filter out all keys that aren't...
def to_template(template_name=None): """ Decorator for simple call TemplateResponse Examples: @to_template("test.html") def test(request): return {'test': 100} @to_template def test2(request): return {'test': 100, 'TEMPLATE': 'test.html'} @to_template def test2(request, template_name='test.html'): return {'test': 100, ...
def receiver(signal, **kwargs): """ Introduced in Django 1.3 (django.dispatch.receiver) A decorator for connecting receivers to signals. Used by passing in the signal and keyword arguments to connect:: @receiver(post_save, sender=MyModel) def signal_receiver(sender, **kwargs): do_stuff() """ def _decorator(func): signa...
def main(): """The main function. These are the steps performed for the data clean up: 1. Prints the version number. 2. Reads the configuration file (:py:func:`read_config_file`). 3. Creates a new directory with ``data_clean_up`` as prefix and the date and time as suffix. 4. Check the input file type (``bfile``, ``tfil...
datetime.datetime.today().strftime("%Y-%m-%d_%H.%M.%S") while os.path.isdir(dirname): time.sleep(1) dirname = "data_clean_up." dirname += datetime.datetime.today().strftime("%Y-%m-%d_%H.%M.%S") # Creating the output directory os.mkdir(dirname) # Configuring the root logger add_file_handler_to_root(os.path.join(dirname,...
"w") as o_file: for s in suffixes: print >>o_file, current_in + s except IOError: msg = "{}: cannot write summary".format(dirname) raise ProgramError(msg) # Counting the number of markers and samples in the datafile logger.info("Counting initial number of samples and markers") nb_markers, nb_samples = count_markers_sam...
script_name, options = conf[number] # Getting the output prefix output_prefix = os.path.join(dirname, "{}_{}".format(number, script_name)) # Getting the function to use function_to_use = available_functions[script_name] # Executing the function logger.info("Running {} {}".format(number, script_name)) logger.info(" - Us...
final suffixes suffixes = None if current_in_type == "tfile": suffixes = ((".tped", nb_markers), (".tfam", nb_samples)) elif current_in_type == "bfile": suffixes = ((".bed", None), (".bim", nb_markers), (".fam", nb_samples)) else: suffixes = ((".ped", nb_samples), (".map", nb_markers)) with open(os.path.join(dirname, "...
"initial_files.txt"), final_files=os.path.join(dirname, "final_files.txt"), final_nb_markers="{:,d}".format(nb_markers), final_nb_samples="{:,d}".format(nb_samples), plink_version=plink_version, )
def run_duplicated_samples(in_prefix, in_type, out_prefix, base_dir, options): """Runs step1 (duplicated samples). :param in_prefix: the prefix of the input files. :param in_type: the type of the input files. :param out_prefix: the output prefix. :param base_dir: the output directory. :param options: the options needed...
# We know we need tfile required_type = "tfile" check_input_files(in_prefix, in_type, required_type) # We need to inject the name of the input file and the name of the output # prefix script_prefix = os.path.join(out_prefix, "dup_samples") options += ["--{}".format(required_type), in_prefix, "--out", script_prefix] # W...
not good enough samples not_good_enough = set() if os.path.isfile(script_prefix + ".not_good_enough"): with open(script_prefix + ".not_good_enough", "r") as i_file: not_good_enough = { tuple(line.rstrip("\r\n").split("\t")[:4]) for line in i_file.read().splitlines()[1:] } # Checking which samples were chosen chosen_sam...
> 0: text = ( "While merging duplicates, a total of {:,d} genotype{} {} " "zeroed out. A total of {:,d} sample{} {} found to be not " "good enough for duplicate completion.".format( nb_zeroed_out, "s" if nb_zeroed_out > 1 else "", "were" if nb_zeroed_out > 1 else "was", len(not_good_enough), "s" if len(not_good_enough)...
"the best duplicate (see Table~{}).".format( "were" if len(not_good_still) > 1 else "was", len(not_good_still), "s" if len(not_good_still) > 1 else "", "were" if len(not_good_still) > 1 else "was", "were" if len(not_good_still) > 1 else "was", r"~\ref{" + table_label + "}", ) ) print >>o_file, latex_template.wrap_lines...
"dataset).".format( len(not_good_still), "s" if len(not_good_still) > 1 else "", "were" if len(not_good_still) > 1 else "was", "were" if len(not_good_still) > 1 else "was", "are" if len(not_good_still) > 1 else "is", ) ) duplicated_samples_list = duplicated_count.most_common() print >>o_file, longtable_template.render(...
rep_count in counter: print >>o_file, " - x{}\t{:,d}\t\t-{:,d}".format( rep_type, rep_count, (rep_count * rep_type) - rep_count, ) print >>o_file, ("Poorly chosen replicated " "samples\t{:,d}".format(len(not_good_still))) print >>o_file, "---" # We know this step does produce a new data set (tfile), so we return it ret...
def run_duplicated_snps(in_prefix, in_type, out_prefix, base_dir, options): """Runs step2 (duplicated snps). :param in_prefix: the prefix of the input files. :param in_type: the type of the input files. :param out_prefix: the output prefix. :param base_dir: the output directory. :param options: the options needed. :typ...
file, needed for the :py:mod:`pyGenClean.DupSNPs.duplicated_snps` module. """ # Creating the output directory os.mkdir(out_prefix) # We know we need a tfile required_type = "tfile" check_input_files(in_prefix, in_type, required_type) # This step require a map file (we now have a tfile) if not os.path.isfile(in_prefix +...
the script try: duplicated_snps.main(options) except duplicated_snps.ProgramError as e: msg = "duplicated_snps: {}".format(e) raise ProgramError(msg) # Reading the number of duplicated markers duplicated_count = defaultdict(int) if os.path.isfile(script_prefix + ".duplicated_snps.tped"): with open(script_prefix + ".dup...
os.path.isfile(script_prefix + ".chosen_snps.info"): with open(script_prefix + ".chosen_snps.info", "r") as i_file: chosen_markers = set(i_file.read().splitlines()) # Finding if some 'not_good_enough' samples were chosen not_good_still = chosen_markers & not_good_enough # Adding the 'not chosen markers' to the list of ...
>>o_file, " - x{}\t{:,d}\t-{:,d}".format( rep_type, rep_count, nb_removed_rep, ) total_nb_removed_rep += nb_removed_rep total_remaining = total_nb_removed_rep - len(removed_markers) print >>o_file, ( "Number of replicated markers kept\t{nb:,d}\t+{nb:,d}".format( nb=total_remaining, ) ) print >>o_file, ("Poorly chosen r...
"good enough for duplicate completion.".format( nb_zeroed_out, "s" if nb_zeroed_out > 1 else "", "were" if nb_zeroed_out > 1 else "was", len(not_good_enough), "s" if len(not_good_enough) > 1 else "", "were" if len(not_good_enough) > 1 else "was", ) ) print >>o_file, latex_template.wrap_lines(text) text = ( "A total of ...
total_remaining > 1 else "is", ) ) print >>o_file, latex_template.wrap_lines(text) if len(not_good_still) > 0: start = "A total of" end = " and {} still present in the final dataset.".format( "are" if len(not_good_still) > 1 else "is", ) if total_remaining > 0: start = "Out of these," end = "." text = latex_template.te...
it return _StepResult( next_file=os.path.join(out_prefix, "dup_snps.final"), next_file_type="tfile", latex_summary=latex_file, description=duplicated_snps.desc, long_description=duplicated_snps.long_desc, graph_path=None, )
def run_noCall_hetero_snps(in_prefix, in_type, out_prefix, base_dir, options): """Runs step 3 (clean no call and hetero). :param in_prefix: the prefix of the input files. :param in_type: the type of the input files. :param out_prefix: the output prefix. :param base_dir: the output directory. :param options: the options...
the output directory os.mkdir(out_prefix) # We know we need a tfile required_type = "tfile" check_input_files(in_prefix, in_type, required_type) # We need to inject the name of the input file and the name of the output # prefix script_prefix = os.path.join(out_prefix, "clean_noCall_hetero") options += ["--{}".format(re...
os.path.isfile(i_filename): with open(i_filename, "r") as i_file: for line in i_file: nb_all_failed += 1 print >>o_file, line.rstrip("\r\n") + "\tall failed" # The second file i_filename = os.path.join(script_prefix + ".allHetero") if os.path.isfile(i_filename): with open(i_filename, "r") as i_file: for line in i_file:...