Ejemplo n.º 1
0
def process_original_gwas(args, imputed):
    logging.info("Processing GWAS file %s", args.gwas_file)
    g = pandas.read_table(args.gwas_file)
    g = g.assign(current_build="hg38",
                 imputation_status="original")[COLUMN_ORDER]
    # Remember the palindromic snps are to be excluded from the input GWAS;
    logging.info("Read %d variants", g.shape[0])

    if not args.keep_all_observed:
        if args.keep_criteria == "GTEX_VARIANT_ID":
            g = g.loc[~g.panel_variant_id.isin(imputed.panel_variant_id)]
        elif args.keep_criteria == "CHR_POS":
            g = g.assign(k=gwas_k(g))
            imputed = imputed.assign(k=gwas_k(imputed))
            g = g.loc[~g.k.isin({x for x in imputed.k})]
            g.drop("k", axis=1, inplace=True)
            imputed.drop("k", axis=1, inplace=True)
        else:
            raise RuntimeError("Unsupported keep option")
        logging.info("Kept %d variants as observed", g.shape[0])

    g = pandas.concat([g, imputed])[COLUMN_ORDER]
    logging.info("%d variants", g.shape[0])

    logging.info("Filling median")
    g = Genomics.fill_column_to_median(g, "sample_size", numpy.int32)

    logging.info("Sorting by chromosome-position")
    g = Genomics.sort(g)

    logging.info("Saving")
    Utilities.save_dataframe(g, args.output)

    return g[["panel_variant_id"]]
Ejemplo n.º 2
0
def by_chromosome(context, chromosome):
    vm = context.vmf.read_row_group(chromosome - 1).to_pandas()
    if args.frequency_filter:
        vm = filter_by_frequency(vm, args.frequency_filter)

    g = context.get_genotype_file(chromosome)

    regions = context.regions
    regions = regions[regions.chr == "chr{}".format(chromosome)]

    for i, region in enumerate(regions.itertuples()):
        logging.log(9, "Processing region in chr %d: %d/%d", chromosome, i + 1,
                    regions.shape[0])
        vmw = Genomics.entries_for_window(chromosome,
                                          region.start - args.window,
                                          region.stop + args.window, vm)
        ids = vmw.id.values
        logging.log(9, "%d variants", len(ids))
        d = Parquet._read(g, columns=ids, skip_individuals=True)
        d = numpy.array([d[x] for x in ids], dtype=numpy.float32)
        if context.args.standardise_geno:
            cov = numpy.corrcoef(d, ddof=1).astype(numpy.float32, copy=False)
        else:
            cov = numpy.cov(d).astype(numpy.float32, copy=False)
        logging.log(9, "%d rows", cov.shape[0])
        context.sink(cov, ids, region)
def clean_up(d):
    d = d.assign(sample_size=[
        int(x) if not math.isnan(x) else "NA" for x in d.sample_size
    ])
    if "chromosome" in d.columns.values and "position" in d.columns.values:
        d = Genomics.sort(d)
    return d
def process(w, s, c, data, data_annotation_, features, features_metadata, x_weights, summary_fields, train, postfix=None, nested_folds=10, use_individuals=None):
    gene_id_ = data_annotation_.gene_id if postfix is None else "{}-{}".format(data_annotation_.gene_id, postfix)
    logging.log(8, "loading data")
    d_ = Parquet._read(data, [data_annotation_.gene_id], specific_individuals=use_individuals)
    features_ = Genomics.entries_for_gene_annotation(data_annotation_, args.window, features_metadata)

    if x_weights is not None:
        x_w = features_[["id"]].merge(x_weights[x_weights.gene_id == data_annotation_.gene_id], on="id")
        features_ = features_[features_.id.isin(x_w.id)]
        x_w = robjects.FloatVector(x_w.w.values)
    else:
        x_w = None

    if features_.shape[0] == 0:
        logging.log(9, "No features available")
        return

    features_data_ = Parquet._read(features, [x for x in features_.id.values],
                                   specific_individuals=[x for x in d_["individual"]])

    logging.log(8, "training")
    weights, summary = train(features_data_, features_, d_, data_annotation_, x_w, not args.dont_prune, nested_folds)

    if weights.shape[0] == 0:
        logging.log(9, "no weights, skipping")
        return

    logging.log(8, "saving")
    weights = weights.assign(gene=data_annotation_.gene_id). \
        merge(features_.rename(columns={"id": "feature", "allele_0": "ref_allele", "allele_1": "eff_allele"}), on="feature"). \
        rename(columns={"feature": "varID"}). \
        assign(gene=gene_id_)

    weights = weights[["gene", "rsid", "varID", "ref_allele", "eff_allele", "weight"]]
    if args.output_rsids:
        weights.loc[weights.rsid == "NA", "rsid"] = weights.loc[weights.rsid == "NA", "varID"]
    w.write(weights.to_csv(sep="\t", index=False, header=False, na_rep="NA").encode())

    summary = summary. \
        assign(gene=gene_id_, genename=data_annotation_.gene_name,
               gene_type=data_annotation_.gene_type). \
        rename(columns={"n_features": "n_snps_in_window", "n_features_in_model": "n.snps.in.model",
                        "zscore_pval": "pred.perf.pval", "rho_avg_squared": "pred.perf.R2",
                        "cv_converged":"nested_cv_converged"})
    summary["pred.perf.qval"] = None
    summary = summary[summary_fields]
    s.write(summary.to_csv(sep="\t", index=False, header=False, na_rep="NA").encode())

    var_ids = [x for x in weights.varID.values]
    cov = numpy.cov([features_data_[k] for k in var_ids], ddof=1)
    ids = [x for x in weights.rsid.values] if args.output_rsids else var_ids
    cov = matrices._flatten_matrix_data([(gene_id_, ids, cov)])
    for cov_ in cov:
        l = "{} {} {} {}\n".format(cov_[0], cov_[1], cov_[2], cov_[3]).encode()
        c.write(l)
Ejemplo n.º 5
0
def build_regions(annotation, chromosome, sub_jobs, window):
    results = []
    genes = []
    for i in range(0, sub_jobs):
        s = Genomics.entries_for_split(chromosome, sub_jobs, i, annotation)
        start = numpy.min(s.start) - window
        if start < 0: start = 0
        end = numpy.max(s.end) + window
        results.append((i + 1, start, end))
        genes.append(s.gene_id.values)
    return pandas.DataFrame(results, columns=["split", "start", "end"]), genes
def run(args):
    if os.path.exists(args.output):
        logging.info("output path %s exists. Nope.", args.output)
        return

    start = timer()
    logging.info("Parsing input GWAS")
    d = GWAS.load_gwas(args.gwas_file,
                       args.output_column_map,
                       force_special_handling=args.force_special_handling,
                       skip_until_header=args.skip_until_header,
                       separator=args.separator,
                       handle_empty_columns=args.handle_empty_columns,
                       input_pvalue_fix=args.input_pvalue_fix,
                       enforce_numeric_columns=args.enforce_numeric_columns)
    logging.info("loaded %d variants", d.shape[0])

    d = pre_process_gwas(args, d)

    if args.fill_from_snp_info:
        d = fill_coords(args, d)

    if args.chromosome_format:
        d = d.assign(chromosome=Genomics.to_int(d.chromosome))
        d = d.assign(chromosome=["chr{}".format(x) for x in d.chromosome])

    if args.liftover:
        d = liftover(args, d)

    if args.snp_reference_metadata:
        d = fill_from_metadata(args,
                               d,
                               extra_col_dict=load_extra_col_key_value_pairs(
                                   args.meta_extra_col))

    if args.output_order:
        order = args.output_order
        for c in order:
            if not c in d:
                d = d.assign(**{c: numpy.nan})
        d = d[order]

    d = clean_up(d)

    logging.info("Saving...")
    Utilities.save_dataframe(d, args.output, fill_na=True)
    end = timer()
    logging.info("Finished converting GWAS in %s seconds", str(end - start))
Ejemplo n.º 7
0
def count_variants(chromosome, start, end, vf, m, last_chromosome, args):
    try:
        chromosome = int(chromosome.split("chr")[1])
        start = int(start)
        end = int(end)
        if chromosome != last_chromosome:
            logging.info("Reading chromosome %d", chromosome)
            m = vf.read_row_group(chromosome - 1).to_pandas()
            last_chromosome = chromosome
            if args.frequency_filter:
                logging.log(9, "Filtering by frequency")
                m = m[(m.allele_1_frequency > args.frequency_filter)
                      & (m.allele_1_frequency < 1 - args.frequency_filter)]
        v = Genomics.entries_for_window(chromosome, start, end, m)
        count = v.shape[0]
    except:
        count = "NA"
    return count, m, last_chromosome
Ejemplo n.º 8
0
def fill_from_metadata(args, d):
    m = get_panel_variants(args, d)
    if "panel_variant_id" in d: d = d.drop(["panel_variant_id"])

    logging.info("alligning alleles")

    d = Genomics.match(d, m)

    if not args.keep_all_original_entries:
        d = d.loc[~d.panel_variant_id.isna()]
        logging.info("%d variants after restricting to reference variants",
                     d.shape[0])

        logging.info("Ensuring variant uniqueness")
        d = ensure_uniqueness(d)
        logging.info("%d variants after ensuring uniqueness", d.shape[0])

    logging.info("Checking for missing frequency entries")
    d["frequency"] = filled_frequency(d, m)

    return d
def pre_process_gwas(args, d):
    if args.split_column:
        for s in args.split_column:
            d = PandasHelpers.split_column(d, s)
        if "position" in d:
            d = d.assign(position=d.position.astype(int))

    if args.insert_value:
        for spec in args.insert_value:
            d = insert_value(d, spec)

    # Some GWAs have NA's in fre
    if "frequency" in d:
        d["frequency"] = Genomics.to_number(d.frequency)

    if "n_controls" in d:
        if "n_cases" in d:
            logging.info("Adding up to sample size")
            d["sample_size"] = d.n_cases + d.n_controls
        elif "sample_size" in d:
            logging.info("difference to cases")
            d["n_cases"] = d.sample_size - d.n_controls

    return d
def run(args):
    Utilities.maybe_create_folder(args.intermediate_folder)
    Utilities.ensure_requisite_folders(args.output_prefix)

    logging.info("Opening data")
    p_ = re.compile(args.data_name_pattern)
    f = [x for x in sorted(os.listdir(args.data_folder)) if p_.search(x)]
    tissue_names = [p_.search(x).group(1) for x in f]
    data = []
    for i in range(0, len(tissue_names)):
        logging.info("Loading %s", tissue_names[i])
        data.append((tissue_names[i],
                     pq.ParquetFile(os.path.join(args.data_folder, f[i]))))
    data = collections.OrderedDict(data)
    available_data = {
        x
        for p in data.values() for x in p.metadata.schema.names
    }

    logging.info("Preparing output")
    WEIGHTS_FIELDS = [
        "gene", "rsid", "varID", "ref_allele", "eff_allele", "weight"
    ]
    SUMMARY_FIELDS = [
        "gene", "genename", "gene_type", "alpha", "n_snps_in_window",
        "n.snps.in.model", "rho_avg", "pred.perf.R2", "pred.perf.pval"
    ]

    Utilities.ensure_requisite_folders(args.output_prefix)

    if args.skip_regression:
        weights, summaries, covariances = None, None, None
    else:
        weights, summaries, covariances = setup_output(args.output_prefix,
                                                       tissue_names,
                                                       WEIGHTS_FIELDS,
                                                       SUMMARY_FIELDS)

    logging.info("Loading data annotation")
    data_annotation = StudyUtilities._load_gene_annotation(
        args.data_annotation)
    data_annotation = data_annotation[data_annotation.gene_id.isin(
        available_data)]
    if args.chromosome or (args.sub_batches and args.sub_batch):
        data_annotation = StudyUtilities._filter_gene_annotation(
            data_annotation, args.chromosome, args.sub_batches, args.sub_batch)
    logging.info("Kept %i entries", data_annotation.shape[0])

    logging.info("Opening features annotation")
    if not args.chromosome:
        features_metadata = pq.read_table(args.features_annotation).to_pandas()
    else:
        features_metadata = pq.ParquetFile(
            args.features_annotation).read_row_group(args.chromosome -
                                                     1).to_pandas()

    if args.chromosome and args.sub_batches:
        logging.info("Trimming variants")
        features_metadata = StudyUtilities.trim_variant_metadata_on_gene_annotation(
            features_metadata, data_annotation, args.window)

    if args.rsid_whitelist:
        logging.info("Filtering features annotation")
        whitelist = TextFileTools.load_list(args.rsid_whitelist)
        whitelist = set(whitelist)
        features_metadata = features_metadata[features_metadata.rsid.isin(
            whitelist)]

    logging.info("Opening features")
    features = pq.ParquetFile(args.features)

    logging.info("Setting R seed")
    seed = numpy.random.randint(1e8)

    if args.run_tag:
        d = pandas.DataFrame({
            "run": [args.run_tag],
            "cv_seed": [seed]
        })[["run", "cv_seed"]]
        for t in tissue_names:
            Utilities.save_dataframe(
                d, "{}_{}_runs.txt.gz".format(args.output_prefix, t))

    failed_run = False
    try:
        for i, data_annotation_ in enumerate(data_annotation.itertuples()):
            logging.log(9, "processing %i/%i:%s", i + 1,
                        data_annotation.shape[0], data_annotation_.gene_id)
            logging.log(8, "loading data")
            d_ = {}
            for k, v in data.items():
                d_[k] = Parquet._read(v, [data_annotation_.gene_id],
                                      to_pandas=True)
            features_ = Genomics.entries_for_gene_annotation(
                data_annotation_, args.window, features_metadata)

            if features_.shape[0] == 0:
                logging.log(9, "No features available")
                continue

            features_data_ = Parquet._read(features,
                                           [x for x in features_.id.values],
                                           to_pandas=True)
            features_data_["id"] = range(1, features_data_.shape[0] + 1)
            features_data_ = features_data_[["individual", "id"] +
                                            [x for x in features_.id.values]]

            logging.log(8, "training")
            prepare_ctimp(args.script_path, seed, args.intermediate_folder,
                          data_annotation_, features_, features_data_, d_)
            del (features_data_)
            del (d_)
            if args.skip_regression:
                continue

            subprocess.call([
                "bash",
                _execution_script(args.intermediate_folder,
                                  data_annotation_.gene_id)
            ])

            w = pandas.read_table(_weights(args.intermediate_folder,
                                           data_annotation_.gene_id),
                                  sep="\s+")
            s = pandas.read_table(_summary(args.intermediate_folder,
                                           data_annotation_.gene_id),
                                  sep="\s+")

            for e_, entry in enumerate(s.itertuples()):
                entry_weights = w[["SNP", "REF.0.", "ALT.1.",
                                   entry.tissue]].rename(
                                       columns={
                                           "SNP": "varID",
                                           "REF.0.": "ref_allele",
                                           "ALT.1.": "eff_allele",
                                           entry.tissue: "weight"
                                       })
                entry_weights = entry_weights[entry_weights.weight != 0]
                entry_weights = entry_weights.assign(
                    gene=data_annotation_.gene_id)
                entry_weights = entry_weights.merge(features_,
                                                    left_on="varID",
                                                    right_on="id",
                                                    how="left")
                entry_weights = entry_weights[WEIGHTS_FIELDS]
                if args.output_rsids:
                    entry_weights.loc[entry_weights.rsid == "NA",
                                      "rsid"] = entry_weights.loc[
                                          entry_weights.rsid == "NA", "varID"]
                weights[entry.tissue].write(
                    entry_weights.to_csv(sep="\t",
                                         index=False,
                                         header=False,
                                         na_rep="NA").encode())

                entry_summary = s[s.tissue == entry.tissue].rename(
                    columns={
                        "zscore_pval": "pred.perf.pval",
                        "rho_avg_squared": "pred.perf.R2"
                    })
                entry_summary = entry_summary.assign(
                    gene=data_annotation_.gene_id,
                    alpha=0.5,
                    genename=data_annotation_.gene_name,
                    gene_type=data_annotation_.gene_type,
                    n_snps_in_window=features_.shape[0])
                entry_summary["n.snps.in.model"] = entry_weights.shape[0]
                #must repeat strings beause of weird pandas indexing issue
                entry_summary = entry_summary.drop(
                    ["R2", "n", "tissue"], axis=1)[[
                        "gene", "genename", "gene_type", "alpha",
                        "n_snps_in_window", "n.snps.in.model", "rho_avg",
                        "pred.perf.R2", "pred.perf.pval"
                    ]]
                summaries[entry.tissue].write(
                    entry_summary.to_csv(sep="\t",
                                         index=False,
                                         header=False,
                                         na_rep="NA").encode())

                features_data_ = Parquet._read(
                    features, [x for x in entry_weights.varID.values],
                    to_pandas=True)
                var_ids = [x for x in entry_weights.varID.values]
                cov = numpy.cov([features_data_[k] for k in var_ids], ddof=1)
                ids = [x for x in entry_weights.rsid.values
                       ] if args.output_rsids else var_ids
                cov = matrices._flatten_matrix_data([(data_annotation_.gene_id,
                                                      ids, cov)])
                for cov_ in cov:
                    l = "{} {} {} {}\n".format(cov_[0], cov_[1], cov_[2],
                                               cov_[3]).encode()
                    covariances[entry.tissue].write(l)

            if not args.keep_intermediate_folder:
                logging.info("Cleaning up")
                shutil.rmtree(
                    _intermediate_folder(args.intermediate_folder,
                                         data_annotation_.gene_id))

            if args.MAX_M and i >= args.MAX_M:
                logging.info("Early abort")
                break

    except Exception as e:
        logging.info("Exception running model training:\n%s",
                     traceback.format_exc())
        failed_run = True
    finally:
        pass
        # if not args.keep_intermediate_folder:
        #     shutil.rmtree(args.intermediate_folder)

    if not args.skip_regression:
        set_down(weights, summaries, covariances, tissue_names, failed_run)

    logging.info("Finished")
def run(args):
    wp = args.output_prefix + "_weights.txt.gz"
    if os.path.exists(wp):
        logging.info("Weights output exists already, delete it or move it")
        return

    sp = args.output_prefix + "_summary.txt.gz"
    if os.path.exists(sp):
        logging.info("Summary output exists already, delete it or move it")
        return

    cp = args.output_prefix + "_covariance.txt.gz"
    if os.path.exists(wp):
        logging.info("covariance output exists already, delete it or move it")
        return

    r = args.output_prefix + "_run.txt.gz"
    if os.path.exists(wp):
        logging.info("run output exists already, delete it or move it")
        return

    logging.info("Starting")
    Utilities.ensure_requisite_folders(args.output_prefix)

    logging.info("Opening data")
    data = pq.ParquetFile(args.data)
    available_data = {x for x in data.metadata.schema.names}

    logging.info("Loading data annotation")
    data_annotation = StudyUtilities.load_gene_annotation(args.data_annotation, args.chromosome, args.sub_batches, args.sub_batch, args.simplify_data_annotation)
    data_annotation = data_annotation[data_annotation.gene_id.isin(available_data)]
    if args.gene_whitelist:
        logging.info("Applying gene whitelist")
        data_annotation = data_annotation[data_annotation.gene_id.isin(set(args.gene_whitelist))]
    logging.info("Kept %i entries", data_annotation.shape[0])

    logging.info("Opening features annotation")
    if not args.chromosome:
        features_metadata = pq.read_table(args.features_annotation).to_pandas()
    else:
        features_metadata = pq.ParquetFile(args.features_annotation).read_row_group(args.chromosome-1).to_pandas()

    if args.output_rsids:
        if not args.keep_highest_frequency_rsid_entry and features_metadata[(features_metadata.rsid != "NA") & features_metadata.rsid.duplicated()].shape[0]:
            logging.warning("Several variants map to a same rsid (hint: multiple INDELS?).\n"
                            "Can't proceed. Consider the using the --keep_highest_frequency_rsid flag, or models will be ill defined.")
            return

    if args.chromosome and args.sub_batches:
        logging.info("Trimming variants")
        features_metadata = StudyUtilities.trim_variant_metadata_on_gene_annotation(features_metadata, data_annotation, args.window)
        logging.info("Kept %d", features_metadata.shape[0])

    if args.variant_call_filter:
        logging.info("Filtering variants by average call rate")
        features_metadata = features_metadata[features_metadata.avg_call > args.variant_call_filter]
        logging.info("Kept %d", features_metadata.shape[0])

    if args.variant_r2_filter:
        logging.info("Filtering variants by imputation R2")
        features_metadata = features_metadata[features_metadata.r2 > args.variant_r2_filter]
        logging.info("Kept %d", features_metadata.shape[0])

    if args.variant_variance_filter:
        logging.info("Filtering variants by (dosage/2)'s variance")
        features_metadata = features_metadata[features_metadata["std"]/2 > numpy.sqrt(args.variant_variance_filter)]
        logging.info("Kept %d", features_metadata.shape[0])

    if args.discard_palindromic_snps:
        logging.info("Discarding palindromic snps")
        features_metadata = Genomics.discard_gtex_palindromic_variants(features_metadata)
        logging.info("Kept %d", features_metadata.shape[0])

    if args.rsid_whitelist:
        logging.info("Filtering features annotation for whitelist")
        whitelist = TextFileTools.load_list(args.rsid_whitelist)
        whitelist = set(whitelist)
        features_metadata = features_metadata[features_metadata.rsid.isin(whitelist)]
        logging.info("Kept %d", features_metadata.shape[0])

    if args.only_rsids:
        logging.info("discarding non-rsids")
        features_metadata = StudyUtilities.trim_variant_metadata_to_rsids_only(features_metadata)
        logging.info("Kept %d", features_metadata.shape[0])

        if args.keep_highest_frequency_rsid_entry and features_metadata[(features_metadata.rsid != "NA") & features_metadata.rsid.duplicated()].shape[0]:
            logging.info("Keeping only the highest frequency entry for every rsid")
            k = features_metadata[["rsid", "allele_1_frequency", "id"]]
            k.loc[k.allele_1_frequency > 0.5, "allele_1_frequency"] = 1 - k.loc[k.allele_1_frequency > 0.5, "allele_1_frequency"]
            k = k.sort_values(by=["rsid", "allele_1_frequency"], ascending=False)
            k = k.groupby("rsid").first().reset_index()
            features_metadata = features_metadata[features_metadata.id.isin(k.id)]
            logging.info("Kept %d", features_metadata.shape[0])
        else:
            logging.info("rsids are unique, no need to restrict to highest frequency entry")

    if args.features_weights:
        logging.info("Loading weights")
        x_weights = get_weights(args.features_weights, {x for x in features_metadata.id})
        logging.info("Filtering features metadata to those available in weights")
        features_metadata = features_metadata[features_metadata.id.isin(x_weights.id)]
        logging.info("Kept %d entries", features_metadata.shape[0])
    else:
        x_weights = None

    logging.info("Opening features")
    features = pq.ParquetFile(args.features)

    logging.info("Setting R seed")
    s = numpy.random.randint(1e8)
    set_seed(s)
    if args.run_tag:
        d = pandas.DataFrame({"run":[args.run_tag], "cv_seed":[s]})[["run", "cv_seed"]]
        Utilities.save_dataframe(d, r)

    WEIGHTS_FIELDS=["gene", "rsid", "varID", "ref_allele", "eff_allele", "weight"]
    SUMMARY_FIELDS=["gene", "genename", "gene_type", "alpha", "n_snps_in_window", "n.snps.in.model",
                    "test_R2_avg", "test_R2_sd", "cv_R2_avg", "cv_R2_sd", "in_sample_R2", "nested_cv_fisher_pval",
                    "nested_cv_converged", "rho_avg", "rho_se", "rho_zscore", "pred.perf.R2", "pred.perf.pval", "pred.perf.qval"]

    train = train_elastic_net_wrapper if args.mode == "elastic_net" else train_ols

    available_individuals = check_missing(args, data, features)

    with gzip.open(wp, "w") as w:
        w.write(("\t".join(WEIGHTS_FIELDS) + "\n").encode())
        with gzip.open(sp, "w") as s:
            s.write(("\t".join(SUMMARY_FIELDS) + "\n").encode())
            with gzip.open(cp, "w") as c:
                c.write("GENE RSID1 RSID2 VALUE\n".encode())
                for i,data_annotation_ in enumerate(data_annotation.itertuples()):
                    if args.MAX_M and  i>=args.MAX_M:
                        logging.info("Early abort")
                        break
                    logging.log(9, "processing %i/%i:%s", i+1, data_annotation.shape[0], data_annotation_.gene_id)

                    if args.repeat:
                        for j in range(0, args.repeat):
                            logging.log(9, "%i-th reiteration", j)
                            process(w, s, c, data, data_annotation_, features, features_metadata, x_weights, SUMMARY_FIELDS, train, j, nested_folds=args.nested_cv_folds, use_individuals=available_individuals)
                    else:
                        process(w, s, c, data, data_annotation_, features, features_metadata, x_weights, SUMMARY_FIELDS, train, nested_folds=args.nested_cv_folds, use_individuals=available_individuals)

    logging.info("Finished")
Ejemplo n.º 12
0
def run(args):
    if os.path.exists(args.output):
        logging.info("Output already exists, either delete it or move it")
        return

    logging.info("Loading group")
    groups = pandas.read_table(args.group)
    groups = groups.assign(chromosome = groups.gtex_intron_id.str.split(":").str.get(0))
    groups = groups.assign(position=groups.gtex_intron_id.str.split(":").str.get(1))
    groups = Genomics.sort(groups)

    logging.info("Getting parquet genotypes")
    file_map = get_file_map(args)

    logging.info("Getting genes")
    with sqlite3.connect(args.model_db_group_key) as connection:
        # Pay heed to the order. This avoids arbitrariness in sqlite3 loading of results.
        extra = pandas.read_sql("SELECT * FROM EXTRA order by gene", connection)
        extra = extra[extra["n.snps.in.model"] > 0]

    individuals = TextFileTools.load_list(args.individuals) if args.individuals else None

    logging.info("Processing")
    Utilities.ensure_requisite_folders(args.output)

    genes_ = groups[["chromosome", "position", "gene_id"]].drop_duplicates()
    with gzip.open(args.output, "w") as f:
        f.write("GENE RSID1 RSID2 VALUE\n".encode())
        with sqlite3.connect(args.model_db_group_key) as db_group_key:
            with sqlite3.connect(args.model_db_group_values) as db_group_values:
                for i,t_ in enumerate(genes_.itertuples()):
                    g_ = t_.gene_id
                    chr_ = t_.chromosome.split("chr")[1]
                    logging.log(8, "Proccessing %i/%i:%s", i+1, len(genes_), g_)

                    if not n_.search(chr_):
                        logging.log(9, "Unsupported chromosome: %s", chr_)
                        continue
                    dosage = file_map[int(chr_)]

                    group = groups[groups.gene_id == g_]
                    wg=[]
                    for value in group.intron_id:
                        wk = pandas.read_sql("select * from weights where gene = '{}';".format(value), db_group_values)
                        if wk.shape[0] == 0:
                            continue
                        wg.append(wk)

                    if len(wg) > 0:
                        wg = pandas.concat(wg)
                        w = pandas.concat([wk, wg])[["varID", "rsid"]].drop_duplicates()
                    else:
                        w = wk[["varID", "rsid"]].drop_duplicates()

                    if w.shape[0] == 0:
                        logging.log(8, "No data, skipping")
                        continue

                    if individuals:
                        d = Parquet._read(dosage, columns=w.varID.values, specific_individuals=individuals)
                        del d["individual"]
                    else:
                        d = Parquet._read(dosage, columns=w.varID.values, skip_individuals=True)

                    var_ids = list(d.keys())
                    if len(var_ids) == 0:
                        if len(w.varID.values) == 1:
                            logging.log(9, "workaround for single missing genotype at %s", g_)
                            d = {w.varID.values[0]:[0,1]}
                        else:
                            logging.log(9, "No genotype available for %s, skipping",g_)
                            next

                    if args.output_rsids:
                        ids = [x for x in pandas.DataFrame({"varID": var_ids}).merge(w[["varID", "rsid"]], on="varID").rsid.values]
                    else:
                        ids = var_ids

                    c = numpy.cov([d[x] for x in var_ids])
                    c = matrices._flatten_matrix_data([(g_, ids, c)])
                    for entry in c:
                        l = "{} {} {} {}\n".format(entry[0], entry[1], entry[2], entry[3])
                        f.write(l.encode())
    logging.info("Finished building covariance.")