OSCR

A genome-wide cross-trait analysis detects shared genetic architecture between alcohol use disorder and ischemic stroke.

Code ↔ Paper

2 matches between paragraphs of the paper and lines of its authors' code, computed by the harvester (lexical-v1). Click a colored paragraph or line to see its counterpart.

2 blocks of code here have a permanent identifier (oscr:b:…), listed with the matches below: citable for good, with a page of its own. Select a match and press Cite to copy it. What a block identifier is.

The 2 matches
  1. [1] § Materials and methods › Global and local genetic correlation analysis ↔ ldsc.py, lines 547 to 617 · score 0.74 · liability scale, population prevalence, sample prevalence, munge_sumstats.py, genetic correlation, LDSC · block oscr:b:C0T1QRDE1JXR2-U · Report a mismatch
  2. [2] § Materials and methods › Global and local genetic correlation analysis ↔ ldsc_mod/ldsc.py, lines 547 to 617 · score 0.74 · liability scale, population prevalence, sample prevalence, munge_sumstats.py, genetic correlation, LDSC · block oscr:b:5CKB2AF0SBD10-4 · Report a mismatch

Paper

Loaded from Europe PMC by your browser; OSCR does not store it: doi.org · Europe PMC

The paper is loaded when this pane is shown.

The authors' code

Python · 660 lines · 30 KB · GPL-3.0 · 1 match

  1. #!/usr/bin/env python
  2. '''
  3. (c) 2014 Brendan Bulik-Sullivan and Hilary Finucane
  4. LDSC is a command line tool for estimating
  5. 1. LD Score
  6. 2. heritability / partitioned heritability
  7. 3. genetic covariance / correlation
  8. '''
  9. from __future__ import division
  10. import ldscore.ldscore as ld
  11. import ldscore.parse as ps
  12. import ldscore.sumstats as sumstats
  13. import ldscore.regressions as reg
  14. import numpy as np
  15. import pandas as pd
  16. from subprocess import call
  17. from itertools import product
  18. import time, sys, traceback, argparse
  19. try:
  20. x = pd.DataFrame({'A': [1, 2, 3]})
  21. x.sort_values(by='A')
  22. except AttributeError:
  23. raise ImportError('LDSC requires pandas version >= 0.17.0')
  24. __version__ = '1.0.1'
  25. MASTHEAD = "*********************************************************************\n"
  26. MASTHEAD += "* LD Score Regression (LDSC)\n"
  27. MASTHEAD += "* Version {V}\n".format(V=__version__)
  28. MASTHEAD += "* (C) 2014-2019 Brendan Bulik-Sullivan and Hilary Finucane\n"
  29. MASTHEAD += "* Broad Institute of MIT and Harvard / MIT Department of Mathematics\n"
  30. MASTHEAD += "* GNU General Public License v3\n"
  31. MASTHEAD += "*********************************************************************\n"
  32. pd.set_option('display.max_rows', 500)
  33. pd.set_option('display.max_columns', 500)
  34. pd.set_option('display.width', 1000)
  35. pd.set_option('precision', 4)
  36. pd.set_option('max_colwidth',1000)
  37. np.set_printoptions(linewidth=1000)
  38. np.set_printoptions(precision=4)
  39. def sec_to_str(t):
  40. '''Convert seconds to days:hours:minutes:seconds'''
  41. [d, h, m, s, n] = reduce(lambda ll, b : divmod(ll[0], b) + ll[1:], [(t, 1), 60, 60, 24])
  42. f = ''
  43. if d > 0:
  44. f += '{D}d:'.format(D=d)
  45. if h > 0:
  46. f += '{H}h:'.format(H=h)
  47. if m > 0:
  48. f += '{M}m:'.format(M=m)
  49. f += '{S}s'.format(S=s)
  50. return f
  51. def _remove_dtype(x):
  52. '''Removes dtype: float64 and dtype: int64 from pandas printouts'''
  53. x = str(x)
  54. x = x.replace('\ndtype: int64', '')
  55. x = x.replace('\ndtype: float64', '')
  56. return x
  57. class Logger(object):
  58. '''
  59. Lightweight logging.
  60. TODO: replace with logging module
  61. '''
  62. def __init__(self, fh):
  63. self.log_fh = open(fh, 'wb')
  64. def log(self, msg):
  65. '''
  66. Print to log file and stdout with a single command.
  67. '''
  68. print >>self.log_fh, msg
  69. print msg
  70. def __filter__(fname, noun, verb, merge_obj):
  71. merged_list = None
  72. if fname:
  73. f = lambda x,n: x.format(noun=noun, verb=verb, fname=fname, num=n)
  74. x = ps.FilterFile(fname)
  75. c = 'Read list of {num} {noun} to {verb} from {fname}'
  76. print f(c, len(x.IDList))
  77. merged_list = merge_obj.loj(x.IDList)
  78. len_merged_list = len(merged_list)
  79. if len_merged_list > 0:
  80. c = 'After merging, {num} {noun} remain'
  81. print f(c, len_merged_list)
  82. else:
  83. error_msg = 'No {noun} retained for analysis'
  84. raise ValueError(f(error_msg, 0))
  85. return merged_list
  86. def annot_sort_key(s):
  87. '''For use with --cts-bin. Fixes weird pandas crosstab column order.'''
  88. if type(s) == tuple:
  89. s = [x.split('_')[0] for x in s]
  90. s = map(lambda x: float(x) if x != 'min' else -float('inf'), s)
  91. else: # type(s) = str:
  92. s = s.split('_')[0]
  93. if s == 'min':
  94. s = float('-inf')
  95. else:
  96. s = float(s)
  97. return s
  98. def ldscore(args, log):
  99. '''
  100. Wrapper function for estimating l1, l1^2, l2 and l4 (+ optionally standard errors) from
  101. reference panel genotypes.
  102. Annot format is
  103. chr snp bp cm <annotations>
  104. '''
  105. if args.bfile:
  106. snp_file, snp_obj = args.bfile+'.bim', ps.PlinkBIMFile
  107. ind_file, ind_obj = args.bfile+'.fam', ps.PlinkFAMFile
  108. array_file, array_obj = args.bfile+'.bed', ld.PlinkBEDFile
  109. # read bim/snp
  110. array_snps = snp_obj(snp_file)
  111. m = len(array_snps.IDList)
  112. log.log('Read list of {m} SNPs from {f}'.format(m=m, f=snp_file))
  113. if args.annot is not None: # read --annot
  114. try:
  115. if args.thin_annot: # annot file has only annotations
  116. annot = ps.ThinAnnotFile(args.annot)
  117. n_annot, ma = len(annot.df.columns), len(annot.df)
  118. log.log("Read {A} annotations for {M} SNPs from {f}".format(f=args.annot,
  119. A=n_annot, M=ma))
  120. annot_matrix = annot.df.values
  121. annot_colnames = annot.df.columns
  122. keep_snps = None
  123. else:
  124. annot = ps.AnnotFile(args.annot)
  125. n_annot, ma = len(annot.df.columns) - 4, len(annot.df)
  126. log.log("Read {A} annotations for {M} SNPs from {f}".format(f=args.annot,
  127. A=n_annot, M=ma))
  128. annot_matrix = np.array(annot.df.iloc[:,4:])
  129. annot_colnames = annot.df.columns[4:]
  130. keep_snps = None
  131. if np.any(annot.df.SNP.values != array_snps.df.SNP.values):
  132. raise ValueError('The .annot file must contain the same SNPs in the same'+\
  133. ' order as the .bim file.')
  134. except Exception:
  135. log.log('Error parsing .annot file')
  136. raise
  137. elif args.extract is not None: # --extract
  138. keep_snps = __filter__(args.extract, 'SNPs', 'include', array_snps)
  139. annot_matrix, annot_colnames, n_annot = None, None, 1
  140. elif args.cts_bin is not None and args.cts_breaks is not None: # --cts-bin
  141. cts_fnames = sumstats._splitp(args.cts_bin) # read filenames
  142. args.cts_breaks = args.cts_breaks.replace('N','-') # replace N with negative sign
  143. try: # split on x
  144. breaks = [[float(x) for x in y.split(',')] for y in args.cts_breaks.split('x')]
  145. except ValueError as e:
  146. raise ValueError('--cts-breaks must be a comma-separated list of numbers: '
  147. +str(e.args))
  148. if len(breaks) != len(cts_fnames):
  149. raise ValueError('Need to specify one set of breaks for each file in --cts-bin.')
  150. if args.cts_names:
  151. cts_colnames = [str(x) for x in args.cts_names.split(',')]
  152. if len(cts_colnames) != len(cts_fnames):
  153. msg = 'Must specify either no --cts-names or one value for each file in --cts-bin.'
  154. raise ValueError(msg)
  155. else:
  156. cts_colnames = ['ANNOT'+str(i) for i in xrange(len(cts_fnames))]
  157. log.log('Reading numbers with which to bin SNPs from {F}'.format(F=args.cts_bin))
  158. cts_levs = []
  159. full_labs = []
  160. for i,fh in enumerate(cts_fnames):
  161. vec = ps.read_cts(cts_fnames[i], array_snps.df.SNP.values)
  162. max_cts = np.max(vec)
  163. min_cts = np.min(vec)
  164. cut_breaks = list(breaks[i])
  165. name_breaks = list(cut_breaks)
  166. if np.all(cut_breaks >= max_cts) or np.all(cut_breaks <= min_cts):
  167. raise ValueError('All breaks lie outside the range of the cts variable.')
  168. if np.all(cut_breaks <= max_cts):
  169. name_breaks.append(max_cts)
  170. cut_breaks.append(max_cts+1)
  171. if np.all(cut_breaks >= min_cts):
  172. name_breaks.append(min_cts)
  173. cut_breaks.append(min_cts-1)
  174. name_breaks.sort()
  175. cut_breaks.sort()
  176. n_breaks = len(cut_breaks)
  177. # so that col names are consistent across chromosomes with different max vals
  178. name_breaks[0] = 'min'
  179. name_breaks[-1] = 'max'
  180. name_breaks = [str(x) for x in name_breaks]
  181. labs = [name_breaks[i]+'_'+name_breaks[i+1] for i in xrange(n_breaks-1)]
  182. cut_vec = pd.Series(pd.cut(vec, bins=cut_breaks, labels=labs))
  183. cts_levs.append(cut_vec)
  184. full_labs.append(labs)
  185. annot_matrix = pd.concat(cts_levs, axis=1)
  186. annot_matrix.columns = cts_colnames
  187. # crosstab -- for now we keep empty columns
  188. annot_matrix = pd.crosstab(annot_matrix.index,
  189. [annot_matrix[i] for i in annot_matrix.columns], dropna=False,
  190. colnames=annot_matrix.columns)
  191. # add missing columns
  192. if len(cts_colnames) > 1:
  193. for x in product(*full_labs):
  194. if x not in annot_matrix.columns:
  195. annot_matrix[x] = 0
  196. else:
  197. for x in full_labs[0]:
  198. if x not in annot_matrix.columns:
  199. annot_matrix[x] = 0
  200. annot_matrix = annot_matrix[sorted(annot_matrix.columns, key=annot_sort_key)]
  201. if len(cts_colnames) > 1:
  202. # flatten multi-index
  203. annot_colnames = ['_'.join([cts_colnames[i]+'_'+b for i,b in enumerate(c)])
  204. for c in annot_matrix.columns]
  205. else:
  206. annot_colnames = [cts_colnames[0]+'_'+b for b in annot_matrix.columns]
  207. annot_matrix = np.matrix(annot_matrix)
  208. keep_snps = None
  209. n_annot = len(annot_colnames)
  210. if np.any(np.sum(annot_matrix, axis=1) == 0):
  211. # This exception should never be raised. For debugging only.
  212. raise ValueError('Some SNPs have no annotation in --cts-bin. This is a bug!')
  213. else:
  214. annot_matrix, annot_colnames, keep_snps = None, None, None,
  215. n_annot = 1
  216. # read fam
  217. array_indivs = ind_obj(ind_file)
  218. n = len(array_indivs.IDList)
  219. log.log('Read list of {n} individuals from {f}'.format(n=n, f=ind_file))
  220. # read keep_indivs
  221. if args.keep:
  222. keep_indivs = __filter__(args.keep, 'individuals', 'include', array_indivs)
  223. else:
  224. keep_indivs = None
  225. # read genotype array
  226. log.log('Reading genotypes from {fname}'.format(fname=array_file))
  227. geno_array = array_obj(array_file, n, array_snps, keep_snps=keep_snps,
  228. keep_indivs=keep_indivs, mafMin=args.maf)
  229. # filter annot_matrix down to only SNPs passing MAF cutoffs
  230. if annot_matrix is not None:
  231. annot_keep = geno_array.kept_snps
  232. annot_matrix = annot_matrix[annot_keep,:]
  233. # determine block widths
  234. x = np.array((args.ld_wind_snps, args.ld_wind_kb, args.ld_wind_cm), dtype=bool)
  235. if np.sum(x) != 1:
  236. raise ValueError('Must specify exactly one --ld-wind option')
  237. if args.ld_wind_snps:
  238. max_dist = args.ld_wind_snps
  239. coords = np.array(xrange(geno_array.m))
  240. elif args.ld_wind_kb:
  241. max_dist = args.ld_wind_kb*1000
  242. coords = np.array(array_snps.df['BP'])[geno_array.kept_snps]
  243. elif args.ld_wind_cm:
  244. max_dist = args.ld_wind_cm
  245. coords = np.array(array_snps.df['CM'])[geno_array.kept_snps]
  246. block_left = ld.getBlockLefts(coords, max_dist)
  247. if block_left[len(block_left)-1] == 0 and not args.yes_really:
  248. error_msg = 'Do you really want to compute whole-chomosome LD Score? If so, set the '
  249. error_msg += '--yes-really flag (warning: it will use a lot of time / memory)'
  250. raise ValueError(error_msg)
  251. scale_suffix = ''
  252. if args.pq_exp is not None:
  253. log.log('Computing LD with pq ^ {S}.'.format(S=args.pq_exp))
  254. msg = 'Note that LD Scores with pq raised to a nonzero power are'
  255. msg += 'not directly comparable to normal LD Scores.'
  256. log.log(msg)
  257. scale_suffix = '_S{S}'.format(S=args.pq_exp)
  258. pq = np.matrix(geno_array.maf*(1-geno_array.maf)).reshape((geno_array.m, 1))
  259. pq = np.power(pq, args.pq_exp)
  260. if annot_matrix is not None:
  261. annot_matrix = np.multiply(annot_matrix, pq)
  262. else:
  263. annot_matrix = pq
  264. log.log("Estimating LD Score.")
  265. lN = geno_array.ldScoreVarBlocks(block_left, args.chunk_size, annot=annot_matrix)
  266. col_prefix = "L2"; file_suffix = "l2"
  267. if n_annot == 1:
  268. ldscore_colnames = [col_prefix+scale_suffix]
  269. else:
  270. ldscore_colnames = [y+col_prefix+scale_suffix for y in annot_colnames]
  271. # print .ldscore. Output columns: CHR, BP, RS, [LD Scores]
  272. out_fname = args.out + '.' + file_suffix + '.ldscore'
  273. new_colnames = geno_array.colnames + ldscore_colnames
  274. df = pd.DataFrame.from_records(np.c_[geno_array.df, lN])
  275. df.columns = new_colnames
  276. if args.print_snps:
  277. if args.print_snps.endswith('gz'):
  278. print_snps = pd.read_csv(args.print_snps, header=None, compression='gzip')
  279. elif args.print_snps.endswith('bz2'):
  280. print_snps = pd.read_csv(args.print_snps, header=None, compression='bz2')
  281. else:
  282. print_snps = pd.read_csv(args.print_snps, header=None)
  283. if len(print_snps.columns) > 1:
  284. raise ValueError('--print-snps must refer to a file with a one column of SNP IDs.')
  285. log.log('Reading list of {N} SNPs for which to print LD Scores from {F}'.format(\
  286. F=args.print_snps, N=len(print_snps)))
  287. print_snps.columns=['SNP']
  288. df = df.ix[df.SNP.isin(print_snps.SNP),:]
  289. if len(df) == 0:
  290. raise ValueError('After merging with --print-snps, no SNPs remain.')
  291. else:
  292. msg = 'After merging with --print-snps, LD Scores for {N} SNPs will be printed.'
  293. log.log(msg.format(N=len(df)))
  294. l2_suffix = '.gz'
  295. log.log("Writing LD Scores for {N} SNPs to {f}.gz".format(f=out_fname, N=len(df)))
  296. df.drop(['CM','MAF'], axis=1).to_csv(out_fname, sep="\t", header=True, index=False,
  297. float_format='%.3f')
  298. call(['gzip', '-f', out_fname])
  299. if annot_matrix is not None:
  300. M = np.atleast_1d(np.squeeze(np.asarray(np.sum(annot_matrix, axis=0))))
  301. ii = geno_array.maf > 0.05
  302. M_5_50 = np.atleast_1d(np.squeeze(np.asarray(np.sum(annot_matrix[ii,:], axis=0))))
  303. else:
  304. M = [geno_array.m]
  305. M_5_50 = [np.sum(geno_array.maf > 0.05)]
  306. # print .M
  307. fout_M = open(args.out + '.'+ file_suffix +'.M','wb')
  308. print >>fout_M, '\t'.join(map(str,M))
  309. fout_M.close()
  310. # print .M_5_50
  311. fout_M_5_50 = open(args.out + '.'+ file_suffix +'.M_5_50','wb')
  312. print >>fout_M_5_50, '\t'.join(map(str,M_5_50))
  313. fout_M_5_50.close()
  314. # print annot matrix
  315. if (args.cts_bin is not None) and not args.no_print_annot:
  316. out_fname_annot = args.out + '.annot'
  317. new_colnames = geno_array.colnames + ldscore_colnames
  318. annot_df = pd.DataFrame(np.c_[geno_array.df, annot_matrix])
  319. annot_df.columns = new_colnames
  320. del annot_df['MAF']
  321. log.log("Writing annot matrix produced by --cts-bin to {F}".format(F=out_fname+'.gz'))
  322. annot_df.to_csv(out_fname_annot, sep="\t", header=True, index=False)
  323. call(['gzip', '-f', out_fname_annot])
  324. # print LD Score summary
  325. pd.set_option('display.max_rows', 200)
  326. log.log('\nSummary of LD Scores in {F}'.format(F=out_fname+l2_suffix))
  327. t = df.ix[:,4:].describe()
  328. log.log( t.ix[1:,:] )
  329. np.seterr(divide='ignore', invalid='ignore') # print NaN instead of weird errors
  330. # print correlation matrix including all LD Scores and sample MAF
  331. log.log('')
  332. log.log('MAF/LD Score Correlation Matrix')
  333. log.log( df.ix[:,4:].corr() )
  334. # print condition number
  335. if n_annot > 1: # condition number of a column vector w/ nonzero var is trivially one
  336. log.log('\nLD Score Matrix Condition Number')
  337. cond_num = np.linalg.cond(df.ix[:,5:])
  338. log.log( reg.remove_brackets(str(np.matrix(cond_num))) )
  339. if cond_num > 10000:
  340. log.log('WARNING: ill-conditioned LD Score Matrix!')
  341. # summarize annot matrix if there is one
  342. if annot_matrix is not None:
  343. # covariance matrix
  344. x = pd.DataFrame(annot_matrix, columns=annot_colnames)
  345. log.log('\nAnnotation Correlation Matrix')
  346. log.log( x.corr() )
  347. # column sums
  348. log.log('\nAnnotation Matrix Column Sums')
  349. log.log(_remove_dtype(x.sum(axis=0)))
  350. # row sums
  351. log.log('\nSummary of Annotation Matrix Row Sums')
  352. row_sums = x.sum(axis=1).describe()
  353. log.log(_remove_dtype(row_sums))
  354. np.seterr(divide='raise', invalid='raise')
  355. parser = argparse.ArgumentParser()
  356. parser.add_argument('--out', default='ldsc', type=str,
  357. help='Output filename prefix. If --out is not set, LDSC will use ldsc as the '
  358. 'defualt output filename prefix.')
  359. # Basic LD Score Estimation Flags'
  360. parser.add_argument('--bfile', default=None, type=str,
  361. help='Prefix for Plink .bed/.bim/.fam file')
  362. parser.add_argument('--l2', default=False, action='store_true',
  363. help='Estimate l2. Compatible with both jackknife and non-jackknife.')
  364. # Filtering / Data Management for LD Score
  365. parser.add_argument('--extract', default=None, type=str,
  366. help='File with SNPs to include in LD Score estimation. '
  367. 'The file should contain one SNP ID per row.')
  368. parser.add_argument('--keep', default=None, type=str,
  369. help='File with individuals to include in LD Score estimation. '
  370. 'The file should contain one individual ID per row.')
  371. parser.add_argument('--ld-wind-snps', default=None, type=int,
  372. help='Specify the window size to be used for estimating LD Scores in units of '
  373. '# of SNPs. You can only specify one --ld-wind-* option.')
  374. parser.add_argument('--ld-wind-kb', default=None, type=float,
  375. help='Specify the window size to be used for estimating LD Scores in units of '
  376. 'kilobase-pairs (kb). You can only specify one --ld-wind-* option.')
  377. parser.add_argument('--ld-wind-cm', default=None, type=float,
  378. help='Specify the window size to be used for estimating LD Scores in units of '
  379. 'centiMorgans (cM). You can only specify one --ld-wind-* option.')
  380. parser.add_argument('--print-snps', default=None, type=str,
  381. help='This flag tells LDSC to only print LD Scores for the SNPs listed '
  382. '(one ID per row) in PRINT_SNPS. The sum r^2 will still include SNPs not in '
  383. 'PRINT_SNPs. This is useful for reducing the number of LD Scores that have to be '
  384. 'read into memory when estimating h2 or rg.' )
  385. # Fancy LD Score Estimation Flags
  386. parser.add_argument('--annot', default=None, type=str,
  387. help='Filename prefix for annotation file for partitioned LD Score estimation. '
  388. 'LDSC will automatically append .annot or .annot.gz to the filename prefix. '
  389. 'See docs/file_formats_ld for a definition of the .annot format.')
  390. parser.add_argument('--thin-annot', action='store_true', default=False,
  391. help='This flag says your annot files have only annotations, with no SNP, CM, CHR, BP columns.')
  392. parser.add_argument('--cts-bin', default=None, type=str,
  393. help='This flag tells LDSC to compute partitioned LD Scores, where the partition '
  394. 'is defined by cutting one or several continuous variable[s] into bins. '
  395. 'The argument to this flag should be the name of a single file or a comma-separated '
  396. 'list of files. The file format is two columns, with SNP IDs in the first column '
  397. 'and the continuous variable in the second column. ')
  398. parser.add_argument('--cts-breaks', default=None, type=str,
  399. help='Use this flag to specify names for the continuous variables cut into bins '
  400. 'with --cts-bin. For each continuous variable, specify breaks as a comma-separated '
  401. 'list of breakpoints, and separate the breakpoints for each variable with an x. '
  402. 'For example, if binning on MAF and distance to gene (in kb), '
  403. 'you might set --cts-breaks 0.1,0.25,0.4x10,100,1000 ')
  404. parser.add_argument('--cts-names', default=None, type=str,
  405. help='Use this flag to specify names for the continuous variables cut into bins '
  406. 'with --cts-bin. The argument to this flag should be a comma-separated list of '
  407. 'names. For example, if binning on DAF and distance to gene, you might set '
  408. '--cts-bin DAF,DIST_TO_GENE ')
  409. parser.add_argument('--per-allele', default=False, action='store_true',
  410. help='Setting this flag causes LDSC to compute per-allele LD Scores, '
  411. 'i.e., \ell_j := \sum_k p_k(1-p_k)r^2_{jk}, where p_k denotes the MAF '
  412. 'of SNP j. ')
  413. parser.add_argument('--pq-exp', default=None, type=float,
  414. help='Setting this flag causes LDSC to compute LD Scores with the given scale factor, '
  415. 'i.e., \ell_j := \sum_k (p_k(1-p_k))^a r^2_{jk}, where p_k denotes the MAF '
  416. 'of SNP j and a is the argument to --pq-exp. ')
  417. parser.add_argument('--no-print-annot', default=False, action='store_true',
  418. help='By defualt, seting --cts-bin or --cts-bin-add causes LDSC to print '
  419. 'the resulting annot matrix. Setting --no-print-annot tells LDSC not '
  420. 'to print the annot matrix. ')
  421. parser.add_argument('--maf', default=None, type=float,
  422. help='Minor allele frequency lower bound. Default is MAF > 0.')
  423. # Basic Flags for Working with Variance Components
  424. parser.add_argument('--h2', default=None, type=str,
  425. help='Filename for a .sumstats[.gz] file for one-phenotype LD Score regression. '
  426. '--h2 requires at minimum also setting the --ref-ld and --w-ld flags.')
  427. parser.add_argument('--h2-cts', default=None, type=str,
  428. help='Filename for a .sumstats[.gz] file for cell-type-specific analysis. '
  429. '--h2-cts requires the --ref-ld-chr, --w-ld, and --ref-ld-chr-cts flags.')
  430. parser.add_argument('--rg', default=None, type=str,
  431. help='Comma-separated list of prefixes of .chisq filed for genetic correlation estimation.')
  432. parser.add_argument('--ref-ld', default=None, type=str,
  433. help='Use --ref-ld to tell LDSC which LD Scores to use as the predictors in the LD '
  434. 'Score regression. '
  435. 'LDSC will automatically append .l2.ldscore/.l2.ldscore.gz to the filename prefix.')
  436. parser.add_argument('--ref-ld-chr', default=None, type=str,
  437. help='Same as --ref-ld, but will automatically concatenate .l2.ldscore files split '
  438. 'across 22 chromosomes. LDSC will automatically append .l2.ldscore/.l2.ldscore.gz '
  439. 'to the filename prefix. If the filename prefix contains the symbol @, LDSC will '
  440. 'replace the @ symbol with chromosome numbers. Otherwise, LDSC will append chromosome '
  441. 'numbers to the end of the filename prefix.'
  442. 'Example 1: --ref-ld-chr ld/ will read ld/1.l2.ldscore.gz ... ld/22.l2.ldscore.gz'
  443. 'Example 2: --ref-ld-chr ld/@_kg will read ld/1_kg.l2.ldscore.gz ... ld/22_kg.l2.ldscore.gz')
  444. parser.add_argument('--w-ld', default=None, type=str,
  445. help='Filename prefix for file with LD Scores with sum r^2 taken over SNPs included '
  446. 'in the regression. LDSC will automatically append .l2.ldscore/.l2.ldscore.gz.')
  447. parser.add_argument('--w-ld-chr', default=None, type=str,
  448. help='Same as --w-ld, but will read files split into 22 chromosomes in the same '
  449. 'manner as --ref-ld-chr.')
  450. parser.add_argument('--overlap-annot', default=False, action='store_true',
  451. help='This flag informs LDSC that the partitioned LD Scores were generates using an '
  452. 'annot matrix with overlapping categories (i.e., not all row sums equal 1), '
  453. 'and prevents LDSC from displaying output that is meaningless with overlapping categories.')
  454. parser.add_argument('--print-coefficients',default=False,action='store_true',
  455. help='when categories are overlapping, print coefficients as well as heritabilities.')
  456. parser.add_argument('--frqfile', type=str,
  457. help='For use with --overlap-annot. Provides allele frequencies to prune to common '
  458. 'snps if --not-M-5-50 is not set.')
  459. parser.add_argument('--frqfile-chr', type=str,
  460. help='Prefix for --frqfile files split over chromosome.')
  461. parser.add_argument('--no-intercept', action='store_true',
  462. help = 'If used with --h2, this constrains the LD Score regression intercept to equal '
  463. '1. If used with --rg, this constrains the LD Score regression intercepts for the h2 '
  464. 'estimates to be one and the intercept for the genetic covariance estimate to be zero.')
  465. parser.add_argument('--intercept-h2', action='store', default=None,
  466. help = 'Intercepts for constrained-intercept single-trait LD Score regression.')
  467. parser.add_argument('--intercept-gencov', action='store', default=None,
  468. help = 'Intercepts for constrained-intercept cross-trait LD Score regression.'
  469. ' Must have same length as --rg. The first entry is ignored.')
  470. parser.add_argument('--M', default=None, type=str,
  471. help='# of SNPs (if you don\'t want to use the .l2.M files that came with your .l2.ldscore.gz files)')
  472. parser.add_argument('--two-step', default=None, type=float,
  473. help='Test statistic bound for use with the two-step estimator. Not compatible with --no-intercept and --constrain-intercept.')
  474. parser.add_argument('--chisq-max', default=None, type=float,
  475. help='Max chi^2.')
  476. parser.add_argument('--ref-ld-chr-cts', default=None, type=str,
  477. help='Name of a file that has a list of file name prefixes for cell-type-specific analysis.')
  478. parser.add_argument('--print-all-cts', action='store_true', default=False)
  479. # Flags for both LD Score estimation and h2/gencor estimation
  480. parser.add_argument('--print-cov', default=False, action='store_true',
  481. help='For use with --h2/--rg. This flag tells LDSC to print the '
  482. 'covaraince matrix of the estimates.')
  483. parser.add_argument('--print-delete-vals', default=False, action='store_true',
  484. help='If this flag is set, LDSC will print the block jackknife delete-values ('
  485. 'i.e., the regression coefficeints estimated from the data with a block removed). '
  486. 'The delete-values are formatted as a matrix with (# of jackknife blocks) rows and '
  487. '(# of LD Scores) columns.')
  488. # Flags you should almost never use
  489. parser.add_argument('--chunk-size', default=50, type=int,
  490. help='Chunk size for LD Score calculation. Use the default.')
  491. parser.add_argument('--pickle', default=False, action='store_true',
  492. help='Store .l2.ldscore files as pickles instead of gzipped tab-delimited text.')
  493. parser.add_argument('--yes-really', default=False, action='store_true',
  494. help='Yes, I really want to compute whole-chromosome LD Score.')
  495. parser.add_argument('--invert-anyway', default=False, action='store_true',
  496. help="Force LDSC to attempt to invert ill-conditioned matrices.")
  497. parser.add_argument('--n-blocks', default=200, type=int,
  498. help='Number of block jackknife blocks.')
  499. parser.add_argument('--not-M-5-50', default=False, action='store_true',
  500. help='This flag tells LDSC to use the .l2.M file instead of the .l2.M_5_50 file.')
  501. parser.add_argument('--return-silly-things', default=False, action='store_true',
  502. help='Force ldsc to return silly genetic correlation estimates.')
  503. parser.add_argument('--no-check-alleles', default=False, action='store_true',
  504. help='For rg estimation, skip checking whether the alleles match. This check is '
  505. 'redundant for pairs of chisq files generated using munge_sumstats.py and the '
  506. 'same argument to the --merge-alleles flag.')
  507. # transform to liability scale
  508. parser.add_argument('--samp-prev',default=None,
  509. help='Sample prevalence of binary phenotype (for conversion to liability scale).')
  510. parser.add_argument('--pop-prev',default=None,
  511. help='Population prevalence of binary phenotype (for conversion to liability scale).')
  512. if __name__ == '__main__':
  513. args = parser.parse_args()
  514. if args.out is None:
  515. raise ValueError('--out is required.')
  516. log = Logger(args.out+'.log')
  517. try:
  518. defaults = vars(parser.parse_args(''))
  519. opts = vars(args)
  520. non_defaults = [x for x in opts.keys() if opts[x] != defaults[x]]
  521. header = MASTHEAD
  522. header += "Call: \n"
  523. header += './ldsc.py \\\n'
  524. options = ['--'+x.replace('_','-')+' '+str(opts[x])+' \\' for x in non_defaults]
  525. header += '\n'.join(options).replace('True','').replace('False','')
  526. header = header[0:-1]+'\n'
  527. log.log(header)
  528. log.log('Beginning analysis at {T}'.format(T=time.ctime()))
  529. start_time = time.time()
  530. if args.n_blocks <= 1:
  531. raise ValueError('--n-blocks must be an integer > 1.')
  532. if args.bfile is not None:
  533. if args.l2 is None:
  534. raise ValueError('Must specify --l2 with --bfile.')
  535. if args.annot is not None and args.extract is not None:
  536. raise ValueError('--annot and --extract are currently incompatible.')
  537. if args.cts_bin is not None and args.extract is not None:
  538. raise ValueError('--cts-bin and --extract are currently incompatible.')
  539. if args.annot is not None and args.cts_bin is not None:
  540. raise ValueError('--annot and --cts-bin are currently incompatible.')
  541. if (args.cts_bin is not None) != (args.cts_breaks is not None):
  542. raise ValueError('Must set both or neither of --cts-bin and --cts-breaks.')
  543. if args.per_allele and args.pq_exp is not None:
  544. raise ValueError('Cannot set both --per-allele and --pq-exp (--per-allele is equivalent to --pq-exp 1).')
  545. if args.per_allele:
  546. args.pq_exp = 1
  547. ldscore(args, log)
  548. # summary statistics
  549. elif (args.h2 or args.rg or args.h2_cts) and (args.ref_ld or args.ref_ld_chr) and (args.w_ld or args.w_ld_chr):
  550. if args.h2 is not None and args.rg is not None:
  551. raise ValueError('Cannot set both --h2 and --rg.')
  552. if args.ref_ld and args.ref_ld_chr:
  553. raise ValueError('Cannot set both --ref-ld and --ref-ld-chr.')
  554. if args.w_ld and args.w_ld_chr:
  555. raise ValueError('Cannot set both --w-ld and --w-ld-chr.')
  556. if (args.samp_prev is not None) != (args.pop_prev is not None):
  557. raise ValueError('Must set both or neither of --samp-prev and --pop-prev.')
  558. if not args.overlap_annot or args.not_M_5_50:
  559. if args.frqfile is not None or args.frqfile_chr is not None:
  560. log.log('The frequency file is unnecessary and is being ignored.')
  561. args.frqfile = None
  562. args.frqfile_chr = None
  563. if args.overlap_annot and not args.not_M_5_50:
  564. if not ((args.frqfile and args.ref_ld) or (args.frqfile_chr and args.ref_ld_chr)):
  565. raise ValueError('Must set either --frqfile and --ref-ld or --frqfile-chr and --ref-ld-chr')
  566. if args.rg:
  567. sumstats.estimate_rg(args, log)
  568. elif args.h2:
  569. sumstats.estimate_h2(args, log)
  570. elif args.h2_cts:
  571. sumstats.cell_type_specific(args, log)
  572. # bad flags
  573. else:
  574. print header
  575. print 'Error: no analysis selected.'
  576. print 'ldsc.py -h describes options.'
  577. except Exception:
  578. ex_type, ex, tb = sys.exc_info()
  579. log.log( traceback.format_exc(ex) )
  580. raise
  581. finally:
  582. log.log('Analysis finished at {T}'.format(T=time.ctime()) )
  583. time_elapsed = round(time.time()-start_time,2)
  584. log.log('Total time elapsed: {T}'.format(T=sec_to_str(time_elapsed)))

ldsc.py at commit 2fdeeb3, under GPL-3.0 · at the source

Overview

Authors: Abiodun J Fatoba1, Dorcas O Fatoba1, Claire L Simpson1
ORCID iDs: Claire L Simpson
  1. Department of Genetics, Genomics and Informatics, University of Tennessee Health Science Center, Memphis, TN 38103 USA
Institutions: University of Tennessee Health Science Center (United States)
Journal: Human genetics, volume 145, issue 1, article 97
Dates: received 6 October 2025; accepted 17 October 2026; published online 20 November 2026; in print 2026
Type: Research article · Language: English
License: CC BY
Identifiers: DOI 10.1007/s00439-026-02889-4 · PMID 43062518 · PMCID PMC13788104 · OpenAlex W7237182107
Open access: hybrid, a free copy (OpenAlex)
Status: code verified (how the code is found and verified)
Categories: genetics / omics (modality), human (organism), other condition (population), stroke (population), cellular / molecular (subfield)
Methods: Statistics
MeSH: Alcoholism*, Genetic Predisposition to Disease*, Genome-Wide Association Study*, Ischemic Stroke*, Humans, Polymorphism, Single Nucleotide, Quantitative Trait Loci (* major topic)
Topic: Genetic Associations and Epidemiology (Genetics, Biochemistry, Genetics and Molecular Biology), according to OpenAlex
Citations: not cited yet (Europe PMC); 34 references in the paper

Abstract

Alcohol use disorder (AUD) is a life-threatening mental disorder with high mortality and morbidity due to its various health complications. While observational studies have highlighted the role of alcohol consumption in the risk of ischemic stroke (IS), the contribution of shared genetic factors remains unclear. Our study used cross-trait Multi-trait Analysis of GWAS (MTAG) to investigate the shared genetic architecture underlying AUD and IS using genome-wide association studies (GWAS) summary statistics for alcohol use disorder (N = 500,348) and ischemic stroke (N = 1,296,908) from the FinnGen and GIGASTROKE databases. Local Analysis of Variant Association (LAVA) identified nine loci exhibiting significant positive and negative genetic correlation after Bonferroni correction. We further identified 19 independent genome-wide significant variants (P < 5 × 10− 8), among which one variant (rs12979469) mapped to SLC44A2 showed evidence of association with both traits. Gene-based analysis via MAGMA also supports SLC44A2 as a shared gene. Fine-mapping and colocalization further identified additional candidate genes, including CDK6 and RASIP1, which were supported by cross-trait analysis (CPASSOC P < 5 × 10− 8) but showed weaker evidence in single-trait GWAS. Summary data-based Mendelian Randomization (SMR) revealed significant associations between the expression of ABO and NBEAL1 and IS in tibial artery tissue (PSMR = 4.28 × 10⁻⁶, PHEIDI > 0.05), whereas no significant association was observed in brain tissues for AUD. Tissue enrichment analysis by GTEx further supports these findings, showing significant enrichment of AUD in brain tissues but nominal significance of IS in tibial artery tissues. Together, these findings suggest that the genetic overlap between AUD and IS is more consistent with variant-level pleiotropy rather than a shared gene expression or tissue-specific mechanism. Overall, our findings highlight SLC44A2, CDK6, and RASIP1 as candidate genes associated with both IS and AUD, and provide insights into the complex genetic relationship between AUD and IS.

Reproduced under the paper's license (CC BY), from the paper cited above.

Repositories

Its files are read in the Code ↔ Paper reader above, with 2 matches between paragraphs and lines of code.

bulik/ldsc

License: GPL-3.0
State: the link answers, verified on 26 October 2026
Evidence: files inventoried
Commit: 2fdeeb3b44379408794154993dbd6101b8946b7e, 16 January 2026
Languages: Python (19), MATLAB (4), Perl (1), R (1)
Size: 1,093 files, 25 scripts
Software Heritage: archived
Found in: the text, “Global and local genetic correlation analysis”
Holds: README, license file, environment (environment.yml, requirements.txt, setup.py), tests
Not found: CITATION.cff, continuous integration, documentation
Tools: NumPy (18 files), pandas (11 files), SciPy (5 files), BEDTools (2 files)
Availability: 2 checks, the latest on 26 October 2026: the link answers
  • 26 October 2026: the link answers
  • 26 September 2026: the link answers
27 files
At the source: github.com/bulik/ldsc

JonJala/mtag

License: GPL-3.0
State: the link answers, verified on 25 October 2026
Evidence: files inventoried
Commit: 9e17f3cf1fbcf57b6bc466daefdc51fd0de3c5dc, 7 March 2023
Languages: Python (21), Perl (1), R (1)
Size: 1,096 files, 23 scripts
Software Heritage: not archived
Found in: the text, “Cross-trait meta-analysis”
Holds: README, license file, environment (environment.yml, ldsc_mod/requirements.txt), tests
Not found: CITATION.cff, continuous integration, documentation
Tools: NumPy (18 files), pandas (11 files), SciPy (6 files)
Availability: 1 check, the latest on 25 October 2026: the link answers
  • 25 October 2026: the link answers
25 files

Tracing map

Proposed by the machine: these links were found in the paper and verified at the source, without human review. The map will receive a Zenodo DOI once one of the paper's authors has validated it with their ORCID.

What the map holds:

  • 2 repositories of the authors' code, each at its verified commit, with its license and how the link was found in the paper;
  • 48 scripts, each with its path and the digest of its content;
  • 2 matches between paragraphs of the paper and lines of the code (method lexical-v1);
  • neither the text of the paper nor the code itself.

Its JSON (tracing-map.json) is deposited on Zenodo with its DOI once the map is validated.

Data

No dataset and no data link were found in the paper.

Data availability

The dataset used in this study can be found in the public repositories at FinnGen Consortium (https://r12.finngen.fi/) and GWAS catalog (https://www.ebi.ac.uk/gwas/publications/36180795).

Reproduced under the paper's license (CC BY), from the paper cited above.

Versions

The history of this record: each version stored by the harvester or made by a correction of its authors or of the maintainers of its code, and what changed in its facts. The texts of the paper (its abstract, its availability statements) are not part of it; versions that changed only those are not listed.

Version 1, 23 November 2026: the first record

Recorded: type, language, journal, volume, issue, pages, dates, 3 authors, 7 MeSH terms, 33 references.

Cite

This paper

Fatoba, A. J., Fatoba, D. O., & L Simpson, C. (2026). A genome-wide cross-trait analysis detects shared genetic architecture between alcohol use disorder and ischemic stroke. Human genetics, 145(1), 97. https://doi.org/10.1007/s00439-026-02889-4

BibTeX

@article{fatoba2026genome,
author = {Fatoba, Abiodun J and Fatoba, Dorcas O and L Simpson, Claire},
title = {{A genome-wide cross-trait analysis detects shared genetic architecture between alcohol use disorder and ischemic stroke}},
journal = {Human genetics},
year = {2026},
month = nov,
volume = {145},
number = {1},
pages = {97},
publisher = {Springer Science+Business Media},
issn = {0340-6717},
doi = {10.1007/s00439-026-02889-4},
url = {https://doi.org/10.1007/s00439-026-02889-4},
pmid = {43062518},
pmcid = {PMC13788104}
}

RIS

TY - JOUR
AU - Fatoba, Abiodun J
AU - Fatoba, Dorcas O
AU - L Simpson, Claire
TI - A genome-wide cross-trait analysis detects shared genetic architecture between alcohol use disorder and ischemic stroke
T2 - Human genetics
J2 - Hum Genet
PY - 2026
DA - 2026/11/20
VL - 145
IS - 1
SP - 97
SN - 0340-6717
PB - Springer Science+Business Media
DO - 10.1007/s00439-026-02889-4
UR - https://doi.org/10.1007/s00439-026-02889-4
LA - en
ER -

CSL-JSON

{
"id": "10.1007/s00439-026-02889-4",
"type": "article-journal",
"title": "A genome-wide cross-trait analysis detects shared genetic architecture between alcohol use disorder and ischemic stroke",
"container-title": "Human genetics",
"author": [
{
"family": "Fatoba",
"given": "Abiodun J"
},
{
"family": "Fatoba",
"given": "Dorcas O"
},
{
"family": "L Simpson",
"given": "Claire"
}
],
"container-title-short": "Hum Genet",
"volume": "145",
"issue": "1",
"page": "97",
"DOI": "10.1007/s00439-026-02889-4",
"PMID": "43062518",
"PMCID": "PMC13788104",
"ISSN": "0340-6717",
"publisher": "Springer Science+Business Media",
"URL": "https://doi.org/10.1007/s00439-026-02889-4",
"language": "en",
"issued": {
"date-parts": [
[
2026,
11,
20
]
]
}
}

The tracing map gets a citation of its own once an author has validated it and it has a DOI.

Similar papers

The papers with a page that share the most with this one: the tools found in their code, their categories, datasets, cited references and authors, the rarest counting most.

[1] doi:10.1038/s41591-023-02653-5 [code]
Multi-ancestry study of the genetics of problematic alcohol use in over 1 million individuals.
Journal: Nature medicine
In common: BEDTools, pandas, SciPy, 1 other tool, genetics / omics, other condition, 3 references
[2] doi:10.1093/hmg/ddad174 [code]
Novel insight into the etiology of ischemic stroke gained by integrative multiome-wide association study.
Journal: Human molecular genetics
In common: stroke, genetics / omics, cellular / molecular, 5 references
[3] doi:10.1186/s40246-025-00789-8 [code]
Shared genetic architecture between stroke and blood lipids: a large-scale genome-wide cross-trait analysis.
Journal: Human genomics
In common: BEDTools, pandas, SciPy, 1 other tool, stroke, genetics / omics, cellular / molecular, 2 references
[4] doi:10.1093/brain/awab432 [code]
Gene-mapping study of extremes of cerebral small vessel disease reveals TRIM47 as a strong candidate.
Journal: Brain : a journal of neurology
In common: BEDTools, pandas, SciPy, 1 other tool, stroke, genetics / omics, cellular / molecular, 2 references
[5] doi:10.1038/s41467-024-46023-2 [code]
Genetic architecture of the structural connectome.
Journal: Nature communications
In common: BEDTools, pandas, SciPy, 1 other tool, genetics / omics, cellular / molecular, 2 references
[6] doi:10.1161/jaha.125.046208
Integration of Genome-Wide Association Studies With Single-Cell and Bulk Expression Quantitative Trait Locus to Identify Stroke Susceptibility Genes.
Journal: Journal of the American Heart Association
In common: stroke, genetics / omics, cellular / molecular, 4 references
[7] doi:10.1038/s41588-021-00973-1 [code]
Common and rare variant association analyses in amyotrophic lateral sclerosis identify 15 risk loci with distinct genetic architectures and neuron-specific biology.
Journal: Nature genetics
In common: BEDTools, pandas, SciPy, 1 other tool, genetics / omics, other condition, 2 references
[8] doi:10.1038/s41586-025-09083-y [code]
Single-cell transcriptomic and chromatin dynamics of the human brain in PTSD.
Journal: Nature
In common: BEDTools, pandas, SciPy, 1 other tool, genetics / omics, other condition, cellular / molecular, 1 reference
[9] doi:10.1038/s41593-025-02136-5 [code]
The stroke risk gene Foxf2 maintains brain endothelial cell function via Tie2 signaling.
Journal: Nature neuroscience
In common: pandas, SciPy, NumPy, stroke, genetics / omics, cellular / molecular, 2 references
[10] doi:10.1038/s41467-024-55706-9 [code]
Genome-wide association study unravels mechanisms of brain glymphatic activity.
Journal: Nature communications
In common: BEDTools, pandas, SciPy, 1 other tool, genetics / omics, cellular / molecular, 1 reference

Contribute

The authors of this paper can claim it, correct its record and validate its tracing map, and the maintainers of its code (its owner, or a public member of its organization) correct what it says of their repository; anyone signed in can ask for its removal. Every request goes to OSCR's own machine, which answers it; your account page follows them.

Sign in with ORCID to claim this paper as one of its authors, correct its record or validate its tracing map: when the paper's metadata lists your ORCID iD, you are recognized at once. Maintainers of its code: sign in with GitHub, then claim the repository on your account page.

Add the badge to the code's README

OSCR: the badge of this paper

If you are an author or a maintainer of this paper's code, you can add this badge. It says what OSCR knows of the paper (its code, its validated tracing map) and links the code to this page. Paste one of these snippets under the README's title. Keep the two marks around it, so that the badge can be replaced in place and is never added twice. OSCR changes nothing in your repository.

Markdown
<!-- oscr-badge:start -->
[![OSCR](https://openscicode.org/badge/doi/10.1007/s00439-026-02889-4.svg)](https://openscicode.org/badge/doi/10.1007/s00439-026-02889-4)
<!-- oscr-badge:end -->
reStructuredText
.. oscr-badge:start

.. image:: https://openscicode.org/badge/doi/10.1007/s00439-026-02889-4.svg
   :target: https://openscicode.org/badge/doi/10.1007/s00439-026-02889-4
   :alt: OSCR

.. oscr-badge:end
HTML
<!-- oscr-badge:start -->
<a href="https://openscicode.org/badge/doi/10.1007/s00439-026-02889-4"><img src="https://openscicode.org/badge/doi/10.1007/s00439-026-02889-4.svg" alt="OSCR"></a>
<!-- oscr-badge:end -->

On GitHub, open the README, choose Edit (the pencil), paste the snippet under the title, then "Commit changes".

If you choose to, you can have the badge kept up to date for you, with oscr badge --write from the command line or with the GitHub Action in your repository's workflows. Every other form and option (a card, AsciiDoc, LaTeX, shields.io) is on the badge page.

Request its removal

To ask OSCR to remove this record, the copies of its authors' scripts or its tracing map, use the removal request page: signed in, you say who you are, what to remove and why, then review and confirm the request. Published rules decide every request (how).

Discussion, reproductions, activity

Discussion: code errors and mismatches between the code and the paper about this paper and its code, from readers and its authors, beside the paper and its tracing map.

Report a mismatch between the code and the paper · Report a code error (signed in)

Reproductions: reports from readers who ran the authors' code and did not get the paper's result, what they ran, with which environment, commit and data.

Report a reproduction failure (signed in)

Versions of its code: the releases of its code tied to a version of this paper (the preprint, the accepted manuscript, the version of record…), each with the tracing map versioned with it.

Activity: what happens around this paper: new versions of its record, its map's validation, discussions and reproductions. It opens with sign-in.