diff --git "a/data/dataset_Epigenetics.csv" "b/data/dataset_Epigenetics.csv" new file mode 100644--- /dev/null +++ "b/data/dataset_Epigenetics.csv" @@ -0,0 +1,14997 @@ +"keyword","repo_name","file_path","file_extension","file_size","line_count","content","language" +"Epigenetics","Weikai-47/Pepper_T2T","2. Validation/plot_coverage.depth.py",".py","1742","47","import pandas as pd +import matplotlib.pyplot as plt +plt.rc('font',family='Times New Roman') +import numpy as np + +data = pd.read_excel('./副本Andean_coverage6.xlsx') +data['ONT_position'] = 0 +data.columns = ['HiFi_chr','HiFi_start','HiFi_end','HiFi_value','HiFi_position', + 'NGS_chr','NGS_start','NGS_end','NGS_value','NGS_position', + 'ONT_chr','ONT_start','ONT_end','ONT_value','ONT_position'] +list_data = list(data.groupby('NGS_chr')) + +chr_dict = {} +for i in list_data: + chr_dict[i[0]] = i[1] + +labels = [0] +count = 0 +for i in range(1,14): + for j in ['HiFi_start','NGS_start','ONT_start','HiFi_end','NGS_end','ONT_end']: + chr_dict['chr{}'.format(i)][j] += count + count = chr_dict['chr{}'.format(i)].iloc[-1,:]['NGS_end'] + labels.append(count/1000000) + +data1 = chr_dict['chr1'] +for i in range(2,14): + data1 = pd.concat([data1,chr_dict['chr{}'.format(i)]]) + +for i in ['NGS','ONT','HiFi']: + data1[i+'_position'] = (data1[i+'_start'].astype('float') + data1[i+'_end'].astype('float'))/2.0 + + +name = ['HiFi','NGS','ONT'] +color = ['pink','aqua','lavender'] +for i in range(0,3): + plt.subplot(3, 1, i+1) + ax = plt.gca() # gca:get current axis得到当前轴 + # 设置图片的右边框和上边框为不显示 + ax.spines['right'].set_color('none') + ax.spines['top'].set_color('none') + print(data1[name[i]+'_value']) + plt.bar(data1[name[i]+'_position'] / 1000000, data1[name[i]+'_value'], width=1.0, color=color[i]) + plt.scatter(data1[name[i]+'_position'] / 1000000, data1[name[i]+'_value'], color='black', s=0.8, alpha=0.6, marker='s') + plt.ylabel(name[i]+' Sequence Depth', fontsize=14) + plt.xticks(labels) +plt.show() +","Python" +"Epigenetics","Weikai-47/Pepper_T2T","SVM-based classifier/2.FeatureImportances.py",".py","1518","39","import numpy as np +from sklearn.svm import SVC +from sklearn.ensemble import RandomForestClassifier, GradientBoostingClassifier + + +def stat_feature_importance(X, Y, model, name_list): + X = np.array(X) + Y = np.array(Y) + + # 训练模型 + model.fit(X, Y) + + # 根据模型类型获取特征重要性 + if hasattr(model, 'coef_'): + # 对于线性模型 + feature_importance = np.abs(model.coef_) + elif hasattr(model, 'feature_importances_'): + # 对于支持feature_importances_属性的模型,如RF和Gradient Boosting + feature_importance = model.feature_importances_ + else: + raise ValueError(""Model does not have feature importance attribute"") + + # 对于线性模型,feature_importance是一个二维数组,我们需要将其转化为一维 + if len(feature_importance.shape) > 1: + feature_importance = np.mean(feature_importance, axis=0) + + # 创建一个字典来存储特征名称和它们的重要性 + feature_importance_dict = dict(zip(name_list, feature_importance)) + # 按重要性降序排序字典 + sorted_feature_importance = dict(sorted(feature_importance_dict.items(), key=lambda item: item[1], reverse=True)) + + with open(""../features_importance.csv"", ""w"") as f: + # 输出排序后的特征重要性 + for feature, importance in sorted_feature_importance.items(): + print(f""{feature}: {importance}"") + f.write(feature + "","" + str(importance) + '\n') + + +","Python" +"Epigenetics","Weikai-47/Pepper_T2T","SVM-based classifier/1.GridSearch.py",".py","5067","150","import numpy as np +import pandas as pd +from sklearn.model_selection import cross_val_score, GridSearchCV +from sklearn.svm import SVC +from sklearn.ensemble import RandomForestClassifier +from sklearn.neighbors import KNeighborsClassifier +from sklearn.ensemble import GradientBoostingClassifier +import Visualization as vis +from sklearn.model_selection import StratifiedKFold +from sklearn.feature_selection import RFECV +from Feature_Importance import stat_feature_importance + +# (1) load and transform the data +data = pd.read_excel(""../CBGs_cnv.xlsx"") +data1 = pd.read_excel(""../STab.356_reseq.xlsx"")[[""Sample name"",""Capsaicinoids content (mg/kg DW)""]] + +index = data.columns +data = pd.DataFrame(np.array(data).T) +data.index = index +data = data.reset_index() +data.columns = data.iloc[1,:] +data = data.iloc[2:,:] +data = data.merge(data1,left_on=""Gene"",right_on=""Sample name"") + +name_list = [] +for i in data.columns: + if i != ""Sample name"": + name_list.append(i) + +data = data[name_list] +list1 = [i for i in data.columns] +list1[0] = 'SampleID' +data.columns = list1 +data['Capsaicinoids content (mg/kg DW)'] = data['Capsaicinoids content (mg/kg DW)'].astype('float') +data = data[data[""Capsaicinoids content (mg/kg DW)""] >= 0] + +# split the labels according to the median, so we can get the balanced dataset +C_level = np.array(data['Capsaicinoids content (mg/kg DW)'].astype(float)).tolist() +C_level.sort(reverse=True) + +def func2(x): + if x <= C_level[int(len(C_level)/2)]: + return 0.0 + else: + return 1.0 + +data['Capsaicinoids content (mg/kg DW)'] = data['Capsaicinoids content (mg/kg DW)'].apply(func2).astype(int) + +# (2) Features selection +X = data.drop([""SampleID"", ""Capsaicinoids content (mg/kg DW)""], axis=1) +y = data[""Capsaicinoids content (mg/kg DW)""] + +# 初始化一个SVM分类器 +RF = RandomForestClassifier() +# 使用RFECV进行特征选择,以找到最佳特征数量 +# StratifiedKFold用于确保每个类的样本比例保持一致 +# step表示每次迭代要移除的特征数 +# cv代表交叉验证的策略,这里使用5折交叉验证 +rfecv = RFECV(estimator=RF, step=1, cv=StratifiedKFold(5), scoring='accuracy') +rfecv.fit(X, y) + +# 打印出最佳特征数量 +print(""Optimal number of features : %d"" % rfecv.n_features_) + +# 选择特征 +X_new = rfecv.transform(X) + +# 获取被选中的特征的布尔掩码 +selected_features_mask = rfecv.support_ + +# 使用布尔掩码来获取被选中的特征名称 +selected_features_names = X.columns[selected_features_mask] + +print(""Selected features names:"") +print(selected_features_names) + +# (3) Set the parameters for models +models = [ + (""Support Vector Machine (Kernal: linear)"", SVC(), {""C"": [0.0001, 0.001, 0.01, 0.1, 1, 10], ""kernel"": [ ""linear"" ]}), + (""Random Forest"", RandomForestClassifier(), {""n_estimators"": [10, 50, 100, 150], ""max_depth"": [1, 10, 20, 30], 'max_features':[None, 'sqrt', 'log2']}), + (""K Nearest Neighbors"", KNeighborsClassifier(), {""n_neighbors"": [3, 5, 7, 10], ""weights"": [""uniform"", ""distance""]}), + (""Gradient Boosting"", GradientBoostingClassifier(), + { + 'n_estimators': [10, 50, 100, 150], + 'learning_rate': [0.01, 0.1, 0.2], + 'max_depth': [1, 10, 20, 30], + 'max_features': [None, 'sqrt', 'log2'], + 'subsample': [0.8, 0.9, 1.0] + } + ) +] + +acc_scores = {} +precision_scores = {} +recall_scores = {} + +model_list = [] +best_acc = 0 +best_model = None + +# (4) train and evaluate the models +for name, model, params in models: + # Grid Search the hyperparameters + grid_search = GridSearchCV(model, params, cv=10, scoring=""accuracy"") + grid_search.fit(X_new, y) + + # print the best hyperparameters + print(f""{name}:"") + print(""Best Parameters:"", grid_search.best_params_) + print(""Best Score:"", grid_search.best_score_) + + # use the best hyperparameters to test + model = grid_search.best_estimator_ + model_list.append(model) + scores1 = cross_val_score(model, X_new, y, cv=10, scoring=""accuracy"") + acc_scores[name] = scores1 + + # output the outcome + print(""Cross-Validation Scores:"") + print(""Accuracy:"", scores1.mean()) + + if scores1.mean() > best_acc: + best_acc = scores1.mean() + best_model = model + + # Calculate precision and recall + scores2 = cross_val_score(model, X_new, y, cv=10, scoring=""precision"") + precision_scores[name] = scores2 + + # output the outcome + print(""Cross-Validation Scores:"") + print(""Precision:"", scores2.mean()) + + scores3 = cross_val_score(model, X_new, y, cv=10, scoring=""recall"") + recall_scores[name] = scores3 + + # output the outcome + print(""Cross-Validation Scores:"") + print(""Recall:"", scores3.mean()) + + print(""-------------------------------"") + +# (5) Viualization +vis.Visualize_Performance(acc_scores) + +vis.Draw_ROC_curve(X_new,y,model_list,89) + +# (6) Statistic Feature importance +stat_feature_importance(X_new,y,best_model,selected_features_names) +","Python" +"Epigenetics","Weikai-47/Pepper_T2T","SVM-based classifier/0.Count_CNVs.sh",".sh","976","49","fr = open(""/data/pepper/CaT2T.CBGs.bed"",'r') + +REGIONS = [] + +for line in fr: + chr = line.strip().split()[0] + start = line.strip().split()[1] + end = line.strip().split()[2] + + region = chr + "":"" + start + ""-"" + end + + REGIONS.append(region) + +print(REGIONS) + + +import glob + +SAMPLES = [i.split(""/"")[-2] for i in glob.glob(""/data/pepper/*/CRR*_CaT2T.bam"")] + +print(SAMPLES) +print(""Total sample size: "",len(SAMPLES)) + + +rule all: + input: + expand(""{sample}/{sample}_{region}.CN"",sample=SAMPLES,region=REGIONS) + + +rule amycne: + input: + gc = ""/data/pepper/gc_content.tab"", + cov = ""{sample}/{sample}.regions.bed"" + output: + ""{sample}/{sample}_{region}.CN"" + threads: + 4 + resources: + mem_mb = 8000 + params: + ""{region}"" + shell: + """""" + python /home/biotools/AMYCNE-master/AMYCNE.py \ + --genotype --gc {input.gc} \ + --coverage {input.cov} \ + --R {params} > {output} + """""" +","Shell" +"Epigenetics","Weikai-47/Pepper_T2T","SVM-based classifier/3.Visualization.py",".py","3172","85","import numpy as np +import pandas as pd +from sklearn.model_selection import cross_val_score, GridSearchCV, cross_val_predict +from sklearn.svm import SVC +from sklearn.ensemble import RandomForestClassifier +from sklearn.metrics import accuracy_score, precision_score, recall_score, f1_score +from sklearn.neighbors import KNeighborsClassifier +from sklearn.ensemble import GradientBoostingClassifier +import matplotlib.pyplot as plt +import seaborn as sns +from sklearn.metrics import precision_score, recall_score +from sklearn.metrics import roc_curve, auc +from sklearn.model_selection import train_test_split + +def Visualize_Performance(acc_scores): + # Generate some random data to represent in the boxplot + np.random.seed(10) + data = pd.DataFrame(acc_scores) + + # Set the style of the seaborn library + sns.set_style(""whitegrid"") + + # Create a figure and a set of subplots + plt.figure(figsize=(10, 6)) + + # Create the boxplot with additional parameters for better aesthetics + sns.boxplot(data=data, + showmeans=True, + meanprops={""marker"": ""o"", + ""markerfacecolor"": ""white"", + ""markeredgecolor"": ""black"", + ""markersize"": ""10""}) + + # Set the labels and title + plt.xlabel('Prediction Algorithms', fontsize=14) + plt.ylabel('Accuracy', fontsize=14) + + # Improve the aesthetics of the plot axes + plt.tick_params(axis='both', which='major', labelsize=12) + + # Show the plot + plt.show() + +def Draw_ROC_curve(X,Y,model_list,random_state): + # (1) split the train dataset and test dataset + X_train, X_test, y_train, y_test = train_test_split(X, Y, test_size=0.2, random_state=random_state) + + # (2) 建立model,绘制ROC曲线 + SVM_model = model_list[0] + RF_model = model_list[1] + KNN_model = model_list[2] + GBoost_model = model_list[3] + + # 训练模型 + SVM_model.fit(X_train, y_train) + RF_model.fit(X_train, y_train) + KNN_model.fit(X_train, y_train) + GBoost_model.fit(X_train, y_train) + + # 计算各个模型的概率预测值并绘制ROC曲线 + models = [SVM_model, RF_model, KNN_model, GBoost_model] + model_names = ['SVM', 'Random Forest', 'K-Nearest Neighbors', 'Gradient Boosting'] + + plt.figure() + for model, model_name in zip(models, model_names): + if isinstance(model, RandomForestClassifier) or isinstance(model, KNeighborsClassifier): + y_pred_proba = model.predict_proba(X_test)[:, 1] # 使用predict_proba获取概率值 + else: + y_pred_proba = model.decision_function(X_test) + + fpr, tpr, thresholds = roc_curve(y_test, y_pred_proba) + roc_auc = auc(fpr, tpr) + + plt.plot(fpr, tpr, lw=2, label=f'{model_name} (AUC = {roc_auc:.2f})') + + plt.plot([0, 1], [0, 1], color='navy', lw=2, linestyle='--') + plt.xlim([0.0, 1.0]) + plt.ylim([0.0, 1.05]) + plt.xlabel('False Positive Rate') + plt.ylabel('True Positive Rate') + plt.title('Receiver Operating Characteristic (ROC) Curves') + plt.legend(loc='lower right') + plt.show() + +","Python" +"Epigenetics","epiviz/epiviz","closure-library/closure/bin/scopify.py",".py","6785","222","#!/usr/bin/python +# +# Copyright 2010 The Closure Library Authors. All Rights Reserved. +# +# Licensed under the Apache License, Version 2.0 (the ""License""); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an ""AS-IS"" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + + +""""""Automatically converts codebases over to goog.scope. + +Usage: +cd path/to/my/dir; +../../../../javascript/closure/bin/scopify.py + +Scans every file in this directory, recursively. Looks for existing +goog.scope calls, and goog.require'd symbols. If it makes sense to +generate a goog.scope call for the file, then we will do so, and +try to auto-generate some aliases based on the goog.require'd symbols. + +Known Issues: + + When a file is goog.scope'd, the file contents will be indented +2. + This may put some lines over 80 chars. These will need to be fixed manually. + + We will only try to create aliases for capitalized names. We do not check + to see if those names will conflict with any existing locals. + + This creates merge conflicts for every line of every outstanding change. + If you intend to run this on your codebase, make sure your team members + know. Better yet, send them this script so that they can scopify their + outstanding changes and ""accept theirs"". + + When an alias is ""captured"", it can no longer be stubbed out for testing. + Run your tests. + +"""""" + +__author__ = 'nicksantos@google.com (Nick Santos)' + +import os.path +import re +import sys + +REQUIRES_RE = re.compile(r""goog.require\('([^']*)'\)"") + +# Edit this manually if you want something to ""always"" be aliased. +# TODO(nicksantos): Add a flag for this. +DEFAULT_ALIASES = {} + +def Transform(lines): + """"""Converts the contents of a file into javascript that uses goog.scope. + + Arguments: + lines: A list of strings, corresponding to each line of the file. + Returns: + A new list of strings, or None if the file was not modified. + """""" + requires = [] + + # Do an initial scan to be sure that this file can be processed. + for line in lines: + # Skip this file if it has already been scopified. + if line.find('goog.scope') != -1: + return None + + # If there are any global vars or functions, then we also have + # to skip the whole file. We might be able to deal with this + # more elegantly. + if line.find('var ') == 0 or line.find('function ') == 0: + return None + + for match in REQUIRES_RE.finditer(line): + requires.append(match.group(1)) + + if len(requires) == 0: + return None + + # Backwards-sort the requires, so that when one is a substring of another, + # we match the longer one first. + for val in DEFAULT_ALIASES.values(): + if requires.count(val) == 0: + requires.append(val) + + requires.sort() + requires.reverse() + + # Generate a map of requires to their aliases + aliases_to_globals = DEFAULT_ALIASES.copy() + for req in requires: + index = req.rfind('.') + if index == -1: + alias = req + else: + alias = req[(index + 1):] + + # Don't scopify lowercase namespaces, because they may conflict with + # local variables. + if alias[0].isupper(): + aliases_to_globals[alias] = req + + aliases_to_matchers = {} + globals_to_aliases = {} + for alias, symbol in aliases_to_globals.items(): + globals_to_aliases[symbol] = alias + aliases_to_matchers[alias] = re.compile('\\b%s\\b' % symbol) + + # Insert a goog.scope that aliases all required symbols. + result = [] + + START = 0 + SEEN_REQUIRES = 1 + IN_SCOPE = 2 + + mode = START + aliases_used = set() + insertion_index = None + num_blank_lines = 0 + for line in lines: + if mode == START: + result.append(line) + + if re.search(REQUIRES_RE, line): + mode = SEEN_REQUIRES + + elif mode == SEEN_REQUIRES: + if (line and + not re.search(REQUIRES_RE, line) and + not line.isspace()): + # There should be two blank lines before goog.scope + result += ['\n'] * 2 + result.append('goog.scope(function() {\n') + insertion_index = len(result) + result += ['\n'] * num_blank_lines + mode = IN_SCOPE + elif line.isspace(): + # Keep track of the number of blank lines before each block of code so + # that we can move them after the goog.scope line if necessary. + num_blank_lines += 1 + else: + # Print the blank lines we saw before this code block + result += ['\n'] * num_blank_lines + num_blank_lines = 0 + result.append(line) + + if mode == IN_SCOPE: + for symbol in requires: + if not symbol in globals_to_aliases: + continue + + alias = globals_to_aliases[symbol] + matcher = aliases_to_matchers[alias] + for match in matcher.finditer(line): + # Check to make sure we're not in a string. + # We do this by being as conservative as possible: + # if there are any quote or double quote characters + # before the symbol on this line, then bail out. + before_symbol = line[:match.start(0)] + if before_symbol.count('""') > 0 or before_symbol.count(""'"") > 0: + continue + + line = line.replace(match.group(0), alias) + aliases_used.add(alias) + + if line.isspace(): + # Truncate all-whitespace lines + result.append('\n') + else: + result.append(line) + + if len(aliases_used): + aliases_used = [alias for alias in aliases_used] + aliases_used.sort() + aliases_used.reverse() + for alias in aliases_used: + symbol = aliases_to_globals[alias] + result.insert(insertion_index, + 'var %s = %s;\n' % (alias, symbol)) + result.append('}); // goog.scope\n') + return result + else: + return None + +def TransformFileAt(path): + """"""Converts a file into javascript that uses goog.scope. + + Arguments: + path: A path to a file. + """""" + f = open(path) + lines = Transform(f.readlines()) + if lines: + f = open(path, 'w') + for l in lines: + f.write(l) + f.close() + +if __name__ == '__main__': + args = sys.argv[1:] + if not len(args): + args = '.' + + for file_name in args: + if os.path.isdir(file_name): + for root, dirs, files in os.walk(file_name): + for name in files: + if name.endswith('.js') and \ + not os.path.islink(os.path.join(root, name)): + TransformFileAt(os.path.join(root, name)) + else: + if file_name.endswith('.js') and \ + not os.path.islink(file_name): + TransformFileAt(file_name) +","Python" +"Epigenetics","epiviz/epiviz","closure-library/closure/bin/calcdeps.py",".py","18576","591","#!/usr/bin/env python +# +# Copyright 2006 The Closure Library Authors. All Rights Reserved. +# +# Licensed under the Apache License, Version 2.0 (the ""License""); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an ""AS-IS"" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + + +""""""Calculates JavaScript dependencies without requiring Google's build system. + +This tool is deprecated and is provided for legacy users. +See build/closurebuilder.py and build/depswriter.py for the current tools. + +It iterates over a number of search paths and builds a dependency tree. With +the inputs provided, it walks the dependency tree and outputs all the files +required for compilation. +"""""" + + + + + +try: + import distutils.version +except ImportError: + # distutils is not available in all environments + distutils = None + +import logging +import optparse +import os +import re +import subprocess +import sys + + +_BASE_REGEX_STRING = '^\s*goog\.%s\(\s*[\'""](.+)[\'""]\s*\)' +req_regex = re.compile(_BASE_REGEX_STRING % 'require') +prov_regex = re.compile(_BASE_REGEX_STRING % 'provide') +ns_regex = re.compile('^ns:((\w+\.)*(\w+))$') +version_regex = re.compile('[\.0-9]+') + + +def IsValidFile(ref): + """"""Returns true if the provided reference is a file and exists."""""" + return os.path.isfile(ref) + + +def IsJsFile(ref): + """"""Returns true if the provided reference is a Javascript file."""""" + return ref.endswith('.js') + + +def IsNamespace(ref): + """"""Returns true if the provided reference is a namespace."""""" + return re.match(ns_regex, ref) is not None + + +def IsDirectory(ref): + """"""Returns true if the provided reference is a directory."""""" + return os.path.isdir(ref) + + +def ExpandDirectories(refs): + """"""Expands any directory references into inputs. + + Description: + Looks for any directories in the provided references. Found directories + are recursively searched for .js files, which are then added to the result + list. + + Args: + refs: a list of references such as files, directories, and namespaces + + Returns: + A list of references with directories removed and replaced by any + .js files that are found in them. Also, the paths will be normalized. + """""" + result = [] + for ref in refs: + if IsDirectory(ref): + # Disable 'Unused variable' for subdirs + # pylint: disable=unused-variable + for (directory, subdirs, filenames) in os.walk(ref): + for filename in filenames: + if IsJsFile(filename): + result.append(os.path.join(directory, filename)) + else: + result.append(ref) + return map(os.path.normpath, result) + + +class DependencyInfo(object): + """"""Represents a dependency that is used to build and walk a tree."""""" + + def __init__(self, filename): + self.filename = filename + self.provides = [] + self.requires = [] + + def __str__(self): + return '%s Provides: %s Requires: %s' % (self.filename, + repr(self.provides), + repr(self.requires)) + + +def BuildDependenciesFromFiles(files): + """"""Build a list of dependencies from a list of files. + + Description: + Takes a list of files, extracts their provides and requires, and builds + out a list of dependency objects. + + Args: + files: a list of files to be parsed for goog.provides and goog.requires. + + Returns: + A list of dependency objects, one for each file in the files argument. + """""" + result = [] + filenames = set() + for filename in files: + if filename in filenames: + continue + + # Python 3 requires the file encoding to be specified + if (sys.version_info[0] < 3): + file_handle = open(filename, 'r') + else: + file_handle = open(filename, 'r', encoding='utf8') + + try: + dep = CreateDependencyInfo(filename, file_handle) + result.append(dep) + finally: + file_handle.close() + + filenames.add(filename) + + return result + + +def CreateDependencyInfo(filename, source): + """"""Create dependency info. + + Args: + filename: Filename for source. + source: File-like object containing source. + + Returns: + A DependencyInfo object with provides and requires filled. + """""" + dep = DependencyInfo(filename) + for line in source: + if re.match(req_regex, line): + dep.requires.append(re.search(req_regex, line).group(1)) + if re.match(prov_regex, line): + dep.provides.append(re.search(prov_regex, line).group(1)) + return dep + + +def BuildDependencyHashFromDependencies(deps): + """"""Builds a hash for searching dependencies by the namespaces they provide. + + Description: + Dependency objects can provide multiple namespaces. This method enumerates + the provides of each dependency and adds them to a hash that can be used + to easily resolve a given dependency by a namespace it provides. + + Args: + deps: a list of dependency objects used to build the hash. + + Raises: + Exception: If a multiple files try to provide the same namepace. + + Returns: + A hash table { namespace: dependency } that can be used to resolve a + dependency by a namespace it provides. + """""" + dep_hash = {} + for dep in deps: + for provide in dep.provides: + if provide in dep_hash: + raise Exception('Duplicate provide (%s) in (%s, %s)' % ( + provide, + dep_hash[provide].filename, + dep.filename)) + dep_hash[provide] = dep + return dep_hash + + +def CalculateDependencies(paths, inputs): + """"""Calculates the dependencies for given inputs. + + Description: + This method takes a list of paths (files, directories) and builds a + searchable data structure based on the namespaces that each .js file + provides. It then parses through each input, resolving dependencies + against this data structure. The final output is a list of files, + including the inputs, that represent all of the code that is needed to + compile the given inputs. + + Args: + paths: the references (files, directories) that are used to build the + dependency hash. + inputs: the inputs (files, directories, namespaces) that have dependencies + that need to be calculated. + + Raises: + Exception: if a provided input is invalid. + + Returns: + A list of all files, including inputs, that are needed to compile the given + inputs. + """""" + deps = BuildDependenciesFromFiles(paths + inputs) + search_hash = BuildDependencyHashFromDependencies(deps) + result_list = [] + seen_list = [] + for input_file in inputs: + if IsNamespace(input_file): + namespace = re.search(ns_regex, input_file).group(1) + if namespace not in search_hash: + raise Exception('Invalid namespace (%s)' % namespace) + input_file = search_hash[namespace].filename + if not IsValidFile(input_file) or not IsJsFile(input_file): + raise Exception('Invalid file (%s)' % input_file) + seen_list.append(input_file) + file_handle = open(input_file, 'r') + try: + for line in file_handle: + if re.match(req_regex, line): + require = re.search(req_regex, line).group(1) + ResolveDependencies(require, search_hash, result_list, seen_list) + finally: + file_handle.close() + result_list.append(input_file) + + # All files depend on base.js, so put it first. + base_js_path = FindClosureBasePath(paths) + if base_js_path: + result_list.insert(0, base_js_path) + else: + logging.warning('Closure Library base.js not found.') + + return result_list + + +def FindClosureBasePath(paths): + """"""Given a list of file paths, return Closure base.js path, if any. + + Args: + paths: A list of paths. + + Returns: + The path to Closure's base.js file including filename, if found. + """""" + + for path in paths: + pathname, filename = os.path.split(path) + + if filename == 'base.js': + f = open(path) + + is_base = False + + # Sanity check that this is the Closure base file. Check that this + # is where goog is defined. This is determined by the @provideGoog + # flag. + for line in f: + if '@provideGoog' in line: + is_base = True + break + + f.close() + + if is_base: + return path + +def ResolveDependencies(require, search_hash, result_list, seen_list): + """"""Takes a given requirement and resolves all of the dependencies for it. + + Description: + A given requirement may require other dependencies. This method + recursively resolves all dependencies for the given requirement. + + Raises: + Exception: when require does not exist in the search_hash. + + Args: + require: the namespace to resolve dependencies for. + search_hash: the data structure used for resolving dependencies. + result_list: a list of filenames that have been calculated as dependencies. + This variable is the output for this function. + seen_list: a list of filenames that have been 'seen'. This is required + for the dependency->dependent ordering. + """""" + if require not in search_hash: + raise Exception('Missing provider for (%s)' % require) + + dep = search_hash[require] + if not dep.filename in seen_list: + seen_list.append(dep.filename) + for sub_require in dep.requires: + ResolveDependencies(sub_require, search_hash, result_list, seen_list) + result_list.append(dep.filename) + + +def GetDepsLine(dep, base_path): + """"""Returns a JS string for a dependency statement in the deps.js file. + + Args: + dep: The dependency that we're printing. + base_path: The path to Closure's base.js including filename. + """""" + return 'goog.addDependency(""%s"", %s, %s);' % ( + GetRelpath(dep.filename, base_path), dep.provides, dep.requires) + + +def GetRelpath(path, start): + """"""Return a relative path to |path| from |start|."""""" + # NOTE: Python 2.6 provides os.path.relpath, which has almost the same + # functionality as this function. Since we want to support 2.4, we have + # to implement it manually. :( + path_list = os.path.abspath(os.path.normpath(path)).split(os.sep) + start_list = os.path.abspath( + os.path.normpath(os.path.dirname(start))).split(os.sep) + + common_prefix_count = 0 + for i in range(0, min(len(path_list), len(start_list))): + if path_list[i] != start_list[i]: + break + common_prefix_count += 1 + + # Always use forward slashes, because this will get expanded to a url, + # not a file path. + return '/'.join(['..'] * (len(start_list) - common_prefix_count) + + path_list[common_prefix_count:]) + + +def PrintLine(msg, out): + out.write(msg) + out.write('\n') + + +def PrintDeps(source_paths, deps, out): + """"""Print out a deps.js file from a list of source paths. + + Args: + source_paths: Paths that we should generate dependency info for. + deps: Paths that provide dependency info. Their dependency info should + not appear in the deps file. + out: The output file. + + Returns: + True on success, false if it was unable to find the base path + to generate deps relative to. + """""" + base_path = FindClosureBasePath(source_paths + deps) + if not base_path: + return False + + PrintLine('// This file was autogenerated by calcdeps.py', out) + excludesSet = set(deps) + + for dep in BuildDependenciesFromFiles(source_paths + deps): + if not dep.filename in excludesSet: + PrintLine(GetDepsLine(dep, base_path), out) + + return True + + +def PrintScript(source_paths, out): + for index, dep in enumerate(source_paths): + PrintLine('// Input %d' % index, out) + f = open(dep, 'r') + PrintLine(f.read(), out) + f.close() + + +def GetJavaVersion(): + """"""Returns the string for the current version of Java installed."""""" + proc = subprocess.Popen(['java', '-version'], stderr=subprocess.PIPE) + proc.wait() + version_line = proc.stderr.read().splitlines()[0] + return version_regex.search(version_line.decode('utf-8')).group() + + +def FilterByExcludes(options, files): + """"""Filters the given files by the exlusions specified at the command line. + + Args: + options: The flags to calcdeps. + files: The files to filter. + Returns: + A list of files. + """""" + excludes = [] + if options.excludes: + excludes = ExpandDirectories(options.excludes) + + excludesSet = set(excludes) + return [i for i in files if not i in excludesSet] + + +def GetPathsFromOptions(options): + """"""Generates the path files from flag options. + + Args: + options: The flags to calcdeps. + Returns: + A list of files in the specified paths. (strings). + """""" + + search_paths = options.paths + if not search_paths: + search_paths = ['.'] # Add default folder if no path is specified. + + search_paths = ExpandDirectories(search_paths) + return FilterByExcludes(options, search_paths) + + +def GetInputsFromOptions(options): + """"""Generates the inputs from flag options. + + Args: + options: The flags to calcdeps. + Returns: + A list of inputs (strings). + """""" + inputs = options.inputs + if not inputs: # Parse stdin + logging.info('No inputs specified. Reading from stdin...') + inputs = filter(None, [line.strip('\n') for line in sys.stdin.readlines()]) + + logging.info('Scanning files...') + inputs = ExpandDirectories(inputs) + + return FilterByExcludes(options, inputs) + + +def Compile(compiler_jar_path, source_paths, out, flags=None): + """"""Prepares command-line call to Closure compiler. + + Args: + compiler_jar_path: Path to the Closure compiler .jar file. + source_paths: Source paths to build, in order. + flags: A list of additional flags to pass on to Closure compiler. + """""" + args = ['java', '-jar', compiler_jar_path] + for path in source_paths: + args += ['--js', path] + + if flags: + args += flags + + logging.info('Compiling with the following command: %s', ' '.join(args)) + proc = subprocess.Popen(args, stdout=subprocess.PIPE) + (stdoutdata, stderrdata) = proc.communicate() + if proc.returncode != 0: + logging.error('JavaScript compilation failed.') + sys.exit(1) + else: + out.write(stdoutdata.decode('utf-8')) + + +def main(): + """"""The entrypoint for this script."""""" + + logging.basicConfig(format='calcdeps.py: %(message)s', level=logging.INFO) + + usage = 'usage: %prog [options] arg' + parser = optparse.OptionParser(usage) + parser.add_option('-i', + '--input', + dest='inputs', + action='append', + help='The inputs to calculate dependencies for. Valid ' + 'values can be files, directories, or namespaces ' + '(ns:goog.net.XhrIo). Only relevant to ""list"" and ' + '""script"" output.') + parser.add_option('-p', + '--path', + dest='paths', + action='append', + help='The paths that should be traversed to build the ' + 'dependencies.') + parser.add_option('-d', + '--dep', + dest='deps', + action='append', + help='Directories or files that should be traversed to ' + 'find required dependencies for the deps file. ' + 'Does not generate dependency information for names ' + 'provided by these files. Only useful in ""deps"" mode.') + parser.add_option('-e', + '--exclude', + dest='excludes', + action='append', + help='Files or directories to exclude from the --path ' + 'and --input flags') + parser.add_option('-o', + '--output_mode', + dest='output_mode', + action='store', + default='list', + help='The type of output to generate from this script. ' + 'Options are ""list"" for a list of filenames, ""script"" ' + 'for a single script containing the contents of all the ' + 'file, ""deps"" to generate a deps.js file for all ' + 'paths, or ""compiled"" to produce compiled output with ' + 'the Closure compiler.') + parser.add_option('-c', + '--compiler_jar', + dest='compiler_jar', + action='store', + help='The location of the Closure compiler .jar file.') + parser.add_option('-f', + '--compiler_flag', + '--compiler_flags', # for backwards compatibility + dest='compiler_flags', + action='append', + help='Additional flag to pass to the Closure compiler. ' + 'May be specified multiple times to pass multiple flags.') + parser.add_option('--output_file', + dest='output_file', + action='store', + help=('If specified, write output to this path instead of ' + 'writing to standard output.')) + + (options, args) = parser.parse_args() + + search_paths = GetPathsFromOptions(options) + + if options.output_file: + out = open(options.output_file, 'w') + else: + out = sys.stdout + + if options.output_mode == 'deps': + result = PrintDeps(search_paths, ExpandDirectories(options.deps or []), out) + if not result: + logging.error('Could not find Closure Library in the specified paths') + sys.exit(1) + + return + + inputs = GetInputsFromOptions(options) + + logging.info('Finding Closure dependencies...') + deps = CalculateDependencies(search_paths, inputs) + output_mode = options.output_mode + + if output_mode == 'script': + PrintScript(deps, out) + elif output_mode == 'list': + # Just print out a dep per line + for dep in deps: + PrintLine(dep, out) + elif output_mode == 'compiled': + # Make sure a .jar is specified. + if not options.compiler_jar: + logging.error('--compiler_jar flag must be specified if --output is ' + '""compiled""') + sys.exit(1) + + # User friendly version check. + if distutils and not (distutils.version.LooseVersion(GetJavaVersion()) > + distutils.version.LooseVersion('1.6')): + logging.error('Closure Compiler requires Java 1.6 or higher.') + logging.error('Please visit http://www.java.com/getjava') + sys.exit(1) + + Compile(options.compiler_jar, deps, out, options.compiler_flags) + + else: + logging.error('Invalid value for --output flag.') + sys.exit(1) + +if __name__ == '__main__': + main() +","Python" +"Epigenetics","epiviz/epiviz","closure-library/closure/bin/labs/code/generate_jsdoc_test.py",".py","3494","168","#!/usr/bin/env python +# +# Copyright 2013 The Closure Library Authors. All Rights Reserved. +# +# Licensed under the Apache License, Version 2.0 (the ""License""); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required `by applicable law or agreed to in writing, software +# distributed under the License is distributed on an ""AS-IS"" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + + +""""""Unit test for generate_jsdoc."""""" + +__author__ = 'nnaze@google.com (Nathan Naze)' + + +import re +import unittest + +import generate_jsdoc + + +class InsertJsDocTestCase(unittest.TestCase): + """"""Unit test for source. Tests the parser on a known source input."""""" + + def testMatchFirstFunction(self): + match = generate_jsdoc._MatchFirstFunction(_TEST_SOURCE) + self.assertNotEqual(None, match) + self.assertEqual('aaa, bbb, ccc', match.group('arguments')) + + match = generate_jsdoc._MatchFirstFunction(_INDENTED_SOURCE) + self.assertNotEqual(None, match) + self.assertEqual('', match.group('arguments')) + + match = generate_jsdoc._MatchFirstFunction(_ODD_NEWLINES_SOURCE) + self.assertEquals('goog.\nfoo.\nbar\n.baz.\nqux', + match.group('identifier')) + + def testParseArgString(self): + self.assertEquals( + ['foo', 'bar', 'baz'], + list(generate_jsdoc._ParseArgString('foo, bar, baz'))) + + def testExtractFunctionBody(self): + self.assertEquals( + '\n // Function comments.\n return;\n', + generate_jsdoc._ExtractFunctionBody(_TEST_SOURCE)) + + self.assertEquals( + '\n var bar = 3;\n return true;\n', + generate_jsdoc._ExtractFunctionBody(_INDENTED_SOURCE, 2)) + + def testContainsValueReturn(self): + self.assertTrue(generate_jsdoc._ContainsReturnValue(_INDENTED_SOURCE)) + self.assertFalse(generate_jsdoc._ContainsReturnValue(_TEST_SOURCE)) + + def testInsertString(self): + self.assertEquals( + 'abc123def', + generate_jsdoc._InsertString('abcdef', '123', 3)) + + def testInsertJsDoc(self): + self.assertEquals( + _EXPECTED_INDENTED_SOURCE, + generate_jsdoc.InsertJsDoc(_INDENTED_SOURCE)) + + self.assertEquals( + _EXPECTED_TEST_SOURCE, + generate_jsdoc.InsertJsDoc(_TEST_SOURCE)) + + self.assertEquals( + _EXPECTED_ODD_NEWLINES_SOURCE, + generate_jsdoc.InsertJsDoc(_ODD_NEWLINES_SOURCE)) + + +_INDENTED_SOURCE = """"""\ + boo.foo.woo = function() { + var bar = 3; + return true; + }; +"""""" + +_EXPECTED_INDENTED_SOURCE = """"""\ + /** + * @return + */ + boo.foo.woo = function() { + var bar = 3; + return true; + }; +"""""" + + +_TEST_SOURCE = """"""\ + +// Random comment. + +goog.foo.bar = function (aaa, bbb, ccc) { + // Function comments. + return; +}; +"""""" + +_EXPECTED_TEST_SOURCE = """"""\ + +// Random comment. + +/** + * @param {} aaa + * @param {} bbb + * @param {} ccc + */ +goog.foo.bar = function (aaa, bbb, ccc) { + // Function comments. + return; +}; +"""""" + +_ODD_NEWLINES_SOURCE = """"""\ +goog. +foo. +bar +.baz. +qux + = + + function + +(aaa, + +bbb, ccc) { + // Function comments. + return; +}; +"""""" + +_EXPECTED_ODD_NEWLINES_SOURCE = """"""\ +/** + * @param {} aaa + * @param {} bbb + * @param {} ccc + */ +goog. +foo. +bar +.baz. +qux + = + + function + +(aaa, + +bbb, ccc) { + // Function comments. + return; +}; +"""""" + +if __name__ == '__main__': + unittest.main() +","Python" +"Epigenetics","epiviz/epiviz","closure-library/closure/bin/labs/code/run_el_tests.sh",".sh","1016","32","#!/bin/bash +# +# Copyright 2013 The Closure Library Authors +# +# Licensed under the Apache License, Version 2.0 (the ""License""); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an ""AS-IS"" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Wraps the unit tests not using the Google framework so they may be run +# on the continuous build. +# +# Author: nnaze@google.com (Nathan Naze) +# +# Wraps the unit tests not using the Google framework so they may be run +# run on the continuous build. + +set -e + +source googletest.sh || exit 1 + +CLOSURE_SRCDIR=$TEST_SRCDIR/google3/javascript/closure/labs/bin/code/ + +emacs --script $CLOSURE_SRCDIR/closure_test.el +","Shell" +"Epigenetics","epiviz/epiviz","closure-library/closure/bin/labs/code/run_py_tests.sh",".sh","887","29","#!/bin/bash +# +# Copyright 2013 The Closure Library Authors +# +# Licensed under the Apache License, Version 2.0 (the ""License""); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an ""AS-IS"" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Wraps the unit tests not using the Google framework so they may be run +# on the continuous build. + +set -e + +source googletest.sh || exit 1 + +CLOSURE_SRCDIR=$TEST_SRCDIR/google3/javascript/closure/labs/bin/code/ + +PYTHONPATH=$CLOSURE_SRCDIR + +$CLOSURE_SRCDIR/generate_jsdoc_test.py +","Shell" +"Epigenetics","epiviz/epiviz","closure-library/closure/bin/labs/code/generate_jsdoc.py",".py","4318","172","#!/usr/bin/env python +# +# Copyright 2013 The Closure Library Authors. All Rights Reserved. +# +# Licensed under the Apache License, Version 2.0 (the ""License""); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an ""AS-IS"" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +""""""Tool to insert JsDoc before a function. + +This script attempts to find the first function passed in to stdin, generate +JSDoc for it (with argument names and possibly return value), and inject +it in the string. This is intended to be used as a subprocess by editors +such as emacs and vi. +"""""" + +import re +import sys + + +# Matches a typical Closure-style function definition. +_FUNCTION_REGEX = re.compile(r"""""" +# Start of line +^ + +# Indentation +(?P[ ]*) + +# Identifier (handling split across line) +(?P\w+(\s*\.\s*\w+)*) + +# ""= function"" +\s* = \s* function \s* + +# opening paren +\( + +# Function arguments +(?P(?:\s|\w+|,)*) + +# closing paren +\) + +# opening bracket +\s* { + +"""""", re.MULTILINE | re.VERBOSE) + + +def _MatchFirstFunction(script): + """"""Match the first function seen in the script."""""" + return _FUNCTION_REGEX.search(script) + + +def _ParseArgString(arg_string): + """"""Parse an argument string (inside parens) into parameter names."""""" + for arg in arg_string.split(','): + arg = arg.strip() + if arg: + yield arg + + +def _ExtractFunctionBody(script, indentation=0): + """"""Attempt to return the function body."""""" + + # Real extraction would require a token parser and state machines. + # We look for first bracket at the same level of indentation. + regex_str = r'{(.*?)^[ ]{%d}}' % indentation + + function_regex = re.compile(regex_str, re.MULTILINE | re.DOTALL) + match = function_regex.search(script) + if match: + return match.group(1) + + +def _ContainsReturnValue(function_body): + """"""Attempt to determine if the function body returns a value."""""" + return_regex = re.compile(r'\breturn\b[^;]') + + # If this matches, we assume they're returning something. + return bool(return_regex.search(function_body)) + + +def _InsertString(original_string, inserted_string, index): + """"""Insert a string into another string at a given index."""""" + return original_string[0:index] + inserted_string + original_string[index:] + + +def _GenerateJsDoc(args, return_val=False): + """"""Generate JSDoc for a function. + + Args: + args: A list of names of the argument. + return_val: Whether the function has a return value. + + Returns: + The JSDoc as a string. + """""" + + lines = [] + lines.append('/**') + + lines += [' * @param {} %s' % arg for arg in args] + + if return_val: + lines.append(' * @return') + + lines.append(' */') + + return '\n'.join(lines) + '\n' + + +def _IndentString(source_string, indentation): + """"""Indent string some number of characters."""""" + lines = [(indentation * ' ') + line + for line in source_string.splitlines(True)] + return ''.join(lines) + + +def InsertJsDoc(script): + """"""Attempt to insert JSDoc for the first seen function in the script. + + Args: + script: The script, as a string. + + Returns: + Returns the new string if function was found and JSDoc inserted. Otherwise + returns None. + """""" + + match = _MatchFirstFunction(script) + if not match: + return + + # Add argument flags. + args_string = match.group('arguments') + args = _ParseArgString(args_string) + + start_index = match.start(0) + function_to_end = script[start_index:] + + lvalue_indentation = len(match.group('indentation')) + + return_val = False + function_body = _ExtractFunctionBody(function_to_end, lvalue_indentation) + if function_body: + return_val = _ContainsReturnValue(function_body) + + jsdoc = _GenerateJsDoc(args, return_val) + if lvalue_indentation: + jsdoc = _IndentString(jsdoc, lvalue_indentation) + + return _InsertString(script, jsdoc, start_index) + + +if __name__ == '__main__': + stdin_script = sys.stdin.read() + result = InsertJsDoc(stdin_script) + + if result: + sys.stdout.write(result) + else: + sys.stdout.write(stdin_script) +","Python" +"Epigenetics","kjgaulton/pipelines","rare_variants/bin/rare-variants.epacts_skat-o.py",".py","2976","69","#!/usr/bin/env python3 + +import os +import sys +import argparse +import subprocess +import logging +from multiprocessing import Pool + + +def run_epacts(args, name): + vcf_file = os.path.join(args.proc_vcf_dir, name + '.vcf.gz') + group_file = os.path.join(args.group_dir, name + '.group') + out_prefix = os.path.join(args.out_dir, name) + epacts_cmd = [ + 'epacts', 'group', + '--vcf', vcf_file, + '--groupf', group_file, + '--out', out_prefix, + '--ped', args.ped_file, + '--test', 'skat', '--skat-o', + '--max-MAF', str(args.maximum_maf), + '--min-rsq', str(args.minimum_rsquared), + '--pheno', 'T2D', + '--cov', 'Age', + '--cov', 'Sex', + '--cov', 'PC_GoT2D_1', + '--cov', 'PC_GoT2D_2', + '--cov', 'PC_GoT2D_3', + '--cov', 'NUMSING', + '--cov', 'NUMRARE'] + try: + with open(os.devnull, 'w') as f: + subprocess.call(epacts_cmd, stderr=f) + subprocess.call(['make', '-f', out_prefix + '.Makefile', '-j', '1'], stderr=f) + for run_file in [out_prefix+'.phe', out_prefix+'.ind', out_prefix+'.Makefile', out_prefix+'.cov', out_prefix+'.epacts.OK']: + os.remove(run_file) + except Exception as e: + logging.error(e) + pass + return + +def main(args): + logging.info('Starting up.') + with open('fp.list') as f: + fp_names = f.read().splitlines() + args_list = list(zip([args for i in fp_names], fp_names)) + pool = Pool(processes=(args.threads)) + pool.starmap(process_vcf, args_list) + pool.close() + pool.join() + logging.info('Finishing up.') + return + +def process_args(): + parser = argparse.ArgumentParser(description='Run epacts for each group.') + parser.add_argument('--proc_vcf_dir', required=False, type=str, default='proc_vcfs/', help='Path to processed variants directory') + parser.add_argument('--group_dir', required=False, type=str, default='groups/', help='Path to groups directory containing group files') + parser.add_argument('--out_dir', required=False, type=str, default='skat-o/', help='Path to out directory for epacts group test') + parser.add_argument('--ped_file', required=False, type=str, default='/home/joshchiou/T2D/GoT2D.PC.ped', help='Path to PED file containing covariates') + parser.add_argument('-min_rsq', '--minimum_rsquared', required=False, type=float, default=0.6, help='Minimum R^2 value to filter variants') + parser.add_argument('-max_maf', '--maximum_maf', required=False, type=float, default=0.05, help='Maximum minor allele frequency value to filter variants') + parser.add_argument('-t', '--threads', required=False, type=int, default=48, help='Threads to run in parallel') + return parser.parse_args() + +args = process_args() +logging.basicConfig(format='[%(filename)s] %(asctime)s %(levelname)s: %(message)s', datefmt='%I:%M:%S', level=logging.DEBUG) +main(args) +","Python" +"Epigenetics","kjgaulton/pipelines","rare_variants/bin/rare-variants.make_groupfiles.py",".py","3050","67","#!/usr/bin/env python3 + +import os +import sys +import argparse +import subprocess +import logging +from multiprocessing import Pool + + +def make_groupfiles(args, name): + try: + vcf_file = os.path.join(args.proc_vcf_dir, name + '.vcf.gz') + footprints_file = os.path.join(args.footprints_dir, name + '.bed') + p1_cmd = 'zcat {}'.format(vcf_file) + p2_cmd = """"""awk '!/^#/'"""""" + p3_cmd = 'cut -f -5' + p4_cmd = """"""awk 'BEGIN{FS=OFS=""\t""} {print $1,$2-$1,$2,$1"":""$2""_""$4""/""$5}'"""""" + p5_cmd = 'bedtools intersect -a - -b {} -wa -wb'.format(footprints_file) + p_cmd = '{} | {} | {} | {} | {}'.format(p1_cmd, p2_cmd, p3_cmd, p4_cmd, p5_cmd) + intersect_out = os.path.join(args.intersect_dir, name + '.var-fp.bed') + with open(intersect_out, 'w') as f: + subprocess.call(p_cmd, stdout=f, shell=True) + + disrupt_out = os.path.join(args.disrupt_dir, name + '.disrupt.out') + disrupt_err = os.path.join(args.disrupt_dir, name + '.disrupt.err') + with open(disrupt_out, 'w') as out, open(disrupt_err, 'w') as err: + p6 = subprocess.Popen(['python3', 'motif_disruption.py', intersect_out], stdout=subprocess.PIPE, stderr=err) + p7 =subprocess.call(['awk', r'$14 <= 1.0'], stdin=p6.stdout, stdout=out) + + group_file = os.path.join(args.group_dir, name + '.group') + with open(group_file, 'w') as f, open(disrupt_out) as out: + variants = [line.split('\t')[3] for line in out.read().splitlines()] + variants = sorted(list(set(variants))) + group_line = [name] + variants + f.write('\t'.join(group_line)) + except Exception as e: + logging.error(e) + pass + return + +def main(args): + logging.info('Starting up.') + with open('fp.list') as f: + fp_names = f.read().splitlines() + args_list = list(zip([args for i in fp_names], fp_names)) + pool = Pool(processes=(args.threads)) + pool.starmap(process_vcf, args_list) + pool.close() + pool.join() + logging.info('Finishing up.') + return + +def process_args(): + parser = argparse.ArgumentParser(description='Make group files for EPACTS run.') + parser.add_argument('--proc_vcf_dir', required=True, type=str, help='Path to processed VCFs directory') + parser.add_argument('--footprints_dir', required=True, type=str, help='Path to unmerged footprints directory') + parser.add_argument('--intersect_dir', required=True, type=str, help='Path to variants-footprints intersect directory') + parser.add_argument('--disrupt_dir', required=True, type=str, help='Path to disrupted variants directory') + parser.add_argument('--group_dir', required=True, type=str, help='Path to group files directory') + parser.add_argument('-t', '--threads', required=False, type=int, default=48, help='Threads to run in parallel') + return parser.parse_args() + +args = process_args() +logging.basicConfig(format='[%(filename)s] %(asctime)s %(levelname)s: %(message)s', datefmt='%I:%M:%S', level=logging.DEBUG) +main(args) +","Python" +"Epigenetics","kjgaulton/pipelines","rare_variants/bin/rare-variants.preprocess.py",".py","3625","77","#!/usr/bin/env python3 + +import os +import sys +import argparse +import tempfile +import subprocess +import logging +from multiprocessing import Pool + + +def process_vcf(args, footprints, name): + logging.info('Processing motif: {}'.format(name)) + vcf_output = os.path.join(args.output, name + '.vcf') + with open(footprints) as f, open(vcf_output, 'w') as vcf_out: + lines = f.read().splitlines() + tmp = tempfile.TemporaryFile() + with open(args.vcf_header) as head: + vcf_out.write(head.read()) + for line in lines: + chrom, start, end, motif = line.split('\t') + vcf_file = os.path.join(args.vcf_directory, 'GoT2D.chr{}.paper_integrated_snps_indels_sv_beagle_thunder.vcf.gz'.format(chrom)) + query = '{0}:{1}-{2}'.format(chrom, start, end) + tabix_cmd = ['tabix', '-f', vcf_file, query] + subprocess.call(tabix_cmd, stdout=tmp) + tmp.seek(0) + records = [rec.decode() for rec in tmp.read().splitlines()] + for rec in records: + if len(rec.split('\t')[3]) > 1: continue + if len(rec.split('\t')[4]) > 1: continue + if rec.split('\t')[6] != 'PASS': continue + info = rec.split('\t')[7] + AC = float(info.split(';')[0].split('=')[1]) + AN = float(info.split(';')[1].split('=')[1]) + RSQ = float(info.split(';')[6].split('=')[1]) + MAF = AC/AN + if MAF > args.maximum_maf and 1-MAF > args.maximum_maf: continue + if RSQ < args.minimum_rsquared: continue + vcf_out.write('{}\n'.format(rec)) + tmp.close() + bgzip_cmd = ['bgzip', vcf_output] + index_cmd = ['tabix', vcf_output + '.gz'] + if os.path.exists(vcf_output) and os.path.getsize(vcf_output) != 0: + subprocess.call(bgzip_cmd) + if os.path.exists(vcf_output+'.gz'): + subprocess.call(index_cmd) + return + +def main(args): + logging.info('Starting up.') + with open('fp.list') as f: + fp_names = f.read().splitlines() + fp_files = ['merged-footprints/' + name + '.bed' for name in fp_names] + args_list = list(zip([args for i in fp_names], fp_files, fp_names)) + pool = Pool(processes=(args.threads)) + pool.starmap(process_vcf, args_list) + pool.close() + pool.join() + logging.info('Finishing up.') + return + +def process_args(): + parser = argparse.ArgumentParser(description='Make VCF files for each footprint motif.') + #parser.add_argument('-i', '--footprints', required=True, type=str, help='Path to footprints file') + parser.add_argument('-o', '--output', required=True, type=str, help='Path to output directory') + #parser.add_argument('-n', '--name', required=True, type=str, help='Output name to prepend to file') + parser.add_argument('-vcf_dir', '--vcf_directory', required=True, type=str, help='Path to directory containing tabix-indexed vcfs') + parser.add_argument('-head', '--vcf_header', required=False, type=str, default='etc/header.txt', help='Path to vcf header') + parser.add_argument('-min_rsq', '--minimum_rsquared', required=False, type=float, default=0.6, help='Minimum R^2 value to filter variants') + parser.add_argument('-max_maf', '--maximum_maf', required=False, type=float, default=0.05, help='Maximum minor allele frequency value to filter variants') + parser.add_argument('-t', '--threads', required=False, type=int, default=48, help='Threads to run in parallel') + return parser.parse_args() + +args = process_args() +logging.basicConfig(format='[%(filename)s] %(asctime)s %(levelname)s: %(message)s', datefmt='%I:%M:%S', level=logging.DEBUG) +main(args) +","Python" +"Epigenetics","kjgaulton/pipelines","infer_footprints/infer-footprints.py",".py","3965","154","#!/usr/bin/env python3 + +#------------------------------------------------------------------------------# +# infer-footprints.py # +#------------------------------------------------------------------------------# + +# Script to streamline the peak-calling and footprinting pipeline + + + + +#--------------------------------- Imports ------------------------------------# + +import argparse +import gzip +import os.path +import sys +import tempfile + +sys.path.append('/home/data/kglab-python3-modules') +sys.path.append('/lab/kglab-python3-modules') + +import chippeaks +import footprints +import seqalign +import hg19 + + + + +#--------------------------- Function definitions -----------------------------# + +def main(args): + with seqalign.SequenceAlignment( + input_file=(args.input, args.in2) if args.in2 else args.input, + phred_quality_score=args.qual, + processes=args.max_processes, + aligner=seqalign.BwaAligner( + reference_genome_path=args.reference_genome, + trim=args.trim_reads + ) + ) as sa: + sa.remove_supplementary_alignments() + sa.samtools_sort(memory_limit=args.memory_limit) + sa.samtools_index() + bam = sa.bam + bam_index = sa.index + + with chippeaks.ChipPeaks(treatment_bam=bam, nomodel=True, shift=-100) as cp: + cp.blacklist(args.blacklist) + peaks = cp.peaks_narrowPeak + + with footprints.Footprints( + input_bam=bam, + input_bam_index=bam_index, + input_peaks=peaks, + reference_genome_path=args.reference_genome, + motifs_db_path=args.motifs_db_path, + centipede_path=args.centipede_path, + processes=args.max_processes + ) as fp: + fp.cleans_up_footprints = False + fp.dump_json(args.output) + footprints_dict = fp.footprints + + + + +# Parse arguments +def parse_arguments(): + parser = argparse.ArgumentParser( + description=( + 'Pipeline for peak calling' + ) + ) + required_group = parser.add_argument_group('required arguments') + required_group.add_argument( + '-i', + '--input', + required=True, + help='Input file--reads or BAM' + ) + required_group.add_argument( + '-o', + '--output', + required=True, + help='Output file--where to put the DNase footprints.' + ) + required_group.add_argument( + '--memory-limit', + required=True, + type=int, + help='Approximate memory limit for samtools sort, in gigabytes' + ) + required_group.add_argument( + '--blacklist', + required=True, + help='Encode blacklist file' + ) + required_group.add_argument( + '--motifs-db-path', + required=True, + help='Path to motifs database' + ) + optional_group = parser.add_argument_group('optional arguments') + optional_group.add_argument( + '-i2', + '--in2', + help='For paired-end reads' + ) + optional_group.add_argument( + '-q', + '--qual', + default='30', + help='cutoff Phred score for filtering out FASTQ reads' + ) + optional_group.add_argument( + '--max-processes', + type=int, + default=1, + help='Maximum number of processes allowed' + ) + optional_group.add_argument( + '--trim-reads', + type=int, + help='Trimming reads???? idek' + ) + optional_group.add_argument( + '--motifs-list', + help='List of motifs' + ) + optional_group.add_argument( + '--centipede-path', + help='Path to R script for centipede' + ) + optional_group.add_argument( + '--reference-genome', + default=hg19.path, + help='Path to reference genome' + ) + + args = parser.parse_args() + + return args + + + + +#--------------------------------- Execute ------------------------------------# + +if __name__ == '__main__': + args = parse_arguments() + main(args) +","Python" +"Epigenetics","kjgaulton/pipelines","bulk_ATAC-seq/bulk_ATAC-seq_pipeline.py",".py","12758","291","#!/usr/bin/env python3 + +import argparse +import subprocess +import os +import sys +import reprlib +import logging + +#=======================================================# + +def detect_file_format(args): + if args.paired1.endswith('.gz') and args.paired2.endswith('.gz'): + return args.paired1, args.paired2 + if args.paired1.endswith('.bz2') and args.paired2.endswith('.bz2'): + logging.info('BZ2 file format detected -- converting to GZ file format.') + p1_bn, p2_bn = args.paired1.split('.bz2')[0], args.paired2.split('.bz2')[0] + subprocess.call(['bunzip2', args.paired1, args.paired2]) + subprocess.call(['gzip', p1_bn, p2_bn]) + args.paired1, args.paired2 = p1_bn + '.gz', p2_bn + '.gz' + return args.paired1, args.paired2 + if args.paired1.endswith('.fastq') and args.paired2.endswith('.fastq'): + logging.info('Unzipped FASTQ format detected -- converting to GZ file format.') + subprocess.call(['gzip', args.paired1, args.paired2]) + args.paired1, args.paired2 = args.paired1 + '.gz', args.paired2 + '.gz' + return args.paired1, args.paired2 + if args.paired1.endswith('.fq') and args.paired2.endswith('.fq'): + logging.info('Unzipped FQ format detected -- converting to GZ file format.') + p1_bn, p2_bn = args.paired1.split('.fq')[0] + '.fastq', args.paired2.split('.fq')[0] + '.fastq' + os.rename(args.paired1, p1_bn) + os.rename(args.paired2, p2_bn) + subprocess.call(['gzip', p1_bn, p2_bn]) + args.paired1, args.paired2 = p1_bn + '.gz', p2_bn + '.gz' + return args.paired1, args.paired2 + else: + logging.error('Unknown file format or paired end reads have different file formats.') + raise RuntimeError('Paired end reads must be in a valid file format!') + return + +#=======================================================# + +def trim_galore(args): + trim_galore_cmd = ['trim_galore', '--fastqc', '-q', '10', '-o', args.output, '--paired', args.paired1, args.paired2] + with open(os.devnull, 'w') as f: + subprocess.call(trim_galore_cmd, stderr=f, stdout=f) + trim_output_1 = os.path.join(args.output, os.path.basename(args.paired1).split('.fastq.gz')[0] + '_val_1.fq.gz') + trim_output_2 = os.path.join(args.output, os.path.basename(args.paired2).split('.fastq.gz')[0] + '_val_2.fq.gz') + return trim_output_1, trim_output_2 + +#=======================================================# + +def process_reads(args): + output_prefix = os.path.join(args.output, args.name) + align_log = output_prefix + '.align.log' + sort_bam = output_prefix + '.sort.bam' + md_bam = output_prefix + '.sort.md.bam' + rmdup_bam = output_prefix + '.sort.filt.rmdup.bam' + + bwa_mem_cmd = ['bwa', 'mem', '-M', '-t', str(args.threads), args.reference, args.paired1, args.paired2] + samtools_sort_cmd = ['samtools', 'sort', '-m', '{}G'.format(args.memory), '-@', str(args.threads), '-'] + + with open(align_log, 'w') as log, open(sort_bam, 'w') as bam_out: + bwa_mem = subprocess.Popen(bwa_mem_cmd, stdout=subprocess.PIPE, stderr=log) + subprocess.call(samtools_sort_cmd, stdin=bwa_mem.stdout, stdout=bam_out, stderr=log) + + metrics_file = output_prefix + '.picard_rmdup_metrics.txt' + + md_cmd = [ + 'java', '-Xmx{}G'.format(args.memory), + '-jar', args.picard_mark_dup, + 'INPUT={}'.format(sort_bam), + 'OUTPUT={}'.format(md_bam), + 'REMOVE_DUPLICATES=false', + 'ASSUME_SORTED=true', + 'VALIDATION_STRINGENCY=LENIENT', + 'METRICS_FILE={}'.format(metrics_file)] + rmdup_cmd = [ + 'samtools', 'view', + '-b', '-h', '-f', '3', + '-F', '4', '-F', '256', + '-F', '1024', '-F', '2048', + '-q', str(args.quality), + md_bam] + + autosomal_chr = ['chr' + str(c) for c in range(1,23)] + rmdup_cmd.extend(autosomal_chr) + + if os.path.exists(sort_bam) and os.path.getsize(sort_bam) != 0: + with open(os.devnull, 'w') as f: + subprocess.call(md_cmd, stderr=f) + if os.path.exists(md_bam) and os.path.getsize(md_bam) != 0: + subprocess.call(['samtools', 'index', md_bam]) + with open(rmdup_bam, 'w') as f: + subprocess.call(rmdup_cmd, stdout=f) + subprocess.call(['samtools', 'index', rmdup_bam]) + + return md_bam, rmdup_bam + +#=======================================================# + +def call_peaks(args, input_bam): + macs2_log = os.path.join(args.output, '.'.join([args.name, 'macs2_callpeaks.log'])) + macs2_cmd = ['macs2', 'callpeak', + '-t', input_bam, + '--outdir', args.output, + '-n', args.name, + '-g', args.macs2_genome, + '--nomodel', '-B', + '--shift', '-100', + '--extsize', '200', + '--keep-dup', 'all'] + with open(macs2_log, 'w') as f: + subprocess.call(macs2_cmd, stderr=f) + return + +#=======================================================# + +def make_bedgraph(args): + bdgcmp_log = os.path.join(args.output, '.'.join([args.name, 'bdgcmp.log'])) + bdgcmp_cmd = [ + 'macs2', 'bdgcmp', + '-t', os.path.join(args.output, args.name + '_treat_pileup.bdg'), + '-c', os.path.join(args.output, args.name + '_control_lambda.bdg'), + '-m', 'ppois', + '--outdir', args.output, + '--o-prefix', args.name, + '-p', '0.00001'] + with open(bdgcmp_log, 'w') as f: + subprocess.call(bdgcmp_cmd, stderr=f) + + bdgcmp_out = os.path.join(args.output, args.name + '_ppois.bdg') + + bdg_label = 'track type=bedGraph name=\""{0}\"" description=\""{0}, ATAC signal\"" visibility=2 color={1} altColor=0,0,0 autoScale=off maxHeightPixels=64:64:32'.format(args.name, args.bdg_color) + sorted_bdg = os.path.join(args.output, args.name + '_ppois.sorted.bdg') + sort_cmd = ['sort', '-k', '1,1', '-k', '2,2n', bdgcmp_out] + with open(sorted_bdg, 'w') as f: + print(bdg_label, file=f) + with open(sorted_bdg, 'a') as f: + subprocess.call(sort_cmd, stdout=f) + subprocess.call(['gzip', sorted_bdg]) + os.remove(bdgcmp_out) + + narrow_peaks = os.path.join(args.output, args.name + '_peaks.narrowPeak') + peak_label = 'track type=narrowPeak name=\""{0} peaks\"" description=\""{0}, ATAC peaks\"" color={1}'.format(args.name, args.bdg_color) + peaks = open(narrow_peaks).read().splitlines() + with open(narrow_peaks, 'w') as f: + print(peak_label, file=f) + for p in peaks: + print(p, file=f) + + return + +#=======================================================# + +def get_qc_metrics(args, md_bam): + ATAC_peaks = os.path.join(args.output, args.name + '_peaks.narrowPeak') + qc_json = os.path.join(args.output, args.name + '.ataqv.json.gz') + qc_log = os.path.join(args.output, args.name + '.ataqv.log') + qc_cmd = [ + 'ataqv', '--verbose', + '--metrics-file', qc_json, + '--peak-file', ATAC_peaks, + '--tss-file', args.tss, + '--tss-extension', '1000', + '--excluded-region-file', args.blacklist, + '--name', args.name, + '--description', 'Gaulton lab ATAC sample {}'.format(args.name), + '--mitochondrial-reference-name', 'chrM', + '--threads', str(args.threads), + 'human', md_bam] + with open(qc_log, 'w') as f, open(os.devnull, 'w') as n: + subprocess.call(qc_cmd, stdout=f, stderr=n) + return + +#=======================================================# + +def cleanup(args): + read_1_name = os.path.basename(args.paired1).split('.fastq.gz')[0] + read_2_name = os.path.basename(args.paired2).split('.fastq.gz')[0] + #trim_tmp_1 = os.path.join(args.output, read_1_name + '_trimmed.fq.gz') + #trim_tmp_2 = os.path.join(args.output, read_2_name + '_trimmed.fq.gz') + fastqc_zip_1 = os.path.join(args.output, read_1_name + '_val_1_fastqc.zip') + fastqc_zip_2 = os.path.join(args.output, read_2_name + '_val_2_fastqc.zip') + clean = [fastqc_zip_1, fastqc_zip_2] + try: + for f in clean: + os.remove(f) + except: + pass + return + +#=======================================================# + +def main(args): + logging.info('Starting up.') + if not os.path.isdir(args.output): + try: + os.makedirs(args.output) + except OSError: + pass + + args.paired1, args.paired2 = detect_file_format(args) + + if not args.skip_trim: + try: + logging.info('Trimming reads with trim_galore.') + args.paired1, args.paired2 = trim_galore(args) + except Exception as e: + logging.error('Failed during adaptor trimming step with trim_galore.') + print('Check options -p1 and -p2: ' + repr(e), file=sys.stderr) + sys.exit(1) + if not args.skip_align: + try: + logging.info('Aligning reads with bwa and filtering reads with samtools.') + md_bam, rmdup_bam = process_reads(args) + except Exception as e: + logging.error('Failed during alignment step with bwa mem.') + print(repr(e), file=sys.stderr) + sys.exit(1) + if not args.skip_peaks: + try: + logging.info('Calling peaks with MACS2.') + call_peaks(args, rmdup_bam) + except Exception as e: + logging.error('Failed during MACS2 peak calling step.') + print(repr(e), file=sys.stderr) + sys.exit(1) + if not args.skip_bdg: + try: + logging.info('Generating signal track with MACS2.') + make_bedgraph(args) + except Exception as e: + logging.error('Failed during bedgraph generation step.') + print(repr(e), file=sys.stderr) + sys.exit(1) + logging.info('Cleaning up temporary files.') + if not args.skip_qc: + try: + logging.info('Starting up QC using ataqv.') + get_qc_metrics(args, md_bam) + except Exception as e: + logging.error('Failed during QC step.') + print(repr(e), file=sys.stderr) + sys.exit(1) + if not args.skip_cleanup: + cleanup(args) + logging.info('Finishing up.') + return + +#=======================================================# + +def process_args(): + parser = argparse.ArgumentParser(description='Pipeline for ATAC-seq to trim reads, align them to a reference genome, call peaks, and generate a genome browser signal track.') + + io_group = parser.add_argument_group('I/O arguments') + io_group.add_argument('-p1', '--paired1', required=False, type=str, help='Path to paired reads (1)') + io_group.add_argument('-p2', '--paired2', required=False, type=str, help='Path to paired reads (2)') + io_group.add_argument('-o', '--output', required=True, type=str, help='Output directory for processed files') + io_group.add_argument('-n', '--name', required=False, type=str, default='sample', help='Output sample name to prepend') + + align_group = parser.add_argument_group('Alignment arguments') + align_group.add_argument('-t', '--threads', required=False, type=int, default=4, help='Number of threads to use [4]') + align_group.add_argument('-m', '--memory', required=False, type=int, default=8, help='Maximum memory (in Gb) per thread for samtools sort [8]') + align_group.add_argument('-q', '--quality', required=False, type=int, default=30, help='Mapping quality cutoff for samtools [30]') + align_group.add_argument('-ref', '--reference', required=False, type=str, default='/home/joshchiou/references/male.hg19.fa', help='Path to reference genome [/home/joshchiou/references/male.hg19.fa]') + align_group.add_argument('--picard_mark_dup', required=False, type=str, default='/home/joshchiou/bin/MarkDuplicates.jar', help='Path to picard MarkDuplicates.jar [/home/joshchiou/bin/MarkDuplicates.jar]') + + qc_group = parser.add_argument_group('QC arguments') + qc_group.add_argument('--tss', required=False, type=str, default='/home/joshchiou/references/hg19_gencode_tss_unique.bed', help='Path to TSS definitions for calculating ATAC signal enrichment around TSS [/home/joshchiou/references/hg19_gencode_tss_unique.bed]') + qc_group.add_argument('--blacklist', required=False, type=str, default='/home/joshchiou/references/ENCODE.hg19.blacklist.bed', help='Path to blacklist BED file to ignore ENCODE high signal regions [/home/joshchiou/references/ENCODE.hg19.blacklist.bed]') + + bedgraph_group = parser.add_argument_group('Signal track arguments') + bedgraph_group.add_argument('--macs2_genome', required=False, type=str, default='hs', help='MACS2 genome (e.g. hs or mm) for peak calling') + bedgraph_group.add_argument('--bdg_color', required=False, type=str, default='0,0,0', help='Color for genome browser signal track in R,G,B [0,0,0]') + + skip_group = parser.add_argument_group('Skip processing steps') + skip_group.add_argument('--skip_trim', required=False, action='store_true', default=False, help='Skip adapter trimming step [OFF]') + skip_group.add_argument('--skip_align', required=False, action='store_true', default=False, help='Skip read alignment step [OFF]') + skip_group.add_argument('--skip_peaks', required=False, action='store_true', default=False, help='Skip calling peaks step [OFF]') + skip_group.add_argument('--skip_bdg', required=False, action='store_true', default=False, help='Skip making genome browser track [OFF]') + skip_group.add_argument('--skip_qc', required=False, action='store_true', default=False, help='Skip ATAC qc step using ataqv [OFF]') + skip_group.add_argument('--skip_cleanup', required=False, action='store_true', default=False, help='Skip cleanup operations [OFF]') + + return parser.parse_args() + +#=======================================================# +if __name__ == '__main__': + logging.basicConfig(format='[%(filename)s] %(asctime)s %(levelname)s: %(message)s', datefmt='%I:%M:%S', level=logging.DEBUG) + args = process_args() + main(args) +","Python" +"Epigenetics","kjgaulton/pipelines","fgwas_workflow/fgwas-workflow.py",".py","43945","1310","#!/usr/bin/env python3 +#------------------------------------------------------------------------------# +# fgwas-workflow.py # +#------------------------------------------------------------------------------# + +# Apply the workflow suggested by the fgwas manual + + + + +#-------------------------------- Imports -------------------------------------# + +import argparse +import gzip +import os +import subprocess +import operator +import itertools +from multiprocessing import Pool + + + + +#---------------------------- Class definitions -------------------------------# + +class InputFileHeader(): + ''' + The header of the input file + ''' + + non_annotation_column_names = { + 'SNPID', + 'CHR', + 'POS', + 'Z', + 'F', + 'N', + 'NCASE', + 'NCONTROL', + 'LNBF', + 'SEGNUMBER' + } + + def __init__(self, args): + self.args = args + with gzip.open(args.input, 'rt') as f: + self.tuple = tuple(f.readline().replace('\n', '').split(' ')) + self.annotations = { + column_name + for + column_name + in + self.tuple + if + column_name + not + in + self.non_annotation_column_names + } + + def validate(self): + ''' + Validate the input file header + ''' + for column_name in self.non_annotation_column_names: + if self.tuple.count(column_name) > 1: + raise SystemExit( + ( + 'ERROR: Invalid header on input file: Either {0} is ' + 'duplicated, or there is an annotation called {0}.' + ).format(column_name) + ) + elif ( + ( + column_name + not + in + {'N', 'NCASE', 'NCONTROL', 'LNBF', 'SEGNUMBER'} + ) + and + ( + column_name + not + in + self.tuple + ) + ): + raise SystemExit( + ( + 'ERROR: Invalid header on input file: {} is missing.' + ).format(column_name) + ) + if {'N', 'NCASE', 'NCONTROL'} <= set(self.tuple): + raise SystemExit( + 'ERROR: N, NCASE, and NCONTROL were all found in the input ' + 'file header. Please use EITHER quantitative OR case-control ' + 'format.' + ) + + + + +class IndividualAnnotationResults(): + ''' + Individual annotation results + ''' + + def __init__(self, args, header): + self.args = args + self.annotations = header.annotations + self.data = None + self.defined_ci_annotations = set() + self.header = header + + def collect(self): + ''' + Collect individual annotation results + ''' + with Pool(processes=min(args.processes, len(self.annotations))) as pool: + self.data = ( + ( + ('parameter', 'ln(lk)', 'CI_lo', 'estimate', 'CI_hi'), + ) + + + tuple( + sorted( + pool.starmap( + collect_individual_annotation_result, + ( + (args, annotation, self.header) + for + annotation + in + self.annotations + ) + ), + key=operator.itemgetter(1), + reverse=True + ) + ) + ) + + def export(self): + ''' + Export individual annotation results + ''' + if self.data: + with open( + '{}-individual-annotation-results.txt'.format(args.output), + 'w' + ) as f: + f.write( + '\n'.join( + '\t'.join((str(entry) for entry in line)) + for + line + in + self.data + ) + + + '\n' + ) + else: + raise Exception( + 'Cannot export individual annotation results with no data ' + 'present.' + ) + + def identify_defined_ci_annotations(self): + if self.data: + for parameter, llk, ci_lo, estimate, ci_hi in self.data[1:]: + try: + float(ci_lo) + float(ci_hi) + self.defined_ci_annotations.add( + parameter.replace('_ln', '') + ) + except ValueError: + pass + if not self.defined_ci_annotations: + raise SystemExit( + 'None of the provided annotations were viable (all ' + 'individual results had undefined confidence intervals). ' + 'Terminating analysis.' + ) + + def identify_best_starting_state(self): + if self.data: + best_individual_llk = max( + float(llk) + for + parameter, llk, ci_lo, estimate, ci_hi + in + self.data[1:] + ) + best_individual_annotations = [] + for parameter, llk, ci_lo, estimate, ci_hi in self.data[1:]: + if ( + float(llk) == best_individual_llk + and + ( + ( + parameter.replace('_ln', '') + in + self.defined_ci_annotations + ) + if + self.defined_ci_annotations + else + True + ) + ): + best_individual_annotations.append( + (parameter, llk, ci_lo, estimate, ci_hi) + ) + if len(best_individual_annotations) == 1: + best_individual_annotation = best_individual_annotations[0] + self.best_starting_state = { + 'annotations': [best_individual_annotation[0]], + 'llk': best_individual_annotation[1], + 'estimates': { + best_individual_annotation[0]: + best_individual_annotation[2:] + }, + 'xvl': float('-inf'), + 'xv_penalty': 0, + 'output_files': {} + } + elif len(best_individual_annotations) > 1: + annotation_combinations = tuple( + itertools.chain.from_iterable( + itertools.combinations( + ( + parameter + for + parameter, llk, ci_lo, estimate, ci_hi + in + best_individual_annotations + ), + length + ) + for + length + in + range(2, len(best_individual_annotations) + 1) + ) + ) + with Pool( + processes=min( + self.args.processes, + len(annotation_combinations) + ) + ) as pool: + pool.map( + call_fgwas, + ( + { + 'args': self.args, + 'annotation': + '+'.join( + self.annotations + + + list(annotation_combination) + ), + 'tag': + '+'.join( + annotation_combination + ), + 'header': individual_results.header + } + for + annotation_combination + in + annotation_combinations + ) + ) + llk_list = [] + for annotation_combination in annotation_combinations: + with open( + '{}-{}.llk' + .format( + args.output, + '+'.join(annotation_combination) + ) + ) as f: + llk_list.append( + ( + float( + f + .readline() + .replace('ln(lk): ', '') + .replace('\n', '') + ), + annotation_combination + ) + ) + best_combo_llk = max( + llk + for + llk, annotation_combination + in + llk_list + ) + best_combos = tuple( + annotation_combination + for + llk, annotation_combination + in + llk_list + if + llk == best_combo_llk + ) + if ( + (best_combo_llk > best_individual_llk) + and + len(best_combos) == 1 + ): + best_combo = list(best_combos[0]) + estimates = {} + with open( + '{}-{}.params' + .format(args.output, '+'.join(best_combo)) + ) as f: + for line in f: + parsed_line = tuple( + line.replace('\n', '').split(' ') + ) + parameter = parsed_line[0][:-3] + for annotation in self.annotations: + if annotation == parameter: + estimates[annotation] = tuple( + parsed_line[1:] + ) + break + self.best_starting_state = { + 'annotations': best_combo, + 'llk': best_combo_llk, + 'estimates': estimates, + 'xvl': float('-inf'), + 'xv_penalty': 0, + 'output_files': {} + } + else: + print( + 'Next best annotation is ambiguous, taking a null ' + 'step and proceeding to cross-validation phase' + ) + for annotation in set( + '+'.join(combo) + for + combo + in + annotation_combinations + ): + clean_up_intermediate_files( + args, + '{}-{}.', + annotation + ) + else: + raise Exception( + 'Cannot identify annotations with with well-defined confidence ' + 'intervals with no data present.' + ) + + + + + +class FgwasModel(): + ''' + An FGWAS model + ''' + + def __init__(self, args): + self.args = args + if self.args.initialize: + self.annotations = self.args.annotations.split('+') + self.llk = args.llk + else: + self.annotations = [] + self.llk = float('-inf') + self.estimates = {} + self.xvl = float('-inf') + self.cross_validation_penalty = 0 + self.output_files = {} + self.cache() + + def cache(self): + ''' + Cache the model state + ''' + self.annotations_cache = list(self.annotations) + self.llk_cache = float(self.llk) + self.estimates_cache = dict(self.estimates) + self.xvl_cache = float(self.xvl) + self.cross_validation_penalty_cache = float( + self.cross_validation_penalty + ) + self.output_files_cache = dict(self.output_files) + + def revert(self): + ''' + Revert to the cached model state + ''' + self.annotations = self.annotations_cache + self.llk = self.llk_cache + self.estimates = self.estimates_cache + self.xvl = self.xvl_cache + self.cross_validation_penalty = self.cross_validation_penalty_cache + self.output_files = self.output_files_cache + print('Reverted last step') + + def clear(self): + ''' + Clear the model to an empty state + ''' + self.cache() + self.annotations = [] + self.llk = float('-inf') + self.estimates = {} + self.xvl = float('-inf') + self.cross_validation_penalty = 0 + self.output_files = {} + + def set_state(self, state): + ''' + Set the model state according to a dictionary definition + ''' + self.cache() + self.annotations = state['annotations'] + self.llk = state['llk'] + self.estimates = state['estimates'] + self.xvl = state['xvl'] + self.cross_validation_penalty = state['xv_penalty'] + self.output_files = state['output_files'] + + def collect_output_files(self, annotation): + ''' + Collect the output files tagged with a specific annotation + ''' + for extension in ('llk', 'params', 'ridgeparams'): + with open( + '{}-{}.{}'.format(self.args.output, annotation, extension), + 'r' + ) as f: + self.output_files[extension] = f.read() + for extension in ('bfs', 'segbfs'): + with gzip.open( + '{}-{}.{}.gz'.format(self.args.output, annotation, extension), + 'rb' + ) as f: + self.output_files[extension] = f.read() + + def export(self, tag): + ''' + Export the output file state + ''' + for extension in ('llk', 'params', 'ridgeparams'): + with open( + '{}-{}.{}'.format(self.args.output, tag, extension), + 'w' + ) as f: + f.write(self.output_files[extension]) + for extension in ('bfs', 'segbfs'): + with gzip.open( + '{}-{}.{}.gz'.format(self.args.output, tag, extension), + 'wb' + ) as f: + f.write(self.output_files[extension]) + + def append(self, annotation, header): + ''' + Append an annotation to the model and determine the resulting joint + model + ''' + self.cache() + self.annotations.append(annotation) + call_fgwas( + { + 'args': self.args, + 'annotation': '+'.join(self.annotations), + 'header': header + } + ) + with open( + '{}-{}.llk'.format(args.output, annotation.split('+')[-1]) + ) as f: + self.llk = float( + f.readline().replace('ln(lk): ', '').replace('\n', '') + ) + + with open( + '{}-{}.params'.format(args.output, annotation.split('+')[-1]) + ) as f: + for line in f: + parsed_line = tuple(line.replace('\n', '').split(' ')) + parameter = parsed_line[0][:-3] + for annotation in self.annotations: + if annotation == parameter: + self.estimates[annotation] = tuple(parsed_line[1:]) + break + clean_up_intermediate_files(args, '{}-{}.', annotation) + + def append_best_annotation(self, individual_results): + ''' + Identify the next best annotation, append it to the model, and + determine the resulting joint model + ''' + self.cache() + remaining_annotations = { + annotation + for + annotation + in + individual_results.defined_ci_annotations + if + annotation + not + in + self.annotations + } + with Pool( + processes=min( + self.args.processes, + len(remaining_annotations) + ) + ) as pool: + pool.map( + call_fgwas, + ( + { + 'args': self.args, + 'annotation': '+'.join(self.annotations + [annotation]), + 'header': individual_results.header + } + for + annotation + in + remaining_annotations + ) + ) + llk_list = [] + for annotation in remaining_annotations: + positive_estimate = False + with open( + '{}-{}.params'.format(args.output, annotation) + ) as f: + for line in f: + parameter, ci_lo, estimate, ci_hi = ( + line + .replace('\n', '') + .split(' ') + ) + if ( + (parameter.replace('_ln', '') == annotation) + and + (float(estimate) > 0) + ): + positive_estimate = True + if ( + positive_estimate + if + individual_results.args.positive_estimates_only + else + True + ): + with open( + '{}-{}.llk'.format(args.output, annotation) + ) as f: + llk_list.append( + ( + float( + f + .readline() + .replace('ln(lk): ', '') + .replace('\n', '') + ), + annotation + ) + ) + if individual_results.args.positive_estimates_only: + print( + '{} annotations can be added with positive parameter estimates' + .format(len(llk_list)) + ) + if len(llk_list) == 0: + print('No more annotations can be added') + else: + best_llk = max(llk for llk, annotation in llk_list) + best_annotations = tuple( + annotation + for + llk, annotation + in + llk_list + if + llk == best_llk + ) + if len(best_annotations) == 1: + best_annotation = best_annotations[0] + self.llk = best_llk + self.annotations.append(best_annotation) + with open( + '{}-{}.params'.format(args.output, best_annotation) + ) as f: + for line in f: + parsed_line = tuple(line.replace('\n', '').split(' ')) + parameter = parsed_line[0][:-3] + for annotation in self.annotations: + if annotation == parameter: + self.estimates[annotation] = tuple( + parsed_line[1:] + ) + break + self.collect_output_files(best_annotation) + for annotation in remaining_annotations: + clean_up_intermediate_files(args, '{}-{}.', annotation) + print( + 'Added {} to joint model (llk: {})' + .format(best_annotation, str(best_llk)) + ) + elif len(best_annotations) > 1: + annotation_combinations = tuple( + itertools.chain.from_iterable( + itertools.combinations(best_annotations, length) + for + length + in + range(2, len(best_annotations) + 1) + ) + ) + with Pool( + processes=min( + self.args.processes, + len(annotation_combinations) + ) + ) as pool: + pool.map( + call_fgwas, + ( + { + 'args': self.args, + 'annotation': + '+'.join( + self.annotations + + + list(annotation_combination) + ), + 'tag': + '+'.join( + annotation_combination + ), + 'header': individual_results.header + } + for + annotation_combination + in + annotation_combinations + ) + ) + llk_list = [] + for annotation_combination in annotation_combinations: + with open( + '{}-{}.llk' + .format( + args.output, + '+'.join(annotation_combination) + ) + ) as f: + llk_list.append( + ( + float( + f + .readline() + .replace('ln(lk): ', '') + .replace('\n', '') + ), + annotation_combination + ) + ) + best_combo_llk = max( + llk + for + llk, annotation_combination + in + llk_list + ) + best_combos = tuple( + annotation_combination + for + llk, annotation_combination + in + llk_list + if + llk == best_combo_llk + ) + if (best_combo_llk > best_llk) and len(best_combos) == 1: + best_combo = list(best_combos[0]) + self.llk = best_combo_llk + self.annotations.extend(best_combo) + with open( + '{}-{}.params' + .format(args.output, '+'.join(best_combo)) + ) as f: + for line in f: + parsed_line = tuple( + line.replace('\n', '').split(' ') + ) + parameter = parsed_line[0][:-3] + for annotation in self.annotations: + if annotation == parameter: + self.estimates[annotation] = tuple( + parsed_line[1:] + ) + break + self.collect_output_files('+'.join(best_combo)) + print( + 'Added {} to joint model (llk: {})' + .format('+'.join(best_combo), str(best_llk)) + ) + else: + print( + 'Next best annotation is ambiguous, taking a null ' + 'step and proceeding to cross-validation phase' + ) + for annotation in remaining_annotations.union( + set( + '+'.join(combo) + for + combo + in + annotation_combinations + ) + ): + clean_up_intermediate_files( + args, + '{}-{}.', + annotation + ) + + def calibrate_cross_validation_penalty(self, header): + ''' + Calibrate the cross validation penalty + ''' + xv_penalties = tuple( + 0.5 * x / max(args.processes, 10) + for + x + in + range(1, max(args.processes, 10) + 1) + ) + with Pool(processes=args.processes) as pool: + pool.map( + call_fgwas, + tuple( + { + 'args': self.args, + 'annotation': '+'.join(self.annotations), + 'header': header, + 'xv_penalty': xv_penalty + } + for + xv_penalty + in + xv_penalties + ) + ) + xv_likelihoods = [] + for xv_penalty in xv_penalties: + with open( + '{}-p{}.ridgeparams'.format(args.output, str(xv_penalty)), + 'r' + ) as f: + xv_likelihoods.append( + ( + float( + f + .read() + .split('\n')[-2] + .replace('X-validation penalize ln(lk): ', '') + .replace('\n', '') + ), + xv_penalty + ) + ) + clean_up_intermediate_files(args, '{}-p{}.', str(xv_penalty)) + best_xvl_penalty = ( + sorted(xv_likelihoods, key=operator.itemgetter(0), reverse=True) + [0] + ) + self.xvl = best_xvl_penalty[0] + self.cross_validation_penalty = best_xvl_penalty[1] + + def remove_worst_annotation(self, header): + ''' + Identify the annotation contributing least to the model and remove it + ''' + if len(self.annotations) < 2: + raise Exception( + 'Can\'t remove annotations from a model with only one ' + 'annotation.' + ) + self.cache() + with Pool( + processes=min( + self.args.processes, + len(self.annotations) + ) + ) as pool: + pool.map( + call_fgwas, + ( + { + 'args': self.args, + 'annotation': annotation_0, + 'header': header, + 'xv_penalty': self.cross_validation_penalty, + 'drop': '+'.join( + annotation_1 + for + annotation_1 + in + self.annotations + if + (annotation_0 != annotation_1) + ) + } + for + annotation_0 + in + self.annotations + ) + ) + xvl_list = [] + for annotation in self.annotations: + with open( + '{}-{}.ridgeparams'.format(args.output, annotation), + 'r' + ) as f: + xvl_list.append( + ( + float( + f + .read() + .split('\n')[-2] + .replace('X-validation penalize ln(lk): ', '') + .replace('\n', '') + ), + annotation + ) + ) + best_xvl = max(xvl for xvl, annotation in xvl_list) + worst_annotations = tuple( + annotation + for + xvl, annotation + in + xvl_list + if + xvl == best_xvl + ) + if len(worst_annotations) == 1: + worst_annotation = worst_annotations[0] + self.xvl = best_xvl + self.annotations.remove(worst_annotation) + with open( + '{}-{}.params'.format(args.output, worst_annotation) + ) as f: + for line in f: + parsed_line = tuple(line.replace('\n', '').split(' ')) + parameter = parsed_line[0][:-3] + for annotation in self.annotations: + if annotation == parameter: + self.estimates[annotation] = tuple( + parsed_line[1:] + ) + break + self.collect_output_files(worst_annotation) + for annotation in self.annotations_cache: + clean_up_intermediate_files(args, '{}-{}.', annotation) + print( + 'Dropped {} from joint model (xvl: {})' + .format(worst_annotation, str(best_xvl)) + ) + elif len(worst_annotations) > 1: + annotation_combinations = tuple( + itertools.chain.from_iterable( + itertools.combinations(worst_annotations, length) + for + length + in + range(2, len(worst_annotations) + 1) + ) + ) + with Pool( + processes=min( + self.args.processes, + len(annotation_combinations) + ) + ) as pool: + pool.map( + call_fgwas, + ( + { + 'args': self.args, + 'annotation': + '+'.join( + self.annotations + + + list(annotation_combination) + ), + 'tag': + '+'.join( + sorted(annotation_combination) + ), + 'header': header, + 'xv_penalty': self.cross_validation_penalty, + 'drop': '+'.join( + annotation + for + annotation + in + self.annotations + if + (annotation not in annotation_combination) + ) + } + for + annotation_combination + in + annotation_combinations + ) + ) + xvl_list = [] + for annotation_combination in annotation_combinations: + with open( + '{}-{}.ridgeparams' + .format( + args.output, + '+'.join(sorted(annotation_combination)) + ) + ) as f: + xvl_list.append( + ( + float( + f + .read() + .split('\n')[-2] + .replace( + 'X-validation penalize ln(lk): ', + '' + ) + .replace('\n', '') + ), + annotation_combination + ) + ) + best_combo_xvl = max( + xvl + for + xvl, annotation_combination + in + xvl_list + ) + best_combos = [ + annotation_combination + for + xvl, annotation_combination + in + xvl_list + if + xvl == best_combo_xvl + ] + if best_combo_xvl >= best_xvl: + best_combo = sorted( + list( + { + annotation + for + combo + in + best_combos + for + annotation + in + combo + } + ) + ) + self.xvl = best_combo_xvl + for annotation in best_combo: + self.annotations.remove(annotation) + with open( + '{}-{}.params' + .format(args.output, '+'.join(best_combo)) + ) as f: + for line in f: + parsed_line = tuple( + line.replace('\n', '').split(' ') + ) + parameter = parsed_line[0][:-3] + for annotation in self.annotations: + if annotation == parameter: + self.estimates[annotation] = tuple( + parsed_line[1:] + ) + break + self.collect_output_files('+'.join(best_combo)) + print( + 'Dropped {} from joint model (xvl: {})' + .format('+'.join(best_combo), str(best_xvl)) + ) + else: + print( + 'Next annotation to drop is ambiguous, taking a null ' + 'step and terminating analysis' + ) + for annotation in set(self.annotations_cache).union( + set( + '+'.join(sorted(combo)) + for + combo + in + annotation_combinations + ) + ): + clean_up_intermediate_files( + args, + '{}-{}.', + annotation + ) + + + + +#--------------------------- Function definitions -----------------------------# + +# Call fgwas +def call_fgwas(args_dict): + ''' + A function for calling FGWAS. Its argument is a dictionary, which should + at least include keys ""args"", ""annotation"" and ""header"", and may also + include keys ""tag"", ""xv_penalty"" and/or ""drop."" ""xv_penalty"" is required if + ""drop"" is included. + ''' + args = args_dict['args'] + annotation = args_dict['annotation'] + header = args_dict['header'] + tag = ( + args_dict['tag'] + if + 'tag' + in + args_dict.keys() + else + annotation.split('+')[-1] + ) + xv_penalty = ( + args_dict['xv_penalty'] + if + 'xv_penalty' + in + args_dict.keys() + else + None + ) + drop = ( + args_dict['drop'] + if + 'drop' + in + args_dict.keys() + else + '' + ) + fgwas_command_line = ( + ( + 'fgwas', + '-i', args.input, + '-w', annotation * (not bool(drop)) + drop * bool(drop), + '-o', ( + ( + '{}-{}'.format(args.output, tag) + * + ( + (not bool(xv_penalty)) + or + bool(drop) + ) + ) + + + ( + '{}-p{}'.format(args.output, str(xv_penalty)) + * + ( + bool(xv_penalty) + and + (not bool(drop)) + ) + ) + ) + ) + + + (('-xv', '-p', str(xv_penalty)) * bool(xv_penalty)) + + + (('-bed', args.bed) * bool(args.bed)) + + + (('-cc',) * ({'NCASE', 'NCONTROL'} <= set(header.tuple))) + + + (('-fine',) * ('SEGNUMBER' in header.tuple)) + + + (('-k', args.window) * bool(args.window)) + + + ('-print',) + ) + subprocess.call( + fgwas_command_line, + stdout=subprocess.DEVNULL, + stderr=subprocess.DEVNULL + ) + + + + +# Clean up intermediate files +def clean_up_intermediate_files(args, format_string, format_arg): + ''' + Remove the intermediate output files created by the fgwas run + ''' + for intermediate_file in tuple( + (format_string + extension).format(args.output, format_arg) + for + extension + in + ('llk', 'params', 'ridgeparams', 'segbfs.gz', 'bfs.gz') + ): + os.remove(intermediate_file) + + + + +# Collect an individual annotation result +def collect_individual_annotation_result(args, annotation, header): + ''' + Collect the result for an individual annotation + ''' + model = FgwasModel(args) + model.clear() + model.append(annotation, header) + return (annotation, model.llk) + model.estimates[annotation] + + + + +# Main +def main(args): + print('Reading input file header') + header = InputFileHeader(args) + print('Validating input file header') + header.validate() + model = FgwasModel(args) + individual_results = IndividualAnnotationResults(args, header) + print('Collecting individual annotation results') + individual_results.collect() + print('Exporting individual annotation results') + individual_results.export() + print('Identifying annotations with well-defined confidence intervals') + individual_results.identify_defined_ci_annotations() + print( + '{} annotations with well-defined confidence intervals.' + .format(len(individual_results.defined_ci_annotations)) + ) + if not args.initialize: + individual_results.identify_best_starting_state() + model.set_state(individual_results.best_starting_state) + print( + 'Constructing joint model, beginning with: {} (llk: {})' + .format(', '.join(model.annotations), model.llk) + ) + while ( + individual_results.defined_ci_annotations + > + set(model.annotations) + ): + model.append_best_annotation(individual_results) + if model.llk <= model.llk_cache: + model.revert() + break + print('Exporting pre-cross-validation results') + model.export('pre-xv') + print('Calibrating cross-validation penalty') + model.calibrate_cross_validation_penalty(header) + print('Beginning cross-validation phase') + number_of_annotations = len(model.annotations) + for iteration in range(number_of_annotations - 1): + model.remove_worst_annotation(header) + if model.xvl < model.xvl_cache: + model.revert() + break + print('Exporting post-cross-validation results') + model.export('post-xv') + print('Workflow complete.') + + + + +# Parse arguments +def parse_arguments(): + parser = argparse.ArgumentParser( + description=( + 'Apply the workflow suggested by the fgwas manual' + ) + ) + required_group = parser.add_argument_group('required arguments') + required_group.add_argument( + '-i', + '--input', + required=True, + help='Path to fgwas input file' + ) + required_group.add_argument( + '-o', + '--output', + required=True, + help='Prefix for output files' + ) + required_group.add_argument( + '-t', + '--threshold', + required=True, + type=float, + help='Likelihood threshold for model improvement' + ) + required_group.add_argument( + '-p', + '--processes', + required=True, + type=int, + help='Maximum number of fgwas processes to launch' + ) + optional_group = parser.add_argument_group('optional arguments') + optional_group.add_argument( + '-b', + '--bed', + help='Path to .bed file containing regional definitions' + ) + optional_group.add_argument( + '-k', + '--window', + help='Window size' + ) + optional_group.add_argument( + '-w', + '--annotations', + help=( + '""+""-separated list of annotations to use as a model starting ' + 'point.' + ) + ) + optional_group.add_argument( + '-l', + '--llk', + type=float, + help=( + 'Required if -w is used. Likelihood of model with the annotation ' + 'list given by -w.' + ) + ) + alternate_workflow_group = parser.add_argument_group( + 'alternate workflow arguments' + ) + alternate_workflow_group.add_argument( + '--positive-estimates-only', + action='store_true', + help=( + 'Add an annotation to the joint model only if it has a positive ' + 'parameter estimate.' + ) + ) + args = parser.parse_args() + if args.annotations and (not args.llk): + raise SystemExit( + 'ERROR: When a starting annotation list is provided, a starting ' + 'model likelihood must also be provided.' + ) + elif args.llk and (not args.annotations): + raise SystemExit( + 'ERROR: A starting likelihood was provided without a starting ' + 'annotaiton list.' + ) + elif args.llk and args.annotations: + args.initialize = True + else: + args.initialize = False + if args.threshold < 0: + raise SystemExit( + 'ERROR: The likelihood threshold must be nonnegative.' + ) + return args + + + + +#-------------------------------- Execute -------------------------------------# + +if __name__ == '__main__': + args = parse_arguments() + main(args) +","Python" +"Epigenetics","kjgaulton/pipelines","ATAC-seq_centipede_wrapper/atac_centipede_wrapper.sh",".sh","6894","213","#!/bin/bash + +# --------------------------------------------------------------------------- # +# +# ATAC-seq footprint pipeline +# +# --------------------------------------------------------------------------- # + +#Flag-handling and input-handling: + +#initialize variables +need_help=false +sam_file='unassigned' +sam_dir='' +out_dir=$( pwd) +starting_dir=$( pwd) +name='name' +genome=""unassigned"" +motifs=""unassigned"" + +while getopts 'abho:n:s:g:m:v' flag; do + case ""${flag}"" in + s) sam_file=""${OPTARG}"" ;; + o) out_dir=""${OPTARG}"" ;; + g) genome=""${OPTARG}"" ;; + m) motifs=""${OPTARG}"" ;; + n) name=""${OPTARG}"" ;; + h) need_help=true ;; + *) error ""Unexpected option ${flag}"" ;; + esac +done + +#check if all the helper scripts are in the right spot: +fimo_helper=false +filter_helper=false +centipede_helper=false +blacklist_check=false + +#checking fimo helper +if [ -e ~/bin/ATAC_Pipeline/split_fimo_by_motif.py ] +then + $filter_helper=true +fi + +#checking filter helper +if [ -e ~/bin/ATAC_Pipeline/filter_by_postprobs.py ] +then + $fimo_helper=true +fi + +#checking centipede helper +if [ -e ~/bin/ATAC_Pipeline/centipede.R ] +then + $centipede_helper=true +fi + +#check blacklist file +if [ -e ~/bin/ATAC_Pipeline/ENCODE.hg19.blacklist.bed ] +then + $blacklist_check=true +fi + +#handle the help flag -h: +if [ ""$need_help"" = true ] +then + echo ""ATAC-seq footprint pipeline"" + echo """" + echo ""Usage: bash [options]"" + echo """" + echo ""Tips:"" + echo "" Use absolute paths for all files and directories"" + echo "" Store helper scripts ~/bin/ATAC_Pipeline"" + echo "" Use the most recent versions of dependencies (bedtools, samtools, fimo...)"" + echo """" + echo "" Options:"" + echo "" -s "" + echo "" -o "" + echo "" -n "" + echo "" -m "" + echo "" -g "" + echo "" -h "" + echo """" + +#throw an error message if necessary arguments are not present +elif [ $sam_file == 'unassigned' ] || [ $genome == 'unassigned' ] || [ $motifs == 'unassigned' ] +then + echo ""Error: not all required parameters have been initialized. -s, -g, and -m flags are required."" + echo ""use -h option for help"" + +#are the helper scripts in the right spot? +elif [ $filter_helper = false ] || [ $fimo_helper = false ] || [ $centipede_helper = false ] || [ $blacklist_check = false ] +then + echo ""Error: not all helper scripts are in ~/bin/ATAC_Pipeline"" + echo ""use -h option for help"" + +#processing +else + + #make a new directory to keep all the mapped reads: + mkdir ""$out_dir/mapped_reads"" + + #filter based on read quality, remove mitochondrial reads + ext="".filtered.tmp.sam"" + filtered_sam=""$name$ext"" + samtools view -h -f 2 -q 30 ""$sam_file"" | grep -v ""chrM"" > ""$out_dir/mapped_reads/$filtered_sam"" + + #convert from sam to bam: + >&2 echo ""convert from sam to bam"" + ext="".filtered.tmp.bam"" + filtered_bam=""$name$ext"" + samtools view -bS ""$out_dir/mapped_reads/$filtered_sam"" > ""$out_dir/mapped_reads/$filtered_bam"" + + #sort bam file + >&2 echo ""sort bam file"" + ext="".sorted.tmp.bam"" + sorted_bam=""$name$ext"" + samtools sort -@ 4 ""$out_dir/mapped_reads/$filtered_bam"" > ""$out_dir/mapped_reads/$sorted_bam"" + + #remove duplicates + >&2 echo ""remove duplicates"" + ext="".rmdup.bam"" + rmdup_bam=""$name$ext"" + samtools rmdup ""$out_dir/mapped_reads/$sorted_bam"" ""$out_dir/mapped_reads/$rmdup_bam"" + + #index bam file: + >&2 echo ""index bam file"" + samtools index ""$out_dir/mapped_reads/$rmdup_bam"" + + #call peaks with macs2: + >&2 echo ""call peaks"" + mkdir ""$out_dir/peaks"" + macs2 callpeak -t ""$out_dir/mapped_reads/$rmdup_bam"" --outdir ""$out_dir/peaks"" -n ""$name"" --nomodel --shift -100 --extsize 200 -B --keep-dup all + + #remove peaks that fall within ENCODE blacklist regions: + >&2 echo ""removing blacklisted peaks"" + ext=""_peaks.narrowPeak"" + narrow_peak=""$name$ext"" + black=""$name_blacklisted.bed"" + bedtools intersect -v -a $out_dir/peaks/$narrow_peak -b ~/bin/ATAC_Pipeline/ENCODE.hg19.blacklist.bed -wa > $out_dir/peaks/$black + + #get fasta sequences from peaks: + >&2 echo ""get fasta sequences from peaks"" + ext="".peak_seqs.fa"" + peak_seqs=""$name$ext"" + + bedtools getfasta -fi ""$genome"" -bed ""$out_dir/peaks/$black"" > ""$out_dir/peaks/$peak_seqs"" + + #call fimo to get motifs + >&2 echo ""call fimo to get motifs"" + mkdir ""$out_dir/motifs"" + ext="".fimo_motifs.txt"" + fimo_motifs=""$name$ext"" + fimo --text ""$motifs"" ""$out_dir/peaks/$peak_seqs"" > ""$out_dir/$fimo_motifs"" + + #split big fimo motif into individual bed files for each motif: + >&2 echo ""split fimo file by motif"" + cd ""$out_dir/motifs"" + python ~/bin/ATAC_Pipeline/split_fimo_by_motif.py ""$out_dir/$fimo_motifs"" + + #using atactk, create discrete matrices that will go into centipede: + >&2 echo ""make discrete matrices"" + ext=""_matrices"" + mat_dir_name=""$name$ext"" + cd ""$out_dir"" + mkdir -p ""$out_dir/matrices/$mat_dir_name"" + + #loop through each motif to make matrices + for motif in $out_dir/motifs/* + do + ext="".dmatrix.gz"" + mName=$(basename $motif .motif.bed) + >&2 echo ""creating $mName matrix"" + outName=""$mName$ext"" + make_cut_matrix -d -b '(1-100000 1)' -p 4 ""$out_dir/mapped_reads/$rmdup_bam"" $motif | gzip -c > ""$out_dir/matrices/$mat_dir_name/$outName"" + done + + #run centipede on each motif, output posterior probabilites + >&2 echo ""run centipede"" + mkdir ""$out_dir/centipede_postprobs"" + cd ""$out_dir/centipede_postprobs"" + for motif in ""$out_dir/motifs""/* + do + a=$(basename $motif .motif.bed) + ext="".dmatrix.gz"" + matrix=""$a$ext"" + >&2 echo ""motif: $a"" + >&2 echo ""matrix: $matrix"" + + #run centipede: + /usr/bin/Rscript --vanilla ~/bin/ATAC_Pipeline/centipede.R ""$out_dir/matrices/$mat_dir_name/$matrix"" ""$motif"" + done + cd ""$out_dir"" + + #filter out bed regions that satisfy posterior probability threshold (run for 0.99 and 0.95) + mkdir ""$out_dir/footprints_95"" + mkdir ""$out_dir/footprints_99"" + for motif in $out_dir/motifs/* + do + foot=$( basename $motif .motif.bed) + ext1=""_footprints.bed"" + fName=""$foot$ext1"" + ext2="".dmatrix.gz.txt"" + pName=""$foot$ext2"" + + #run python script to get footprint regions that meet threshold posterior probabilities + >&2 echo ""extracting footprints for $foot"" + python ~/bin/ATAC_Pipeline/filter_by_postprobs.py $motif $out_dir/centipede_postprobs/$pName 0.99 > $out_dir/footprints_99/$fName + python ~/bin/ATAC_Pipeline/filter_by_postprobs.py $motif $out_dir/centipede_postprobs/$pName 0.95 > $out_dir/footprints_95/$fName + >&2 echo ""done getting footprint regions for $foot"" + + done + +fi","Shell" +"Epigenetics","kjgaulton/pipelines","ATAC-seq_centipede_wrapper/ATAC_Pipeline/split_fimo_by_motif.py",".py","2090","71","import sys + +fimo = open(str(sys.argv[1])) + +# dataToDictionary------------------------------------------------------------- +# +# Represent fimo file as a dictionary in which the key is the motif name and +# the value is the rest of the line. +#------------------------------------------------------------------------------ +def dataToDictionary(myFile): + + fimo_dict = {} + + file_index = 0 + for line in myFile: + #if this isn't the first line: + if file_index > 0: + #split the line by tabs: + line_list = line.rsplit('\t') + + #dictionary key is the motif name + key = line_list[0] + + #split the chromosome number, start, and stop locations + chr_start_stop = line_list[1].rsplit(':') + chrm = chr_start_stop[0] + start_stop = chr_start_stop[1].rsplit('-') + + #compute actual start and stop: + start = str(int(start_stop[0]) + int(line_list[2])) + stop = str(int(start_stop[0])+ int(line_list[3])) + + #create dictionary entry + item = [chrm, start, stop, key, line_list[5], line_list[4], line_list[6], line_list[len(line_list)-1][:len(line_list[len(line_list)-1])-1]] + if key not in fimo_dict.keys(): + fimo_dict[key] = [item] + else: + fimo_dict[key].append(item) + file_index += 1 + + return fimo_dict + +# splitFimo-------------------------------------------------------------------- +# +# split output from fimo into separate files based on their motif name. This is +# done using the helper function dataToDictionary, which creates a dictionary +# from fimo's output in which the keys are the motif names. +#------------------------------------------------------------------------------ +def splitFimo(): + + #call dataToDictionary: + my_dict = dataToDictionary(fimo) + + #for each motif: + for key in my_dict.keys(): + + my_items = my_dict[key] + filename = key + "".motif.bed"" + output_file = open(filename, 'w') + + #write all corresponding items to its output file: + for item in my_items: + out_string = """" + for i in range(len(item)): + if i < len(item)-1: + out_string += item[i] + '\t' + else: + out_string += item[i] + '\n' + output_file.write(out_string) + +splitFimo()","Python" +"Epigenetics","kjgaulton/pipelines","ATAC-seq_centipede_wrapper/ATAC_Pipeline/centipede.R",".R","1128","29","#!/usr/bin/Rscript +# centipede.R +# Usage: /usr/bin/Rscript --vanilla centipede.R matrix.file motifs.file + +#dir.base=""/data2/smorabito-data2/recreate-ATAC-footprints"" + +# start of script +library(CENTIPEDE) +library(tools) + +# process args +matrix.in <- commandArgs()[7] +motifs.in <- commandArgs()[8] +print(paste0(""Input matrix: "", matrix.in)) +print(paste0(""Input motifs: "", motifs.in)) +file.name <- basename(file_path_sans_ext(motifs.in)) + +# output centipede posterior probabilities +#dir.centipede <- file.path(dir.base,""centipede"") +#dir.output.centipede <- file.path(dir.base, file.name) +#setwd(dir.output.centipede) + +num.columns <- max(count.fields(gzfile(matrix.in), sep=""\t"")) +count.matrix <- read.table(gzfile(matrix.in), sep=""\t"", header=F, fill=T, col.names=paste0('V', seq_len(num.columns))) +count.matrix[is.na(count.matrix)] <- 0 +motifs <- read.table(motifs.in, sep=""\t"", header=F) +centFit <- fitCentipede(Xlist = list(ATAC=as.matrix(count.matrix)), Y=cbind(rep(1, dim(motifs)[1]), motifs[,5])) +write.table(centFit$PostPr,col=F,row=F,sep=""\t"",quote=F,file=paste0(basename(matrix.in),"".txt"")) +#write(centFit$PostPr, stdout())","R" +"Epigenetics","kjgaulton/pipelines","ChIP-seq_imbalance/quasar_genotype.py",".py","12591","438","#!/usr/bin/env python3 +#=============================================================================== +# quasar-genotype.py +#=============================================================================== + +""""""Infer genotypes from ChIP-seq or ATAC-seq data using QuASAR"""""" + + + + +# Imports ---------------------------------------------------------------------- + +import argparse +import functools +import os +import os.path +import pickle +import subprocess +import sys +import socket +import tempfile + +from multiprocessing import Pool + +hostname = socket.gethostname() +if hostname == 'gatsby.ucsd.edu': + sys.path.append('/home/data/kglab-python3-modules') +elif hostname == 'holden': + sys.path.append('/lab/kglab-python3-modules') + +import quasar +import seqalign +import wasp + + + + +# Function definitions --------------------------------------------------------- + +def prepare_quasar_input( + input_file_path: str, + bam_dir: str, + intermediate_dir: str, + reference_genome_path: str, + phred_quality_score: int, + blacklist_path: str, + snps_path: str, + processes: int, + memory: int, + paired_end: bool, + skip_preprocessing: bool, + write_bam: bool, + algorithm_switch_bp=70, + algorithm=None +) -> str: + """"""Format data into input files for QuASAR + + Parameters + ---------- + input_file_path : str + Path to an input file + bam_dir : str + Directory to write BAM files + intermediate_dir : str + Directory to write intermediate pileup / bed files + reference_genome_path : str + Path to reference genome + phred_quality_score : int + Minimum quality score for filtering alignment + blacklist_path : str + Path to ENCODE mappability blacklist + snps_path : str + Path to file containing SNPs to genotype + processes : int + Number of processes + memory : int + Memory limit + paired_end : bool + Indicator for paired_end reads + skip_preprocessing : bool + Indicator to skip preprocessing steps + write_bam : bool + Indicator to write a BAM file to disk + algorithm_switch_bp : int + Read length threshold for switching to `bwa mem` + algorithm : str or None + Force use of either `aln` or `mem` algorithm, if supplied + + Returns + ------- + str + Path to a QuASAR input file + """""" + input_file_path = ( + input_file_path.split(',') + if + ',' in input_file_path + else + input_file_path + ) + bam_prefix, intermediate_prefix = ( + os.path.join( + directory, + ( + os.path.basename( + input_file_path + if + isinstance(input_file_path, str) + else + input_file_path[0] + ) + .replace('.bam', '') + .replace('.fastq', '') + .replace('.gz', '') + ) + ) + for + directory + in + (bam_dir, intermediate_dir) + ) + with open('{}.align.log'.format(bam_prefix), 'w') as log: + sa = seqalign.SequenceAlignment( + input_file=input_file_path, + phred_quality_score=phred_quality_score, + processes=processes, + log=log, + aligner=seqalign.BWA( + reference_genome_path=reference_genome_path, + trim_qual=15, + algorithm_switch_bp=algorithm_switch_bp, + algorithm=algorithm + ), + dedupper=wasp.RmDup(processes=processes, paired_end=paired_end) + ) + if not skip_preprocessing: + sa.apply_quality_filter() + sa.remove_supplementary_alignments() + sa.remove_blacklisted_reads(blacklist_path=blacklist_path) + sa.samtools_sort(memory_limit=memory * processes) + sa.samtools_index() + sa.remove_mitochondrial_reads() + sa.samtools_index() + if write_bam: + sa.write('{}.filt.bam'.format(bam_prefix)) + sa.remove_duplicates() + sa.samtools_sort() + compressed_pileup_bed_path = ( + '{}.pileup.bed.gz'.format(intermediate_prefix) + ) + quasar.write_compressed_pileup_bed( + sa.samtools_mpileup( + positions=snps_path, + reference_genome=reference_genome_path + ), + compressed_pileup_bed_path, + snps_bed_path=snps_path + ) + quasar.bed_to_quasar(compressed_pileup_bed_path) + quasar_input_file_path = '{}.quasar.in.gz'.format(intermediate_prefix) + return ( + quasar_input_file_path + if + os.path.isfile(quasar_input_file_path) + else + None + ) + + +def get_genotypes( + input_list: list, + bam_dir: str, + intermediate_dir: str, + reference_genome_path: str, + phred_quality_score: int, + blacklist_path: str, + snps_path: str, + processes: int, + memory: int, + paired_end: bool, + skip_preprocessing: bool, + write_bam: bool, + algorithm_switch_bp=70, + algorithm=None +): + """"""Obtain genotypes from sequencing data using QuASAR + + Parameters + ---------- + input_list : list + List of input files + bam_dir : str + Directory to write BAM files + intermediate_dir : str + Directory to write intermediate pileup / bed files + reference_genome_path : str + Path to reference genome + phred_quality_score : int + Minimum quality score for filtering alignment + blacklist_path : str + Path to ENCODE mappability blacklist + snps_path : str + Path to file containing SNPs to genotype + processes : int + Number of processes + memory : int + Memory limit + paired_end : bool + Indicator for paired_end reads + skip_preprocessing : bool + Indicator to skip preprocessing steps + write_bam : bool + Indicator to write a BAM file to disk + algorithm_switch_bp : int + Read length threshold for switching to `bwa mem` + algorithm : str or None + Force use of either `aln` or `mem` algorithm, if supplied + """""" + + n_input_files = len(input_list) + with Pool(processes=min(processes, n_input_files)) as ( + pool + ), tempfile.TemporaryDirectory(dir='/home/data/tmp') as ( + temp_dir_name + ): + return quasar.genotype( + *filter( + None, + pool.map( + functools.partial( + prepare_quasar_input, + bam_dir=( + bam_dir + if + bam_dir + else + temp_dir_name + ), + intermediate_dir=( + intermediate_dir + if + intermediate_dir + else + temp_dir_name + ), + reference_genome_path=reference_genome_path, + phred_quality_score=phred_quality_score, + blacklist_path=blacklist_path, + snps_path=snps_path, + processes=max(1, int(processes / n_input_files)), + memory=memory, + paired_end=paired_end, + skip_preprocessing=skip_preprocessing, + write_bam=write_bam, + algorithm_switch_bp=algorithm_switch_bp, + algorithm=algorithm + ), + input_list + ) + ) + ) + + +def main(args): + vcf = quasar.genotype_to_vcf( + get_genotypes( + args.input, + args.bam_dir, + args.inter_dir, + args.reference, + args.quality, + args.blacklist, + args.snps, + args.processes, + args.memory, + args.paired_end, + args.skip_preprocessing, + args.write_bam, + args.algorithm_switch_bp, + args.algorithm + ), + sample_name=args.sample, + snps_bed_path=args.snps, + threshold=args.threshold, + het_only=args.het_only + ) + if args.vcf_chr and not args.quiet: + vcf = tuple(vcf) + if args.vcf_chr: + quasar.write_split_vcf(vcf, args.vcf_chr) + if not args.quiet: + for line in vcf: + print(line) + + +def parse_arguments(): + parser = argparse.ArgumentParser( + description=( + 'Infer genotypes from ChIP-seq or ATAC-seq data using QuASAR' + ) + ) + io_group = parser.add_argument_group('I/O arguments') + io_group.add_argument( + 'input', + metavar='', + nargs='+', + help='Paths to input FASTQ or BAM files' + ) + io_group.add_argument( + '--bam-dir', + metavar='', + help='directory in which to place BAM files' + ) + io_group.add_argument( + '--inter-dir', + metavar='', + help='prefix for intermediate files' + ) + io_group.add_argument( + '--vcf-chr', + metavar='', + help='Prefix for output VCFs split by chromosome' + ) + io_group.add_argument( + '--quiet', + action='store_true', + help='Suppress printing of VCF file to standard output' + ) + + align_group = parser.add_argument_group('Alignment arguments') + align_group.add_argument( + '--processes', + metavar='', + type=int, + default=4, + help='Number of processes to use [4]' + ) + align_group.add_argument( + '--memory', + metavar='', + type=int, + default=8, + help='Maximum memory per thread in GB [8]' + ) + align_group.add_argument( + '--quality', + metavar='', + type=int, + default=10, + help='Mapping quality cutoff for samtools [10]' + ) + align_group.add_argument( + '--reference', + metavar='', + default='/home/joshchiou/references/ucsc.hg19.fasta', + help=( + 'Path to reference genome prepared for BWA ' + '[/home/joshchiou/references/ucsc.hg19.fasta]' + ) + ) + align_group.add_argument( + '--blacklist', + metavar='', + default='/home/data/encode/ENCODE.hg19.blacklist.bed', + help=( + 'Path to ENCODE blacklist file ' + '[/home/data/encode/ENCODE.hg19.blacklist.bed]' + ) + ) + align_group.add_argument( + '--paired-end', + action='store_true', + help='Use for paired-end reads' + ) + align_group.add_argument( + '--write-bam', + action='store_true', + help='Write bam files to disk' + ) + align_group.add_argument( + '--algorithm-switch-bp', + metavar='', + default=70, + help='Read length threshold for switching to `bwa mem` [70]' + ) + align_group.add_argument( + '--algorithm', + choices={'aln', 'mem'}, + default=None, + help='Force use of either `bwa aln` or bwa mem`' + ) + + quasar_group = parser.add_argument_group('QuASAR arguments') + quasar_group.add_argument( + '--snps', + metavar='', + default='/home/data/QuASAR/1KG_SNPs_filt.bed', + help=( + 'BED file containing 1KGP SNPs ' + '[/home/data/QuASAR/1KG_SNPs_filt.bed]' + ) + ) + quasar_group.add_argument( + '--skip-preprocessing', + action='store_true', + help='skip preprocessing steps' + ) + + vcf_group = parser.add_argument_group('VCF arguments') + vcf_group.add_argument( + '--sample', + metavar='', + default='SAMPLE', + help='Name for the sample [SAMPLE]' + ) + vcf_group.add_argument( + '--threshold', + metavar='', + default=0.99, + type=float, + help='Probability threshold for genotype calls [0.99]' + ) + vcf_group.add_argument( + '--het-only', + action='store_true', + help='Output heterozygous variants only' + ) + return parser.parse_args() + + + + +# Execute ---------------------------------------------------------------------- + +if __name__ == '__main__': + args = parse_arguments() + main(args) +","Python" +"Epigenetics","kjgaulton/pipelines","ChIP-seq_imbalance/wasp_map.py",".py","23500","852","#!/usr/bin/env python3 +#=============================================================================== +# wasp_map.py +#=============================================================================== + +""""""Implementation of the re-mapping procedure to eliminate reference bias +detailed in WASP. + +See: https://github.com/bmvdgeijn/WASP/tree/master/mapping +"""""" + + + +# Imports ---------------------------------------------------------------------- + +import argparse +import functools +import math +import os +import os.path +import socket +import sys + +from multiprocessing import Pool + +hostname = socket.gethostname() +if hostname == 'gatsby.ucsd.edu': + sys.path.append('/home/data/kglab-python3-modules') +elif hostname == 'holden': + sys.path.append('/lab/kglab-python3-modules') + +import seqalign +import wasp + + + + +# Function definitions --------------------------------------------------------- + +def setup_directory(output_dir, snp_dir): + """"""Create directories for the WASP mapping pipeline as needed + + Parameters + ---------- + output_dir : str + path to output directory for the pipeline + snp_dir : str + path to directory where SNP files will be stored + """""" + + for directory in (output_dir, snp_dir) + tuple( + os.path.join(output_dir, subdir) + for + subdir + in + ( + 'map1', + 'find_intersecting_snps', + 'map2', + 'filter_remapped_reads', + 'pileup' + ) + ): + if not os.path.isdir(directory): + os.mkdir(directory) + + +def map_reads(file_path, trim_qual, processes=1, algorithm=None): + """"""Map some reads + + Parameters + ---------- + file_path : str, list, tuple + Path to reads on disk that will be mapped. A string for single-end + reads, a list or tuple containing two strings for paired-end reads. + trim_qual : int + MAPQ score for BWA read trimming + processes : int + Maximum number of processes + + Returns + ------- + seqalign.SequenceAlignment + Object representing the aligned data + """""" + + if len(file_path) == 2: + if file_path[1] == 'paired': + file_path = file_path[0] + with seqalign.SequenceAlignment( + file_path, + processes=processes, + aligner=seqalign.BWA( + trim_qual=trim_qual, + algorithm=algorithm, + algorithm_switch_bp=100 + ) + ) as sa: + sa.samtools_sort() + sa.samtools_index + return sa + + +def preprocess_sample( + sample_name, + file_path, + output_dir, + processes=1, + algorithm=None +): + """"""Apply preprocessing steps to an input sample + + Writes a preprocessed BAM file to the map1 subdir of the output directory. + If the input file path matches the output file path, it is assumed that + preprocessing has already been done and this step is skipped. + + Parameters + ---------- + sample_name : str + Sample name + file_path : list + List containin one or two paths to input files (for single- or + paired-end reads) + output_dir : str + Output directory for the pipeline + processes : int + Maximum number of processes to use for this sample + """""" + + map1_path = os.path.join( + output_dir, + 'map1', + '{}.sort.bam'.format(sample_name) + ) + file_path = file_path[0] if len(file_path) == 1 else file_path + + if file_path != map1_path: + alignment = map_reads( + file_path, + trim_qual=15, + processes=processes, + algorithm=algorithm + ) + alignment.write(map1_path) + + +def preprocessing_step(sample_list, output_dir, processes=1, algorithm=None): + """"""Apply preprocessing steps to all input samples + + Preprocesses multiple samples in parallel + + Parameters + ---------- + sample_list : list + List of sample information from the argument parser + output_dir : str + Output directory for the pipeline + processes : int + Maximum number of processes to use + """""" + + n_samples = len(sample_list) + with Pool(processes=min(processes, n_samples)) as pool: + pool.starmap( + functools.partial( + preprocess_sample, + output_dir=output_dir, + processes=max(1, math.floor(processes / n_samples)), + algorithm=algorithm + ), + ( + (sample_name, input_file_path) + for + sample_name, *input_file_path + in + sample_list + ) + ) + + +def _find_intersecting_snps( + input_file_path, + bam_filename, + snp_dir, + output_dir=None +): + """"""Run WASP's `find_intersecting_snps.py` script + + This function wraps wasp.find_intersecting_snps and handles endedness by + interpreting the type of the provided input_file_path + + Parameters + ---------- + input_file_path : str, list, tuple + Path to an input file (or paths to two files if paired-end) as provided + to the argument parser. The length of this parameter is checked to + determine endedness. + bam_filename : str, bytes + Path to an input BAM file (str), or an input BAM file in memory (bytes) + snp_dir : str + Path to directory containing SNP files + output_dir : str + Path to directory where output files will be written + """""" + + wasp.find_intersecting_snps( + bam_filename, + snp_dir, + is_paired_end=len(input_file_path) == 2, + is_sorted=True, + output_dir=output_dir + ) + + +def find_intersecting_snps( + sample_list, + output_dir, + snp_dir, + processes=1, + memory_limit=5 +): + """"""Run WASP's `find_intersecting_snps.py` script + + This function runs _find_intersecting_snps on multiple files in parallel + + Parameters + ---------- + sample_list : list + List of sample information from the argument parser + output_dir : str + Output directory for the pipeline + snp_dir : str + Path to directory containing SNP files + processes : int + Maximum number of processes to use + memory_limit : int + Approximate memory limit in gigabytes [5] + """""" + + with Pool( + processes=min( + processes, + math.floor(memory_limit / 4), + len(sample_list) + ) + ) as pool: + pool.starmap( + functools.partial( + _find_intersecting_snps, + snp_dir=snp_dir, + output_dir=os.path.join( + output_dir, + 'find_intersecting_snps' + ) + ), + ( + ( + input_file_path, + os.path.join( + output_dir, + 'map1', + '{}.sort.bam'.format(sample_name) + ) + ) + for + sample_name, *input_file_path + in + sample_list + ) + ) + + +def remap_sample( + sample_name, + file_path, + output_dir, + processes=1, + algorithm=None +): + """"""Remap an input sample + + Writes a remapped BAM file to the map2 subdirectory of the output directory + + Parameters + ---------- + sample_name : str + Sample name + file_path : list + List containin one or two paths to input files (for single- or + paired-end reads) + output_dir : str + Output directory for the pipeline + processes : int + Maximum number of processes to use for this sample + """""" + + alignment = map_reads( + file_path, + trim_qual=0, + processes=processes, + algorithm=algorithm + ) + alignment.write( + os.path.join(output_dir, 'map2', '{}.sort.bam'.format(sample_name)) + ) + + +def remapping_step(sample_list, output_dir, processes=1, algorithm=None): + """"""Remap all input samples + + Remaps multiple samples in parallel + + Parameters + ---------- + sample_list : list + List of sample information from the argument parser + output_dir : str + Output directory for the pipeline + processes : int + Maximum number of processes to use + """""" + + n_samples = len(sample_list) + with Pool(processes=min(processes, n_samples)) as pool: + pool.starmap( + functools.partial( + remap_sample, + output_dir=output_dir, + processes=max(1, math.floor(processes / n_samples)), + algorithm=algorithm + ), + ( + ( + sample_name, + ( + tuple( + os.path.join( + output_dir, + 'find_intersecting_snps', + '{}.sort.remap.fq{}.gz'.format( + sample_name, + end + ) + ) + for + end + in + (1, 2) + ) + if + len(input_file_path) == 2 + else + os.path.join( + output_dir, + 'find_intersecting_snps', + '{}.sort.remap.fq.gz'.format(sample_name) + ) + ) + ) + for + sample_name, *input_file_path + in + sample_list + ) + ) + + +def filter_remapped_reads(sample_list, output_dir, processes=1, memory_limit=5): + """"""Run WASP's `filter_remapped_reads.py` script + + This function runs wasp.filter_remapped_reads on multiple files in parallel + + Parameters + ---------- + sample_list : list + List of sample information from the argument parser + output_dir : str + Output directory for the pipeline + processes : int + Maximum number of processes to use + memory_limit : int + Approximate memory limit in gigabytes [5] + """""" + + with Pool( + processes=min(processes, memory_limit, len(sample_list)) + ) as pool: + pool.starmap( + wasp.filter_remapped_reads, + ( + ( + os.path.join( + output_dir, + 'find_intersecting_snps', + '{}.sort.to.remap.bam'.format(sample_name) + ), + os.path.join( + output_dir, + 'map2', + '{}.sort.bam'.format(sample_name) + ), + os.path.join( + output_dir, + 'filter_remapped_reads', + '{}.keep.bam'.format(sample_name) + ) + ) + for + sample_name, *input_file_path + in + sample_list + ) + ) + + +def merge_and_rmdup(*sequence_alignments, paired_end=False, processes=1): + """"""Merge kept and remapped reads and apply WASP's dedupper + + Parameters + ---------- + *sequence_alignments + One or more seqalign.SequenceAlignment objects + paired_end : bool + If True, `rmdup_pe.py` will be used, otherwise `rmdup.py` will be used + processes : int + Maximum number of processes for samtools sort + """""" + + sa = seqalign.merge( + *sequence_alignments, + processes=processes, + dedupper=wasp.RmDup(paired_end=paired_end, processes=processes) + ) + sa.samtools_sort() + sa.samtools_index() + sa.remove_supplementary_alignments() + sa.remove_duplicates() + sa.samtools_sort() + sa.samtools_index() + return sa + + +def merge_rmdup_pileup( + sample_name, + input_file_path, + output_dir, + snp_dir, + reference_genome_path, + processes=1 +): + """"""Merge kept and remapped reads, remove duplicates, and generate a pileup + + The pileup will be written to the pileup subdir of the output directory + + Parameters + ---------- + sample_name : str + Sample name + input_file_path : str, list, tuple + Path to an input file (or paths to two files if paired-end) as provided + to the argument parser. The length of this parameter is checked to + determine endedness. + output_dir : str + Output directory for the pipeline + snp_dir : str + Path to directory containing SNP files + reference_genome_path : str + Path to a reference genome on disk + """""" + + alignment = merge_and_rmdup( + os.path.join( + output_dir, + 'filter_remapped_reads', + '{}.keep.bam'.format(sample_name) + ), + os.path.join( + output_dir, + 'find_intersecting_snps', + '{}.sort.keep.bam'.format(sample_name) + ), + paired_end=len(input_file_path) == 2, + processes=processes + ) + with open( + os.path.join( + output_dir, + 'pileup', + '{}.pileup'.format(sample_name) + ), + 'w' + ) as f: + f.write( + alignment.samtools_mpileup( + positions=os.path.join(snp_dir, 'snps.positions.txt'), + reference_genome=reference_genome_path + ) + .decode() + ) + + +def merge_rmdup_pileup_steps( + sample_list, + output_dir, + snp_dir, + reference_genome_path, + processes=1 +): + """"""Merge reads, remove duplicates, and generate a pileup for all samples + + Pileups will be generated for multiple samples in parallel + + Parameters + ---------- + sample_list : list + List of sample information from the argument parser + output_dir : str + Output directory for the pipeline + snp_dir : str + Path to directory containing SNP files + reference_genome_path : str + Path to a reference genome on disk + """""" + + n_samples = len(sample_list) + with Pool(processes=min(processes, n_samples)) as pool: + pool.starmap( + functools.partial( + merge_rmdup_pileup, + output_dir=output_dir, + snp_dir=snp_dir, + reference_genome_path=reference_genome_path, + processes=max(1, math.floor(processes / n_samples)) + ), + ( + (sample_name, input_file_path) + for + sample_name, *input_file_path + in + sample_list + ) + ) + + +def remove_intermediate_files(samples, output_dir): + """"""Remove intermediate files generated during the procedure + + Parameters + ---------- + samples : list + The list of samples obtained from command line arguments + output_dir : str + Directory for output files + """""" + + for file_path in ( + file_path + for + sample_name + in + (sample[0] for sample in samples) + for + file_path + in + ( + os.path.join( + output_dir, + 'map2', + '{}.sort.bam'.format(sample_name) + ), + os.path.join( + output_dir, + 'find_intersecting_snps', + '{}.sort.remap.fq.gz'.format(sample_name) + ), + os.path.join( + output_dir, + 'find_intersecting_snps', + '{}.sort.to.remap.bam'.format(sample_name) + ), + os.path.join( + output_dir, + 'find_intersecting_snps', + '{}.sort.keep.bam'.format(sample_name) + ), + os.path.join( + output_dir, + 'filter_remapped_reads', + '{}.keep.bam'.format(sample_name) + ) + ) + tuple( + os.path.join( + output_dir, + 'find_intersecting_snps', + '{}.sort.remap.fq{}.gz'.format( + sample_name, + end + ) + ) + for + end + in + (1, 2) + ) + if + os.path.isfile(file_path) + ): + os.remove(file_path) + + +def remove_empty_directories(output_dir): + """"""Remove empty directories left over after the pipeline is completed + + Parameters + ---------- + output_dir : str + Directory for output files + """""" + + for directory in ( + os.path.join(output_dir, subdir) + for + subdir + in + ('find_intersecting_snps', 'map2', 'filter_remapped_reads') + if + os.path.isdir(os.path.join(output_dir, subdir)) + if + not os.listdir(os.path.join(output_dir, subdir)) + ): + os.rmdir(directory) + +def main(args): + """"""The main pipeline"""""" + + # Step 0: set up the output directory + setup_directory(args.output_dir, args.snp_dir) + + # Step 1: create SNP files + if args.vcf_format and args.vcf_sample: + wasp.write_positions_snps( + args.vcf_format, + ( + os.path.join(args.snp_dir, 'snps') + if + args.snp_dir + else + os.path.join(args.output_dir, 'snp_dir', 'snps') + ), + het_only=True, + r2=args.r2, + samples=args.vcf_sample, + keep_filtered_vcfs=True + ) + + # Stop here if no sample was given + if args.sample: + + # Step 2: preprocess sequencing data + preprocessing_step( + args.sample, + args.output_dir, + processes=args.processes, + algorithm=args.algorithm + ) + + # Step 3: find intersecting snps + find_intersecting_snps( + args.sample, + args.output_dir, + args.snp_dir, + processes=args.processes, + memory_limit=args.memory_limit + ) + + # Step 4: remap + remapping_step( + args.sample, + args.output_dir, + processes=args.processes, + algorithm=args.algorithm + ) + + # Step 5: filter remapped reads + filter_remapped_reads( + args.sample, + args.output_dir, + processes=args.processes, + memory_limit=args.memory_limit + ) + + # Step 6-7+: Merge remapped_reads, remove duplicates, generate pileups + merge_rmdup_pileup_steps( + args.sample, + args.output_dir, + args.snp_dir, + args.reference_genome, + processes=args.processes + ) + + # Clean up intermediate files + if not args.save_intermediate: + remove_intermediate_files(args.sample, args.output_dir) + + # Clean up empty directories + if not args.save_intermediate: + remove_empty_directories(args.output_dir) + + +def main_skip_to_6(args): + # Stop here if no sample was given + if args.sample: + + # Step 6-7+: Merge remapped_reads, remove duplicates, generate pileups + merge_rmdup_pileup_steps( + args.sample, + args.output_dir, + args.snp_dir, + args.reference_genome, + processes=args.processes + ) + + # Clean up intermediate files + if not args.save_intermediate: + remove_intermediate_files(args.sample, args.output_dir) + + # Clean up empty directories + if not args.save_intermediate: + remove_empty_directories(args.output_dir) + + +# Parse arguments +def parse_arguments(): + parser = argparse.ArgumentParser( + description=( + 'Implementation of the re-mapping procedure to eliminate reference ' + 'bias detailed in WASP.' + ) + ) + parser.add_argument( + 'output_dir', + metavar='', + nargs='?', + default='.', + help=( + 'Directory for output files. If this is not provided, the current ' + 'directory is used.' + ) + ) + io_group = parser.add_argument_group('I/O arguments') + io_group.add_argument( + '--sample', + metavar=('', ''), + action='append', + nargs='+', + help=( + 'Sample name followed by file path (or paths if paired-end reads). ' + 'If the input file is a BAM file with paired-end reads, add a ' + 'third argument ""paired"".' + ) + ) + io_group.add_argument( + '--save-intermediate', + action='store_true', + help='Do not delete intermediate files' + ) + config_group = parser.add_argument_group('config arguments') + config_group.add_argument( + '--vcf-format', + metavar='', + help=( + 'Format for input VCF files. ""{}"" will be replaced by a ' + 'chromosome number or character.' + ) + ) + config_group.add_argument( + '--vcf-sample', + metavar='', + help='Sample to use from VCF files' + ) + config_group.add_argument( + '--snp-dir', + metavar='', + help='Path to SNP directory' + ) + config_group.add_argument( + '--reference-genome', + metavar='', + default='/home/joshchiou/references/ucsc.hg19.fasta', + help=( + 'Path to reference genome ' + '[/home/joshchiou/references/ucsc.hg19.fasta]' + ) + ) + config_group.add_argument( + '--r2', + metavar='', + default=0.9, + type=float, + help=( + 'R2 imputation quality threshold [0.9]. Set this to 0 for ' + 'non-imputed VCF data.' + ) + ) + config_group.add_argument( + '--algorithm', + default=None, + choices={'aln', 'mem'}, + help='Force BWA algorithm' + ) + resource_group = parser.add_argument_group('resource arguments') + resource_group.add_argument( + '--processes', + metavar='', + default=1, + type=int, + help='Maximum number of processes allowed [1]' + ) + resource_group.add_argument( + '--memory-limit', + metavar='', + default=5, + type=int, + help='Approximate memory limit in gigabytes [5]' + ) + troubleshooting_group = parser.add_argument_group( + 'troubleshooting arguments' + ) + troubleshooting_group.add_argument( + '--skip-to-6', + action='store_true', + help='Skip to step 6, merging the reads after remapping' + ) + args = parser.parse_args() + if not args.snp_dir: + args.snp_dir = os.path.join(args.output_dir, 'snp_dir') + return args + + + + +# Execute ---------------------------------------------------------------------- + +if __name__ == '__main__': + args = parse_arguments() + if args.memory_limit < 5: + raise Exception('Please provide at least 5 GB of memory') + if not args.skip_to_6: + main(args) + else: + main_skip_to_6(args) +","Python" +"Epigenetics","kjgaulton/pipelines","snATAC-seq/demultiplex.py",".py","4764","133","#!/usr/bin/env python3 + +import sys +import gzip +import argparse +import logging +import Levenshtein + +def load_barcodes(args): + bcs = {} + with open(args.barcodes) as f: + for line in f: + fields = line.rstrip('\n').split('\t') + index, adapter = fields[0], fields[1] + bcs[index] = bcs.get(index, []) + [adapter] + return bcs + +def process_mismatch(mismatch, adapters): + edit_distances = {a:Levenshtein.distance(mismatch, a) for a in adapters} + min_adap = min(edit_distances, key=edit_distances.get) + min_dist = edit_distances[min_adap] + del edit_distances[min_adap] + min_adap2 = min(edit_distances, key=edit_distances.get) + min_dist2 = edit_distances[min_adap2] + return min_adap, min_dist, min_adap2, min_dist2 + +def demultiplex(args): + i1 = gzip.open(args.index1, 'rt') + i2 = gzip.open(args.index2, 'rt') + r1 = gzip.open(args.reads1, 'rt') + r2 = gzip.open(args.reads2, 'rt') + o1 = gzip.open(args.reads1.split('.fastq.gz')[0] + '.demux.fastq.gz', 'wt') + o2 = gzip.open(args.reads2.split('.fastq.gz')[0] + '.demux.fastq.gz', 'wt') + + edits_made = 0 + while True: + i1_name = i1.readline().strip()[1:] + i1_read = i1.readline().strip() + i1_plus = i1.readline().strip() + i1_qual = i1.readline().strip() + + i2_name = i2.readline().strip()[1:] + i2_read = i2.readline().strip() + i2_plus = i2.readline().strip() + i2_qual = i2.readline().strip() + + r1_name = r1.readline().strip()[1:] + r1_read = r1.readline().strip() + r1_plus = r1.readline().strip() + r1_qual = r1.readline().strip() + + r2_name = r2.readline().strip()[1:] + r2_read = r2.readline().strip() + r2_plus = r2.readline().strip() + r2_qual = r2.readline().strip() + + if i1_name == '' or i2_name == '' or r1_name == '' or r2_name == '': + print('Finished demultiplexing!', file=sys.stderr) + break + if not i1_name.split()[0] == i2_name.split()[0] == r1_name.split()[0] == r2_name.split()[0]: + print('Reads names {} {} {} {} not the same!'.format(i1_name, i2_name, r1_name, r2_name), file = sys.stderr) + break + + p7 = i1_read[:8] + i7 = i1_read[-8:] + i5 = i2_read[:8] + p5 = i2_read[-8:] + if p7 not in args.bcs['p7']: + min_adap, min_dist, min_adap2, min_dist2 = process_mismatch(p7, args.bcs['p7']) + if min_dist <= args.mismatch and abs(min_dist2 - min_dist) > args.closest: + p7 = min_adap + edits_made += 1 + else: + continue + if i7 not in args.bcs['i7']: + min_adap, min_dist, min_adap2, min_dist2 = process_mismatch(i7, args.bcs['i7']) + if min_dist <= args.mismatch and abs(min_dist2 - min_dist) > args.closest: + i7 = min_adap + edits_made +=1 + else: + continue + if i5 not in args.bcs['i5']: + min_adap, min_dist, min_adap2, min_dist2 = process_mismatch(i5, args.bcs['i5']) + if min_dist <= args.mismatch and abs(min_dist2 - min_dist) > args.closest: + i5 = min_adap + edits_made += 1 + else: + continue + if p5 not in args.bcs['p5']: + min_adap, min_dist, min_adap2, min_dist2 = process_mismatch(p5, args.bcs['p5']) + if min_dist <= args.mismatch and abs(min_dist2 - min_dist) > args.closest: + p5 = min_adap + edits_made += 1 + else: + continue + barcode = p7 + i7 + i5 + p5 + o1.write('@' + barcode + ':' + r1_name + '\n') + o1.write(r1_read + '\n') + o1.write('+\n') + o1.write(r1_qual + '\n') + o2.write('@' + barcode + ':' + r2_name + '\n') + o2.write(r2_read + '\n') + o2.write('+\n') + o2.write(r2_qual + '\n') + return edits_made + +def main(args): + logging.info('Starting up.') + args.bcs = load_barcodes(args) + edits = demultiplex(args) + print('Total edits made: {}'.format(edits), file=sys.stderr) + logging.info('Finishing up.') + return + +def process_args(): + parser = argparse.ArgumentParser(description='Demultiplex snATAC-seq reads') + io_group = parser.add_argument_group('I/O arguments') + io_group.add_argument('-r1', '--reads1', required=True, type=str, help='Path to reads 1 file') + io_group.add_argument('-r2', '--reads2', required=True, type=str, help='Path to reads 2 file') + io_group.add_argument('-i1', '--index1', required=True, type=str, help='Path to index 1 file') + io_group.add_argument('-i2', '--index2', required=True, type=str, help='Path to index 2 file') + io_group.add_argument('-b', '--barcodes', required=True, type=str, help='Path to barcodes file') + + process_group = parser.add_argument_group('Process arguments') + process_group.add_argument('-m', '--mismatch', required=False, type=int, default=2, help='Maximum number of mismatches per index') + process_group.add_argument('-c', '--closest', required=False, type=int, default=1, help='Closest edit distance of 2nd best match to the best match') + return parser.parse_args() + +if __name__ == '__main__': + logging.basicConfig(format='[%(filename)s] %(asctime)s %(levelname)s: %(message)s', datefmt='%I:%M:%S', level=logging.DEBUG) + args = process_args() + main(args) +","Python" +"Epigenetics","kjgaulton/pipelines","snATAC-seq/snATAC_pipeline.py",".py","11348","241","#!/usr/bin/env python3 + +import os +import sys +import gzip +import argparse +import logging +import subprocess +import pysam +import numpy as np +import pandas as pd +import scipy.sparse + +def trim_reads(args): + trim_galore_cmd = ['trim_galore', '--nextera', '--fastqc', '-q', '20', '-o', args.output, '--paired', args.read1, args.read2] + with open(os.devnull, 'w') as f: + subprocess.call(trim_galore_cmd, stderr=f, stdout=f) + pair1_trim = os.path.join(args.output, os.path.basename(args.read1).split('.fastq.gz')[0] + '_val_1.fq.gz') + pair2_trim = os.path.join(args.output, os.path.basename(args.read2).split('.fastq.gz')[0] + '_val_2.fq.gz') + return pair1_trim, pair2_trim + +def align_reads(args): + align_log = args.output_prefix + '.align.log' + aligned_bam = args.output_prefix + '.compiled.bam' + filtered_bam = args.output_prefix + '.compiled.filt.bam' + + bwa_mem_cmd = ['bwa', 'mem', '-t', str(args.threads), args.reference, args.read1, args.read2] + fixmate_cmd = ['samtools', 'fixmate', '-r', '-', '-'] + samtools_sort_cmd = ['samtools', 'sort', '-m', str(args.memory)+'G', '-@', str(args.threads), '-'] + filter_cmd = ['samtools', 'view', '-h', '-q', str(args.map_quality), '-f', '3', '-F', '4', '-F', '256', '-F', '1024', '-F', '2048', aligned_bam] + samtools_view_cmd = ['samtools', 'view', '-b', '-'] + + with open(align_log, 'w') as log, open(aligned_bam, 'w') as bam_out: + bwa_mem = subprocess.Popen(bwa_mem_cmd, stdout=subprocess.PIPE, stderr=log) + fixmate = subprocess.Popen(fixmate_cmd, stdin=bwa_mem.stdout, stdout=subprocess.PIPE) + subprocess.call(samtools_sort_cmd, stdin=fixmate.stdout, stdout=bam_out, stderr=log) + + with open(align_log, 'a') as log, open(filtered_bam, 'w') as bam_out: + filt = subprocess.Popen(filter_cmd, stderr=log, stdout=subprocess.PIPE) + view = subprocess.Popen(samtools_view_cmd, stdin=subprocess.PIPE, stdout=bam_out) + for line in filt.stdout: + line = line.decode().rstrip('\n') + if line.startswith('@'): + try: + view.stdin.write('{}\n'.format(line).encode()) + except IOError as err: + if err.errno == errno.EPIPE or err.errno == errno.EINVAL: + break + else: + raise + continue + fields = line.split('\t') + barcode = fields[0].split(':')[0] + fields[0] = barcode + '_' + ':'.join(fields[0].split(':')[1:]) + fields.append('BX:Z:{}'.format(barcode)) + try: + view.stdin.write('{}\n'.format('\t'.join(fields)).encode()) + except IOError as err: + if err.errno == errno.EPIPE or err.errno == errno.EINVAL: + break + else: + raise + view.stdin.close() + view.wait() + return + +def remove_duplicate_reads(args): + filtered_bam = args.output_prefix + '.compiled.filt.bam' + markdup_bam = args.output_prefix + '.filt.md.bam' + rmdup_bam = args.output_prefix + '.filt.rmdup.bam' + markdup_log = args.output_prefix + '.MarkDuplicates.log' + markdup_cmd = ['java', '-Xmx24G', '-jar', args.picard, + 'MarkDuplicates', 'INPUT={}'.format(filtered_bam), 'OUTPUT={}'.format(markdup_bam), + 'VALIDATION_STRINGENCY=LENIENT', 'BARCODE_TAG=BX', 'METRICS_FILE={}'.format(markdup_log), + 'REMOVE_DUPLICATES=false'] + index_cmd = ['samtools', 'index', markdup_bam] + filter_cmd = ['samtools', 'view', '-@', str(args.threads), '-b', '-f', '3', '-F', '1024', markdup_bam] + filter_cmd.extend(['chr{}'.format(c) for c in list(map(str, range(1,23))) + ['X','Y']]) + + with open(os.devnull, 'w') as null: + subprocess.call(markdup_cmd, stderr=null, stdout=null) + subprocess.call(index_cmd) + if os.path.isfile(markdup_bam): + with open(rmdup_bam, 'w') as bam_out: + subprocess.call(filter_cmd, stdout=bam_out) + else: + raise FileNotFoundError('{} not found!'.format(markdup_bam)) + return + +def generate_binary_matrix(args): + rmdup_bam = args.output_prefix + '.filt.rmdup.bam' + tagalign_file = args.output_prefix + '.filt.rmdup.tagAlign.gz' + + barcode_coverage = {} + if os.path.isfile(rmdup_bam): + with gzip.open(tagalign_file, 'wt') as f: + temp_store = [] + bamfile = pysam.AlignmentFile(rmdup_bam, 'rb') + genome_size = {item['SN']:item['LN'] for item in bamfile.header['SQ']} + for read in bamfile: + if not read.is_proper_pair: + continue + barcode = read.query_name.split('_')[0] + read_chr = read.reference_name + read_start = max(1, read.reference_start - args.extension if read.is_reverse else read.reference_start + 4 - args.extension) + read_end = min(genome_size[read_chr], read.reference_end - 5 + args.extension if read.is_reverse else read.reference_end + args.extension) + read_qual = read.mapping_quality + if read.is_reverse: + read_orient = '-' + else: + read_orient = '+' + barcode_coverage[barcode] = barcode_coverage.get(barcode, 0) + 1 + line_out = '\t'.join([read_chr, str(read_start), str(read_end), '{}_{}'.format(args.name,barcode), str(read_qual), read_orient]) + print(line_out, sep='\t', file=f) + bamfile.close() + else: + raise FileNotFoundError('{} not found!'.format(rmdup_bam)) + + barcode_counts = args.output_prefix + '.barcode_counts.txt' + with open(barcode_counts, 'w') as f: + print('barcode', 'count', sep='\t', file=f) + for bc in barcode_coverage: + print('{}_{}'.format(args.name,bc), barcode_coverage[bc], sep='\t', file=f) + pass_barcodes = ['{}_{}'.format(args.name, bc) for bc in barcode_coverage if barcode_coverage[bc] >= args.minimum_reads] + + barcodes_file = args.output_prefix + '.barcodes' + peaks_file = args.output_prefix + '.peaks' + mtx_file = args.output_prefix + '.int.csr.npz' + + matrix = {} + + regions_file = make_windows(args) + peak_intersect = intersect_helper(tagalign_file, regions_file) + + for line in peak_intersect.stdout: + line = line.decode().rstrip('\n') + fields = line.split('\t') + barcode = fields[3] + peak = fields[9] + if barcode not in pass_barcodes: + continue + if peak not in matrix: + matrix[peak] = {} + matrix[peak][barcode] = matrix[peak].get(barcode, 0) + 1 + + threshold = 2 + for peak in list(matrix): + if len(matrix[peak].keys()) < threshold: + del matrix[peak] + peaks = list(matrix) + barcodes = pass_barcodes + mtx = scipy.sparse.dok_matrix((len(barcodes), len(peaks)), dtype=int) + for b in range(len(barcodes)): + for p in range(len(peaks)): + if barcodes[b] in matrix[peaks[p]]: + mtx[b,p] = matrix[peaks[p]][barcodes[b]] + mtx = mtx.tocsr() + scipy.sparse.save_npz(mtx_file, mtx) + + with open(barcodes_file, 'w') as f: + print('\n'.join(barcodes), file=f) + with open(peaks_file, 'w') as f: + print('\n'.join(peaks), file=f) + return + +def intersect_helper(tagalign, regions): + awk_cmd = ['awk', '''BEGIN{{FS=OFS=""\\t""}} {{peakid=$1"":""$2""-""$3; gsub(""chr"","""",peakid); print $1, $2, $3, peakid}}''', regions] + intersect_cmd = ['bedtools', 'intersect', '-a', tagalign, '-b', '-', '-wa', '-wb'] + awk = subprocess.Popen(awk_cmd, stdout=subprocess.PIPE) + intersect = subprocess.Popen(intersect_cmd, stdin=awk.stdout, stdout=subprocess.PIPE) + return intersect + +def make_windows(args): + makewindows_cmd = ['bedtools', 'makewindows', '-g', args.chrom_sizes, '-w', str(args.window_size * 1000)] + filter_cmd = ['grep', '-v', '_'] + blacklist_cmd = ['bedtools', 'intersect', '-a', '-', '-b', args.blacklist, '-v'] + + regions_file = '{}.{}kb_windows.bed'.format(args.output_prefix, args.window_size) + with open(regions_file, 'w') as f: + makewindows = subprocess.Popen(makewindows_cmd, stdout=subprocess.PIPE) + filt = subprocess.Popen(filter_cmd, stdin=makewindows.stdout, stdout=subprocess.PIPE) + subprocess.call(blacklist_cmd, stdin=filt.stdout, stdout=f) + return regions_file + +def main(args): + logging.info('Start.') + if not os.path.isdir(args.output): + os.makedirs(args.output) + args.output_prefix = os.path.join(args.output, args.name) + if not args.skip_trim: + logging.info('Trimming adapters using trim_galore.') + args.read1, args.read2 = trim_reads(args) + if not args.skip_align: + logging.info('Aligning reads using BWA mem with [{}] processors.'.format(args.threads)) + logging.info('Piping output to samtools using [{}] Gb of memory.'.format(args.memory)) + align_reads(args) + if not args.skip_rmdup: + logging.info('Removing duplicate and mitochrondrial reads.'.format(args.minimum_reads)) + remove_duplicate_reads(args) + if not args.skip_matrix: + logging.info('Generating tagalign and chromatin accessibility matrix.') + generate_binary_matrix(args) + logging.info('Finish.') + return + +def process_args(): + parser = argparse.ArgumentParser(description='Align demulitplexed snATAC-seq reads to a reference genome.') + io_group = parser.add_argument_group('I/O arguments') + io_group.add_argument('-r1', '--read1', required=True, type=str, help='Paired-end reads file 1') + io_group.add_argument('-r2', '--read2', required=True, type=str, help='Paired-end reads file 2') + io_group.add_argument('-o', '--output', required=False, type=str, default=os.getcwd(), help='Output directory to store processed files') + io_group.add_argument('-n', '--name', required=True, type=str, help='Prefix for naming all output files') + + align_group = parser.add_argument_group('Alignment arguments') + align_group.add_argument('-t', '--threads', required=False, type=int, default=8, help='Number of threads to use for alignment [8]') + align_group.add_argument('-m', '--memory', required=False, type=int, default=4, help='Maximum amount of memory (G) per thread for samtools sort [4]') + align_group.add_argument('-q', '--map_quality', required=False, type=int, default=30, help='Mapping quality score filter for samtools [30]') + align_group.add_argument('-ref', '--reference', required=False, type=str, default='/home/joshchiou/references/male.hg19.fa', help='Path to the BWA-prepared reference genome') + + dup_group = parser.add_argument_group('Remove duplicates arguments') + dup_group.add_argument('--picard', required=False, type=str, default='/home/joshchiou/bin/picard.jar', help='Path to picard.jar') + + matrix_group = parser.add_argument_group('Matrix generation arguments') + matrix_group.add_argument('--extension', required=False, type=int, default=75, help='Read extension length') + matrix_group.add_argument('--minimum-reads', required=False, type=int, default=1000, help='Minimum number of reads for barcode inclusion') + matrix_group.add_argument('--window-size', required=False, type=int, default=5, help='Size (kb) to use for defining windows of accessibility') + matrix_group.add_argument('--chrom-sizes', required=False, type=str, default='/home/joshchiou/references/hg19.chrom.sizes', help='Chromosome sizes file from UCSC') + matrix_group.add_argument('--blacklist', required=False, type=str, default='/home/joshchiou/references/ENCODE.hg19.blacklist.bed', help='BED file of blacklisted regions') + + skip_group = parser.add_argument_group('Skip steps') + skip_group.add_argument('--skip-trim', required=False, action='store_true', default=False, help='Skip adapter trimming step') + skip_group.add_argument('--skip-align', required=False, action='store_true', default=False, help='Skip read alignment step') + skip_group.add_argument('--skip-rmdup', required=False, action='store_true', default=False, help='Skip duplicate removal step') + skip_group.add_argument('--skip-matrix', required=False, action='store_true', default=False, help='Skip matrix generation step') + return parser.parse_args() + +if __name__ == '__main__': + logging.basicConfig(format='[%(filename)s] %(asctime)s %(levelname)s: %(message)s', datefmt='%I:%M:%S', level=logging.INFO) + args = process_args() + main(args) +","Python" +"Epigenetics","kjgaulton/pipelines","snATAC-seq/snATAC_analysis.ipynb",".ipynb","8972","224","{ + ""cells"": [ + { + ""cell_type"": ""code"", + ""execution_count"": 220, + ""metadata"": {}, + ""outputs"": [ + { + ""name"": ""stdout"", + ""output_type"": ""stream"", + ""text"": [ + ""The rpy2.ipython extension is already loaded. To reload it, use:\n"", + "" %reload_ext rpy2.ipython\n"" + ] + } + ], + ""source"": [ + ""import os\n"", + ""import gzip\n"", + ""import numpy as np\n"", + ""import pandas as pd\n"", + ""import scanpy.api as sc\n"", + ""import matplotlib.pyplot as plt\n"", + ""import seaborn as sns\n"", + ""import statsmodels.api as sm\n"", + ""import sklearn.preprocessing\n"", + ""import scipy.sparse\n"", + ""from anndata import AnnData"" + ] + }, + { + ""cell_type"": ""markdown"", + ""metadata"": {}, + ""source"": [ + ""# Analysis for a single sample"" + ] + }, + { + ""cell_type"": ""code"", + ""execution_count"": null, + ""metadata"": {}, + ""outputs"": [], + ""source"": [ + ""%%time\n"", + ""\n"", + ""wd = '/home/ndeforest/islet_snATAC/raw_data/biobank_2/'\n"", + ""sp = scipy.sparse.load_npz(os.path.join(wd, 'A0016_T2D.int.csr.npz'))\n"", + ""peaks = open(os.path.join(wd, 'A0016_T2D.peaks')).read().splitlines()\n"", + ""barcodes = open(os.path.join(wd, 'A0016_T2D.barcodes')).read().splitlines()\n"", + ""adata = AnnData(sp, {'obs_names':barcodes}, {'var_names':peaks})\n"", + ""\n"", + ""promoters = pd.read_table(os.path.join('/home/joshchiou/joshchiou-data2/islet_snATAC/fresh_only/', 'hg19.5kb.promoter.txt'), sep='\\t', header=None, index_col=0, names=['prom'])\n"", + ""promoter_names = promoters['prom'].to_dict()\n"", + ""adata.var.index = [promoter_names[b] if b in promoter_names else b for b in adata.var.index]\n"", + ""adata.var_names_make_unique(join='.')\n"", + ""\n"", + ""adata.obs['n_counts'] = adata.X.sum(axis=1).A1\n"", + ""adata.obs['log10_n_counts'] = np.log10(adata.obs['n_counts'])\n"", + ""adata.raw = AnnData(adata.X > 0, {'obs_names':adata.obs.index}, {'var_names':adata.var.index})\n"", + ""\n"", + ""sc.pp.normalize_per_cell(adata, counts_per_cell_after=1e4)\n"", + ""adata_filter = sc.pp.filter_genes_dispersion(adata.X, flavor='seurat', n_bins=50)\n"", + ""hvgs = adata.var.loc[adata_filter.gene_subset].index.tolist()\n"", + ""\n"", + ""adata = adata[:,adata.var.index.isin(hvgs)]\n"", + ""sc.pp.normalize_per_cell(adata, counts_per_cell_after=1e4)\n"", + ""\n"", + ""sc.pp.log1p(adata)\n"", + ""sc.pp.regress_out(adata, ['log10_n_counts'])\n"", + ""sc.pp.scale(adata)\n"", + ""sc.tl.pca(adata, zero_center=False, random_state=0)\n"", + ""sc.pp.neighbors(adata, n_neighbors=30, method='umap', metric='cosine', random_state=0, n_pcs=50)\n"", + ""sc.tl.louvain(adata, resolution=1.5, random_state=0)\n"", + ""sc.tl.umap(adata, min_dist=0.3, random_state=0)\n"", + ""sc.pl.umap(adata, color=['louvain'], size=49, legend_loc='on data')\n"", + ""sc.pl.umap(adata, color=['log10_n_counts'], size=49, color_map='Blues')\n"", + ""\n"", + ""sc.pl.umap(adata, color=['INS-IGF2','GCG','SST'], size=49, color_map='Blues', use_raw=True)\n"", + ""sc.pl.umap(adata, color=['PPY','NKX2-3','REG1A'], size=49, color_map='Blues', use_raw=True)\n"", + ""sc.pl.umap(adata, color=['CFTR','PTPN22','PDGFRB'], size=49, color_map='Blues', use_raw=True)\n"", + ""sc.pl.umap(adata, color=['ARX','PDX1','HOXA5'], size=49, color_map='Blues', use_raw=True)"" + ] + }, + { + ""cell_type"": ""markdown"", + ""metadata"": {}, + ""source"": [ + ""# Analysis with MNN correction for multiple samples"" + ] + }, + { + ""cell_type"": ""code"", + ""execution_count"": 2, + ""metadata"": {}, + ""outputs"": [ + { + ""name"": ""stdout"", + ""output_type"": ""stream"", + ""text"": [ + ""CPU times: user 21.4 s, sys: 7.34 s, total: 28.8 s\n"", + ""Wall time: 28.8 s\n"" + ] + } + ], + ""source"": [ + ""%%time\n"", + ""\n"", + ""# merged dataset from 3 islet samples\n"", + ""wd = '/home/joshchiou/joshchiou-data2/islet_snATAC/fresh_only/'\n"", + ""sp = scipy.sparse.load_npz(os.path.join(wd, 'Islet_1234.5kb.int.csr.npz'))\n"", + ""peaks = pd.read_table(os.path.join(wd, 'Islet_1234.5kb.int.peaks'), header=None, names=['peaks'])\n"", + ""barcodes = pd.read_table(os.path.join(wd, 'Islet_1234.5kb.int.barcodes'), header=None, names=['barcodes'])\n"", + ""remove = pd.read_table(os.path.join(wd, 'Islet_123.remove'), header=None, names=['remove'])\n"", + ""\n"", + ""adata = AnnData(sp, {'obs_names':barcodes['barcodes']}, {'var_names':peaks['peaks']})\n"", + ""adata.raw = AnnData(sp > 0, {'obs_names':barcodes['barcodes']}, {'var_names':adata.var.index})\n"", + ""adata.obs['n_counts'] = adata.X.sum(axis=1).A1\n"", + ""adata.obs['log10_n_counts'] = np.log10(adata.obs['n_counts'])\n"", + ""\n"", + ""adata.obs['Islet1'] = adata.obs.index.str.contains('Islet1').astype(int)\n"", + ""adata.obs['Islet2'] = adata.obs.index.str.contains('Islet2').astype(int)\n"", + ""adata.obs['Islet3'] = adata.obs.index.str.contains('Islet3').astype(int)\n"", + ""adata.var['n_cells'] = adata.raw.X.sum(axis=0).A1\n"", + ""\n"", + ""sc.pp.normalize_per_cell(adata, counts_per_cell_after=1e4)\n"", + ""adata_filter = sc.pp.filter_genes_dispersion(adata.X, flavor='seurat', n_bins=50)\n"", + ""hvgs = adata.var.loc[adata_filter.gene_subset].index.tolist()\n"", + ""adata.var['Islet1'] = (adata.raw.X > 0)[adata.obs.index.str.contains('Islet1'),:].sum(axis=0).A1\n"", + ""adata.var['Islet2'] = (adata.raw.X > 0)[adata.obs.index.str.contains('Islet2'),:].sum(axis=0).A1\n"", + ""adata.var['Islet3'] = (adata.raw.X > 0)[adata.obs.index.str.contains('Islet3'),:].sum(axis=0).A1\n"", + ""hvgs = adata.var.loc[adata.var.index.isin(hvgs)]\n"", + ""hvgs = hvgs.loc[(hvgs['Islet1'] > 0) & (hvgs['Islet2'] > 0) & (hvgs['Islet3'] > 0)].index\n"", + ""adata.var = adata.var.drop(['Islet1','Islet2','Islet3'], axis=1)\n"", + ""\n"", + ""sp = sp_filt = None"" + ] + }, + { + ""cell_type"": ""code"", + ""execution_count"": null, + ""metadata"": { + ""scrolled"": true + }, + ""outputs"": [], + ""source"": [ + ""%%time\n"", + ""\n"", + ""# regress out read depth\n"", + ""adatas = {}\n"", + ""for sample in ['Islet1','Islet2','Islet3']:\n"", + "" adatas[sample] = adata[adata.obs.index.str.contains(sample), :]\n"", + "" adatas[sample] = adatas[sample][:, adatas[sample].var.index.isin(hvgs)]\n"", + "" sc.pp.normalize_per_cell(adatas[sample], counts_per_cell_after=1e4)\n"", + "" sc.pp.log1p(adatas[sample])\n"", + "" sc.pp.regress_out(adatas[sample], ['log10_n_counts'])\n"", + ""\n"", + ""# perform MNN correction\n"", + ""adata_mnn = sc.pp.mnn_correct(adatas['Islet3'], adatas['Islet2'], adatas['Islet1'], k=10, batch_key='donor', index_unique=None)[0]\n"", + ""adata_mnn.write(os.path.join(wd, 'Islet_123.MNN_corrected.h5ad'))"" + ] + }, + { + ""cell_type"": ""code"", + ""execution_count"": null, + ""metadata"": { + ""scrolled"": true + }, + ""outputs"": [], + ""source"": [ + ""sc.pp.scale(adata_mnn)\n"", + ""sc.tl.pca(adata_mnn, zero_center=True, svd_solver='arpack', random_state=0)\n"", + ""sc.pp.neighbors(adata_mnn, n_neighbors=30, method='umap', metric='cosine', random_state=0, n_pcs=50)\n"", + ""sc.tl.louvain(adata_mnn, resolution=1.5, random_state=0)\n"", + ""sc.tl.umap(adata_mnn, n_components=2, min_dist=0.3, random_state=0)\n"", + ""sc.pl.umap(adata_mnn, color=['louvain'], size=16, legend_loc='on data')\n"", + ""donor_map = {'0':'3', '1':'2', '2':'1'}\n"", + ""adata_mnn.obs['donor'] = adata_mnn.obs['donor'].map(donor_map)\n"", + ""# clusters projected onto UMAP\n"", + ""sc.pl.umap(adata_mnn, color=['donor'], size=16, alpha=.5)\n"", + ""# donor projected onto UMAP\n"", + ""sc.pl.umap(adata_mnn, color=['log10_n_counts'], size=16, color_map='Blues')\n"", + ""\n"", + ""# read depth boxplot\n"", + ""fig, ax1 = plt.subplots(1,1,figsize=(7,5))\n"", + ""sns.boxplot(x='louvain', y='log10_n_counts', data=adata_mnn.obs)\n"", + ""plt.show()\n"", + ""\n"", + ""# correlation with PCs\n"", + ""pc = pd.DataFrame(adata_mnn.obsm['X_pca'], index=adata_mnn.obs.index, columns=['PC{}'.format(i) for i in range(1,51)])\n"", + ""pc = pc.join(adata_mnn.obs[['log10_n_counts', 'log10_n_peaks', 'Islet1', 'Islet2', 'Islet3']], how='inner')\n"", + ""fig, ax1 = plt.subplots(1,1,figsize=(10,10))\n"", + ""sns.heatmap(pc.corr(), ax=ax1)\n"", + ""plt.show()\n"", + ""\n"", + ""# marker genes projected onto UMAP\n"", + ""sc.pl.umap(adata_mnn, color=['INS-IGF2','GCG','SST'], size=16, color_map='Blues', use_raw=True)\n"", + ""sc.pl.umap(adata_mnn, color=['PPY','NKX2-3','REG1A'], size=16, color_map='Blues', use_raw=True)\n"", + ""sc.pl.umap(adata_mnn, color=['CFTR','PTPN22','PDGFRB'], size=16, color_map='Blues', use_raw=True)"" + ] + } + ], + ""metadata"": { + ""kernelspec"": { + ""display_name"": ""Python 3"", + ""language"": ""python"", + ""name"": ""python3"" + }, + ""language_info"": { + ""codemirror_mode"": { + ""name"": ""ipython"", + ""version"": 3 + }, + ""file_extension"": "".py"", + ""mimetype"": ""text/x-python"", + ""name"": ""python"", + ""nbconvert_exporter"": ""python"", + ""pygments_lexer"": ""ipython3"", + ""version"": ""3.6.6"" + } + }, + ""nbformat"": 4, + ""nbformat_minor"": 2 +} +","Unknown" +"Epigenetics","kjgaulton/pipelines","ATAC-seq_footprinting/run_fimo.py",".py","1388","47","#!/usr/bin/python3 + +import os +import sys +import subprocess +from multiprocessing import Pool + +sample = sys.argv[1] + +def runFimo(motifName, sampleName): + d_base = '/home/joshchiou/joshchiou-data2/FACS.alpha+beta_cells/' + d_seqs = os.path.join(d_base, 'seqs') + d_bed = os.path.join(d_base, 'motifs', sampleName) + + dataPWM = os.path.join('/home/joshchiou/references/combined.motif_database.meme') + seqFasta = os.path.join(d_seqs, '.'.join([sampleName, 'seqs.fa'])) + motifBed = os.path.join(d_bed, '.'.join([motifName, sampleName, 'bed'])) + + d_list = [d_base, d_seqs, d_bed] + for d in d_list: + if not os.path.exists(d): + try: + os.makedirs(d) + except: + pass + + try: + with open(os.devnull, 'w') as f: + subprocess.call('fimo --parse-genomic-coord --max-strand --skip-matched-sequence --bgfile motif-file --motif {0} {1} {2} | awk \'BEGIN{{FS=OFS=\""\\t\""}} NR>1 {{print $3,$4,$5+1,$1,$7,$6}}\' | sort -k1,1 -k2,2n | awk -F\""\\t\"" \'!uniq[$1 FS $2 FS $3 FS $6]++\' > {3}'.format(motifName, dataPWM, seqFasta, motifBed), stderr=f, shell=True) + except: + sys.stderr.write(Exception) + sys.stderr.write('\n') + pass + return + +with open('/home/joshchiou/references/combined_motifs.list','r') as f: + motifList = f.read().splitlines() + +argsList=[] +for motif in motifList: + argsList.append((motif, sample)) + +pool = Pool(processes=(24)) +pool.starmap(runFimo, argsList) +pool.close() +pool.join() +","Python" +"Epigenetics","kjgaulton/pipelines","ATAC-seq_footprinting/get_alternative_sequence.py",".py","1941","57","#!/usr/bin/env python3 + +import argparse +import subprocess +from pyfaidx import Fasta + +def process_args(): + parser = argparse.ArgumentParser(description='Script to insert SNP alleles into reference sequences') + parser.add_argument('-p', '--peaks', required=True, type=str, help='Path to peaks file (3 col)') + parser.add_argument('-v', '--variants', required=True, type=str, help='Path to variants bed-like file (6 col)') + parser.add_argument('-f', '--fasta', required=True, type=str, help='Path to reference fasta') + return parser.parse_args() + +def get_alt_sequence(args, fasta, chrom, start, stop, var, ref, alt): + header = '>{0}:{1}-{2}\t{0}:{3}_{4}/{5}'.format(chrom, start, stop, var, ref, alt) + left = fasta[chrom][start:var-1] + right = fasta[chrom][var:stop] + ref_sequence = left + ref + right + alt_sequence = left + alt + right + return header, ref_sequence, alt_sequence + +def load_fasta(args): + fasta = Fasta(args.fasta, as_raw=True) + return fasta + +def get_atac_variants(args): + intersect_out = '.'.join([args.peaks.split('.bed')[0], args.variants.split('.bed')[0], 'tmp']) + cmd = ['bedtools', 'intersect', + '-a', args.peaks, + '-b', args.variants, + '-wa','-wb'] + with open(intersect_out, 'w') as f: + subprocess.call(cmd, stdout=f) + return intersect_out + +def process_intersect(line): + fields = line.split('\t') + chrom, start, stop = fields[0], int(fields[1]), int(fields[2]) + var, ref, alt = int(fields[5]), fields[7], fields[8] + return chrom, start, stop, var, ref, alt + +def main(args): + intersect_out = get_atac_variants(args) + fasta = load_fasta(args) + with open(intersect_out, 'r') as f: + lines = f.read().splitlines() + for line in lines: + chrom, start, stop, var, ref, alts = process_intersect(line) + for alt in alts.split(','): + header, ref_sequence, alt_sequence = get_alt_sequence(args, fasta, chrom, start, stop, var, ref, alt) + print(header) + print(alt_sequence) + return + +args = process_args() +main(args) +","Python" +"Epigenetics","kjgaulton/pipelines","ATAC-seq_footprinting/count_footprints_normalized.py",".py","1623","52","#!/usr/bin/env python3 + +import os +import argparse +import numpy as np +import pandas as pd +pd.options.display.float_format = '${:,.2f}'.format + +def process_args(): + parser = argparse.ArgumentParser(description='Insert a useful description here') + parser.add_argument('-d','--dirs', nargs='+', required=True, type=str, help='List of directories containing footprints') + parser.add_argument('-l', '--motifs', required=False, type=str, default='/home/joshchiou/references/combined_motifs.list', help='Path to list of motifs') + return parser.parse_args() + +def proc_header(args): + basenames = [os.path.basename(d.rstrip('/')) for d in args.dirs] + return basenames + +def load_motifs(args): + with open(args.motifs) as f: + motif_list = f.read().splitlines() + return motif_list + +def count_footprints(fp_file): + if not os.path.exists(fp_file): + return 0 + with open(fp_file) as f: + count = sum(1 for line in f) + return count + +def process_dataframe(table): + df = pd.DataFrame(table[1:], columns=table[0]).set_index('Motif') + df = df[(df.T != 0).any()] + totals = [np.sum(df[column]) for column in df] + norm_factor = totals/min(totals) + for i,column in enumerate(df): + df[column] = df[column] / norm_factor[i] + return df + +def main(args): + table = [['Motif'] + proc_header(args)] + motif_list = load_motifs(args) + for motif in motif_list: + counts = [count_footprints(os.path.join(d, '.'.join([motif,os.path.basename(d.rstrip('/')),'footprints.bed']))) for d in args.dirs] + table.append([motif] + counts) + data = process_dataframe(table) + data.round(2).to_csv('normalized_counts.tab', sep='\t') + return + +args = process_args() +main(args) +","Python" +"Epigenetics","kjgaulton/pipelines","ATAC-seq_footprinting/multi-centipede.py",".py","2721","74","#!/usr/bin/python3 + +import os +import sys +import subprocess +from multiprocessing import Pool + +sample = sys.argv[1] + +def runCentipede(motifName, sampleName): + d_base = '/home/joshchiou/joshchiou-data2/FACS.alpha+beta_cells/' + d_bam = os.path.join(d_base, 'bams') + d_bed = os.path.join(d_base, 'motifs', sampleName) + d_matrix = os.path.join(d_base, 'matrices', sampleName) + d_centipede = os.path.join(d_base, 'centipede', sampleName) + d_log = os.path.join(d_centipede, 'log') + d_post_centipede = os.path.join(d_base, 'post-centipede', sampleName) + + readsBam = os.path.join(d_bam, '.'.join([sampleName, 'bam'])) + motifBed = os.path.join(d_bed, '.'.join([motifName, sampleName, 'bed'])) + motifMatrix = os.path.join(d_matrix, '.'.join([motifName, sampleName, 'discrete.matrix.gz'])) + centipedeLog = os.path.join(d_centipede, 'log', '.'.join([motifName, sampleName, 'centipede.log'])) + + d_list = [d_base, d_bam, d_bed, d_matrix, d_centipede, d_log, d_post_centipede] + for d in d_list: + if not os.path.exists(d): + try: + os.makedirs(d) + except: + pass + if os.path.exists(motifBed) and os.path.getsize(motifBed) > 0: + try: + with open(centipedeLog, 'w') as f: + subprocess.call( + 'make_cut_matrix -d -b \'(1-100000 1)\' -p 1 {0} {1} | gzip -c > {2}'.format(readsBam, motifBed, motifMatrix), + stdout=f, + stderr=f, + shell=True) + except: + sys.stderr.write(Exception) + sys.stderr.write('\n') + pass + + if os.path.isfile(motifMatrix): + try: + with open(centipedeLog, 'a') as f: + subprocess.call('./centipede.R {0} {1} {2}'.format(motifMatrix, motifBed, sampleName), + stdout=f, + stderr=f, + shell=True) + except: + sys.stderr.write(Exception) + sys.stderr.write('\n') + pass + + centipedeOut = os.path.join(d_centipede, '.'.join([motifName, sampleName, 'PostPr.txt'])) + combinedOut = os.path.join(d_post_centipede, '.'.join([motifName, sampleName, 'footprints.bed'])) + + if os.path.isfile(centipedeOut): + subprocess.call('paste {0} {1} | awk \'$7 > 0.95\' > {2}'.format(motifBed, centipedeOut, combinedOut), shell=True) + return + +with open('/home/joshchiou/references/combined_motifs.list','r') as f: + motifList = f.read().splitlines() + +argsList=[] +for motif in motifList: + argsList.append((motif, sample)) + +pool = Pool(processes=(24)) +pool.starmap(runCentipede, argsList) +pool.close() +pool.join() +","Python" +"Epigenetics","kjgaulton/pipelines","kglab-python3-modules/chipseqpeaks.py",".py","7361","255","#!/usr/bin/env python3 +#=============================================================================== +# chipseqpeaks.py +#=============================================================================== + +""""""Easy management of ChIP-seq peak calling data + +A mini-module for managing ChIP-seq peak calling data. The language of this +module treats ""ChIP-seq peaks"" as an abstraction, but mostly handles them as +MACS2 output stored in memory. + +Example +------- +with chipseqpeaks.ChipSeqPeaks( + input_bam='bytes object or path to BAM file' +) as cp: + cp.cleans_up = False + cp.blacklist('path to blacklist') + cp.write('output prefix') + +Class +---------------- +ChipSeqPeaks + object representing ChIP-seq peaks + +Function +--------- +check_input + check that an input is str or bytes +"""""" + + + + +# Imports ====================================================================== + +import os +import os.path +import subprocess +import socket +import sys +import tempfile + + + + +# Classes ====================================================================== + +class ChIPSeqPeaks(): + """"""ChIP-seq peaks"""""" + + def __init__( + self, + treatment_bam, + control_bam=None, + qvalue=0.05, + nomodel=False, + shift=0, + broad=False, + broad_cutoff=0.1, + log=None + ): + self.treatment_bam = check_input(treatment_bam) + self.control_bam = check_input(control_bam) if control_bam else None + self.qvalue = qvalue + self.nomodel = nomodel + self.shift = shift + self.broad = broad + self.broad_cutoff = broad_cutoff + self.cleans_up = False + self.cleanup_prefix = None + self.log = log + self.output_extensions = ( + ( + 'peaks.xls', + 'peaks.narrowPeak', + 'summits.bed', + 'treat_pileup.bdg' + ) + + + ('control_lambda.bdg',) * bool(control_bam) + + + ('peaks.broadPeak', 'peaks.gappedPeak') * broad + + ) + self.call_peaks() + + def __enter__(self): + self.cleans_up = True + return self + + def __exit__(self, exc_type, exc_value, traceback): + if self.cleans_up: + for ext in self.output_extensions: + self.clean_up('{}_{}'.format(self.cleanup_prefix, ext)) + return False + + def __repr__(self): + return '\n'.join( + 'ChipPeaks(', + ')' + ).format(self) + + def call_peaks(self): + with tempfile.NamedTemporaryFile() as ( + temp_treatment_bam + ), tempfile.NamedTemporaryFile() as ( + temp_control_bam + ), tempfile.TemporaryDirectory() as ( + temp_dir_name + ): + temp_treatment_bam.write(self.treatment_bam) + if self.control_bam: + temp_control_bam.write(self.control_bam) + with tempfile.NamedTemporaryFile( + dir=temp_dir_name + ) as temp: + temp_name = temp.name + subprocess.call( + ( + 'macs2', 'callpeak', + '-B', + '--extsize', '200', + '--keep-dup', 'all', + '--treatment', temp_treatment_bam.name, + '--name', temp_name, + '--qvalue', str(self.qvalue), + '--shift', str(self.shift), + ) + + + ( + ('--control', temp_control_bam.name) + * + bool(self.control_bam) + ) + + + ('--nomodel',) * self.nomodel + + + ( + ('--broad', '--broad-cutoff', str(self.broad_cutoff)) + * + self.broad + ), + stderr=self.log + ) + for ext in self.output_extensions: + with subprocess.Popen( + ('cat', '{}_{}'.format(temp_name, ext)), + stdout=subprocess.PIPE + ) as cat: + output_file, _ = cat.communicate() + setattr(self, ext.replace('.', '_'), output_file) + + def bdgcmp(self): + self.output_extensions = self.output_extensions + ('ppois.bdg',) + with tempfile.NamedTemporaryFile() as ( + temp_treat_pileup + ), tempfile.NamedTemporaryFile() as ( + temp_control_lambda + ), tempfile.TemporaryDirectory() as ( + temp_dir_name + ): + temp_treat_pileup.write(self.treat_pileup_bdg) + temp_control_lambda.write(self.control_lambda_bdg) + with tempfile.NamedTemporaryFile( + dir=temp_dir_name + ) as temp: + temp_name = temp.name + subprocess.call( + ( + 'macs2', 'bdgcmp', + '-t', temp_treat_pileup.name, + '-c', temp_control_lambda.name, + '-m', 'ppois', + '--o-prefix', temp_name, + '-p', '0.00001' + ), + stderr=self.log + ) + with subprocess.Popen( + ('cat', '{}_ppois.bdg'.format(temp_name)), + stdout=subprocess.PIPE + ) as cat: + self.ppois_bdg, _ = cat.communicate() + + def blacklist(self, blacklist_path): + for peaks in ( + (self.peaks_narrowPeak,) + + + ( + (self.peaks_broadPeak, self.peaks_gappedPeak) + if + self.broad + else + () + ) + ): + with subprocess.Popen( + ( + 'bedtools', + 'intersect', + '-v', + '-a', 'stdin', + '-b', blacklist_path, + '-wa' + ), + stdin=subprocess.PIPE, + stdout=subprocess.PIPE, + stderr=self.log + ) as bedtools_intersect: + peaks, _ = bedtools_intersect.communicate( + input=peaks + ) + + def write(self, prefix, *extensions): + for ext in (extensions if extensions else self.output_extensions): + with open('{}_{}'.format(prefix, ext), 'wb') as f: + f.write(getattr(self, ext.replace('.', '_'))) + self.cleanup_prefix = prefix + + def clean_up(self, path): + if (os.path.isfile(path) if path else False): + os.remove(path) + + + + +# Exceptions =================================================================== + +class Error(Exception): + """"""Base class for other exceptions"""""" + pass + + +class BadInputError(Error): + """"""Bad input error"""""" + pass + + + + +# Functions ==================================================================== + +def check_input(input_file): + """"""Check that an input is str or bytes"""""" + + if isinstance(input_file, bytes): + bytes_obj = input_file + elif isinstance(input_file, str): + with open(input_file, 'rb') as f: + bytes_obj = f.read() + else: + raise BadInputError('Input must be either str or bytes') + return bytes_obj +","Python" +"Epigenetics","kjgaulton/pipelines","kglab-python3-modules/namedpipe.py",".py","1065","47","#!/usr/bin/env python3 +#=============================================================================== +# namedpipe.py +#=============================================================================== + +""""""Utility for named pipes"""""" + + + + +# Imports ====================================================================== + +import os +import tempfile + + + + +# Classes ====================================================================== + +class NamedPipe(): + '''Context manager for a named pipe''' + + def __init__(self, pipe_name): + self.name = pipe_name + os.mkfifo(pipe_name) + + def __enter__(self): + return self + + def __exit__(self, exc_type, exc_value, traceback): + os.remove(self.name) + return False + + def __repr_(self): + return ""NamedPipe('{}')"".format(self.name) + + + + +# Functions ==================================================================== + +def temp_named_pipe(): + with tempfile.NamedTemporaryFile(dir='/home/data/tmp') as temp: + pipe_name = temp.name + return NamedPipe(pipe_name) +","Python" +"Epigenetics","kjgaulton/pipelines","kglab-python3-modules/footprints.py",".py","8717","329","#!/usr/bin/env python3 +#=============================================================================== +# footprints.py +#=============================================================================== + +""""""Easy management of transcription factor footprinting data + +A mini-module for managing footprint data. The language of this module treats +""footprints"" as an abstraction, but mostly handles them as a JSON object / +dictionary containing the results of a centipede fit. + +Example +------- +with footprints.Footprints( + input_bam='bytes object or path to BAM file', + input_peaks='bytes object or path to peaks file', + motifs_db_path='path to motifs database' +) as fp: + fp.cleans_up_footprints = False + fp.dump_json('Path to output footprints file') + +High-level class +---------------- +Footprints + object representing footprints + +Low-level classes +----------------- +Centipede + class containing Centipede commands +NamedPipe + context manager for a named pipe + +Function +--------- +check_input + check that an input is str or bytes +"""""" + + + + +# Constants ==================================================================== + +CENTIPEDE_SCRIPT = ( +'''#!/usr/bin/R + +sink(""/dev/null"") + +library(jsonlite) +library(CENTIPEDE) +library(CENTIPEDE.tutorial) +suppressMessages(library(Rsamtools)) + +args=commandArgs(trailingOnly=T) +motifs <- args[1] +bam.sorted <- args[2] +test_motif <- args[3] + +cen <- centipede_data( + bam_file=bam.sorted, + fimo_file=motifs, + pvalue=1e-4, + flank_size=100 +) + +fit <- fitCentipede( + Xlist = list(DNase = cen$mat), + Y = as.matrix(data.frame( + Intercept = rep(1, nrow(cen$mat)) + )) +) + +json_fit <- toJSON(fit) + +sink() + +cat(json_fit) +''' +) + + + + +# Imports ====================================================================== + +import json +import os +import os.path +import socket +import subprocess +import sys +import tempfile +from multiprocessing import Pool + +hostname = socket.gethostname() +if hostname == 'gatsby.ucsd.edu': + sys.path.append('/home/data/kglab-python3-modules') +elif hostname == 'holden': + sys.path.append('/lab/kglab-python3-modules') + +import hg19 +import namedpipe + + + + +# Classes ====================================================================== + +class Footprints(): + """"""TF footprints"""""" + + def __init__( + self, + input_bam, + input_peaks, + motifs_db_path, + centipede_path=None, + input_bam_index=None, + reference_genome_path=hg19.PATH, + processes=1 + ): + self.bam = check_input(input_bam) + self.bam_index = ( + check_input(input_bam_index) + if + input_bam_index + else + None + ) + self.peaks = check_input(input_peaks) + self.motifs_db_path = motifs_db_path + self.centipede_path = centipede_path + self.reference_genome_path = reference_genome_path + self.processes = processes + self.cleans_up_footprints = False + self.cleans_up_motifs = False + self.footprints_file_path = None + self.motifs_file_path = None + self.get_fasta() + self.find_motifs() + self.infer_footprints() + + def __enter__(self): + self.cleans_up_footprints = True + self.cleans_up_motifs = True + return self + + def __exit__(self, exc_type, exc_value, traceback): + if self.cleans_up_footprints: + self.clean_up(self.footprints_file_path) + if self.cleans_up_motifs: + self.clean_up(self.motifs_file_path) + return False + + def __repr__(self): + return '\n'.join( + 'Footprints(', + ')' + ).format(self) + + def get_fasta(self): + with namedpipe.temp_named_pipe() as peaks_pipe: + with subprocess.Popen( + ( + 'sh', + '-c', + ( + 'bedtools getfasta -bed {0} -fi {1} & cat > {0}' + .format(peaks_pipe.name, self.reference_genome_path) + ) + ), + stdin=subprocess.PIPE, + stdout=subprocess.PIPE + ) as bedtools_getfasta: + self.fasta, _ = bedtools_getfasta.communicate(input=self.peaks) + + def find_motifs(self): + with tempfile.NamedTemporaryFile() as temp_fasta: + temp_fasta.write(self.fasta) + with subprocess.Popen( + ( + 'fimo', + '--parse-genomic-coord', + '--max-strand', + '--text', + self.motifs_db_path, + temp_fasta.name + ), + stdout=subprocess.PIPE + ) as fimo: + self.motifs, _ = fimo.communicate() + + def infer_footprints(self): + motif_names = { + line.split('\t')[0] + for + line + in + self.motifs.decode().splitlines() + } + if self.centipede_path: + centipede_path = self.centipede_path + else: + with tempfile.NamedTemporaryFile() as temp_centipede: + centipede_path = temp_centipede.name + with open(centipede_path, 'w') as f: + f.write(CENTIPEDE_SCRIPT) + with Pool(processes=min(self.processes, len(motif_names))) as pool: + self.footprints = dict( + tup + for + tup + in + pool.starmap( + centipede, + ( + (self, centipede_path, search_motif_name) + for + search_motif_name + in + motif_names + ) + ) + if + tup + ) + os.remove(centipede_path) + + def dump_json(self, footprints_file_path): + with open(footprints_file_path, 'w') as f: + json.dump(self.footprints, f) + self.footprints_file_path = footprints_file_path + + def write_footprints(self, footprints_file_path): + self.dump_json(footprints_file_path) + + def write_motifs(self, motifs_file_path): + with open(motifs_file_path, 'wb') as f: + f.write(self.motifs) + self.motifs_file_path = motifs_file_path + + def clean_up(self, path): + if (os.path.isfile(path) if path else False): + os.remove(path) + + + + +# Exceptions =================================================================== + +class Error(Exception): + """"""Base class for other exceptions"""""" + pass + + +class BadInputError(Error): + """"""Bad input error"""""" + pass + + + + +# Functions ==================================================================== + +def check_input(input_file): + """"""Check that an input is str or bytes"""""" + + if isinstance(input_file, bytes): + bytes_obj = input_file + elif isinstance(input_file, str): + with open(input_file, 'rb') as f: + bytes_obj = f.read() + else: + raise BadInputError('Input must be either str or bytes') + return bytes_obj + + +def centipede(footprints, centipede_path, search_motif): + decoded_motifs = footprints.motifs.decode().splitlines() + header = ( + decoded_motifs[0] + .replace('sequence_name', 'sequence.name') + .replace('\tq-value', '') + ) + with tempfile.NamedTemporaryFile() as ( + temp_motifs_split + ), tempfile.NamedTemporaryFile() as ( + temp_bam + ): + temp_motifs_split.write( + ( + header + + + '\n' + + + '\n'.join( + line.replace('\t\t', '\t') + for + line + in + decoded_motifs[1:] + if + line.split('\t')[0] == search_motif + ) + + + '\n' + ) + .encode() + ) + temp_bam.write(footprints.bam) + if footprints.bam_index: + with open('{}.bai'.format(temp_bam.name), 'wb') as temp_bai: + temp_bai.write(footprints.bam_index) + with subprocess.Popen( + ( + 'Rscript', + centipede_path, + temp_motifs_split.name, + temp_bam.name, + search_motif + ), + stdout=subprocess.PIPE + ) as centipede: + fit, _ = centipede.communicate() + if footprints.bam_index: + os.remove('{}.bai'.format(temp_bam.name)) + return ((search_motif, json.loads(fit)) if fit else None) +","Python" +"Epigenetics","kjgaulton/pipelines","kglab-python3-modules/hg19.py",".py","5974","253","#!/usr/bin/env python3 +#=============================================================================== +# hg19.py +#=============================================================================== + +""""""Get the coordinates of a variant from its RSID, or an RSID from its +coordinates. + +Examples +-------- +rs10_coord = coord('rs10') +print( + 'rs10 is on chromosome {0.chr} at position {0.pos}' + .format(rs10_coord) +) + +rs10_coord_tuple = coord_tuple('rs10') +print( + 'rs10 is on chromosome {} at position {}' + .format(rs10_coord_tuple[0], rs10_coord_tuple[1]) +) + +rs_something = rsid(chr=1, pos=10019) +print( + 'The RSID of the variant on chromosome 1 at position 10019 is {}.' + .format(rs_something) +) + +Notes +----- +This module might be a good place to put more utilities later. + +coord() returns a fancy object, which is useful for writing readable code. + +coord_tuple() returns a tuple, which is more lightweight and useful for going +fast. + +rsid() returns an RSID. + +Classes +------- +DataDirectory + storage class for data directory configuration +Coordinates + The coordinates of a variant + +Functions +--------- +coord + get the coordinates and return them as an object +coord_tuple + get the coordinates and return them as a tuple +rsid + get the rsid and return it as a string + +Global +------ +path + absolute path to the hg19 reference genome +"""""" + + + + +# Imports ====================================================================== + +import gzip +import subprocess +import os.path +import socket + + + + +# Constants ==================================================================== + +HOSTNAME = socket.gethostname() + +PATH = ( + '/data2/broad-resource-bundle-hg19/ucsc.hg19.fasta' + if + HOSTNAME == 'holden' + else + '/home/data/broad-resource-bundle-hg19/ucsc.hg19.fasta' +) + +SORTED_BY_RSID_FORMAT = ( + '/data2/dbSNP/sorted-by-rsid/{}.bed.gz' + if + HOSTNAME == 'holden' + else + '/home/data/dbSNP/sorted-by-rsid/{}.bed.gz' +) + +SORTED_BY_COORD_PATH = ( + '/data2/dbSNP/dbSNP150.rsid.bed.gz' + if + HOSTNAME == 'holden' + else + '/home/data/dbSNP/dbSNP150.rsid.bed.gz' +) + + + + +# Classes ====================================================================== + +class Coordinates(): + """"""The coordinates of a variant"""""" + + def __init__(self, chr, pos): + self.chr = chr + self.pos = pos + self.tuple = chr, pos + + def __repr__(self): + return 'Coordinates(chr={}, pos={})'.format(self.chr, self.pos) + + +class Variant(): + """"""The id and coordinates of a variant"""""" + + def __init__(self, id, chr, pos): + self.id = id + self.chr = chr + self.pos = pos + self.tuple = id, chr, pos + + def __repr__(self): + return 'Variant(id={}, chr={}, pos={})'.format( + self.id, + self.chr, + self.pos + ) + + + + +# Functions ==================================================================== + +def coord(rsid): + """"""Get the coordinates and return them as an object"""""" + + chr, pos = coord_tuple(rsid) + return Coordinates(chr, pos) + + +def coord_tuple(rsid): + """"""Get the coordinates and return them as a tuple"""""" + + with subprocess.Popen( + ('zcat', SORTED_BY_RSID_FORMAT.format(rsid[:4])), + stdout=subprocess.PIPE + ) as zcat: + with subprocess.Popen( + ( + 'awk', + '$4==""{}"" {{print; exit}}'.format(rsid) + ), + stdin=zcat.stdout, + stdout=subprocess.PIPE + ) as awk: + dbsnp_line, _ = awk.communicate() + try: + chr, _, pos, _, _, _ = dbsnp_line.decode().split('\t') + except ValueError: + raise ValueError( + '{} was not found in the database'.format(rsid) + ) + return chr[3:], int(pos) + + +def rsid(chr, pos): + """"""Get the rsid and return it as a string"""""" + + with subprocess.Popen( + ( + 'tabix', + SORTED_BY_COORD_PATH, + 'chr{0}:{1}-{1}'.format(str(chr).replace('chr', ''), pos) + ), + stdout=subprocess.PIPE + ) as tabix: + dbsnp_line, _ = tabix.communicate() + try: + _, _, _, rsid, *rest = dbsnp_line.decode().split('\t') + except ValueError: + raise ValueError( + 'A variant at chromosome {}, position {} was not found in the ' + 'database' + .format(chr, pos) + ) + return rsid + + +def range(chr, start, end): + """"""Generate all variants within a given genomic range"""""" + + with subprocess.Popen( + ( + 'tabix', + SORTED_BY_COORD_PATH, + 'chr{0}:{1}-{2}'.format(str(chr).replace('chr', ''), start, end) + ), + stdout=subprocess.PIPE + ) as tabix: + dbsnp_lines, _ = tabix.communicate() + for dbsnp_line in dbsnp_lines.decode().splitlines(): + chr, _, pos, rsid, *rest = dbsnp_line.split('\t') + yield Variant(rsid, chr.replace('chr', ''), int(pos)) + + +def generate_coord_rsid_pairs(file): + for line in file: + chr, _, pos, rsid, *alleles = line.split() + yield (chr.replace('chr', ''), int(pos)), rsid + + +def coord_rsid_dict(): + """"""A dictionary containing coord: rsid pairs"""""" + + with gzip.open(SORTED_BY_COORD_PATH, 'rt') as f: + return dict(generate_coord_rsid_pairs(f)) + + + + +# test ========================================================================= + +if __name__ == '__main__': + rs10_coord = coord('rs10') + print( + 'rs10 is on chromosome {0.chr} at position {0.pos}' + .format(rs10_coord) + ) + + rs10_coord_tuple = coord_tuple('rs10') + print( + 'rs10 is on chromosome {} at position {}' + .format(rs10_coord_tuple[0], rs10_coord_tuple[1]) + ) + + rs_something = rsid(chr=1, pos=10019) + print( + 'The RSID of the variant on chromosome 1 at position 10019 is {}.' + .format(rs_something) + ) + + try: + coord('rs10a') + except ValueError: + print('error was handled') +","Python" +"Epigenetics","kjgaulton/pipelines","kglab-python3-modules/seqalign.py",".py","32111","1019","#!/usr/bin/env python3 +#=============================================================================== +# seqalign.py +#=============================================================================== + +""""""Easy management of sequence alignment data + +A mini-module for managing sequence alignment data. The language of this module +treats a ""sequence alignment"" as an abstraction, but mostly handles it as a BAM +file stored in memory. + +Example +------- +with SequenceAlignment( + input_file_path='path to input bam or fastq file' +) as sa: + sa.cleans_up_bam = False + sa.remove_supplementary_alignments() + sa.samtools_sort(memory_limit=10) + sa.samtools_index() + sa.write('path to output BAM file') + +Notes +----- +The ""input_file"" argument should be a string for single-end reads or for +data that is already aligned. For raw paired-end reads, it should be a tuple +containing two strings giving the paths to the two fasta / fastq files. + +High-level class +---------------- +SequenceAlignment + object representing aligned sequencing data + +Low-level classes +----------------- +BWA + commands for running bwa + +Functions +--------- +file_format_from_extension + infer the format of a sequencing data file from its extension +median_read_length + determine the median length of reads in a fasta or fastq file +"""""" + + + + +# Imports ====================================================================== + +import gzip +import itertools +import math +import os +import os.path +import socket +import subprocess +import sys +import tempfile +from Bio import SeqIO + +hostname = socket.gethostname() +if hostname == 'gatsby.ucsd.edu': + sys.path.append('/home/data/kglab-python3-modules') +elif hostname == 'holden': + sys.path.append('/lab/kglab-python3-modules') + +import hg19 +import namedpipe + + + + +# Classes ====================================================================== + +class SequenceAlignment(): + """"""A representation of aligned sequencing data + + Attributes + ---------- + bam : bytes + Aligned sequencing data in BAM format + index : bytes + BAI index file generated by samtools index + phred_quality_score : int + Minimum MAPQ score for reads in this alignment + bam_file_path : str + File path used the last time the BAM was written to disk + cleans_up_bam : bool + When True, __exit__() will remove the last BAM file written to disk + has_been_sorted : bool + Defaults to False, becomes True after samtools_sort() is run + aligner : obj + A callable object representing the aligner used for sequence alignment + dedupper : obj + A callable object representing the algorithm used for removing + duplicates + processes : int + Maximum number of processes available for method calls + log : file object + File object to which logging information will be written + """""" + + def __init__( + self, + input_file, + phred_quality_score=10, + aligner=None, + dedupper=None, + processes=1, + log=None + ): + """"""Set the parameters for the alignment + + Parameters + ---------- + input_file : bytes, tuple, list, str + Sequencing data. Bytes objects are assumed to be BAM files in + memory. Strings are assumed to be paths to sequencing data on + disk. Tuples or lists are assumed to be pairs of strings indicating + paired-end read files. + phred_quality_score : int + Minimum MAPQ score for reads in this alignmentaligner : obj + alignment : obj + A callable object representing the aligner used for sequence + alignment + dedupper : obj + A callable object representing the algorithm used for removing + duplicates + processes : int + Maximum number of processes available for method calls + log : file object + File object to which logging information will be written + + """""" + + self.index = None + self.phred_quality_score = int(phred_quality_score) + self.bam_file_path = None + self.cleans_up_bam = False + self.has_been_sorted = False + self.aligner = aligner + self.dedupper = dedupper + self.processes = int(processes) + self.log = log + self.bam = self.parse_input(input_file) + + def __enter__(self): + """"""When an instance of this class is used as a context manager, it is + assumed that a BAM file written to disk should be removed after exiting + context. + """""" + + self.cleans_up_bam = True + return self + + def __exit__(self, exc_type, exc_value, traceback): + """"""Clean up a BAM file on disk"""""" + + if self.cleans_up_bam: + self.clean_up(self.bam_file_path) + self.clean_up('{}.bai'.format(self.bam_file_path)) + return False + + def __repr__(self): + """"""Show some of the alignment parameters"""""" + + return '\n'.join( + ( + 'SequenceAlignment(', + ' phred_quality_score : {0.phred_quality_score}', + ' processes : {0.processes}', + ' cleans_up_bam : {0.cleans_up_bam}', + ')' + ) + ).format(self) + + def __add__(self, sequence_alignment): + """"""Merge this SequenceAlignment with another one + + If the ``+`` operator is used, the resulting alignment will use the + max of the two minimum MAPQ scores. If the ``|`` operator is used, the + resulting alignment will use the min of the two minimum MAPQ scores. + + Parameters + ---------- + sequence_alignment : SequenceAlignment + Another SequenceAlignment object + + Returns + ------- + SequenceAlignment + A SequenceAlignment object representing data generated by samtools + merge + """""" + + return merge( + self, + sequence_alignment, + phred_quality_score=max( + self.phred_quality_score, + sequence_alignment.phred_quality_score + ), + processes=min(self.processes, sequence_alignment.processes), + ) + + def __or__(self, sequence_alignment): + """"""Merge this SequenceAlignment with another one + + If the ``+`` operator is used, the resulting alignment will use the + max of the two minimum MAPQ scores. If the ``|`` operator is used, the + resulting alignment will use the min of the two minimum MAPQ scores. + + Parameters + ---------- + sequence_alignment : SequenceAlignment + Another SequenceAlignment object + + Returns + ------- + SequenceAlignment + A SequenceAlignment object representing data generated by samtools + merge + """""" + + return merge( + self, + sequence_alignment, + phred_quality_score=min( + self.phred_quality_score, + sequence_alignment.phred_quality_score + ), + processes=min(self.processes, sequence_alignment.processes), + ) + + def parse_input(self, input_file): + """"""Parse the input file + + Aligns sequencing data if necessary, and finally assigns an appropriate + bytes object to the bam attribute + + Parameters + ---------- + input_file : bytes, tuple, list, str + Sequencing data. Bytes objects are assumed to be BAM files in + memory. Strings are assumed to be paths to sequencing data on + disk. Tuples or lists are assumed to be pairs of strings indicating + paired-end read files. + + Returns + ------- + bytes + A BAM File in memory + """""" + + if not isinstance(input_file, (bytes, tuple, list, str)): + raise TypeError('input_file must be bytes, tuple, list, or str') + elif isinstance(input_file, bytes): + return input_file + elif isinstance(input_file, (tuple, list)): + if len(input_file) != 2: + raise ValueError( + 'If input_file_path is a tuple, it must have length 2' + ) + self.raw_reads_path = input_file + return self.align_reads() + elif isinstance(input_file, str): + format = file_format_from_extension(input_file) + if format in {'fasta', 'fastq'}: + self.raw_reads_path = input_file + return self.align_reads() + elif format in {'sam', 'bam'}: + with subprocess.Popen( + ( + 'samtools', 'view', + '-bhq', str(self.phred_quality_score), + '-@', str(self.processes), + input_file + ), + stdout=subprocess.PIPE, + stderr=self.log + ) as samtools_view: + return samtools_view.communicate()[0] + + def align_reads(self): + """"""Align raw reads using the provided aligner + + The default aligner is BWA + + Returns + ------- + bytes + A BAM File in memory + """""" + + if not self.aligner: + self.aligner = BWA() + return self.aligner(self) + + def remove_supplementary_alignments(self): + """"""Remove supplementary alignments from the BAM data using samtools + view + """""" + + with subprocess.Popen( + ( + 'samtools', 'view', + '-bh', + '-F', '0x800', + '-@', str(self.processes) + ), + stdin=subprocess.PIPE, + stdout=subprocess.PIPE, + stderr=self.log + ) as samtools_view: + bam, _ = samtools_view.communicate(input=self.bam) + self.bam = bam + + def apply_quality_filter(self): + """"""Apply a quality filter to the BAM data using samtools view, with + flags: -F 1548 -q {phred_quality_score} + """""" + + with subprocess.Popen( + ( + 'samtools', 'view', + '-bh', + '-F', '1548', + '-q', str(self.phred_quality_score), + '-@', str(self.processes) + ), + stdin=subprocess.PIPE, + stdout=subprocess.PIPE, + stderr=self.log + ) as samtools_view: + bam, _ = samtools_view.communicate(input=self.bam) + self.bam = bam + + def samtools_index(self): + """"""Index the BAM data"""""" + + if not self.has_been_sorted: + raise Exception( + 'BAM must be sorted before it can be indexed' + ) + with namedpipe.temp_named_pipe() as ( + bam_pipe + ), namedpipe.temp_named_pipe() as ( + index_pipe + ): + with subprocess.Popen( + ( + 'sh', + '-c', 'cat {0} & samtools index {1} {0} & cat > {1}'.format( + index_pipe.name, + bam_pipe.name + ) + ), + stdin=subprocess.PIPE, + stdout=subprocess.PIPE, + stderr=self.log + ) as samtools_index: + self.index, _ = samtools_index.communicate(input=self.bam) + + def remove_mitochondrial_reads(self): + """"""Remove mitochondrial reads from the BAM data using samtools view"""""" + + if not self.index: + raise Exception( + 'use SequenceAlignment.samtools_index() before using ' + 'SequenceAlignment.remove_mitochondrial_reads()' + ) + with tempfile.NamedTemporaryFile(dir='/home/data/tmp') as temp_bam: + temp_bam.write(self.bam) + with open('{}.bai'.format(temp_bam.name), 'wb') as f: + f.write(self.index) + with subprocess.Popen( + ( + 'samtools', 'view', + '-bh', + '-@', str(self.processes), + temp_bam.name + ) + + + tuple( + 'chr{}'.format(chromosome) + for + chromosome + in + (tuple(range(1,23)) + ('X', 'Y')) + ), + stdout=subprocess.PIPE, + stderr=self.log + ) as samtools_view: + bam, _ = samtools_view.communicate() + self.bam = bam + os.remove('{}.bai'.format(temp_bam.name)) + + def samtools_sort(self, memory_limit=5): + """"""Sort the BAM data using samtools"""""" + + if memory_limit < 5: + raise MemoryLimitError('Please provide at least 5 GB of memory') + with subprocess.Popen( + ( + 'samtools', 'sort', + '-m', '{}M'.format( + int(1024 / self.processes * memory_limit) + ), + '-@', str(self.processes) + ), + stdin=subprocess.PIPE, + stdout=subprocess.PIPE, + stderr=self.log + ) as samtools_sort: + bam, _ = samtools_sort.communicate(input=self.bam) + self.bam = bam + self.has_been_sorted=True + + def remove_blacklisted_reads(self, blacklist_path): + """"""Remove reads from regions in a provided BED file using bedtools + + Parameters + ---------- + blacklist_path : str + Path to a BED file on disk + """""" + + with subprocess.Popen( + ( + 'bedtools', 'intersect', + '-abam', 'stdin', + '-b', blacklist_path, + '-v' + ), + stdin=subprocess.PIPE, + stdout=subprocess.PIPE, + stderr=self.log + ) as bedtools_intersect: + bam, _ = bedtools_intersect.communicate(input=self.bam) + self.bam = bam + + def remove_duplicates(self, dedupper=None): + """"""Remove duplicates from the BAM data using the provided dedupper"""""" + + if not (dedupper or self.dedupper): + raise Exception( + 'Indicate a dedupper if you\'re going to remove duplicates' + ) + else: + dedupper = dedupper if dedupper else self.dedupper + self.bam = dedupper(self.bam, log=self.log) + + def samtools_mpileup(self, positions, reference_genome=hg19.PATH): + """"""Generate a pileup from the BAM data using samtools mpileup + + Parameters + ---------- + positions : str + Path to a variant positions file on disk + reference_genome : + Path to a reference genome on disk + + Returns + ------- + bytes + A pileup file generated by samtools mpileup + """""" + + with subprocess.Popen( + ( + 'samtools', 'mpileup', + '-f', reference_genome, + '-l', positions, + '-' + ), + stdin=subprocess.PIPE, + stdout=subprocess.PIPE, + stderr=self.log + ) as samtools_mpileup: + return samtools_mpileup.communicate(self.bam)[0] + + def write(self, bam_file_path): + """"""Write a BAM file to disk, along with an index if one is present + + Parameters + ---------- + bam_file_path : str + Path where the BAM file will be written + """""" + + with open(bam_file_path, 'wb') as f: + f.write(self.bam) + self.bam_file_path = bam_file_path + if self.index: + with open('{}.bai'.format(bam_file_path), 'wb') as f: + f.write(self.index) + + def clean_up(self, path): + """"""Remove a file + + Parameters + ---------- + path + path to file that will be removed + """""" + + if (os.path.isfile(path) if path else False): + os.remove(path) + + +class BWA(): + """"""A class with methods for calling BWA + + Notes + ----- + BWA defaults: + trim_qual: 0 + seed_len: inf + max_seed_diff: 2 + + AQUAS (Kundaje lab) defaults for ChIP-seq: + trim_qual: 5 + seed_len: 32 + max_seed_diff: 2 + + Gaulton lab ChIP-seq pipeline settings: + trim_qual: 15 + seed_len: inf + max_seed_diff: 2 + + Attributes + ---------- + reference_genome_path : str + Path to a reference genome on disk + trim_qual : int + MAPQ score for read trimming + seed_len : int + Seed length [inf] + max_seed_diff : int + Maximum mismatches in seed before a read is dropped [2] + max_reads_for_length_check : int + Maximum number of reads to use for read length checking [1e6] + algorithm : str + If set, force use of either the aln or the mem algorithm + algorithm_switch_bp : int + Read length at which the algorithm will automatically switch from aln + to mem [70] + """""" + + def __init__( + self, + reference_genome_path=hg19.PATH, + trim_qual=0, + seed_len='inf', + max_seed_diff=2, + max_reads_for_length_check=int(1e6), + algorithm=None, + algorithm_switch_bp=70 + ): + """"""Set the parameters for sequence alignment with BWA + + Parameters + ---------- + reference_genome_path : str + Path to a reference genome on disk + trim_qual : int + MAPQ score for read trimming + seed_len : int + Seed length [inf] + max_seed_diff : int + Maximum mismatches in seed before a read is dropped [2] + max_reads_for_length_check : int + Maximum number of reads to use for read length checking [1e6] + """""" + + self.reference_genome_path = reference_genome_path + self.trim_qual = int(trim_qual) if trim_qual else 0 + self.seed_len=seed_len + self.max_seed_diff=max_seed_diff + self.max_reads_for_length_check = max_reads_for_length_check + self.algorithm = algorithm + self.algorithm_switch_bp = algorithm_switch_bp + + def __repr__(self): + return 'BWA()' + + def __call__(self, sequence_alignment): + """"""Perform sequence alignment using an appropriate algorithm + + First, read lengths are checked to determine the appropriate algorithm, + then the alignment is carried out. + + Parameters + ---------- + sequence_alignment : SequenceAlignment + a SequenceAlignemnt object + + Returns + ------- + bytes + A BAM file in memory + """""" + + if self.algorithm == 'aln': + return self.bwa_aln(sequence_alignment) + if self.algorithm == 'mem': + return self.bwa_mem(sequence_alignment) + + median_read_length = get_median_read_length( + sequence_alignment.raw_reads_path, + self.max_reads_for_length_check + ) + if median_read_length <= self.algorithm_switch_bp: + return self.bwa_aln(sequence_alignment) + elif median_read_length > self.algorithm_switch_bp: + return self.bwa_mem(sequence_alignment) + + def bwa_aln(self, sequence_alignment): + """"""Perform sequence alignment using the bwa aln algorithm + + Single-end and paired end reads are handled appropriately based on the + type of the SequenceAlignment's raw reads path + + Parameters + ---------- + sequence_alignment : SequenceAlignment + a SequenceAlignemnt object + + Returns + ------- + bytes + A BAM file + """""" + + if not isinstance(sequence_alignment.raw_reads_path, str): + with namedpipe.temp_named_pipe() as ( + sai_pipe_0 + ), namedpipe.temp_named_pipe() as ( + sai_pipe_1 + ): + with subprocess.Popen( + ( + 'sh', '-c', + ( + 'bwa sampe {0} {1} {2} {3} {4} & ' + 'bwa aln -t {5} -q {6} -l {7} -k {8} {0} {3} > ' + '{1} & ' + 'bwa aln -t {5} -q {6} -l {7} -k {8} {0} {4} > ' + '{2} & ' + ) + .format( + self.reference_genome_path, + sai_pipe_0.name, + sai_pipe_1.name, + sequence_alignment.raw_reads_path[0], + sequence_alignment.raw_reads_path[1], + math.floor(sequence_alignment.processes / 2), + self.trim_qual, + self.seed_len, + self.max_seed_diff + ) + ), + stdout=subprocess.PIPE, + stderr=sequence_alignment.log + ) as bwa_aln_sampe: + with subprocess.Popen( + ( + 'samtools', 'view', + '-Sbq', str(sequence_alignment.phred_quality_score), + '-@', str(sequence_alignment.processes) + ), + stdin=bwa_aln_sampe.stdout, + stdout=subprocess.PIPE, + stderr=sequence_alignment.log + ) as samtools_view: + return samtools_view.communicate()[0] + else: + with namedpipe.temp_named_pipe() as sai_pipe: + with subprocess.Popen( + ( + 'sh', '-c', + ( + 'bwa samse {0} {1} {2} & ' + 'bwa aln -t {3} -q {4} -l {5} -k {6} {0} {2} > {1}; ' + ) + .format( + self.reference_genome_path, + sai_pipe.name, + sequence_alignment.raw_reads_path, + sequence_alignment.processes, + self.trim_qual, + self.seed_len, + self.max_seed_diff + ) + ), + stdout=subprocess.PIPE, + stderr=sequence_alignment.log + ) as bwa_aln_samse: + with subprocess.Popen( + ( + 'samtools', 'view', + '-bhq', str( + sequence_alignment.phred_quality_score + ), + '-@', str(sequence_alignment.processes) + ), + stdin=bwa_aln_samse.stdout, + stdout=subprocess.PIPE, + stderr=sequence_alignment.log + ) as samtools_view: + return samtools_view.communicate()[0] + + def bwa_mem(self, sequence_alignment): + """"""Perform sequence alignment using the bwa mem algorithm + + Parameters + ---------- + sequence_alignment : SequenceAlignment + a SequenceAlignemnt object + + Returns + ------- + bytes + A BAM file + """""" + + with subprocess.Popen( + ('bwa', 'mem', self.reference_genome_path) + + ( + tuple(sequence_alignment.raw_reads_path) + if + not isinstance(sequence_alignment.raw_reads_path, str) + else + (sequence_alignment.raw_reads_path,) + ) + + ( + '-t', str(sequence_alignment.processes) + ), + stdout=subprocess.PIPE, + stderr=sequence_alignment.log + ) as bwa_mem: + with subprocess.Popen( + ( + 'samtools', 'view', + '-bhq', str(sequence_alignment.phred_quality_score), + '-@', str(sequence_alignment.processes) + ), + stdin=bwa_mem.stdout, + stdout=subprocess.PIPE, + stderr=sequence_alignment.log + ) as samtools_view: + return samtools_view.communicate()[0] + + +class Bowtie2(): + pass + + +class STAR(): + pass + + + + +# Exceptions =================================================================== + +class Error(Exception): + """"""Base class for other exceptions"""""" + + pass + + +class FileExtensionError(Error): + """"""File extension error"""""" + + pass + + +class MemoryLimitError(Error): + """"""File extension error"""""" + + pass + + +class MissingInputError(Error): + """"""Missing input error"""""" + + pass + + + + +# Functions ==================================================================== + +def file_format_from_extension(file_path): + """"""Infer the format of a sequencing data file from its extension + + Parameters + ---------- + file_path : str + Path to a sequencing data file + + Returns + ------- + str + one of ``fasta``, ``fastq``, ``sam``, ``bam`` + """""" + + if ( + (file_path.split('.')[-1] in {'fasta', 'fa'}) + or ( + file_path.split('.')[-1] == 'gz' + and (file_path.split('.')[-2] in {'fasta', 'fa'}) + ) + ): + format = 'fasta' + elif ( + (file_path.split('.')[-1] in {'fastq', 'fq', 'fq1', 'fq2'}) + or ( + file_path.split('.')[-1] == 'gz' + and (file_path.split('.')[-2] in {'fastq', 'fq', 'fq1', 'fq2'}) + ) + ): + format = 'fastq' + elif file_path.split('.')[-1] in {'sam', 'bam'}: + format = file_path.split('.')[-1] + else: + raise FileExtensionError( + 'Could not parse file extension of {}' + .format(os.path.basename(file_path)) + ) + return format + + +def get_median_read_length(raw_reads_paths, number_of_reads): + """"""Return the median read length of a FASTA or FASTQ file + + Parameters + ---------- + raw_reads_paths : str, list, tuple + Path to raw reads file (or paths if paired-end) + number_of_reads : int + Maximum number of reads to read in before determining median read length + + Returns + ------- + int or float + The median read length + """""" + + histogram = {} + if not isinstance(raw_reads_paths, str): + formats = tuple( + file_format_from_extension(raw_reads_paths[i]) + for i in range(2) + ) + else: + formats = (file_format_from_extension(raw_reads_paths),) + raw_reads_paths = (raw_reads_paths,) + for raw_reads_path, format in zip(raw_reads_paths, formats): + with ( + gzip.open(raw_reads_path, 'rt') + if raw_reads_path[-3:] == '.gz' + else open(raw_reads_path, 'r') + ) as raw_reads: + for record in itertools.islice( + SeqIO.parse(raw_reads, format), + number_of_reads + ): + try: + histogram[len(record.seq)] += 1 + except KeyError: + histogram[len(record.seq)] = 1 + if not histogram: + raise Exception('No reads in input file') + read_lengths = tuple( + length for length, count in sorted(histogram.items()) + ) + total_reads = sum(count for length, count in histogram.items()) + cumulative_count = 0 + for length, count in sorted(histogram.items()): + cumulative_count += count + if cumulative_count > total_reads / 2: + median = length + break + elif cumulative_count == total_reads / 2: + read_lengths = tuple( + length for length, count in sorted(histogram.items()) + ) + next_length = read_lengths[read_lengths.index(length) + 1] + median = (length + next_length) / 2 + break + return median + + +def samtools_merge(*bams): + """"""Merge BAM files using samtools merge + + Parameters + ---------- + *bams + Variable number of paths to BAM files on disk or BAM files as bytes + objects (the two can be mixed) + + Returns + ------- + bytes + A BAM file in memory + """""" + + bam_file_paths = [] + temp_files = [] + for bam in bams: + if isinstance(bam, str): + bam_file_paths.append(bam) + elif isinstance(bam, bytes): + temp = tempfile.NamedTemporaryFile(dir='/home/data/tmp') + temp.write(bam) + temp_files.append(temp) + bam_file_paths.append(temp.name) + with subprocess.Popen( + ['samtools', 'merge', '-'] + bam_file_paths, + stdout=subprocess.PIPE + ) as samtools_merge: + bam, _ = samtools_merge.communicate() + for temp in temp_files: + temp.close() + return bam + + +def to_bam(alignment): + """"""Flatten an alignment to a BAM file in memory or on disk + + Parameters + ---------- + alignment + A string containing the path to a BAM file on disk, a bytes object + containing a BAM file in memory, or a SequenceAlignment object + + Returns + ------- + str or bytes + Path to a BAM file on disk (str), or a BAM file in memory (bytes) + """""" + + if isinstance(alignment, (bytes, str)): + return alignment + elif isinstance(alignment, SequenceAlignment): + return alignment.bam + +def merge( + *sequence_alignments, + phred_quality_score=10, + aligner=None, + dedupper=None, + processes=1, + log=None +): + """"""Merge SequenceAlignment objects + + Produces a new SequenceAlignment object with a merged bam attribute and + other parameters as provided + + Parameters + ---------- + *sequence_alignments + One or more SequenceAlignment objects + phred_quality_score : int + Minimum MAPQ score for reads in this alignmentaligner : obj + alignment : obj + A callable object representing the aligner used for sequence + alignment + dedupper : obj + A callable object representing the algorithm used for removing + duplicates + processes : int + Maximum number of processes available for method calls + log : file object + File object to which logging information will be written + + Returns + ------- + SequenceAlignment + A new SequenceAlignment object representing merged data + """""" + + return SequenceAlignment( + samtools_merge(*(to_bam(sa) for sa in sequence_alignments)), + phred_quality_score=phred_quality_score, + processes=processes, + aligner=aligner, + dedupper=dedupper, + log=log + ) + + +# Test ========================================================================= + +if __name__ == '__main__': + with SequenceAlignment( + input_file='/home/data/aaylward-data/bam/ChIP_FOXA1_hepg2_2.fq', + processes=23, + aligner=BWA( + trim_qual=15 + ) + ) as sa: + sa.cleans_up_bam=False + print('applying quality filter') + sa.apply_quality_filter() + print('sorting') + sa.samtools_sort(memory_limit=64) + print('indexing') + sa.samtools_index() + print('removing mitochondrial reads') + sa.remove_mitochondrial_reads() + sa.write('/home/data/aaylward-data/bam/joshs-chip-test.bam') +","Python" +"Epigenetics","kjgaulton/pipelines","ATAC_Pipeline/split_fimo_by_motif.py",".py","2090","71","import sys + +fimo = open(str(sys.argv[1])) + +# dataToDictionary------------------------------------------------------------- +# +# Represent fimo file as a dictionary in which the key is the motif name and +# the value is the rest of the line. +#------------------------------------------------------------------------------ +def dataToDictionary(myFile): + + fimo_dict = {} + + file_index = 0 + for line in myFile: + #if this isn't the first line: + if file_index > 0: + #split the line by tabs: + line_list = line.rsplit('\t') + + #dictionary key is the motif name + key = line_list[0] + + #split the chromosome number, start, and stop locations + chr_start_stop = line_list[1].rsplit(':') + chrm = chr_start_stop[0] + start_stop = chr_start_stop[1].rsplit('-') + + #compute actual start and stop: + start = str(int(start_stop[0]) + int(line_list[2])) + stop = str(int(start_stop[0])+ int(line_list[3])) + + #create dictionary entry + item = [chrm, start, stop, key, line_list[5], line_list[4], line_list[6], line_list[len(line_list)-1][:len(line_list[len(line_list)-1])-1]] + if key not in fimo_dict.keys(): + fimo_dict[key] = [item] + else: + fimo_dict[key].append(item) + file_index += 1 + + return fimo_dict + +# splitFimo-------------------------------------------------------------------- +# +# split output from fimo into separate files based on their motif name. This is +# done using the helper function dataToDictionary, which creates a dictionary +# from fimo's output in which the keys are the motif names. +#------------------------------------------------------------------------------ +def splitFimo(): + + #call dataToDictionary: + my_dict = dataToDictionary(fimo) + + #for each motif: + for key in my_dict.keys(): + + my_items = my_dict[key] + filename = key + "".motif.bed"" + output_file = open(filename, 'w') + + #write all corresponding items to its output file: + for item in my_items: + out_string = """" + for i in range(len(item)): + if i < len(item)-1: + out_string += item[i] + '\t' + else: + out_string += item[i] + '\n' + output_file.write(out_string) + +splitFimo()","Python" +"Epigenetics","kjgaulton/pipelines","ATAC_Pipeline/centipede.R",".R","1128","29","#!/usr/bin/Rscript +# centipede.R +# Usage: /usr/bin/Rscript --vanilla centipede.R matrix.file motifs.file + +#dir.base=""/data2/smorabito-data2/recreate-ATAC-footprints"" + +# start of script +library(CENTIPEDE) +library(tools) + +# process args +matrix.in <- commandArgs()[7] +motifs.in <- commandArgs()[8] +print(paste0(""Input matrix: "", matrix.in)) +print(paste0(""Input motifs: "", motifs.in)) +file.name <- basename(file_path_sans_ext(motifs.in)) + +# output centipede posterior probabilities +#dir.centipede <- file.path(dir.base,""centipede"") +#dir.output.centipede <- file.path(dir.base, file.name) +#setwd(dir.output.centipede) + +num.columns <- max(count.fields(gzfile(matrix.in), sep=""\t"")) +count.matrix <- read.table(gzfile(matrix.in), sep=""\t"", header=F, fill=T, col.names=paste0('V', seq_len(num.columns))) +count.matrix[is.na(count.matrix)] <- 0 +motifs <- read.table(motifs.in, sep=""\t"", header=F) +centFit <- fitCentipede(Xlist = list(ATAC=as.matrix(count.matrix)), Y=cbind(rep(1, dim(motifs)[1]), motifs[,5])) +write.table(centFit$PostPr,col=F,row=F,sep=""\t"",quote=F,file=paste0(basename(matrix.in),"".txt"")) +#write(centFit$PostPr, stdout())","R" +"Epigenetics","kjgaulton/pipelines","islet_snATAC_pipeline/islet_snATAC.ipynb",".ipynb","9097","233","{ + ""cells"": [ + { + ""cell_type"": ""code"", + ""execution_count"": null, + ""metadata"": { + ""scrolled"": true + }, + ""outputs"": [], + ""source"": [ + ""import os\n"", + ""import numpy as np\n"", + ""import pandas as pd\n"", + ""import scipy.io\n"", + ""\n"", + ""# plotting\n"", + ""import matplotlib.pyplot as plt\n"", + ""import seaborn as sns\n"", + ""\n"", + ""# single cell\n"", + ""import scanpy.api as sc\n"", + ""from anndata import AnnData\n"", + ""\n"", + ""# etc\n"", + ""%load_ext rpy2.ipython"" + ] + }, + { + ""cell_type"": ""markdown"", + ""metadata"": {}, + ""source"": [ + ""### Regress out read depth per experiment"" + ] + }, + { + ""cell_type"": ""code"", + ""execution_count"": null, + ""metadata"": {}, + ""outputs"": [], + ""source"": [ + ""wd = 'islet_snATAC/'\n"", + ""\n"", + ""adatas = {}\n"", + ""samples = ['Islet1','Islet2','Islet3']\n"", + ""\n"", + ""# dictionary naming 5kb windows genome-wide based on overlap with gencode v19 gene TSS\n"", + ""promoters = pd.read_csv('references/gencode.v19.5kb_windows.promoter_names.txt.gz', sep='\\t', header=None, index_col=0, names=['prom'])\n"", + ""promoter_names = promoters['prom'].to_dict() \n"", + ""\n"", + ""# cells from low quality and doublet clusters were identified through iterative clustering\n"", + ""low_quality = open(os.path.join(wd, 'islet_snATAC.lowqual')).read().splitlines()\n"", + ""doublets = open(os.path.join(wd, 'islet_snATAC.doublets')).read().splitlines()\n"", + ""\n"", + ""qc_metrics = pd.read_csv(os.path.join(wd, 'references/islet.qc_metrics.txt'), sep='\\t', header=0, index_col=0)\n"", + ""hvw = open(os.path.join(wd,'references/islet_snATAC.hvw')).read().splitlines()\n"", + ""\n"", + ""for sample in samples:\n"", + "" sp = scipy.io.mmread(os.path.join(wd, sample, '{}.mtx.gz'.format(sample))).tocsr()\n"", + "" regions = open(os.path.join(wd, sample, '{}.regions'.format(sample))).read().splitlines()\n"", + "" barcodes = open(os.path.join(wd, sample, '{}.barcodes'.format(sample))).read().splitlines()\n"", + "" adatas[sample] = AnnData(sp, {'obs_names':barcodes}, {'var_names':regions})\n"", + "" adatas[sample].var.index = [promoter_names[b] if b in promoter_names else b for b in adatas[sample].var.index]\n"", + "" adatas[sample].var_names_make_unique(join='.')\n"", + "" \n"", + "" adatas[sample] = adatas[sample][~adatas[sample].obs.index.isin(low_quality + doublets),:].copy()\n"", + "" adatas[sample].obs = adatas[sample].obs.join(qc_metrics, how='inner')\n"", + "" adatas[sample].obs['experiment'] = [i.split('_')[0] for i in adatas[sample].obs.index]\n"", + "" raw = adatas[sample].copy()\n"", + "" \n"", + "" sc.pp.normalize_per_cell(adatas[sample], counts_per_cell_after=1e4)\n"", + "" adatas[sample] = adatas[sample][:, adatas[sample].var.index.isin(hvgs)]\n"", + "" sc.pp.log1p(adatas[sample])\n"", + "" adatas[sample].obs['log_usable_counts'] = np.log(raw[:, raw.var.index.isin(hvgs)].X.sum(axis=1).A1)\n"", + "" sc.pp.regress_out(adatas[sample], ['log_usable_counts'])\n"", + "" adatas[sample].write(os.path.join(wd, '{}.norm.h5ad'.format(sample)))\n"", + "" \n"", + "" sc.pp.normalize_per_cell(raw, counts_per_cell_after=1e4)\n"", + "" sc.pp.log1p(raw)\n"", + "" raw.write(os.path.join(wd, '{}.raw.h5ad'.format(sample)))\n"" + ] + }, + { + ""cell_type"": ""markdown"", + ""metadata"": {}, + ""source"": [ + ""### Merge files from all samples"" + ] + }, + { + ""cell_type"": ""code"", + ""execution_count"": null, + ""metadata"": {}, + ""outputs"": [], + ""source"": [ + ""adatas = {}\n"", + ""adatas_raw = {}\n"", + ""samples = ['Islet1','Islet2','Islet3']\n"", + ""\n"", + ""for sample in samples:\n"", + "" adatas[sample] = sc.read_h5ad(os.path.join(wd, '{}.norm.h5ad'.format(sample)))\n"", + "" adatas_raw[sample] = sc.read_h5ad(os.path.join(wd, '{}.raw.h5ad'.format(sample)))\n"", + "" \n"", + ""adata_norm = AnnData.concatenate(adatas['Islet1'], adatas['Islet2'], adatas['Islet3'], \n"", + "" batch_key='norm', index_unique=None)\n"", + ""adata_norm_raw = AnnData.concatenate(adatas_raw['Islet1'], adatas_raw['Islet2'], adatas_raw['Islet3'],\n"", + "" batch_key='norm', index_unique=None)\n"", + ""adata_norm.raw = adata_norm_raw.copy()\n"", + ""\n"", + ""sc.pp.scale(adata_norm)\n"", + ""sc.tl.pca(adata_norm, zero_center=True, svd_solver='arpack', random_state=0)\n"", + ""pc = pd.DataFrame(adata_norm.obsm['X_pca'], columns=['PC{}'.format(i) for i in range(1,51)], index=adata_norm.obs.index)\n"", + ""metadata = pd.DataFrame(index=adata_norm.obs.index)\n"", + ""metadata['donor'] = [i.split('_')[0] for i in metadata.index]"" + ] + }, + { + ""cell_type"": ""markdown"", + ""metadata"": {}, + ""source"": [ + ""### Run Harmony (rpy2) to correct for batch effects"" + ] + }, + { + ""cell_type"": ""code"", + ""execution_count"": null, + ""metadata"": {}, + ""outputs"": [], + ""source"": [ + ""%%R -i pc -i metadata -o harmonized\n"", + ""library(harmony)\n"", + ""library(magrittr)\n"", + ""\n"", + ""# run Harmony on the PCs\n"", + ""harmonized <- HarmonyMatrix(pc, metadata, c('donor'), do_pca=FALSE)\n"", + ""harmonized <- data.frame(harmonized)"" + ] + }, + { + ""cell_type"": ""markdown"", + ""metadata"": {}, + ""source"": [ + ""### Plot cluster based on corrected components"" + ] + }, + { + ""cell_type"": ""code"", + ""execution_count"": null, + ""metadata"": {}, + ""outputs"": [], + ""source"": [ + ""adata_norm.obsm['X_pca'] = harmonized.values\n"", + ""sc.pp.neighbors(adata_norm, n_neighbors=30, method='umap', metric='cosine', random_state=0, n_pcs=50)\n"", + ""sc.tl.leiden(adata_norm, resolution=1.5, random_state=0)\n"", + ""sc.tl.umap(adata_norm, min_dist=0.3, random_state=0)\n"", + ""\n"", + ""sc.settings.set_figure_params(dpi=100)\n"", + ""sc.pl.umap(adata_norm, color=['leiden'], size=9, legend_loc='on data')\n"", + ""sc.pl.umap(adata_norm, color=['experiment'], size=1, alpha=.5)\n"", + ""\n"", + ""# plot quality metrics\n"", + ""sc.pl.umap(adata_norm, color=['log_usable_counts'], size=9, color_map='Blues')\n"", + ""sc.pl.umap(adata_norm, color=['frac_reads_in_peaks','frac_reads_in_promoters','frac_promoters_used'], cmap='Reds', size=9, legend_loc='on data', title=['Frac. reads in peaks', 'Frac. reads in promoters', 'Frac. promoters used'])\n"", + ""\n"", + ""# 5kb windows overlapping marker promoters \n"", + ""sc.pl.umap(adata_norm, color=['GCG','INS-IGF2','SST'], size=9, color_map='Blues', frameon=True, use_raw=True)\n"", + ""sc.pl.umap(adata_norm, color=['PPY','CFTR','REG1A'], size=9, color_map='Blues', frameon=True, use_raw=True)\n"", + ""sc.pl.umap(adata_norm, color=['CD93','PDGFRB','NCF2'], size=9, color_map='Blues', frameon=True, use_raw=True)"" + ] + }, + { + ""cell_type"": ""markdown"", + ""metadata"": {}, + ""source"": [ + ""### Subclustering at high resolution to identify potential doublet subclusters"" + ] + }, + { + ""cell_type"": ""code"", + ""execution_count"": null, + ""metadata"": {}, + ""outputs"": [], + ""source"": [ + ""subset_cluster = ['0']\n"", + ""sc.tl.louvain(adata_norm, restrict_to=('leiden',subset_cluster), resolution=3, random_state=0, key_added='subset')\n"", + ""sc.pl.umap(adata_norm, color=['subset'], size=9)\n"", + ""\n"", + ""fig, ax1 = plt.subplots(1,1,figsize=(5,5))\n"", + ""subset = adata_norm.obs.join(pd.DataFrame(adata_norm.obsm['X_umap'], index=adata_norm.obs.index, columns=['UMAP1','UMAP2']), how='inner')\n"", + ""subset = subset.loc[subset['leiden'].isin(subset_cluster)]\n"", + ""for s in sorted(set(subset['subset'])):\n"", + "" ax1.scatter(subset.loc[subset['subset']==s, 'UMAP1'], subset.loc[subset['subset']==s, 'UMAP2'], alpha=1, s=4, label=s)\n"", + ""ax1.legend(markerscale=3)\n"", + ""plt.show()\n"", + ""\n"", + ""# plot qc metrics including subclusters\n"", + ""for qc_metric in ['log10_usable_counts', 'frac_reads_in_peaks', 'frac_promoters_used']:\n"", + "" fig, ax1 = plt.subplots(1,1,figsize=(7,5))\n"", + "" sns.boxplot(x='subset', y=qc_metric, data=adata_norm.obs, ax=ax1)\n"", + "" ax1.axhline(adata_norm.obs[qc_metric].median(), color='black', ls='dotted')\n"", + "" ax1.set_xticklabels(ax1.get_xticklabels(), rotation=90)\n"", + "" plt.show()\n"", + ""\n"", + ""# check marker promoters for potential doublet subclusters\n"", + ""sc.pl.dotplot(adata_norm, ['GCG','INS-IGF2','SST','PPY','CFTR','REG1A','CD93','PDGFRB','NCF2'],\n"", + "" standard_scale='var', groupby='subset', dendrogram=False, use_raw=True)\n"", + "" \n"", + ""adata_norm.obs.loc[adata_norm.obs['subset'].isin(['0,28'])].to_csv(os.path.join(wd, '{}.doublets'.format(sample_name)), header=False, columns=[])"" + ] + } + ], + ""metadata"": { + ""kernelspec"": { + ""display_name"": ""Python 3"", + ""language"": ""python"", + ""name"": ""python3"" + }, + ""language_info"": { + ""codemirror_mode"": { + ""name"": ""ipython"", + ""version"": 3 + }, + ""file_extension"": "".py"", + ""mimetype"": ""text/x-python"", + ""name"": ""python"", + ""nbconvert_exporter"": ""python"", + ""pygments_lexer"": ""ipython3"", + ""version"": ""3.7.6"" + } + }, + ""nbformat"": 4, + ""nbformat_minor"": 2 +} +","Unknown" +"Epigenetics","kjgaulton/pipelines","islet_snATAC_pipeline/snATAC_pipeline.py",".py","16638","304","#!/usr/bin/env python3 + +import os +import sys +import gzip +import argparse +import logging +import subprocess +import pysam +import numpy as np +import pandas as pd +import scipy.sparse +from multiprocessing import Pool + +def trim_reads(args): + pair1_trim = os.path.join(args.output, os.path.basename(args.read1).split('.fastq.gz')[0] + '_val_1.fq.gz') + pair2_trim = os.path.join(args.output, os.path.basename(args.read2).split('.fastq.gz')[0] + '_val_2.fq.gz') + if os.path.isfile(pair1_trim) and os.path.isfile(pair2_trim): + return pair1_trim, pair2_trim + trim_galore_cmd = ['trim_galore', '--nextera', '--fastqc', '-q', '20', '-o', args.output, '--paired', args.read1, args.read2] + with open(os.devnull, 'w') as f: + subprocess.call(trim_galore_cmd, stderr=f, stdout=f) + return pair1_trim, pair2_trim + +def align_reads(args): + align_log = args.output_prefix + '.align.log' + aligned_bam = args.output_prefix + '.compiled.bam' + filtered_bam = args.output_prefix + '.compiled.filt.bam' + + bwa_mem_cmd = ['bwa', 'mem', '-t', str(args.threads), args.reference, args.read1, args.read2] + filter1_cmd = ['samtools', 'view', '-b', '-h', '-q', str(args.map_quality), '-F', '2048', '-'] + fixmate_cmd = ['samtools', 'fixmate', '-r', '-', '-'] + samtools_sort_cmd = ['samtools', 'sort', '-m', str(args.memory)+'G', '-@', str(args.threads), '-'] + filter2_cmd = ['samtools', 'view', '-h', '-f', '3', '-F', '4', '-F', '256', '-F', '1024', aligned_bam] + samtools_view_cmd = ['samtools', 'view', '-b', '-'] + + with open(align_log, 'w') as log, open(aligned_bam, 'w') as bam_out: + bwa_mem = subprocess.Popen(bwa_mem_cmd, stdout=subprocess.PIPE, stderr=log) + filt1 = subprocess.Popen(filter1_cmd, stdin=bwa_mem.stdout, stdout=subprocess.PIPE) + fixmate = subprocess.Popen(fixmate_cmd, stdin=filt1.stdout, stdout=subprocess.PIPE) + subprocess.call(samtools_sort_cmd, stdin=fixmate.stdout, stdout=bam_out, stderr=log) + + with open(align_log, 'a') as log, open(filtered_bam, 'w') as bam_out: + filt2 = subprocess.Popen(filter2_cmd, stderr=log, stdout=subprocess.PIPE) + view = subprocess.Popen(samtools_view_cmd, stdin=subprocess.PIPE, stdout=bam_out) + for line in filt2.stdout: + line = line.decode().rstrip('\n') + if line.startswith('@'): + try: + view.stdin.write('{}\n'.format(line).encode()) + except IOError as err: + if err.errno == errno.EPIPE or err.errno == errno.EINVAL: + break + else: + raise + continue + fields = line.split('\t') + barcode = fields[0].split(':')[0] + fields[0] = barcode + '_' + ':'.join(fields[0].split(':')[1:]) + fields.append('BX:Z:{}'.format(barcode)) + try: + view.stdin.write('{}\n'.format('\t'.join(fields)).encode()) + except IOError as err: + if err.errno == errno.EPIPE or err.errno == errno.EINVAL: + break + else: + raise + view.stdin.close() + view.wait() + return + +def remove_duplicate_reads(args): + filtered_bam = args.output_prefix + '.compiled.filt.bam' + markdup_bam = args.output_prefix + '.filt.md.bam' + rmdup_bam = args.output_prefix + '.filt.rmdup.bam' + markdup_log = args.output_prefix + '.MarkDuplicates.log' + markdup_cmd = ['java', '-Xmx24G', '-jar', args.picard, + 'MarkDuplicates', 'INPUT={}'.format(filtered_bam), 'OUTPUT={}'.format(markdup_bam), + 'VALIDATION_STRINGENCY=LENIENT', 'BARCODE_TAG=BX', 'METRICS_FILE={}'.format(markdup_log), + 'REMOVE_DUPLICATES=false'] + index_cmd = ['samtools', 'index', markdup_bam] + filter_cmd = ['samtools', 'view', '-@', str(args.threads), '-b', '-f', '3', '-F', '1024', markdup_bam] + filter_cmd.extend(['chr{}'.format(c) for c in list(map(str, range(1,23))) + ['X','Y']]) + + with open(os.devnull, 'w') as null: + subprocess.call(markdup_cmd, stderr=null, stdout=null) + subprocess.call(index_cmd) + if os.path.isfile(markdup_bam): + with open(rmdup_bam, 'w') as bam_out: + subprocess.call(filter_cmd, stdout=bam_out) + else: + raise FileNotFoundError('{} not found!'.format(markdup_bam)) + return + +def qc_metrics(args): + md_bam = args.output_prefix + '.filt.md.bam' + rmdup_bam = args.output_prefix + '.filt.rmdup.bam' + tagalign_file = args.output_prefix + '.filt.rmdup.tagAlign.gz' + + if os.path.isfile(rmdup_bam): + with gzip.open(tagalign_file, 'wt') as f: + bamfile = pysam.AlignmentFile(rmdup_bam, 'rb') + genome_size = {item['SN']:item['LN'] for item in bamfile.header['SQ']} + for read in bamfile: + if not read.is_proper_pair: + continue + barcode = read.query_name.split('_')[0] + read_chr = read.reference_name + read_start = max(1, read.reference_end - args.shift - args.extsize - 5 if read.is_reverse else read.reference_start + args.shift + 4) + read_end = min(genome_size[read_chr], read.reference_end - args.shift - 5 if read.is_reverse else read.reference_start + args.shift + args.extsize + 4) + read_qual = read.mapping_quality + if read.is_reverse: + read_orient = '-' + else: + read_orient = '+' + line_out = '\t'.join([read_chr, str(read_start), str(read_end), '{}_{}'.format(args.name,barcode), str(read_qual), read_orient]) + print(line_out, sep='\t', file=f) + bamfile.close() + else: + raise FileNotFoundError('{} not found!'.format(rmdup_bam)) + + qc_metrics = {} + chr_names = ['chr1', 'chr2', 'chr3', 'chr4', 'chr5', 'chr6', 'chr7', 'chr8', 'chr9', 'chr10', 'chr11', 'chr12', 'chr13', 'chr14', 'chr15', 'chr16', 'chr17', 'chr18', 'chr19', 'chr20', 'chr21', 'chr22', 'chrX', 'chrY'] + # mito and duplicated read percentage + if os.path.isfile(md_bam): + bamfile = pysam.AlignmentFile(md_bam, 'rb') + for read in bamfile: + barcode = '{}_{}'.format(args.name, read.query_name.split('_')[0]) + if barcode not in qc_metrics: + qc_metrics[barcode] = {} + if not read.is_duplicate: + if read.reference_name in chr_names: + qc_metrics[barcode]['unique_usable_reads'] = qc_metrics[barcode].get('unique_usable_reads', 0) + 1 + elif read.reference_name == 'chrM': + qc_metrics[barcode]['unique_mito_reads'] = qc_metrics[barcode].get('unique_mito_reads', 0) + 1 + qc_metrics[barcode]['total_sequenced_reads'] = qc_metrics[barcode].get('total_sequenced_reads', 0) + 1 + else: + qc_metrics[barcode]['duplicated_reads'] = qc_metrics[barcode].get('duplicated_reads', 0) + 1 + qc_metrics[barcode]['total_sequenced_reads'] = qc_metrics[barcode].get('total_sequenced_reads', 0) + 1 + else: + raise FileNotFoundError('{} not found!'.format(md_bam)) + qc_metrics = pd.DataFrame.from_dict(qc_metrics, orient='index').fillna(0).astype(int) + # reads in peaks + macs2_cmd = ['macs2', 'callpeak', '-t', tagalign_file, '--outdir', args.output, '-n', args.name, '-p', '.05', '--nomodel', '--keep-dup', 'all', '--shift', '0', '--extsize', '200', '-g', 'hs'] + with open(os.devnull, 'w') as f: + subprocess.call(macs2_cmd, stderr=f) + try: + os.remove(args.output_prefix + '_peaks.xls') + os.remove(args.output_prefix + '_summits.bed') + except: + pass + blacklist_cmd = subprocess.Popen(['bedtools', 'intersect', '-a' , args.output_prefix + '_peaks.narrowPeak', '-b', args.blacklist_file, '-v'], stdout=subprocess.PIPE) + intersect_cmd = subprocess.Popen(['bedtools', 'intersect', '-a', tagalign_file, '-b', '-' ], stdin=blacklist_cmd.stdout, stdout=subprocess.PIPE) + peak_counts = {bc:0 for bc in qc_metrics.index} + for line in intersect_cmd.stdout: + line = line.decode() + fields = line.rstrip().split('\t') + peak_counts[fields[3]] += 1 + qc_metrics['reads_in_peaks'] = qc_metrics.index.map(peak_counts).fillna(0).astype(int) + # reads in promoter and promoter usage + tss_counts = {bc:0 for bc in qc_metrics.index} + tss_cmd1 = subprocess.Popen(['bedtools', 'intersect', '-a', tagalign_file, '-b', args.promoter_file, '-wa'], stdout=subprocess.PIPE) + uniq = subprocess.Popen(['uniq'], stdin=tss_cmd1.stdout, stdout=subprocess.PIPE) + for line in uniq.stdout: + line = line.decode() + fields = line.rstrip().split('\t') + tss_counts[fields[3]] += 1 + + tss_used = {bc:[] for bc in qc_metrics.index} + tss_cmd2 = subprocess.Popen(['bedtools', 'intersect', '-a', tagalign_file, '-b', args.promoter_file, '-wa', '-wb'], stdout=subprocess.PIPE) + for line in tss_cmd2.stdout: + line = line.decode() + fields = line.rstrip().split('\t') + tss_used[fields[3]].append(fields[9]) + qc_metrics['reads_in_promoters'] = qc_metrics.index.map(tss_counts).fillna(0).astype(int) + qc_metrics['tss_used'] = [len(set(tss_used[bc])) for bc in qc_metrics.index] + total_prom = len(sorted(set(pd.read_table(args.promoter_file, sep='\t', header=None, names=['chr','start','end','promoter'])['promoter']))) + qc_metrics['frac_reads_in_peaks'] = qc_metrics['reads_in_peaks'].div(qc_metrics['unique_usable_reads']).replace(np.inf, 0).fillna(0) + qc_metrics['frac_reads_in_promoters'] = qc_metrics['reads_in_promoters'].div(qc_metrics['unique_usable_reads']).replace(np.inf, 0).fillna(0) + qc_metrics['frac_promoters_used'] = qc_metrics['tss_used']/total_prom + qc_metrics['frac_mito_reads'] = qc_metrics['unique_mito_reads'].div(qc_metrics['unique_usable_reads'] + qc_metrics['unique_mito_reads']).replace(np.inf, 0).fillna(0) + qc_metrics['frac_duplicated_reads'] = qc_metrics['duplicated_reads'].div(qc_metrics['total_sequenced_reads']).fillna(0) + qc_metrics.to_csv(os.path.join(args.output_prefix + '.qc_metrics.txt'), sep='\t') + return + + +def generate_matrix(args): + tagalign_file = args.output_prefix + '.filt.rmdup.tagAlign.gz' + qc_metrics = pd.read_table(args.output_prefix + '.qc_metrics.txt', sep='\t', header=0, index_col=0) + pass_barcodes = qc_metrics.loc[qc_metrics['unique_usable_reads'] >= args.minimum_reads].index + + lf_mtx_file = args.output_prefix + '.long_fmt_mtx.txt.gz' + barcodes_file = args.output_prefix + '.barcodes' + regions_file = args.output_prefix + '.regions' + mtx_file = args.output_prefix + '.mtx' + + windows_file = make_windows(args) + window_intersect = intersect_regions(tagalign_file, windows_file) + cut = subprocess.Popen(['cut', '-f', '4,10'], stdin=window_intersect.stdout, stdout=subprocess.PIPE) + sort = subprocess.Popen(['sort', '-S', '{}G'.format(args.memory * args.threads)], stdin=cut.stdout, stdout=subprocess.PIPE) + uniq = subprocess.Popen(['uniq', '-c'], stdin=sort.stdout, stdout=subprocess.PIPE) + awk = subprocess.Popen(['awk', '''BEGIN{{OFS=""\\t""}} {{print $2,$3,$1}}'''], stdin=uniq.stdout, stdout=subprocess.PIPE) + with gzip.open(lf_mtx_file, 'wt') as f: + subprocess.call(['gzip', '-c'], stdin=awk.stdout, stdout=f) + + lf_mtx = pd.read_table(lf_mtx_file, sep='\t', header=None, names=['barcode','region','count']) + lf_mtx = lf_mtx.loc[lf_mtx['barcode'].isin(pass_barcodes)] + lf_mtx.to_csv(lf_mtx_file, sep='\t', header=False, index=False, compression='gzip') + + tmp_R = args.output_prefix + '.tmp.R' + with open(tmp_R, 'w') as tR: + print('''library(Matrix)''', file=tR) + print('''data <- read.table('{}', sep='\\t', header=FALSE)'''.format(lf_mtx_file), file=tR) + print('''sparse.data <- with(data, sparseMatrix(i=as.numeric(V1), j=as.numeric(V2), x=V3, dimnames=list(levels(V1), levels(V2))))''', file=tR) + print('''t <- writeMM(sparse.data, '{}')'''.format(mtx_file), file=tR) + print('''write.table(data.frame(rownames(sparse.data)), file='{}', col.names=FALSE, row.names=FALSE, quote=FALSE)'''.format(barcodes_file), file=tR) + print('''write.table(data.frame(colnames(sparse.data)), file='{}', col.names=FALSE, row.names=FALSE, quote=FALSE)'''.format(regions_file), file=tR) + subprocess.call(['Rscript', tmp_R]) + subprocess.call(['gzip', mtx_file]) + os.remove(windows_file) + os.remove(tmp_R) + return + + +def intersect_regions(tagalign, regions): + awk_cmd = ['awk', '''BEGIN{{FS=OFS=""\\t""}} {{peakid=$1"":""$2""-""$3; gsub(""chr"","""",peakid); print $1, $2, $3, peakid}}''', regions] + intersect_cmd = ['bedtools', 'intersect', '-a', tagalign, '-b', '-', '-wa', '-wb'] + awk = subprocess.Popen(awk_cmd, stdout=subprocess.PIPE) + intersect = subprocess.Popen(intersect_cmd, stdin=awk.stdout, stdout=subprocess.PIPE) + return intersect + +def make_windows(args): + makewindows_cmd = ['bedtools', 'makewindows', '-g', args.chrom_sizes, '-w', str(args.window_size * 1000)] + filter_cmd = ['grep', '-v', '_'] + blacklist_cmd = ['bedtools', 'intersect', '-a', '-', '-b', args.blacklist_file, '-v'] + windows_file = '{}.{}kb_windows.bed'.format(args.output_prefix, args.window_size) + with open(windows_file, 'w') as f: + makewindows = subprocess.Popen(makewindows_cmd, stdout=subprocess.PIPE) + filt = subprocess.Popen(filter_cmd, stdin=makewindows.stdout, stdout=subprocess.PIPE) + subprocess.call(blacklist_cmd, stdin=filt.stdout, stdout=f) + return windows_file + +def main(args): + logging.info('Start.') + if not os.path.isdir(args.output): + os.makedirs(args.output) + args.output_prefix = os.path.join(args.output, args.name) + if not args.skip_trim: + logging.info('Trimming adapters using trim_galore.') + args.read1, args.read2 = trim_reads(args) + if not args.skip_align: + logging.info('Aligning reads using BWA mem with [{}] processors.'.format(args.threads)) + logging.info('Piping output to samtools using [{}] Gb of memory.'.format(args.memory)) + align_reads(args) + if not args.skip_rmdup: + logging.info('Removing duplicate and mitochrondrial reads.'.format(args.minimum_reads)) + remove_duplicate_reads(args) + if not args.skip_qc: + qc_metrics(args) + if not args.skip_matrix: + logging.info('Generating tagalign and chromatin accessibility matrix.') + generate_matrix(args) + logging.info('Finish.') + return + +def process_args(): + parser = argparse.ArgumentParser(description='Process combinatorial barcoding snATAC-seq data.') + io_group = parser.add_argument_group('I/O arguments') + io_group.add_argument('-r1', '--read1', required=True, type=str, help='Paired-end reads file 1') + io_group.add_argument('-r2', '--read2', required=True, type=str, help='Paired-end reads file 2') + io_group.add_argument('-o', '--output', required=False, type=str, default=os.getcwd(), help='Output directory to store processed files') + io_group.add_argument('-n', '--name', required=True, type=str, help='Prefix for naming all output files') + + align_group = parser.add_argument_group('Alignment arguments') + align_group.add_argument('-ref', '--reference', required=True, type=str, help='Path to the BWA-indexed reference genome') + align_group.add_argument('-t', '--threads', required=False, type=int, default=8, help='Number of threads to use for alignment [8]') + align_group.add_argument('-m', '--memory', required=False, type=int, default=4, help='Maximum amount of memory (G) per thread for samtools sort [4]') + align_group.add_argument('-q', '--map_quality', required=False, type=int, default=30, help='Mapping quality score filter for samtools [30]') + + dup_group = parser.add_argument_group('Remove duplicates arguments') + dup_group.add_argument('--picard', required=True, type=str, help='Path to picard.jar') + + matrix_group = parser.add_argument_group('Matrix generation arguments') + matrix_group.add_argument('--shift', required=False, type=int, default=-100, help='Read shift size') + matrix_group.add_argument('--extsize', required=False, type=int, default=200, help='Read extension size') + matrix_group.add_argument('--minimum-reads', required=False, type=int, default=500, help='Minimum number of reads for barcode inclusion') + matrix_group.add_argument('--window-size', required=False, type=int, default=5, help='Size (kb) to use for defining windows of accessibility') + matrix_group.add_argument('--chrom-sizes', required=False, type=str, default='references/hg19.chrom.sizes', help='Chromosome sizes file from UCSC') + matrix_group.add_argument('--blacklist-file', required=False, type=str, default='references/hg19-blacklist.v1.bed.gz', help='BED file of blacklisted regions') + matrix_group.add_argument('--promoter-file', required=False, type=str, default='references/gencode.v19.1kb_promoters.pc_transcripts.bed.gz', help='BED file of autosomal promoter regions') + + skip_group = parser.add_argument_group('Skip steps') + skip_group.add_argument('--skip-trim', required=False, action='store_true', default=False, help='Skip adapter trimming step') + skip_group.add_argument('--skip-align', required=False, action='store_true', default=False, help='Skip read alignment step') + skip_group.add_argument('--skip-rmdup', required=False, action='store_true', default=False, help='Skip duplicate removal step') + skip_group.add_argument('--skip-qc', required=False, action='store_true', default=False, help='Skip QC metrics calculation step') + skip_group.add_argument('--skip-matrix', required=False, action='store_true', default=False, help='Skip matrix generation step') + return parser.parse_args() + +if __name__ == '__main__': + logging.basicConfig(format='[%(filename)s] %(asctime)s %(levelname)s: %(message)s', datefmt='%I:%M:%S', level=logging.INFO) + args = process_args() + main(args) +","Python" +"Epigenetics","kjgaulton/pipelines","T1D_snATAC_pipeline/T1D_merged_snATAC.ipynb",".ipynb","14447","279","{ + ""cells"": [ + { + ""cell_type"": ""code"", + ""execution_count"": null, + ""metadata"": { + ""scrolled"": true + }, + ""outputs"": [], + ""source"": [ + ""import os\n"", + ""import numpy as np\n"", + ""import pandas as pd\n"", + ""import scipy.io\n"", + ""\n"", + ""# plotting\n"", + ""import matplotlib.pyplot as plt\n"", + ""import seaborn as sns\n"", + ""\n"", + ""# single cell\n"", + ""import scanpy.api as sc\n"", + ""from anndata import AnnData\n"", + ""\n"", + ""# etc\n"", + ""%load_ext rpy2.ipython"" + ] + }, + { + ""cell_type"": ""markdown"", + ""metadata"": {}, + ""source"": [ + ""### Regress out read depth per experiment"" + ] + }, + { + ""cell_type"": ""code"", + ""execution_count"": null, + ""metadata"": {}, + ""outputs"": [], + ""source"": [ + ""wd = 'T1D_snATAC/'\n"", + ""\n"", + ""adatas = {}\n"", + ""samples = ['nPOD-6282','nPOD-6251-1','nPOD-6251-2','nPOD-6004-1','nPOD-6004-2','nPOD-6007',\n"", + "" 'IIDP-AFC2208-1','IIDP-AFC2208-2','IIDP-AFEA331','IIDP-AFEP022','IIDP-AEHU156',\n"", + "" 'HemaCare-D205220','HemaCare-D105','HemaCare-D147558','HemaCare-D270271','HemaCare-D182364','HemaCare-D273097',\n"", + "" '10x-5k-1','10x-5k-2','10x-5k-3','10x-10k-1','10x-10k-2','10x-10k-3']\n"", + ""\n"", + ""# dictionary naming 5kb windows genome-wide based on overlap with gencode v19 gene TSS\n"", + ""promoters = pd.read_csv(os.path.join('references', 'gencode.v19.5kb_windows.promoter_names.txt.gz'), sep='\\t', header=None, index_col=0, names=['prom'])\n"", + ""promoter_names = promoters['prom'].to_dict() \n"", + ""\n"", + ""# cells from low quality and doublet clusters were identified through iterative clustering\n"", + ""low_frip = open(os.path.join(wd, 'T1D_snATAC.lowfrip')).read().splitlines()\n"", + ""low_reads = open(os.path.join(wd, 'T1D_snATAC.lowreads')).read().splitlines()\n"", + ""doublets = open(os.path.join(wd, 'T1D_snATAC.doublets')).read().splitlines()\n"", + ""\n"", + ""qc_metrics = pd.read_csv(os.path.join(wd, 'T1D_snATAC.qc_metrics.txt'), sep='\\t', header=0, index_col=0)\n"", + ""hvw = open(os.path.join(wd,'T1D_snATAC.hvw')).read().splitlines()\n"", + ""\n"", + ""for sample in samples:\n"", + "" sp = scipy.io.mmread(os.path.join(wd, sample, '{}.mtx.gz'.format(sample))).tocsr()\n"", + "" regions = open(os.path.join(wd, sample, '{}.regions'.format(sample))).read().splitlines()\n"", + "" barcodes = open(os.path.join(wd, sample, '{}.barcodes'.format(sample))).read().splitlines()\n"", + "" adatas[sample] = AnnData(sp, {'obs_names':barcodes}, {'var_names':regions})\n"", + "" adatas[sample].var.index = [promoter_names[b] if b in promoter_names else b for b in adatas[sample].var.index]\n"", + "" adatas[sample].var_names_make_unique(join='.')\n"", + "" \n"", + "" adatas[sample] = adatas[sample][~adatas[sample].obs.index.isin(low_frip + low_reads + doublets),:].copy()\n"", + "" adatas[sample].obs = adatas[sample].obs.join(qc_metrics, how='inner')\n"", + "" adatas[sample].obs['experiment'] = [i.split('_')[0] for i in adatas[sample].obs.index]\n"", + "" raw = adatas[sample].copy()\n"", + "" \n"", + "" sc.pp.normalize_per_cell(adatas[sample], counts_per_cell_after=1e4)\n"", + "" adatas[sample] = adatas[sample][:, adatas[sample].var.index.isin(hvgs)]\n"", + "" sc.pp.log1p(adatas[sample])\n"", + "" adatas[sample].obs['log_usable_counts'] = np.log(raw[:, raw.var.index.isin(hvgs)].X.sum(axis=1).A1)\n"", + "" sc.pp.regress_out(adatas[sample], ['log_usable_counts'])\n"", + "" adatas[sample].write(os.path.join(wd, '{}.norm.h5ad'.format(sample)))\n"", + "" \n"", + "" sc.pp.normalize_per_cell(raw, counts_per_cell_after=1e4)\n"", + "" sc.pp.log1p(raw)\n"", + "" raw.write(os.path.join(wd, '{}.raw.h5ad'.format(sample)))\n"" + ] + }, + { + ""cell_type"": ""markdown"", + ""metadata"": {}, + ""source"": [ + ""### Merge files from all samples"" + ] + }, + { + ""cell_type"": ""code"", + ""execution_count"": null, + ""metadata"": {}, + ""outputs"": [], + ""source"": [ + ""adatas = {}\n"", + ""adatas_raw = {}\n"", + ""samples = ['nPOD-6282','nPOD-6251-1','nPOD-6251-2','nPOD-6004-1','nPOD-6004-2','nPOD-6007',\n"", + "" 'IIDP-AFC2208-1','IIDP-AFC2208-2','IIDP-AFEA331','IIDP-AFEP022','IIDP-AEHU156',\n"", + "" 'HemaCare-D205220','HemaCare-D105','HemaCare-D147558','HemaCare-D270271','HemaCare-D182364','HemaCare-D273097',\n"", + "" '10x-5k-1','10x-5k-2','10x-5k-3','10x-10k-1','10x-10k-2','10x-10k-3']\n"", + ""for sample in samples:\n"", + "" adatas[sample] = sc.read_h5ad(os.path.join(wd, '{}.norm.h5ad'.format(sample)))\n"", + "" adatas_raw[sample] = sc.read_h5ad(os.path.join(wd, '{}.raw.h5ad'.format(sample)))\n"", + "" \n"", + ""adata_norm = AnnData.concatenate(adatas['nPOD-6282'], adatas['nPOD-6251-1'], adatas['nPOD-6251-2'], adatas['nPOD-6004-1'], adatas['nPOD-6004-2'], adatas['nPOD-6007'], \n"", + "" adatas['IIDP-AFC2208-1'], adatas['IIDP-AFC2208-2'], adatas['IIDP-AFEA331'], adatas['IIDP-AFEP022'], adatas['IIDP-AEHU156'],\n"", + "" adatas['HemaCare-D205220'], adatas['HemaCare-D105'], adatas['HemaCare-D147558'], adatas['HemaCare-D270271'], adatas['HemaCare-D182364'], adatas['HemaCare-D273097'],\n"", + "" adatas['10x-5k-1'], adatas['10x-5k-2'], adatas['10x-5k-3'], adatas['10x-10k-1'], adatas['10x-10k-2'], adatas['10x-10k-3'],\n"", + "" batch_key='norm', index_unique=None)\n"", + ""adata_norm_raw = AnnData.concatenate(adatas_raw['nPOD-6282'], adatas_raw['nPOD-6251-1'], adatas_raw['nPOD-6251-2'], adatas_raw['nPOD-6004-1'], adatas_raw['nPOD-6004-2'], adatas_raw['nPOD-6007'],\n"", + "" adatas_raw['IIDP-AFC2208-1'], adatas_raw['IIDP-AFC2208-2'], adatas_raw['IIDP-AFEA331'], adatas_raw['IIDP-AFEP022'], adatas_raw['IIDP-AEHU156'],\n"", + "" adatas_raw['HemaCare-D205220'], adatas_raw['HemaCare-D105'], adatas_raw['HemaCare-D147558'], adatas_raw['HemaCare-D270271'], adatas_raw['HemaCare-D182364'], adatas_raw['HemaCare-D273097'],\n"", + "" adatas_raw['10x-5k-1'], adatas_raw['10x-5k-2'], adatas_raw['10x-5k-3'], adatas_raw['10x-10k-1'], adatas_raw['10x-10k-2'], adatas_raw['10x-10k-3'],\n"", + "" batch_key='norm', index_unique=None)\n"", + ""adata_norm.raw = adata_norm_raw.copy()\n"", + ""\n"", + ""sc.pp.scale(adata_norm)\n"", + ""sc.tl.pca(adata_norm, zero_center=True, svd_solver='arpack', random_state=0)\n"", + ""pc = pd.DataFrame(adata_norm.obsm['X_pca'], columns=['PC{}'.format(i) for i in range(1,51)], index=adata_norm.obs.index)\n"", + ""metadata = pd.read_csv(os.path.join(wd, 'T1D_snATAC.metadata.txt'), sep='\\t', header=0, index_col=0)\n"", + ""metadata = metadata.loc[pc.index]"" + ] + }, + { + ""cell_type"": ""markdown"", + ""metadata"": {}, + ""source"": [ + ""### Run Harmony (rpy2) to correct for batch effects"" + ] + }, + { + ""cell_type"": ""code"", + ""execution_count"": null, + ""metadata"": {}, + ""outputs"": [], + ""source"": [ + ""%%R -i pc -i metadata -o harmonized\n"", + ""library(harmony)\n"", + ""library(magrittr)\n"", + ""\n"", + ""# run Harmony on the PCs\n"", + ""harmonized <- HarmonyMatrix(pc, metadata, c('donor','sex','technology'), do_pca=FALSE)\n"", + ""harmonized <- data.frame(harmonized)"" + ] + }, + { + ""cell_type"": ""markdown"", + ""metadata"": {}, + ""source"": [ + ""### Plot cluster based on corrected components"" + ] + }, + { + ""cell_type"": ""code"", + ""execution_count"": null, + ""metadata"": {}, + ""outputs"": [], + ""source"": [ + ""adata_norm.obsm['X_pca'] = harmonized.values\n"", + ""sc.pp.neighbors(adata_norm, n_neighbors=30, method='umap', metric='cosine', random_state=0, n_pcs=50)\n"", + ""sc.tl.leiden(adata_norm, resolution=1.5, random_state=0)\n"", + ""sc.tl.umap(adata_norm, min_dist=0.3, random_state=0)\n"", + ""\n"", + ""sc.settings.set_figure_params(dpi=100)\n"", + ""sc.pl.umap(adata_norm, color=['leiden'], size=9, legend_loc='on data')\n"", + ""sc.pl.umap(adata_norm, color=['experiment'], size=1, alpha=.5)\n"", + ""\n"", + ""# plot quality metrics\n"", + ""sc.pl.umap(adata_norm, color=['log_usable_counts'], size=9, color_map='Blues')\n"", + ""sc.pl.umap(adata_norm, color=['frac_reads_in_peaks','frac_reads_in_promoters','frac_promoters_used'], cmap='Reds', size=9, legend_loc='on data', title=['Frac. reads in peaks', 'Frac. reads in promoters', 'Frac. promoters used'])\n"", + ""\n"", + ""# 5kb windows overlapping marker promoters \n"", + ""sc.pl.umap(adata_norm, color=['INS-IGF2','GCG','SST'], size=9, color_map='Blues', frameon=True, use_raw=True)\n"", + ""sc.pl.umap(adata_norm, color=['PPY','REG1A','CFTR'], size=9, color_map='Blues', frameon=True, use_raw=True)\n"", + ""sc.pl.umap(adata_norm, color=['PDGFRB','CLDN5','C1QB'], size=9, color_map='Blues', frameon=True, use_raw=True)\n"", + ""sc.pl.umap(adata_norm, color=['CD3D','CD4','FOXP3'], size=9, color_map='Blues', frameon=True, use_raw=True)\n"", + ""sc.pl.umap(adata_norm, color=['CD8B','IFNG','NCR1'], size=9, color_map='Blues', frameon=True, use_raw=True)\n"", + ""sc.pl.umap(adata_norm, color=['MS4A1','TCL1A','FOXP3'], size=9, color_map='Blues', frameon=True, use_raw=True)\n"", + ""sc.pl.umap(adata_norm, color=['GATA1','PTCRA','IL1B'], size=9, color_map='Blues', frameon=True, use_raw=True)"" + ] + }, + { + ""cell_type"": ""code"", + ""execution_count"": null, + ""metadata"": { + ""scrolled"": false + }, + ""outputs"": [], + ""source"": [ + ""# More 5kb windows overlapping marker promoters \n"", + ""sc.pl.umap(adata_norm, color=['INS-IGF2','IAPP','SIX2'], size=9, color_map='Blues', frameon=True, use_raw=True)\n"", + ""sc.pl.umap(adata_norm, color=['GCG','FEV','GATA6'], size=9, color_map='Blues', frameon=True, use_raw=True)\n"", + ""sc.pl.umap(adata_norm, color=['SST','HHEX','SALL1'], size=9, color_map='Blues', frameon=True, use_raw=True)\n"", + ""sc.pl.umap(adata_norm, color=['PPY','SUCNR1','CDH20'], size=9, color_map='Blues', frameon=True, use_raw=True)\n"", + ""sc.pl.umap(adata_norm, color=['CFTR','6:51940000-51945000','4:143470000-143475000'], size=9, color_map='Blues', frameon=True, use_raw=True)\n"", + ""sc.pl.umap(adata_norm, color=['REG1A','PTF1A','PRSS1'], size=9, color_map='Blues', frameon=True, use_raw=True)\n"", + ""sc.pl.umap(adata_norm, color=['TCEA2','CLEC14A','ROBO4'], size=9, color_map='Blues', frameon=True, use_raw=True)\n"", + ""sc.pl.umap(adata_norm, color=['C1QA','C1QB','C1QC'], size=9, color_map='Blues', frameon=True, use_raw=True)\n"", + ""sc.pl.umap(adata_norm, color=['CD69','BCL11B','STK17B'], size=9, color_map='Blues', frameon=True, use_raw=True)\n"", + ""sc.pl.umap(adata_norm, color=['PDGFRB','SPARC','COL6A3'], size=9, color_map='Blues', frameon=True, use_raw=True)\n"", + ""sc.pl.umap(adata_norm, color=['CD14','IL1B','MAFB'], size=9, color_map='Blues', frameon=True, use_raw=True) # Monocyte\n"", + ""sc.pl.umap(adata_norm, color=['CD4','CD3D','IL2RA'], size=9, color_map='Blues', frameon=True, use_raw=True, vmax=2) # CD4 T-cell\n"", + ""sc.pl.umap(adata_norm, color=['CD8A','NFIC','FASLG'], size=9, color_map='Blues', frameon=True, use_raw=True, vmax=2) # CD8 T-cell\n"", + ""sc.pl.umap(adata_norm, color=['CD19','MS4A1','CD79A'], size=9, color_map='Blues', frameon=True, use_raw=True, vmax=2) #B-cell \n"", + ""sc.pl.umap(adata_norm, color=['NCAM1','PRF1','SH2D1B'], size=9, color_map='Blues', frameon=True, use_raw=True, vmax=2) # NK cell\n"", + ""sc.pl.umap(adata_norm, color=['ITGA2B','PTGER3','CD9'], size=9, color_map='Blues', frameon=True, use_raw=True, vmax=2) # Megakaryocyte\n"", + ""sc.pl.umap(adata_norm, color=['PTCRA','LAMP5','RGS7'], size=9, color_map='Blues', frameon=True, use_raw=True, vmax=2) # pDC, FLT3 \n"", + ""sc.pl.umap(adata_norm, color=['CXCR3','B3GNT6','SDPR'], size=9, color_map='Blues', frameon=True, use_raw=True, vmax=2) # monocyte-derived DC, LAMP2\n"" + ] + }, + { + ""cell_type"": ""markdown"", + ""metadata"": {}, + ""source"": [ + ""### Subclustering at high resolution to identify potential doublet subclusters"" + ] + }, + { + ""cell_type"": ""code"", + ""execution_count"": null, + ""metadata"": {}, + ""outputs"": [], + ""source"": [ + ""subset_cluster = ['0']\n"", + ""sc.tl.louvain(adata_norm, restrict_to=('leiden',subset_cluster), resolution=3, random_state=0, key_added='subset')\n"", + ""sc.pl.umap(adata_norm, color=['subset'], size=9)\n"", + ""\n"", + ""fig, ax1 = plt.subplots(1,1,figsize=(5,5))\n"", + ""subset = adata_norm.obs.join(pd.DataFrame(adata_norm.obsm['X_umap'], index=adata_norm.obs.index, columns=['UMAP1','UMAP2']), how='inner')\n"", + ""subset = subset.loc[subset['leiden'].isin(subset_cluster)]\n"", + ""for s in sorted(set(subset['subset'])):\n"", + "" ax1.scatter(subset.loc[subset['subset']==s, 'UMAP1'], subset.loc[subset['subset']==s, 'UMAP2'], alpha=1, s=4, label=s)\n"", + ""ax1.legend(markerscale=3)\n"", + ""plt.show()\n"", + ""\n"", + ""# plot qc metrics including subclusters\n"", + ""for qc_metric in ['log10_usable_counts', 'frac_reads_in_peaks', 'frac_promoters_used']:\n"", + "" fig, ax1 = plt.subplots(1,1,figsize=(7,5))\n"", + "" sns.boxplot(x='subset', y=qc_metric, data=adata_norm.obs, ax=ax1)\n"", + "" ax1.axhline(adata_norm.obs[qc_metric].median(), color='black', ls='dotted')\n"", + "" ax1.set_xticklabels(ax1.get_xticklabels(), rotation=90)\n"", + "" plt.show()\n"", + ""\n"", + ""# check marker promoters for potential doublet subclusters\n"", + ""sc.pl.dotplot(adata_norm, ['INS-IGF2','GCG','SST','PPY','REG1A','CFTR','PDGFRB','CLDN5','C1QB',\n"", + "" 'CD3D','CD4','FOXP3','CD8B','IFNG','NCR1','MS4A1','TCL1A','FOXP3','GATA1','PTCRA','IL1B'],\n"", + "" standard_scale='var', groupby='subset', dendrogram=False, use_raw=True)\n"", + "" \n"", + ""adata_norm.obs.loc[adata_norm.obs['subset'].isin(['0,28'])].to_csv(os.path.join(wd, '{}.acinar.doublets'.format(sample_name)), header=False, columns=[])"" + ] + } + ], + ""metadata"": { + ""kernelspec"": { + ""display_name"": ""Python 3"", + ""language"": ""python"", + ""name"": ""python3"" + }, + ""language_info"": { + ""codemirror_mode"": { + ""name"": ""ipython"", + ""version"": 3 + }, + ""file_extension"": "".py"", + ""mimetype"": ""text/x-python"", + ""name"": ""python"", + ""nbconvert_exporter"": ""python"", + ""pygments_lexer"": ""ipython3"", + ""version"": ""3.7.6"" + } + }, + ""nbformat"": 4, + ""nbformat_minor"": 2 +} +","Unknown" +"Epigenetics","kjgaulton/pipelines","T1D_snATAC_pipeline/snATAC_pipeline_10X.py",".py","13687","248","#!/usr/bin/env python3 + + +import os +import sys +import gzip +import argparse +import logging +import subprocess +import pysam +import numpy as np +import pandas as pd +import scipy.sparse +from multiprocessing import Pool + +def convert_10X_bam(args): + bf = pysam.AlignmentFile(args.input_bam, 'rb') + cf = pysam.AlignmentFile(args.output_prefix + '.compiled.filt.bam', 'wb', template=bf) + + for read in bf: + try: + barcode = read.get_tag('CB').split('-1')[0] + except: + pass + continue + read.query_name = barcode + '_' + read.query_name + cf.write(read) + bf.close() + cf.close() + return + +def remove_duplicate_reads(args): + filt_bam = args.output_prefix + '.compiled.filt.bam' + markdup_bam = args.output_prefix + '.filt.md.bam' + rmdup_bam = args.output_prefix + '.filt.rmdup.bam' + + filt_cmd = ['samtools', 'view', '-bu', '-q', str(args.map_quality), '-F', '256', '-F', '512', '-F', '2048', filt_bam] + sortname_cmd = ['samtools', 'sort', '-n', '-m' , str(args.memory)+'G', '-@', str(args.threads), '-'] + fixmate_cmd = ['samtools', 'fixmate', '-r', '-', '-'] + sortpos_cmd = ['samtools', 'sort', '-m', str(args.memory)+'G', '-@', str(args.threads), '-o', markdup_bam] + index_cmd = ['samtools', 'index', markdup_bam] + rmdup_cmd = ['samtools', 'view', '-@', str(args.threads), '-b', '-f', '3', '-F', '1024', markdup_bam] + rmdup_cmd.extend(['chr{}'.format(c) for c in list(map(str, range(1,23))) + ['X','Y']]) + + with open(os.devnull, 'w') as null: + filt = subprocess.Popen(filt_cmd, stdout=subprocess.PIPE) + sortname = subprocess.Popen(sortname_cmd, stdin=filt.stdout, stdout=subprocess.PIPE) + fixmate = subprocess.Popen(fixmate_cmd, stdin=sortname.stdout, stdout=subprocess.PIPE) + subprocess.call(sortpos_cmd, stdin=fixmate.stdout) + subprocess.call(index_cmd) + if os.path.isfile(markdup_bam): + with open(rmdup_bam, 'w') as bam_out: + subprocess.call(rmdup_cmd, stdout=bam_out) + else: + raise FileNotFoundError('{} not found!'.format(markdup_bam)) + return + +def qc_metrics(args): + md_bam = args.output_prefix + '.filt.md.bam' + rmdup_bam = args.output_prefix + '.filt.rmdup.bam' + tagalign_file = args.output_prefix + '.filt.rmdup.tagAlign.gz' + + if os.path.isfile(rmdup_bam) and not os.path.isfile(tagalign_file): + with gzip.open(tagalign_file, 'wt') as f: + bamfile = pysam.AlignmentFile(rmdup_bam, 'rb') + genome_size = {item['SN']:item['LN'] for item in bamfile.header['SQ']} + for read in bamfile: + if not read.is_proper_pair: + continue + barcode = read.query_name.split('_')[0] + read_chr = read.reference_name + read_start = max(1, read.reference_end - args.shift - args.extsize - 5 if read.is_reverse else read.reference_start + args.shift + 4) + read_end = min(genome_size[read_chr], read.reference_end - args.shift - 5 if read.is_reverse else read.reference_start + args.shift + args.extsize + 4) + read_qual = read.mapping_quality + if read.is_reverse: + read_orient = '-' + else: + read_orient = '+' + line_out = '\t'.join([read_chr, str(read_start), str(read_end), '{}_{}'.format(args.name,barcode), str(read_qual), read_orient]) + print(line_out, sep='\t', file=f) + bamfile.close() +# else: +# raise FileNotFoundError('{} not found!'.format(rmdup_bam)) + + qc_metrics = {} + chr_names = ['chr1', 'chr2', 'chr3', 'chr4', 'chr5', 'chr6', 'chr7', 'chr8', 'chr9', 'chr10', 'chr11', 'chr12', 'chr13', 'chr14', 'chr15', 'chr16', 'chr17', 'chr18', 'chr19', 'chr20', 'chr21', 'chr22', 'chrX', 'chrY'] + if os.path.isfile(md_bam): + bamfile = pysam.AlignmentFile(md_bam, 'rb') + for read in bamfile: + barcode = '{}_{}'.format(args.name, read.query_name.split('_')[0]) + if barcode not in qc_metrics: + qc_metrics[barcode] = {} + if not read.is_duplicate: + if read.reference_name in chr_names: + qc_metrics[barcode]['unique_usable_reads'] = qc_metrics[barcode].get('unique_usable_reads', 0) + 1 + elif read.reference_name == 'chrM': + qc_metrics[barcode]['unique_mito_reads'] = qc_metrics[barcode].get('unique_mito_reads', 0) + 1 + qc_metrics[barcode]['total_sequenced_reads'] = qc_metrics[barcode].get('total_sequenced_reads', 0) + 1 + else: + qc_metrics[barcode]['duplicated_reads'] = qc_metrics[barcode].get('duplicated_reads', 0) + 1 + qc_metrics[barcode]['total_sequenced_reads'] = qc_metrics[barcode].get('total_sequenced_reads', 0) + 1 + else: + raise FileNotFoundError('{} not found!'.format(md_bam)) + qc_metrics = pd.DataFrame.from_dict(qc_metrics, orient='index').fillna(0).astype(int) + macs2_cmd = ['macs2', 'callpeak', '-t', tagalign_file, '--outdir', args.output, '-n', args.name, '-p', '.05', '--nomodel', '--keep-dup', 'all', '--shift', '0', '--extsize', '200', '-g', 'hs'] + with open(os.devnull, 'w') as f: + subprocess.call(macs2_cmd, stderr=f) + try: + os.remove(args.output_prefix + '_peaks.xls') + os.remove(args.output_prefix + '_summits.bed') + except: + pass + blacklist_cmd = subprocess.Popen(['bedtools', 'intersect', '-a' , args.output_prefix + '_peaks.narrowPeak', '-b', args.blacklist_file, '-v'], stdout=subprocess.PIPE) + intersect_cmd = subprocess.Popen(['bedtools', 'intersect', '-a', tagalign_file, '-b', '-' ], stdin=blacklist_cmd.stdout, stdout=subprocess.PIPE) + peak_counts = {bc:0 for bc in qc_metrics.index} + for line in intersect_cmd.stdout: + line = line.decode() + fields = line.rstrip().split('\t') + peak_counts[fields[3]] += 1 + qc_metrics['reads_in_peaks'] = qc_metrics.index.map(peak_counts).fillna(0).astype(int) + tss_counts = {bc:0 for bc in qc_metrics.index} + tss_used = {bc:[] for bc in qc_metrics.index} + tss_cmd = subprocess.Popen(['bedtools', 'intersect', '-a', tagalign_file, '-b', args.promoter_file, '-wa', '-wb'], stdout=subprocess.PIPE) + for line in tss_cmd.stdout: + line = line.decode() + fields = line.rstrip().split('\t') + tss_counts[fields[3]] += 1 + tss_used[fields[3]].append(fields[9]) + qc_metrics['reads_in_promoters'] = qc_metrics.index.map(tss_counts).fillna(0).astype(int) + qc_metrics['tss_used'] = [len(set(tss_used[bc])) for bc in qc_metrics.index] + total_prom = len(open(args.promoter_file).read().splitlines()) + qc_metrics['frac_reads_in_peaks'] = qc_metrics['reads_in_peaks'].div(qc_metrics['unique_usable_reads']).replace(np.inf, 0).fillna(0) + qc_metrics['frac_reads_in_promoters'] = qc_metrics['reads_in_promoters'].div(qc_metrics['unique_usable_reads']).replace(np.inf, 0).fillna(0) + qc_metrics['frac_promoters_used'] = qc_metrics['tss_used']/total_prom + qc_metrics['frac_mito_reads'] = qc_metrics['unique_mito_reads'].div(qc_metrics['unique_usable_reads'] + qc_metrics['unique_mito_reads']).replace(np.inf, 0).fillna(0) + qc_metrics['frac_duplicated_reads'] = qc_metrics['duplicated_reads'].div(qc_metrics['total_sequenced_reads']).fillna(0) + qc_metrics.to_csv(os.path.join(args.output_prefix + '.qc_metrics.txt'), sep='\t') + return + +def generate_matrix(args): + tagalign_file = args.output_prefix + '.filt.rmdup.tagAlign.gz' + qc_metrics = pd.read_table(args.output_prefix + '.qc_metrics.txt', sep='\t', header=0, index_col=0) + pass_barcodes = qc_metrics.loc[qc_metrics['unique_usable_reads'] >= args.minimum_reads].index + + lf_mtx_file = args.output_prefix + '.long_fmt_mtx.txt.gz' + barcodes_file = args.output_prefix + '.barcodes' + regions_file = args.output_prefix + '.regions' + mtx_file = args.output_prefix + '.mtx' + + windows_file = make_windows(args) + window_intersect = intersect_regions(tagalign_file, windows_file) + cut = subprocess.Popen(['cut', '-f', '4,10'], stdin=window_intersect.stdout, stdout=subprocess.PIPE) + sort = subprocess.Popen(['sort', '-S', '{}G'.format(args.memory * args.threads)], stdin=cut.stdout, stdout=subprocess.PIPE) + uniq = subprocess.Popen(['uniq', '-c'], stdin=sort.stdout, stdout=subprocess.PIPE) + awk = subprocess.Popen(['awk', '''BEGIN{{OFS=""\\t""}} {{print $2,$3,$1}}'''], stdin=uniq.stdout, stdout=subprocess.PIPE) + with gzip.open(lf_mtx_file, 'wt') as f: + subprocess.call(['gzip', '-c'], stdin=awk.stdout, stdout=f) + + lf_mtx = pd.read_table(lf_mtx_file, sep='\t', header=None, names=['barcode','region','count']) + lf_mtx = lf_mtx.loc[lf_mtx['barcode'].isin(pass_barcodes)] + lf_mtx.to_csv(lf_mtx_file, sep='\t', header=False, index=False, compression='gzip') + + tmp_R = args.output_prefix + '.tmp.R' + with open(tmp_R, 'w') as tR: + print('''library(Matrix)''', file=tR) + print('''data <- read.table('{}', sep='\\t', header=FALSE)'''.format(lf_mtx_file), file=tR) + print('''sparse.data <- with(data, sparseMatrix(i=as.numeric(V1), j=as.numeric(V2), x=V3, dimnames=list(levels(V1), levels(V2))))''', file=tR) + print('''t <- writeMM(sparse.data, '{}')'''.format(mtx_file), file=tR) + print('''write.table(data.frame(rownames(sparse.data)), file='{}', col.names=FALSE, row.names=FALSE, quote=FALSE)'''.format(barcodes_file), file=tR) + print('''write.table(data.frame(colnames(sparse.data)), file='{}', col.names=FALSE, row.names=FALSE, quote=FALSE)'''.format(regions_file), file=tR) + subprocess.call(['Rscript', tmp_R]) + subprocess.call(['gzip', mtx_file]) + os.remove(windows_file) + os.remove(tmp_R) + return + +def intersect_regions(tagalign, regions): + awk_cmd = ['awk', '''BEGIN{{FS=OFS=""\\t""}} {{peakid=$1"":""$2""-""$3; gsub(""chr"","""",peakid); print $1, $2, $3, peakid}}''', regions] + intersect_cmd = ['bedtools', 'intersect', '-a', tagalign, '-b', '-', '-wa', '-wb'] + awk = subprocess.Popen(awk_cmd, stdout=subprocess.PIPE) + intersect = subprocess.Popen(intersect_cmd, stdin=awk.stdout, stdout=subprocess.PIPE) + return intersect + +def make_windows(args): + makewindows_cmd = ['bedtools', 'makewindows', '-g', args.chrom_sizes, '-w', str(args.window_size * 1000)] + filter_cmd = ['grep', '-v', '_'] + blacklist_cmd = ['bedtools', 'intersect', '-a', '-', '-b', args.blacklist_file, '-v'] + windows_file = '{}.{}kb_windows.bed'.format(args.output_prefix, args.window_size) + with open(windows_file, 'w') as f: + makewindows = subprocess.Popen(makewindows_cmd, stdout=subprocess.PIPE) + filt = subprocess.Popen(filter_cmd, stdin=makewindows.stdout, stdout=subprocess.PIPE) + subprocess.call(blacklist_cmd, stdin=filt.stdout, stdout=f) + return windows_file + +def main(args): + logging.info('Start.') + if not os.path.isdir(args.output): + os.makedirs(args.output) + args.output_prefix = os.path.join(args.output, args.name) + if not args.skip_convert: + convert_10X_bam(args) + if not args.skip_rmdup: + logging.info('Removing duplicate and mitochrondrial reads.'.format(args.minimum_reads)) + remove_duplicate_reads(args) + if not args.skip_qc: + qc_metrics(args) + if not args.skip_matrix: + logging.info('Generating tagalign and chromatin accessibility matrix.') + generate_matrix(args) + logging.info('Finish.') + return + +def process_args(): + parser = argparse.ArgumentParser(description='Use 10X output to process snATAC-seq data.') + io_group = parser.add_argument_group('I/O arguments') + io_group.add_argument('-b', '--input-bam', required=True, type=str, help='Position sorted bam from 10X output') + io_group.add_argument('-o', '--output', required=False, type=str, default=os.getcwd(), help='Output directory to store processed files') + io_group.add_argument('-n', '--name', required=True, type=str, help='Prefix for naming all output files') + + align_group = parser.add_argument_group('Alignment arguments') + align_group.add_argument('-ref', '--reference', required=True, type=str, help='Path to the BWA-indexed reference genome') + align_group.add_argument('-t', '--threads', required=False, type=int, default=8, help='Number of threads to use for alignment [8]') + align_group.add_argument('-m', '--memory', required=False, type=int, default=4, help='Maximum amount of memory (G) per thread for samtools sort [4]') + align_group.add_argument('-q', '--map-quality', required=False, type=int, default=30, help='Mapping quality score filter for samtools [30]') + + matrix_group = parser.add_argument_group('Matrix generation arguments') + matrix_group.add_argument('--shift', required=False, type=int, default=-100, help='Read shift length') + matrix_group.add_argument('--extsize', required=False, type=int, default=200, help='Read extension size') + matrix_group.add_argument('--minimum-reads', required=False, type=int, default=4000, help='Minimum number of reads for barcode inclusion') + matrix_group.add_argument('--minimum-frip', required=False, type=float, default=0, help='Minimum frip for barcode inclusion') + matrix_group.add_argument('--window-size', required=False, type=int, default=5, help='Size (kb) to use for defining windows of accessibility') + matrix_group.add_argument('--chrom-sizes', required=False, type=str, default='references/hg19.chrom.sizes', help='Chromosome sizes file from UCSC') + matrix_group.add_argument('--blacklist-file', required=False, type=str, default='references/hg19-blacklist.v1.bed', help='BED file of blacklisted regions') + matrix_group.add_argument('--promoter-file', required=False, type=str, default='references/gencode.v19.1kb_promoters.pc_transcripts.bed.gz', help='BED file of autosomal promoter regions') + + + skip_group = parser.add_argument_group('Skip steps') + skip_group.add_argument('--skip-convert', required=False, action='store_true', default=False, help='Skip bam conversion step') + skip_group.add_argument('--skip-rmdup', required=False, action='store_true', default=False, help='Skip duplicate removal step') + skip_group.add_argument('--skip-qc', required=False, action='store_true', default=False, help='Skip quality metrics step') + skip_group.add_argument('--skip-matrix', required=False, action='store_true', default=False, help='Skip matrix generation step') + return parser.parse_args() + +if __name__ == '__main__': + logging.basicConfig(format='[%(filename)s] %(asctime)s %(levelname)s: %(message)s', datefmt='%I:%M:%S', level=logging.INFO) + args = process_args() + main(args) +","Python" +"Epigenetics","kjgaulton/pipelines","T1D_snATAC_pipeline/snATAC_pipeline_CB.py",".py","16638","304","#!/usr/bin/env python3 + +import os +import sys +import gzip +import argparse +import logging +import subprocess +import pysam +import numpy as np +import pandas as pd +import scipy.sparse +from multiprocessing import Pool + +def trim_reads(args): + pair1_trim = os.path.join(args.output, os.path.basename(args.read1).split('.fastq.gz')[0] + '_val_1.fq.gz') + pair2_trim = os.path.join(args.output, os.path.basename(args.read2).split('.fastq.gz')[0] + '_val_2.fq.gz') + if os.path.isfile(pair1_trim) and os.path.isfile(pair2_trim): + return pair1_trim, pair2_trim + trim_galore_cmd = ['trim_galore', '--nextera', '--fastqc', '-q', '20', '-o', args.output, '--paired', args.read1, args.read2] + with open(os.devnull, 'w') as f: + subprocess.call(trim_galore_cmd, stderr=f, stdout=f) + return pair1_trim, pair2_trim + +def align_reads(args): + align_log = args.output_prefix + '.align.log' + aligned_bam = args.output_prefix + '.compiled.bam' + filtered_bam = args.output_prefix + '.compiled.filt.bam' + + bwa_mem_cmd = ['bwa', 'mem', '-t', str(args.threads), args.reference, args.read1, args.read2] + filter1_cmd = ['samtools', 'view', '-b', '-h', '-q', str(args.map_quality), '-F', '2048', '-'] + fixmate_cmd = ['samtools', 'fixmate', '-r', '-', '-'] + samtools_sort_cmd = ['samtools', 'sort', '-m', str(args.memory)+'G', '-@', str(args.threads), '-'] + filter2_cmd = ['samtools', 'view', '-h', '-f', '3', '-F', '4', '-F', '256', '-F', '1024', aligned_bam] + samtools_view_cmd = ['samtools', 'view', '-b', '-'] + + with open(align_log, 'w') as log, open(aligned_bam, 'w') as bam_out: + bwa_mem = subprocess.Popen(bwa_mem_cmd, stdout=subprocess.PIPE, stderr=log) + filt1 = subprocess.Popen(filter1_cmd, stdin=bwa_mem.stdout, stdout=subprocess.PIPE) + fixmate = subprocess.Popen(fixmate_cmd, stdin=filt1.stdout, stdout=subprocess.PIPE) + subprocess.call(samtools_sort_cmd, stdin=fixmate.stdout, stdout=bam_out, stderr=log) + + with open(align_log, 'a') as log, open(filtered_bam, 'w') as bam_out: + filt2 = subprocess.Popen(filter2_cmd, stderr=log, stdout=subprocess.PIPE) + view = subprocess.Popen(samtools_view_cmd, stdin=subprocess.PIPE, stdout=bam_out) + for line in filt2.stdout: + line = line.decode().rstrip('\n') + if line.startswith('@'): + try: + view.stdin.write('{}\n'.format(line).encode()) + except IOError as err: + if err.errno == errno.EPIPE or err.errno == errno.EINVAL: + break + else: + raise + continue + fields = line.split('\t') + barcode = fields[0].split(':')[0] + fields[0] = barcode + '_' + ':'.join(fields[0].split(':')[1:]) + fields.append('BX:Z:{}'.format(barcode)) + try: + view.stdin.write('{}\n'.format('\t'.join(fields)).encode()) + except IOError as err: + if err.errno == errno.EPIPE or err.errno == errno.EINVAL: + break + else: + raise + view.stdin.close() + view.wait() + return + +def remove_duplicate_reads(args): + filtered_bam = args.output_prefix + '.compiled.filt.bam' + markdup_bam = args.output_prefix + '.filt.md.bam' + rmdup_bam = args.output_prefix + '.filt.rmdup.bam' + markdup_log = args.output_prefix + '.MarkDuplicates.log' + markdup_cmd = ['java', '-Xmx24G', '-jar', args.picard, + 'MarkDuplicates', 'INPUT={}'.format(filtered_bam), 'OUTPUT={}'.format(markdup_bam), + 'VALIDATION_STRINGENCY=LENIENT', 'BARCODE_TAG=BX', 'METRICS_FILE={}'.format(markdup_log), + 'REMOVE_DUPLICATES=false'] + index_cmd = ['samtools', 'index', markdup_bam] + filter_cmd = ['samtools', 'view', '-@', str(args.threads), '-b', '-f', '3', '-F', '1024', markdup_bam] + filter_cmd.extend(['chr{}'.format(c) for c in list(map(str, range(1,23))) + ['X','Y']]) + + with open(os.devnull, 'w') as null: + subprocess.call(markdup_cmd, stderr=null, stdout=null) + subprocess.call(index_cmd) + if os.path.isfile(markdup_bam): + with open(rmdup_bam, 'w') as bam_out: + subprocess.call(filter_cmd, stdout=bam_out) + else: + raise FileNotFoundError('{} not found!'.format(markdup_bam)) + return + +def qc_metrics(args): + md_bam = args.output_prefix + '.filt.md.bam' + rmdup_bam = args.output_prefix + '.filt.rmdup.bam' + tagalign_file = args.output_prefix + '.filt.rmdup.tagAlign.gz' + + if os.path.isfile(rmdup_bam): + with gzip.open(tagalign_file, 'wt') as f: + bamfile = pysam.AlignmentFile(rmdup_bam, 'rb') + genome_size = {item['SN']:item['LN'] for item in bamfile.header['SQ']} + for read in bamfile: + if not read.is_proper_pair: + continue + barcode = read.query_name.split('_')[0] + read_chr = read.reference_name + read_start = max(1, read.reference_end - args.shift - args.extsize - 5 if read.is_reverse else read.reference_start + args.shift + 4) + read_end = min(genome_size[read_chr], read.reference_end - args.shift - 5 if read.is_reverse else read.reference_start + args.shift + args.extsize + 4) + read_qual = read.mapping_quality + if read.is_reverse: + read_orient = '-' + else: + read_orient = '+' + line_out = '\t'.join([read_chr, str(read_start), str(read_end), '{}_{}'.format(args.name,barcode), str(read_qual), read_orient]) + print(line_out, sep='\t', file=f) + bamfile.close() + else: + raise FileNotFoundError('{} not found!'.format(rmdup_bam)) + + qc_metrics = {} + chr_names = ['chr1', 'chr2', 'chr3', 'chr4', 'chr5', 'chr6', 'chr7', 'chr8', 'chr9', 'chr10', 'chr11', 'chr12', 'chr13', 'chr14', 'chr15', 'chr16', 'chr17', 'chr18', 'chr19', 'chr20', 'chr21', 'chr22', 'chrX', 'chrY'] + # mito and duplicated read percentage + if os.path.isfile(md_bam): + bamfile = pysam.AlignmentFile(md_bam, 'rb') + for read in bamfile: + barcode = '{}_{}'.format(args.name, read.query_name.split('_')[0]) + if barcode not in qc_metrics: + qc_metrics[barcode] = {} + if not read.is_duplicate: + if read.reference_name in chr_names: + qc_metrics[barcode]['unique_usable_reads'] = qc_metrics[barcode].get('unique_usable_reads', 0) + 1 + elif read.reference_name == 'chrM': + qc_metrics[barcode]['unique_mito_reads'] = qc_metrics[barcode].get('unique_mito_reads', 0) + 1 + qc_metrics[barcode]['total_sequenced_reads'] = qc_metrics[barcode].get('total_sequenced_reads', 0) + 1 + else: + qc_metrics[barcode]['duplicated_reads'] = qc_metrics[barcode].get('duplicated_reads', 0) + 1 + qc_metrics[barcode]['total_sequenced_reads'] = qc_metrics[barcode].get('total_sequenced_reads', 0) + 1 + else: + raise FileNotFoundError('{} not found!'.format(md_bam)) + qc_metrics = pd.DataFrame.from_dict(qc_metrics, orient='index').fillna(0).astype(int) + # reads in peaks + macs2_cmd = ['macs2', 'callpeak', '-t', tagalign_file, '--outdir', args.output, '-n', args.name, '-p', '.05', '--nomodel', '--keep-dup', 'all', '--shift', '0', '--extsize', '200', '-g', 'hs'] + with open(os.devnull, 'w') as f: + subprocess.call(macs2_cmd, stderr=f) + try: + os.remove(args.output_prefix + '_peaks.xls') + os.remove(args.output_prefix + '_summits.bed') + except: + pass + blacklist_cmd = subprocess.Popen(['bedtools', 'intersect', '-a' , args.output_prefix + '_peaks.narrowPeak', '-b', args.blacklist_file, '-v'], stdout=subprocess.PIPE) + intersect_cmd = subprocess.Popen(['bedtools', 'intersect', '-a', tagalign_file, '-b', '-' ], stdin=blacklist_cmd.stdout, stdout=subprocess.PIPE) + peak_counts = {bc:0 for bc in qc_metrics.index} + for line in intersect_cmd.stdout: + line = line.decode() + fields = line.rstrip().split('\t') + peak_counts[fields[3]] += 1 + qc_metrics['reads_in_peaks'] = qc_metrics.index.map(peak_counts).fillna(0).astype(int) + # reads in promoter and promoter usage + tss_counts = {bc:0 for bc in qc_metrics.index} + tss_cmd1 = subprocess.Popen(['bedtools', 'intersect', '-a', tagalign_file, '-b', args.promoter_file, '-wa'], stdout=subprocess.PIPE) + uniq = subprocess.Popen(['uniq'], stdin=tss_cmd1.stdout, stdout=subprocess.PIPE) + for line in uniq.stdout: + line = line.decode() + fields = line.rstrip().split('\t') + tss_counts[fields[3]] += 1 + + tss_used = {bc:[] for bc in qc_metrics.index} + tss_cmd2 = subprocess.Popen(['bedtools', 'intersect', '-a', tagalign_file, '-b', args.promoter_file, '-wa', '-wb'], stdout=subprocess.PIPE) + for line in tss_cmd2.stdout: + line = line.decode() + fields = line.rstrip().split('\t') + tss_used[fields[3]].append(fields[9]) + qc_metrics['reads_in_promoters'] = qc_metrics.index.map(tss_counts).fillna(0).astype(int) + qc_metrics['tss_used'] = [len(set(tss_used[bc])) for bc in qc_metrics.index] + total_prom = len(sorted(set(pd.read_table(args.promoter_file, sep='\t', header=None, names=['chr','start','end','promoter'])['promoter']))) + qc_metrics['frac_reads_in_peaks'] = qc_metrics['reads_in_peaks'].div(qc_metrics['unique_usable_reads']).replace(np.inf, 0).fillna(0) + qc_metrics['frac_reads_in_promoters'] = qc_metrics['reads_in_promoters'].div(qc_metrics['unique_usable_reads']).replace(np.inf, 0).fillna(0) + qc_metrics['frac_promoters_used'] = qc_metrics['tss_used']/total_prom + qc_metrics['frac_mito_reads'] = qc_metrics['unique_mito_reads'].div(qc_metrics['unique_usable_reads'] + qc_metrics['unique_mito_reads']).replace(np.inf, 0).fillna(0) + qc_metrics['frac_duplicated_reads'] = qc_metrics['duplicated_reads'].div(qc_metrics['total_sequenced_reads']).fillna(0) + qc_metrics.to_csv(os.path.join(args.output_prefix + '.qc_metrics.txt'), sep='\t') + return + + +def generate_matrix(args): + tagalign_file = args.output_prefix + '.filt.rmdup.tagAlign.gz' + qc_metrics = pd.read_table(args.output_prefix + '.qc_metrics.txt', sep='\t', header=0, index_col=0) + pass_barcodes = qc_metrics.loc[qc_metrics['unique_usable_reads'] >= args.minimum_reads].index + + lf_mtx_file = args.output_prefix + '.long_fmt_mtx.txt.gz' + barcodes_file = args.output_prefix + '.barcodes' + regions_file = args.output_prefix + '.regions' + mtx_file = args.output_prefix + '.mtx' + + windows_file = make_windows(args) + window_intersect = intersect_regions(tagalign_file, windows_file) + cut = subprocess.Popen(['cut', '-f', '4,10'], stdin=window_intersect.stdout, stdout=subprocess.PIPE) + sort = subprocess.Popen(['sort', '-S', '{}G'.format(args.memory * args.threads)], stdin=cut.stdout, stdout=subprocess.PIPE) + uniq = subprocess.Popen(['uniq', '-c'], stdin=sort.stdout, stdout=subprocess.PIPE) + awk = subprocess.Popen(['awk', '''BEGIN{{OFS=""\\t""}} {{print $2,$3,$1}}'''], stdin=uniq.stdout, stdout=subprocess.PIPE) + with gzip.open(lf_mtx_file, 'wt') as f: + subprocess.call(['gzip', '-c'], stdin=awk.stdout, stdout=f) + + lf_mtx = pd.read_table(lf_mtx_file, sep='\t', header=None, names=['barcode','region','count']) + lf_mtx = lf_mtx.loc[lf_mtx['barcode'].isin(pass_barcodes)] + lf_mtx.to_csv(lf_mtx_file, sep='\t', header=False, index=False, compression='gzip') + + tmp_R = args.output_prefix + '.tmp.R' + with open(tmp_R, 'w') as tR: + print('''library(Matrix)''', file=tR) + print('''data <- read.table('{}', sep='\\t', header=FALSE)'''.format(lf_mtx_file), file=tR) + print('''sparse.data <- with(data, sparseMatrix(i=as.numeric(V1), j=as.numeric(V2), x=V3, dimnames=list(levels(V1), levels(V2))))''', file=tR) + print('''t <- writeMM(sparse.data, '{}')'''.format(mtx_file), file=tR) + print('''write.table(data.frame(rownames(sparse.data)), file='{}', col.names=FALSE, row.names=FALSE, quote=FALSE)'''.format(barcodes_file), file=tR) + print('''write.table(data.frame(colnames(sparse.data)), file='{}', col.names=FALSE, row.names=FALSE, quote=FALSE)'''.format(regions_file), file=tR) + subprocess.call(['Rscript', tmp_R]) + subprocess.call(['gzip', mtx_file]) + os.remove(windows_file) + os.remove(tmp_R) + return + + +def intersect_regions(tagalign, regions): + awk_cmd = ['awk', '''BEGIN{{FS=OFS=""\\t""}} {{peakid=$1"":""$2""-""$3; gsub(""chr"","""",peakid); print $1, $2, $3, peakid}}''', regions] + intersect_cmd = ['bedtools', 'intersect', '-a', tagalign, '-b', '-', '-wa', '-wb'] + awk = subprocess.Popen(awk_cmd, stdout=subprocess.PIPE) + intersect = subprocess.Popen(intersect_cmd, stdin=awk.stdout, stdout=subprocess.PIPE) + return intersect + +def make_windows(args): + makewindows_cmd = ['bedtools', 'makewindows', '-g', args.chrom_sizes, '-w', str(args.window_size * 1000)] + filter_cmd = ['grep', '-v', '_'] + blacklist_cmd = ['bedtools', 'intersect', '-a', '-', '-b', args.blacklist_file, '-v'] + windows_file = '{}.{}kb_windows.bed'.format(args.output_prefix, args.window_size) + with open(windows_file, 'w') as f: + makewindows = subprocess.Popen(makewindows_cmd, stdout=subprocess.PIPE) + filt = subprocess.Popen(filter_cmd, stdin=makewindows.stdout, stdout=subprocess.PIPE) + subprocess.call(blacklist_cmd, stdin=filt.stdout, stdout=f) + return windows_file + +def main(args): + logging.info('Start.') + if not os.path.isdir(args.output): + os.makedirs(args.output) + args.output_prefix = os.path.join(args.output, args.name) + if not args.skip_trim: + logging.info('Trimming adapters using trim_galore.') + args.read1, args.read2 = trim_reads(args) + if not args.skip_align: + logging.info('Aligning reads using BWA mem with [{}] processors.'.format(args.threads)) + logging.info('Piping output to samtools using [{}] Gb of memory.'.format(args.memory)) + align_reads(args) + if not args.skip_rmdup: + logging.info('Removing duplicate and mitochrondrial reads.'.format(args.minimum_reads)) + remove_duplicate_reads(args) + if not args.skip_qc: + qc_metrics(args) + if not args.skip_matrix: + logging.info('Generating tagalign and chromatin accessibility matrix.') + generate_matrix(args) + logging.info('Finish.') + return + +def process_args(): + parser = argparse.ArgumentParser(description='Process combinatorial barcoding snATAC-seq data.') + io_group = parser.add_argument_group('I/O arguments') + io_group.add_argument('-r1', '--read1', required=True, type=str, help='Paired-end reads file 1') + io_group.add_argument('-r2', '--read2', required=True, type=str, help='Paired-end reads file 2') + io_group.add_argument('-o', '--output', required=False, type=str, default=os.getcwd(), help='Output directory to store processed files') + io_group.add_argument('-n', '--name', required=True, type=str, help='Prefix for naming all output files') + + align_group = parser.add_argument_group('Alignment arguments') + align_group.add_argument('-ref', '--reference', required=True, type=str, help='Path to the BWA-indexed reference genome') + align_group.add_argument('-t', '--threads', required=False, type=int, default=8, help='Number of threads to use for alignment [8]') + align_group.add_argument('-m', '--memory', required=False, type=int, default=4, help='Maximum amount of memory (G) per thread for samtools sort [4]') + align_group.add_argument('-q', '--map_quality', required=False, type=int, default=30, help='Mapping quality score filter for samtools [30]') + + dup_group = parser.add_argument_group('Remove duplicates arguments') + dup_group.add_argument('--picard', required=True, type=str, help='Path to picard.jar') + + matrix_group = parser.add_argument_group('Matrix generation arguments') + matrix_group.add_argument('--shift', required=False, type=int, default=-100, help='Read shift size') + matrix_group.add_argument('--extsize', required=False, type=int, default=200, help='Read extension size') + matrix_group.add_argument('--minimum-reads', required=False, type=int, default=500, help='Minimum number of reads for barcode inclusion') + matrix_group.add_argument('--window-size', required=False, type=int, default=5, help='Size (kb) to use for defining windows of accessibility') + matrix_group.add_argument('--chrom-sizes', required=False, type=str, default='references/hg19.chrom.sizes', help='Chromosome sizes file from UCSC') + matrix_group.add_argument('--blacklist-file', required=False, type=str, default='references/hg19-blacklist.v1.bed.gz', help='BED file of blacklisted regions') + matrix_group.add_argument('--promoter-file', required=False, type=str, default='references/gencode.v19.1kb_promoters.pc_transcripts.bed.gz', help='BED file of autosomal promoter regions') + + skip_group = parser.add_argument_group('Skip steps') + skip_group.add_argument('--skip-trim', required=False, action='store_true', default=False, help='Skip adapter trimming step') + skip_group.add_argument('--skip-align', required=False, action='store_true', default=False, help='Skip read alignment step') + skip_group.add_argument('--skip-rmdup', required=False, action='store_true', default=False, help='Skip duplicate removal step') + skip_group.add_argument('--skip-qc', required=False, action='store_true', default=False, help='Skip QC metrics calculation step') + skip_group.add_argument('--skip-matrix', required=False, action='store_true', default=False, help='Skip matrix generation step') + return parser.parse_args() + +if __name__ == '__main__': + logging.basicConfig(format='[%(filename)s] %(asctime)s %(levelname)s: %(message)s', datefmt='%I:%M:%S', level=logging.INFO) + args = process_args() + main(args) +","Python" +"Epigenetics","kjgaulton/pipelines","variant_annotation_matrix/vam.py",".py","26231","884","#!/usr/bin/env python3 +#------------------------------------------------------------------------------# +# vam.py # +#------------------------------------------------------------------------------# + +# Construct a matrix from a variants file and a .bed annotation file + + + + +#-------------------------------- Imports -------------------------------------# + +import argparse +from operator import attrgetter +from multiprocessing import Pool +import gzip + + + + +#----------------------- Class Bootstrapping Function -------------------------# + +def bootstrap(cls): + cls.bootstrap() + return(cls) + + + + +#----------------------------- Class Definitions ------------------------------# + +@bootstrap +class Chromosome(): + '''A chromosome''' + + @classmethod + def bootstrap(cls): + for comparison_string in ( + '__eq__', + '__ne__', + '__lt__', + '__le__', + '__gt__', + '__ge__' + ): + integer_comparison = getattr(int, comparison_string) + def chromosome_comparison( + self, + chr, + integer_comparison=integer_comparison + ): + return integer_comparison(self.int, chr.int) + setattr(cls, comparison_string, chromosome_comparison) + + def __init__(self, chromosome_name): + self.char = ( + str(chromosome_name) + .casefold() + .replace('chr', '') + .replace('23', 'x') + .replace('24', 'y') + .replace('25', 'm') + ) + try: + self.int = int(self.char) + if self.int not in range(1,26): + self.raise_chromosome_name_error(chromosome_name) + except ValueError: + try: + self.int = {'x': 23, 'y': 24, 'm': 25}[self.char] + except KeyError: + self.raise_chromosome_name_error(chromosome_name) + self.variants = [] + self.annotations = {} + self.variants_have_been_sorted = False + self.annotations_have_been_sorted = False + + def __int__(self): + return self.int + + def sort_variants(self): + self.variants.sort(key=attrgetter('position')) + self.variants_have_been_sorted = True + + def sort_annotations(self): + for name, interval_list in self.annotations.items(): + interval_list.sort() + self.annotations_have_been_sorted = True + + def annotate_variants(self, annotation_subset): + if ( + self.variants_have_been_sorted + and + self.annotations_have_been_sorted + ): + for variant in self.variants: + for annotation_name, interval_list in self.annotations.items(): + empty_interval_count = 0 + for interval in interval_list: + if interval[1] < variant.position: + empty_interval_count += 1 + elif interval[0] > variant.position: + break + else: + if annotation_subset: + if annotation_name in annotation_subset: + variant.annotations.add(annotation_name) + else: + variant.annotations.add(annotation_name) + break + for x in range(empty_interval_count): + interval_list.pop(0) + else: + raise Exception( + 'Variants and annotations must be sorted before variants can ' + 'be annotated' + ) + + def raise_chromosome_name_error(self, chromosome_name): + raise SystemExit( + 'Error: {} is not a valid chromosome name. Valid names include ' + 'integers 1-25 or characters XxYyMm and may or not be prefixed ' + 'with chr, CHR, Chr, etc.'.format(str(chromosome_name)) + ) + + + + +class HeaderErrors(): + '''Errors for header parsing''' + + def raise_no_segnumber(self): + raise SystemExit( + 'Error: The -f flag was used, but no SEGNUMBER column was ' + 'found in the variants file header.' + ) + + def raise_column_index_out_of_range(self, column_string, index, ncol): + raise SystemExit( + ( + 'Error: The index provided to --{} was {}, but ' + 'there are only {} columns in the variants file.' + ).format( + column_string, + index + 1, + ncol + ) + ) + + def raise_ambiguity(self, column_string): + raise SystemExit( + ( + 'Error: No {} column was specified and the variants file ' + 'header is ambiguous.' + ).format( + column_string + ) + ) + + def raise_bad_column_header(self, column_string): + raise SystemExit( + ( + 'Error: The string provided to --{} is not in the variants ' + 'file header.' + ).format( + column_string + ) + ) + + def raise_possible_delimiter_error(self): + raise SystemExit( + ( + 'Error: There doesn\'t seem to be enough information in the ' + 'variants file. Did you forget to set the delimiter with -d ?' + ) + ) + + + + +class VariantsHeader(): + '''The header of an input variants file''' + + errors = HeaderErrors() + + def __init__( + self, + header_string, + delimiter, + chromosome_arg, + position_arg, + fine_mapping_arg + ): + self.tuple = tuple( + header_string.replace( + '\n', '' + ).replace( + '\\t', '\t' + ).split( + delimiter + ) + ) + if len(self.tuple) < 2: + self.errors.raise_possible_delimiter_error() + if fine_mapping_arg: + try: + self.segnumber_index = self.tuple.index('SEGNUMBER') + except ValueError: + self.errors.raise_no_segnumber() + for column_string, arg in ( + ('chromosome', chromosome_arg), + ('position', position_arg) + ): + self.get_index(column_string, arg) + self.sorting_attrs = tuple( + attr + for + attr + in + ('segnumber', 'chromosome', 'position') + if + hasattr(self, '{}_index'.format(attr)) + ) + + def get_index(self, column_string, arg): + attr = '{}_index'.format(column_string) + try: + index = int(arg) - 1 + if index > len(self.tuple): + self.errors.raise_column_index_out_of_range( + column_string, + index, + len(self.tuple) + ) + else: + setattr(self, attr, index) + except ValueError: + try: + setattr(self, attr, self.tuple.index(arg) - 1) + except ValueError: + self.errors.raise_bad_column_header(column_string) + except TypeError: + for index in range(len(self.tuple)): + prefix = self.tuple[index].casefold() + if ( + ( + column_string[0:3] == prefix[0:3] + ) + and + ( + column_string[3:].startswith(prefix[3:]) + ) + ): + try: + getattr(self, '{}_index'.format(column_string)) + self.errors.raise_ambiguity(column_string) + except AttributeError: + setattr(self, attr, index) + try: + getattr(self, '{}_index'.format(column_string)) + except AttributeError: + self.errors.raise_ambiguity(column_string) + + + + +class Variant(): + '''A variant''' + + raise_possible_delimiter_error = ( + HeaderErrors().raise_possible_delimiter_error + ) + + def __init__(self, tup, header): + self.tuple = tup + if len(self.tuple) < 2: + self.raise_possible_delimiter_error() + self.chromosome = Chromosome( + self.tuple[getattr(header, 'chromosome_index')] + ).int + for attr in ( + attr for attr in header.sorting_attrs if attr != 'chromosome' + ): + try: + setattr( + self, + attr, + int( + self.tuple[getattr(header, '{}_index'.format(attr))] + ) + ) + except ValueError: + raise SystemExit( + ( + 'Error: The {} of a variant with the following tuple ' + 'representation could not be parsed as an integer:\n{}' + ).format(attr, repr(self.tuple)) + ) + self.annotations = set() + + + + +class VariantDistributor(): + ''' + A container for variants that can distribute them over the chromosomes. + ''' + + def __init__(self, variant_generator): + self.generator = variant_generator + + def distribute(self, genome): + for variant in self.generator: + try: + genome[variant.chromosome].variants.append(variant) + genome[variant.chromosome].variants_have_been_sorted = False + except KeyError: + genome[variant.chromosome] = Chromosome(variant.chromosome) + genome[variant.chromosome].variants.append(variant) + genome[variant.chromosome].variants_have_been_sorted = False + + + + +class AnnotationDistributor(): + ''' + A container for annotations that can distribute them over the chromosomes. + ''' + + def __init__(self, annotation_generator): + self.generator = annotation_generator + + def distribute(self, genome): + for annotation in self.generator: + try: + ( + genome[Chromosome(annotation[0]).int] + .annotations[annotation[3]] + .append((int(annotation[1]), int(annotation[2]))) + ) + ( + genome[Chromosome(annotation[0]).int] + .annotations_have_been_sorted + ) = ( + False + ) + except KeyError: + try: + ( + genome[Chromosome(annotation[0]).int] + .annotations[annotation[3]] + ) = ( + [(int(annotation[1]), int(annotation[2]))] + ) + ( + genome[Chromosome(annotation[0]).int] + .annotations_have_been_sorted + ) = ( + False + ) + except KeyError: + pass + except (ValueError, IndexError): + raise SystemExit( + ( + 'Error: The annotation file does not appear to be in ' + 'headerless BED format at a line with the following ' + 'tuple representation:\n{}' + ).format(repr(annotation)) + ) + + + + +class MultiprocessingHandler(): + ''' + A device to perform multiprocessing tasks + ''' + + def __init__(self, genome): + self.genome = genome + + def sort_variants(self): + keys = [] + enumerated_variant_positions = [] + for key, chromosome in self.genome.items(): + keys.append(key) + enumerated_variant_positions.append( + tuple( + (elem, n) + for + (n, elem) + in + enumerate( + variant.position + for + variant + in + chromosome.variants + ) + ) + ) + with Pool(processes=args.processes) as pool: + enumerated_variant_positions = pool.map( + sorted, + enumerated_variant_positions + ) + for index in range(len(keys)): + self.genome[keys[index]].variants = tuple( + self.genome[keys[index]].variants[i] + for + i + in + ( + n + for + (elem, n) + in + enumerated_variant_positions[index] + ) + ) + self.genome[keys[index]].variants_have_been_sorted = True + + def sort_annotations(self): + keys = [] + interval_lists = [] + for key, chromosome in self.genome.items(): + for name, interval_list in chromosome.annotations.items(): + keys.append((key, name)) + interval_lists.append(list(interval_list)) + with Pool(processes=args.processes) as pool: + interval_lists = pool.map( + sorted, + interval_lists, + chunksize = min(1, int(len(interval_lists) / args.processes)) + ) + for index in range(len(keys)): + self.genome[keys[index][0]].annotations[keys[index][1]] = ( + list(interval_lists[index]) + ) + self.genome[keys[index][0]].annotations_have_been_sorted = True + + def annotate_variants(self, annotation_subset): + keys = [] + argument_list = [] + for key, chromosome in self.genome.items(): + if ( + chromosome.variants_have_been_sorted + and + chromosome.annotations_have_been_sorted + ): + keys.append(key) + argument_list.append( + ( + tuple( + variant.position for variant in chromosome.variants + ), + dict(chromosome.annotations), + annotation_subset + ) + ) + else: + raise Exception( + 'Variants and annotations must be sorted before variants ' + 'can be annotated' + ) + + with Pool(processes=args.processes) as pool: + annotations_per_variant = pool.starmap( + annotate_variants, + argument_list + ) + for index in range(len(keys)): + for i in range(len(self.genome[keys[index]].variants)): + ( + self + .genome[keys[index]] + .variants[i] + .annotations + ) = annotations_per_variant[index][i] + + + + + +#--------------------------- Function Definitions -----------------------------# + +### Convenience functions for parsing arguments + +# Construct annotation susbset +def get_annotation_subset(params_filename): + try: + with open(params_filename, 'r') as params_file: + f.readline() + return { + line.split(' ')[0].replace('_ln', '') + for + line + in + params_file + if + float(line.split(' ')[2]) > 0 + } + except TypeError: + print('Using all annotations since no --params argument was given.') + return None + + + + +# Handle a .gz extension on the output path +def output_handle_gz_extension(output_file_path): + return ''.join( + ( + output_file_path[0:-3], + (output_file_path[-3:] != '.gz') * output_file_path[-3:] + ) + ) + + + + +### Loading data from the input files + +# Load variants +def load_variants(args): + with open(args.variants, 'r') as variants_file: + if args.add_header: + variants_header = VariantsHeader( + args.add_header, + args.delimiter, + args.chromosome, + args.position, + args.fine_mapping + ) + elif args.replace_header: + variants_header = VariantsHeader( + args.replace_header, + args.delimiter, + args.chromosome, + args.position, + args.fine_mapping + ) + variants_file.readline() + else: + variants_header = VariantsHeader( + variants_file.readline(), + args.delimiter, + args.chromosome, + args.position, + args.fine_mapping + ) + variant_distributor = VariantDistributor( + Variant( + tup, + variants_header + ) + for + tup + in + { + tuple( + line.replace('\n', '').split(args.delimiter) + ) + for + line + in + variants_file + } + ) + return variants_header, variant_distributor + + + + +# Load annotations +def load_annotations(args): + with open(args.annotations, 'r') as annotations_file: + annotation_distributor = AnnotationDistributor( + annotation + for + annotation + in + { + tuple( + line.replace('\n', '').split() + ) + for + line + in + annotations_file + } + ) + return annotation_distributor + + + + +### Multiprocessing function + +# Annotate variants +def annotate_variants(variant_positions, annotations, annotation_subset): + annotations_per_variant = [] + for variant_position in variant_positions: + annotations_per_variant.append(set()) + for annotation_name, interval_list in annotations.items(): + empty_interval_count = 0 + for interval in interval_list: + if interval[1] < variant_position: + empty_interval_count += 1 + elif interval[0] > variant_position: + break + else: + if annotation_subset: + if annotation_name in annotation_subset: + annotations_per_variant[-1].add(annotation_name) + else: + annotations_per_variant[-1].add(annotation_name) + break + for x in range(empty_interval_count): + interval_list.pop(0) + return annotations_per_variant + + + + +### Generating and writing the matrix + +# Generate lines of the matrix +def generate_matrix(variants_header, genome): + chromosomes = tuple( + sorted( + chromosome + for + key, chromosome + in + genome.items() + ) + ) + annotations = tuple( + sorted( + { + annotation_name + for + chromosome + in + chromosomes + for + annotation_name + in + chromosome.annotations.keys() + } + ) + ) + yield variants_header.tuple + annotations + for chromosome in chromosomes: + for variant in chromosome.variants: + yield ( + variant.tuple + + + tuple( + str( + int( + annotation + in + variant.annotations + ) + ) + for + annotation + in + annotations + ) + ) + + + + +# Write to output +def write_output(args, variants_header, matrix_generator): + if args.fine_mapping: + header = next(matrix_generator) + matrix_generator = ( + row + for + row + in + ( + ( + header, + ) + + + tuple( + sorted( + matrix_generator, + key = lambda row: int( + row[variants_header.segnumber_index] + ) + ) + ) + ) + ) + output_data = ( + '\n'.join( + ( + args.delimiter.join( + row + ) + for + row + in + matrix_generator + ) + ) + + + '\n' + ) + if args.compress_output: + with gzip.open('{}.gz'.format(args.output), 'wb') as f: + f.write(bytes(output_data, 'utf8')) + else: + with open(args.output, 'w') as f: + f.write(output_data) + + + + +# Main +def main(args): + annotation_subset = get_annotation_subset(args.params) + genome = {} + print('Loading variants') + variants_header, variant_distributor = load_variants(args) + print('Distributing variants') + variant_distributor.distribute(genome) + print('Loading annotations') + annotation_distributor = load_annotations(args) + print('Distributing annotations') + annotation_distributor.distribute(genome) + print('Annotating variants') + if args.processes > 1: + multiprocessing_handler = MultiprocessingHandler(genome) + multiprocessing_handler.sort_variants() + multiprocessing_handler.sort_annotations() + multiprocessing_handler.annotate_variants(annotation_subset) + else: + for key, chromosome in genome.items(): + chromosome.sort_variants() + chromosome.sort_annotations() + chromosome.annotate_variants(annotation_subset) + print('Preparing output matrix') + matrix_generator = generate_matrix(variants_header, genome) + print('Writing to file') + write_output(args, variants_header, matrix_generator) + print('Done') + + + + +# Parse arguments +def parse_arguments(): + parser = argparse.ArgumentParser( + description=( + 'Construct a binary variant-annotation matrix from a table of ' + 'input variants and a .bed file defining annotations.' + ), + epilog=( + 'The ( --chromosome / --position ) argument is not required if ' + 'the corresponding column is identified in the variants file ' + 'header by a (case-insensitive) prefix of (""chromosome"" / ' + '""position"") at least three characters long. Examples: ""chr"" ""POS"" ' + '""ChRoM"" ""positio""' + ) + ) + + io_group = parser.add_argument_group('I/O arguments') + io_group.add_argument( + '-v', + '--variants', + required=True, + help='path to variants file' + ) + io_group.add_argument( + '-a', + '--annotations', + required=True, + help='path to .bed file giving annotation data' + ) + io_group.add_argument( + '-o', + '--output', + required=True, + help='path to output file' + ) + + multiprocessing_group = parser.add_argument_group( + 'multiprocessing arguments' + ) + multiprocessing_group.add_argument( + '-p', + '--processes', + type=int, + default=1, + choices=range(1, 26), + help='number of processes to launch' + ) + + formatting_group = parser.add_argument_group('formatting arguments') + formatting_group.add_argument( + '-d', + '--delimiter', + default='\t', + help='delimiter for input file, if not tab' + ) + formatting_group.add_argument( + '--chromosome', + help=( + 'provide the (1-based) index of the column giving the chromosome ' + 'of each variant in the variants file, or a string giving its ' + 'header' + ) + ) + formatting_group.add_argument( + '--position', + help=( + 'provide the (1-based) index of the column giving the position ' + 'of each variant in the variants file, or a string giving its ' + 'header' + ) + ) + provide_header_group = formatting_group.add_mutually_exclusive_group() + provide_header_group.add_argument( + '--add-header', + help=( + 'Provide a string to be used as the header for a variants file ' + 'that does not have one' + ) + ) + provide_header_group.add_argument( + '--replace-header', + help=( + 'Provide a string to be used as a replacement for the variants ' + 'file\'s header' + ) + ) + + output_compression_group = parser.add_argument_group( + 'output compression arguments' + ) + output_compression_group.add_argument( + '-z', + '--compress-output', + action='store_true', + help='compress output file with gzip' + ) + + fgwas_group = parser.add_argument_group( + 'optional FGWAS-specific arguments' + ) + fgwas_group.add_argument( + '-f', + '--fine-mapping', + action='store_true', + help='produce output sorted by SEGNUMBER for fine mapping' + ) + fgwas_group.add_argument( + '--params', + help='path to .params file contatining a subset of annotations to use' + ) + + args = parser.parse_args() + if args.compress_output: + args.output = output_handle_gz_extension(args.output) + return args + + + + +#-------------------------------- Execute -------------------------------------# + +if __name__ == '__main__': + args = parse_arguments() + main(args) +","Python" +"Epigenetics","kjgaulton/pipelines","single-cell_ATAC-seq/bin/sc-ATAC.pipeline.py",".py","7701","163","#!/usr/bin/env python3 + +import os +import sys +import argparse +import subprocess +import traceback +import logging + + +def extract_barcodes(args): + extract_dir = os.path.join(args.output, 'extract-bc') + if not os.path.isdir(extract_dir): + try: + os.mkdir(extract_dir) + except FileExistsError: + pass + extract_p1_cmd = [ + 'python3', 'sc-ATAC.extract-bc.py', + '-i1', args.index1, '-i2', args.index2, + '-r', args.paired1, '-N', str(args.ambiguous_bases), + '-o', extract_dir, '-n', args.name + '.R1'] + extract_p2_cmd = [ + 'python3', 'sc-ATAC.extract-bc.py', + '-i1', args.index1, '-i2', args.index2, + '-r', args.paired2, '-N', str(args.ambiguous_bases), + '-o', extract_dir, '-n', args.name + '.R2'] + extract_p1_log = os.path.join(extract_dir, '.'.join([args.name, 'R1', 'extract-bc.log'])) + extract_p2_log = os.path.join(extract_dir, '.'.join([args.name, 'R2', 'extract-bc.log'])) + with open(extract_p1_log, 'w') as log1, open(extract_p2_log, 'w') as log2: + logging.info('--Extracting barcodes for reads 1 file [{}]'.format(args.paired1)) + subprocess.call(extract_p1_cmd, stderr=log1) + logging.info('--Extracting barcodes for reads 2 file [{}]'.format(args.paired2)) + subprocess.call(extract_p2_cmd, stderr=log2) + extract_p1 = os.path.join(extract_dir, args.name + '.R1.extract-bc.fastq.gz') + extract_p2 = os.path.join(extract_dir, args.name + '.R2.extract-bc.fastq.gz') + return extract_p1, extract_p2 + +def correct_barcodes(args): + correct_dir = os.path.join(args.output, 'correct-bc') + if not os.path.isdir(correct_dir): + try: + os.mkdir(correct_dir) + except FileExistsError: + pass + correct_p1_cmd = [ + 'python3', 'sc-ATAC.correct-bc.py', + '-o', correct_dir, '-n', args.name + '.R1', + '-r', args.extract1, '-a', args.adapters, + '--n_mismatches', str(args.mismatches), + '--closest_distance', str(args.closest_distance)] + correct_p2_cmd = [ + 'python3', 'sc-ATAC.correct-bc.py', + '-o', correct_dir, '-n', args.name + '.R2', + '-r', args.extract2, '-a', args.adapters, + '--n_mismatches', str(args.mismatches), + '--closest_distance', str(args.closest_distance)] + correct_p1_log = os.path.join(correct_dir, '.'.join([args.name, 'R1', 'correct-bc.log'])) + correct_p2_log = os.path.join(correct_dir, '.'.join([args.name, 'R2', 'correct-bc.log'])) + with open(correct_p1_log, 'w') as log1, open(correct_p2_log, 'w') as log2: + logging.info('--Correcting barcodes for reads 1 file [{}]'.format(args.extract1)) + subprocess.call(correct_p1_cmd, stderr=log1) + logging.info('--Correcting barcodes for reads 2 file [{}]'.format(args.extract2)) + subprocess.call(correct_p2_cmd, stderr=log2) + correct1 = os.path.join(correct_dir, args.name + '.R1.correct-bc.fastq.gz') + correct2 = os.path.join(correct_dir, args.name + '.R2.correct-bc.fastq.gz') + return correct1, correct2 + +def align_reads(args): + align_dir = os.path.join(args.output, 'aligned_bams') + if not os.path.isdir(align_dir): + try: + os.mkdir(align_dir) + except FileExistsError: + pass + align_cmd = [ + 'python3' , 'sc-ATAC.align_reads.py', + '-o', align_dir, '-n', args.name, + '-p1', args.correct1, '-p2', args.correct2, + '-t', str(args.threads), '-m', str(args.memory), + '-mapq', str(args.map_quality), '-ref', args.reference + ] + align_log = os.path.join(align_dir, args.name + '.align.log') + with open(align_log, 'w') as log: + subprocess.call(align_cmd, stderr=log) + compiled_bam = os.path.join(align_dir, args.name + '.compiled.bam') + return compiled_bam + +def split_cells(args): + split_dir = os.path.join(args.output, 'split_cells') + if not os.path.isdir(split_dir): + try: + os.mkdir(split_dir) + except FileExistsError: + pass + split_cmd = [ + 'python3', 'sc-ATAC.split_cells.py', + '-i', args.compiled_bam, '-o', split_dir, + '-n', args.name, '-m', str(args.memory), + '-min', str(args.min_reads), '-mark_dup', args.picard_mark_dup + ] + split_log = os.path.join(split_dir, args.name + '.split+rmdup.log') + with open(split_log, 'w') as log: + subprocess.call(split_cmd, stderr=log) + return + +def main(args): + logging.info('Starting up.') + if not os.path.isdir(args.output): + try: + os.mkdir(args.output) + except FileExistsError: + pass + except Exception: + pass + try: + logging.info('Extracting barcodes from index fastq files and inserting them into read names.') + args.extract1, args.extract2 = extract_barcodes(args) + if os.path.exists(args.extract1) and os.path.exists(args.extract2): + logging.info('Correcting barcodes using a maximum of [{}] mismatches and minimum distance of [{}].'.format(args.mismatches, args.closest_distance)) + args.correct1, args.correct2 = correct_barcodes(args) + else: + logging.error('Check if [{}] and [{}] exist.'.format(args.extract1, args.extract2)) + if os.path.exists(args.correct1) and os.path.exists(args.correct2): + logging.info('Aligning reads with BWA-MEM using [{}] threads, [{}]G memory and removing duplicates with Picard MarkDuplicates.'.format(args.threads, args.memory)) + args.compiled_bam = align_reads(args) + else: + logging.error('Check if [{}] and [{}] exist.'.format(args.correct1, args.correct2)) + if os.path.exists(args.compiled_bam): + split_cells(args) + else: + logging.error('Check if [{}] exists.'.format(args.compiled_bam)) + except Exception as e: + logging.error(e) + traceback.print_exc(file=sys.stderr) + sys.exit(1) + logging.info('Finishing up.') + return + +def process_args(): + parser = argparse.ArgumentParser(description='Pipeline for single cell ATAC-seq analysis') + parser.add_argument('-i1', '--index1', required=True, type=str, help='Path to index1 fastq file') + parser.add_argument('-i2', '--index2', required=True, type=str, help='Path to index2 fastq file') + parser.add_argument('-p1', '--paired1', required=True, type=str, help='Path to paired-end reads 1 fastq file') + parser.add_argument('-p2', '--paired2', required=True, type=str, help='Path to paired-end reads 2 fastq file') + parser.add_argument('-o', '--output', required=True, type=str, help='Output directory to store processed files') + parser.add_argument('-n', '--name', required=True, type=str, help='Prefix for naming all output files') + parser.add_argument('-a', '--adapters', required=False, type=str, default='../illumina_adapters/', help='Path to directory that contains Illumina adapters') + parser.add_argument('-t', '--threads', required=False, type=int, default=8, help='Maximum amount of threads to be used [8]') + parser.add_argument('-mem', '--memory', required=False, type=int, default=4, help='Maximum amount of memory to be used per thread [4]') + parser.add_argument('-ref', '--reference', required=True, type=str, help='Reference genome for aligning reads') + parser.add_argument('-mark_dup', '--picard_mark_dup', required=False, type=str, default='../picard/MarkDuplicates.jar', help='Path to picard\'s MarkDuplicates.jar tool') + parser.add_argument('--ambiguous_bases', required=False, type=int, default=12, help='Maximum number of ambiguous bases N per barcode [12].') + parser.add_argument('--mismatches', required=False, type=int, default=3, help='Maximum number of mismatches [3].') + parser.add_argument('--closest_distance', required=False, type=int, default=1, help='Minimum edit distance that secondary match needs to be away from the primary match [1].') + parser.add_argument('--min_reads', required=False, type=int, default=500, help='Minimum number of reads for output barcodes [3]') + parser.add_argument('--map_quality', required=False, type=int, default=10, help='Mapping quality score filter for samtools [10]') + return parser.parse_args() + +args = process_args() +logging.basicConfig(format='[%(filename)s] %(asctime)s %(levelname)s: %(message)s', datefmt='%I:%M:%S', level=logging.DEBUG) +main(args) +","Python" +"Epigenetics","kjgaulton/pipelines","single-cell_ATAC-seq/bin/sc-ATAC.make_matrix.py",".py","3611","89","#!/usr/bin/env python3 + +import os +import sys +import glob +import argparse +import subprocess +import logging +import traceback +import tempfile +import pandas as pd +from multiprocessing import Pool + +def make_windows(args): + if args.chrom_sizes is not None: + makewindows_cmd = ['bedtools', 'makewindows', '-g', args.chrom_sizes, '-w', str(200)] + gzip_cmd = ['gzip', '-c'] + windows_200bp = os.path.join(args.output, 'hg19.200bp_windows.bed.gz') + with open(windows_200bp, 'w') as f: + mkwindows = subprocess.Popen(makewindows_cmd, stdout=subprocess.PIPE) + subprocess.call(gzip_cmd, stdin=mkwindows.stdout, stdout=f) + return windows_200bp + +def genome_coverage(args, bam): + barcode = os.path.basename(bam).split(args.name+'.')[1].split('.rmdup.bam')[0] + genomecov_cmd = ['bedtools', 'genomecov', '-ibam', bam, '-pc', '-bg'] + bed_out = os.path.join(args.output, '.'.join([args.name, barcode, 'PE_coverage.bed'])) + with open(bed_out, 'w') as f: + genomecov = subprocess.call(genomecov_cmd, stdout=f) + return bed_out + +def make_matrix(args): + bed_frame = pd.read_csv(args.bed, sep='\t', header=None) + bed_frame.columns = ['chrom', 'start', 'end'] + for bar in args.barcodes: + bar_bed = os.path.join(args.output, '.'.join([args.name, bar, 'PE_coverage.bed'])) + intersect_cmd = ['bedtools', 'intersect', '-a', args.bed, '-b', bar_bed, '-wao'] + cut_cmd = ['cut', '-f', '7'] + tmp = tempfile.TemporaryFile('w') + intersect = subprocess.Popen(intersect_cmd, stdout=subprocess.PIPE) + subprocess.call(cut_cmd, stdin=intersect.stdout, stdout=tmp) + tmp.seek(0) + print(tmp.read()) + tmp.close() + return + +def main(args): + logging.info('Starting up.') + try: + if not os.path.isdir(args.output): + try: + os.mkdir(args.output) + except FileExistsError: + pass + if args.bed is None: + logging.info('BED file unspecified, defaulting to 200 bp windows.') + args.bed = make_windows(args) + logging.info('Proceed to calculate genome coverage of input bams using [{}] threads.'.format(args.threads)) + rmdup_bams = glob.glob(os.path.join(args.input, '*.rmdup.bam')) + args.barcodes = [os.path.basename(bam).split(args.name+'.')[1].split('.rmdup.bam')[0] for bam in rmdup_bams] + args_list = [(args, bam) for bam in rmdup_bams] + #pool = Pool(processes=(args.threads)) + #cov_files = pool.starmap(genome_coverage, args_list) + #pool.close() + #pool.join() + make_matrix(args) + except Exception as e: + logging.error(e) + traceback.print_exc(file=sys.stderr) + sys.exit(1) + logging.info('Finishing up.') + return + +def process_args(): + parser = argparse.ArgumentParser(description='Create a matrix for read coverage for each sample based on 200 bp windows.') + parser.add_argument('-i', '--input', required=True, type=str, help='Path to input directory containing rmdup bams') + parser.add_argument('-o', '--output', required=True, type=str, help='Output directory to store processed files') + parser.add_argument('-n', '--name', required=True, type=str, help='Prefix for naming all output files') + parser.add_argument('-b', '--bed', required=False, type=str, help='BED file that will be used to define regions [200bp windows]') + parser.add_argument('-chrom', '--chrom_sizes', required=False, type=str, default='../misc/hg19.chrom.sizes', help='Path to chromosome size files [../misc/hg19.chrom.sizes]') + parser.add_argument('-t', '--threads', required=False, type=int, default=16, help='Number of threads for calculating genome coverage') + + + return parser.parse_args() + +args = process_args() +logging.basicConfig(format='[%(filename)s] %(asctime)s %(levelname)s: %(message)s', datefmt='%I:%M:%S', level=logging.DEBUG) +main(args) +","Python" +"Epigenetics","kjgaulton/pipelines","single-cell_ATAC-seq/bin/sc-ATAC.extract-bc.py",".py","4078","89","#!/usr/bin/env python3 + +import gzip +import bz2 +import argparse +import os +import logging + +def process_barcode(args, i1_file, i2_file, reads_file): + all_files = {'i1_file': i1_file, 'i2_file': i2_file, 'reads_file': reads_file} + output_file = os.path.join(args.output, args.name + '.extract-bc.fastq.gz') + + total_reads = 0 + skipped_reads = 0 + processed_reads = 0 + + with gzip.open(output_file, 'wb') as out: + while True: + full, names, reads, pluses, qualities = [{} for i in range(5)] + for k,f in all_files.items(): + full[k] = f.readline().strip()[1:].decode() + names[k] = full[k].split(' ')[0] + reads[k] = f.readline().strip().decode() + pluses[k] = f.readline().strip().decode() + qualities[k] = f.readline().strip().decode() + if full[k] == reads[k] == pluses[k] == qualities[k] == '': + # EOF + return total_reads, skipped_reads, processed_reads + if '' in names.values(): + raise ValueError('You have a blank read name!') + if len(list(set(names.values()))) > 1: + raise ValueError('Your read names are not the same!') + + r7 = reads['i1_file'][:8] + i7 = reads['i1_file'][-8:] + r5 = reads['i2_file'][:8] + i5 = reads['i2_file'][-8:] + barcode = r7 + i7 + r5 + i5 + total_reads += 1 + + if barcode.count('N') >= args.N_ambiguous_bases: + logging.warning('Barcode \""{}\"" from read \""{}\"" has more than {} N\'s, skipping...'.format(barcode, names['reads_file'], args.N_ambiguous_bases)) + skipped_reads += 1 + continue + + out.write('@{}:{}\n'.format(barcode, full['reads_file']).encode()) + out.write('{}\n'.format(reads['reads_file']).encode()) + out.write('+\n'.encode()) + out.write('{}\n'.format(qualities['reads_file']).encode()) + processed_reads += 1 + return total_reads, skipped_reads, processed_reads + +def main(args): + logging.info('Starting up.') + logging.info('Reading in index and read files.') + + read_files = [args.index1, args.index2, args.reads] + if all(f.endswith('.gz') for f in read_files): + with gzip.open(args.index1) as i1_file, gzip.open(args.index2) as i2_file, gzip.open(args.reads) as reads_file: + total_reads, skipped_reads, processed_reads = process_barcode(args, i1_file, i2_file, reads_file) + elif all(f.endswith('.bz2') for f in read_files): + with bz2.BZ2File(args.index1) as i1_file, bz2.BZ2File(args.index2) as i2_file, bz2.BZ2File(args.reads) as reads_file: + total_reads, skipped_reads, processed_reads = process_barcode(args, i1_file, i2_file, reads_file) + elif all(f.endswith('.fastq') or f.endswith('.fq') for f in read_files): + with open(args.index1) as i1_file, open(args.index2) as i2_file, open(args.reads) as reads_file: + total_reads, skipped_reads, processed_reads = process_barcode(args, i1_file, i2_file, reads_file) + else: + raise OSError('All file extensions must be the same. Check if all of your input files end with either: .gz, .bz2, .fastq, or .fq.') + + logging.info('Finishing up.') + logging.info('Total raw reads: {}'.format(total_reads)) + logging.info('Skipped barcodes (Ambiguous): {}'.format(skipped_reads)) + logging.info('Processed barcodes (Ambiguous): {}'.format(processed_reads)) + return + +def process_args(): + parser = argparse.ArgumentParser(description='Extract barcodes from a single-cell ATAC-seq experiment.') + parser.add_argument('-o', '--output', required=True, type=str, help='Output directory to store processed files') + parser.add_argument('-n', '--name', required=True, type=str, help='Prefix for naming all output files') + parser.add_argument('-i1', '--index1', required=True, type=str, help='Path to index 1 fastq file.') + parser.add_argument('-i2', '--index2', required=True, type=str, help='Path to index 2 fastq file.') + parser.add_argument('-r', '--reads', required=True, type=str, help='Path to reads fastq file.') + parser.add_argument('-N', '--N_ambiguous_bases', required=False, type=int, default=12, help='Maximum number of ambiguous bases (N).') + return parser.parse_args() + +args = process_args() +logging.basicConfig(format='[%(filename)s] %(asctime)s %(levelname)s: %(message)s', datefmt='%I:%M:%S', level=logging.DEBUG) +main(args) +","Python" +"Epigenetics","kjgaulton/pipelines","single-cell_ATAC-seq/bin/sc-ATAC.split_cells.py",".py","4953","117","#!/usr/bin/env python3 + +import os +import sys +import argparse +import tempfile +import subprocess +import logging +import traceback + + +def split_bam(args): + samtools_view_cmd = ['samtools', 'view', '-h', args.input_bam] + bam_in = subprocess.Popen(samtools_view_cmd, stdout=subprocess.PIPE) + header, cells = [], {} + for line in bam_in.stdout: + line = line.decode().rstrip('\n') + if line.startswith(('@HD', '@SQ', '@PG')): + header.append(line) + elif line.startswith(('A', 'C', 'G', 'T')): + barcode = line.split(':')[0] + cells[barcode] = cells.get(barcode, []) + [line] + else: + raise SystemExit('Check if your input bam file is formatted correctly. The bam file needs a header. Each read should start with the barcode.') + return header, cells + +def filter_barcodes(args, cells): + barcode_counts = args.prefix + '.barcode_counts.txt' + barcodes = {b:len(cells[b]) for b in cells.keys()} + with open(barcode_counts, 'w') as f: + print('Barcode'.ljust(32), 'Count', sep='\t', file=f) + for barcode, count in barcodes.items(): + print(barcode, count, sep='\t', file=f) + filtered = [b for b,c in barcodes.items() if c >= args.min_reads] + return filtered + +def output_cells(args, header, cells, pass_filter): + reads_before_rmdup = 0 + for bar in pass_filter: + tmp = tempfile.TemporaryFile('w+b') + for line in header: + tmp.write('{}\n'.format(line).encode()) + for line in cells[bar]: + tmp.write('{}\n'.format(line).encode()) + tmp.seek(0) + cell_bam = '.'.join([args.prefix, bar, 'filt.bam']) + samtools_sort_cmd = ['samtools', 'sort', '-m', '{}G'.format(args.memory), '-O', 'bam', '-'] + with open(cell_bam, 'w') as out_bam: + subprocess.call(samtools_sort_cmd, stdin=tmp, stdout=out_bam) + tmp.seek(0) + reads_before_rmdup += sum(1 for _ in tmp) + tmp.close() + return reads_before_rmdup / 2 + +def remove_duplicates(args, barcodes): + reads_after_rmdup = 0 + for bar in barcodes: + input_bam = '.'.join([args.prefix, bar, 'filt.bam']) + output_bam = '.'.join([args.prefix, bar, 'rmdup.bam']) + metrics_file = '.'.join([args.prefix, bar, 'picard_rmdup_metrics.txt']) + rmdup_cmd = [ + 'java', '-Xmx{}G'.format(args.memory), + '-jar', args.picard_mark_dup, + 'INPUT={}'.format(input_bam), + 'OUTPUT={}'.format(output_bam), + 'REMOVE_DUPLICATES=true', + 'VALIDATION_STRINGENCY=LENIENT', + 'METRICS_FILE={}'.format(metrics_file) + ] + with open(os.devnull) as f: + subprocess.call(rmdup_cmd, stderr=f) + count_reads_cmd = ['samtools', 'view', output_bam] + p = subprocess.Popen(count_reads_cmd, stdout=subprocess.PIPE) + reads_after_rmdup += sum(1 for _ in p.stdout) + return reads_after_rmdup / 2 + +def main(args): + logging.info('Starting up.') + try: + logging.info('Read in combined bam file [{}]'.format(args.input_bam)) + header, cells = split_bam(args) + logging.info('Filtering barcodes for [{}] minimum reads.'.format(args.min_reads)) + pass_filter = filter_barcodes(args, cells) + logging.info('Outputting bams for cells that pass the filter.') + before_reads = output_cells(args, header, cells, pass_filter) + logging.info('Removing duplicate reads using picard.') + after_reads = remove_duplicates(args, pass_filter) + pass_rate = float(len(pass_filter))/len(cells.keys()) + dup_rate = (before_reads - after_reads) / float(before_reads) * 100 + logging.info('Finishing up.') + logging.info('Total barcodes: {}'.format(len(cells.keys()))) + logging.info('Barcodes passing filter: {}'.format(len(pass_filter))) + logging.info('Percentage barcodes passing filter: {0:.2f}%'.format(pass_rate)) + logging.info('Pairs before rmdup: {}'.format(before_reads)) + logging.info('Pairs after rmdup: {}'.format(after_reads)) + logging.info('Est. PCR duplication rate: {0:.2f}%'.format(dup_rate)) + except Exception as e: + logging.error(e) + traceback.print_exc(file=sys.stderr) + sys.exit(1) + return + +def process_args(): + parser = argparse.ArgumentParser(description='Split compiled bam, collect metrics, and remove duplicate read pairs.') + parser.add_argument('-i', '--input_bam', required=True, type=str, help='Path to combined.bam file') + parser.add_argument('-o', '--output', required=True, type=str, help='Output directory to store processed files') + parser.add_argument('-n', '--name', required=True, type=str, help='Prefix for naming all output files') + parser.add_argument('-m', '--memory', required=False, type=int, default=4, help='Maximum memory for samtools sort and picard MarkDuplicates.jar') + parser.add_argument('-min', '--min_reads', required=False, type=int, default=500, help='Minimum number of reads for output cells') + parser.add_argument('-mark_dup', '--picard_mark_dup', required=False, type=str, default='Picard/MarkDuplicates.jar', help='Path to picard\'s MarkDuplicates.jar tool') + return parser.parse_args() + +args = process_args() +args.prefix = os.path.join(args.output, args.name) +logging.basicConfig(format='[%(filename)s] %(asctime)s %(levelname)s: %(message)s', datefmt='%I:%M:%S', level=logging.DEBUG) +main(args) +","Python" +"Epigenetics","kjgaulton/pipelines","single-cell_ATAC-seq/bin/sc-ATAC.correct-bc.py",".py","6918","139","#!/usr/bin/env python3 + +import gzip +import argparse +import os +import logging +import Levenshtein + +def load_adapters(args): + adapter_files = [os.path.join(args.adapters, f) for f in ['r7_ATAC', 'i7_ATAC', 'i5_ATAC', 'r5_ATAC']] + for adapter_file in adapter_files: + if not os.path.exists(adapter_file): + raise Exception('Missing [{}]. Check if Illumina adapter files [r7_ATAC, i7_ATAC, i5_ATAC, r5_ATAC] exist or are properly named!'.format(os.path.basename(adapter_file))) + r7_adapters = open(adapter_files[0]).read().splitlines() + i7_adapters = open(adapter_files[1]).read().splitlines() + i5_adapters = open(adapter_files[2]).read().splitlines() + r5_adapters = open(adapter_files[3]).read().splitlines() + return r7_adapters, i7_adapters, i5_adapters, r5_adapters + +def process_mismatch(r7_mismatch, r7_adapters): + edit_distances = {adap:Levenshtein.distance(r7_mismatch, adap) for adap in r7_adapters} + min_adap = min(edit_distances, key=edit_distances.get) + min_dist = edit_distances[min_adap] + del edit_distances[min_adap] + min_adap2 = min(edit_distances, key=edit_distances.get) + min_dist2 = edit_distances[min_adap2] + return min_adap, min_dist, min_adap2, min_dist2 + +def correct_barcodes(args, r7_adapters, i7_adapters, i5_adapters, r5_adapters): + total_reads = 0 + perfect_reads = 0 + skipped_reads = 0 + processed_reads = 0 + + corrected_output = os.path.join(args.output, args.name + '.correct-bc.fastq.gz') + + with gzip.open(args.reads) as reads_file, gzip.open(corrected_output, 'wb') as corr_out: + lines = reads_file.read().splitlines() + for i in range(0, len(lines), 4): + read_info = ':'.join(lines[i].decode()[1:].split(':')[1:]) + name = lines[i].decode()[1:].split()[0] + read = lines[i+1].decode() + plus = lines[i+2].decode() + qual = lines[i+3].decode() + barcode = name.split(':')[0] + r7,i7,i5,r5 = barcode[:8], barcode[8:16], barcode[16:24], barcode[24:] + total_reads += 1 + if r7 in r7_adapters and i7 in i7_adapters and i5 in i5_adapters and r5 in r5_adapters: + perfect_reads += 1 + if r7 not in r7_adapters: + min_adap, min_dist, min_adap2, min_dist2 = process_mismatch(r7, r7_adapters) + if min_dist <= args.n_mismatches and min_dist2 - min_dist > args.closest_distance: + r7 = min_adap + elif min_dist > args.n_mismatches: + logging.warning('r7 [{}], closest match [{}], edit distance [{}] is greater than maximum n_mismatches [{}]'.format(r7, min_adap, min_dist, args.n_mismatches)) + skipped_reads += 1 + continue + else: + logging.warning('r7 [{}], closest match [{}], minimum edit distance [{}] is too close to secondary edit distance [{}]'.format(r7, min_adap, min_dist, min_dist2)) + skipped_reads += 1 + continue + + if i7 not in i7_adapters: + min_adap, min_dist, min_adap2, min_dist2 = process_mismatch(i7, i7_adapters) + if min_dist <= args.n_mismatches and min_dist2 - min_dist > args.closest_distance: + i7 = min_adap + elif min_dist > args.n_mismatches: + logging.warning('i7 [{}], closest match [{}], edit distance [{}] is greater than maximum n_mismatches [{}]'.format(i7, min_adap, min_dist, args.n_mismatches)) + skipped_reads += 1 + continue + else: + logging.warning('i7 [{}], closest match [{}], minimum edit distance [{}] is too close to secondary edit distance [{}]'.format(i7, min_adap, min_dist, min_dist2)) + skipped_reads += 1 + continue + + if i5 not in i5_adapters: + min_adap, min_dist, min_adap2, min_dist2 = process_mismatch(i5, i5_adapters) + if min_dist <= args.n_mismatches and min_dist2 - min_dist > args.closest_distance: + i5 = min_adap + elif min_dist > args.n_mismatches: + logging.warning('i5 [{}], closest match [{}], edit distance [{}] is greater than maximum n_mismatches [{}]'.format(i5, min_adap, min_dist, args.n_mismatches)) + skipped_reads += 1 + continue + else: + logging.warning('i5 [{}], closest match [{}], minimum edit distance [{}] is too close to secondary edit distance [{}]'.format(i5, min_adap, min_dist, min_dist2)) + skipped_reads += 1 + continue + + if r5 not in r5_adapters: + min_adap, min_dist, min_adap2, min_dist2 = process_mismatch(r5, r5_adapters) + if min_dist <= args.n_mismatches and min_dist2 - min_dist > args.closest_distance: + r5 = min_adap + elif min_dist > args.n_mismatches: + logging.warning('r5 [{}], closest match [{}], edit distance [{}] is greater than maximum n_mismatches [{}]'.format(r5, min_adap, min_dist, args.n_mismatches)) + skipped_reads += 1 + continue + else: + logging.warning('r5 [{}], closest match [{}], minimum edit distance [{}] is too close to secondary edit distance [{}]'.format(r5, min_adap, min_dist, min_dist2)) + skipped_reads += 1 + continue + + new_barcode = r7 + i7 + i5 + r5 + corr_out.write('@{}:{}\n'.format(new_barcode, read_info).encode()) + corr_out.write('{}\n'.format(read).encode()) + corr_out.write('{}\n'.format(plus).encode()) + corr_out.write('{}\n'.format(qual).encode()) + processed_reads += 1 + + return total_reads, perfect_reads, skipped_reads, processed_reads + +def main(args): + logging.info('Starting up.') + logging.info('Reading in barcoded reads file.') + + r7_adapters, i7_adapters, i5_adapters, r5_adapters = load_adapters(args) + logging.info('Correcting barcoded reads using a maximum edit distance of [{}].'.format(args.n_mismatches)) + total_reads, perfect_reads, skipped_reads, processed_reads = correct_barcodes(args, r7_adapters, i7_adapters, i5_adapters, r5_adapters) + logging.info('Finishing up.') + logging.info('Processed barcodes (Ambiguous): {}'.format(total_reads)) + logging.info('Perfect barcodes (Min. distance): {}'.format(perfect_reads)) + logging.info('Skipped barcodes (Min. distance): {}'.format(skipped_reads)) + logging.info('Processed barcodes (Min. distance): {}'.format(processed_reads)) + return + +def process_args(): + parser = argparse.ArgumentParser(description='Allow for mismatches for barcodes in a single-cell ATAC-seq experiment.') + parser.add_argument('-o', '--output', required=True, type=str, help='Output directory to store processed files') + parser.add_argument('-n', '--name', required=True, type=str, help='Prefix for naming all output files') + parser.add_argument('-r', '--reads', required=True, type=str, help='Path to barcoded reads fastq file.') + parser.add_argument('-a', '--adapters', required=False, type=str, default='illumina_adapters/', help='Path to directory that contains Illumina adapter sequences.') + parser.add_argument('--n_mismatches', required=False, type=int, default=3, help='Maximum number of mismatches.') + parser.add_argument('--closest_distance', required=False, type=int, default=1, help='Minimum edit distance that secondary match needs to be away from the primary match.') + return parser.parse_args() + + +args = process_args() +logging.basicConfig(format='[%(filename)s] %(asctime)s %(levelname)s: %(message)s', datefmt='%I:%M:%S', level=logging.DEBUG) +main(args) +","Python" +"Epigenetics","kjgaulton/pipelines","single-cell_ATAC-seq/bin/sc-ATAC.align_reads.py",".py","3747","72","#!/usr/bin/env python3 + +import os +import argparse +import logging +import subprocess + + +def trim_reads(args): + trim_galore_cmd = ['trim_galore', '--nextera', '--fastqc', '-q', '20', '-o', args.output, '--paired', args.paired1, args.paired2] + with open(os.devnull, 'w') as f: + subprocess.call(trim_galore_cmd, stderr=f, stdout=f) + pair1_trim = os.path.join(args.output, os.path.basename(args.paired1).split('.fastq.gz')[0] + '_val_1.fq.gz') + pair2_trim = os.path.join(args.output, os.path.basename(args.paired2).split('.fastq.gz')[0] + '_val_2.fq.gz') + return pair1_trim, pair2_trim + +def align_reads(args): + output_prefix = os.path.join(args.output, args.name) + + bwa_mem_cmd = ['bwa', 'mem', '-t', str(args.threads), args.reference, args.paired1, args.paired2] + quality_filt_cmd = ['samtools', 'view', '-h', '-f', '2', '-q', str(args.map_quality), '-@', '1', '-'] + mito_filt_cmd = ['grep', '-v', 'chrM'] + samtools_sort_cmd = ['samtools', 'sort', '-m', str(args.memory)+'G', '-@', str(args.threads), '-'] + + align_log = output_prefix + '.align.log' + aligned_bam = output_prefix + '.compiled.bam' + + with open(align_log, 'w') as log, open(aligned_bam, 'w') as bam_out: + bwa_mem = subprocess.Popen(bwa_mem_cmd, stdout=subprocess.PIPE, stderr=log) + qual_filt = subprocess.Popen(quality_filt_cmd, stdin=bwa_mem.stdout, stdout=subprocess.PIPE, stderr=log) + mito_filt = subprocess.Popen(mito_filt_cmd, stdin=qual_filt.stdout, stdout=subprocess.PIPE, stderr=log) + subprocess.call(samtools_sort_cmd, stdin=mito_filt.stdout, stdout=bam_out, stderr=log) + + count_reads_cmd = ['samtools', 'view', aligned_bam] + p = subprocess.Popen(count_reads_cmd, stdout=subprocess.PIPE) + aligned_reads = sum(1 for _ in p.stdout) + return aligned_reads / 2 + +def main(args): + logging.info('Starting up.') + + if not args.skip_trim: + logging.info('Trimming adapters using trim_galore.') + args.paired1, args.paired2 = trim_reads(args) + + if not args.skip_align: + logging.info('Aligning reads using BWA mem with [{}] processors.'.format(args.threads)) + logging.info('Piping output to samtools using [{}] Gb of memory.'.format(args.memory)) + aligned_reads = align_reads(args) + logging.info('Finishing up.') + if aligned_reads is not None: + logging.info('Aligned pairs: {}'.format(aligned_reads)) + return + +def process_args(): + parser = argparse.ArgumentParser(description='Align all reads to the reference genome and make compiled bam.') + parser.add_argument('-o', '--output', required=True, type=str, help='Output directory to store processed files') + parser.add_argument('-n', '--name', required=True, type=str, help='Prefix for naming all output files') + parser.add_argument('-p1', '--paired1', required=True, type=str, help='Paired reads file 1') + parser.add_argument('-p2', '--paired2', required=True, type=str, help='Paired reads file 2') + parser.add_argument('-t', '--threads', required=False, type=int, default=8, help='Number of threads to use for alignment') + parser.add_argument('-m', '--memory', required=False, type=int, default=4, help='Maximum amount of memory to use for samtools sort') + parser.add_argument('-mapq', '--map_quality', required=False, type=int, default=10, help='Mapping quality score filter for samtools') + parser.add_argument('-ref', '--reference', required=True, type=str, help='Path to the reference genome') + parser.add_argument('--skip_trim', required=False, action='store_true', default=False, help='Skip adapter trimming step') + parser.add_argument('--skip_align', required=False, action='store_true', default=False, help='Skip aligning reads step') + return parser.parse_args() + +args = process_args() +logging.basicConfig(format='[%(filename)s] %(asctime)s %(levelname)s: %(message)s', datefmt='%I:%M:%S', level=logging.DEBUG) +main(args) +","Python" +"Epigenetics","kjgaulton/pipelines","reweight_variants/update_bayes_factor.py",".py","1986","51","#!/usr/bin/env python3 + +import os +import argparse +import pandas as pd +import numpy as np + +def process_args(): + parser = argparse.ArgumentParser(description='Update PPA for fine-mapping studies using .ridgeparams file') + parser.add_argument('-r', '--ridgeparams', required=True, type=str, help='Path to ridgeparams output file from fgwas') + parser.add_argument('-f', '--finemap', required=True, type=str, help='Path to annotated fine-mapping file') + return parser.parse_args() + +def load_ridgeparams(args): + states = {} + with open(args.finemap) as f: + all_states = [x.split('\t')[5] for x in f.read().splitlines()] + states = {x:0 for x in all_states} + with open(args.ridgeparams) as f: + lines = f.read().splitlines()[1:-1] + for line in lines: + state, parameter = line.split(' ') + states[state] = float(parameter) + return states + +def load_finemap(args, states): + finemap_master = pd.read_table(args.finemap, header=None) + finemap_master.columns=['chrom', 'pos', 'rsid', 'locus', 'lnbf', 'state'] + finemap_master['parameter'] = [states[x] for x in finemap_master['state']] + loci = sorted(set(finemap_master['locus'])) + return finemap_master, loci + +def update_loci(finemap_master, locus): + finemap_subset = finemap_master[finemap_master['locus'] == locus] + finemap_subset['new_lnbf'] = np.log(np.exp(finemap_subset['lnbf']) * (np.exp(finemap_subset['parameter'])/sum(np.exp(finemap_subset['parameter'])))) + finemap_subset['new_ppa'] = np.exp(finemap_subset['new_lnbf'])/sum(np.exp(finemap_subset['new_lnbf'])) + finemap_subset = finemap_subset.sort_values('new_ppa', ascending=False) + return finemap_subset + +def main(args): + finemap_name = os.path.basename(args.finemap).split('.')[0] + states = load_ridgeparams(args) + finemap_master, loci = load_finemap(args, states) + for locus in loci: + finemap_subset = update_loci(finemap_master, locus) + finemap_subset.to_csv('.'.join([locus, finemap_name, 'updated_PPA.tab']), sep='\t', index=False) + return + +args = process_args() +main(args) +","Python" +"Epigenetics","kjgaulton/pipelines","reweight_variants/convert_log_to_ln.py",".py","497","15","#!/usr/bin/env python3 + +import sys +import numpy as np +import pandas as pd + +metabo = pd.read_csv(sys.argv[1], sep='\t', header=None) +metabo.columns = ['chrom', 'position', 'rsid', 'locus', 'logbf', 'state'] +base10 = np.array([10 for x in metabo['logbf']]) +metabo['lnbf'] = np.log(np.power(base10, metabo['logbf'])) + +out_cols = ['chrom', 'position', 'rsid', 'locus', 'lnbf', 'state'] +metabo_out = metabo[out_cols] +metabo_out.to_csv('metabo.islet_ATAC.lnbf.bed', sep='\t', header=False, index=False) +","Python" +"Epigenetics","kjgaulton/pipelines","lung_snATAC_pipeline/lung_snATAC.ipynb",".ipynb","11958","267","{ + ""cells"": [ + { + ""cell_type"": ""code"", + ""execution_count"": null, + ""metadata"": { + ""scrolled"": true + }, + ""outputs"": [], + ""source"": [ + ""import os\n"", + ""import numpy as np\n"", + ""import pandas as pd\n"", + ""import scipy.io\n"", + ""\n"", + ""# plotting\n"", + ""import matplotlib.pyplot as plt\n"", + ""import seaborn as sns\n"", + ""\n"", + ""# single cell\n"", + ""import scanpy.api as sc\n"", + ""from anndata import AnnData\n"", + ""\n"", + ""# etc\n"", + ""%load_ext rpy2.ipython"" + ] + }, + { + ""cell_type"": ""markdown"", + ""metadata"": {}, + ""source"": [ + ""### Regress out read depth per experiment"" + ] + }, + { + ""cell_type"": ""code"", + ""execution_count"": null, + ""metadata"": {}, + ""outputs"": [], + ""source"": [ + ""wd = 'lung_snATAC/'\n"", + ""\n"", + ""adatas = {}\n"", + ""samples = ['D062','D088','D110','D150','D032','D032-2','D046','D139','D122','D175','D231']\n"", + ""\n"", + ""# dictionary naming 5kb windows genome-wide based on overlap with gencode v19 gene TSS\n"", + ""promoters = pd.read_csv(os.path.join('references', 'gencode.v19.5kb_windows.promoter_names.txt.gz'), sep='\\t', header=None, index_col=0, names=['prom'])\n"", + ""promoter_names = promoters['prom'].to_dict() \n"", + ""\n"", + ""# cells from low quality and doublet clusters were identified through iterative clustering\n"", + ""low_frip = open(os.path.join(wd, 'lung_snATAC.merged_samples.lowfrip')).read().splitlines()\n"", + ""low_reads = open(os.path.join(wd, 'lung_snATAC.merged_samples.lowreads')).read().splitlines()\n"", + ""doublets = open(os.path.join(wd, 'lung_snATAC.merged_samples.doublets')).read().splitlines()\n"", + ""\n"", + ""qc_metrics = pd.read_csv(os.path.join(wd, 'lung_snATAC.merged_samples.qc_metrics.txt'), sep='\\t', header=0, index_col=0)\n"", + ""hvw = open(os.path.join(wd,'lung_snATAC.merged_samples.hvw')).read().splitlines()\n"", + ""\n"", + ""for sample in samples:\n"", + "" sp = scipy.io.mmread(os.path.join(wd, sample, '{}.mtx.gz'.format(sample))).tocsr()\n"", + "" regions = open(os.path.join(wd, sample, '{}.regions'.format(sample))).read().splitlines()\n"", + "" barcodes = open(os.path.join(wd, sample, '{}.barcodes'.format(sample))).read().splitlines()\n"", + "" adatas[sample] = AnnData(sp, {'obs_names':barcodes}, {'var_names':regions})\n"", + "" adatas[sample].var.index = [promoter_names[b] if b in promoter_names else b for b in adatas[sample].var.index]\n"", + "" adatas[sample].var_names_make_unique(join='.')\n"", + "" \n"", + "" adatas[sample] = adatas[sample][~adatas[sample].obs.index.isin(low_frip + low_reads + doublets),:].copy()\n"", + "" adatas[sample].obs = adatas[sample].obs.join(qc_metrics, how='inner')\n"", + "" adatas[sample].obs['experiment'] = [i.split('_')[0] for i in adatas[sample].obs.index]\n"", + "" raw = adatas[sample].copy()\n"", + "" \n"", + "" sc.pp.normalize_per_cell(adatas[sample], counts_per_cell_after=1e4)\n"", + "" adatas[sample] = adatas[sample][:, adatas[sample].var.index.isin(hvgs)]\n"", + "" sc.pp.log1p(adatas[sample])\n"", + "" adatas[sample].obs['log_usable_counts'] = np.log(raw[:, raw.var.index.isin(hvgs)].X.sum(axis=1).A1)\n"", + "" sc.pp.regress_out(adatas[sample], ['log_usable_counts'])\n"", + "" adatas[sample].write(os.path.join(wd, '{}.norm.h5ad'.format(sample)))\n"", + "" \n"", + "" sc.pp.normalize_per_cell(raw, counts_per_cell_after=1e4)\n"", + "" sc.pp.log1p(raw)\n"", + "" raw.write(os.path.join(wd, '{}.raw.h5ad'.format(sample)))\n"" + ] + }, + { + ""cell_type"": ""markdown"", + ""metadata"": {}, + ""source"": [ + ""### Merge files from all samples"" + ] + }, + { + ""cell_type"": ""code"", + ""execution_count"": null, + ""metadata"": {}, + ""outputs"": [], + ""source"": [ + ""adatas = {}\n"", + ""adatas_raw = {}\n"", + ""samples = ['D062','D088','D150','D110', 'D032','D032-2','D046','D139','D122','D175','D231']\n"", + ""\n"", + ""for sample in samples:\n"", + "" adatas[sample] = sc.read_h5ad(os.path.join(wd, '{}.norm.h5ad'.format(sample)))\n"", + "" adatas_raw[sample] = sc.read_h5ad(os.path.join(wd, '{}.raw.h5ad'.format(sample)))\n"", + "" \n"", + ""adata_norm = AnnData.concatenate(adatas['D062'], adatas['D088'], adatas['D110'], adatas['D150'],\n"", + "" adatas['D032'], adatas['D032-2'], adatas['D046'], adatas['D139'],\n"", + "" adatas['D122'], adatas['D175'], adatas['D231'],\n"", + "" batch_key='norm', index_unique=None)\n"", + ""adata_norm_raw = AnnData.concatenate(adatas_raw['D062'], adatas_raw['D088'], adatas_raw['D110'], adatas_raw['D150'],\n"", + "" adatas_raw['D032'], adatas_raw['D032-2'], adatas_raw['D046'], adatas_raw['D139'],\n"", + "" adatas_raw['D122'], adatas_raw['D175'], adatas_raw['D231'],\n"", + "" batch_key='norm', index_unique=None)\n"", + ""adata_norm.raw = adata_norm_raw.copy()\n"", + ""\n"", + ""sc.pp.scale(adata_norm)\n"", + ""sc.tl.pca(adata_norm, zero_center=True, svd_solver='arpack', random_state=0)\n"", + ""pc = pd.DataFrame(adata_norm.obsm['X_pca'], columns=['PC{}'.format(i) for i in range(1,51)], index=adata_norm.obs.index)\n"", + ""metadata = pd.read_csv(os.path.join(wd, 'lung_snATAC.merged_samples.metadata.txt'), sep='\\t', header=0, index_col=0)\n"", + ""metadata = metadata.loc[pc.index]"" + ] + }, + { + ""cell_type"": ""markdown"", + ""metadata"": {}, + ""source"": [ + ""### Run Harmony (rpy2) to correct for batch effects"" + ] + }, + { + ""cell_type"": ""code"", + ""execution_count"": null, + ""metadata"": {}, + ""outputs"": [], + ""source"": [ + ""%%R -i pc -i metadata -o harmonized\n"", + ""library(harmony)\n"", + ""library(magrittr)\n"", + ""\n"", + ""# run Harmony on the PCs\n"", + ""harmonized <- HarmonyMatrix(pc, metadata, c('experiment','sex'), do_pca=FALSE)\n"", + ""harmonized <- data.frame(harmonized)"" + ] + }, + { + ""cell_type"": ""markdown"", + ""metadata"": {}, + ""source"": [ + ""### Plot cluster based on corrected components"" + ] + }, + { + ""cell_type"": ""code"", + ""execution_count"": null, + ""metadata"": { + ""scrolled"": false + }, + ""outputs"": [], + ""source"": [ + ""adata_norm.obsm['X_pca'] = harmonized.values\n"", + ""sc.pp.neighbors(adata_norm, n_neighbors=30, method='umap', metric='cosine', random_state=0, n_pcs=50)\n"", + ""sc.tl.leiden(adata_norm, resolution=1.5, random_state=0)\n"", + ""sc.tl.umap(adata_norm, min_dist=0.3, random_state=0)\n"", + ""\n"", + ""sc.settings.set_figure_params(dpi=100)\n"", + ""sc.pl.umap(adata_norm, color=['leiden'], size=1, alpha=.5)\n"", + ""sc.pl.umap(adata_norm, color=['experiment'], size=1, alpha=.5)\n"", + ""\n"", + ""# plot quality metrics\n"", + ""sc.pl.umap(adata_norm, color=['log_usable_counts'], size=1, color_map='Blues')\n"", + ""sc.pl.umap(adata_norm, color=['frac_reads_in_peaks','frac_reads_in_promoters','frac_promoters_used'], cmap='Reds', size=1, legend_loc='on data')\n"", + ""\n"", + ""# 5kb windows overlapping marker promoters \n"", + ""sc.pl.umap(adata_norm, color=['SLC11A1','CD247','MS4A1'], size=9, color_map='Blues', frameon=True, use_raw=True)\n"", + ""sc.pl.umap(adata_norm, color=['SFTPC','EDN3','MCIDAS'], size=9, color_map='Blues', frameon=True, use_raw=True)\n"", + ""sc.pl.umap(adata_norm, color=['VWF','GBP4','PROX1'], size=9, color_map='Blues', frameon=True, use_raw=True)\n"", + ""sc.pl.umap(adata_norm, color=['WNT2','MYOCD','GJC1'], size=9, color_map='Blues', frameon=True, use_raw=True)\n"" + ] + }, + { + ""cell_type"": ""code"", + ""execution_count"": null, + ""metadata"": { + ""scrolled"": false + }, + ""outputs"": [], + ""source"": [ + ""# More 5kb windows overlapping marker promoters \n"", + ""sc.pl.umap(adata_norm, color=['C1QA','C1QB','C1QC'], size=4, color_map='Blues', frameon=True, use_raw=True)\n"", + ""sc.pl.umap(adata_norm, color=['CD3E','CD8A','BCL11B'], size=4, color_map='Blues', frameon=True, use_raw=True)\n"", + ""sc.pl.umap(adata_norm, color=['NCR1','SH2D1B','IFNG'], size=4, color_map='Blues', frameon=True, use_raw=True)\n"", + ""sc.pl.umap(adata_norm, color=['CD79A','CD19','MS4A1'], size=4, color_map='Blues', frameon=True, use_raw=True)\n"", + ""sc.pl.umap(adata_norm, color=['SERTM1','EDN3','CTNND2'], size=4, color_map='Blues', frameon=True, use_raw=True)\n"", + ""sc.pl.umap(adata_norm, color=['SFTPB','SFTPA1','ACOXL'], size=4, color_map='Blues', frameon=True, use_raw=True)\n"", + ""sc.pl.umap(adata_norm, color=['SOX2','TEKT4','MCIDAS'], size=4, color_map='Blues', frameon=True, use_raw=True)\n"", + ""sc.pl.umap(adata_norm, color=['CLEC14A','EGFL7','CDH5'], size=4, color_map='Blues', frameon=True, use_raw=True)\n"", + ""sc.pl.umap(adata_norm, color=['VWF','PTPRB','CD93'], size=4, color_map='Blues', frameon=True, use_raw=True)\n"", + ""sc.pl.umap(adata_norm, color=['ART1','APOB','EML1'], size=4, color_map='Blues', frameon=True, use_raw=True)\n"", + ""sc.pl.umap(adata_norm, color=['PROX1','PDE1A','HOXD8'], size=4, color_map='Blues', frameon=True, use_raw=True)\n"", + ""sc.pl.umap(adata_norm, color=['WNT2','MEOX2','SCN7A'], size=4, color_map='Blues', frameon=True, use_raw=True)\n"", + ""sc.pl.umap(adata_norm, color=['DNAI2','GJC1','FOXS1'], size=4, color_map='Blues', frameon=True, use_raw=True)\n"", + ""sc.pl.umap(adata_norm, color=['DES','MYOCD','PRELP'], size=4, color_map='Blues', frameon=True, use_raw=True)\n"", + ""sc.pl.umap(adata_norm, color=['CD34','MFAP5','FBLN2'], size=4, color_map='Blues', frameon=True, use_raw=True)\n"" + ] + }, + { + ""cell_type"": ""markdown"", + ""metadata"": {}, + ""source"": [ + ""### Subclustering at high resolution to identify potential doublet subclusters"" + ] + }, + { + ""cell_type"": ""code"", + ""execution_count"": null, + ""metadata"": {}, + ""outputs"": [], + ""source"": [ + ""subset_cluster = ['0']\n"", + ""sc.tl.louvain(adata_norm, restrict_to=('leiden',subset_cluster), resolution=3, random_state=0, key_added='subset')\n"", + ""sc.pl.umap(adata_norm, color=['subset'], size=9)\n"", + ""\n"", + ""fig, ax1 = plt.subplots(1,1,figsize=(5,5))\n"", + ""subset = adata_norm.obs.join(pd.DataFrame(adata_norm.obsm['X_umap'], index=adata_norm.obs.index, columns=['UMAP1','UMAP2']), how='inner')\n"", + ""subset = subset.loc[subset['leiden'].isin(subset_cluster)]\n"", + ""for s in sorted(set(subset['subset'])):\n"", + "" ax1.scatter(subset.loc[subset['subset']==s, 'UMAP1'], subset.loc[subset['subset']==s, 'UMAP2'], alpha=1, s=4, label=s)\n"", + ""ax1.legend(markerscale=3)\n"", + ""plt.show()\n"", + ""\n"", + ""# plot qc metrics including subclusters\n"", + ""for qc_metric in ['log10_usable_counts', 'frac_reads_in_peaks', 'frac_promoters_used']:\n"", + "" fig, ax1 = plt.subplots(1,1,figsize=(7,5))\n"", + "" sns.boxplot(x='subset', y=qc_metric, data=adata_norm.obs, ax=ax1)\n"", + "" ax1.axhline(adata_norm.obs[qc_metric].median(), color='black', ls='dotted')\n"", + "" ax1.set_xticklabels(ax1.get_xticklabels(), rotation=90)\n"", + "" plt.show()\n"", + ""\n"", + ""# check marker promoters for potential doublet subclusters\n"", + ""sc.pl.dotplot(adata_norm, ['SLC11A1','CD247','MS4A1','SFTPC','EDN3','MCIDAS','VWF','GBP4','PROX1','WNT2','MYOCD','GJC1'],\n"", + "" standard_scale='var', groupby='subset', dendrogram=False, use_raw=True)\n"", + "" \n"", + ""adata_norm.obs.loc[adata_norm.obs['subset'].isin(['0,28'])].to_csv(os.path.join(wd, '{}.alveolar_type_2.doublets'.format(sample_name)), header=False, columns=[])"" + ] + } + ], + ""metadata"": { + ""kernelspec"": { + ""display_name"": ""Python 3"", + ""language"": ""python"", + ""name"": ""python3"" + }, + ""language_info"": { + ""codemirror_mode"": { + ""name"": ""ipython"", + ""version"": 3 + }, + ""file_extension"": "".py"", + ""mimetype"": ""text/x-python"", + ""name"": ""python"", + ""nbconvert_exporter"": ""python"", + ""pygments_lexer"": ""ipython3"", + ""version"": ""3.7.6"" + } + }, + ""nbformat"": 4, + ""nbformat_minor"": 2 +} +","Unknown" +"Epigenetics","kjgaulton/pipelines","lung_snATAC_pipeline/lung_snATAC_pipeline.py",".py","16718","304","#!/usr/bin/env python3 + +import os +import sys +import gzip +import argparse +import logging +import subprocess +import pysam +import numpy as np +import pandas as pd +import scipy.sparse +from multiprocessing import Pool + +def trim_reads(args): + pair1_trim = os.path.join(args.output, os.path.basename(args.read1).split('.fastq.gz')[0] + '_val_1.fq.gz') + pair2_trim = os.path.join(args.output, os.path.basename(args.read2).split('.fastq.gz')[0] + '_val_2.fq.gz') + if os.path.isfile(pair1_trim) and os.path.isfile(pair2_trim): + return pair1_trim, pair2_trim + trim_galore_cmd = ['trim_galore', '--nextera', '--fastqc', '-q', '20', '-o', args.output, '--paired', args.read1, args.read2] + with open(os.devnull, 'w') as f: + subprocess.call(trim_galore_cmd, stderr=f, stdout=f) + return pair1_trim, pair2_trim + +def align_reads(args): + align_log = args.output_prefix + '.align.log' + aligned_bam = args.output_prefix + '.compiled.bam' + filtered_bam = args.output_prefix + '.compiled.filt.bam' + + bwa_mem_cmd = ['bwa', 'mem', '-t', str(args.threads), args.reference, args.read1, args.read2] + filter1_cmd = ['samtools', 'view', '-b', '-h', '-q', str(args.map_quality), '-F', '2048', '-'] + fixmate_cmd = ['samtools', 'fixmate', '-r', '-', '-'] + samtools_sort_cmd = ['samtools', 'sort', '-m', str(args.memory)+'G', '-@', str(args.threads), '-'] + filter2_cmd = ['samtools', 'view', '-h', '-f', '3', '-F', '4', '-F', '256', '-F', '1024', aligned_bam] + samtools_view_cmd = ['samtools', 'view', '-b', '-'] + + with open(align_log, 'w') as log, open(aligned_bam, 'w') as bam_out: + bwa_mem = subprocess.Popen(bwa_mem_cmd, stdout=subprocess.PIPE, stderr=log) + filt1 = subprocess.Popen(filter1_cmd, stdin=bwa_mem.stdout, stdout=subprocess.PIPE) + fixmate = subprocess.Popen(fixmate_cmd, stdin=filt1.stdout, stdout=subprocess.PIPE) + subprocess.call(samtools_sort_cmd, stdin=fixmate.stdout, stdout=bam_out, stderr=log) + + with open(align_log, 'a') as log, open(filtered_bam, 'w') as bam_out: + filt2 = subprocess.Popen(filter2_cmd, stderr=log, stdout=subprocess.PIPE) + view = subprocess.Popen(samtools_view_cmd, stdin=subprocess.PIPE, stdout=bam_out) + for line in filt2.stdout: + line = line.decode().rstrip('\n') + if line.startswith('@'): + try: + view.stdin.write('{}\n'.format(line).encode()) + except IOError as err: + if err.errno == errno.EPIPE or err.errno == errno.EINVAL: + break + else: + raise + continue + fields = line.split('\t') + barcode = fields[0].split(':')[0] + fields[0] = barcode + '_' + ':'.join(fields[0].split(':')[1:]) + fields.append('BX:Z:{}'.format(barcode)) + try: + view.stdin.write('{}\n'.format('\t'.join(fields)).encode()) + except IOError as err: + if err.errno == errno.EPIPE or err.errno == errno.EINVAL: + break + else: + raise + view.stdin.close() + view.wait() + return + +def remove_duplicate_reads(args): + filtered_bam = args.output_prefix + '.compiled.filt.bam' + markdup_bam = args.output_prefix + '.filt.md.bam' + rmdup_bam = args.output_prefix + '.filt.rmdup.bam' + markdup_log = args.output_prefix + '.MarkDuplicates.log' + markdup_cmd = ['java', '-Xmx24G', '-jar', args.picard, + 'MarkDuplicates', 'INPUT={}'.format(filtered_bam), 'OUTPUT={}'.format(markdup_bam), + 'VALIDATION_STRINGENCY=LENIENT', 'BARCODE_TAG=BX', 'METRICS_FILE={}'.format(markdup_log), + 'REMOVE_DUPLICATES=false'] + index_cmd = ['samtools', 'index', markdup_bam] + filter_cmd = ['samtools', 'view', '-@', str(args.threads), '-b', '-f', '3', '-F', '1024', markdup_bam] + filter_cmd.extend(['chr{}'.format(c) for c in list(map(str, range(1,23))) + ['X','Y']]) + + with open(os.devnull, 'w') as null: + subprocess.call(markdup_cmd, stderr=null, stdout=null) + subprocess.call(index_cmd) + if os.path.isfile(markdup_bam): + with open(rmdup_bam, 'w') as bam_out: + subprocess.call(filter_cmd, stdout=bam_out) + else: + raise FileNotFoundError('{} not found!'.format(markdup_bam)) + return + +def qc_metrics(args): + md_bam = args.output_prefix + '.filt.md.bam' + rmdup_bam = args.output_prefix + '.filt.rmdup.bam' + tagalign_file = args.output_prefix + '.filt.rmdup.tagAlign.gz' + + if os.path.isfile(rmdup_bam): + with gzip.open(tagalign_file, 'wt') as f: + bamfile = pysam.AlignmentFile(rmdup_bam, 'rb') + genome_size = {item['SN']:item['LN'] for item in bamfile.header['SQ']} + for read in bamfile: + if not read.is_proper_pair: + continue + barcode = read.query_name.split('_')[0] + read_chr = read.reference_name + read_start = max(1, read.reference_end - args.shift - args.extsize - 5 if read.is_reverse else read.reference_start + args.shift + 4) + read_end = min(genome_size[read_chr], read.reference_end - args.shift - 5 if read.is_reverse else read.reference_start + args.shift + args.extsize + 4) + read_qual = read.mapping_quality + if read.is_reverse: + read_orient = '-' + else: + read_orient = '+' + line_out = '\t'.join([read_chr, str(read_start), str(read_end), '{}_{}'.format(args.name,barcode), str(read_qual), read_orient]) + print(line_out, sep='\t', file=f) + bamfile.close() + else: + raise FileNotFoundError('{} not found!'.format(rmdup_bam)) + + qc_metrics = {} + chr_names = ['chr1', 'chr2', 'chr3', 'chr4', 'chr5', 'chr6', 'chr7', 'chr8', 'chr9', 'chr10', 'chr11', 'chr12', 'chr13', 'chr14', 'chr15', 'chr16', 'chr17', 'chr18', 'chr19', 'chr20', 'chr21', 'chr22', 'chrX', 'chrY'] + # mito and duplicated read percentage + if os.path.isfile(md_bam): + bamfile = pysam.AlignmentFile(md_bam, 'rb') + for read in bamfile: + barcode = '{}_{}'.format(args.name, read.query_name.split('_')[0]) + if barcode not in qc_metrics: + qc_metrics[barcode] = {} + if not read.is_duplicate: + if read.reference_name in chr_names: + qc_metrics[barcode]['unique_usable_reads'] = qc_metrics[barcode].get('unique_usable_reads', 0) + 1 + elif read.reference_name == 'chrM': + qc_metrics[barcode]['unique_mito_reads'] = qc_metrics[barcode].get('unique_mito_reads', 0) + 1 + qc_metrics[barcode]['total_sequenced_reads'] = qc_metrics[barcode].get('total_sequenced_reads', 0) + 1 + else: + qc_metrics[barcode]['duplicated_reads'] = qc_metrics[barcode].get('duplicated_reads', 0) + 1 + qc_metrics[barcode]['total_sequenced_reads'] = qc_metrics[barcode].get('total_sequenced_reads', 0) + 1 + else: + raise FileNotFoundError('{} not found!'.format(md_bam)) + qc_metrics = pd.DataFrame.from_dict(qc_metrics, orient='index').fillna(0).astype(int) + # reads in peaks + macs2_cmd = ['macs2', 'callpeak', '-t', tagalign_file, '--outdir', args.output, '-n', args.name, '-p', '.05', '--nomodel', '--keep-dup', 'all', '--shift', '0', '--extsize', '200', '-g', 'hs'] + with open(os.devnull, 'w') as f: + subprocess.call(macs2_cmd, stderr=f) + try: + os.remove(args.output_prefix + '_peaks.xls') + os.remove(args.output_prefix + '_summits.bed') + except: + pass + blacklist_cmd = subprocess.Popen(['bedtools', 'intersect', '-a' , args.output_prefix + '_peaks.narrowPeak', '-b', args.blacklist_file, '-v'], stdout=subprocess.PIPE) + intersect_cmd = subprocess.Popen(['bedtools', 'intersect', '-a', tagalign_file, '-b', '-' ], stdin=blacklist_cmd.stdout, stdout=subprocess.PIPE) + peak_counts = {bc:0 for bc in qc_metrics.index} + for line in intersect_cmd.stdout: + line = line.decode() + fields = line.rstrip().split('\t') + peak_counts[fields[3]] += 1 + qc_metrics['reads_in_peaks'] = qc_metrics.index.map(peak_counts).fillna(0).astype(int) + # reads in promoter and promoter usage + tss_counts = {bc:0 for bc in qc_metrics.index} + tss_cmd1 = subprocess.Popen(['bedtools', 'intersect', '-a', tagalign_file, '-b', args.promoter_file, '-wa'], stdout=subprocess.PIPE) + uniq = subprocess.Popen(['uniq'], stdin=tss_cmd1.stdout, stdout=subprocess.PIPE) + for line in uniq.stdout: + line = line.decode() + fields = line.rstrip().split('\t') + tss_counts[fields[3]] += 1 + + tss_used = {bc:[] for bc in qc_metrics.index} + tss_cmd2 = subprocess.Popen(['bedtools', 'intersect', '-a', tagalign_file, '-b', args.promoter_file, '-wa', '-wb'], stdout=subprocess.PIPE) + for line in tss_cmd2.stdout: + line = line.decode() + fields = line.rstrip().split('\t') + tss_used[fields[3]].append(fields[9]) + qc_metrics['reads_in_promoters'] = qc_metrics.index.map(tss_counts).fillna(0).astype(int) + qc_metrics['tss_used'] = [len(set(tss_used[bc])) for bc in qc_metrics.index] + total_prom = len(sorted(set(pd.read_table(args.promoter_file, sep='\t', header=None, names=['chr','start','end','promoter'])['promoter']))) + qc_metrics['frac_reads_in_peaks'] = qc_metrics['reads_in_peaks'].div(qc_metrics['unique_usable_reads']).replace(np.inf, 0).fillna(0) + qc_metrics['frac_reads_in_promoters'] = qc_metrics['reads_in_promoters'].div(qc_metrics['unique_usable_reads']).replace(np.inf, 0).fillna(0) + qc_metrics['frac_promoters_used'] = qc_metrics['tss_used']/total_prom + qc_metrics['frac_mito_reads'] = qc_metrics['unique_mito_reads'].div(qc_metrics['unique_usable_reads'] + qc_metrics['unique_mito_reads']).replace(np.inf, 0).fillna(0) + qc_metrics['frac_duplicated_reads'] = qc_metrics['duplicated_reads'].div(qc_metrics['total_sequenced_reads']).fillna(0) + qc_metrics.to_csv(os.path.join(args.output_prefix + '.qc_metrics.txt'), sep='\t') + return + + +def generate_matrix(args): + tagalign_file = args.output_prefix + '.filt.rmdup.tagAlign.gz' + qc_metrics = pd.read_table(args.output_prefix + '.qc_metrics.txt', sep='\t', header=0, index_col=0) + pass_barcodes = qc_metrics.loc[qc_metrics['unique_usable_reads'] >= args.minimum_reads].index + + lf_mtx_file = args.output_prefix + '.long_fmt_mtx.txt.gz' + barcodes_file = args.output_prefix + '.barcodes' + regions_file = args.output_prefix + '.regions' + mtx_file = args.output_prefix + '.mtx' + + windows_file = make_windows(args) + window_intersect = intersect_regions(tagalign_file, windows_file) + cut = subprocess.Popen(['cut', '-f', '4,10'], stdin=window_intersect.stdout, stdout=subprocess.PIPE) + sort = subprocess.Popen(['sort', '-S', '{}G'.format(args.memory * args.threads)], stdin=cut.stdout, stdout=subprocess.PIPE) + uniq = subprocess.Popen(['uniq', '-c'], stdin=sort.stdout, stdout=subprocess.PIPE) + awk = subprocess.Popen(['awk', '''BEGIN{{OFS=""\\t""}} {{print $2,$3,$1}}'''], stdin=uniq.stdout, stdout=subprocess.PIPE) + with gzip.open(lf_mtx_file, 'wt') as f: + subprocess.call(['gzip', '-c'], stdin=awk.stdout, stdout=f) + + lf_mtx = pd.read_table(lf_mtx_file, sep='\t', header=None, names=['barcode','region','count']) + lf_mtx = lf_mtx.loc[lf_mtx['barcode'].isin(pass_barcodes)] + lf_mtx.to_csv(lf_mtx_file, sep='\t', header=False, index=False, compression='gzip') + + tmp_R = args.output_prefix + '.tmp.R' + with open(tmp_R, 'w') as tR: + print('''library(Matrix)''', file=tR) + print('''data <- read.table('{}', sep='\\t', header=FALSE)'''.format(lf_mtx_file), file=tR) + print('''sparse.data <- with(data, sparseMatrix(i=as.numeric(V1), j=as.numeric(V2), x=V3, dimnames=list(levels(V1), levels(V2))))''', file=tR) + print('''t <- writeMM(sparse.data, '{}')'''.format(mtx_file), file=tR) + print('''write.table(data.frame(rownames(sparse.data)), file='{}', col.names=FALSE, row.names=FALSE, quote=FALSE)'''.format(barcodes_file), file=tR) + print('''write.table(data.frame(colnames(sparse.data)), file='{}', col.names=FALSE, row.names=FALSE, quote=FALSE)'''.format(regions_file), file=tR) + subprocess.call(['Rscript', tmp_R]) + subprocess.call(['gzip', mtx_file]) + os.remove(windows_file) + os.remove(tmp_R) + return + + +def intersect_regions(tagalign, regions): + awk_cmd = ['awk', '''BEGIN{{FS=OFS=""\\t""}} {{peakid=$1"":""$2""-""$3; gsub(""chr"","""",peakid); print $1, $2, $3, peakid}}''', regions] + intersect_cmd = ['bedtools', 'intersect', '-a', tagalign, '-b', '-', '-wa', '-wb'] + awk = subprocess.Popen(awk_cmd, stdout=subprocess.PIPE) + intersect = subprocess.Popen(intersect_cmd, stdin=awk.stdout, stdout=subprocess.PIPE) + return intersect + +def make_windows(args): + makewindows_cmd = ['bedtools', 'makewindows', '-g', args.chrom_sizes, '-w', str(args.window_size * 1000)] + filter_cmd = ['grep', '-v', '_'] + blacklist_cmd = ['bedtools', 'intersect', '-a', '-', '-b', args.blacklist_file, '-v'] + windows_file = '{}.{}kb_windows.bed'.format(args.output_prefix, args.window_size) + with open(windows_file, 'w') as f: + makewindows = subprocess.Popen(makewindows_cmd, stdout=subprocess.PIPE) + filt = subprocess.Popen(filter_cmd, stdin=makewindows.stdout, stdout=subprocess.PIPE) + subprocess.call(blacklist_cmd, stdin=filt.stdout, stdout=f) + return windows_file + +def main(args): + logging.info('Start.') + if not os.path.isdir(args.output): + os.makedirs(args.output) + args.output_prefix = os.path.join(args.output, args.name) + if not args.skip_trim: + logging.info('Trimming adapters using trim_galore.') + args.read1, args.read2 = trim_reads(args) + if not args.skip_align: + logging.info('Aligning reads using BWA mem with [{}] processors.'.format(args.threads)) + logging.info('Piping output to samtools using [{}] Gb of memory.'.format(args.memory)) + align_reads(args) + if not args.skip_rmdup: + logging.info('Removing duplicate and mitochrondrial reads.'.format(args.minimum_reads)) + remove_duplicate_reads(args) + if not args.skip_qc: + qc_metrics(args) + if not args.skip_matrix: + logging.info('Generating tagalign and chromatin accessibility matrix.') + generate_matrix(args) + logging.info('Finish.') + return + +def process_args(): + parser = argparse.ArgumentParser(description='Process combinatorial barcoding snATAC-seq data.') + io_group = parser.add_argument_group('I/O arguments') + io_group.add_argument('-r1', '--read1', required=True, type=str, help='Paired-end reads file 1') + io_group.add_argument('-r2', '--read2', required=True, type=str, help='Paired-end reads file 2') + io_group.add_argument('-o', '--output', required=False, type=str, default=os.getcwd(), help='Output directory to store processed files') + io_group.add_argument('-n', '--name', required=True, type=str, help='Prefix for naming all output files') + + align_group = parser.add_argument_group('Alignment arguments') + align_group.add_argument('-t', '--threads', required=False, type=int, default=8, help='Number of threads to use for alignment [8]') + align_group.add_argument('-m', '--memory', required=False, type=int, default=4, help='Maximum amount of memory (G) per thread for samtools sort [4]') + align_group.add_argument('-q', '--map_quality', required=False, type=int, default=30, help='Mapping quality score filter for samtools [30]') + align_group.add_argument('-ref', '--reference', required=False, type=str, default='references/male.hg19.fa', help='Path to the BWA indexed reference genome') + + dup_group = parser.add_argument_group('Remove duplicates arguments') + dup_group.add_argument('--picard', required=False, type=str, default='/home/joshchiou/bin/picard.jar', help='Path to picard.jar') + + matrix_group = parser.add_argument_group('Matrix generation arguments') + matrix_group.add_argument('--shift', required=False, type=int, default=-100, help='Read shift size') + matrix_group.add_argument('--extsize', required=False, type=int, default=200, help='Read extension size') + matrix_group.add_argument('--minimum-reads', required=False, type=int, default=1000, help='Minimum number of reads for barcode inclusion') + matrix_group.add_argument('--window-size', required=False, type=int, default=5, help='Size (kb) to use for defining windows of accessibility') + matrix_group.add_argument('--chrom-sizes', required=False, type=str, default='references/hg19.chrom.sizes', help='Chromosome sizes file from UCSC') + matrix_group.add_argument('--blacklist-file', required=False, type=str, default='references/hg19-blacklist.v1.bed.gz', help='BED file of blacklisted regions') + matrix_group.add_argument('--promoter-file', required=False, type=str, default='references/gencode.v19.1kb_promoters.pc_transcripts.bed.gz', help='BED file of autosomal promoter regions') + + skip_group = parser.add_argument_group('Skip steps') + skip_group.add_argument('--skip-trim', required=False, action='store_true', default=False, help='Skip adapter trimming step') + skip_group.add_argument('--skip-align', required=False, action='store_true', default=False, help='Skip read alignment step') + skip_group.add_argument('--skip-rmdup', required=False, action='store_true', default=False, help='Skip duplicate removal step') + skip_group.add_argument('--skip-qc', required=False, action='store_true', default=False, help='Skip QC metrics calculation step') + skip_group.add_argument('--skip-matrix', required=False, action='store_true', default=False, help='Skip matrix generation step') + return parser.parse_args() + +if __name__ == '__main__': + logging.basicConfig(format='[%(filename)s] %(asctime)s %(levelname)s: %(message)s', datefmt='%I:%M:%S', level=logging.INFO) + args = process_args() + main(args) +","Python" +"Epigenetics","kjgaulton/pipelines","ChIP-seq/ChIP-seq_pipeline.py",".py","8208","173","#!/usr/bin/env python3 + +import argparse +import subprocess +import os +import sys +import reprlib +import logging + +#=======================================================# + +def process_reads(args, reads, name): + output_prefix = os.path.join(args.output, name) + align_log = output_prefix + '.align.log' + aligned_bam = output_prefix + '.sort.filt.bam' + rmdup_bam = output_prefix + '.sort.filt.rmdup.bam' + + # align reads with bwa aln / bwa samse + # then filter out reads that are unmapped, chrM reads, < quality score + # then sort reads + bwa_aln_cmd = ['bwa', 'aln', '-q', '15', '-t', str(args.processes), args.reference, reads] + bwa_samse_cmd = ['bwa', 'samse', args.reference, '-', reads] + quality_filt_cmd = ['samtools', 'view', '-h', '-F', '1548', '-q', str(args.quality), '-@', str(args.processes), '-'] + mito_filt_cmd = ['grep', '-v', 'chrM'] + samtools_sort_cmd = ['samtools', 'sort', '-m', '{}G'.format(args.memory), '-@', str(args.processes), '-'] + + with open(align_log, 'w') as log, open(aligned_bam, 'w') as bam_out: + bwa_aln = subprocess.Popen(bwa_aln_cmd, stdout=subprocess.PIPE, stderr=log) + bwa_samse = subprocess.Popen(bwa_samse_cmd, stdin=bwa_aln.stdout, stdout=subprocess.PIPE, stderr=log) + qual_filt = subprocess.Popen(quality_filt_cmd, stdin=bwa_samse.stdout, stdout=subprocess.PIPE, stderr=log) + mito_filt = subprocess.Popen(mito_filt_cmd, stdin=qual_filt.stdout, stdout=subprocess.PIPE, stderr=log) + subprocess.call(samtools_sort_cmd, stdin=mito_filt.stdout, stdout=bam_out, stderr=log) + + # use picard MarkDuplicates to filter out duplicate reads + # then index the bam file + metrics_file = output_prefix + '.MarkDuplicates.metrics' + rmdup_cmd = [ + 'java', '-Xmx{}G'.format(12), + '-jar', args.markdup, + 'INPUT={}'.format(aligned_bam), + 'OUTPUT={}'.format(rmdup_bam), + 'REMOVE_DUPLICATES=true', + 'VALIDATION_STRINGENCY=LENIENT', + 'METRICS_FILE={}'.format(metrics_file)] + index_cmd = ['samtools', 'index', rmdup_bam] + + if os.path.exists(aligned_bam) and os.path.getsize(aligned_bam) != 0: + with open(os.devnull, 'w') as f: + subprocess.call(rmdup_cmd, stderr=f) + if os.path.exists(rmdup_bam) and os.path.getsize(rmdup_bam) != 0: + subprocess.call(index_cmd) + + return rmdup_bam + +#=======================================================# + +def call_peaks(args, treat_bam, control_bam): + macs2_log = os.path.join(args.output, '.'.join([args.name, 'macs2_callpeaks.log'])) + macs2_cmd = ['macs2', 'callpeak', + '-t', treat_bam, + '-c', control_bam, + '-g', args.macs2_genome, + '--outdir', args.output, + '-n', args.name, + '-q', str(args.qvalue), + '--extsize', '200', + '-B', + '--keep-dup', 'all' ] + if args.broad: + macs2_cmd.extend(['--broad', '--broad-cutoff', str(args.broad_cutoff)]) + with open(macs2_log, 'w') as f: + subprocess.call(macs2_cmd, stderr=f) + return + +#=======================================================# + +def bdgcmp(args): + bdgcmp_log = os.path.join(args.output, '.'.join([args.name, 'bdgcmp.log'])) + bdgcmp_cmd = [ + 'macs2', 'bdgcmp', + '-t', os.path.join(args.output, args.name + '_treat_pileup.bdg'), + '-c', os.path.join(args.output, args.name + '_control_lambda.bdg'), + '-m', 'ppois', + '--outdir', args.output, + '--o-prefix', args.name, + '-p', '0.00001'] + with open(bdgcmp_log, 'w') as f: + subprocess.call(bdgcmp_cmd, stderr=f) + + bdgcmp_out = os.path.join(args.output, args.name + '_ppois.bdg') + + # add track label to the bedgraph, sort, and gzip + label = 'track type=bedGraph name=\""{0}\"" description=\""{0}\"" visibility=2 color={1} altColor=0,0,0 autoScale=off maxHeightPixels=64:64:32'.format(args.name, args.color) + sorted_bdg = os.path.join(args.output, args.name + '_ppois.sorted.bdg') + sort_cmd = ['sort', '-k', '1,1', '-k', '2,2n', bdgcmp_out] + with open(sorted_bdg, 'w') as f: + print(label, file=f) + with open(sorted_bdg, 'a') as f: + subprocess.call(sort_cmd, stdout=f) + subprocess.call(['gzip', sorted_bdg]) + os.remove(bdgcmp_out) + return + +#=======================================================# + +def main(args): + logging.info('Starting up.') + if not os.path.isdir(args.output): + try: + os.makedirs(args.output) + except OSError: + pass + if not args.skip_align: + try: + logging.info('Aligning reads with bwa aln/samse and filtering reads with samtools.') + logging.info('Processing treatment bam [{}].'.format(args.treatment)) + args.treatment = process_reads(args, args.treatment, args.name) + logging.info('Processing control bam [{}].'.format(args.control)) + args.control = process_reads(args, args.control, args.name + '_control') + except Exception as e: + print('Check options -t and -c: ' + repr(e), file=sys.stderr) + if not args.skip_peaks: + try: + logging.info('Calling peaks with MACS2.') + call_peaks(args, args.treatment, args.control) + except Exception as e: + print(repr(e), file=sys.stderr) + if not args.skip_track: + try: + logging.info('Building signal track with MACS2 output.') + bdgcmp(args) + except Exception as e: + print(repr(e), file=sys.stderr) + logging.info('Finishing up.') + return + +#=======================================================# + +def process_args(): + parser = argparse.ArgumentParser(description='Pipeline for ChIP to align reads to a reference genome, and then call peaks.') + + io_group = parser.add_argument_group('I/O arguments') + io_group.add_argument('-t', '--treatment', required=True, type=str, help='Path to treatment file [.fastq.gz OR .bam if --skip_align is ON]') + io_group.add_argument('-c', '--control', required=True, type=str, help='Path to control file [.fastq.gz OR .bam if --skip_align is ON]') + io_group.add_argument('-o', '--output', required=True, type=str, help='Output directory for processed files') + io_group.add_argument('-n', '--name', required=False, type=str, default='sample', help='Output sample name to prepend') + + align_group = parser.add_argument_group('Alignment and rmdup arguments') + align_group.add_argument('-p', '--processes', required=False, type=int, default=4, help='Number of processes to use [4]') + align_group.add_argument('-m', '--memory', required=False, type=int, default=8, help='Maximum memory per thread [8]') + align_group.add_argument('-q', '--quality', required=False, type=int, default=10, help='Mapping quality cutoff for samtools [10]') + align_group.add_argument('-ref', '--reference', required=False, type=str, default='/home/joshchiou/references/ucsc.hg19.fasta', help='Path to reference genome prepared for BWA [/home/joshchiou/references/ucsc.hg19.fasta]') + align_group.add_argument('-markdup', '--markdup', required=False, type=str, default='/home/joshchiou/bin/MarkDuplicates.jar', help='Path to MarkDuplicates.jar [/home/joshchiou/bin/MarkDuplicates.jar]') + + macs2_group = parser.add_argument_group('MACS2 parameters') + macs2_group.add_argument('--qvalue', required=False, type=float, default=0.05, help='MACS2 callpeak qvalue cutoff [0.05]') + macs2_group.add_argument('--broad', required=False, action='store_true', default=False, help='Broad peak option for MACS2 callpeak [OFF]') + macs2_group.add_argument('--broad_cutoff', required=False, type=float, default=0.05, help='MACS2 callpeak qvalue cutoff for broad regions [0.05]') + macs2_group.add_argument('--color', required=False, type=str, default='0,0,0', help='Color in R,G,B format to display for genome browser track [0,0,0]') + macs2_group.add_argument('--macs2_genome', required=False, type=str, default='hg', help='MACS2 genome size (e.g. hg for hg19, mm for mm10)') + + skip_group = parser.add_argument_group('Skip processing') + skip_group.add_argument('--skip_align', required=False, action='store_true', default=False, help='Skip read alignment step [OFF]') + skip_group.add_argument('--skip_peaks', required=False, action='store_true', default=False, help='Skip calling peaks step [OFF]') + skip_group.add_argument('--skip_track', required=False, action='store_true', default=False, help='Skip making signal track for genome browser [OFF]') + return parser.parse_args() + +#=======================================================# +if __name__ == '__main__': + logging.basicConfig(format='[%(filename)s] %(asctime)s %(levelname)s: %(message)s', datefmt='%I:%M:%S', level=logging.DEBUG) + args = process_args() + main(args) +","Python" +"Epigenetics","fernandam93/epiclocks_cancer","6.1_run_CAUSE_for_GrimAge_PrCinPRACTICAL.R",".R","4351","103","####################################################################### +# EPIGENETIC CLOCKS AND MULTIPLE CANCERS # +####################################################################### +# R version 4.0.2 (2020-06-22) +# Last modified: 18 August 2021 + +# This script runs CAUSE for GrimAge acceleration and prostate cancer +# in PRACTICAL (data for prostate cancer can be obtained from MR-Base) +# This needs to be run using the terminal + +#---------------------------------------------------------------------# +# Housekeeping #---- +#---------------------------------------------------------------------# + +# Clear environment +rm(list=ls()) #Remove any existing objects in R + +# Install packages +if (!require(""pacman"")) install.packages(""pacman"") +pacman::p_load(""MRInstruments"", ""TwoSampleMR"", ""tidyverse"", ""dplyr"", ""readr"", ""ieugwasr"") +pacman::p_load_gh(""jean997/cause@v1.2.0"", ""explodecomputer/genetics.binaRies"") + +# Available outcomes +ao <- available_outcomes() +#---------------------------------------------------------------------# +# Read exposure #---- +#---------------------------------------------------------------------# +#read exposure +GrimAge <- read.table(""GrimAge_EUR_summary_statistics.txt"", header = T) + +#---------------------------------------------------------------------# +# Outcomes #---- +#---------------------------------------------------------------------# + +# Option 1: obtain complete summary statistics from MR-Base +# Extract outcome SNPs matching the SNPs in the exposure dataset (output is in the two sample MR package format) +prostate_ca <- extract_outcome_data( + snps = GrimAge$rsID, + outcomes = c(""ieu-b-85""), proxies = F +) + +# Save +#write.table(prostate_ca, ""prostate_ca_complete_summary_stats.txt"", row.names = F, col.names = T) + +# Option 2: Upload complete summary statistics (preferred option) +prostate_ca <- read.table(""prostate_ca_complete_summary_stats.txt"", header = T) + +#---------------------------------------------------------------------# +# Merge GWAS data #---- +#---------------------------------------------------------------------# + +X <- gwas_merge(GrimAge, prostate_ca, + snp_name_cols = c(""rsID"", ""SNP""), + beta_hat_cols = c(""Effect"", ""beta.outcome""), + se_cols = c(""SE"", ""se.outcome""), + A1_cols = c(""A1"", ""effect_allele.outcome""), + A2_cols = c(""A2"", ""other_allele.outcome"")) + +#---------------------------------------------------------------------# +# Calculate nuisance parameters #---- +#---------------------------------------------------------------------# + +# only > 100,000 variants +set.seed(100) +varlist <- with(X, sample(snp, size=1000000, replace=FALSE)) +params <- est_cause_params(X, varlist) +head(params$mix_grid) + +#---------------------------------------------------------------------# +# Clump data #---- +#---------------------------------------------------------------------# + +X$p_value <- 2*pnorm(abs(X$beta_hat_1/X$seb1), lower.tail=FALSE) +X_clump <- X %>% rename(rsid = snp, + pval = p_value) %>% + ieugwasr::ld_clump(dat = ., + clump_r2 = 0.01, + clump_p = 1e-03, #should use larger p value, 1e-03 as used for posteriors, not 5e-08 + # plink_bin = genetics.binaRies::get_plink_binary(), + #bfile = ""~/EUR"" + ) +keep_snps <- X_clump$rsid + +#---------------------------------------------------------------------# +# MR-CAUSE analysis #---- +#---------------------------------------------------------------------# + +# X is unclumped data and variants clumped data +res <- cause(X=X, variants = keep_snps, param_ests = params) +plot(res$sharing) +plot(res$causal) +summary(res, ci_size=0.95) +plot(res) +plot(res, type=""data"") + +png('CAUSE/CAUSE_GrimAge_PrC1.png', res=300, height=2000, width=3500) +plot(res) +dev.off() + +png('CAUSE/CAUSE_GrimAge_PrC2.png', res=300, height=2000, width=3500) +plot(res, type=""data"") +dev.off() +","R" +"Epigenetics","fernandam93/epiclocks_cancer","5.1_create_metaanalysis_plots_detail.R",".R","11779","218","####################################################################### +# EPIGENETIC CLOCKS AND MULTIPLE CANCERS # +####################################################################### +# R version 4.0.2 (2020-06-22) +# Last modified: 11 October 2021 + +# This script creates plots for the meta-analysis of two-sample MR results +# across UK Biobank, FinnGen and international consortiums +# This script uses the forest.meta function to create plots with details on +# individual study ORs and CIs, between study heterogeneity, etc + +#---------------------------------------------------------------------# +# Housekeeping #---- +#---------------------------------------------------------------------# + +# Clear environment +rm(list=ls()) #Remove any existing objects in R + +# Set working directory +setwd(""your_working_directory"") + +if (!require(""pacman"")) install.packages(""pacman"") +pacman::p_load(""meta"", ""metafor"", ""openxlsx"", ""TwoSampleMR"", ""tidyverse"", ""dplyr"", ""ggpubr"", ""ggforestplot"", ""cowplot"") + +#---------------------------------------------------------------------# +# Load two-sample MR results #---- +#---------------------------------------------------------------------# + +# Function to load MR results +load_data_func <- function(file_name) +{ + results <- read.table(file = file_name, header = T) + results <- split_outcome(results) # to keep the Y axis label clean we exclude the exposure ID labels from the exposure column +} + +results_IEU <- load_data_func(""results_IEU.txt"") +results_UKB <- load_data_func(""results_UKB_new.txt"") +results_FINNGEN <- load_data_func(""results_FINNGEN.txt"") + +#---------------------------------------------------------------------# +# Format MR results #---- +#---------------------------------------------------------------------# + +# Add new column with study name +results_IEU$study[results_IEU$outcome==""Colorectal cancer""] <- ""GECCO"" +results_IEU$study[results_IEU$outcome==""Lung cancer""] <- ""ILCCO"" +results_IEU$study[results_IEU$outcome==""Breast cancer (Combined Oncoarray; iCOGS; GWAS meta analysis)""] <- ""BCAC"" +results_IEU$study[results_IEU$outcome==""Ovarian cancer""] <- ""OCAC"" +results_IEU$study[results_IEU$outcome==""Prostate cancer""] <- ""PRACTICAL"" +results_UKB$study <- ""UK Biobank"" +results_FINNGEN$study <- ""FinnGen"" + +# Rename IEU results and filter to only include some of them in the meta-analysis +results_IEU$outcome[results_IEU$outcome==""Breast cancer (Combined Oncoarray; iCOGS; GWAS meta analysis)""] <- ""Breast cancer"" +results_IEU <- results_IEU[which(results_IEU$outcome=='Breast cancer' | results_IEU$outcome=='Ovarian cancer' | results_IEU$outcome=='Prostate cancer' | results_IEU$outcome=='Lung cancer' | results_IEU$outcome=='Colorectal cancer'),] + +# Rename UKB results and filter to only include some of them in the meta-analysis +results_UKB$outcome[results_UKB$outcome==""breast cancer""] <- 'Breast cancer' +results_UKB$outcome[results_UKB$outcome==""ovarian cancer""] <- 'Ovarian cancer' +results_UKB$outcome[results_UKB$outcome==""prostate cancer""] <- 'Prostate cancer' +results_UKB$outcome[results_UKB$outcome==""lung cancer unadjusted""] <- 'Lung cancer' +results_UKB$outcome[results_UKB$outcome==""colorectal cancer""] <- 'Colorectal cancer' +results_UKB <- results_UKB[which(results_UKB$outcome=='Breast cancer' | results_UKB$outcome=='Ovarian cancer' | results_UKB$outcome=='Prostate cancer' | results_UKB$outcome=='Lung cancer' | results_UKB$outcome=='Colorectal cancer'),] + +# Rename FinnGen results and filter to only include some of them in the meta-analysis +results_FINNGEN$outcome[results_FINNGEN$outcome==""breast cancer (excluding cancer in controls)""] <- 'Breast cancer' +results_FINNGEN$outcome[results_FINNGEN$outcome==""ovarian cancer (excluding cancer in controls)""] <- 'Ovarian cancer' +results_FINNGEN$outcome[results_FINNGEN$outcome==""prostate cancer (excluding cancer in controls)""] <- 'Prostate cancer' +results_FINNGEN$outcome[results_FINNGEN$outcome==""lung cancer (excluding cancer in controls)""] <- 'Lung cancer' +results_FINNGEN$outcome[results_FINNGEN$outcome==""colorectal cancer (excluding cancer in controls)""] <- 'Colorectal cancer' +results_FINNGEN <- results_FINNGEN[which(results_FINNGEN$outcome=='Breast cancer' | results_FINNGEN$outcome=='Ovarian cancer' | results_FINNGEN$outcome=='Prostate cancer' | results_FINNGEN$outcome=='Lung cancer' | results_FINNGEN$outcome=='Colorectal cancer'),] + +# Combine results +results <- rbind(results_IEU, results_UKB, results_FINNGEN) + +# Sort results by outcome +cancers <- c(""Breast cancer"", ""Ovarian cancer"", ""Prostate cancer"", ""Lung cancer"", ""Colorectal cancer"") +results<-results[order(match(results$outcome, cancers)),] + +#---------------------------------------------------------------------# +# Run meta-analysis #---- +#---------------------------------------------------------------------# + +#Function to run a fixed effect meta-analysis +meta_func2 <- function(method_varname, exp_varname, out1, out2="""", out3="""", out4="""", + out5="""", out6="""", out7="""", out8="""", out9="""", out10="""", + out11="""", out12="""", out13="""", out14="""", out15="""", + out16="""", out17="""", out18="""", out19="""", out20="""", out21="""") +{ + input <- results[which(results$method==method_varname),] + input <- input[which(input$id.exposure==exp_varname),] + input <- input[which(input$outcome==out1 | input$outcome==out2 | input$outcome==out3 | + input$outcome==out4 | input$outcome==out5 | input$outcome==out6 | + input$outcome==out7 | input$outcome==out8 | input$outcome==out9 | + input$outcome==out10 | input$outcome==out11 | input$outcome==out12 | + input$outcome==out13 | input$outcome==out14 | input$outcome==out15 | + input$outcome==out16 | input$outcome==out17 | input$outcome==out18 | + input$outcome==out19 | input$outcome==out20 | input$outcome==out21),] + #meta-analysis + a <- metagen(TE = b, seTE = se, data = input, + studlab = paste(study), sm = ""OR"", + hakn = FALSE, byvar = c(outcome), + method.tau=""DL"", comb.fixed = T, comb.random = F, exclude = id.outcome %in% c(""J2M7ze"")) #excluding colorectal cancer in UKB from MA + print(a) + + #forest plot + forest.meta(a, studlab = TRUE, + comb.fixed = a$comb.fixed, + type.study=""square"", + squaresize=0.5, + lty.fixed = 2, + type.fixed=""diamond"", + bylab = """", + text.fixed = ""Total"", # write anything + text.fixed.w = ""Total"", + col.study=""black"", + col.square=""black"", + col.diamond=""white"", + col.diamond.lines=""black"", + col.label.right=""black"", + col.label.left=""black"", + colgap.right = ""0.5cm"", + colgap.forest.left =""2.2cm"", + col.by = ""black"", + smlab=""Odds ratio [95% CI]"", + leftcols=c(""studlab""),# To remove ""logHR"" and ""seHR"" from plot + leftlabs = c(""Study""), + rightcols=c(""w.fixed"", ""effect"", ""ci""), + rightlabs=c(""Weight"", ""OR"",""[95% CI]""), + test.overall = F, + lwd=0.9, + print.I2 = a$comb.fixed, + plotwidth=""4.5cm"", + print.I2.ci = a$comb.fixed, + print.tau2 = F, + print.Q = FALSE, + digits = 2, + fontsize = 9, + overall = FALSE, + overall.hetstat = FALSE) + m <- recordPlot() +} + +#IVW +IVW_GrimAge <- meta_func2(""Inverse variance weighted"", ""GrimAge"", ""Breast cancer"", ""Ovarian cancer"", ""Prostate cancer"", + ""Lung cancer"", ""Colorectal cancer"") +IVW_PhenoAge <- meta_func2(""Inverse variance weighted"", ""PhenoAge"", ""Breast cancer"", ""Ovarian cancer"", ""Prostate cancer"", + ""Lung cancer"", ""Colorectal cancer"") +IVW_Hannum <- meta_func2(""Inverse variance weighted"", ""Hannum"", ""Breast cancer"", ""Ovarian cancer"", ""Prostate cancer"", + ""Lung cancer"", ""Colorectal cancer"") +IVW_IEAA <- meta_func2(""Inverse variance weighted"", ""IEAA"", ""Breast cancer"", ""Ovarian cancer"", ""Prostate cancer"", + ""Lung cancer"", ""Colorectal cancer"") + + +#Egger +egger_GrimAge <- meta_func2(""MR Egger"", ""GrimAge"", ""Breast cancer"", ""Ovarian cancer"", ""Prostate cancer"", + ""Lung cancer"", ""Colorectal cancer"") +egger_PhenoAge <- meta_func2(""MR Egger"", ""PhenoAge"", ""Breast cancer"", ""Ovarian cancer"", ""Prostate cancer"", + ""Lung cancer"", ""Colorectal cancer"") +egger_Hannum <- meta_func2(""MR Egger"", ""Hannum"", ""Breast cancer"", ""Ovarian cancer"", ""Prostate cancer"", + ""Lung cancer"", ""Colorectal cancer"") +egger_IEAA <- meta_func2(""MR Egger"", ""IEAA"", ""Breast cancer"", ""Ovarian cancer"", ""Prostate cancer"", + ""Lung cancer"", ""Colorectal cancer"") + + +#Mode based +mode_GrimAge <- meta_func2(""Weighted mode"", ""GrimAge"", ""Breast cancer"", ""Ovarian cancer"", ""Prostate cancer"", + ""Lung cancer"", ""Colorectal cancer"") +mode_PhenoAge <- meta_func2(""Weighted mode"", ""PhenoAge"", ""Breast cancer"", ""Ovarian cancer"", ""Prostate cancer"", + ""Lung cancer"", ""Colorectal cancer"") +mode_Hannum <- meta_func2(""Weighted mode"", ""Hannum"", ""Breast cancer"", ""Ovarian cancer"", ""Prostate cancer"", + ""Lung cancer"", ""Colorectal cancer"") +mode_IEAA <- meta_func2(""Weighted mode"", ""IEAA"", ""Breast cancer"", ""Ovarian cancer"", ""Prostate cancer"", + ""Lung cancer"", ""Colorectal cancer"") + +#median based +median_GrimAge <- meta_func2(""Weighted median"", ""GrimAge"", ""Breast cancer"", ""Ovarian cancer"", ""Prostate cancer"", + ""Lung cancer"", ""Colorectal cancer"") +median_PhenoAge <- meta_func2(""Weighted median"", ""PhenoAge"", ""Breast cancer"", ""Ovarian cancer"", ""Prostate cancer"", + ""Lung cancer"", ""Colorectal cancer"") +median_Hannum <- meta_func2(""Weighted median"", ""Hannum"", ""Breast cancer"", ""Ovarian cancer"", ""Prostate cancer"", + ""Lung cancer"", ""Colorectal cancer"") +median_IEAA <- meta_func2(""Weighted median"", ""IEAA"", ""Breast cancer"", ""Ovarian cancer"", ""Prostate cancer"", + ""Lung cancer"", ""Colorectal cancer"") + +#---------------------------------------------------------------------# +# Save meta-analysis plots #---- +#---------------------------------------------------------------------# + +save_func_MA <- function(file_name, plot_name) +{ + png(file_name, res=330, height=3000, width=2000) + print(plot_name) + dev.off() +} + +#save +save_func_MA('MA_IVW_GrimAge.png', IVW_GrimAge) +save_func_MA('MA_IVW_PhenoAge.png', IVW_PhenoAge) +save_func_MA('MA_IVW_Hannum.png', IVW_Hannum) +save_func_MA('MA_IVW_IEAA.png', IVW_IEAA) + +save_func_MA('MA_egger_GrimAge.png', egger_GrimAge) +save_func_MA('MA_egger_PhenoAge.png', egger_PhenoAge) +save_func_MA('MA_egger_Hannum.png', egger_Hannum) +save_func_MA('MA_egger_IEAA.png', egger_IEAA) + +save_func_MA('MA_median_GrimAge.png', median_GrimAge) +save_func_MA('MA_median_PhenoAge.png', median_PhenoAge) +save_func_MA('MA_median_Hannum.png', median_Hannum) +save_func_MA('MA_median_IEAA.png', median_IEAA) + +save_func_MA('MA_mode_GrimAge.png', mode_GrimAge) +save_func_MA('MA_mode_PhenoAge.png', mode_PhenoAge) +save_func_MA('MA_mode_Hannum.png', mode_Hannum) +save_func_MA('MA_mode_IEAA.png', mode_IEAA) + +","R" +"Epigenetics","fernandam93/epiclocks_cancer","5.4_run_2SMR_for_cancer_byproxy_outcomes_and_create_plots.R",".R","9028","194","####################################################################### +# EPIGENETIC CLOCKS AND MULTIPLE CANCERS # +####################################################################### +# R version 4.0.2 (2020-06-22) +# Last modified: 12 October 2021 + +# This script creates plots for two-sample MR results +# for epigenetic age acceleration and parental cancer in UK Biobank +# This script uses the forestplot function to create colourful plots + +#---------------------------------------------------------------------# +# Housekeeping #---- +#---------------------------------------------------------------------# + +# Clear environment +rm(list=ls()) #Remove any existing objects in R + +# Set working directory +setwd(""your_working_directory"") + +# Install and load packages +if (!require(""pacman"")) install.packages(""pacman"") +pacman::p_load(""MRInstruments"", ""TwoSampleMR"", ""tidyverse"", ""dplyr"", ""ggpubr"", ""ggplot2"", ""ggforce"", ""data.table"", ""ggforestplot"", ""openxlsx"") + +#---------------------------------------------------------------------# +# Read Exposures #---- +#---------------------------------------------------------------------# + +exp_dat <- read.table(file = ""exp_data.txt"", header = T) + +#---------------------------------------------------------------------# +# Outcomes #---- +#---------------------------------------------------------------------# + +# Function to read and format outcome data +out_func_proxies <- function(name, file) +{ + # Extract outcome SNPs matching the SNPs in the exposure dataset + outcome_var <- read.table(paste(""folder_containing_data/"" , file, sep = """"), + header = T) %>% format_data(snps = exp_dat$SNP, + type = ""outcome"", + snp_col = ""SNP"", + beta_col = ""BETA"", + se_col = ""SE"", + effect_allele_col = ""ALLELE1"", + other_allele_col = ""ALLELE0"", + chr_col = ""CHR"", + pos_col = ""BP"", + eaf_col = ""A1FREQ"", + pval_col = ""P_BOLT_LMM_INF"", + info_col = ""INFO"") + outcome_var$outcome <- name + return(outcome_var) +} + +proxy_breast <- out_func_proxies(""Breast cancer"", ""proxy_breast.txt"") +proxy_prostate <- out_func_proxies(""Prostate cancer"", ""proxy_prostate.txt"") +proxy_lung <- out_func_proxies(""Lung cancer"", ""proxy_lung.txt"") +proxy_colorectal <- out_func_proxies(""Colorectal cancer"", ""proxy_bowel.txt"") + +# Combine outcomes +proxies_out_dat <- rbind(proxy_colorectal, proxy_breast, proxy_lung, proxy_prostate) + +#---------------------------------------------------------------------# +# Harmonisation #---- +#---------------------------------------------------------------------# + +# Harmonise exposure and outcome datasets +data_proxies <- harmonise_data( + exposure_dat = exp_dat, + outcome_dat = proxies_out_dat +) + +#---------------------------------------------------------------------# +# Results #---- +#---------------------------------------------------------------------# + +# Run MR analysis +results_proxies <- mr(data_proxies, method_list = c(""mr_ivw"", ""mr_egger_regression"", + ""mr_weighted_median"", ""mr_weighted_mode"")) + +#---------------------------------------------------------------------# +# Transform UKB outcomes #---- +#---------------------------------------------------------------------# + +# Create dataframe with data on number of cases and controls for each outcome +cancer <- c(""Colorectal cancer"", ""Lung cancer"", ""Prostate cancer"", ""Breast cancer"") +ncase <- c(45213, 51073, 31527, 35356) +ncontrol <- c(412429, 404606, 160579, 206992) +UKB_cc <- data.frame(cancer, ncase, ncontrol) + +# Function to transform betas from risk difference (BOLT-LMM output) to log odds scale before exponentiation in UK Biobank +UKB_func <- function(outcome) { + ncase <- UKB_cc$ncase[UKB_cc$cancer==outcome] + ncontrol <- UKB_cc$ncontrol[UKB_cc$cancer==outcome] + u <- ncase/(ncase+ncontrol) +} + +# Create u column based on number of cases and controls for each outcome +results_proxies$u[results_proxies$outcome==""Colorectal cancer""] <- UKB_func(""Colorectal cancer"") +results_proxies$u[results_proxies$outcome==""Lung cancer""] <- UKB_func(""Lung cancer"") +results_proxies$u[results_proxies$outcome==""Prostate cancer""] <- UKB_func(""Prostate cancer"") +results_proxies$u[results_proxies$outcome==""Breast cancer""] <- UKB_func(""Breast cancer"") + +# Correct UK Biobank betas and SEs using the newly created u column +results_proxies$b <- results_proxies$b/(results_proxies$u*(1-results_proxies$u)) +results_proxies$se <- results_proxies$se/(results_proxies$u*(1-results_proxies$u)) + +# Remove u column from UK Biobank results +results_proxies <- subset(results_proxies, select = -c(u) ) + +#write.table(results_proxies, ""results_proxies.txt"", row.names = F) +#results_proxies <- read.table(""results_proxies.txt"", header = T) +#---------------------------------------------------------------------# +# Prepare for visualization #---- +#---------------------------------------------------------------------# + +# Reorder methods as factors +as.factor(results_proxies$method) +results_proxies$method <- factor(results_proxies$method, levels = c(""Weighted mode"", ""Weighted median"", + ""MR Egger"", ""Inverse variance weighted"")) + +# Reporder outcomes as factors +as.factor(results_proxies$outcome) +results_proxies$outcome <- factor(results_proxies$outcome, levels = c(""Breast cancer"", + ""Prostate cancer"", + ""Lung cancer"", + ""Colorectal cancer"" + )) + +results_proxies <- arrange(results_proxies, outcome) + +#---------------------------------------------------------------------# +# Forest function #---- +#---------------------------------------------------------------------# + +myforestplot_3 <- function(df, exp_dataset, exp_dataset2, xlab) +{ + x <- forestplot( + df = df[which(df$id.exposure==exp_dataset & df$method!=""MR Egger""),], + estimate = b, + se = se, + pvalue = pval, + name = outcome, + logodds = T, + colour = method, + title = exp_dataset2, + xlab = xlab, + xlim= c(0.9,1.15) + ) + colours_BP <- c(""#6DC6BD"", ""#2E7EBB"", ""#08306B"") + x <- x + scale_color_manual(values=colours_BP) + #x <- x + scale_x_continuous(breaks = c(0.3, 1, 3, 5, 8, 10)) + print(x) +} + +#---------------------------------------------------------------------# +# Forest plots #---- +#---------------------------------------------------------------------# + +# Create plots using forest plot functions above +p_grim <- myforestplot_3(results_proxies, ""GrimAge"", ""GrimAge"", ""Odds ratio (95% CI) per year increase in GrimAge acceleration"") +#p_grim <- ggarrange(p_grim, legend = ""bottom"") +#p_grim +p_pheno <- myforestplot_3(results_proxies, ""PhenoAge"", ""PhenoAge"", ""Odds ratio (95% CI) per year increase in PhenoAge acceleration"") +#p_pheno <- ggarrange(p_pheno, legend = ""bottom"") +#p_pheno +p_hannum <- myforestplot_3(results_proxies, ""Hannum"", ""HannumAge"", ""Odds ratio (95% CI) per year increase in HannumAge acceleration"") +#p_hannum <- ggarrange(p_hannum, legend = ""bottom"") +#p_hannum +p_ieaa <- myforestplot_3(results_proxies, ""IEAA"", ""Intrinsic HorvathAge"", ""Odds ratio (95% CI) per year increase in Intrinsic HorvathAge acceleration"") +#p_ieaa <- ggarrange(p_ieaa, legend = ""bottom"") +#p_ieaa + +# Combine plots +combine_func <- function(A, B, C, D){ + plot.new() + par(mar=c(1,1,1,1), mgp=c(3,1,0)) + x <- ggarrange(A, B, C, D, labels=c('A', 'B', 'C', 'D'), + ncol = 2, nrow = 2, common.legend = T, hjust = -3, legend = ""bottom"") + print(x) +} + +proxies_all <- combine_func(p_grim, p_pheno, p_hannum, p_ieaa) + +# Save +save_func22 <- function(file_name, plot_name) +{ + png(file_name, res=330, height=3000, width=5100) + print(plot_name) + dev.off() +} +save_func22('proxies_grim_pheno_hannum_ieaa.png', proxies_all) +","R" +"Epigenetics","fernandam93/epiclocks_cancer","3.4_run_2SMR_for_additional_consortium_subtypes.R",".R","7166","132","####################################################################### +# EPIGENETIC CLOCKS AND MULTIPLE CANCERS # +####################################################################### +# R version 4.0.2 (2020-06-22) +# Last modified: 12 October 2021 + +# This script runs two-sample MR for epigenetic clock acceleration +# measures and cancer in consortiums (additional subtypes) + +#---------------------------------------------------------------------# +# Housekeeping #---- +#---------------------------------------------------------------------# + +# Clear environment +rm(list=ls()) #Remove any existing objects in R + +# Set working directory +setwd(""your_working_directory"") + +# Install and load packages +if (!require(""pacman"")) install.packages(""pacman"") +pacman::p_load(""MRInstruments"", ""TwoSampleMR"", ""tidyverse"", ""dplyr"", ""ggpubr"", ""ggplot2"", ""ggforce"", ""data.table"", ""ggforestplot"", ""openxlsx"", ""readxl"") + +#---------------------------------------------------------------------# +# Read exposure #---- +#---------------------------------------------------------------------# + +exp_dat <- read.table(file = ""exp_data.txt"", header = T) + +#---------------------------------------------------------------------# +# Outcomes #---- +#---------------------------------------------------------------------# + +# Read BCAC data on breast cancer subtypes +out_func_bc <- function(name, beta, se) +{ + # Extract outcome SNPs matching the SNPs in the exposure dataset + outcome_var <- read.xlsx(""subtype_BC_raw.xlsx"", + colNames = T) %>% format_data(snps = exp_dat$SNP, + type = ""outcome"", + snp_col = ""SNP.iCOGs"", + beta_col = beta, + se_col = se, + effect_allele_col = ""Effect.Meta"", + other_allele_col = ""Baseline.Meta"", + chr_col = ""chr.iCOGs"", + pos_col = ""Position.iCOGs"", + eaf_col = ""EAFcontrols.iCOGs"", + pval_col = ""MTOP_p_value_meta"") + outcome_var$outcome <- name + return(outcome_var) +} + +luminal_A <- out_func_bc(""Luminal A"", ""Luminal_A_log_or_meta"", ""Luminal_A_se_meta"") +luminal_B <- out_func_bc(""Luminal B"", ""Luminal_B_log_or_meta"", ""Luminal_B_se_meta"") +luminal_B_HER2Neg <- out_func_bc(""Luminal B HER2 Negative"", ""Luminal_B_HER2Neg_log_or_meta"", ""Luminal_B_HER2Neg_se_meta"") +HER2_Enriched <- out_func_bc(""HER2 Enriched"", ""HER2_Enriched_log_or_meta"", ""HER2_Enriched_se_meta"") +Triple_Neg <- out_func_bc(""Triple Negative"", ""Triple_Neg_log_or_meta"", ""Triple_Neg_se_meta"") + + +#Read GECCO data on colorectal cancer subtypes +out_func_gecco_sub <- function(sheet, name) +{ + # Extract outcome SNPs matching the SNPs in the exposure dataset + outcome_var <- read_excel(""GECCO_all.xlsx"", sheet = sheet, col_names = T) + outcome_var$SNP <- exp_dat$SNP[match(outcome_var$Position, exp_dat$pos.exposure)] + outcome_var <- outcome_var %>% format_data(snps = exp_dat$SNP, + type = ""outcome"", + snp_col = ""SNP"", + beta_col = ""Effect"", + se_col = ""StdErr"", + effect_allele_col = ""Allele1"", + other_allele_col = ""Allele2"", + chr_col = ""Chr"", + pos_col = ""Position"", + eaf_col = ""Freq1"", + pval_col = ""P.value"") + outcome_var$outcome <- name + return(outcome_var) +} + + +colon <- out_func_gecco_sub(""colon"", ""Colon cancer"") +distal <- out_func_gecco_sub(""distal"", ""Distal colon cancer"") +female <- out_func_gecco_sub(""female"", ""Female colorectal cancer"") +male <- out_func_gecco_sub(""male"", ""Male colorectal cancer"") +proximal <- out_func_gecco_sub(""proximal"", ""Proximal colon cancer"") +rectal <- out_func_gecco_sub(""rectal"", ""Rectal cancer"") + +# Upload outcome datasets including proxies (these are already in two-sample MR format) +# CIMBA subtypes +BRCA1_BC_new_proxies <- read.table(""CIMBA_BRCA1_BC_replaced_proxies.txt"", header = T) +BRCA2_BC_new_proxies <- read.table(""CIMBA_BRCA2_BC_replaced_proxies.txt"", header = T) +BRCA1_OC_new_proxies <- read.table(""CIMBA_BRCA1_OC_replaced_proxies.txt"", header = T) +BRCA2_OC_new_proxies <- read.table(""CIMBA_BRCA2_OC_replaced_proxies.txt"", header = T) +# PRACTICAL subtypes +PRACT_adv_proxies <- read.table(""PRACTICAL_adv_replaced_proxies.txt"", header = T) +PRACT_age55_proxies <- read.table(""PRACTICAL_age55_replaced_proxies.txt"", header = T) +PRACT_caseonly_proxies <- read.table(""PRACTICAL_caseonly_replaced_proxies.txt"", header = T) +PRACT_gleason_proxies <- read.table(""PRACTICAL_gleason_replaced_proxies.txt"", header = T) +PRACT_highvslow_proxies <- read.table(""PRACTICAL_highvslow_replaced_proxies.txt"", header = T) +PRACT_highvslowint_proxies <- read.table(""PRACTICAL_highvslowint_replaced_proxies.txt"", header = T) + +# Combine outcomes +subtype_out_dat <- rbind(luminal_A, luminal_B, luminal_B_HER2Neg, HER2_Enriched, + Triple_Neg, BRCA1_BC_new_proxies, BRCA2_BC_new_proxies, BRCA1_OC_new_proxies, BRCA2_OC_new_proxies, + PRACT_adv_proxies, PRACT_age55_proxies, PRACT_caseonly_proxies, PRACT_gleason_proxies, + PRACT_highvslow_proxies, PRACT_highvslowint_proxies, colon, rectal, male, female, proximal, distal) + +#---------------------------------------------------------------------# +# Harmonisation #---- +#---------------------------------------------------------------------# + +# Harmonise exposure and outcome datasets +data_subtype <- harmonise_data( + exposure_dat = exp_dat, + outcome_dat = subtype_out_dat +) + +#---------------------------------------------------------------------# +# Results #---- +#---------------------------------------------------------------------# +#MR +results_subtype <- mr(data_subtype, method_list = c(""mr_ivw"", ""mr_egger_regression"", + ""mr_weighted_median"", ""mr_weighted_mode"")) + +#---------------------------------------------------------------------# +# Save results #---- +#---------------------------------------------------------------------# + +#write.table(results_subtype, ""results_subtypes.txt"", row.names = F) +","R" +"Epigenetics","fernandam93/epiclocks_cancer","5.2_create_metaanalysis_plots_colour.R",".R","5471","134","####################################################################### +# EPIGENETIC CLOCKS AND MULTIPLE CANCERS # +####################################################################### +# R version 4.0.2 (2020-06-22) +# Last modified: 11 October 2021 + +# This script creates a plot for the meta-analysis of two-sample MR results +# across UK Biobank, FinnGen and international consortiums +# This script uses the forestplot function to create colourful plots + +#---------------------------------------------------------------------# +# Housekeeping #---- +#---------------------------------------------------------------------# + +# Clear environment +rm(list=ls()) #Remove any existing objects in R + +# Set working directory +setwd(""your_working_directory"") + +if (!require(""pacman"")) install.packages(""pacman"") +pacman::p_load(""meta"", ""metafor"", ""openxlsx"", ""TwoSampleMR"", ""tidyverse"", ""dplyr"", ""ggpubr"", ""ggforestplot"", ""cowplot"") + +#---------------------------------------------------------------------# +# Load meta-analysis results #---- +#---------------------------------------------------------------------# + +results <- read.xlsx(""MA_clocks_incFDR.xlsx"") +GrimAge <- results[which(results$exposure==""GrimAge""),] +PhenoAge <- results[which(results$exposure==""PhenoAge""),] +Hannum <- results[which(results$exposure==""Hannum""),] +IEAA <- results[which(results$exposure==""IEAA""),] + +#---------------------------------------------------------------------# +# Format meta-analysis results #---- +#---------------------------------------------------------------------# + +cancers <- c('Breast cancer', 'Ovarian cancer', 'Prostate cancer', 'Lung cancer', 'Colorectal cancer') + +as.factor(GrimAge$outcome) +GrimAge$outcome <- factor(GrimAge$outcome, levels = cancers) +GrimAge <- arrange(GrimAge, outcome) + +as.factor(PhenoAge$outcome) +PhenoAge$outcome <- factor(PhenoAge$outcome, levels = cancers) +PhenoAge <- arrange(PhenoAge, outcome) + +as.factor(Hannum$outcome) +Hannum$outcome <- factor(Hannum$outcome, levels = cancers) +Hannum <- arrange(Hannum, outcome) + +as.factor(IEAA$outcome) +IEAA$outcome <- factor(IEAA$outcome, levels = cancers) +IEAA <- arrange(IEAA, outcome) + +#reorder methods +as.factor(GrimAge$method) +GrimAge$method <- factor(GrimAge$method, levels = c(""Weighted mode"", ""Weighted median"", + ""MR Egger"", ""Inverse variance weighted"")) +#reorder methods +as.factor(PhenoAge$method) +PhenoAge$method <- factor(PhenoAge$method, levels = c(""Weighted mode"", ""Weighted median"", + ""MR Egger"", ""Inverse variance weighted"")) +#reorder methods +as.factor(Hannum$method) +Hannum$method <- factor(Hannum$method, levels = c(""Weighted mode"", ""Weighted median"", + ""MR Egger"", ""Inverse variance weighted"")) +#reorder methods +as.factor(IEAA$method) +IEAA$method <- factor(IEAA$method, levels = c(""Weighted mode"", ""Weighted median"", + ""MR Egger"", ""Inverse variance weighted"")) + +#---------------------------------------------------------------------# +# Plot Function #---- +#---------------------------------------------------------------------# + +myforestplot <- function(df, title, xlab) +{ + x <- forestplot( + df = df[which(df$method!=""MR Egger""),], + estimate = b, # b and se have already been multiplied by 10 in the MA stage + se = se, + pvalue = pval, + name = outcome, + logodds = TRUE, + colour = method, + title = title, + xlab = xlab, + xlim= c(0.88,1.22) + ) + colours <- c(""#6DC6BD"", ""#2E7EBB"", ""#08306B"") + #colours <- c(""#3FBC73FF"", ""#238A8DFF"", ""#3A548CFF"", ""black"") + x <- x + scale_color_manual(values=colours) + #x <- x + scale_x_continuous(breaks = c(0.5, 1, 1.5, 2, 2.5, 3, 5)) + print(x) +} + +#---------------------------------------------------------------------# +# Forest plots #---- +#---------------------------------------------------------------------# + +#main analyses +GrimAge_MA <- myforestplot(GrimAge, ""GrimAge"", ""Odds ratio (95% CI) per 1 year increase in GrimAge acceleration"") +PhenoAge_MA <- myforestplot(PhenoAge, ""PhenoAge"", ""Odds ratio (95% CI) per 1 year increase in PhenoAge acceleration"") +Hannum_MA <- myforestplot(Hannum, ""HannumAge"", ""Odds ratio (95% CI) per 1 year increase in HannumAge acceleration"") +IEAA_MA <- myforestplot(IEAA, ""Intrinsic HorvathAge"", ""Odds ratio (95% CI) per 1 year increase in Intrinsic HorvathAge acceleration"") + + +#in one plot +comb_func <- function(A, B, C, D){ + plot.new() + par(mar=c(1,1,1,1), mgp=c(3,1,0)) + x <- ggarrange(A, B, C, D, labels=c('A', 'B', 'C', 'D'), + ncol = 2, nrow = 2, common.legend = T, hjust = -3, legend = ""bottom"") + print(x) +} + +all <- comb_func(GrimAge_MA, PhenoAge_MA, Hannum_MA, IEAA_MA) + +#---------------------------------------------------------------------# +# Save plot #---- +#---------------------------------------------------------------------# + +save_func2 <- function(file_name, plot_name) +{ + png(file_name, res=330, height=3000, width=5100) + print(plot_name) + dev.off() +} + +#save +save_func2('MA_all.png', all) + +","R" +"Epigenetics","fernandam93/epiclocks_cancer","5.3_create_plots_for_subtypes.R",".R","12425","243","####################################################################### +# EPIGENETIC CLOCKS AND MULTIPLE CANCERS # +####################################################################### +# R version 4.0.2 (2020-06-22) +# Last modified: 12 October 2021 + +# This script creates plots for the two-sample MR results +# for epigenetic age acceleration and cancer subtypes in international consortiums +# This script uses the forestplot function to create colourful plots + +#---------------------------------------------------------------------# +# Housekeeping #---- +#---------------------------------------------------------------------# + +# Clear environment +rm(list=ls()) #Remove any existing objects in R + +# Set working directory +setwd(""your_working_directory"") + +if (!require(""pacman"")) install.packages(""pacman"") +pacman::p_load(""MRInstruments"", ""TwoSampleMR"", ""tidyverse"", ""dplyr"", ""ggpubr"", ""ggplot2"", ""ggforce"", ""data.table"", ""ggforestplot"") + + +#---------------------------------------------------------------------# +# Read results #---- +#---------------------------------------------------------------------# + +results_IEU <- read.table(""results_IEU.txt"", header = T) +results_subtype <- read.table(""results_subtypes.txt"", header = T) +results_subtype <- results_subtype[which(results_subtype$outcome!=""Gleason Score""),] +results_IEU <- rbind(results_IEU, results_subtype) +#---------------------------------------------------------------------# +# Prepare for analyses #---- +#---------------------------------------------------------------------# + +#create groups for IEU outcomes +results_IEU$group <- ""Cancers"" +results_IEU$group[results_IEU$id.outcome==""ieu-a-1121""| results_IEU$id.outcome==""ieu-a-1122""| results_IEU$id.outcome==""ieu-a-1123""| results_IEU$id.outcome==""ieu-a-1124""| results_IEU$id.outcome==""ieu-a-1125""] <- ""Ovarian cancer subtypes"" +results_IEU$group[results_IEU$id.outcome==""ieu-a-1127""| results_IEU$id.outcome==""ieu-a-1128"" | results_IEU$outcome==""BRCA1 breast cancer""| results_IEU$outcome==""BRCA2 breast cancer"" | results_IEU$outcome==""Luminal B HER2 Negative"" | results_IEU$outcome==""Triple Negative"" | results_IEU$outcome==""Luminal A"" | results_IEU$outcome==""Luminal B"" | results_IEU$outcome==""HER2 Enriched""] <- ""Breast cancer subtypes"" +results_IEU$group[results_IEU$id.outcome==""ieu-a-967""| results_IEU$id.outcome==""ieu-a-965""] <- ""Lung cancer subtypes"" +results_IEU$group[results_IEU$outcome==""BRCA1 ovarian cancer""| results_IEU$outcome==""BRCA2 ovarian cancer""] <- ""Ovarian cancer subtypes"" +results_IEU$group[results_IEU$outcome==""Early onset prostate cancer""|results_IEU$outcome==""High risk prostate cancer (vs low and intermediate risk)"" | results_IEU$outcome==""Advanced prostate cancer"" | results_IEU$outcome==""High risk prostate cancer (vs low risk)"" | results_IEU$outcome==""Advanced prostate cancer (cases only)""] <- ""Prostate cancer subtypes"" +results_IEU$group[results_IEU$outcome==""Colon cancer""|results_IEU$outcome==""Rectal cancer"" | results_IEU$outcome==""Male colorectal cancer"" | results_IEU$outcome==""Female colorectal cancer"" | results_IEU$outcome==""Distal colon cancer"" | results_IEU$outcome==""Proximal colon cancer""] <- ""Colorectal cancer subtypes"" + +#split outcome so that id doesnt appear in plot +results_IEU <- split_outcome(results_IEU) + +results_IEU$outcome[results_IEU$outcome==""Breast cancer (Combined Oncoarray; iCOGS; GWAS meta analysis)""] <- ""Breast cancer"" +results_IEU$outcome[results_IEU$outcome==""ER+ Breast cancer (Combined Oncoarray; iCOGS; GWAS meta analysis)""] <- ""ER+"" +results_IEU$outcome[results_IEU$outcome==""ER- Breast cancer (Combined Oncoarray; iCOGS; GWAS meta analysis)""] <- ""ER-"" + +#rename subtypes so that they fit in plot +results_IEU$outcome[results_IEU$outcome==""High grade serous ovarian cancer""] <- ""High grade serous"" +results_IEU$outcome[results_IEU$outcome==""Low grade serous ovarian cancer""] <- ""Low grade serous"" +results_IEU$outcome[results_IEU$outcome==""Invasive mucinous ovarian cancer""] <- ""Invasive mucinous"" +results_IEU$outcome[results_IEU$outcome==""Clear cell ovarian cancer""] <- ""Clear cell"" +results_IEU$outcome[results_IEU$outcome==""Endometrioid ovarian cancer""] <- ""Endometrioid"" +results_IEU$outcome[results_IEU$outcome==""Lung adenocarcinoma""] <- ""Adenocarcinoma"" +results_IEU$outcome[results_IEU$outcome==""Squamous cell lung cancer""] <- ""Squamous cell"" +results_IEU$outcome[results_IEU$outcome==""High risk prostate cancer (vs low and intermediate risk)""] <- ""High risk (vs low and intermediate risk)"" +results_IEU$outcome[results_IEU$outcome==""High risk prostate cancer (vs low risk)""] <- ""High risk (vs low risk)"" +results_IEU$outcome[results_IEU$outcome==""Advanced prostate cancer (cases only)""] <- ""Advanced (cases only)"" +results_IEU$outcome[results_IEU$outcome==""Advanced prostate cancer""] <- ""Advanced"" +results_IEU$outcome[results_IEU$outcome==""Early onset prostate cancer""] <- ""Early onset"" + +# Reorder groups as factors +as.factor(results_IEU$group) +results_IEU$group <- factor(results_IEU$group, levels = c(""Cancers"", ""Breast cancer subtypes"", ""Ovarian cancer subtypes"", ""Prostate cancer subtypes"", ""Lung cancer subtypes"", ""Colorectal cancer subtypes"")) + +# Reorder outcomes as factors +as.factor(results_IEU$outcome) +results_IEU$outcome <- factor(results_IEU$outcome, levels = c(""Breast cancer"" ,""ER+"" , ""ER-"" , + ""Triple Negative"", ""Luminal B HER2 Negative"", + ""HER2 Enriched"", ""Luminal A"", ""Luminal B"", ""BRCA1 breast cancer"", + ""BRCA2 breast cancer"", + ""Ovarian cancer"", ""High grade serous"", + ""Low grade serous"" ,""Invasive mucinous"", + ""Clear cell"", ""Endometrioid"", + ""BRCA1 ovarian cancer"", ""BRCA2 ovarian cancer"", + ""Prostate cancer"", + ""Advanced"", + ""Advanced (cases only)"", + ""Early onset"", + ""High risk (vs low risk)"", + ""High risk (vs low and intermediate risk)"", + ""Adenocarcinoma"" , ""Lung cancer"" , + ""Squamous cell"", + ""Colorectal cancer"", + ""Colon cancer"", + ""Proximal colon cancer"", + ""Distal colon cancer"", + ""Rectal cancer"", + ""Male colorectal cancer"", + ""Female colorectal cancer"")) + +results_IEU <- arrange(results_IEU, outcome) + +# Reorder methods as factors +as.factor(results_IEU$method) +results_IEU$method <- factor(results_IEU$method, levels = c(""Weighted mode"", ""Weighted median"", ""MR Egger"", ""Inverse variance weighted"")) + + + +#---------------------------------------------------------------------# +# Forest function #---- +#---------------------------------------------------------------------# + +# Function for IVW results only +myforestplot <- function(df, exp_dataset, clock_label, xlab) +{ + x <- forestplot( + df = df[which(df$id.exposure==exp_dataset & df$method==""Inverse variance weighted""),], + estimate = b, + se = se, + pvalue = pval, + name = outcome, + logodds = T, + #colour = method, + title = clock_label, + xlab = xlab, + #xlim= c(0.5,1.5) + ) + + ggforce::facet_col( + facets = ~group, + scales = ""free_y"", + space = ""free"" + ) + #colours_BP <- c(""#FE7A25"", ""#FFCE41"", ""#00bfff"", ""#98C409"") + #x <- x + scale_color_manual(values=colours_BP) + #x <- x + scale_x_continuous(breaks = c(0.3, 1, 3, 5, 8, 10)) + print(x) +} + +# Function for sensitivity analyses and IVW MR +myforestplot_3 <- function(df, exp_dataset, clock_label, xlab) +{ + x <- forestplot( + df = df[which(df$id.exposure==exp_dataset & df$group!=""Cancers"" & df$method!=""MR Egger"" ),], + estimate = b, + se = se, + pvalue = pval, + name = outcome, + logodds = T, + colour = method, + title = clock_label, + xlab = xlab, + xlim= c(0.5,1.5) + ) + + ggforce::facet_col( + facets = ~group, + scales = ""free_y"", + space = ""free"" + ) + colours_BP <- c(""#6DC6BD"", ""#2E7EBB"", ""#08306B"") + x <- x + scale_color_manual(values=colours_BP) + x <- x + scale_x_continuous(breaks = c(0.50, 0.75, 1.00, 1.25, 1.5, 1.75, 2)) + print(x) +} + +# Function for prostate and colorectal cancer subtypes only +myforestplot_4 <- function(df, exp_dataset, clock_label, xlab) +{ + x <- forestplot( + df = df[which(df$id.exposure==exp_dataset & df$group!=""Cancers"" & df$group!=""Breast cancer subtypes"" & df$group!=""Lung cancer subtypes"" & df$group!=""Ovarian cancer subtypes"" & df$method!=""MR Egger"" ),], + estimate = b, + se = se, + pvalue = pval, + name = outcome, + logodds = T, + colour = method, + title = clock_label, + xlab = xlab, + xlim= c(0.5,1.5) + ) + + ggforce::facet_col( + facets = ~group, + scales = ""free_y"", + space = ""free"" + ) + colours_BP <- c(""#6DC6BD"", ""#2E7EBB"", ""#08306B"") + x <- x + scale_color_manual(values=colours_BP) + x <- x + scale_x_continuous(breaks = c(0.50, 0.75, 1.00, 1.25, 1.5, 1.75, 2)) + print(x) +} + +#---------------------------------------------------------------------# +# Forest plots #---- +#---------------------------------------------------------------------# + +# Create plots using forest plot functions above +p1 <- myforestplot(results_IEU, ""GrimAge"", ""GrimAge"", ""Odds ratio (95% CI)"") +p2 <- myforestplot(results_IEU, ""IEAA"", ""Intrinsic HorvathAge"", ""Odds ratio (95% CI)"") +p3 <- myforestplot(results_IEU, ""PhenoAge"", ""PhenoAge"", ""Odds ratio (95% CI)"") +p4 <- myforestplot(results_IEU, ""Hannum"", ""HannumAge"", ""Odds ratio (95% CI)"") + +p_grim <- myforestplot_3(results_IEU, ""GrimAge"", ""GrimAge"", ""Odds ratio (95% CI) per year increase in GrimAge acceleration"") +p_pheno <- myforestplot_3(results_IEU, ""PhenoAge"", ""PhenoAge"", ""Odds ratio (95% CI) per year increase in PhenoAge acceleration"") +p_hannum <- myforestplot_3(results_IEU, ""Hannum"", ""HannumAge"", ""Odds ratio (95% CI) per year increase in HannumAge acceleration"") +p_ieaa <- myforestplot_3(results_IEU, ""IEAA"", ""Intrinsic HorvathAge"", ""Odds ratio (95% CI) per year increase in Intrinsic HorvathAge acceleration"") + +p_grim2 <- myforestplot_4(results_IEU, ""GrimAge"", ""GrimAge"", ""Odds ratio (95% CI) per year increase in GrimAge acceleration"") +p_grim2 <- ggarrange(p_grim2, legend = ""bottom"") +p_grim2 + +# Combine plots +combine_func2 <- function(A, B){ + plot.new() + par(mar=c(1,1,1,1), mgp=c(3,1,0)) + x <- ggarrange(A, B, labels=c('A', 'B'), + ncol = 2, nrow = 1, common.legend = T, hjust = -3, legend = ""bottom"") + print(x) +} + +p_grim_pheno <- combine_func2(p_grim, p_pheno) +p_hannum_ieaa <- combine_func2(p_hannum, p_ieaa) + +# Save plots +save_func20 <- function(file_name, plot_name) +{ + png(file_name, res=300, height=5000, width=3000) + print(plot_name) + dev.off() +} +save_func20('subtype_consortia.png', p_grim) + +save_func2000 <- function(file_name, plot_name) +{ + png(file_name, res=330, height=3000, width=3000) + print(plot_name) + dev.off() +} +save_func2000('subtype_grim_prc_crc.png', p_grim2) + +save_func21 <- function(file_name, plot_name) +{ + png(file_name, res=300, height=5000, width=5000) + print(plot_name) + dev.off() +} +save_func21('subtype_grim_pheno.png', p_grim_pheno) +save_func21('subtype_hannum_ieaa.png', p_hannum_ieaa) +","R" +"Epigenetics","fernandam93/epiclocks_cancer","3.1_run_2SMR_for_FinnGen.R",".R","3321","66","####################################################################### +# EPIGENETIC CLOCKS AND MULTIPLE CANCERS # +####################################################################### +# R version 4.0.2 (2020-06-22) +# Last modified: 17 August 2021 + +# This script runs two-sample MR for epigenetic clock acceleration +# measures and cancer in FinnGen + +#---------------------------------------------------------------------# +# Housekeeping #---- +#---------------------------------------------------------------------# + +# Clear environment +rm(list=ls()) #Remove any existing objects in R + +# Set working directory +setwd(""your_working_directory"") + +if (!require(""pacman"")) install.packages(""pacman"") +pacman::p_load(""MRInstruments"", ""TwoSampleMR"", ""tidyverse"", ""dplyr"", ""ggpubr"", ""ggplot2"", ""ggforce"", ""data.table"", ""ggforestplot"", ""openxlsx"") + +#---------------------------------------------------------------------# +# Read exposure #---- +#---------------------------------------------------------------------# +# Read exposure dataset +exp_dat <- read.table(""exp_data.txt"", header = T) + +#---------------------------------------------------------------------# +# Outcomes #---- +#---------------------------------------------------------------------# + +# Upload outcome datasets including proxies (these are already in two-sample MR format) +breast_cancer_excall_proxies <- read.table(""finngen_breast_exallc_replaced_proxies.txt"", header = T) +ovarian_cancer_excall_proxies <- read.table(""finngen_ovarian_exallc_replaced_proxies.txt"", header = T) +prostate_cancer_excall_proxies <- read.table(""finngen_prostate_exallc_replaced_proxies.txt"", header = T) +lung_cancer_excall_proxies <- read.table(""finngen_lung_exallc_replaced_proxies.txt"", header = T) +colorectal_cancer_excall_proxies <- read.table(""finngen_colorectal_exallc_replaced_proxies.txt"", header = T) + +FINNGEN_out_dat <- rbind(breast_cancer_excall_proxies, ovarian_cancer_excall_proxies, + prostate_cancer_excall_proxies, lung_cancer_excall_proxies, + colorectal_cancer_excall_proxies) + +#---------------------------------------------------------------------# +# Harmonisation #---- +#---------------------------------------------------------------------# +# Harmonise exposure and outcome datasets +data_FINNGEN <- harmonise_data( + exposure_dat = exp_dat, + outcome_dat = FINNGEN_out_dat +) +#---------------------------------------------------------------------# +# Results #---- +#---------------------------------------------------------------------# +#MR +results_FINNGEN <- mr(data_FINNGEN, method_list = c(""mr_ivw"", ""mr_egger_regression"", + ""mr_weighted_median"", ""mr_weighted_mode"")) + +#---------------------------------------------------------------------# +# Save results #---- +#---------------------------------------------------------------------# + +#write.table(results_FINNGEN, ""results_FINNGEN.txt"", row.names = F) + + +","R" +"Epigenetics","fernandam93/epiclocks_cancer","3.2_run_2SMR_for_UKB.R",".R","4706","91","####################################################################### +# EPIGENETIC CLOCKS AND MULTIPLE CANCERS # +####################################################################### +# R version 4.0.2 (2020-06-22) +# Last modified: 17 August 2021 + +# This script runs two-sample MR for epigenetic clock acceleration +# measures and cancer in UK Biobank + +#---------------------------------------------------------------------# +# Housekeeping #---- +#---------------------------------------------------------------------# + +# Clear environment +rm(list=ls()) #Remove any existing objects in R + +# Set working directory +setwd(""your_working_directory"") + +if (!require(""pacman"")) install.packages(""pacman"") +pacman::p_load(""MRInstruments"", ""TwoSampleMR"", ""tidyverse"", ""dplyr"", ""ggpubr"", ""ggplot2"", ""ggforce"", ""data.table"", ""ggforestplot"", ""openxlsx"") + +#---------------------------------------------------------------------# +# Read exposure #---- +#---------------------------------------------------------------------# +#read exposure +exp_dat <- read.table(""data/exp_data.txt"", header = T) + +#---------------------------------------------------------------------# +# Outcomes #---- +#---------------------------------------------------------------------# + +# Function for UKB outcome datasets +out_func_UKB <- function(file, name) +{ + # Extract outcome SNPs matching the SNPs in the exposure dataset + outcome_var <- read.table(paste(""folder_containing_data"", file,"".txt"", sep = """"), + header = T) %>% format_data(snps = exp_dat$SNP, + type = ""outcome"", + snp_col = ""SNP"", + beta_col = ""beta"", + se_col = ""se"", + effect_allele_col = ""ALLELE1"", + other_allele_col = ""ALLELE0"", + chr_col = ""CHR"", + pos_col = ""GENPOS"", + eaf_col = ""A1FREQ"", + pval_col = ""P_BOLT_LMM_INF"", + ncase_col = ""ncase"", + ncontrol_col = ""ncontrol"") + outcome_var$outcome <- name + return(outcome_var) +} + +lung_cancer <- out_func_UKB(""lung_cancer_data"", ""lung cancer"") +lung_cancer_unadj <- out_func_UKB(""lung_cancer_unadj_data"", ""lung cancer unadjusted"") +ovarian_cancer <- out_func_UKB(""ovarian_cancer_data"", ""ovarian cancer"") +breast_cancer <- out_func_UKB(""breast_cancer_data"", ""breast cancer"") +prostate_cancer <- out_func_UKB(""prostate_cancer_data"", ""prostate cancer"") +colorectal_cancer <- out_func_UKB(""colorectal_cancer_data"", ""colorectal cancer"") +pan_cancer <- out_func_UKB(""pan_cancer_data"", ""pan cancer"") +pan_cancer_incC44 <- out_func_UKB(""pan_inclc44_cancer_data"", ""pan cancer inc C44"") + +# Combine outcome datasets +UKB_out_dat <- rbind(lung_cancer, lung_cancer_unadj, ovarian_cancer, breast_cancer, + prostate_cancer, colorectal_cancer, pan_cancer, pan_cancer_incC44) + +#---------------------------------------------------------------------# +# Harmonisation #---- +#---------------------------------------------------------------------# +# Harmonise exposure and outcome datasets +data_UKB <- harmonise_data( + exposure_dat = exp_dat, + outcome_dat = UKB_out_dat +) +#---------------------------------------------------------------------# +# Results #---- +#---------------------------------------------------------------------# +# Run two-sample MR +results_UKB <- mr(data_UKB, method_list = c(""mr_ivw"", ""mr_egger_regression"", + ""mr_weighted_median"", ""mr_weighted_mode"")) + +# NOTE: BOLT-LMM transformation was not required here, as the data had already been transformed when we obtained it + +#---------------------------------------------------------------------# +# Save results #---- +#---------------------------------------------------------------------# + +#write.table(results_UKB, ""results/results/results_UKB_new.txt"", row.names = F) + +","R" +"Epigenetics","fernandam93/epiclocks_cancer","1_create_exposure_datasets.R",".R","4984","127","####################################################################### +# EPIGENETIC CLOCKS AND MULTIPLE CANCERS # +####################################################################### +# R version 4.0.2 (2020-06-22) +# Last modified: 17 August 2021 + +# This script creates exposure datasets for epigenetic clock acceleration +# measures, which can later be used in two-sample MR analyses +# This script also estimates R2 and F-statistics for each of the exposures + +#---------------------------------------------------------------------# +# Housekeeping #---- +#---------------------------------------------------------------------# + +# Clear environment +rm(list=ls()) #Remove any existing objects in R + +# Set working directory +setwd(""your_working_directory"") + +# Load required packages +if (!require(""pacman"")) install.packages(""pacman"") +pacman::p_load(""MRInstruments"", ""TwoSampleMR"", ""tidyverse"", ""dplyr"", ""ggpubr"", ""ggplot2"", ""ggforce"", ""data.table"", ""ggforestplot"",""gtools"") + +#---------------------------------------------------------------------# +# Exposures #---- +#---------------------------------------------------------------------# +# Create function to extract GWAS significant SNPs and perform LD-clumping +# Output in two-sample MR format +# NOTE: this takes really long if run in RStudio +exposure_func <- function(data_name, file, SNP) { + x <- read.table(file = file, header = T) + x$pheno <- ""DNA methylation ageing"" + x <- format_data(x, type = ""exposure"", + phenotype_col = ""pheno"", + snp_col = SNP, + beta_col = ""Effect"", + se_col = ""SE"", + eaf_col = ""Freq1"", + effect_allele_col = ""A1"", + other_allele_col = ""A2"", + pval_col = ""P"", + samplesize_col = ""N"", + chr_col = ""chr"", + pos_col = ""bp"") + x$id.exposure <- data_name + x <- clump_data(x, clump_p1 = 5e-08, clump_p2 = 5e-08) +} + +# Apply function to raw epigenetic age acceleration datasets +GrimAge_exp_dat <- exposure_func(""GrimAge"",""GrimAge_EUR_summary_statistics.txt"", ""rsID"") +Hannum_exp_dat <- exposure_func(""Hannum"",""Hannum_EUR_summary_statistics.txt"", ""roblrsID"") +IEAA_exp_dat <- exposure_func(""IEAA"",""IEAA_EUR_summary_statistics.txt"", ""rsID"") +PhenoAge_exp_dat <- exposure_func(""PhenoAge"",""PhenoAge_EUR_summary_statistics.txt"", ""rsID"") + +#combine exposures +exp_dat <- rbind(GrimAge_exp_dat, Hannum_exp_dat, IEAA_exp_dat, PhenoAge_exp_dat) + +#save unique list of SNPs +#write.table(unique(exp_dat$SNP), ""SNP_list.txt"", row.names = F, col.names = F) + +#---------------------------------------------------------------------# +# R2 and F-statistic #---- +#---------------------------------------------------------------------# + +# Calculate R2 and F statistics for each exposure dataset +#method 1 +exp_dat$r2 <- (2 * (exp_dat$beta.exposure^2) * exp_dat$eaf.exposure * (1 - exp_dat$eaf.exposure)) / + (2 * (exp_dat$beta.exposure^2) * exp_dat$eaf.exposure * (1 - exp_dat$eaf.exposure) + + 2 * exp_dat$samplesize.exposure * exp_dat$eaf.exposure * + (1 - exp_dat$eaf.exposure) * exp_dat$se.exposure^2) +exp_dat$F <- exp_dat$r2 * (exp_dat$samplesize.exposure - 2) / (1 - exp_dat$r2) +#method 2 +# exp_dat$F_stat <- exp_dat$beta.exposure^2 / exp_dat$se.exposure^2 +# exp_dat$R2_stat <- exp_dat$F_stat/(exp_dat$samplesize.exposure-2+exp_dat$F_stat) + +# Calculate total R2 for each exposure dataset +r2_func <- function(id) +{ + x <- exp_dat[which(exp_dat$id.exposure==id),] + sum(x$r2, na.rm = T) +} + +variance_GrimAge <- r2_func(""GrimAge"") # 0.47% +variance_Hannum <- r2_func(""Hannum"") # 1.48% +variance_IEAA <- r2_func(""IEAA"") # 4.41% +variance_PhenoAge <- r2_func(""PhenoAge"") #1.86% + +# Calculate minimum F-statistic for each exposure dataset +Fmin_func <- function(id) +{ + x <- exp_dat[which(exp_dat$id.exposure==id),] + min(x$F, na.rm = T) +} + +Fmin_GrimAge <- Fmin_func(""GrimAge"") # 31 +Fmin_Hannum <- Fmin_func(""Hannum"") # 31 +Fmin_IEAA <- Fmin_func(""IEAA"") # 31 +Fmin_PhenoAge <- Fmin_func(""PhenoAge"") # 32 + +# Calculate maximum F-statistic for each exposure dataset +Fmax_func <- function(id) +{ + x <- exp_dat[which(exp_dat$id.exposure==id),] + max(x$F, na.rm = T) +} + +Fmax_GrimAge <- Fmax_func(""GrimAge"") # 45 +Fmax_Hannum <- Fmax_func(""Hannum"") # 99 +Fmax_IEAA <- Fmax_func(""IEAA"") # 240 +Fmax_PhenoAge <- Fmax_func(""PhenoAge"") # 89 + +# Calculate median F-statistic for each exposure dataset +Fmedian_func <- function(id) +{ + x <- exp_dat[which(exp_dat$id.exposure==id),] + median(x$F, na.rm = T) +} + +Fmedian_GrimAge <- Fmedian_func(""GrimAge"") # 36 +Fmedian_Hannum <- Fmedian_func(""Hannum"") # 38 +Fmedian_IEAA <- Fmedian_func(""IEAA"") # 47 +Fmedian_PhenoAge <- Fmedian_func(""PhenoAge"") # 45 + +#save +#write.table(exp_dat, ""exp_data.txt"", row.names = F) +","R" +"Epigenetics","fernandam93/epiclocks_cancer","5.5_create_ldsc_plots.R",".R","2169","57","####################################################################### +# EPIGENETIC CLOCKS AND MULTIPLE CANCERS # +####################################################################### +# R version 4.0.2 (2020-06-22) +# Last modified: 14 October 2021 + +# This script creates a figure for LD score regression results +# for epigenetic age acceleration and cancer in international consortiums, +# UK Biobank and FinnGen + +#---------------------------------------------------------------------# +# Housekeeping #---- +#---------------------------------------------------------------------# + +# Clear environment +rm(list=ls()) #Remove any existing objects in R + +# Set working directory +setwd(""your_working_directory"") + +library(""openxlsx"") + +#---------------------------------------------------------------------# +# LD Score plots #---- +#---------------------------------------------------------------------# + +# Read results stored in an xlsx file (sheet ""rg"" contains genetic correlations and sheet ""p"" contains p-values) +rg <- as.matrix(read.xlsx(""ldsc_results_clocks_cancers.xlsx"", sheet = ""rg"", colNames = T, rowNames = T)) +p<- as.matrix(read.xlsx(""ldsc_results_clocks_cancers.xlsx"", sheet = ""p"", colNames = T, rowNames = T)) + +# Set colours +col2 <- colorRampPalette(c('firebrick3', 'white', 'deepskyblue3')) + +# Create plot +corrplot::corrplot(rg, method = ""color"", p.mat = p, is.corr = F, insig = ""label_sig"", + na.label = ""-"", + tl.col = ""black"", tl.cex = 0.8, tl.srt = 45, + #addCoef.col = ""black"", + number.cex = 0.8, sig.level = c(0.001, 0.01, 0.05), cl.ratio = 0.2, col = col2(37), + pch.col = 'black', pch.cex = 1.5, #cl.pos = ""n"", + outline = ""black"", + mar = c(1,0,0,4), + cl.align.text = ""l"") + +m <- recordPlot() + +m + +# Save +save_func_MA <- function(file_name, plot_name) +{ + png(file_name, res=330, height=2500, width=2100) + print(plot_name) + dev.off() +} +save_func_MA('ldsc.png', m) +","R" +"Epigenetics","fernandam93/epiclocks_cancer","2.3_find_LD_proxies_for_CIMBA_subtypes.R",".R","15652","238","#################################################################################### +# EPIGENETIC CLOCKS AND MULTIPLE CANCERS +#################################################################################### +# R version 4.0.2 (2020-06-22) +# Last modified: 17 August 2021 + +# This script finds LD-proxies for cancer subtypes in CIMBA, which can then be +# used in two-sample MR analyses +# Output in two-sample MR format + +#---------------------------------------------------------------------# +# Housekeeping #---- +#---------------------------------------------------------------------# + +# Clear environment +rm(list=ls()) #Remove any existing objects in R + +# Set working directory +setwd(""your_working_directory"") + +if (!require(""pacman"")) install.packages(""pacman"") +pacman::p_load(""MRInstruments"", ""TwoSampleMR"", ""tidyverse"", ""dplyr"", ""ggpubr"", ""ggplot2"", ""ggforce"", ""data.table"", ""ggforestplot"",""gtools"", ""LDlinkR"") + +#---------------------------------------------------------------------# +# Read exp and out datasets #---- +#---------------------------------------------------------------------# + +# Read exposure +exp_dat <- read.table(""exp_data.txt"", header = T) + +#Function to read outcome +out_func_cimba2 <- function(BRCA, name, beta, se, p) +{ + # Extract outcome SNPs matching the SNPs in the exposure dataset + outcome_var <- read.table(paste(""CIMBA_"", BRCA, "".txt"", sep = """"), + header = T) %>% format_data(snps = exp_dat$SNP, + type = ""outcome"", + snp_col = ""rs_id"", + chr_col = ""chr"", + pos_col = ""position"", + beta_col = beta, + se_col = se, + effect_allele_col = ""onco_icogs_effect"", + other_allele_col = ""onco_icogs_baseline"", + eaf_col = ""onco_icogs_bc_freq"", + pval_col = p) + outcome_var$outcome <- name + return(outcome_var) +} + +# Read CIMBA outcomes +BRCA1_BC_new <- out_func_cimba2(""BRCA1"", ""BRCA1 breast cancer"", ""onco_icogs_bc_effect"", ""onco_icogs_bc_se"", ""onco_icogs_bc_pval"") +BRCA2_BC_new <- out_func_cimba2(""BRCA2"", ""BRCA2 breast cancer"", ""onco_icogs_bc_effect"", ""onco_icogs_bc_se"", ""onco_icogs_bc_pval"") +BRCA1_OC_new <- out_func_cimba2(""BRCA1"", ""BRCA1 ovarian cancer"", ""onco_icogs_oc_effect"", ""onco_icogs_oc_se"", ""onco_icogs_oc_pval"") +BRCA2_OC_new <- out_func_cimba2(""BRCA2"", ""BRCA2 ovarian cancer"", ""onco_icogs_oc_effect"", ""onco_icogs_oc_se"", ""onco_icogs_oc_pval"") + +#---------------------------------------------------------------------# +# Identify SNPs that need proxies #---- +#---------------------------------------------------------------------# + +# Function to find list of snps in exposure dataset that are missing from the outcome dataset +find_missing_SNP <- function(out_dat) { + snps_need_proxy <- subset(exp_dat, !(exp_dat$SNP %in% out_dat$SNP)) +} + +s <- find_missing_SNP(BRCA1_BC_new) + +count(s) #check how many snps are in list +s$SNP #see list of snps +s[1,1] #see snp missing n#1 +s[2,1] #see snp missing n#2 +s[3,1] #see snp missing n#3 +s[4,1] #see snp missing n#4 +s[5,1] #see snp missing n#4 + +#---------------------------------------------------------------------# +# Find proxies for these snps #---- +#---------------------------------------------------------------------# + +#Function to find LD proxy using LDLINK +find_LD_proxy <- function(snps_need_proxy) { + proxy <- (LDproxy(snps_need_proxy[1,1], ""EUR"", ""r2"", token = Sys.getenv(""LDLINK_TOKEN""), file = F))[c(1,4),] + proxy$original <- snps_need_proxy[1,1] + proxy2 <- (LDproxy(snps_need_proxy[2,1], ""EUR"", ""r2"", token = Sys.getenv(""LDLINK_TOKEN""), file = F))[c(1,3),] + proxy2$original <- snps_need_proxy[2,1] + proxy3 <- (LDproxy(snps_need_proxy[3,1], ""EUR"", ""r2"", token = Sys.getenv(""LDLINK_TOKEN""), file = F))[1:2,] + proxy3$original <- snps_need_proxy[3,1] + proxy4 <- (LDproxy(snps_need_proxy[4,1], ""EUR"", ""r2"", token = Sys.getenv(""LDLINK_TOKEN""), file = F))[c(1,9),] + proxy4$original <- snps_need_proxy[4,1] + proxy5 <- (LDproxy(snps_need_proxy[5,1], ""EUR"", ""r2"", token = Sys.getenv(""LDLINK_TOKEN""), file = F))[1:2,] + proxy5$original <- snps_need_proxy[5,1] + proxies <- rbind(proxy, proxy2, proxy3, proxy4, proxy5) + proxies + # we could change number of proxies we want to find +} + +a <- find_LD_proxy(s) +a[2,1] #see proxy snp (for snp missing n#1) +a[4,1] #see proxy snp (for snp missing n#2) +a[6,1] #see proxy snp (for snp missing n#3) +a[8,1] #see proxy snp (for snp missing n#4) +a[10,1] #see proxy snp (for snp missing n#5) + +# We need to make sure the identified proxy SNPs are available in outcome dataset before continuing +# Here, we used the terminal to do this (e.g., zcat finngen_R5_C3_BREAST_EXALLC.gz | grep rs290794) +# If SNPs aren't available, you need to find the next best proxy for the missing SNP + + +# List all SNPs included in the outcome dataset, including proxies for those that are missing +# This can then be used to extract data related to these SNPs using grep in the terminal +list_all_snps<- function(out_dat, proxy) { + exp_snps <- out_dat$SNP + proxy_snp <- proxy[c(2,4,6,8,10),1] + all_snps <- c(exp_snps, proxy_snp) +} +all <- list_all_snps(BRCA1_BC_new, a) + +write.table(all, ""CIMBA_SNP_list_inc_proxies.txt"", quote = F, sep = "" "", col.names = F, row.names = F) + +#---------------------------------------------------------------------# +# NOW USE THE TERMINAL TO EXTRACT DATA FOR ALL SNPS #---- +#---------------------------------------------------------------------# +#Example: +#zcat finngen_R5_C3_BRONCHUS_LUNG_EXALLC.gz | grep -w -F -f FINNGEN_SNP_list_inc_proxies.txt -e rsids > finngen_lung_exallc_inc_proxies.txt + + # Use nano finngen_lung_exallc_inc_proxies.txt to remove hashtag in column names before using the grep command + +#---------------------------------------------------------------------# +# Back to R -> Format data first #---- +#---------------------------------------------------------------------# +# Function to format data (two-sample MR format) +# Here, it is important to use the format_data function using the SNP list including proxies, not the original SNP list +out_func_CIMBA_proxies <- function(BRCA, name, beta, se, p) +{ + # Extract outcome SNPs matching the SNPs in the exposure dataset + outcome_var <- read.table(paste(""CIMBA_"", BRCA,""_inc_proxies.txt"", sep = """"), + header = T) %>% format_data(snps = all, + type = ""outcome"", + snp_col = ""rs_id"", + chr_col = ""chr"", + pos_col = ""position"", + beta_col = beta, + se_col = se, + effect_allele_col = ""onco_icogs_effect"", + other_allele_col = ""onco_icogs_baseline"", + eaf_col = ""onco_icogs_bc_freq"", + pval_col = p) + outcome_var$outcome <- name + return(outcome_var) +} + +BRCA1_BC_proxies <- out_func_CIMBA_proxies(""BRCA1"", ""BRCA1 breast cancer"", ""onco_icogs_bc_effect"", ""onco_icogs_bc_se"", ""onco_icogs_bc_pval"") +BRCA2_BC_proxies <- out_func_CIMBA_proxies(""BRCA2"", ""BRCA2 breast cancer"", ""onco_icogs_bc_effect"", ""onco_icogs_bc_se"", ""onco_icogs_bc_pval"") +BRCA1_OC_proxies <- out_func_CIMBA_proxies(""BRCA1"", ""BRCA1 ovarian cancer"", ""onco_icogs_oc_effect"", ""onco_icogs_oc_se"", ""onco_icogs_oc_pval"") +BRCA2_OC_proxies <- out_func_CIMBA_proxies(""BRCA2"", ""BRCA2 ovarian cancer"", ""onco_icogs_oc_effect"", ""onco_icogs_oc_se"", ""onco_icogs_oc_pval"") + +# Find list of SNPs in the proxy dataset that are missing from the outcome dataset, +# just to make sure that we aren't missing any SNPs before moving on to the next step +find_missing_SNP_proxy <- function(out_dat) { + snps_need_proxy <- subset(as.data.frame(all), !(all %in% out_dat$SNP)) +} + +s2 <- find_missing_SNP_proxy(BRCA1_BC_proxies) + +#---------------------------------------------------------------------# +# Modify outcome dataset so that proxy SNP ""rsid"" is replaced by the original SNP ""rsid"" #---- +#---------------------------------------------------------------------# +# Function to add columns for the replacement data to the proxy dataset +replacement_cols_proxy <- function(proxy) { + proxy <- proxy %>% separate(Coord, c(""chr"",""pos""), sep = ""([:])"") + proxy$chr <- gsub(""chr"", """", proxy$chr) + proxy <- proxy %>% separate(Correlated_Alleles, c(""A1_original"",""A1_proxy"", ""A2_original"", ""A2_proxy""), sep = ""([,=])"") + proxy$original_chr <- c(proxy[1,2], proxy[1,2], proxy[3,2], proxy[3,2], proxy[5,2], proxy[5,2], proxy[7,2], proxy[7,2], proxy[9,2], proxy[9,2]) + proxy$original_pos <- c(proxy[1,3], proxy[1,3], proxy[3,3], proxy[3,3], proxy[5,3], proxy[5,3], proxy[7,3], proxy[7,3], proxy[9,3], proxy[9,3]) + proxy + +} + +b <- replacement_cols_proxy(a) + +# Function to replace proxy SNP details by original SNP details +replace_proxy_by_original <- function(proxy, out_dat_proxies) { + #proxy 1 + out_dat_proxies$effect_allele.outcome[out_dat_proxies$SNP==proxy[2,1] & out_dat_proxies$effect_allele.outcome == proxy[2,10]] <- proxy[2,9] #A1 effect allele + out_dat_proxies$effect_allele.outcome[out_dat_proxies$SNP==proxy[2,1] & out_dat_proxies$effect_allele.outcome == proxy[2,12]] <- proxy[2,11] #A1 effect allele + out_dat_proxies$other_allele.outcome[out_dat_proxies$SNP==proxy[2,1] & out_dat_proxies$other_allele.outcome == proxy[2,10]] <- proxy[2,9] #A2 other allele + out_dat_proxies$other_allele.outcome[out_dat_proxies$SNP==proxy[2,1] & out_dat_proxies$other_allele.outcome == proxy[2,12]] <- proxy[2,11] #A2 other allele + out_dat_proxies$chr.outcome[out_dat_proxies$SNP==proxy[2,1]] <- proxy[2,16] #change chr + out_dat_proxies$pos.outcome[out_dat_proxies$SNP==proxy[2,1]] <- proxy[2,17] #change pos + out_dat_proxies$SNP[out_dat_proxies$SNP==proxy[2,1]] <- proxy[2,15] #change rsid + #proxy 2 + out_dat_proxies$effect_allele.outcome[out_dat_proxies$SNP==proxy[4,1] & out_dat_proxies$effect_allele.outcome == proxy[4,10]] <- proxy[4,9] #A1 effect allele + out_dat_proxies$effect_allele.outcome[out_dat_proxies$SNP==proxy[4,1] & out_dat_proxies$effect_allele.outcome == proxy[4,12]] <- proxy[4,11] #A1 effect allele + out_dat_proxies$other_allele.outcome[out_dat_proxies$SNP==proxy[4,1] & out_dat_proxies$other_allele.outcome == proxy[4,10]] <- proxy[4,9] #A2 other allele + out_dat_proxies$other_allele.outcome[out_dat_proxies$SNP==proxy[4,1] & out_dat_proxies$other_allele.outcome == proxy[4,12]] <- proxy[4,11] #A2 other allele + out_dat_proxies$chr.outcome[out_dat_proxies$SNP==proxy[4,1]] <- proxy[4,16] #change chr + out_dat_proxies$pos.outcome[out_dat_proxies$SNP==proxy[4,1]] <- proxy[4,17] #change pos + out_dat_proxies$SNP[out_dat_proxies$SNP==proxy[4,1]] <- proxy[4,15] #change rsid + #proxy 3 + out_dat_proxies$effect_allele.outcome[out_dat_proxies$SNP==proxy[6,1] & out_dat_proxies$effect_allele.outcome == proxy[6,10]] <- proxy[6,9] #A1 effect allele + out_dat_proxies$effect_allele.outcome[out_dat_proxies$SNP==proxy[6,1] & out_dat_proxies$effect_allele.outcome == proxy[6,12]] <- proxy[6,11] #A1 effect allele + out_dat_proxies$other_allele.outcome[out_dat_proxies$SNP==proxy[6,1] & out_dat_proxies$other_allele.outcome == proxy[6,10]] <- proxy[6,9] #A2 other allele + out_dat_proxies$other_allele.outcome[out_dat_proxies$SNP==proxy[6,1] & out_dat_proxies$other_allele.outcome == proxy[6,12]] <- proxy[6,11] #A2 other allele + out_dat_proxies$chr.outcome[out_dat_proxies$SNP==proxy[6,1]] <- proxy[6,16] #change chr + out_dat_proxies$pos.outcome[out_dat_proxies$SNP==proxy[6,1]] <- proxy[6,17] #change pos + out_dat_proxies$SNP[out_dat_proxies$SNP==proxy[6,1]] <- proxy[6,15] #change rsid + #proxy 4 + out_dat_proxies$effect_allele.outcome[out_dat_proxies$SNP==proxy[8,1] & out_dat_proxies$effect_allele.outcome == proxy[8,10]] <- proxy[8,9] #A1 effect allele + out_dat_proxies$effect_allele.outcome[out_dat_proxies$SNP==proxy[8,1] & out_dat_proxies$effect_allele.outcome == proxy[8,12]] <- proxy[8,11] #A1 effect allele + out_dat_proxies$other_allele.outcome[out_dat_proxies$SNP==proxy[8,1] & out_dat_proxies$other_allele.outcome == proxy[8,10]] <- proxy[8,9] #A2 other allele + out_dat_proxies$other_allele.outcome[out_dat_proxies$SNP==proxy[8,1] & out_dat_proxies$other_allele.outcome == proxy[8,12]] <- proxy[8,11] #A2 other allele + out_dat_proxies$chr.outcome[out_dat_proxies$SNP==proxy[8,1]] <- proxy[8,16] #change chr + out_dat_proxies$pos.outcome[out_dat_proxies$SNP==proxy[8,1]] <- proxy[8,17] #change pos + out_dat_proxies$SNP[out_dat_proxies$SNP==proxy[8,1]] <- proxy[8,15] #change rsid + out_dat_proxies + #proxy 5 + out_dat_proxies$effect_allele.outcome[out_dat_proxies$SNP==proxy[10,1] & out_dat_proxies$effect_allele.outcome == proxy[10,10]] <- proxy[10,9] #A1 effect allele + out_dat_proxies$effect_allele.outcome[out_dat_proxies$SNP==proxy[10,1] & out_dat_proxies$effect_allele.outcome == proxy[10,12]] <- proxy[10,11] #A1 effect allele + out_dat_proxies$other_allele.outcome[out_dat_proxies$SNP==proxy[10,1] & out_dat_proxies$other_allele.outcome == proxy[10,10]] <- proxy[10,9] #A2 other allele + out_dat_proxies$other_allele.outcome[out_dat_proxies$SNP==proxy[10,1] & out_dat_proxies$other_allele.outcome == proxy[10,12]] <- proxy[10,11] #A2 other allele + out_dat_proxies$chr.outcome[out_dat_proxies$SNP==proxy[10,1]] <- proxy[10,16] #change chr + out_dat_proxies$pos.outcome[out_dat_proxies$SNP==proxy[10,1]] <- proxy[10,17] #change pos + out_dat_proxies$SNP[out_dat_proxies$SNP==proxy[10,1]] <- proxy[10,15] #change rsid + out_dat_proxies +} + +BRCA1_BC_new2 <- replace_proxy_by_original(b, BRCA1_BC_proxies) +BRCA2_BC_new2 <- replace_proxy_by_original(b, BRCA2_BC_proxies) +BRCA1_OC_new2 <- replace_proxy_by_original(b, BRCA1_OC_proxies) +BRCA2_OC_new2 <- replace_proxy_by_original(b, BRCA2_OC_proxies) + + +write.table(BRCA1_BC_new2, ""CIMBA_BRCA1_BC_replaced_proxies.txt"", sep = "" "", row.names = F, col.names = T) +write.table(BRCA2_BC_new2, ""CIMBA_BRCA2_BC_replaced_proxies.txt"", sep = "" "", row.names = F, col.names = T) +write.table(BRCA1_OC_new2, ""CIMBA_BRCA1_OC_replaced_proxies.txt"", sep = "" "", row.names = F, col.names = T) +write.table(BRCA2_OC_new2, ""CIMBA_BRCA2_OC_replaced_proxies.txt"", sep = "" "", row.names = F, col.names = T) + +","R" +"Epigenetics","fernandam93/epiclocks_cancer","4_run_metaanalysis.R",".R","11424","196","####################################################################### +# EPIGENETIC CLOCKS AND MULTIPLE CANCERS # +####################################################################### +# R version 4.0.2 (2020-06-22) +# Last modified: 11 October 2021 + +# This script runs a meta-analysis of two-sample MR results +# across UK Biobank, FinnGen and international consortiums +# This script also applies an FDR correction to main meta-analysed IVW results + +#---------------------------------------------------------------------# +# Housekeeping #---- +#---------------------------------------------------------------------# + +# Clear environment +rm(list=ls()) #Remove any existing objects in R + +# Set working directory +setwd(""your_working_directory"") + +if (!require(""pacman"")) install.packages(""pacman"") +pacman::p_load(""meta"", ""metafor"", ""openxlsx"", ""TwoSampleMR"", ""tidyverse"", ""dplyr"", ""ggpubr"", ""ggforestplot"", ""cowplot"") + +#---------------------------------------------------------------------# +# Load two-sample MR results #---- +#---------------------------------------------------------------------# + +# Function to load MR results +load_data_func <- function(file_name) +{ + results <- read.table(file = file_name, header = T) + results <- split_outcome(results) # to keep the Y axis label clean we exclude the exposure ID labels from the exposure column +} + +results_IEU <- load_data_func(""results_IEU.txt"") +results_UKB <- load_data_func(""results_UKB_new.txt"") +results_FINNGEN <- load_data_func(""results_FINNGEN.txt"") + +#---------------------------------------------------------------------# +# Format MR results #---- +#---------------------------------------------------------------------# + +# Add new column with study name +results_IEU$study[results_IEU$outcome==""Colorectal cancer""] <- ""GECCO"" +results_IEU$study[results_IEU$outcome==""Lung cancer""] <- ""ILCCO"" +results_IEU$study[results_IEU$outcome==""Breast cancer (Combined Oncoarray; iCOGS; GWAS meta analysis)""] <- ""BCAC"" +results_IEU$study[results_IEU$outcome==""Ovarian cancer""] <- ""OCAC"" +results_IEU$study[results_IEU$outcome==""Prostate cancer""] <- ""PRACTICAL"" +results_UKB$study <- ""UK Biobank"" +results_FINNGEN$study <- ""FinnGen"" + +# Rename IEU results and filter to only include some of them in the meta-analysis +results_IEU$outcome[results_IEU$outcome==""Breast cancer (Combined Oncoarray; iCOGS; GWAS meta analysis)""] <- ""Breast cancer"" +results_IEU <- results_IEU[which(results_IEU$outcome=='Breast cancer' | results_IEU$outcome=='Ovarian cancer' | results_IEU$outcome=='Prostate cancer' | results_IEU$outcome=='Lung cancer' | results_IEU$outcome=='Colorectal cancer'),] + +# Rename UKB results and filter to only include some of them in the meta-analysis +results_UKB$outcome[results_UKB$outcome==""breast cancer""] <- 'Breast cancer' +results_UKB$outcome[results_UKB$outcome==""ovarian cancer""] <- 'Ovarian cancer' +results_UKB$outcome[results_UKB$outcome==""prostate cancer""] <- 'Prostate cancer' +results_UKB$outcome[results_UKB$outcome==""lung cancer unadjusted""] <- 'Lung cancer' +results_UKB$outcome[results_UKB$outcome==""colorectal cancer""] <- 'Colorectal cancer' +results_UKB <- results_UKB[which(results_UKB$outcome=='Breast cancer' | results_UKB$outcome=='Ovarian cancer' | results_UKB$outcome=='Prostate cancer' | results_UKB$outcome=='Lung cancer' | results_UKB$outcome=='Colorectal cancer'),] + +# Rename FinnGen results and filter to only include some of them in the meta-analysis +results_FINNGEN$outcome[results_FINNGEN$outcome==""breast cancer (excluding cancer in controls)""] <- 'Breast cancer' +results_FINNGEN$outcome[results_FINNGEN$outcome==""ovarian cancer (excluding cancer in controls)""] <- 'Ovarian cancer' +results_FINNGEN$outcome[results_FINNGEN$outcome==""prostate cancer (excluding cancer in controls)""] <- 'Prostate cancer' +results_FINNGEN$outcome[results_FINNGEN$outcome==""lung cancer (excluding cancer in controls)""] <- 'Lung cancer' +results_FINNGEN$outcome[results_FINNGEN$outcome==""colorectal cancer (excluding cancer in controls)""] <- 'Colorectal cancer' +results_FINNGEN <- results_FINNGEN[which(results_FINNGEN$outcome=='Breast cancer' | results_FINNGEN$outcome=='Ovarian cancer' | results_FINNGEN$outcome=='Prostate cancer' | results_FINNGEN$outcome=='Lung cancer' | results_FINNGEN$outcome=='Colorectal cancer'),] + +# Combine results +results <- rbind(results_IEU, results_UKB, results_FINNGEN) + +#---------------------------------------------------------------------# +# Run meta-analysis #---- +#---------------------------------------------------------------------# + +# Function to run a fixed effect meta-analysis +meta_func <- function(method_varname, exp_varname, out1, out2="""", out3="""", out4="""", + out5="""", out6="""", out7="""", out8="""", out9="""", out10="""", + out11="""", out12="""", out13="""", out14="""", out15="""", + out16="""", out17="""", out18="""", out19="""", out20="""", out21="""") +{ + input <- results[which(results$method==method_varname),] + input <- input[which(input$id.exposure==exp_varname),] + input <- input[which(input$outcome==out1 | input$outcome==out2 | input$outcome==out3 | + input$outcome==out4 | input$outcome==out5 | input$outcome==out6 | + input$outcome==out7 | input$outcome==out8 | input$outcome==out9 | + input$outcome==out10 | input$outcome==out11 | input$outcome==out12 | + input$outcome==out13 | input$outcome==out14 | input$outcome==out15 | + input$outcome==out16 | input$outcome==out17 | input$outcome==out18 | + input$outcome==out19 | input$outcome==out20 | input$outcome==out21),] + #meta-analysis + a <- metagen(TE = b, seTE = se, data = input, + studlab = paste(study), sm = ""OR"", + hakn = FALSE, byvar = c(outcome), + method.tau=""DL"", comb.fixed = T, comb.random = F, exclude = id.outcome %in% c(""J2M7ze"")) #excluding colorectal cancer in UKB from MA + print(a) + + #extract values from meta output + TE.tibble <- as_tibble(a$TE.fixed.w) + se.tibble <- as_tibble(a$seTE.fixed.w) + p.tibble <- as_tibble(a$pval.fixed.w) + bylevs.tibble <- as_tibble(a$bylevs) + #combine tibbles and change column names + tibble <- cbind(TE.tibble, se.tibble, p.tibble, bylevs.tibble) + colnames(tibble) <- c(""b"", ""se"", ""pval"", ""outcome"") + #add columns for exposure and method + tibble$exposure <- exp_varname + tibble$method <- method_varname + tibble + +} + +#IVW +IVW_GrimAge <- meta_func(""Inverse variance weighted"", ""GrimAge"", ""Breast cancer"", ""Ovarian cancer"", ""Prostate cancer"", + ""Lung cancer"", ""Colorectal cancer"") +IVW_PhenoAge <- meta_func(""Inverse variance weighted"", ""PhenoAge"", ""Breast cancer"", ""Ovarian cancer"", ""Prostate cancer"", + ""Lung cancer"", ""Colorectal cancer"") +IVW_Hannum <- meta_func(""Inverse variance weighted"", ""Hannum"", ""Breast cancer"", ""Ovarian cancer"", ""Prostate cancer"", + ""Lung cancer"", ""Colorectal cancer"") +IVW_IEAA <- meta_func(""Inverse variance weighted"", ""IEAA"", ""Breast cancer"", ""Ovarian cancer"", ""Prostate cancer"", + ""Lung cancer"", ""Colorectal cancer"") + + +#Egger +egger_GrimAge <- meta_func(""MR Egger"", ""GrimAge"", ""Breast cancer"", ""Ovarian cancer"", ""Prostate cancer"", + ""Lung cancer"", ""Colorectal cancer"") +egger_PhenoAge <- meta_func(""MR Egger"", ""PhenoAge"", ""Breast cancer"", ""Ovarian cancer"", ""Prostate cancer"", + ""Lung cancer"", ""Colorectal cancer"") +egger_Hannum <- meta_func(""MR Egger"", ""Hannum"", ""Breast cancer"", ""Ovarian cancer"", ""Prostate cancer"", + ""Lung cancer"", ""Colorectal cancer"") +egger_IEAA <- meta_func(""MR Egger"", ""IEAA"", ""Breast cancer"", ""Ovarian cancer"", ""Prostate cancer"", + ""Lung cancer"", ""Colorectal cancer"") + + +#Mode based +mode_GrimAge <- meta_func(""Weighted mode"", ""GrimAge"", ""Breast cancer"", ""Ovarian cancer"", ""Prostate cancer"", + ""Lung cancer"", ""Colorectal cancer"") +mode_PhenoAge <- meta_func(""Weighted mode"", ""PhenoAge"", ""Breast cancer"", ""Ovarian cancer"", ""Prostate cancer"", + ""Lung cancer"", ""Colorectal cancer"") +mode_Hannum <- meta_func(""Weighted mode"", ""Hannum"", ""Breast cancer"", ""Ovarian cancer"", ""Prostate cancer"", + ""Lung cancer"", ""Colorectal cancer"") +mode_IEAA <- meta_func(""Weighted mode"", ""IEAA"", ""Breast cancer"", ""Ovarian cancer"", ""Prostate cancer"", + ""Lung cancer"", ""Colorectal cancer"") + +#median based +median_GrimAge <- meta_func(""Weighted median"", ""GrimAge"", ""Breast cancer"", ""Ovarian cancer"", ""Prostate cancer"", + ""Lung cancer"", ""Colorectal cancer"") +median_PhenoAge <- meta_func(""Weighted median"", ""PhenoAge"", ""Breast cancer"", ""Ovarian cancer"", ""Prostate cancer"", + ""Lung cancer"", ""Colorectal cancer"") +median_Hannum <- meta_func(""Weighted median"", ""Hannum"", ""Breast cancer"", ""Ovarian cancer"", ""Prostate cancer"", + ""Lung cancer"", ""Colorectal cancer"") +median_IEAA <- meta_func(""Weighted median"", ""IEAA"", ""Breast cancer"", ""Ovarian cancer"", ""Prostate cancer"", + ""Lung cancer"", ""Colorectal cancer"") + +# COMBINE METHODS +GrimAge <- rbind(IVW_GrimAge, egger_GrimAge, median_GrimAge, mode_GrimAge) +PhenoAge <- rbind(IVW_PhenoAge, egger_PhenoAge, median_PhenoAge, mode_PhenoAge) +Hannum <- rbind(IVW_Hannum, egger_Hannum, median_Hannum, mode_Hannum) +IEAA <- rbind(IVW_IEAA, egger_IEAA, median_IEAA, mode_IEAA) + +################################################################## +# Multiple testing correction +################################################################## + +# Function to apply multiple testing correction to main meta-analysed IVW results +multiple_testing_func <- function(results_IVW){ + results_IVW$p.fdr<- p.adjust(results_IVW$pval, method = ""fdr"") + results_IVW$p.bon<- p.adjust(results_IVW$pval, method = ""bonferroni"") + results_IVW$p.hoch <- p.adjust(results_IVW$pval, method = ""hochberg"") + results_IVW$p.sig <- ifelse(results_IVW$pval < .05, ""*"", """") + results_IVW$p.fdr.sig <- ifelse(results_IVW$p.fdr < .05, ""*"", """") + results_IVW$p.bon.sig <- ifelse(results_IVW$p.bon < .05, ""*"", """") + results_IVW$p.hoch.sig <- ifelse(results_IVW$p.hoch < .05, ""*"", """") + return(results_IVW) +} + +IVW_GrimAge <- multiple_testing_func(IVW_GrimAge) +IVW_PhenoAge <- multiple_testing_func(IVW_PhenoAge) +IVW_Hannum <- multiple_testing_func(IVW_Hannum) +IVW_IEAA <- multiple_testing_func(IVW_IEAA) + + +# Add FDR p-values +GrimAge <- merge(GrimAge, IVW_GrimAge[, c(""p.fdr"", ""method"", ""outcome"")], by=c(""method"", ""outcome""), all.x = T) +PhenoAge <- merge(PhenoAge, IVW_PhenoAge[, c(""p.fdr"", ""method"", ""outcome"")], by=c(""method"", ""outcome""), all.x = T) +Hannum <- merge(Hannum, IVW_Hannum[, c(""p.fdr"", ""method"", ""outcome"")], by=c(""method"", ""outcome""), all.x = T) +IEAA <- merge(IEAA, IVW_IEAA[, c(""p.fdr"", ""method"", ""outcome"")], by=c(""method"", ""outcome""), all.x = T) + +# Combine datasets and save meta-analysis results +MA_fdr_corrected <- rbind(GrimAge, PhenoAge, Hannum, IEAA) +write.xlsx(MA_fdr_corrected, ""MA_clocks_incFDR.xlsx"") + +","R" +"Epigenetics","fernandam93/epiclocks_cancer","3.3_run_2SMR_for_consortiums.R",".R","3980","97","####################################################################### +# EPIGENETIC CLOCKS AND MULTIPLE CANCERS # +####################################################################### +# R version 4.0.2 (2020-06-22) +# Last modified: 26 August 2021 + +# This script runs two-sample MR for epigenetic clock acceleration +# measures and cancer in consortiums + +#---------------------------------------------------------------------# +# Housekeeping #---- +#---------------------------------------------------------------------# + +# Clear environment +rm(list=ls()) #Remove any existing objects in R + +# Set working directory +setwd(""your_working_directory"") + +if (!require(""pacman"")) install.packages(""pacman"") +pacman::p_load(""MRInstruments"", ""TwoSampleMR"", ""tidyverse"", ""dplyr"", ""ggpubr"", ""ggplot2"", ""ggforce"", ""data.table"", ""ggforestplot"",""gtools"") + +#---------------------------------------------------------------------# +# Available data #---- +#---------------------------------------------------------------------# + +ao <- available_outcomes() + + +#---------------------------------------------------------------------# +# Read exposure #---- +#---------------------------------------------------------------------# +#read exposure +exp_dat <- read.table(""exp_data.txt"", header = T) + +#---------------------------------------------------------------------# +# Outcomes #---- +#---------------------------------------------------------------------# +# Extract outcomes from the IEU catalog (MR-Base) +IEU_out_dat <- extract_outcome_data( + snps = exp_dat$SNP, + outcomes = c(""ieu-a-1126"", ""ieu-b-85"", ""ieu-a-966"", ""ieu-a-1120"", ""ieu-a-1127"", + ""ieu-a-1128"", ""ieu-a-1121"", ""ieu-a-1122"", ""ieu-a-1123"", ""ieu-a-1124"", + ""ieu-a-1125"", ""ieu-a-965"", ""ieu-a-967"") +) + +# Read GECCO outcomes +x <- read.csv(""GECCO.csv"", + header = T) +x$SNP <- exp_dat$SNP[match(x$Position, exp_dat$pos.exposure)] + + +out_func_GECCO <- function(name) +{ + # Extract outcome SNPs matching the SNPs in the exposure dataset + outcome_var <- x %>% format_data(snps = exp_dat$SNP, + type = ""outcome"", + snp_col = ""SNP"", + beta_col = ""Effect"", + se_col = ""StdErr"", + effect_allele_col = ""Allele1"", + other_allele_col = ""Allele2"", + chr_col = ""Chr"", + pos_col = ""Position"", + eaf_col = ""Freq1"", + pval_col = ""P.value"") + outcome_var$outcome <- name + return(outcome_var) +} + +GECCO <- out_func_GECCO(""Colorectal cancer"") + +IEU_out_dat <- smartbind(IEU_out_dat, GECCO) +#---------------------------------------------------------------------# +# Harmonisation #---- +#---------------------------------------------------------------------# +# Harmonise exposure and outcome datasets +data_IEU <- harmonise_data( + exposure_dat = exp_dat, + outcome_dat = IEU_out_dat +) + +#---------------------------------------------------------------------# +# Results #---- +#---------------------------------------------------------------------# +# Run two-sample MR +results_IEU <- mr(data_IEU, method_list = c(""mr_ivw"", ""mr_egger_regression"", + ""mr_weighted_median"", ""mr_weighted_mode"")) + +#---------------------------------------------------------------------# +# Save results #---- +#---------------------------------------------------------------------# + +#write.table(results_IEU, ""results_IEU.txt"", row.names = F) + + +","R" +"Epigenetics","fernandam93/epiclocks_cancer","2.2_find_LD_proxies_for_PRACTICAL_subtypes.R",".R","15928","245","#################################################################################### +# EPIGENETIC CLOCKS AND MULTIPLE CANCERS +#################################################################################### +# R version 4.0.2 (2020-06-22) +# Last modified: 17 August 2021 + +# This script finds LD-proxies for cancer subtypes in PRACTICAL, which can then be +# used in two-sample MR analyses +# Output in two-sample MR format + +#---------------------------------------------------------------------# +# Housekeeping #---- +#---------------------------------------------------------------------# + +# Clear environment +rm(list=ls()) #Remove any existing objects in R + +# Set working directory +setwd(""your_working_directory"") + +if (!require(""pacman"")) install.packages(""pacman"") +pacman::p_load(""MRInstruments"", ""TwoSampleMR"", ""tidyverse"", ""dplyr"", ""ggpubr"", ""ggplot2"", ""ggforce"", ""data.table"", ""ggforestplot"",""gtools"", ""LDlinkR"") + +#---------------------------------------------------------------------# +# Read exposure and outcome datasets #---- +#---------------------------------------------------------------------# + +# Read exposure +exp_dat <- read.table(""exp_data.txt"", header = T) + +# Function to read outcome +out_func_practical <- function(var, name) +{ + # Extract outcome SNPs matching the SNPs in the exposure dataset + outcome_var <- read.table(paste(""PRACTICAL_"", var, "".txt"", sep = """"), + header = T) %>% format_data(snps = exp_dat$SNP, + type = ""outcome"", + snp_col = ""SNP"", + beta_col = ""Effect"", + se_col = ""StdErr"", + effect_allele_col = ""Allele1"", + other_allele_col = ""Allele2"", + chr_col = ""Chr"", + pos_col = ""position"", + eaf_col = ""Freq1"", + pval_col = ""Pvalue"") + outcome_var$outcome <- name + return(outcome_var) +} + + +PRACT_adv <- out_func_practical(""adv"", ""Advanced prostate cancer"") +PRACT_age55 <- out_func_practical(""age55"", ""Early onset prostate cancer"") +PRACT_caseonly <- out_func_practical(""caseonly"", ""Advanced prostate cancer (cases only)"") +PRACT_gleason <- out_func_practical(""gleason"", ""Gleason Score"") +PRACT_highvslow <- out_func_practical(""highvslow"", ""High risk prostate cancer (vs low risk)"") +PRACT_highvslowint <- out_func_practical(""highvslowint"", ""High risk prostate cancer (vs low and intermediate risk)"") + +#---------------------------------------------------------------------# +# Identify SNPs that need proxies #---- +#---------------------------------------------------------------------# + +# Function to find list of snps in exposure dataset that are missing from the outcome dataset +find_missing_SNP <- function(out_dat) { + snps_need_proxy <- subset(exp_dat, !(exp_dat$SNP %in% out_dat$SNP)) +} + +s <- find_missing_SNP(PRACT_adv) + +count(s) #check how many snps are in list +s$SNP #see list of snps +s[1,1] #see snp missing n#1 +s[2,1] #see snp missing n#2 +s[3,1] #see snp missing n#3 +s[4,1] #see snp missing n#4 +s[5,1] #see snp missing n#4 + +#---------------------------------------------------------------------# +# Find proxies for these snps #---- +#---------------------------------------------------------------------# + +# Function to find LD proxy using LDLINK +find_LD_proxy <- function(snps_need_proxy) { + proxy <- (LDproxy(snps_need_proxy[1,1], ""EUR"", ""r2"", token = Sys.getenv(""LDLINK_TOKEN""), file = F))[c(1,4),] + proxy$original <- snps_need_proxy[1,1] + proxy2 <- (LDproxy(snps_need_proxy[2,1], ""EUR"", ""r2"", token = Sys.getenv(""LDLINK_TOKEN""), file = F))[c(1,3),] + proxy2$original <- snps_need_proxy[2,1] + proxy3 <- (LDproxy(snps_need_proxy[3,1], ""EUR"", ""r2"", token = Sys.getenv(""LDLINK_TOKEN""), file = F))[1:2,] + proxy3$original <- snps_need_proxy[3,1] + proxy4 <- (LDproxy(snps_need_proxy[4,1], ""EUR"", ""r2"", token = Sys.getenv(""LDLINK_TOKEN""), file = F))[c(1,9),] + proxy4$original <- snps_need_proxy[4,1] + proxy5 <- (LDproxy(snps_need_proxy[5,1], ""EUR"", ""r2"", token = Sys.getenv(""LDLINK_TOKEN""), file = F))[1:2,] + proxy5$original <- snps_need_proxy[5,1] + proxies <- rbind(proxy, proxy2, proxy3, proxy4, proxy5) + proxies + # we could change number of proxies we want to find +} + +a <- find_LD_proxy(s) +a[2,1] #see proxy snp (for snp missing n#1) +a[4,1] #see proxy snp (for snp missing n#2) +a[6,1] #see proxy snp (for snp missing n#3) +a[8,1] #see proxy snp (for snp missing n#4) +a[10,1] #see proxy snp (for snp missing n#5) + +# We need to make sure the identified proxy SNPs are available in outcome dataset before continuing +# Here, we used the terminal to do this (e.g., zcat finngen_R5_C3_BREAST_EXALLC.gz | grep rs290794) +# If SNPs aren't available, you need to find the next best proxy for the missing SNP + +# List all SNPs included in the outcome dataset, including proxies for those that are missing +# This can then be used to extract data related to these SNPs using grep in the terminal +list_all_snps<- function(out_dat, proxy) { + exp_snps <- out_dat$SNP + proxy_snp <- proxy[c(2,4,6,8,10),1] + all_snps <- c(exp_snps, proxy_snp) +} +all <- list_all_snps(PRACT_adv, a) + +write.table(all, ""PRACTICAL_SNP_list_inc_proxies.txt"", quote = F, sep = "" "", col.names = F, row.names = F) + +#---------------------------------------------------------------------# +# NOW USE THE TERMINAL TO EXTRACT DATA FOR ALL SNPS #---- +#---------------------------------------------------------------------# +#Example: +#zcat finngen_R5_C3_BRONCHUS_LUNG_EXALLC.gz | grep -w -F -f FINNGEN_SNP_list_inc_proxies.txt -e rsids > finngen_lung_exallc_inc_proxies.txt + +#---------------------------------------------------------------------# +# Back to R -> Format data first #---- +#---------------------------------------------------------------------# +# Function to format data (two-sample MR format) +# Here, it is important to use the format_data function using the SNP list including proxies, not the original SNP list +out_func_practical_proxies <- function(var, name) +{ + # Extract outcome SNPs matching the SNPs in the exposure dataset + outcome_var <- read.table(paste(""PRACTICAL_"", var, ""_inc_proxies.txt"", sep = """"), + header = T) %>% format_data(snps = all, + type = ""outcome"", + snp_col = ""SNP"", + beta_col = ""Effect"", + se_col = ""StdErr"", + effect_allele_col = ""Allele1"", + other_allele_col = ""Allele2"", + chr_col = ""Chr"", + pos_col = ""position"", + eaf_col = ""Freq1"", + pval_col = ""Pvalue"") + outcome_var$outcome <- name + return(outcome_var) +} + +PRACT_adv_proxies <- out_func_practical_proxies(""adv"", ""Advanced prostate cancer"") +PRACT_age55_proxies <- out_func_practical_proxies(""age55"", ""Early onset prostate cancer"") +PRACT_caseonly_proxies <- out_func_practical_proxies(""caseonly"", ""Advanced prostate cancer (cases only)"") +PRACT_gleason_proxies <- out_func_practical_proxies(""gleason"", ""Gleason Score"") +PRACT_highvslow_proxies <- out_func_practical_proxies(""highvslow"", ""High risk prostate cancer (vs low risk)"") +PRACT_highvslowint_proxies <- out_func_practical_proxies(""highvslowint"", ""High risk prostate cancer (vs low and intermediate risk)"") + + +# Find list of SNPs in the proxy dataset that are missing from the outcome dataset, +# just to make sure that we aren't missing any SNPs before moving on to the next step +find_missing_SNP_proxy <- function(out_dat) { + snps_need_proxy <- subset(as.data.frame(all), !(all %in% out_dat$SNP)) +} + +s2 <- find_missing_SNP_proxy(PRACT_adv_proxies) + +#---------------------------------------------------------------------# +# Modify outcome dataset so that proxy SNP ""rsid"" is replaced by original SNP ""rsid"" #---- +#---------------------------------------------------------------------# +# Function to add columns for the replacement data to the proxy dataset +replacement_cols_proxy <- function(proxy) { + proxy <- proxy %>% separate(Coord, c(""chr"",""pos""), sep = ""([:])"") + proxy$chr <- gsub(""chr"", """", proxy$chr) + proxy <- proxy %>% separate(Correlated_Alleles, c(""A1_original"",""A1_proxy"", ""A2_original"", ""A2_proxy""), sep = ""([,=])"") + proxy$original_chr <- c(proxy[1,2], proxy[1,2], proxy[3,2], proxy[3,2], proxy[5,2], proxy[5,2], proxy[7,2], proxy[7,2], proxy[9,2], proxy[9,2]) + proxy$original_pos <- c(proxy[1,3], proxy[1,3], proxy[3,3], proxy[3,3], proxy[5,3], proxy[5,3], proxy[7,3], proxy[7,3], proxy[9,3], proxy[9,3]) + proxy + +} + +b <- replacement_cols_proxy(a) + +# Function to replace proxy SNP details by original SNP details +replace_proxy_by_original <- function(proxy, out_dat_proxies) { + #proxy 1 + out_dat_proxies$effect_allele.outcome[out_dat_proxies$SNP==proxy[2,1] & out_dat_proxies$effect_allele.outcome == proxy[2,10]] <- proxy[2,9] #A1 effect allele + out_dat_proxies$effect_allele.outcome[out_dat_proxies$SNP==proxy[2,1] & out_dat_proxies$effect_allele.outcome == proxy[2,12]] <- proxy[2,11] #A1 effect allele + out_dat_proxies$other_allele.outcome[out_dat_proxies$SNP==proxy[2,1] & out_dat_proxies$other_allele.outcome == proxy[2,10]] <- proxy[2,9] #A2 other allele + out_dat_proxies$other_allele.outcome[out_dat_proxies$SNP==proxy[2,1] & out_dat_proxies$other_allele.outcome == proxy[2,12]] <- proxy[2,11] #A2 other allele + out_dat_proxies$chr.outcome[out_dat_proxies$SNP==proxy[2,1]] <- proxy[2,16] #change chr + out_dat_proxies$pos.outcome[out_dat_proxies$SNP==proxy[2,1]] <- proxy[2,17] #change pos + out_dat_proxies$SNP[out_dat_proxies$SNP==proxy[2,1]] <- proxy[2,15] #change rsid + #proxy 2 + out_dat_proxies$effect_allele.outcome[out_dat_proxies$SNP==proxy[4,1] & out_dat_proxies$effect_allele.outcome == proxy[4,10]] <- proxy[4,9] #A1 effect allele + out_dat_proxies$effect_allele.outcome[out_dat_proxies$SNP==proxy[4,1] & out_dat_proxies$effect_allele.outcome == proxy[4,12]] <- proxy[4,11] #A1 effect allele + out_dat_proxies$other_allele.outcome[out_dat_proxies$SNP==proxy[4,1] & out_dat_proxies$other_allele.outcome == proxy[4,10]] <- proxy[4,9] #A2 other allele + out_dat_proxies$other_allele.outcome[out_dat_proxies$SNP==proxy[4,1] & out_dat_proxies$other_allele.outcome == proxy[4,12]] <- proxy[4,11] #A2 other allele + out_dat_proxies$chr.outcome[out_dat_proxies$SNP==proxy[4,1]] <- proxy[4,16] #change chr + out_dat_proxies$pos.outcome[out_dat_proxies$SNP==proxy[4,1]] <- proxy[4,17] #change pos + out_dat_proxies$SNP[out_dat_proxies$SNP==proxy[4,1]] <- proxy[4,15] #change rsid + #proxy 3 + out_dat_proxies$effect_allele.outcome[out_dat_proxies$SNP==proxy[6,1] & out_dat_proxies$effect_allele.outcome == proxy[6,10]] <- proxy[6,9] #A1 effect allele + out_dat_proxies$effect_allele.outcome[out_dat_proxies$SNP==proxy[6,1] & out_dat_proxies$effect_allele.outcome == proxy[6,12]] <- proxy[6,11] #A1 effect allele + out_dat_proxies$other_allele.outcome[out_dat_proxies$SNP==proxy[6,1] & out_dat_proxies$other_allele.outcome == proxy[6,10]] <- proxy[6,9] #A2 other allele + out_dat_proxies$other_allele.outcome[out_dat_proxies$SNP==proxy[6,1] & out_dat_proxies$other_allele.outcome == proxy[6,12]] <- proxy[6,11] #A2 other allele + out_dat_proxies$chr.outcome[out_dat_proxies$SNP==proxy[6,1]] <- proxy[6,16] #change chr + out_dat_proxies$pos.outcome[out_dat_proxies$SNP==proxy[6,1]] <- proxy[6,17] #change pos + out_dat_proxies$SNP[out_dat_proxies$SNP==proxy[6,1]] <- proxy[6,15] #change rsid + #proxy 4 + out_dat_proxies$effect_allele.outcome[out_dat_proxies$SNP==proxy[8,1] & out_dat_proxies$effect_allele.outcome == proxy[8,10]] <- proxy[8,9] #A1 effect allele + out_dat_proxies$effect_allele.outcome[out_dat_proxies$SNP==proxy[8,1] & out_dat_proxies$effect_allele.outcome == proxy[8,12]] <- proxy[8,11] #A1 effect allele + out_dat_proxies$other_allele.outcome[out_dat_proxies$SNP==proxy[8,1] & out_dat_proxies$other_allele.outcome == proxy[8,10]] <- proxy[8,9] #A2 other allele + out_dat_proxies$other_allele.outcome[out_dat_proxies$SNP==proxy[8,1] & out_dat_proxies$other_allele.outcome == proxy[8,12]] <- proxy[8,11] #A2 other allele + out_dat_proxies$chr.outcome[out_dat_proxies$SNP==proxy[8,1]] <- proxy[8,16] #change chr + out_dat_proxies$pos.outcome[out_dat_proxies$SNP==proxy[8,1]] <- proxy[8,17] #change pos + out_dat_proxies$SNP[out_dat_proxies$SNP==proxy[8,1]] <- proxy[8,15] #change rsid + out_dat_proxies + #proxy 5 + out_dat_proxies$effect_allele.outcome[out_dat_proxies$SNP==proxy[10,1] & out_dat_proxies$effect_allele.outcome == proxy[10,10]] <- proxy[10,9] #A1 effect allele + out_dat_proxies$effect_allele.outcome[out_dat_proxies$SNP==proxy[10,1] & out_dat_proxies$effect_allele.outcome == proxy[10,12]] <- proxy[10,11] #A1 effect allele + out_dat_proxies$other_allele.outcome[out_dat_proxies$SNP==proxy[10,1] & out_dat_proxies$other_allele.outcome == proxy[10,10]] <- proxy[10,9] #A2 other allele + out_dat_proxies$other_allele.outcome[out_dat_proxies$SNP==proxy[10,1] & out_dat_proxies$other_allele.outcome == proxy[10,12]] <- proxy[10,11] #A2 other allele + out_dat_proxies$chr.outcome[out_dat_proxies$SNP==proxy[10,1]] <- proxy[10,16] #change chr + out_dat_proxies$pos.outcome[out_dat_proxies$SNP==proxy[10,1]] <- proxy[10,17] #change pos + out_dat_proxies$SNP[out_dat_proxies$SNP==proxy[10,1]] <- proxy[10,15] #change rsid + out_dat_proxies +} + +PRACT_adv_new <- replace_proxy_by_original(b, PRACT_adv_proxies) +PRACT_age55_new <- replace_proxy_by_original(b, PRACT_age55_proxies) +PRACT_caseonly_new <- replace_proxy_by_original(b, PRACT_caseonly_proxies) +PRACT_gleason_new <- replace_proxy_by_original(b, PRACT_gleason_proxies) +PRACT_highvslow_new <- replace_proxy_by_original(b, PRACT_highvslow_proxies) +PRACT_highvslowint_new <- replace_proxy_by_original(b, PRACT_highvslowint_proxies) + + + +write.table(PRACT_adv_new, ""PRACTICAL_adv_replaced_proxies.txt"", sep = "" "", row.names = F, col.names = T) +write.table(PRACT_age55_new, ""PRACTICAL_age55_replaced_proxies.txt"", sep = "" "", row.names = F, col.names = T) +write.table(PRACT_caseonly_new, ""PRACTICAL_caseonly_replaced_proxies.txt"", sep = "" "", row.names = F, col.names = T) +write.table(PRACT_highvslow_new, ""PRACTICAL_highvslow_replaced_proxies.txt"", sep = "" "", row.names = F, col.names = T) +write.table(PRACT_highvslowint_new, ""PRACTICAL_highvslowint_replaced_proxies.txt"", sep = "" "", row.names = F, col.names = T) +write.table(PRACT_gleason_new, ""PRACTICAL_gleason_replaced_proxies.txt"", sep = "" "", row.names = F, col.names = T) + +","R" +"Epigenetics","fernandam93/epiclocks_cancer","6.2_run_CAUSE_for_GrimAge_CRCinGECCO.R",".R","3888","92"," +####################################################################### +# EPIGENETIC CLOCKS AND MULTIPLE CANCERS # +####################################################################### +# R version 4.0.2 (2020-06-22) +# Last modified: 12 November 2021 + +# This script runs CAUSE for GrimAge acceleration and colorectal cancer in GECCO +# This needs to be run using the terminal + +#---------------------------------------------------------------------# +# Housekeeping #---- +#---------------------------------------------------------------------# + +# Clear environment +rm(list=ls()) #Remove any existing objects in R + +# Install packages +if (!require(""pacman"")) install.packages(""pacman"") +pacman::p_load(""MRInstruments"", ""TwoSampleMR"", ""tidyverse"", ""dplyr"", ""readr"", ""ieugwasr"") +pacman::p_load_gh(""jean997/cause@v1.2.0"", ""explodecomputer/genetics.binaRies"") + +# Available outcomes +ao <- available_outcomes() +#---------------------------------------------------------------------# +# Read exposure #---- +#---------------------------------------------------------------------# + +# Read exposure +GrimAge <- read.table(""GrimAge_EUR_summary_statistics.txt"", header = T) + +#---------------------------------------------------------------------# +# Outcomes #---- +#---------------------------------------------------------------------# + +# Read outcome +colorectal_ca <- read.table(""GECCO_summary_statistics.txt"", header = T) #already in two-sample MR format + +#---------------------------------------------------------------------# +# Merge GWAS data #---- +#---------------------------------------------------------------------# + +X <- gwas_merge(GrimAge, colorectal_ca, + snp_name_cols = c(""rsID"", ""SNP""), + beta_hat_cols = c(""Effect"", ""beta.outcome""), + se_cols = c(""SE"", ""se.outcome""), + A1_cols = c(""A1"", ""effect_allele.outcome""), + A2_cols = c(""A2"", ""other_allele.outcome"")) + +#---------------------------------------------------------------------# +# Calculate nuisance parameters #---- +#---------------------------------------------------------------------# + +# only > 100,000 variants +set.seed(100) +varlist <- with(X, sample(snp, size=1000000, replace=FALSE)) +params <- est_cause_params(X, varlist) +head(params$mix_grid) + +#---------------------------------------------------------------------# +# Clump data #---- +#---------------------------------------------------------------------# +X$p_value <- 2*pnorm(abs(X$beta_hat_1/X$seb1), lower.tail=FALSE) +X_clump <- X %>% rename(rsid = snp, + pval = p_value) %>% + ieugwasr::ld_clump(dat = ., + clump_r2 = 0.01, + clump_p = 1e-03, #should use larger p value, 1e-03 as used for posteriors, not 5e-08 + # plink_bin = genetics.binaRies::get_plink_binary(), + #bfile = ""~/EUR"" + ) +keep_snps <- X_clump$rsid +#---------------------------------------------------------------------# +# MR-CAUSE analysis #---- +#---------------------------------------------------------------------# + +# X is unclumped data and variants clumped data +res <- cause(X=X, variants = keep_snps, param_ests = params) +plot(res$sharing) +plot(res$causal) +summary(res, ci_size=0.95) +plot(res) +plot(res, type=""data"") + +png('CAUSE/CAUSE_GrimAge_CRC1.png', res=300, height=2000, width=3500) +plot(res) +dev.off() + +png('CAUSE/CAUSE_GrimAge_CRC2.png', res=300, height=2000, width=3500) +plot(res, type=""data"") +dev.off() +","R" +"Epigenetics","fernandam93/epiclocks_cancer","2.1_find_LD_proxies_for_FinnGen_outcomes.R",".R","14509","229","#################################################################################### +# EPIGENETIC CLOCKS AND MULTIPLE CANCERS +#################################################################################### +# R version 4.0.2 (2020-06-22) +# Last modified: 17 August 2021 + +# This script finds LD-proxies for cancer outcomes in FinnGen, which can then be +# used in two-sample MR analyses +# Output in two-sample MR format + +#---------------------------------------------------------------------# +# Housekeeping #---- +#---------------------------------------------------------------------# + +# Clear environment +rm(list=ls()) #Remove any existing objects in R + +# Set working directory +setwd(""your_working_directory"") + +if (!require(""pacman"")) install.packages(""pacman"") +pacman::p_load(""MRInstruments"", ""TwoSampleMR"", ""tidyverse"", ""dplyr"", ""ggpubr"", ""ggplot2"", ""ggforce"", ""data.table"", ""ggforestplot"",""gtools"", ""LDlinkR"") + +#---------------------------------------------------------------------# +# Read exposure and outcome datasets #---- +#---------------------------------------------------------------------# + +# Read exposure +exp_dat <- read.table(""exp_data.txt"", header = T) + +# Function to read outcome +out_func_FINNGEN <- function(file, name) +{ + # Extract outcome SNPs matching the SNPs in the exposure dataset + outcome_var <- read.table(paste(""finngen_"", file,"".txt"", sep = """"), + header = T) %>% format_data(snps = exp_dat$SNP, + type = ""outcome"", + snp_col = ""rsids"", + beta_col = ""beta"", + se_col = ""sebeta"", + effect_allele_col = ""alt"", + other_allele_col = ""ref"", + chr_col = ""chrom"", + pos_col = ""pos"", + eaf_col = ""maf"", + pval_col = ""pval"") + outcome_var$outcome <- name + return(outcome_var) +} + +# Read FinnGen outcome (all finngen datasets are missing the same SNPs, +# so we can find proxies for only one of the outcomes) +lung_cancer_exallc <- out_func_FINNGEN(""lung_exallc"", ""lung cancer (excluding cancer in controls)"") + +#---------------------------------------------------------------------# +# Identify SNPs that need proxies #---- +#---------------------------------------------------------------------# + +# Function to find list of snps in exposure dataset that are missing from the outcome dataset +find_missing_SNP <- function(out_dat) { + snps_need_proxy <- subset(exp_dat, !(exp_dat$SNP %in% out_dat$SNP)) +} + +s <- find_missing_SNP(lung_cancer_exallc) + +count(s) #check how many snps are in list +s$SNP #see list of snps +s[1,1] #see snp missing n#1 +s[2,1] #see snp missing n#2 +s[3,1] #see snp missing n#3 +s[4,1] #see snp missing n#4 + +#---------------------------------------------------------------------# +# Find proxies for these snps #---- +#---------------------------------------------------------------------# + +# Function to find LD proxy using LDLINK +find_LD_proxy <- function(snps_need_proxy) { + proxy <- (LDproxy(snps_need_proxy[1,1], ""EUR"", ""r2"", token = Sys.getenv(""LDLINK_TOKEN""), file = F))[c(1,4),] + proxy$original <- snps_need_proxy[1,1] + proxy2 <- (LDproxy(snps_need_proxy[2,1], ""EUR"", ""r2"", token = Sys.getenv(""LDLINK_TOKEN""), file = F))[1:2,] + proxy2$original <- snps_need_proxy[2,1] + proxy3 <- (LDproxy(snps_need_proxy[3,1], ""EUR"", ""r2"", token = Sys.getenv(""LDLINK_TOKEN""), file = F))[1:2,] + proxy3$original <- snps_need_proxy[3,1] + proxy4 <- (LDproxy(snps_need_proxy[4,1], ""EUR"", ""r2"", token = Sys.getenv(""LDLINK_TOKEN""), file = F))[1:2,] + proxy4$original <- snps_need_proxy[4,1] + proxies <- rbind(proxy, proxy2, proxy3, proxy4) + proxies + # we could change number of proxies we want to find +} + +a <- find_LD_proxy(s) +a[2,1] #see proxy snp (for snp missing n#1) +a[4,1] #see proxy snp (for snp missing n#2) +a[6,1] #see proxy snp (for snp missing n#3) +a[8,1] #see proxy snp (for snp missing n#4) + +# We need to make sure the identified proxy SNPs are available in outcome dataset before continuing +# Here, we used the terminal to do this (e.g., zcat finngen_R5_C3_BREAST_EXALLC.gz | grep rs290794) +# If SNPs aren't available, you need to find the next best proxy for the missing SNP + + +# List all SNPs included in the outcome dataset, including proxies for those that are missing +# This can then be used to extract data related to these SNPs using grep in the terminal +list_all_snps<- function(out_dat, proxy) { + exp_snps <- out_dat$SNP + proxy_snp <- proxy[c(2,4,6,8),1] + all_snps <- c(exp_snps, proxy_snp) +} +all <- list_all_snps(lung_cancer_exallc, a) + +write.table(all, ""FINNGEN_SNP_list_inc_proxies.txt"", quote = F, sep = "" "", col.names = F, row.names = F) +all <- read.table(""FINNGEN_SNP_list_inc_proxies.txt"", header = F) +#---------------------------------------------------------------------# +# NOW USE THE TERMINAL TO EXTRACT DATA FOR ALL SNPS #---- +#---------------------------------------------------------------------# +#Example: +#zcat finngen_R5_C3_BRONCHUS_LUNG_EXALLC.gz | grep -w -F -f FINNGEN_SNP_list_inc_proxies.txt -e rsids > finngen_lung_exallc_inc_proxies.txt + + # Use nano finngen_lung_exallc_inc_proxies.txt to remove hashtag in column names before using the grep command + +#---------------------------------------------------------------------# +# Back to R -> Format data first #---- +#---------------------------------------------------------------------# +# Function to format data (two-sample MR format) +# Here, it is important to use the format_data function using the SNP list including proxies, not the original SNP list +out_func_FINNGEN_proxies <- function(file, name) +{ + # Extract outcome SNPs matching the SNPs in the exposure dataset + outcome_var <- read.table(paste(""finngen_"", file,""_inc_proxies.txt"", sep = """"), + header = T) %>% format_data(snps = all, + type = ""outcome"", + snp_col = ""rsids"", + beta_col = ""beta"", + se_col = ""sebeta"", + effect_allele_col = ""alt"", + other_allele_col = ""ref"", + chr_col = ""chrom"", + pos_col = ""pos"", + eaf_col = ""maf"", + pval_col = ""pval"") + outcome_var$outcome <- name + return(outcome_var) +} + +lung_cancer_exallc_proxies <- out_func_FINNGEN_proxies(""lung_exallc"", ""lung cancer (excluding cancer in controls)"") +breast_cancer_exallc_proxies <- out_func_FINNGEN_proxies(""breast_exallc"", ""breast cancer (excluding cancer in controls)"") +colorectal_cancer_exallc_proxies <- out_func_FINNGEN_proxies(""colorectal_exallc"", ""colorectal cancer (excluding cancer in controls)"") +ovarian_cancer_exallc_proxies <- out_func_FINNGEN_proxies(""ovary_exallc"", ""ovarian cancer (excluding cancer in controls)"") +prostate_cancer_exallc_proxies <- out_func_FINNGEN_proxies(""prostate_exallc"", ""prostate cancer (excluding cancer in controls)"") + + +# Find list of SNPs in the proxy dataset that are missing from the outcome dataset, +# just to make sure that we aren't missing any SNPs before moving on to the next step +find_missing_SNP_proxy <- function(out_dat) { + snps_need_proxy <- subset(as.data.frame(all), !(all %in% out_dat$SNP)) +} + +s2 <- find_missing_SNP_proxy(lung_cancer_exallc_proxies) + +#---------------------------------------------------------------------# +# Modify outcome dataset so that the proxy SNP ""rsid"" is replaced by the original SNP ""rsid"" #---- +#---------------------------------------------------------------------# +# Function to add columns for the replacement data to the proxy dataset +replacement_cols_proxy <- function(proxy) { + proxy <- proxy %>% separate(Coord, c(""chr"",""pos""), sep = ""([:])"") + proxy$chr <- gsub(""chr"", """", proxy$chr) + proxy <- proxy %>% separate(Correlated_Alleles, c(""A1_original"",""A1_proxy"", ""A2_original"", ""A2_proxy""), sep = ""([,=])"") + proxy$original_chr <- c(proxy[1,2], proxy[1,2], proxy[3,2], proxy[3,2], proxy[5,2], proxy[5,2], proxy[7,2], proxy[7,2]) + proxy$original_pos <- c(proxy[1,3], proxy[1,3], proxy[3,3], proxy[3,3], proxy[5,3], proxy[5,3], proxy[7,3], proxy[7,3]) + proxy + +} + +b <- replacement_cols_proxy(a) + +# Function to replace proxy SNP details by original SNP details +replace_proxy_by_original <- function(proxy, out_dat_proxies) { + #proxy 1 + out_dat_proxies$effect_allele.outcome[out_dat_proxies$SNP==proxy[2,1] & out_dat_proxies$effect_allele.outcome == proxy[2,10]] <- proxy[2,9] #A1 effect allele + out_dat_proxies$effect_allele.outcome[out_dat_proxies$SNP==proxy[2,1] & out_dat_proxies$effect_allele.outcome == proxy[2,12]] <- proxy[2,11] #A1 effect allele + out_dat_proxies$other_allele.outcome[out_dat_proxies$SNP==proxy[2,1] & out_dat_proxies$other_allele.outcome == proxy[2,10]] <- proxy[2,9] #A2 other allele + out_dat_proxies$other_allele.outcome[out_dat_proxies$SNP==proxy[2,1] & out_dat_proxies$other_allele.outcome == proxy[2,12]] <- proxy[2,11] #A2 other allele + out_dat_proxies$chr.outcome[out_dat_proxies$SNP==proxy[2,1]] <- proxy[2,16] #change chr + out_dat_proxies$pos.outcome[out_dat_proxies$SNP==proxy[2,1]] <- proxy[2,17] #change pos + out_dat_proxies$SNP[out_dat_proxies$SNP==proxy[2,1]] <- proxy[2,15] #change rsid + #proxy 2 + out_dat_proxies$effect_allele.outcome[out_dat_proxies$SNP==proxy[4,1] & out_dat_proxies$effect_allele.outcome == proxy[4,10]] <- proxy[4,9] #A1 effect allele + out_dat_proxies$effect_allele.outcome[out_dat_proxies$SNP==proxy[4,1] & out_dat_proxies$effect_allele.outcome == proxy[4,12]] <- proxy[4,11] #A1 effect allele + out_dat_proxies$other_allele.outcome[out_dat_proxies$SNP==proxy[4,1] & out_dat_proxies$other_allele.outcome == proxy[4,10]] <- proxy[4,9] #A2 other allele + out_dat_proxies$other_allele.outcome[out_dat_proxies$SNP==proxy[4,1] & out_dat_proxies$other_allele.outcome == proxy[4,12]] <- proxy[4,11] #A2 other allele + out_dat_proxies$chr.outcome[out_dat_proxies$SNP==proxy[4,1]] <- proxy[4,16] #change chr + out_dat_proxies$pos.outcome[out_dat_proxies$SNP==proxy[4,1]] <- proxy[4,17] #change pos + out_dat_proxies$SNP[out_dat_proxies$SNP==proxy[4,1]] <- proxy[4,15] #change rsid + #proxy 3 + out_dat_proxies$effect_allele.outcome[out_dat_proxies$SNP==proxy[6,1] & out_dat_proxies$effect_allele.outcome == proxy[6,10]] <- proxy[6,9] #A1 effect allele + out_dat_proxies$effect_allele.outcome[out_dat_proxies$SNP==proxy[6,1] & out_dat_proxies$effect_allele.outcome == proxy[6,12]] <- proxy[6,11] #A1 effect allele + out_dat_proxies$other_allele.outcome[out_dat_proxies$SNP==proxy[6,1] & out_dat_proxies$other_allele.outcome == proxy[6,10]] <- proxy[6,9] #A2 other allele + out_dat_proxies$other_allele.outcome[out_dat_proxies$SNP==proxy[6,1] & out_dat_proxies$other_allele.outcome == proxy[6,12]] <- proxy[6,11] #A2 other allele + out_dat_proxies$chr.outcome[out_dat_proxies$SNP==proxy[6,1]] <- proxy[6,16] #change chr + out_dat_proxies$pos.outcome[out_dat_proxies$SNP==proxy[6,1]] <- proxy[6,17] #change pos + out_dat_proxies$SNP[out_dat_proxies$SNP==proxy[6,1]] <- proxy[6,15] #change rsid + #proxy 4 + out_dat_proxies$effect_allele.outcome[out_dat_proxies$SNP==proxy[8,1] & out_dat_proxies$effect_allele.outcome == proxy[8,10]] <- proxy[8,9] #A1 effect allele + out_dat_proxies$effect_allele.outcome[out_dat_proxies$SNP==proxy[8,1] & out_dat_proxies$effect_allele.outcome == proxy[8,12]] <- proxy[8,11] #A1 effect allele + out_dat_proxies$other_allele.outcome[out_dat_proxies$SNP==proxy[8,1] & out_dat_proxies$other_allele.outcome == proxy[8,10]] <- proxy[8,9] #A2 other allele + out_dat_proxies$other_allele.outcome[out_dat_proxies$SNP==proxy[8,1] & out_dat_proxies$other_allele.outcome == proxy[8,12]] <- proxy[8,11] #A2 other allele + out_dat_proxies$chr.outcome[out_dat_proxies$SNP==proxy[8,1]] <- proxy[8,16] #change chr + out_dat_proxies$pos.outcome[out_dat_proxies$SNP==proxy[8,1]] <- proxy[8,17] #change pos + out_dat_proxies$SNP[out_dat_proxies$SNP==proxy[8,1]] <- proxy[8,15] #change rsid + out_dat_proxies +} + +lung_cancer_exallc_new <- replace_proxy_by_original(b, lung_cancer_exallc_proxies) +breast_cancer_exallc_new <- replace_proxy_by_original(b, breast_cancer_exallc_proxies) +colorectal_cancer_exallc_new <- replace_proxy_by_original(b, colorectal_cancer_exallc_proxies) +ovarian_cancer_exallc_new <- replace_proxy_by_original(b, ovarian_cancer_exallc_proxies) +prostate_cancer_exallc_new <- replace_proxy_by_original(b, prostate_cancer_exallc_proxies) + + +write.table(breast_cancer_exallc_new, ""finngen_breast_exallc_replaced_proxies.txt"", sep = "" "", row.names = F, col.names = T) +write.table(ovarian_cancer_exallc_new, ""finngen_ovarian_exallc_replaced_proxies.txt"", sep = "" "", row.names = F, col.names = T) +write.table(prostate_cancer_exallc_new, ""finngen_prostate_exallc_replaced_proxies.txt"", sep = "" "", row.names = F, col.names = T) +write.table(lung_cancer_exallc_new, ""finngen_lung_exallc_replaced_proxies.txt"", sep = "" "", row.names = F, col.names = T) +write.table(colorectal_cancer_exallc_new, ""finngen_colorectal_exallc_replaced_proxies.txt"", sep = "" "", row.names = F, col.names = T) + + + +","R" +"Epigenetics","yeminlan/ADEpigenetics","distance_to_ensembleTSS.R",".R","300","8","mtl <- read.table('t1',header=F) +colnames(mtl) <- 'Distance' +mtl$Distance.group <- cut(mtl$Distance,breaks=c(0,1000,50000,100000,Inf),include.lowest=T) +levels(mtl$Distance.group) <- c(""within.1kb"",""1-50kb"",""50-100kb"",""beyond.100kb"") +write.csv(mtl,'distance_to_ensembleTSS.csv',row.names=F,quote=F) + + +","R" +"Epigenetics","yeminlan/ADEpigenetics","shared_peaks.R",".R","1100","28","d <- read.csv('MTL.result.log2.csv',check.names=F) + + +tmp <- read.table('EntorhinalCortex.sig.txt',header=T) +d$entor <- tmp[,1] +tmp <- read.table('PrefrontalCortex.sig.txt',header=F) +d$prefr <- tmp[,1] +tmp <- read.table('PrefrontalCortex_TauBurden.sig.txt',header=F) +d$prefr.tau <- tmp[,1] +rm(tmp) + +tmp <- subset(d,select=c(""H3K122ac.category"",""prefr.tau"")) +tmp[,3] <- ""others"" +tmp[tmp[,1]==""DD_Gain"" ,3] <- ""DD_Gain"" +tmp[tmp[,1]==""DD_Loss"" ,3] <- ""DD_Loss"" +as.data.frame(table(paste0(tmp[,3],"":"",tmp[,2]))) + + + +write.table(subset(d,H3K27ac.category==""DD_Gain"" & entor==""gain"",select=""Locus""),'~/tmp/DD_gain_EntorGain.bed',row.names=F,col.names=F,quote=F) + +write.table(subset(d,H3K27ac.category==""DD_Loss"" & entor==""loss"",select=""Locus""),'~/tmp/DD_loss_EntorLoss.bed',row.names=F,col.names=F,quote=F) + +write.table(subset(d,H3K9ac.category==""DD_Gain"" & prefr.tau==""gain"",select=""Locus""),'~/tmp/DD_gain_PrefrTauPos.bed',row.names=F,col.names=F,quote=F) + +write.table(subset(d,H3K9ac.category==""DD_Loss"" & prefr.tau==""loss"",select=""Locus""),'~/tmp/DD_loss_PrefrTauNeg.bed',row.names=F,col.names=F,quote=F) + +","R" +"Epigenetics","yeminlan/ADEpigenetics","main.sh",".sh","3467","76","## get multiMTL table1 with H3K27ac/H3K9ac/H3K122ac +for i in `ls ../maskedMTL/MTL.* | grep -v ""gain\|loss\|Y\|O\|A""`; do ln -s $i .;done +cat MTL.H3K27ac.bed MTL.H3K9ac.bed MTL.H3K122ac.bed | sort -k1,1 -k2,2n | bedtools merge > multiMTL.bed +R --no-save < log/peak_size.R +rm MTL.*.bed + +## get presence/absence in each +for i in `ls ../maskedMTL/MTL.* | grep ""Y.bed\|O.bed\|A.bed""`; do ln -s $i .;done +for i in `ls MTL.*.bed|sed ""s|.bed||g""`; do bedtools intersect -a multiMTL.bed -b $i.bed -c | cut -f4 > In.$i;done +for i in `ls In.*`; do echo ""$i"" | cat - $i > $i.tmp; done +paste In.MTL.CTCF.*.tmp In.MTL.Rad21.*.tmp In.MTL.H3K27ac.*.tmp In.MTL.H3K9ac.*.tmp In.MTL.H3K122ac.*.tmp In.MTL.H3K4me1.*.tmp | sed ""s|In.MTL.|In.|g"" > InMTL.txt +rm MTL.*.bed In.MTL.* + +## parse AUC from individual-mark-MTL AUC.txt files +# H3K27ac +echo -e ""#chr\tstart\tend"" |cat - ../run_H3K27ac/peak_calling.v2/MTL.bed > t1 +paste t1 ../run_H3K27ac/peak_calling.v2/AUC.txt > t2 +bedtools intersect -a multiMTL.bed -b t2 -wa -wb > t3 +R --no-save < log/summarize_AUC.R +mv AUC.txt AUC.H3K27ac.txt +rm t1 t2 t3 +# H3K9ac +echo -e ""#chr\tstart\tend"" |cat - ../run_H3K9ac/peak_calling.v2/MTL.bed > t1 +paste t1 ../run_H3K9ac/peak_calling.v2/AUC.txt > t2 +bedtools intersect -a multiMTL.bed -b t2 -wa -wb > t3 +R --no-save < log/summarize_AUC.R +mv AUC.txt AUC.H3K9ac.txt +rm t1 t2 t3 +# H3K122ac +echo -e ""#chr\tstart\tend"" |cat - ../run_H3K122ac/peak_calling.v2/MTL.bed > t1 +paste t1 ../run_H3K122ac/peak_calling.v2/AUC.txt > t2 +bedtools intersect -a multiMTL.bed -b t2 -wa -wb > t3 +R --no-save < log/summarize_AUC.R +mv AUC.txt AUC.H3K122ac.txt +rm t1 t2 t3 +# +paste AUC.H3K27ac.txt AUC.H3K9ac.txt AUC.H3K122ac.txt > AUC.txt +rm AUC.H3K27ac.txt AUC.H3K9ac.txt AUC.H3K122ac.txt + +## get MTL.result.csv +R --no-save < log/get_csv.R + +## add result of pairwise comparison +R --no-save < log/pairwise_comparison.R + +## add nearest gene +annotatePeaks.pl multiMTL.bed hg19 > multiMTL.anno.txt +R --no-save < log/add_nearest_gene.R + +## add rna result +ln -s ../brain.rna/brain.rna.csv . +R --no-save < log/add_rna.R + +## has CTCF/Rad21 within 5kb +bedtools closest -a multiMTL.bed -b ../run_CTCF/peak_calling.v2/MTL.bed -t ""first"" -d | awk '{print($7<=5000)?1:0}' > MTL.hasCTCF_5kb.bed +bedtools closest -a multiMTL.bed -b ../run_Rad21/peak_calling.v2/MTL.bed -t ""first"" -d | awk '{print($7<=5000)?1:0}' > MTL.hasRad21_5kb.bed + +## collapse MTL table so that each transcript appear once (record only the nearest peak to its TSS) +R --no-save < log/MTL.result.collapsed.R + +## count multiMTLs for venn diagram +R --no-save < log/get_venn.R + +## overlap with PrefrontalCortex K9ac peaks +bedtools intersect -a multiMTL.bed -b ../run_ROSMAP_PrefrontalCortex_H3K9ac/differential/Again.bed -c | awk '{print ($4>0)?""gain"":""-""}' > t1 +bedtools intersect -a multiMTL.bed -b ../run_ROSMAP_PrefrontalCortex_H3K9ac/differential/Aloss.bed -c | awk '{print ($4>0)?""loss"":""-""}' > t2 +paste -d- t1 t2 | sed ""s|---|nonsig|g"" | sed ""s|--||g"" > PrefrontalCortex.sig.txt +rm t1 t2 + +## overlap with PrefrontalCortex K9ac Tau-burden peaks +bedtools intersect -a multiMTL.bed -b ../run_ROSMAP_PrefrontalCortex_H3K9ac/ROSMAP/peaks_correlated_with_tau.pos.bed -c | awk '{print ($4>0)?""gain"":""-""}' > t1 +bedtools intersect -a multiMTL.bed -b ../run_ROSMAP_PrefrontalCortex_H3K9ac/ROSMAP/peaks_correlated_with_tau.neg.bed -c | awk '{print ($4>0)?""loss"":""-""}' > t2 +paste -d- t1 t2 | sed ""s|---|nonsig|g"" | sed ""s|--||g"" > PrefrontalCortex_TauBurden.sig.txt +rm t1 t2 + +","Shell" +"Epigenetics","yeminlan/ADEpigenetics","get_venn.R",".R","7564","124","library(plyr) +library(data.table) +library(venneuler) + +mtl <- read.csv('MTL.result.csv',stringsAsFactors = F) + +########################### +## replace with ensembleTSS +#d <- read.csv('distance_to_ensembleTSS.csv',header=T) +#mtl$dist.to.nearest.gene <- d$Distance +#rm(d) +########################### + +mtl$group1 <- ""within.1kb"" +mtl$group1[abs(mtl$dist.to.nearest.gene)>1000] <- "">1kb"" +mtl$group2 <- ""no.H3K4me1"" +mtl$group2[(mtl$In.H3K4me1.Y+mtl$In.H3K4me1.O+mtl$In.H3K4me1.A)>0] <- ""has.H3K4me1"" +table(subset(mtl,select=c(""group1"",""group2""))) + +################# + +mtl.part <- subset(mtl,group1==""within.1kb"" & group2==""has.H3K4me1"",select=c(""In.H3K27ac.Y"",""In.H3K9ac.Y"",""In.H3K122ac.Y"")) +mtl.part$group <- paste0(as.numeric(mtl.part[,1]>0),""-"",as.numeric(mtl.part[,2]>0),""-"",as.numeric(mtl.part[,3]>0)) +t1 <- as.data.frame(table(mtl.part$group)) +colnames(t1) <- c(""group"",""Y"") +mtl.part <- subset(mtl,group1==""within.1kb"" & group2==""has.H3K4me1"",select=c(""In.H3K27ac.O"",""In.H3K9ac.O"",""In.H3K122ac.O"")) +mtl.part$group <- paste0(as.numeric(mtl.part[,1]>0),""-"",as.numeric(mtl.part[,2]>0),""-"",as.numeric(mtl.part[,3]>0)) +t2 <- as.data.frame(table(mtl.part$group)) +colnames(t2) <- c(""group"",""O"") +mtl.part <- subset(mtl,group1==""within.1kb"" & group2==""has.H3K4me1"",select=c(""In.H3K27ac.A"",""In.H3K9ac.A"",""In.H3K122ac.A"")) +mtl.part$group <- paste0(as.numeric(mtl.part[,1]>0),""-"",as.numeric(mtl.part[,2]>0),""-"",as.numeric(mtl.part[,3]>0)) +t3 <- as.data.frame(table(mtl.part$group)) +colnames(t3) <- c(""group"",""A"") +mtl.part <- subset(mtl,group1==""within.1kb"" & group2==""has.H3K4me1"",select=c(""In.H3K27ac.Y"",""In.H3K9ac.Y"",""In.H3K122ac.Y"",""In.H3K27ac.O"",""In.H3K9ac.O"",""In.H3K122ac.O"",""In.H3K27ac.A"",""In.H3K9ac.A"",""In.H3K122ac.A"")) +mtl.part$In.H3K27ac <- mtl.part$In.H3K27ac.Y + mtl.part$In.H3K27ac.O + mtl.part$In.H3K27ac.A +mtl.part$In.H3K9ac <- mtl.part$In.H3K9ac.Y + mtl.part$In.H3K9ac.O + mtl.part$In.H3K9ac.A +mtl.part$In.H3K122ac <- mtl.part$In.H3K122ac.Y + mtl.part$In.H3K122ac.O + mtl.part$In.H3K122ac.A +mtl.part <- subset(mtl.part,select=c(""In.H3K27ac"",""In.H3K9ac"",""In.H3K122ac"")) +mtl.part$group <- paste0(as.numeric(mtl.part[,1]>0),""-"",as.numeric(mtl.part[,2]>0),""-"",as.numeric(mtl.part[,3]>0)) +t4 <- as.data.frame(table(mtl.part$group)) +colnames(t4) <- c(""group"",""any"") +t <- join(t1,t2) +t <- join(t,t3) +t <- join(t,t4) + +################# + +mtl.part <- subset(mtl,group1==""within.1kb"" & group2==""no.H3K4me1"",select=c(""In.H3K27ac.Y"",""In.H3K9ac.Y"",""In.H3K122ac.Y"")) +mtl.part$group <- paste0(as.numeric(mtl.part[,1]>0),""-"",as.numeric(mtl.part[,2]>0),""-"",as.numeric(mtl.part[,3]>0)) +t1 <- as.data.frame(table(mtl.part$group)) +colnames(t1) <- c(""group"",""Y"") +mtl.part <- subset(mtl,group1==""within.1kb"" & group2==""no.H3K4me1"",select=c(""In.H3K27ac.O"",""In.H3K9ac.O"",""In.H3K122ac.O"")) +mtl.part$group <- paste0(as.numeric(mtl.part[,1]>0),""-"",as.numeric(mtl.part[,2]>0),""-"",as.numeric(mtl.part[,3]>0)) +t2 <- as.data.frame(table(mtl.part$group)) +colnames(t2) <- c(""group"",""O"") +mtl.part <- subset(mtl,group1==""within.1kb"" & group2==""no.H3K4me1"",select=c(""In.H3K27ac.A"",""In.H3K9ac.A"",""In.H3K122ac.A"")) +mtl.part$group <- paste0(as.numeric(mtl.part[,1]>0),""-"",as.numeric(mtl.part[,2]>0),""-"",as.numeric(mtl.part[,3]>0)) +t3 <- as.data.frame(table(mtl.part$group)) +colnames(t3) <- c(""group"",""A"") +mtl.part <- subset(mtl,group1==""within.1kb"" & group2==""no.H3K4me1"",select=c(""In.H3K27ac.Y"",""In.H3K9ac.Y"",""In.H3K122ac.Y"",""In.H3K27ac.O"",""In.H3K9ac.O"",""In.H3K122ac.O"",""In.H3K27ac.A"",""In.H3K9ac.A"",""In.H3K122ac.A"")) +mtl.part$In.H3K27ac <- mtl.part$In.H3K27ac.Y + mtl.part$In.H3K27ac.O + mtl.part$In.H3K27ac.A +mtl.part$In.H3K9ac <- mtl.part$In.H3K9ac.Y + mtl.part$In.H3K9ac.O + mtl.part$In.H3K9ac.A +mtl.part$In.H3K122ac <- mtl.part$In.H3K122ac.Y + mtl.part$In.H3K122ac.O + mtl.part$In.H3K122ac.A +mtl.part <- subset(mtl.part,select=c(""In.H3K27ac"",""In.H3K9ac"",""In.H3K122ac"")) +mtl.part$group <- paste0(as.numeric(mtl.part[,1]>0),""-"",as.numeric(mtl.part[,2]>0),""-"",as.numeric(mtl.part[,3]>0)) +t4 <- as.data.frame(table(mtl.part$group)) +colnames(t4) <- c(""group"",""any"") +t <- join(t1,t2) +t <- join(t,t3) +t <- join(t,t4) + +################# + +mtl.part <- subset(mtl,group1=="">1kb"" & group2==""has.H3K4me1"",select=c(""In.H3K27ac.Y"",""In.H3K9ac.Y"",""In.H3K122ac.Y"")) +mtl.part$group <- paste0(as.numeric(mtl.part[,1]>0),""-"",as.numeric(mtl.part[,2]>0),""-"",as.numeric(mtl.part[,3]>0)) +t1 <- as.data.frame(table(mtl.part$group)) +colnames(t1) <- c(""group"",""Y"") +mtl.part <- subset(mtl,group1=="">1kb"" & group2==""has.H3K4me1"",select=c(""In.H3K27ac.O"",""In.H3K9ac.O"",""In.H3K122ac.O"")) +mtl.part$group <- paste0(as.numeric(mtl.part[,1]>0),""-"",as.numeric(mtl.part[,2]>0),""-"",as.numeric(mtl.part[,3]>0)) +t2 <- as.data.frame(table(mtl.part$group)) +colnames(t2) <- c(""group"",""O"") +mtl.part <- subset(mtl,group1=="">1kb"" & group2==""has.H3K4me1"",select=c(""In.H3K27ac.A"",""In.H3K9ac.A"",""In.H3K122ac.A"")) +mtl.part$group <- paste0(as.numeric(mtl.part[,1]>0),""-"",as.numeric(mtl.part[,2]>0),""-"",as.numeric(mtl.part[,3]>0)) +t3 <- as.data.frame(table(mtl.part$group)) +colnames(t3) <- c(""group"",""A"") +mtl.part <- subset(mtl,group1=="">1kb"" & group2==""has.H3K4me1"",select=c(""In.H3K27ac.Y"",""In.H3K9ac.Y"",""In.H3K122ac.Y"",""In.H3K27ac.O"",""In.H3K9ac.O"",""In.H3K122ac.O"",""In.H3K27ac.A"",""In.H3K9ac.A"",""In.H3K122ac.A"")) +mtl.part$In.H3K27ac <- mtl.part$In.H3K27ac.Y + mtl.part$In.H3K27ac.O + mtl.part$In.H3K27ac.A +mtl.part$In.H3K9ac <- mtl.part$In.H3K9ac.Y + mtl.part$In.H3K9ac.O + mtl.part$In.H3K9ac.A +mtl.part$In.H3K122ac <- mtl.part$In.H3K122ac.Y + mtl.part$In.H3K122ac.O + mtl.part$In.H3K122ac.A +mtl.part <- subset(mtl.part,select=c(""In.H3K27ac"",""In.H3K9ac"",""In.H3K122ac"")) +mtl.part$group <- paste0(as.numeric(mtl.part[,1]>0),""-"",as.numeric(mtl.part[,2]>0),""-"",as.numeric(mtl.part[,3]>0)) +t4 <- as.data.frame(table(mtl.part$group)) +colnames(t4) <- c(""group"",""any"") +t <- join(t1,t2) +t <- join(t,t3) +t <- join(t,t4) + +################# + +mtl.part <- subset(mtl,group1=="">1kb"" & group2==""no.H3K4me1"",select=c(""In.H3K27ac.Y"",""In.H3K9ac.Y"",""In.H3K122ac.Y"")) +mtl.part$group <- paste0(as.numeric(mtl.part[,1]>0),""-"",as.numeric(mtl.part[,2]>0),""-"",as.numeric(mtl.part[,3]>0)) +t1 <- as.data.frame(table(mtl.part$group)) +colnames(t1) <- c(""group"",""Y"") +mtl.part <- subset(mtl,group1=="">1kb"" & group2==""no.H3K4me1"",select=c(""In.H3K27ac.O"",""In.H3K9ac.O"",""In.H3K122ac.O"")) +mtl.part$group <- paste0(as.numeric(mtl.part[,1]>0),""-"",as.numeric(mtl.part[,2]>0),""-"",as.numeric(mtl.part[,3]>0)) +t2 <- as.data.frame(table(mtl.part$group)) +colnames(t2) <- c(""group"",""O"") +mtl.part <- subset(mtl,group1=="">1kb"" & group2==""no.H3K4me1"",select=c(""In.H3K27ac.A"",""In.H3K9ac.A"",""In.H3K122ac.A"")) +mtl.part$group <- paste0(as.numeric(mtl.part[,1]>0),""-"",as.numeric(mtl.part[,2]>0),""-"",as.numeric(mtl.part[,3]>0)) +t3 <- as.data.frame(table(mtl.part$group)) +colnames(t3) <- c(""group"",""A"") +mtl.part <- subset(mtl,group1=="">1kb"" & group2==""no.H3K4me1"",select=c(""In.H3K27ac.Y"",""In.H3K9ac.Y"",""In.H3K122ac.Y"",""In.H3K27ac.O"",""In.H3K9ac.O"",""In.H3K122ac.O"",""In.H3K27ac.A"",""In.H3K9ac.A"",""In.H3K122ac.A"")) +mtl.part$In.H3K27ac <- mtl.part$In.H3K27ac.Y + mtl.part$In.H3K27ac.O + mtl.part$In.H3K27ac.A +mtl.part$In.H3K9ac <- mtl.part$In.H3K9ac.Y + mtl.part$In.H3K9ac.O + mtl.part$In.H3K9ac.A +mtl.part$In.H3K122ac <- mtl.part$In.H3K122ac.Y + mtl.part$In.H3K122ac.O + mtl.part$In.H3K122ac.A +mtl.part <- subset(mtl.part,select=c(""In.H3K27ac"",""In.H3K9ac"",""In.H3K122ac"")) +mtl.part$group <- paste0(as.numeric(mtl.part[,1]>0),""-"",as.numeric(mtl.part[,2]>0),""-"",as.numeric(mtl.part[,3]>0)) +t4 <- as.data.frame(table(mtl.part$group)) +colnames(t4) <- c(""group"",""any"") +t <- join(t1,t2) +t <- join(t,t3) +t <- join(t,t4) + +","R" +"Epigenetics","yeminlan/ADEpigenetics","correlation_anova_kmeans.R",".R","7209","201","library(corrplot) +library(ggplot2) +library(reshape2) +library(plyr) +library(data.table) + +auc <- read.table('AUC.txt',sep=""\t"",header=T,stringsAsFactors = F) +mtl <- read.table('MTL.txt',sep=""\t"",header=F,stringsAsFactors = F) +mtl$ID <- paste0(""MTL_"",rownames(mtl)) +rownames(auc) <- mtl$ID +colnames(mtl)[1:6] <- c(""chr"",""start"",""end"",""peak.in.AD"",""peak.in.O"",""peak.in.Y"") + +sample.list <- as.data.frame(colnames(auc)) +colnames(sample.list) <- ""sample"" +sample.list$group <- as.factor(gsub(""\\..*$"","""",sample.list$sample)) + +NeuFrac <- read.table('NeuFrac.txt',sep=""\t"",header=T,stringsAsFactors = F) +NeuFrac$sampleID <- gsub(""-"",""."",NeuFrac$sampleID) + +############################### + +## spearman's correlation +pdf(""correlation.pdf"",height=8,width=7) +c <- cor(auc, method = ""spearman"") +col <- colorRampPalette(c(""blue"",""grey90"",""red"", ""grey90"", ""blue"")) +corrplot(c, type = ""lower"", method = ""number"", order=""hclust"", hclust.method = ""ward.D"", mar=c(0,3,0,0), + tl.cex = 0.5, tl.col = ""black"", number.cex = 0.4, addshade = ""all"", + bg=""white"", cl.lim=c(0,1), col=col(100)) +dev.off() +rm(c,col) + +############################### + +## mask peaks with 10% highest pearson corr with NeuFrac +c <- apply(auc, 1, function(x) cor(NeuFrac$percentage, x, method = ""pearson"") ) +c <- abs(c) +mtl$mask <- as.numeric(c>quantile(c, probs = 0.9)) + +auc.filter <- auc[mtl$mask==0,] + +## PCA plot of all/top10000 MTLs +pdf(""PCA.mask.pdf"",height=8,width=8) +#all MTLs +pc <- prcomp(t(auc.filter), scale=TRUE) +scores <- as.data.frame(pc$x) +v <- as.integer(100*(pc$sdev)^2/sum(pc$sdev^2)) +for (i in 1:5){ + print( paste0(""PC"",i,"" ("",v[i],""%): "",cor(NeuFrac$percentage, scores[,i], method = ""pearson"")) ) +} +ggplot(data = scores, aes(x = PC1, y = PC2, label = rownames(scores), col=sample.list$group)) + + geom_hline(yintercept = 0, colour = ""gray65"") + + geom_vline(xintercept = 0, colour = ""gray65"") + + geom_text(alpha = 0.8, size = 2) + + theme_bw() + theme(panel.grid.major=element_blank(), panel.grid.minor=element_blank()) + + theme(legend.position = ""none"") + + ggtitle(""PCA plot of all MTLs"") + + xlab(paste0(""PC1 ("",v[1],""%)"")) + + ylab(paste0(""PC2 ("",v[2],""%)"")) +#top10000 MTLs +x <- auc.filter[order(rowSums(auc.filter),decreasing=T),] +x <- x[1:10000,] +pc <- prcomp(t(x), scale=TRUE) +scores <- as.data.frame(pc$x) +v <- as.integer(100*(pc$sdev)^2/sum(pc$sdev^2)) +for (i in 1:5){ + print( paste0(""PC"",i,"" ("",v[i],""%): "",cor(NeuFrac$percentage, scores[,i], method = ""pearson"")) ) +} +ggplot(data = scores, aes(x = PC1, y = PC2, label = rownames(scores), col=sample.list$group)) + + geom_hline(yintercept = 0, colour = ""gray65"") + + geom_vline(xintercept = 0, colour = ""gray65"") + + geom_text(alpha = 0.8, size = 2) + + theme_bw() + theme(panel.grid.major=element_blank(), panel.grid.minor=element_blank()) + + theme(legend.position = ""none"") + + ggtitle(""PCA plot of top 10000 MTLs"") + + xlab(paste0(""PC1 ("",v[1],""%)"")) + + ylab(paste0(""PC2 ("",v[2],""%)"")) +dev.off() +rm(pc,scores,v,x) + +############################### + +## PCA plot of all/top10000 MTLs +pdf(""PCA.pdf"",height=8,width=8) +#all MTLs +pc <- prcomp(t(auc), scale=TRUE) +scores <- as.data.frame(pc$x) +v <- as.integer(100*(pc$sdev)^2/sum(pc$sdev^2)) +for (i in 1:5){ + print( paste0(""PC"",i,"" ("",v[i],""%): "",cor(NeuFrac$percentage, scores[,i], method = ""spearman"")) ) +} +ggplot(data = scores, aes(x = PC1, y = PC2, label = rownames(scores), col=sample.list$group)) + + geom_hline(yintercept = 0, colour = ""gray65"") + + geom_vline(xintercept = 0, colour = ""gray65"") + + geom_text(alpha = 0.8, size = 2) + + theme_bw() + theme(panel.grid.major=element_blank(), panel.grid.minor=element_blank()) + + theme(legend.position = ""none"") + + ggtitle(""PCA plot of all MTLs"") + + xlab(paste0(""PC1 ("",v[1],""%)"")) + + ylab(paste0(""PC2 ("",v[2],""%)"")) +#top10000 MTLs +x <- auc[order(rowSums(auc),decreasing=T),] +x <- x[1:10000,] +pc <- prcomp(t(x), scale=TRUE) +scores <- as.data.frame(pc$x) +v <- as.integer(100*(pc$sdev)^2/sum(pc$sdev^2)) +for (i in 1:5){ + print( paste0(""PC"",i,"" ("",v[i],""%): "",cor(NeuFrac$percentage, scores[,i], method = ""spearman"")) ) +} +ggplot(data = scores, aes(x = PC1, y = PC2, label = rownames(scores), col=sample.list$group)) + + geom_hline(yintercept = 0, colour = ""gray65"") + + geom_vline(xintercept = 0, colour = ""gray65"") + + geom_text(alpha = 0.8, size = 2) + + theme_bw() + theme(panel.grid.major=element_blank(), panel.grid.minor=element_blank()) + + theme(legend.position = ""none"") + + ggtitle(""PCA plot of top 10000 MTLs"") + + xlab(paste0(""PC1 ("",v[1],""%)"")) + + ylab(paste0(""PC2 ("",v[2],""%)"")) +dev.off() +rm(pc,scores,v,x) + +############################### + +## anova +for (i in 1:dim(auc)[1]) { + d <- melt(auc[i,]) + colnames(d) <- c(""sample"",""auc"") + d <- join(d,sample.list,by=""sample"") + fit <- lm(auc ~ group, data=d) + fit2 <- anova(fit) + mtl$anova[i] <- fit2$`Pr(>F)`[1] +} +rm(d,i,fit,fit2) + +## PCA plot of significant MTLs +auc.sig <- auc[mtl$anova<0.05,] +pdf(""PCA.sig.pdf"",height=8,width=8) +pc <- prcomp(t(auc.sig), scale=TRUE) +scores <- as.data.frame(pc$x) +v <- as.integer(100*(pc$sdev)^2/sum(pc$sdev^2)) +ggplot(data = scores, aes(x = PC1, y = PC2, label = rownames(scores), col=sample.list$group)) + + geom_hline(yintercept = 0, colour = ""gray65"") + + geom_vline(xintercept = 0, colour = ""gray65"") + + geom_text(alpha = 0.8, size = 2) + + theme_bw() + theme(panel.grid.major=element_blank(), panel.grid.minor=element_blank()) + + theme(legend.position = ""none"") + + ggtitle(""PCA plot of significant MTLs"") + + xlab(paste0(""PC1 ("",v[1],""%)"")) + + ylab(paste0(""PC2 ("",v[2],""%)"")) +dev.off() +rm(pc,scores,v) + +## k-means for anova.sig.MTLs +pdf(""k-means_decide.pdf"",height=4,width=6) +wss <- (nrow(auc.sig)-1)*sum(apply(auc.sig,2,var)) +for (i in 2:15) wss[i] <- sum(kmeans(auc.sig,centers=i)$withinss) +plot(1:15, wss, type=""b"", xlab=""Number of Clusters"", ylab=""Within groups sum of squares"") +dev.off() + +bestK <- 10 + +set.seed(1) +wss <- kmeans(auc.sig,centers=bestK) +d <- as.data.frame(wss$cluster) +d$ID <- row.names(d) +colnames(d) <- c(""k.means"",""ID"") +mtl <- join(mtl,d) +mtl$k.means[is.na(mtl$k.means)] <- 0 #non-sig MTLs were assigned to cluster0 +rm(d,wss) + +for (i in 1:bestK){ + t <- mtl[mtl$k.means==i,] + print(c(wilcox.test(t$Y.auc,t$O.auc)$p.value, wilcox.test(t$Y.auc,t$AD.auc)$p.value, wilcox.test(t$O.auc,t$AD.auc)$p.value)) +} +rm(i,t) + +############################### + +mtl$AD.auc <- rowMeans(auc[,colnames(auc) %like% ""AD.""]) +mtl$O.auc <- rowMeans(auc[,colnames(auc) %like% ""O.""]) +mtl$Y.auc <- rowMeans(auc[,colnames(auc) %like% ""Y.""]) + +############################### + +d <- melt(mtl,id.vars=c(""chr"",""start"",""end"",""peak.in.AD"",""peak.in.O"",""peak.in.Y"",""ID"",""anova"",""k.means""), + variable.name = ""group"", value.name = ""ave.AUC"") +d <- d[d$k.means!=0,] +d$group <- gsub("".auc"","""",d$group) +d$group <- factor(d$group,c(""Y"",""O"",""AD"")) +pdf(""k-means_boxplot.pdf"",height=4,width=8) +ggplot(d,aes(group,ave.AUC,fill=group)) + geom_boxplot() + + facet_wrap(~k.means, nrow = 2, scales = ""free"") + + theme_bw() + theme(panel.grid.major=element_blank(), panel.grid.minor=element_blank()) + + theme(legend.position = ""none"") + xlab("""") +dev.off() +table(mtl$k.means) +rm(d) + +############################### + +write.csv(mtl,""MTL.result.csv"",row.names = F) +","R" +"Epigenetics","yeminlan/ADEpigenetics","distance_to_ensembleTSS.sh",".sh","336","10","awk '{FS=OFS=""\t""}{if($6==""+"")print $1,$2,$2;else print $1,$3,$3}' /project/ibilab/library/annotation/hg19/hg19_ensembl.bed12 | sort -k1,1 -k2,2n | uniq > hg19_TSS.bed +bedtools closest -a multiMTL.bed -b hg19_TSS.bed -d -t first | cut -f7 | sed ""s|-1|1000000|g"" > t1 +R --no-save < log/distance_to_ensembleTSS.R +rm t1 hg19_TSS.bed + + + + + +","Shell" +"Epigenetics","yeminlan/ADEpigenetics","get_csv.R",".R","2185","44","library(corrplot) +library(ggplot2) +library(reshape2) +library(plyr) +library(data.table) + +mtl <- read.table('multiMTL.bed',sep=""\t"",header=F,stringsAsFactors = F) +mtl$ID <- paste0(""MTL_"",rownames(mtl)) +colnames(mtl) <- c(""chr"",""start"",""end"",""ID"") + +in.mtl <- read.table('InMTL.txt',sep=""\t"",header=T,stringsAsFactors = F) +mtl <- cbind(mtl,in.mtl) +rm(in.mtl) + +auc <- read.table('AUC.txt',sep=""\t"",header=T,stringsAsFactors = F) +rownames(auc) <- mtl$ID + +sample.list <- as.data.frame(colnames(auc)) +colnames(sample.list) <- ""sample"" +sample.list$group <- as.factor(gsub(""\\..*$"","""",sample.list$sample)) +sample.list$marker <- as.factor(gsub(""^.*\\."","""",sample.list$sample)) + +mtl$CTCF.Y.auc <- log2( rowMeans(auc[,colnames(auc) %like% ""Y.*.CTCF""]) + 1) +mtl$CTCF.O.auc <- log2( rowMeans(auc[,colnames(auc) %like% ""O.*.CTCF""]) + 1) +mtl$CTCF.A.auc <- log2( rowMeans(auc[,colnames(auc) %like% ""AD.*.CTCF""]) + 1) +mtl$Rad21.Y.auc <- log2( rowMeans(auc[,colnames(auc) %like% ""Y.*.Rad21""]) + 1) +mtl$Rad21.O.auc <- log2( rowMeans(auc[,colnames(auc) %like% ""O.*.Rad21""]) + 1) +mtl$Rad21.A.auc <- log2( rowMeans(auc[,colnames(auc) %like% ""AD.*.Rad21""]) + 1) +mtl$H3K27ac.Y.auc <- log2( rowMeans(auc[,colnames(auc) %like% ""Y.*.H3K27ac""]) + 1) +mtl$H3K27ac.O.auc <- log2( rowMeans(auc[,colnames(auc) %like% ""O.*.H3K27ac""]) + 1) +mtl$H3K27ac.A.auc <- log2( rowMeans(auc[,colnames(auc) %like% ""AD.*.H3K27ac""]) + 1) +mtl$H3K9ac.Y.auc <- log2( rowMeans(auc[,colnames(auc) %like% ""Y.*.H3K9ac""]) + 1) +mtl$H3K9ac.O.auc <- log2( rowMeans(auc[,colnames(auc) %like% ""O.*.H3K9ac""]) + 1) +mtl$H3K9ac.A.auc <- log2( rowMeans(auc[,colnames(auc) %like% ""AD.*.H3K9ac""]) + 1) +mtl$H3K122ac.Y.auc <- log2( rowMeans(auc[,colnames(auc) %like% ""Y.*.H3K122ac""]) + 1) +mtl$H3K122ac.O.auc <- log2( rowMeans(auc[,colnames(auc) %like% ""O.*.H3K122ac""]) + 1) +mtl$H3K122ac.A.auc <- log2( rowMeans(auc[,colnames(auc) %like% ""AD.*.H3K122ac""]) + 1) +mtl$H3K4me1.Y.auc <- log2( rowMeans(auc[,colnames(auc) %like% ""Y.*.H3K4me1""]) + 1) +mtl$H3K4me1.O.auc <- log2( rowMeans(auc[,colnames(auc) %like% ""O.*.H3K4me1""]) + 1) +mtl$H3K4me1.A.auc <- log2( rowMeans(auc[,colnames(auc) %like% ""AD.*.H3K4me1""]) + 1) + +write.csv(mtl,""MTL.result.csv"",row.names = F) + +","R" +"Epigenetics","yeminlan/ADEpigenetics","pairwise_comparison.R",".R","5341","169","library(corrplot) +library(ggplot2) +library(reshape2) +library(plyr) +library(data.table) + +MTL <- read.csv('MTL.result.csv') +AUC <- read.table('AUC.txt',sep=""\t"",header=T,stringsAsFactors = F) + +################ H3K27ac ################ + +auc <- AUC[,colnames(AUC) %like% ""H3K27ac""] +mtl <- subset(MTL,select=""ID"") + +sample.list <- as.data.frame(colnames(auc)) +colnames(sample.list) <- ""sample"" +sample.list$group <- as.factor(gsub(""\\..*$"","""",sample.list$sample)) + +## pairwise comparison of Y_vs_O +s1 <- sample.list[sample.list$group == ""Y"",] +s2 <- sample.list[sample.list$group == ""O"",] +x1 <- subset(auc,select=s1$sample) +x2 <- subset(auc,select=s2$sample) +## wilcox +for (i in 1:dim(x1)[1]) { + mtl$Y.vs.O.pval[i] <- wilcox.test( as.numeric(x1[i,]), as.numeric(x2[i,]) )$p.value +} +mtl$Y.vs.O.qval <- p.adjust(mtl$Y.vs.O.pval,method=""fdr"") +mtl$Y.vs.O.diff <- rowMeans(x2) - rowMeans(x1) +rm(s1,s2,x1,x2,i) + +## pairwise comparison of Y_vs_AD +s1 <- sample.list[sample.list$group == ""Y"",] +s2 <- sample.list[sample.list$group == ""AD"",] +x1 <- subset(auc,select=s1$sample) +x2 <- subset(auc,select=s2$sample) +## wilcox +for (i in 1:dim(x1)[1]) { + mtl$Y.vs.AD.pval[i] <- wilcox.test( as.numeric(x1[i,]), as.numeric(x2[i,]) )$p.value +} +mtl$Y.vs.AD.qval <- p.adjust(mtl$Y.vs.AD.pval,method=""fdr"") +mtl$Y.vs.AD.diff <- rowMeans(x2) - rowMeans(x1) +rm(s1,s2,x1,x2,i) + +## pairwise comparison of O_vs_AD +s1 <- sample.list[sample.list$group == ""O"",] +s2 <- sample.list[sample.list$group == ""AD"",] +x1 <- subset(auc,select=s1$sample) +x2 <- subset(auc,select=s2$sample) +## wilcox +for (i in 1:dim(x1)[1]) { + mtl$O.vs.AD.pval[i] <- wilcox.test( as.numeric(x1[i,]), as.numeric(x2[i,]) )$p.value +} +mtl$O.vs.AD.qval <- p.adjust(mtl$O.vs.AD.pval,method=""fdr"") +mtl$O.vs.AD.diff <- rowMeans(x2) - rowMeans(x1) +rm(s1,s2,x1,x2,i) + +mtl$ID <- NULL +colnames(mtl) <- paste0(""H3K27ac."",colnames(mtl)) +MTL <- cbind(MTL,mtl) + +################ H3K9ac ################ + +auc <- AUC[,colnames(AUC) %like% ""H3K9ac""] +mtl <- subset(MTL,select=""ID"") + +sample.list <- as.data.frame(colnames(auc)) +colnames(sample.list) <- ""sample"" +sample.list$group <- as.factor(gsub(""\\..*$"","""",sample.list$sample)) + +## pairwise comparison of Y_vs_O +s1 <- sample.list[sample.list$group == ""Y"",] +s2 <- sample.list[sample.list$group == ""O"",] +x1 <- subset(auc,select=s1$sample) +x2 <- subset(auc,select=s2$sample) +## wilcox +for (i in 1:dim(x1)[1]) { + mtl$Y.vs.O.pval[i] <- wilcox.test( as.numeric(x1[i,]), as.numeric(x2[i,]) )$p.value +} +mtl$Y.vs.O.qval <- p.adjust(mtl$Y.vs.O.pval,method=""fdr"") +mtl$Y.vs.O.diff <- rowMeans(x2) - rowMeans(x1) +rm(s1,s2,x1,x2,i) + +## pairwise comparison of Y_vs_AD +s1 <- sample.list[sample.list$group == ""Y"",] +s2 <- sample.list[sample.list$group == ""AD"",] +x1 <- subset(auc,select=s1$sample) +x2 <- subset(auc,select=s2$sample) +## wilcox +for (i in 1:dim(x1)[1]) { + mtl$Y.vs.AD.pval[i] <- wilcox.test( as.numeric(x1[i,]), as.numeric(x2[i,]) )$p.value +} +mtl$Y.vs.AD.qval <- p.adjust(mtl$Y.vs.AD.pval,method=""fdr"") +mtl$Y.vs.AD.diff <- rowMeans(x2) - rowMeans(x1) +rm(s1,s2,x1,x2,i) + +## pairwise comparison of O_vs_AD +s1 <- sample.list[sample.list$group == ""O"",] +s2 <- sample.list[sample.list$group == ""AD"",] +x1 <- subset(auc,select=s1$sample) +x2 <- subset(auc,select=s2$sample) +## wilcox +for (i in 1:dim(x1)[1]) { + mtl$O.vs.AD.pval[i] <- wilcox.test( as.numeric(x1[i,]), as.numeric(x2[i,]) )$p.value +} +mtl$O.vs.AD.qval <- p.adjust(mtl$O.vs.AD.pval,method=""fdr"") +mtl$O.vs.AD.diff <- rowMeans(x2) - rowMeans(x1) +rm(s1,s2,x1,x2,i) + +mtl$ID <- NULL +colnames(mtl) <- paste0(""H3K9ac."",colnames(mtl)) +MTL <- cbind(MTL,mtl) + +################ H3K122ac ################ + +auc <- AUC[,colnames(AUC) %like% ""H3K122ac""] +mtl <- subset(MTL,select=""ID"") + +sample.list <- as.data.frame(colnames(auc)) +colnames(sample.list) <- ""sample"" +sample.list$group <- as.factor(gsub(""\\..*$"","""",sample.list$sample)) + +## pairwise comparison of Y_vs_O +s1 <- sample.list[sample.list$group == ""Y"",] +s2 <- sample.list[sample.list$group == ""O"",] +x1 <- subset(auc,select=s1$sample) +x2 <- subset(auc,select=s2$sample) +## wilcox +for (i in 1:dim(x1)[1]) { + mtl$Y.vs.O.pval[i] <- wilcox.test( as.numeric(x1[i,]), as.numeric(x2[i,]) )$p.value +} +mtl$Y.vs.O.qval <- p.adjust(mtl$Y.vs.O.pval,method=""fdr"") +mtl$Y.vs.O.diff <- rowMeans(x2) - rowMeans(x1) +rm(s1,s2,x1,x2,i) + +## pairwise comparison of Y_vs_AD +s1 <- sample.list[sample.list$group == ""Y"",] +s2 <- sample.list[sample.list$group == ""AD"",] +x1 <- subset(auc,select=s1$sample) +x2 <- subset(auc,select=s2$sample) +## wilcox +for (i in 1:dim(x1)[1]) { + mtl$Y.vs.AD.pval[i] <- wilcox.test( as.numeric(x1[i,]), as.numeric(x2[i,]) )$p.value +} +mtl$Y.vs.AD.qval <- p.adjust(mtl$Y.vs.AD.pval,method=""fdr"") +mtl$Y.vs.AD.diff <- rowMeans(x2) - rowMeans(x1) +rm(s1,s2,x1,x2,i) + +## pairwise comparison of O_vs_AD +s1 <- sample.list[sample.list$group == ""O"",] +s2 <- sample.list[sample.list$group == ""AD"",] +x1 <- subset(auc,select=s1$sample) +x2 <- subset(auc,select=s2$sample) +## wilcox +for (i in 1:dim(x1)[1]) { + mtl$O.vs.AD.pval[i] <- wilcox.test( as.numeric(x1[i,]), as.numeric(x2[i,]) )$p.value +} +mtl$O.vs.AD.qval <- p.adjust(mtl$O.vs.AD.pval,method=""fdr"") +mtl$O.vs.AD.diff <- rowMeans(x2) - rowMeans(x1) +rm(s1,s2,x1,x2,i) + +mtl$ID <- NULL +colnames(mtl) <- paste0(""H3K122ac."",colnames(mtl)) +MTL <- cbind(MTL,mtl) + +################################ + +write.csv(MTL,'MTL.result.csv',row.names = F) +","R" +"Epigenetics","yeminlan/ADEpigenetics","MTL.result.collapsed.R",".R","576","15","## add CTCF/Rad21 within 5kb +d <- read.csv('MTL.result.log2.csv',header=T,check.names=F) +t1 <- read.table('MTL.hasCTCF_5kb.bed',header=F) +t2 <- read.table('MTL.hasRad21_5kb.bed',header=F) +d$hasCTCF.5kb <- t1$V1 +d$hasRad21.5kb <- t2$V1 +write.csv(d,'MTL.result.log2.csv',row.names=F) + +## collapse MTL table so that each transcript appear once (record only the nearest peak to its TSS) +d <- d[order(d$Distance,decreasing=F),] +d2 <- subset(d, !duplicated(Genes)) +d2 <- d2[order(as.numeric(rownames(d2)),decreasing=F),] +write.csv(d2,'MTL.result.log2.collapsed.csv',row.names=F) + +","R" +"Epigenetics","yeminlan/ADEpigenetics","add_nearest_gene.R",".R","605","19","library(plyr) +library(data.table) + +mtl <- read.csv('MTL.result.csv',stringsAsFactors = F) + +t <- read.table('multiMTL.anno.txt',header=T,sep=""\t"",comment.char = """",quote = """",stringsAsFactors = F) +t <- t[,c(2,3,4,10,16)] +colnames(t) <- c(""chr"",""start"",""end"",""dist.to.nearest.gene"",""nearest.gene"") +t$start <- t$start-1 +mtl <- join(mtl,t) +mtl <- mtl[,c( 1:3,dim(mtl)[2]-1,dim(mtl)[2],4:(dim(mtl)[2]-2) )] + +## merge coordinate 3-columns to 1 column +mtl$coordinate <- paste0(mtl$chr,"":"",mtl$start,""-"",mtl$end) +mtl <- mtl[, c( dim(mtl)[2],4:(dim(mtl)[2]-1) ) ] + +## +write.csv(mtl,'MTL.result.csv',row.names = F) +","R" +"Epigenetics","yeminlan/ADEpigenetics","peak_size.R",".R","1041","35","library(ggplot2) + +d1 <- read.table('multiMTL.bed',header=F,sep=""\t"") +d1$peakwidth <- (d1[,3] - d1[,2]) +d1$group <- ""multiMTL"" +d1 <- subset(d1, select=c(""peakwidth"",""group"")) + +d2 <- read.table('MTL.H3K27ac.bed',header=F,sep=""\t"") +d2$peakwidth <- (d2[,3] - d2[,2]) +d2$group <- ""MTL.H3K27ac"" +d2 <- subset(d2, select=c(""peakwidth"",""group"")) + +d3 <- read.table('MTL.H3K9ac.bed',header=F,sep=""\t"") +d3$peakwidth <- (d3[,3] - d3[,2]) +d3$group <- ""MTL.H3K9ac"" +d3 <- subset(d3, select=c(""peakwidth"",""group"")) + +d4 <- read.table('MTL.H3K122ac.bed',header=F,sep=""\t"") +d4$peakwidth <- (d4[,3] - d4[,2]) +d4$group <- ""MTL.H3K122ac"" +d4 <- subset(d4, select=c(""peakwidth"",""group"")) + +d <- rbind(d1,d2,d3,d4) +d$group <- factor(d$group,c(""multiMTL"",""MTL.H3K27ac"",""MTL.H3K9ac"",""MTL.H3K122ac"")) + +pdf('peak_size.pdf',height=4,width=6) +ggplot(d,aes(log10(peakwidth),col=group)) + + #geom_density() + + geom_freqpoly() + + theme_bw(base_size=16) + + theme(panel.grid.major=element_blank(), panel.grid.minor=element_blank()) + + geom_hline(yintercept = 0) +dev.off() + +","R" +"Epigenetics","yeminlan/ADEpigenetics","summarize_AUC.R",".R","1289","47","library(plyr) +library(data.table) + +## read AUC.txt from single mark MTL +d <- read.table('t3',header=F,sep=""\t"") +# multiMTL +dA <- d[,1:3] +colnames(dA) <- c(""chr"",""start"",""end"") +# MTL +dB <- d[,4:6] +colnames(dB) <- c(""chr"",""start"",""end"") +# AUC +dC <- d[,7:dim(d)[2]] +h <- read.table('t2',header=T,sep=""\t"",comment.char="""",check.names=F) +colnames(dC) <- colnames(h)[4:dim(h)[2]] +rm(h) + +# use AUC*width to aggregate +dA$coordinate <- paste0(dA$chr,"":"",dA$start,""-"",dA$end) +dB$width <- dB$end-dB$start +dC <- dC * dB$width/1000 +d <- cbind( subset(dA,select=""coordinate"") , subset(dB,select=""width"") , dC ) +D <- aggregate(d[,-1] ,by=list(d$coordinate),FUN=""sum"") +colnames(D)[1] <- ""coordinate"" + +## divide aggregated sum by aggregated width +DA <- D[,1:2] +DA$chr <- gsub("":.*$"","""",DA$coordinate) +DA$start <- gsub(""-.*$"","""",gsub("".*:"","""",DA$coordinate)) +DA$end <- gsub("".*-"","""",DA$coordinate) +DB <- D[,3:dim(D)[2]] +DB <- DB*1000/DA$width +D <- cbind( subset(DA,select=c(""coordinate"")) ,DB) +# + +## join to multiMTL table and replace zeros +mtl <- read.table('multiMTL.bed',header=F,sep=""\t"") +colnames(mtl) <- c(""chr"",""start"",""end"") +mtl$coordinate <- paste0(mtl$chr,"":"",mtl$start,""-"",mtl$end) +mtl <- join(mtl,D) +D <- mtl[,c(-1:-4)] +D[is.na(D)] <- 0 + +write.table(D,'AUC.txt',sep=""\t"",row.names=F,quote=F) + + +","R" +"Epigenetics","yeminlan/ADEpigenetics","add_rna.R",".R","2331","41","library(plyr) +library(data.table) + +mtl <- read.csv('MTL.result.csv', check.names=F, stringsAsFactors = F) +colnames(mtl) <- c(""Locus"",""Distance"",""Genes"",""ID"", + ""CTCF.InA"",""CTCF.InO"",""CTCF.InY"",""Rad21.InA"",""Rad21.InO"",""Rad21.InY"", + ""H3K27ac.InA"",""H3K27ac.InO"",""H3K27ac.InY"",""H3K9ac.InA"",""H3K9ac.InO"",""H3K9ac.InY"", + ""H3K122ac.InA"",""H3K122ac.InO"",""H3K122ac.InY"",""H3K4me1.InA"",""H3K4me1.InO"",""H3K4me1.InY"", + ""CTCF.HY"",""CTCF.HO"",""CTCF.HA"",""Rad21.HY"",""Rad21.HO"",""Rad21.HA"", + ""H3K27ac.HY"",""H3K27ac.HO"",""H3K27ac.HA"",""H3K9ac.HY"",""H3K9ac.HO"",""H3K9ac.HA"", + ""H3K122ac.HY"",""H3K122ac.HO"",""H3K122ac.HA"",""H3K4me1.HY"",""H3K4me1.HO"",""H3K4me1.HA"", + ""H3K27ac.PHO-HY"",""H3K27ac.QHO-HY"",""H3K27ac.HO-HY"",""H3K27ac.PHA-HY"",""H3K27ac.QHA-HY"",""H3K27ac.HA-HY"", + ""H3K27ac.PHA-HO"",""H3K27ac.QHA-HO"",""H3K27ac.HA-HO"",""H3K9ac.PHO-HY"",""H3K9ac.QHO-HY"",""H3K9ac.HO-HY"", + ""H3K9ac.PHA-HY"",""H3K9ac.QHA-HY"",""H3K9ac.HA-HY"",""H3K9ac.PHA-HO"",""H3K9ac.QHA-HO"",""H3K9ac.HA-HO"", + ""H3K122ac.PHO-HY"",""H3K122ac.QHO-HY"",""H3K122ac.HO-HY"",""H3K122ac.PHA-HY"",""H3K122ac.QHA-HY"",""H3K122ac.HA-HY"", + ""H3K122ac.PHA-HO"",""H3K122ac.QHA-HO"",""H3K122ac.HA-HO"") + +mtl$Distance <- abs(mtl$Distance) +mtl$Distance.group <- cut(mtl$Distance,breaks=c(0,1000,50000,100000,Inf),include.lowest=T) +levels(mtl$Distance.group) <- c(""within.1kb"",""1-50kb"",""50-100kb"",""beyond.100kb"") + +mtl$`H3K27ac.HO-HY` <- mtl$H3K27ac.HO - mtl$H3K27ac.HY +mtl$`H3K27ac.HA-HY` <- mtl$H3K27ac.HA - mtl$H3K27ac.HY +mtl$`H3K27ac.HA-HO` <- mtl$H3K27ac.HA - mtl$H3K27ac.HO +mtl$`H3K9ac.HO-HY` <- mtl$H3K9ac.HO - mtl$H3K9ac.HY +mtl$`H3K9ac.HA-HY` <- mtl$H3K9ac.HA - mtl$H3K9ac.HY +mtl$`H3K9ac.HA-HO` <- mtl$H3K9ac.HA - mtl$H3K9ac.HO +mtl$`H3K122ac.HO-HY` <- mtl$H3K122ac.HO - mtl$H3K122ac.HY +mtl$`H3K122ac.HA-HY` <- mtl$H3K122ac.HA - mtl$H3K122ac.HY +mtl$`H3K122ac.HA-HO` <- mtl$H3K122ac.HA - mtl$H3K122ac.HO + +mtl <- subset(mtl,select=c(""Locus"",""Genes"",""Distance"",""Distance.group"",""ID"", colnames(mtl)[!(colnames(mtl) %in% c(""Locus"",""Genes"",""Distance"",""Distance.group"",""ID""))] )) + +rna <- read.csv('brain.rna.csv', check.names=F, stringsAsFactors = F) +colnames(rna)[1] <- ""Genes"" + +mtl <- join(mtl,rna) + +write.csv(mtl,'MTL.result.log2.csv',row.names = F) + +","R"