code stringlengths 1 18.2k |
|---|
def params(self): """A generator that iterates through all parameters requested the correct number of times each. Returns them as a dict with form {'param_name': param_value, ... } for use as f(**params).""" comb_sizes = [] comb_keys = [] for key,val in self.comb_params.items(): comb_keys.append(key) comb_sizes.append(... |
have one parameter set, check how many times to repeat it num_repeats = self.default_repeats for func in self.count_funcs: c = func(params) if c: num_repeats = c for i in range(num_repeats): yield params |
def add_params(self, p): """Add new variables or change values to be used for particular parameter names that will not be jointly varied.""" new_params = p.copy() for key,val in new_params.items(): if not isinstance(val, collections.Iterable): new_params[key] = [new_params[key]] #_check_comb_param(key, val) self.comb_p... |
def GetRGB(self, scheme='infrared', names=None): """Get an RGB color scheme based on predefined presets or specify your own band names to use. A given set of names always overrides a scheme. Note: Available schemes are defined in ``RGB_SCHEMES`` and include: - ``true`` - ``infrared`` - ``false_a`` - ``false_b`` - ``fal... |
then there are np.nans present r = ((r - np.nanmin(r)) * (1/(np.nanmax(r) - np.nanmin(r)) * 255)).astype('uint8') g = ((g - np.nanmin(g)) * (1/(np.nanmax(g) - np.nanmin(g)) * 255)).astype('uint8') b = ((b - np.nanmin(b)) * (1/(np.nanmax(b) - np.nanmin(b)) * 255)).astype('uint8') return np.dstack([r, g, b]) |
def login(self): """ Gets and stores an OAUTH token from Rightscale. """ log.debug('Logging into RightScale...') login_data = { 'grant_type': 'refresh_token', 'refresh_token': self.refresh_token, } response = self._request('post', self.oauth_path, data=login_data) raw_token = response.json() auth_token = "Bearer %s" % ... |
def request(self, method, path='/', url=None, ignore_codes=[], **kwargs): """ Wrapper for the ._request method that verifies if we're logged into RightScale before making a call, and sanity checks the oauth expiration time. :param str method: An HTTP method (e.g. 'get', 'post', 'PUT', etc...) :param str path: A path co... |
in :attr:`ignore_codes`, then an exception is raised. :type ignore_codes: list of int :param kwargs: Any other kwargs to pass to :meth:`requests.request()`. Returns a :class:`requests.Response` object. """ # On every call, check if we're both logged in, and if the token is # expiring. If it is, we'll re-login with the ... |
def _request(self, method, path='/', url=None, ignore_codes=[], **kwargs): """ Performs HTTP request. :param str method: An HTTP method (e.g. 'get', 'post', 'PUT', etc...) :param str path: A path component of the target URL. This will be appended to the value of ``self.endpoint``. If both :attr:`path` and :attr:`url` a... |
:meth:`requests.request()`. Returns a :class:`requests.Response` object. """ _url = url if url else (self.endpoint + path) r = self.s.request(method, _url, **kwargs) if not r.ok and r.status_code not in ignore_codes: r.raise_for_status() return HTTPResponse(r) |
def validate(epub_path): """Minimal validation. :return bool: True if valid else False """ try: subprocess.check_call([c.JAVA, '-jar', c.EPUBCHECK, epub_path]) return True except subprocess.CalledProcessError: return False |
def rename_next_state_fluent(name: str) -> str: '''Returns next state fluent canonical name. Args: name (str): The current state fluent name. Returns: str: The next state fluent name. ''' i = name.index('/') functor = name[:i-1] arity = name[i+1:] return "{}/{}".format(functor, arity) |
def rename_state_fluent(name: str) -> str: '''Returns current state fluent canonical name. Args: name (str): The next state fluent name. Returns: str: The current state fluent name. ''' i = name.index('/') functor = name[:i] arity = name[i+1:] return "{}'/{}".format(functor, arity) |
def main(argString=None): """The main function of the module. :param argString: the options. :type argString: list """ # Getting and checking the options args = parseArgs(argString) checkArgs(args) merge_related_samples(args.ibs_related, args.out, args.no_status) |
def merge_related_samples(file_name, out_prefix, no_status): """Merge related samples. :param file_name: the name of the input file. :param out_prefix: the prefix of the output files. :param no_status: is there a status column in the file? :type file_name: str :type out_prefix: str :type no_status: boolean In the outpu... |
not in header_index: msg = "{}: no column named status".format(file_name) raise ProgramError(msg) for line in input_file: row = line.rstrip("\r\n").split("\t") sample_1 = (row[header_index["FID1"]], row[header_index["IID1"]]) sample_2 = (row[header_index["FID2"]], row[header_index["IID2"]]) tmp_set = {sample_1, sample_... |
j += 1 continue if len(group & samples_sets[j]) > 0: # We have a match, we start from the beginning group |= samples_sets[j] removed.add(j) j = i + 1 continue j += 1 final_samples_set.append(group) # Printing the output file output_file = None try: output_file = open(out_prefix + ".merged_related_individuals", 'w') to_... |
the group chosen = random.choice(list(group)) chosen_samples.add(chosen) remaining_samples |= group - {chosen} # Printing the files try: filename = out_prefix + ".chosen_related_individuals" with open(filename, "w") as chosen_file: for sample_id in chosen_samples: print >>chosen_file, "\t".join(sample_id) filename = ou... |
def checkArgs(args): """Checks the arguments and options. :param args: a 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... |
def admin_url(model, url, object_id=None): """ Returns the URL for the given model and admin url name. """ opts = model._meta url = "admin:%s_%s_%s" % (opts.app_label, opts.object_name.lower(), url) args = () if object_id is not None: args = (object_id,) return reverse(url, args=args) |
def handle_save(self, request, response): """ Handles redirect back to the dashboard when save is clicked (eg not save and continue editing), by checking for a redirect response, which only occurs if the form is valid. """ form_valid = isinstance(response, HttpResponseRedirect) if request.POST.get("_save") and form_val... |
def add_view(self, *args, **kwargs): """ Redirect to the change view if the singleton instance exists. """ try: singleton = self.model.objects.get() except (self.model.DoesNotExist, self.model.MultipleObjectsReturned): kwargs.setdefault("extra_context", {}) kwargs["extra_context"]["singleton"] = True response = super(S... |
def changelist_view(self, *args, **kwargs): """ Redirect to the add view if no records exist or the change view if the singleton instance exists. """ try: singleton = self.model.objects.get() except self.model.MultipleObjectsReturned: return super(SingletonAdmin, self).changelist_view(*args, **kwargs) except self.model... |
def change_view(self, *args, **kwargs): """ If only the singleton instance exists, pass ``True`` for ``singleton`` into the template which will use CSS to hide the "save and add another" button. """ kwargs.setdefault("extra_context", {}) kwargs["extra_context"]["singleton"] = self.model.objects.count() == 1 response = ... |
def pub(topic_name, json_msg, repeat_rate=None, host=jps.env.get_master_host(), pub_port=jps.DEFAULT_PUB_PORT): '''publishes the data to the topic :param topic_name: name of the topic :param json_msg: data to be published :param repeat_rate: if None, publishes once. if not None, it is used as [Hz]. ''' pub = jps.Publis... |
def echo(topic_name, num_print=None, out=sys.stdout, host=jps.env.get_master_host(), sub_port=jps.DEFAULT_SUB_PORT): '''print the data for the given topic forever ''' class PrintWithCount(object): def __init__(self, out): self._printed = 0 self._out = out def print_and_increment(self, msg): self._out.write('{}\n'.forma... |
def show_list(timeout_in_sec, out=sys.stdout, host=jps.env.get_master_host(), sub_port=jps.DEFAULT_SUB_PORT): '''get the name list of the topics, and print it ''' class TopicNameStore(object): def __init__(self): self._topic_names = set() def callback(self, msg, topic): self._topic_names.add(topic) def get_topic_names(... |
def record(file_path, topic_names=[], host=jps.env.get_master_host(), sub_port=jps.DEFAULT_SUB_PORT): '''record the topic data to the file ''' class TopicRecorder(object): def __init__(self, file_path, topic_names): self._topic_names = topic_names self._file_path = file_path self._output = open(self._file_path, 'w') si... |
def play(file_path, host=jps.env.get_master_host(), pub_port=jps.DEFAULT_PUB_PORT): '''replay the recorded data by record() ''' pub = jps.Publisher('*', host=host, pub_port=pub_port) time.sleep(0.2) last_time = None print('start publishing file {}'.format(file_path)) with open(file_path, 'r') as f: # super hack to remo... |
def topic_command(): '''command line tool for jps ''' parser = argparse.ArgumentParser(description='json pub/sub tool') pub_common_parser = jps.ArgumentParser(subscriber=False, add_help=False) sub_common_parser = jps.ArgumentParser(publisher=False, add_help=False) command_parsers = parser.add_subparsers(dest='command',... |
parents=[pub_common_parser]) play_parser.add_argument('file', type=str, help='input file name') args = parser.parse_args() if args.command == 'pub': pub(args.topic_name, args.data, repeat_rate=args.repeat, host=args.host, pub_port=args.publisher_port) elif args.command == 'echo': echo(args.topic_name, args.num, host=ar... |
def str_to_class(class_name): """ Returns a class based on class name """ mod_str, cls_str = class_name.rsplit('.', 1) mod = __import__(mod_str, globals(), locals(), ['']) cls = getattr(mod, cls_str) return cls |
def get_hierarchy_uploader(root): """ Returns uploader, that uses get_hierarch_path to store files """ # Workaround to avoid Django 1.7 makemigrations wierd behaviour: # More details: https://code.djangoproject.com/ticket/22436 import sys if len(sys.argv) > 1 and sys.argv[1] in ('makemigrations', 'migrate'): # Hide our... |
def load_config_from_setup(app): """ Replace values in app.config from package metadata """ # for now, assume project root is one level up root = os.path.join(app.confdir, '..') setup_script = os.path.join(root, 'setup.py') fields = ['--name', '--version', '--url', '--author'] dist_info_cmd = [sys.executable, setup_scr... |
def build_url_field(self, field_name, model_class): """ Create a field representing the object's own URL. """ field_class = self.serializer_url_field field_kwargs = rest_framework.serializers.get_url_kwargs(model_class) field_kwargs.update({"parent_lookup_field": self.get_parent_lookup_field()}) return field_class, fie... |
def get_parent_lookup_field(self): """ Return tha parent_lookup_field for the NestedHyperlinkedModelSerializer. If `parent_lookup_field` of `parent_model` is not defined lookup ForeignKey field of model. :return: parent_lookup_field """ if hasattr(self.Meta, "parent_lookup_field"): return getattr(self.Meta, "parent_loo... |
def get_object(self, view_name, view_args, view_kwargs): """ Return the object corresponding to a matched URL. Takes the matched URL conf arguments, and should return an object instance, or raise an `ObjectDoesNotExist` exception. """ lookup_value = view_kwargs.get(self.lookup_url_kwarg) parent_lookup_value = view_kwar... |
def get_url(self, obj, view_name, request, format): """ Given an object, return the URL that hyperlinks to the object. May raise a `NoReverseMatch` if the `view_name` and `lookup_field` attributes are not configured to correctly match the URL conf. """ # Unsaved objects will not yet have a valid URL. if obj.pk is None:... |
def create_table(self, drop=False, with_test_data=False): """ Creates the honeypot_log table """ db = self.get_sql_hook(self.sql_conn_id) table = self.table_name if drop: sql = "DROP TABLE IF EXISTS {table};".format(**locals()) logging.info("Executing SQL: \n" + sql) db.run(sql) sql = """CREATE TABLE IF NOT EXISTS hone... |
def list_to_tree(cls, files): """Converts a list of filenames into a directory tree structure.""" def attach(branch, trunk): """Insert a branch of directories on its trunk.""" parts = branch.split('/', 1) if len(parts) == 1: # branch is a file trunk[FILE_MARKER].append(parts[0]) else: node, others = parts if node not i... |
def tree_walk(cls, directory, tree): """Walks a tree returned by `cls.list_to_tree` returning a list of 3-tuples as if from os.walk().""" results = [] dirs = [d for d in tree if d != FILE_MARKER] files = tree[FILE_MARKER] results.append((directory, dirs, files)) for d in dirs: subdir = os.path.join(directory, d) subtre... |
def walk_from_list(cls, files): """A function that mimics :func:`os.walk()` by simulating a directory with the list of files passed as an argument. :param files: A list of file paths :return: A function that mimics :func:`os.walk()` walking a directory containing only the files listed in the argument """ tree = cls.lis... |
def create_token_for_user(user: get_user_model()) -> bytes: """ Create a new random auth token for user. """ token = urandom(48) AuthToken.objects.create( hashed_token=AuthToken._hash_token(token), user=user) return token |
def str(self): """Get Access to string functions. Returns ------- StringMethods Examples -------- >>> sr = bl.Series([b' aB ', b'GoOsfrABA']) >>> print(sr.str.lower().evaluate()) <BLANKLINE> --- --------- 0 ab 1 goosfraba """ if self.dtype.char != 'S': raise AttributeError('Can only use .str when data is of type np.byt... |
def evaluate(self, verbose=False, decode=True, passes=None, num_threads=1, apply_experimental=True): """Evaluates by creating a Series containing evaluated data and index. See `LazyResult` Returns ------- Series Series with evaluated data and index. Examples -------- >>> sr = bl.Series(np.arange(3)) > 0 >>> weld_code =... |
def tail(self, n=5): """Return Series with the last n values. Parameters ---------- n : int Number of values. Returns ------- Series Series containing the last n values. Examples -------- >>> sr = bl.Series(np.arange(3)) >>> print(sr.tail(2).evaluate()) <BLANKLINE> --- -- 1 1 2 2 """ if self._length is not None: length... |
def agg(self, aggregations): """Multiple aggregations optimized. Parameters ---------- aggregations : list of str Which aggregations to perform. Returns ------- Series Series with resulting aggregations. """ check_type(aggregations, list) new_index = Index(np.array(aggregations, dtype=np.bytes_), np.dtype(np.bytes_)) r... |
def unique(self): """Return unique values in the Series. Note that because it is hash-based, the result will NOT be in the same order (unlike pandas). Returns ------- LazyArrayResult Unique values in random order. """ return LazyArrayResult(weld_unique(self.values, self.weld_type), self.weld_type) |
def fillna(self, value): """Returns Series with missing values replaced with value. Parameters ---------- value : {int, float, bytes, bool} Scalar value to replace missing values with. Returns ------- Series With missing values replaced. """ if not is_scalar(value): raise TypeError('Value to replace with is not a valid... |
def apply(self, func, mapping=None, new_dtype=None, **kwargs): """Apply an element-wise UDF to the Series. There are currently 6 options for using a UDF. First 4 are lazy, other 2 are eager and require the use of the raw decorator: - One of the predefined functions in baloo.functions. - Implementing a function which en... |
raw decorator to check this. Parameters ---------- func : function or str Weld code as a str to encode or function from baloo.functions. mapping : dict, optional Additional mappings in the weld_template to replace on execution. self is added by default to reference to this Series. new_dtype : numpy.dtype, optional Spec... |
4 1 5 2 6 >>> print(bl.Series([1., 4., 100.]).apply(bl.sqrt).evaluate()) # lazy predefined function <BLANKLINE> --- -- 0 1 1 2 2 10 >>> sr = bl.Series([4, 2, 3, 1]) >>> print(sr.apply(bl.sort, kind='q').evaluate()) # eager wrapper over np.sort (which uses raw decorator) <BLANKLINE> --- -- 0 1 1 2 2 3 3 4 >>> print(sr.a... |
default_mapping else: mapping.update(default_mapping) if new_dtype is None: new_dtype = self.dtype return Series(weld_udf(func, mapping), self.index, new_dtype, self.name) else: raise TypeError('Expected function or str defining a weld_template') |
def from_pandas(cls, series): """Create baloo Series from pandas Series. Parameters ---------- series : pandas.series.Series Returns ------- Series """ from pandas import Index as PandasIndex, MultiIndex as PandasMultiIndex if isinstance(series.index, PandasIndex): baloo_index = Index.from_pandas(series.index) elif isi... |
def diagnostics(self, **kwds): """ Endpoint: /system/diagnostics.json Runs a set of diagnostic tests on the server. Returns a dictionary containing the results. """ # Don't process the result automatically, since this raises an exception # on failure, which doesn't provide the cause of the failure self._client.get("/sy... |
def read_source_manifest(file_name): """Reads Illumina manifest.""" alleles = {} open_function = open if file_name.endswith(".gz"): open_function = gzip.open with open_function(file_name, 'rb') as input_file: header_index = dict([ (col_name, i) for i, col_name in enumerate(input_file.readline().rstrip("\r\n").split("\t... |
def read_source_alleles(file_name): """Reads an allele file.""" alleles = {} open_function = open if file_name.endswith(".gz"): open_function = gzip.open with open_function(file_name, 'rb') as input_file: for line in input_file: row = line.rstrip("\r\n").split("\t") marker_name = row[0] allele1, allele2 = row[1].split(... |
def compute_statistics(out_dir, gold_prefix, source_prefix, same_samples, use_sge, final_out_prefix): """Compute the statistics.""" # Now, creating a temporary directory if not os.path.isdir(out_dir): try: os.mkdir(out_dir) except OSError: msg = "{}: file exists".format(out_dir) raise ProgramError(msg) # The out prefix... |
+ [out_prefix + "_{}_source".format(i) for i in range(nb)], use_sge, transpose=True, ) # Creating reports # The diff file diff_file = None try: diff_file = open(final_out_prefix + ".diff", 'w') except IOError: msg = "{}: can't write file".format(final_out_prefix + ".diff") raise ProgramError(msg) # The diff file header... |
input_file: row = line.rstrip("\r\n").split("\t") marker_name = row[1] geno = row[4] if geno != "0 0": geno = set(geno.split(" ")) source_genotypes[marker_name] = geno except IOError: msg = "{}: no such file".format(filename) raise ProgramError(msg) # Reading the gold freq file gold_genotypes = {} filename = out_prefix... |
= source_genotypes[marker_name] gold_geno = gold_genotypes[marker_name] # Comparing the genotypes if source_geno != gold_geno: nb_diff += 1 source_geno_print = list(source_geno - {"0"}) source_geno_print.sort() if len(source_geno_print) == 1: source_geno_print.append(source_geno_print[0]) gold_geno_print = list(gold_ge... |
def check_fam_for_samples(required_samples, source, gold): """Check fam files for required_samples.""" # Checking the source panel source_samples = set() with open(source, 'r') as input_file: for line in input_file: sample = tuple(line.rstrip("\r\n").split(" ")[:2]) if sample in required_samples: source_samples.add(sam... |
def read_same_samples_file(filename, out_prefix): """Reads a file containing same samples.""" # The same samples same_samples = [] # Creating the extraction files gold_file = None try: gold_file = open(out_prefix + ".gold_samples2keep", 'w') except IOError: msg = "{}: can't create file".format(out_prefix + ".gold_sampl... |
def flipSNPs(inPrefix, outPrefix, flipFileName): """Flip SNPs using Plink.""" plinkCommand = ["plink", "--noweb", "--bfile", inPrefix, "--flip", flipFileName, "--make-bed", "--out", outPrefix] runCommand(plinkCommand) |
def exclude_SNPs_samples(inPrefix, outPrefix, exclusionSNP=None, keepSample=None, transpose=False): """Exclude some SNPs and keep some samples using Plink.""" if (exclusionSNP is None) and (keepSample is None): msg = "Something wront with development... work on that source code..." raise ProgramError(msg) plinkCommand ... |
def renameSNPs(inPrefix, updateFileName, outPrefix): """Updates the name of the SNPs using Plink.""" plinkCommand = ["plink", "--noweb", "--bfile", inPrefix, "--update-map", updateFileName, "--update-name", "--make-bed", "--out", outPrefix] runCommand(plinkCommand) |
def findFlippedSNPs(goldFrqFile1, sourceAlleles, outPrefix): """Find flipped SNPs and flip them in the data1.""" goldAlleles = {} with open(goldFrqFile1, "r") as inputFile: headerIndex = None for i, line in enumerate(inputFile): row = createRowFromPlinkSpacedOutput(line) if i == 0: # This is the header headerIndex = di... |
locals() raise ProgramError(msg) toRemoveOutputFile = None try: toRemoveOutputFile = open(outPrefix + ".snp_to_remove", "w") except IOError: msg = "%(outPrefix)s.snp_to_remove: can't write file" % locals() raise ProgramError(msg) toRemoveOutputFileExplanation = None try: toRemoveOutputFileExplanation = open( outPrefix ... |
flip one if flipGenotype(alleles1) == alleles2: # We need to flip it print >>toFlipOutputFile, snpName else: # Those SNP are discordant... print >>toRemoveOutputFile, snpName print >>toRemoveOutputFileExplanation, "\t".join([ snpName, "Invalid", "".join(alleles1), "".join(alleles2), ]) else: # We want to remove this SN... |
def findOverlappingSNPsWithGoldStandard(prefix, gold_prefixe, out_prefix, use_marker_names=False): """Find the overlapping SNPs in 4 different data sets.""" # Reading the main file sourceSnpToExtract = {} if use_marker_names: sourceSnpToExtract = set() duplicates = set() try: with open(prefix + ".bim", "r") as inputFil... |
= {} if use_marker_names: goldSnpToExtract = set() with open(gold_prefixe + ".bim", "r") as inputFile: for line in inputFile: row = line.rstrip("\r\n").split("\t") chromosome = row[0] position = row[3] snpName = row[1] if use_marker_names: if snpName in sourceSnpToExtract: goldSnpToExtract.add(snpName) else: if (chromo... |
Writing the file if use_marker_names: for snpName in goldSnpToExtract: print >>sourceOutputFile, snpName print >>goldOutputFile, snpName else: for snpID in goldSnpToExtract.iterkeys(): print >>sourceOutputFile, sourceSnpToExtract[snpID] print >>goldOutputFile, goldSnpToExtract[snpID] print >>changeNameOutputFile, "\t".... |
def extractSNPs(prefixes, snpToExtractFileNames, outPrefixes, runSGE): """Extract a list of SNPs using Plink.""" s = None jobIDs = [] jobTemplates = [] if runSGE: # Add the environment variable for DRMAA package if "DRMAA_LIBRARY_PATH" not in os.environ: t = "/shares/data/sge/lib/lx24-amd64/libdrmaa.so.1.0" os.environ[... |
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 should be finished, s... |
def checkArgs(args): """Checks the arguments and options. :param args: a :py:class:`Namespace` object containing the options of the program. :type args: :py:class:`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`... |
a manifest or a allele file if (args.source_manifest is None) and (args.source_alleles is None): msg = ("need an allele file (either an Illumina manifest " "[--source-manifest] or a file containing alleles for each " "marker [--source-alleles]") raise ProgramError(msg) if ((args.source_manifest is not None) and (args.s... |
def _read_binary(self): """Reads data and metadata from binary format.""" # NOTE: binary files store binned data using Fortran-like ordering. # Dimensions are iterated like z, y, x (so x changes fastest) header_path = self.path + 'header' with open(header_path) as f_header: self._read_header(f_header.read()) data = np.... |
def _read_ascii(self): """Reads data and metadata from ASCII format.""" # NOTE: ascii files store binned data using C-like ordering. # Dimensions are iterated like x, y, z (so z changes fastest) header_str = '' with open(self.path) as f: for line in f: if line.startswith('#'): header_str += line self._read_header(heade... |
def _read_header(self, header_str): """Reads metadata from the header.""" # regular expressions re_float = '[-+]?(\d+(\.\d*)?|\.\d+)([eE][-+]?\d+)?' re_uint = '\d+' re_binning = '{d} in (?P<nbins>' + re_uint + ') bin[ s] ' re_binning += 'of (?P<binwidth>' + re_float + ') {unit}' # map of dimensions and units dim_units ... |
line in header_str.splitlines(): match = regex_unit.search(line) if match: self.quantity = match.group('quant') self.unit = match.group('unit') self.statistics = match.group('stats').split() break match = regex_unitless.search(line) if match: self.quantity = match.group('quant') self.unit = None self.statistics = match... |
def main(argString=None): """The main function of the module. :param argString: the options. :type argString: list These are the following steps: 1. Prints the options. 2. Checks if there are enough markers on the chromosome ``23`` (:py:func:`checkBim`). If not, quits here. 3. Runs the sex check analysis using Plink (:... |
(:py:func:`createLrrBafPlot`). """ # 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.replace("_", "-"), value)) # Reads the bim file to see if chromosome 23 is there hasSexProblems = Non... |
percentage") computeHeteroPercentage(args.out + ".chr23_recodeA.raw") # Run plink to get chr 24 if checkBim("{}.bim".format(args.bfile), 1, "24"): logger.info("Creating recoded file for chr24 using Plink") createPedChr24UsingPlink(args) # Compute the number of no call logger.info("Computing the number of no calls") com... |
def createGenderPlot(bfile, intensities, problematic_samples, format, out_prefix): """Creates the gender plot. :param bfile: the prefix of the input binary file. :param intensities: the file containing the intensities. :param problematic_samples: the file containing the problematic samples. :param format: the format of... |
def createLrrBafPlot(raw_dir, problematic_samples, format, dpi, out_prefix): """Creates the LRR and BAF plot. :param raw_dir: the directory containing the intensities. :param problematic_samples: the file containing the problematic samples. :param format: the format of the plot. :param dpi: the DPI of the resulting ima... |
def checkBim(fileName, minNumber, chromosome): """Checks the BIM file for chrN markers. :param fileName: :param minNumber: :param chromosome: :type fileName: str :type minNumber: int :type chromosome: str :returns: ``True`` if there are at least ``minNumber`` markers on chromosome ``chromosome``, ``False`` otherwise. "... |
def computeNoCall(fileName): """Computes the number of no call. :param fileName: the name of the file :type fileName: str Reads the ``ped`` file created by Plink using the ``recodeA`` options (see :py:func:`createPedChr24UsingPlink`) and computes the number and percentage of no calls on the chromosome ``24``. """ outpu... |
"\t".join(row) except IOError: msg = "%(fileName)s: no such file" % locals() raise ProgramError(msg) # Closing the output file outputFile.close() |
def computeHeteroPercentage(fileName): """Computes the heterozygosity percentage. :param fileName: the name of the input file. :type fileName: str Reads the ``ped`` file created by Plink using the ``recodeA`` options (see :py:func:`createPedChr23UsingPlink`) and computes the heterozygosity percentage on the chromosome ... |
# Sorting the data toPrint.sort(reverse=True, key=lambda values: values[3]) # Printing the data for row in toPrint: value = list(row) if value[3] == -9999: value[3] = "ALL_NA" else: value[3] = str(value[3]) print >>outputFile, "\t".join(value) except IOError: msg = "%(fileName)s: no such file" % locals() raise ProgramE... |
def readCheckSexFile(fileName, allProblemsFileName, idsFileName, femaleF, maleF): """Reads the Plink check-sex output file. :param fileName: the name of the input file. :param allProblemsFileName: the name of the output file that will contain all the problems. :param idsFileName: the name of the output file what will c... |
idsFile = open(idsFileName, 'w') except IOError: msg = "%(idsFileName)s: can't write file" % locals() raise ProgramError(msg) try: with open(fileName, 'r') as inputFile: headerIndex = None nbProblems = 0 nbTotalProblems = 0 nbSexUnknown = 0 nbFemaleThreshold = 0 nbMaleThreshold = 0 for line in inputFile: row = createRo... |
"0", so we skip nbSexUnknown += 1 continue snpsex = row[headerIndex["SNPSEX"]] if snpsex == "0": # The new sex is unknown f = None try: f = float(row[headerIndex["F"]]) except ValueError: msg = "F=%s: not a float" % row[headerIndex["F"]] raise ProgramError(msg) if pedsex == "2": # We have a female if f < femaleF: nbFem... |
"%(fileName)s: no such file" # Closing the output files idsFile.close() allProblemsFile.close() if nbProblems == 0: # There are no sex problems to investigate logger.info("There are no sex problem to investigate...") logger.info(" - Nothing else to do...") return False return True |
def createPedChr23UsingPlink(options): """Run Plink to create a ped format. :param options: the options. :type options: argparse.Namespace Uses Plink to create a ``ped`` file of markers on the chromosome ``23``. It uses the ``recodeA`` options to use additive coding. It also subsets the data to keep only samples with s... |
def createPedChr24UsingPlink(options): """Run plink to create a ped format. :param options: the options. :type options: argparse.Namespace Uses Plink to create a ``ped`` file of markers on the chromosome ``24``. It uses the ``recodeA`` options to use additive coding. It also subsets the data to keep only samples with s... |
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... |
BAF, we need a directory if args.lrr_baf: if not os.path.isdir(args.lrr_baf_raw_dir): msg = "{}: no such directory".format(args.lrr_baf_raw_dir) raise ProgramError(msg) if args.lrr_baf_dpi < 10: msg = "{}: DPI too low".format(args.dpi) raise ProgramError(msg) return True |
def use_dill( self ): """Make the cluster use Dill as pickler for transferring results. This isn't generally needed, but is sometimes useful for particularly complex experiments such as those involving closures. (Or, to put it another way, if you find yourself tempted to use this method, consider re-structuring your ex... |
def sync_imports( self, quiet = False ): """Return a context manager to control imports onto all the engines in the underlying cluster. This method is used within a ``with`` statement. Any imports should be done with no experiments running, otherwise the method will block until the cluster is quiet. Generally imports w... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.